@graphrefly/ts 0.1.0 → 0.1.1

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.
Files changed (194) hide show
  1. package/README.md +5 -7
  2. package/dist/{actions-types-DfRob139.d.cts → actions-types-BYzAurt6.d.cts} +1 -1
  3. package/dist/{actions-types-DcDaBRTC.d.ts → actions-types-CFJILlFn.d.ts} +1 -1
  4. package/dist/adapters/index.cjs.map +1 -1
  5. package/dist/adapters/index.d.cts +5 -5
  6. package/dist/adapters/index.d.ts +5 -5
  7. package/dist/adapters/index.js +7 -7
  8. package/dist/adapters/nestjs/microservices.d.cts +1 -1
  9. package/dist/adapters/nestjs/microservices.d.ts +1 -1
  10. package/dist/adapters/nestjs/native.d.cts +2 -2
  11. package/dist/adapters/nestjs/native.d.ts +2 -2
  12. package/dist/adapters/nestjs/native.js +2 -2
  13. package/dist/adapters/nestjs/websockets.d.cts +1 -1
  14. package/dist/adapters/nestjs/websockets.d.ts +1 -1
  15. package/dist/adapters/nestjs.d.cts +1 -1
  16. package/dist/adapters/nestjs.d.ts +1 -1
  17. package/dist/adapters/observe-storage.d.cts +1 -1
  18. package/dist/adapters/observe-storage.d.ts +1 -1
  19. package/dist/adapters/react.cjs.map +1 -1
  20. package/dist/adapters/react.d.cts +1 -1
  21. package/dist/adapters/react.d.ts +1 -1
  22. package/dist/adapters/react.js +1 -1
  23. package/dist/adapters/solid.cjs.map +1 -1
  24. package/dist/adapters/solid.d.cts +1 -1
  25. package/dist/adapters/solid.d.ts +1 -1
  26. package/dist/adapters/solid.js +1 -1
  27. package/dist/adapters/svelte.cjs.map +1 -1
  28. package/dist/adapters/svelte.d.cts +1 -1
  29. package/dist/adapters/svelte.d.ts +1 -1
  30. package/dist/adapters/svelte.js +1 -1
  31. package/dist/adapters/vue.cjs.map +1 -1
  32. package/dist/adapters/vue.d.cts +1 -1
  33. package/dist/adapters/vue.d.ts +1 -1
  34. package/dist/adapters/vue.js +1 -1
  35. package/dist/{agent-runtime-types-tool-CTZx51kE.d.cts → agent-runtime-types-tool-DSzCWLK4.d.cts} +1 -1
  36. package/dist/{agent-runtime-types-tool-B0jR0euI.d.ts → agent-runtime-types-tool-DUZUxrl5.d.ts} +1 -1
  37. package/dist/{capability-admission-CGmtVzfS.d.ts → capability-admission--qmB5qYW.d.ts} +1 -1
  38. package/dist/{capability-admission-BwmsThnQ.d.cts → capability-admission-BbiUMnpF.d.cts} +1 -1
  39. package/dist/{chunk-BIGKAHSX.js → chunk-2U4G3PEU.js} +8 -8
  40. package/dist/{chunk-FLUPPSIP.js → chunk-3KYPNNBH.js} +1 -1
  41. package/dist/chunk-3KYPNNBH.js.map +1 -0
  42. package/dist/{chunk-AVPXWVRL.js → chunk-BOWKPNXS.js} +2 -2
  43. package/dist/{chunk-LRYGIKWY.js → chunk-G3J4KZLK.js} +5 -5
  44. package/dist/{chunk-32WGWBYO.js → chunk-HFPPLLLQ.js} +2 -2
  45. package/dist/{chunk-VYAEEKZ3.js → chunk-IISXKNWE.js} +1 -1
  46. package/dist/chunk-IISXKNWE.js.map +1 -0
  47. package/dist/{chunk-DXBOAAPS.js → chunk-KTJ5LEOL.js} +1 -1
  48. package/dist/chunk-KTJ5LEOL.js.map +1 -0
  49. package/dist/{chunk-HT5R7S47.js → chunk-LPC42V2E.js} +3 -3
  50. package/dist/{chunk-STLRNFU7.js → chunk-T3YMFLRH.js} +3 -3
  51. package/dist/chunk-T3YMFLRH.js.map +1 -0
  52. package/dist/{chunk-V3MSIDUQ.js → chunk-TWOPVCGK.js} +2 -2
  53. package/dist/{chunk-ND43YDGK.js → chunk-V3YEGWSH.js} +1 -1
  54. package/dist/chunk-V3YEGWSH.js.map +1 -0
  55. package/dist/{chunk-2BIF6BQ7.js → chunk-W4ATMMTH.js} +2 -2
  56. package/dist/{committed-fact-log-backend-Cjhgia-O.d.ts → committed-fact-log-backend-B_h6A6cN.d.ts} +1 -1
  57. package/dist/{committed-fact-log-backend-BE3Fx5Zv.d.cts → committed-fact-log-backend-CIhiKL-Q.d.cts} +1 -1
  58. package/dist/composition/index.cjs.map +1 -1
  59. package/dist/composition/index.d.cts +1 -1
  60. package/dist/composition/index.d.ts +1 -1
  61. package/dist/composition/index.js +2 -2
  62. package/dist/cqrs/index.d.cts +1 -1
  63. package/dist/cqrs/index.d.ts +1 -1
  64. package/dist/cqrs/messaging.d.cts +1 -1
  65. package/dist/cqrs/messaging.d.ts +1 -1
  66. package/dist/cqrs/work-queue.d.cts +1 -1
  67. package/dist/cqrs/work-queue.d.ts +1 -1
  68. package/dist/data-structures/index.cjs.map +1 -1
  69. package/dist/data-structures/index.d.cts +5 -5
  70. package/dist/data-structures/index.d.ts +5 -5
  71. package/dist/data-structures/index.js +3 -3
  72. package/dist/executors/tool-provider-adapters.d.cts +3 -3
  73. package/dist/executors/tool-provider-adapters.d.ts +3 -3
  74. package/dist/executors/tool-provider-adapters.js +4 -4
  75. package/dist/executors/tool-provider-runtime.d.cts +4 -4
  76. package/dist/executors/tool-provider-runtime.d.ts +4 -4
  77. package/dist/executors/tool-provider.d.cts +3 -3
  78. package/dist/executors/tool-provider.d.ts +3 -3
  79. package/dist/executors/tool-provider.js +3 -3
  80. package/dist/executors/work-queue.d.cts +1 -1
  81. package/dist/executors/work-queue.d.ts +1 -1
  82. package/dist/graph/index.cjs.map +1 -1
  83. package/dist/graph/index.d.cts +4 -4
  84. package/dist/graph/index.d.ts +4 -4
  85. package/dist/graph/index.js +7 -7
  86. package/dist/{graph-D7DgoW4r.d.ts → graph-BYcUX6Y-.d.ts} +1 -1
  87. package/dist/{graph-BpVjXE3p.d.cts → graph-DpUhfPg-.d.cts} +1 -1
  88. package/dist/{index-NxEHWqYL.d.ts → index-CBXYou1z.d.ts} +1 -1
  89. package/dist/{index-Df4kax8O.d.cts → index-sxZ52y0d.d.cts} +1 -1
  90. package/dist/index.cjs.map +1 -1
  91. package/dist/index.d.cts +6 -6
  92. package/dist/index.d.ts +6 -6
  93. package/dist/index.js +15 -15
  94. package/dist/inspection/boundary.d.cts +2 -2
  95. package/dist/inspection/boundary.d.ts +2 -2
  96. package/dist/{measurements-CIGHDnsE.d.ts → measurements-ByXwo0t6.d.ts} +2 -2
  97. package/dist/{measurements-BwkzVaf4.d.cts → measurements-CQONT7Qg.d.cts} +2 -2
  98. package/dist/memory/index.d.cts +1 -1
  99. package/dist/memory/index.d.ts +1 -1
  100. package/dist/memory/semantic/index.d.cts +1 -1
  101. package/dist/memory/semantic/index.d.ts +1 -1
  102. package/dist/messaging/index.d.cts +1 -1
  103. package/dist/messaging/index.d.ts +1 -1
  104. package/dist/operators/index.cjs.map +1 -1
  105. package/dist/operators/index.d.cts +5 -5
  106. package/dist/operators/index.d.ts +5 -5
  107. package/dist/operators/index.js +3 -3
  108. package/dist/orchestration/index.cjs.map +1 -1
  109. package/dist/orchestration/index.d.cts +5 -5
  110. package/dist/orchestration/index.d.ts +5 -5
  111. package/dist/orchestration/index.js +4 -4
  112. package/dist/orchestration/messaging.d.cts +1 -1
  113. package/dist/orchestration/messaging.d.ts +1 -1
  114. package/dist/orchestration/work-queue.d.cts +2 -2
  115. package/dist/orchestration/work-queue.d.ts +2 -2
  116. package/dist/patterns/event-flow.d.cts +1 -1
  117. package/dist/patterns/event-flow.d.ts +1 -1
  118. package/dist/patterns/index.cjs.map +1 -1
  119. package/dist/patterns/index.d.cts +2 -2
  120. package/dist/patterns/index.d.ts +2 -2
  121. package/dist/patterns/index.js +1 -1
  122. package/dist/{reactive-collection-yjdqrWkb.d.cts → reactive-collection-Bt5117qe.d.cts} +1 -1
  123. package/dist/{reactive-collection-BTdjAVpJ.d.ts → reactive-collection-CZGtOhEp.d.ts} +1 -1
  124. package/dist/{reactive-collection-storage-C1YIW_q2.d.cts → reactive-collection-storage-BzhzmEpP.d.cts} +3 -3
  125. package/dist/{reactive-collection-storage-BZozONHw.d.ts → reactive-collection-storage-NKUpbyyK.d.ts} +3 -3
  126. package/dist/{reactive-map-c-l8bYrl.d.cts → reactive-map-Cf9_oTOT.d.cts} +1 -1
  127. package/dist/{reactive-map-B6sA6p5U.d.ts → reactive-map-DQeA7ThE.d.ts} +1 -1
  128. package/dist/{scheduled-readiness-Batwa3Fm.d.ts → scheduled-readiness-BQdebv1Q.d.ts} +1 -1
  129. package/dist/{scheduled-readiness-BtUBoaGJ.d.cts → scheduled-readiness-D5qPFnZF.d.cts} +1 -1
  130. package/dist/solutions/agentic-memory/browser.d.cts +2 -2
  131. package/dist/solutions/agentic-memory/browser.d.ts +2 -2
  132. package/dist/solutions/agentic-memory/index.d.cts +3 -3
  133. package/dist/solutions/agentic-memory/index.d.ts +3 -3
  134. package/dist/solutions/agentic-memory/node.d.cts +2 -2
  135. package/dist/solutions/agentic-memory/node.d.ts +2 -2
  136. package/dist/solutions/agentic-work-item-memory/index.d.cts +1 -1
  137. package/dist/solutions/agentic-work-item-memory/index.d.ts +1 -1
  138. package/dist/solutions/agentic-work-item-memory-application/index.d.cts +1 -1
  139. package/dist/solutions/agentic-work-item-memory-application/index.d.ts +1 -1
  140. package/dist/solutions/index.d.cts +6 -6
  141. package/dist/solutions/index.d.ts +6 -6
  142. package/dist/solutions/reactive-layout/browser/index.d.cts +2 -2
  143. package/dist/solutions/reactive-layout/browser/index.d.ts +2 -2
  144. package/dist/solutions/reactive-layout/index.d.cts +4 -4
  145. package/dist/solutions/reactive-layout/index.d.ts +4 -4
  146. package/dist/solutions/reactive-layout/node-canvas/index.d.cts +2 -2
  147. package/dist/solutions/reactive-layout/node-canvas/index.d.ts +2 -2
  148. package/dist/solutions/reactive-layout/react-native/index.d.cts +2 -2
  149. package/dist/solutions/reactive-layout/react-native/index.d.ts +2 -2
  150. package/dist/solutions/reactive-layout/skia/index.d.cts +2 -2
  151. package/dist/solutions/reactive-layout/skia/index.d.ts +2 -2
  152. package/dist/solutions/work-item/actions.d.cts +5 -5
  153. package/dist/solutions/work-item/actions.d.ts +5 -5
  154. package/dist/solutions/work-item/index.d.cts +4 -4
  155. package/dist/solutions/work-item/index.d.ts +4 -4
  156. package/dist/solutions/work-item/scheduling.d.cts +4 -4
  157. package/dist/solutions/work-item/scheduling.d.ts +4 -4
  158. package/dist/solutions/work-item/work-queue.d.cts +1 -1
  159. package/dist/solutions/work-item/work-queue.d.ts +1 -1
  160. package/dist/sources/browser.cjs.map +1 -1
  161. package/dist/sources/browser.d.cts +2 -2
  162. package/dist/sources/browser.d.ts +2 -2
  163. package/dist/sources/browser.js +2 -2
  164. package/dist/sources/index.cjs.map +1 -1
  165. package/dist/sources/index.d.cts +2 -2
  166. package/dist/sources/index.d.ts +2 -2
  167. package/dist/sources/index.js +2 -2
  168. package/dist/sources/node.d.cts +1 -1
  169. package/dist/sources/node.d.ts +1 -1
  170. package/dist/storage/index.d.cts +2 -2
  171. package/dist/storage/index.d.ts +2 -2
  172. package/dist/{store-BnjczOv3.d.cts → store-Rxycbh-H.d.cts} +5 -5
  173. package/dist/{store-DEQq1IUZ.d.ts → store-piaqo-AU.d.ts} +5 -5
  174. package/dist/testing/index.cjs.map +1 -1
  175. package/dist/testing/index.d.cts +1 -1
  176. package/dist/testing/index.d.ts +1 -1
  177. package/dist/testing/index.js +1 -1
  178. package/dist/{types-CjoOI5fY.d.cts → types-084NQr4q.d.cts} +1 -1
  179. package/dist/{types-C_rZAUfY.d.ts → types-CIYYkmqF.d.ts} +1 -1
  180. package/dist/work-queue/index.d.cts +1 -1
  181. package/dist/work-queue/index.d.ts +1 -1
  182. package/package.json +2 -2
  183. package/dist/chunk-DXBOAAPS.js.map +0 -1
  184. package/dist/chunk-FLUPPSIP.js.map +0 -1
  185. package/dist/chunk-ND43YDGK.js.map +0 -1
  186. package/dist/chunk-STLRNFU7.js.map +0 -1
  187. package/dist/chunk-VYAEEKZ3.js.map +0 -1
  188. /package/dist/{chunk-BIGKAHSX.js.map → chunk-2U4G3PEU.js.map} +0 -0
  189. /package/dist/{chunk-AVPXWVRL.js.map → chunk-BOWKPNXS.js.map} +0 -0
  190. /package/dist/{chunk-LRYGIKWY.js.map → chunk-G3J4KZLK.js.map} +0 -0
  191. /package/dist/{chunk-32WGWBYO.js.map → chunk-HFPPLLLQ.js.map} +0 -0
  192. /package/dist/{chunk-HT5R7S47.js.map → chunk-LPC42V2E.js.map} +0 -0
  193. /package/dist/{chunk-V3MSIDUQ.js.map → chunk-TWOPVCGK.js.map} +0 -0
  194. /package/dist/{chunk-2BIF6BQ7.js.map → chunk-W4ATMMTH.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sources/index.ts","../../src/protocol/messages.ts","../../src/json/codec.ts","../../src/graph/checkpoint.ts","../../src/ctx/types.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/graph/operators.ts","../../src/graph/sources.ts"],"sourcesContent":["export type {\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"../graph/environment.js\";\nexport {\n\ttype AsyncSourceOpts,\n\ttype CronSchedule,\n\ttype EventListenerOptionsLike,\n\ttype EventTargetLike,\n\tempty,\n\ttype FromCronOptions,\n\ttype FromEventOptions,\n\tfirstValueFrom,\n\tfromAny,\n\tfromAsyncIter,\n\tfromCron,\n\tfromEvent,\n\tfromHttp,\n\tfromHttpWithOptions,\n\tfromIter,\n\tfromPromise,\n\tfromPushNotification,\n\tfromSSE,\n\tfromSSEWithOptions,\n\tfromTimer,\n\tfromWebhook,\n\tfromWebhookWithOptions,\n\tfromWebSocket,\n\tfromWebSocketWithOptions,\n\tinterval,\n\tmatchesCron,\n\ttype NodeInput,\n\tnever,\n\tof,\n\ttype PushRegister,\n\ttype PushUnsubscribe,\n\tparseCron,\n\ttype SingleFromAnyOptions,\n\tsingleFromAny,\n\ttype TimerSourceOpts,\n\tthrowError,\n\ttimer,\n} from \"../graph/sources.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.\n * @param v - v value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isInvalidErrorPayload } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param reason - reason value used by the helper.\n * @param fallback - fallback value used by the helper.\n * @returns The error payload result.\n * @category core\n * @example\n * ```ts\n * import { errorPayload } from \"@graphrefly/ts/core\";\n * ```\n */\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\n/**\n * Look up the tier number for a message type.\n *\n * @param t - One of the closed-set protocol message tags.\n * @returns The tier assigned by the compile-time tier table.\n * @example\n * ```ts\n * messageTier(\"DATA\"); // 3\n * ```\n * @category core\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).\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isDeferredTier } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isValueTier } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isPauseBufferedTier } from \"@graphrefly/ts/core\";\n * ```\n */\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 * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isTerminal } from \"@graphrefly/ts/core\";\n * ```\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 * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isUpAllowed } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\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 deepFreezeStrictJson<T extends StrictJsonValue>(value: T): T {\n\tif (value !== null && typeof value === \"object\") {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) deepFreezeStrictJson(item);\n\t\t} else {\n\t\t\tfor (const item of Object.values(value)) deepFreezeStrictJson(item);\n\t\t}\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\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.\n * @param value - Unknown value to check or decode.\n * @returns A `string` value.\n * @category json\n * @example\n * ```ts\n * import { stableJsonString } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(cloneStrictJsonValue(value));\n}\n\n/** Build a JSON codec using stable object-key ordering.\n * @returns A `Codec<T>` value.\n * @category json\n * @example\n * ```ts\n * import { jsonCodecFor } from \"@graphrefly/ts/storage\";\n * ```\n */\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\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n\t\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\t\tassertNoUnpairedSurrogates(descriptor.value, 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\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\tassertNoUnpairedSurrogates(descriptor.value, seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction strictJsonDataErrorsInner(\n\tvalue: unknown,\n\tlabel: string,\n\tseen: Set<object>,\n): { readonly errors: readonly string[]; readonly value?: StrictJsonValue } {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n\t\tif (typeof value === \"string\" && hasUnpairedSurrogate(value)) {\n\t\t\treturn { errors: [`${label} must not contain unpaired surrogate strings`] };\n\t\t}\n\t\treturn { errors: [], value };\n\t}\n\tif (typeof value === \"number\") {\n\t\ttry {\n\t\t\tassertStrictJsonNumber(value, label);\n\t\t} catch (error) {\n\t\t\treturn { errors: [error instanceof Error ? error.message : String(error)] };\n\t\t}\n\t\treturn { errors: [], value };\n\t}\n\tif (typeof value !== \"object\") {\n\t\treturn { errors: [`${label} is not JSON-encodable`] };\n\t}\n\tif (seen.has(value)) return { errors: [`${label} must not contain circular references`] };\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\treturn { errors: [`stableJsonString: non-plain object at ${label}`] };\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst errors: string[] = [];\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\terrors.push(`${label} must not carry symbol keys`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\t\tif (descriptor === undefined) continue;\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 (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\t\terrors.push(`${label}.${key} must be a data property`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\terrors.push(`${label}.${key} must be an indexed data property`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && isIndex && !descriptor.enumerable) {\n\t\t\t\t\terrors.push(`${label}.${key} must be enumerable`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: StrictJsonValue[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (descriptor === undefined) {\n\t\t\t\t\terrors.push(`stableJsonString: sparse array hole at ${label}[${index}]`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\t\terrors.push(`${label}[${index}] must be a data property`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!descriptor.enumerable) {\n\t\t\t\t\terrors.push(`${label}[${index}] must be enumerable`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst nested = strictJsonDataErrorsInner(descriptor.value, `${label}[${index}]`, seen);\n\t\t\t\terrors.push(...nested.errors);\n\t\t\t\tif (nested.errors.length === 0 && nested.value !== undefined) out.push(nested.value);\n\t\t\t}\n\t\t\tif (errors.length > 0) return { errors };\n\t\t\treturn { errors: [], value: Object.freeze(out) };\n\t\t}\n\t\tconst errors: string[] = [];\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\terrors.push(`${label} must not carry symbol keys`);\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) continue;\n\t\t\tif (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\terrors.push(`${label}.${key} must be a data property`);\n\t\t\t}\n\t\t\tif (!descriptor.enumerable) {\n\t\t\t\terrors.push(`${label}.${key} must be enumerable`);\n\t\t\t}\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\terrors.push(`${label}.${key} must not contain unpaired surrogate keys`);\n\t\t\t}\n\t\t}\n\t\tconst out: Record<string, StrictJsonValue> = {};\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\tconst nested = strictJsonDataErrorsInner(descriptor.value, `${label}.${key}`, seen);\n\t\t\terrors.push(...nested.errors);\n\t\t\tif (nested.errors.length === 0 && nested.value !== undefined) {\n\t\t\t\tObject.defineProperty(out, key, {\n\t\t\t\t\tvalue: nested.value,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (errors.length > 0) return { errors };\n\t\treturn { errors: [], value: Object.freeze(out) };\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Descriptor-safe strict JSON validation errors.\n *\n * The scanner checks property descriptors before reading values, so accessor-backed\n * host objects are rejected without executing getters. It is shared by D585\n * passive store frames and metadata validators that must accept only ordinary DATA.\n * @param value - Unknown value to validate.\n * @param label - Human-readable label for returned issue paths.\n * @returns Validation errors; empty means the value can be cloned as strict JSON.\n * @category json\n */\nexport function strictJsonDataErrors(value: unknown, label = \"strictJsonValue\"): readonly string[] {\n\ttry {\n\t\treturn strictJsonDataErrorsInner(value, label, new Set<object>()).errors;\n\t} catch (error) {\n\t\treturn [error instanceof Error ? error.message : String(error)];\n\t}\n}\n\n/** Clone a host value into deep-frozen strict canonical JSON DATA.\n *\n * The clone is descriptor-safe: accessors, sparse arrays, symbols, non-enumerable\n * fields, circular references, and non-portable JSON numbers are rejected before\n * values are read through normal property access.\n * @param value - Unknown value to clone.\n * @param label - Human-readable label for errors.\n * @returns A deep-frozen strict JSON value with deterministically sorted object keys.\n * @category json\n */\nexport function cloneStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\tconst result = strictJsonDataErrorsInner(value, label, new Set<object>());\n\tif (result.errors.length > 0 || result.value === undefined) {\n\t\tthrow new TypeError(`${label}: ${result.errors.join(\"; \")}`);\n\t}\n\treturn deepFreezeStrictJson(result.value);\n}\n\n/** Clone a host object into a deep-frozen strict canonical JSON object.\n * @param value - Unknown value to clone.\n * @param label - Human-readable label for errors.\n * @returns A deep-frozen strict JSON object.\n * @category json\n */\nexport function cloneStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst cloned = cloneStrictJsonValue(value, label);\n\tif (cloned === null || typeof cloned !== \"object\" || Array.isArray(cloned)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn cloned as StrictJsonObject;\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 * @returns A `Codec<T>` value.\n * @category json\n * @example\n * ```ts\n * import { strictJsonCodecFor } from \"@graphrefly/ts/storage\";\n * ```\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.\n * @param value - Unknown value to check or decode.\n * @returns A `Uint8Array` value.\n * @category json\n * @example\n * ```ts\n * import { strictCanonicalJsonBytes } from \"@graphrefly/ts\";\n * ```\n */\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.\n * @param value - Unknown value to check or decode.\n * @param label - label value used by the helper.\n * @returns The narrowed, validated value.\n * @category json\n * @example\n * ```ts\n * import { assertStrictJsonValue } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn cloneStrictJsonValue(value, label);\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.\n * @param value - Unknown value to check or decode.\n * @param label - label value used by the helper.\n * @returns The narrowed, validated value.\n * @category json\n * @example\n * ```ts\n * import { assertStrictJsonObject } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\treturn cloneStrictJsonObject(value, label);\n}\n","/**\n * Graph checkpoint public data shape (D83/D86/D90/D116).\n *\n * Checkpoint is a graph lifecycle snapshot: strict-JSON-compatible data, no storage I/O,\n * no observe-log replay, and no restore runtime in this first TS slice.\n */\n\nimport { type StrictJsonValue, strictJsonCodec } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { NodeVersionJson } from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\n\nexport const GRAPH_CHECKPOINT_VERSION = \"graphrefly.checkpoint.v1\" as const;\n\nexport type GraphCheckpointVersion = typeof GRAPH_CHECKPOINT_VERSION;\n\nexport type GraphCheckpointJson = StrictJsonValue;\n\nexport type GraphCheckpointValue =\n\t| { kind: \"SENTINEL\" }\n\t| { kind: \"DATA\"; data: GraphCheckpointJson };\n\nexport type GraphCheckpointTerminal =\n\t| { kind: \"none\" }\n\t| { kind: \"COMPLETE\" }\n\t| { kind: \"ERROR\"; error: GraphCheckpointJson };\n\nexport type GraphCheckpointFactory =\n\t| {\n\t\t\tkind: \"registry-ref\";\n\t\t\tref: string;\n\t\t\tconfig?: GraphCheckpointJson;\n\t\t\tconfigVersion?: GraphCheckpointJson;\n\t }\n\t| { kind: \"local-only\"; name: string; reason: string };\n\nexport interface GraphCheckpointNode {\n\tid: string;\n\tname?: string;\n\tfactory: GraphCheckpointFactory;\n\tstatus: string;\n\tdeps: string[];\n\tvalue: GraphCheckpointValue;\n\tbackendState?: GraphCheckpointJson;\n\tversion?: NodeVersionJson;\n\tterminal: GraphCheckpointTerminal;\n\tlifecycle: { activated: boolean; hasCalledFnOnce: boolean };\n\tctxState: { persist: boolean; value: GraphCheckpointValue };\n\tmeta?: { [key: string]: GraphCheckpointJson };\n}\n\nexport interface GraphCheckpointEdge {\n\tfrom: string;\n\tto: string;\n}\n\nexport interface GraphCheckpointMount {\n\tat: string;\n\tcheckpoint: GraphCheckpoint;\n}\n\nexport interface GraphCheckpoint {\n\tversion: GraphCheckpointVersion;\n\tname?: string;\n\tnodes: GraphCheckpointNode[];\n\tedges: GraphCheckpointEdge[];\n\tmounts?: GraphCheckpointMount[];\n}\n\nexport function toCheckpointJson(value: unknown, path = \"$\"): GraphCheckpointJson {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as GraphCheckpointJson;\n\t} catch (cause) {\n\t\tthrow new TypeError(`checkpoint: value at ${path} is not strict JSON compatible`, {\n\t\t\tcause,\n\t\t});\n\t}\n}\n\nexport function checkpointValue(\n\tvalue: unknown,\n\thasData: boolean,\n\tpath: string,\n): GraphCheckpointValue {\n\tif (!hasData || value === SENTINEL) return { kind: \"SENTINEL\" };\n\treturn { kind: \"DATA\", data: toCheckpointJson(value, path) };\n}\n\nexport function checkpointTerminal(value: unknown, path: string): GraphCheckpointTerminal {\n\tif (value === undefined) return { kind: \"none\" };\n\tif (value === true) return { kind: \"COMPLETE\" };\n\treturn { kind: \"ERROR\", error: toCheckpointJson(value, path) };\n}\n\ntype BackendStateContributor = () => unknown;\n\nconst backendStateContributors = new WeakMap<Node<unknown>, BackendStateContributor>();\n\n/** @internal D160: collection-owned backend checkpoint contributor for graph checkpoint. */\nexport function registerBackendStateContributor(\n\tnode: Node<unknown>,\n\tcontributor: BackendStateContributor,\n): void {\n\tbackendStateContributors.set(node, contributor);\n}\n\n/** @internal D160: capture a node's collection backend state when it has a contributor. */\nexport function checkpointBackendStateOfNode(\n\tnode: Node<unknown>,\n\tpath: string,\n): GraphCheckpointJson | undefined {\n\tconst contributor = backendStateContributors.get(node);\n\tif (contributor === undefined) return undefined;\n\treturn toCheckpointJson(contributor(), path);\n}\n","/**\n * 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\nexport interface CtxDepWaveOrigin {\n\treadonly live: readonly (readonly boolean[])[];\n}\n\nconst ctxDepWaveOrigins = new WeakMap<Ctx, CtxDepWaveOrigin>();\n\n/** @internal Attach per-dep wave-origin state without exposing it on the public Ctx shape. */\nexport function setCtxDepWaveOrigin(ctx: Ctx, origin: CtxDepWaveOrigin): void {\n\tctxDepWaveOrigins.set(ctx, origin);\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\n/**\n * Check whether a terminal slot carries COMPLETE.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is the COMPLETE shorthand `true`.\n * @example\n * ```ts\n * isTerminalComplete(true); // true\n * ```\n * @category core\n */\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\n/**\n * Check whether a terminal slot carries ERROR payload data.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is neither none nor COMPLETE.\n * @example\n * ```ts\n * isTerminalError(new Error(\"boom\")); // true\n * ```\n * @category core\n */\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\n/**\n * Read the terminal payload when the slot is an ERROR value.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns The payload when `t` is an ERROR slot, otherwise `undefined`.\n * @example\n * ```ts\n * terminalErrorValue(new Error(\"boom\"));\n * ```\n * @category core\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.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @returns A `number` value.\n * @category core\n * @example\n * ```ts\n * import { depCount } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/**\n * Check whether a terminal slot carries no terminal state.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is `false` or `undefined`.\n * @example\n * ```ts\n * isTerminalNone(false); // true\n * ```\n * @category core\n */\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns A `readonly (readonly unknown[])[]` value.\n * @category core\n * @example\n * ```ts\n * import { depWaves } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for event-counting operator bodies; null = no wave.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns A `readonly unknown[] | null` value.\n * @category core\n * @example\n * ```ts\n * import { depBatch } from \"@graphrefly/ts/core\";\n * ```\n */\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/** Internal adapter helper: dep waves produced by live graph-event deliveries only. */\nexport function depLiveWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\tconst waves = depWaves(ctx, depIndex);\n\tconst live = ctxDepWaveOrigins.get(ctx)?.live[depIndex] ?? [];\n\treturn waves.filter((_, index) => live[index]);\n}\n\n/** Internal adapter helper: flattened DATA values from live-delivered dep waves only. */\nexport function depLiveBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depLiveWaves(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/**\n * Read the most recent DATA value from one upstream dependency during a node run.\n *\n * `depIndex` is positional: `0` reads the first dependency in `node([first, ...])`, `1` reads the\n * second dependency, and so on. If that dependency has not produced DATA in the current graph\n * lifecycle, the value is `undefined`.\n *\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - Zero-based dependency position in the node's dependency list.\n * @returns The latest DATA value for that dependency, or `undefined` when no DATA is available yet.\n * @category core\n * @example\n * ```ts\n * import { depLatest, node } from \"@graphrefly/ts/core\";\n *\n * const count = node<number>([], null, { initial: 1 });\n * const doubled = node<number>([count], (ctx) => {\n * const latest = depLatest(ctx, 0);\n * if (latest === undefined) return;\n * ctx.down([[\"DATA\", Number(latest) * 2]]);\n * });\n * ```\n */\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.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns The dep terminal result.\n * @category core\n * @example\n * ```ts\n * import { depTerminal } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated retired handle-dispatch PoC (R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/** 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 dispatcherHandleStatKey = (h: Handle): string =>\n\tJSON.stringify([String(h.poolId), String(h.handleId)]);\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 * @example\n * ```ts\n * import { Dispatcher } from \"@graphrefly/ts/core\";\n *\n * const dispatcher = new Dispatcher();\n * ```\n * @category core\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(dispatcherHandleStatKey(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(dispatcherHandleStatKey(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 = dispatcherHandleStatKey(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\n/**\n * Graph-local bundle of environment drivers.\n *\n * Instances are immutable snapshots of the process, HTTP, SSE, WebSocket, and webhook\n * driver set consumed by source/adapter bodies.\n *\n * @example\n * ```ts\n * import { EnvironmentDrivers, fetchHttpDriver } from \"@graphrefly/ts/graph\";\n *\n * const drivers = new EnvironmentDrivers().withHttp(fetchHttpDriver());\n * ```\n * @category graph\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\n/**\n * Adapt a Fetch-like function into a graph-local HTTP driver.\n *\n * @param fetchFn - Fetch implementation that returns a response-like object.\n * @returns A driver that performs one-shot HTTP requests and reports a single result.\n * @example\n * ```ts\n * import { fetchHttpDriver } from \"@graphrefly/ts/graph\";\n *\n * const http = fetchHttpDriver(fetch);\n * ```\n * @category graph\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\n/**\n * Adapt a DOM/WebSocket constructor into a graph-local WebSocket driver.\n *\n * @param WebSocketCtor - WebSocket constructor used to open connections.\n * @returns A driver that can connect, send, and optionally stream live sessions.\n * @example\n * ```ts\n * import { domWebSocketDriver } from \"@graphrefly/ts/graph\";\n *\n * const ws = domWebSocketDriver(WebSocket);\n * ```\n * @category graph\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\twaveLive: boolean[][];\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\twaveLive: Array.from({ length: depCount }, () => []),\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\tsetCtxDepWaveOrigin,\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\twaveLive: self._dep.waveLive.map((waves) => [...waves]),\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?: {\n\t\twaveData: unknown[][][];\n\t\twaveLive?: boolean[][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t},\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\tsetCtxDepWaveOrigin(ctx, { live: snapshot?.waveLive ?? self._dep.waveLive });\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\tsetCtxDepWaveOrigin(ctx, { live: self._dep.waveLive });\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.waveLive[idx].push(delivery !== undefined);\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.waveLive[i] = [];\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?: {\n\t\twaveData: unknown[][][];\n\t\twaveLive?: boolean[][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): 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.waveLive[idx] = [];\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.waveLive = [];\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.waveLive[i] = [];\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 } from \"@graphrefly/ts/core\";\n * import { graph } from \"@graphrefly/ts/graph\";\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 * @param bytes - Canonical bytes to decode.\n * @returns A `string` value.\n * @category core\n * @example\n * ```ts\n * import { defaultNodeVersionHash } from \"@graphrefly/ts/core\";\n * ```\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\ttype NodeVersion,\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._dep.waveLive = newDeps.map(() => []);\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/core\";\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\twaveLive?: boolean[][];\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/core\";\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 * @param deps - Declared dependency node or nodes.\n * @param fn - Synchronous function invoked by the helper.\n * @param opts - Options that configure the helper.\n * @returns A `Node<T>` value.\n * @category core\n * @example\n * ```ts\n * import { dynamicNode } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","/**\n * Operators as free-standing factory definitions (D43 / D6 / D40 Catalog-first).\n *\n * Operators are `node` sugar (D6), NOT verbs (D4) and NEVER in parity (D24). Each is a\n * pure {@link Operator} spec — `{factory, body, opts}` — built on the bare `node` primitive\n * (NOT the `derived` verb): `body` reads ctx dep slots positionally and emits via\n * `ctx.down`. Two ways to instantiate:\n *\n * - {@link initNode}(op, deps, opts?) — bare, no Graph; returns a working `Node<T>`.\n * - `g.initNode(op, deps, opts?)` — graph-bound; the SAME call, plus inspection registration\n * (the real factory name lands in the graph's `_entries`, so describe/observe/profile\n * show it — D6/R-describe — while the node stays thin, R-node-thin).\n *\n * The D30 throw→ERROR boundary lives once, in the free {@link initNode} (which `g.initNode`\n * funnels through). The pure-ts `operatorOpts/partialOperatorOpts/gatedOperatorOpts` trio is\n * NOT ported: its sole job (`describeKind:\"derived\"`) is dead under D6/D39 (factory = the\n * REAL operator name); only the `partial`/`terminalAsRealInput` flags survive, carried\n * per-operator in `op.opts`.\n *\n * Config is folded into the factory (`map(fn)`, `scan(reducer, seed)`, `take(n)`, `merge()`),\n * so fn params are annotated where the source type can't be inferred (RxJS-pipe cost);\n * dep-type safety is recovered by the typed `g.initNode` overloads.\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepLatest,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { NodeCore } from \"../node/core.js\";\nimport { Node, type NodeOptions, withNodeCore } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { type GraphCheckpointJson, toCheckpointJson } from \"./checkpoint.js\";\nimport type { GraphRestoreDefinition, GraphRestoreEntry, GraphRestoreRegistry } from \"./restore.js\";\n\n/**\n * A free-standing operator definition (D43). `TIn` = the element type each dep delivers\n * (the operator reads `depLatest(ctx, i) as TIn`); `TOut` = the emitted value type.\n * `__in`/`__out` are phantom-only (never assigned) — they let `g.initNode` infer + check the\n * dep tuple against the operator without an explicit type argument.\n */\nexport interface Operator<TIn = unknown, TOut = unknown> {\n\t/** Real operator name shown in describe (D6/L1.5) — recorded at `_add` by `g.initNode`. */\n\treadonly factory: string;\n\t/** The ctx-body: reads ctx dep slots positionally, emits via `ctx.down`. */\n\treadonly body: (ctx: Ctx) => void;\n\t/** Behavioral node options the operator needs (e.g. `partial:true` for combine-family). */\n\treadonly opts?: Partial<NodeOptions<TOut>>;\n\t/**\n\t * D97/D100 restore metadata derived from a named definition or static built-in config.\n\t * This is semantic metadata only; dispatcher handles stay graph-local runtime state.\n\t */\n\treadonly restore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t};\n\t/** @internal phantom — never set; carries the dep element type for `g.initNode` inference. */\n\treadonly __in?: TIn;\n\t/** @internal phantom — never set; carries the output value type. */\n\treadonly __out?: TOut;\n}\n\ntype MutableRestoreRegistry = Map<string, GraphRestoreEntry> | Record<string, GraphRestoreEntry>;\n\nexport type RestoreRegistryEntry = GraphRestoreEntry;\n\nexport interface Definition<S = unknown, T = unknown> extends GraphRestoreDefinition<S, T> {\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport interface DefineOpts {\n\tregistry?: MutableRestoreRegistry;\n}\n\nfunction registryHas(registry: MutableRestoreRegistry, ref: string): boolean {\n\treturn registry instanceof Map ? registry.has(ref) : Object.hasOwn(registry, ref);\n}\n\nfunction registrySet(\n\tregistry: MutableRestoreRegistry,\n\tref: string,\n\tentry: GraphRestoreEntry,\n): void {\n\tif (registryHas(registry, ref)) {\n\t\tthrow new Error(`restoreRegistry: duplicate ref '${ref}'`);\n\t}\n\tif (registry instanceof Map) registry.set(ref, entry);\n\telse registry[ref] = entry;\n}\n\nexport function addToRestoreRegistry(\n\tregistry: MutableRestoreRegistry,\n\tentry: GraphRestoreEntry,\n): void {\n\tregistrySet(registry, entry.ref, entry);\n}\n\n/**\n * Merge restore registry entries into a duplicate-checking Map.\n *\n * @param entries - Additional restore entries to add.\n * @param base - Optional base registry to copy from.\n * @returns A Map keyed by restore ref.\n * @example\n * ```ts\n * restoreRegistry([define(\"trim\", (value: string) => value.trim())]);\n * ```\n * @category operators\n */\nexport function restoreRegistry(\n\tentries: readonly GraphRestoreEntry[] = [],\n\tbase?: GraphRestoreRegistry,\n): Map<string, GraphRestoreEntry> {\n\tconst out = new Map<string, GraphRestoreEntry>();\n\tif (base instanceof Map) {\n\t\tfor (const [ref, entry] of base) registrySet(out, ref, entry);\n\t} else if (base !== undefined) {\n\t\tfor (const [ref, entry] of Object.entries(base)) registrySet(out, ref, entry);\n\t}\n\tfor (const entry of entries) addToRestoreRegistry(out, entry);\n\treturn out;\n}\n\nfunction isDefinition<S, T>(fn: ((v: S) => T) | Definition<S, T>): fn is Definition<S, T> {\n\treturn typeof fn === \"object\" && fn !== null && (fn as Definition<S, T>).kind === \"definition\";\n}\n\n/**\n * Register a named restore definition.\n *\n * @param ref - Stable restore reference name.\n * @param fn - Pure transform function used during restoration.\n * @param opts - Optional registry to receive the new definition.\n * @returns A named definition record.\n * @example\n * ```ts\n * define(\"trim\", (value: string) => value.trim());\n * ```\n * @category operators\n */\nexport function define<S, T>(\n\tref: string,\n\tfn: (v: S) => T,\n\topts: DefineOpts = {},\n): Definition<S, T> {\n\tconst jsonRef = toCheckpointJson(ref, \"define.ref\");\n\tif (typeof jsonRef !== \"string\") throw new TypeError(\"define: ref must be a string\");\n\tconst definition: Definition<S, T> = {\n\t\tkind: \"definition\",\n\t\tref: jsonRef,\n\t\tfn,\n\t};\n\tif (opts.registry !== undefined) addToRestoreRegistry(opts.registry, definition);\n\treturn definition;\n}\n\n/**\n * Instantiate an operator as a bare `Node<T>` — NO Graph required (D43 bare-node path).\n * Wraps `op.body` in the D30 value-throw→ERROR boundary; merges `op.opts` with caller `opts`\n * (caller wins, so `partial`/`pool`/`dispatcher` overrides take effect). The\n * dispatcher defaults to the process-global (D26) unless `opts.dispatcher` is passed.\n *\n * `g.initNode` is the same call PLUS graph registration; graph inspection\n * (describe/observe/profile) requires that path — a node built bare here is not registered in\n * any graph's index.\n * @param op - op value used by the helper.\n * @param deps - Declared dependency node or nodes.\n * @param opts - Options that configure the helper.\n * @returns A `Node<TOut>` value.\n * @category operators\n * @example\n * ```ts\n * import { initNode } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function initNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn makeInitNode(op, deps, opts);\n}\n\n/** @internal Graph-bound operator instantiation into a graph-local B49 core. */\nexport function initNodeWithCore<TIn, TOut>(\n\tcore: NodeCore,\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn withNodeCore(core, () => makeInitNode(op, deps, opts));\n}\n\nfunction makeInitNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut>,\n): Node<TOut> {\n\tconst body = operatorNodeFn(op);\n\t// D43-reserved / D51: stamp the operator's real factory onto the bare node so a runtime *Map\n\t// inner (created here via fromAny, NOT registered in any graph) is named in describe's\n\t// auto-discovery. A graph-bound g.initNode also records it in `_entries` (entry.factory wins\n\t// there); this field is only read for a node absent from the graph index. Caller opts win.\n\treturn new Node<TOut>([...deps], body, { factory: op.factory, ...op.opts, ...opts });\n}\n\n/** @internal Build the dispatcher body for an Operator spec. */\nexport function operatorNodeFn<TIn, TOut>(op: Operator<TIn, TOut>): NodeFn {\n\treturn (ctx) => {\n\t\ttry {\n\t\t\top.body(ctx);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"operator threw without a valid error payload\")]]); // D30: value-level throw → ERROR\n\t\t}\n\t};\n}\n\n// ── Slice 1 — single-dep map / take / control (CSP-2.7 catalog re-derive, D40) ──\n// All read dep 0 positionally + emit via ctx.down. Under D49 every occurrence is DATA (no\n// equals-absorption); a body that returns WITHOUT emitting gets a substrate-synthesized undirty\n// RESOLVED (R-resolved-undirty) — so a \"skip this wave\" is a bare `return`. Terminal-emitting\n// operators (reduce/last/find/elementAt) read `depTerminal(ctx, 0)` via the\n// `completeWhenDepsComplete:false + terminalAsRealInput:true` flags (R-deps-terminal): the fn fires\n// on the source's COMPLETE and emits its final value. NOT 1:1 pure-ts ports — the frozen reference\n// (D41) uses a producer + internal `subscribeOr`, the D45-banned describe island; these are\n// declared-dep nodes whose single edge `describe` shows truthfully.\n\n/**\n * Transform each upstream DATA value with a synchronous mapping function.\n *\n * @param fn - Mapping function, or a named `define()` definition for checkpoint restoration.\n * @returns An operator that emits `fn(value)` for each upstream value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { map } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const count = g.state(1);\n * const doubled = g.initNode(map((value: number) => value * 2), [count]);\n * ```\n * @remarks **Restorable maps:** Passing a named `define()` registers semantic restore metadata.\n * @category operators\n */\nexport function map<S, T>(fn: ((v: S) => T) | Definition<S, T>): Operator<S, T> {\n\tif (isDefinition(fn)) {\n\t\treturn mapFromFunction(fn.fn, {\n\t\t\tref: \"map\",\n\t\t\tconfig: { fn: toCheckpointJson(fn.ref, `map.fn`) },\n\t\t});\n\t}\n\treturn mapFromFunction(fn);\n}\n\nfunction mapFromFunction<S, T>(\n\tfn: (v: S) => T,\n\trestore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t},\n): Operator<S, T> {\n\treturn {\n\t\tfactory: \"map\",\n\t\t...(restore ? { restore } : {}),\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) ctx.down([[\"DATA\", fn(v as S)]]);\n\t\t},\n\t};\n}\n\n/**\n * Pass through upstream values that satisfy a predicate.\n *\n * @param pred - Predicate evaluated for each upstream DATA value.\n * @returns An operator that emits matching values and stays quiet for non-matches.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { filter } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const count = g.state(0);\n * const even = g.initNode(filter((value: number) => value % 2 === 0), [count]);\n * ```\n * @category operators\n */\nexport function filter<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"filter\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) if (pred(v as S)) ctx.down([[\"DATA\", v]]);\n\t\t},\n\t};\n}\n\n/**\n * Accumulate upstream values and emit each intermediate accumulator.\n *\n * @param reducer - Reducer called with the previous accumulator and each upstream value.\n * @param seed - Initial accumulator value.\n * @returns An operator that emits the accumulator after every input value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { scan } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const values = g.state(1);\n * const total = g.initNode(scan((sum: number, value: number) => sum + value, 0), [values]);\n * ```\n * @category operators\n */\nexport function scan<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"scan\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tfor (const v of b) {\n\t\t\t\tacc = reducer(acc, v as S);\n\t\t\t\tctx.down([[\"DATA\", acc]]);\n\t\t\t}\n\t\t\tctx.state.set(acc);\n\t\t},\n\t};\n}\n\n/**\n * Emit the first `n` upstream values, then complete.\n *\n * @param n - Number of DATA values to pass before completion.\n * @returns An operator that forwards at most `n` values and then emits COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { take } from \"@graphrefly/ts/operators\";\n *\n * const firstThree = graph().initNode(take<number>(3), [source]);\n * ```\n * @category operators\n */\nexport function take<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"take\",\n\t\trestore: { ref: \"take\", config: { n: toCheckpointJson(n, \"take.n\") } },\n\t\tbody: (ctx) => {\n\t\t\tif (n <= 0) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (count >= n) return; // already satisfied\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count >= n) break;\n\t\t\t\tcount += 1;\n\t\t\t\tctx.down(count >= n ? [[\"DATA\", v], [\"COMPLETE\"]] : [[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * Suppress consecutive duplicate values.\n *\n * @param eq - Equality predicate; defaults to `Object.is`.\n * @returns An operator that emits only when the next value differs from the previous emitted value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { distinctUntilChanged } from \"@graphrefly/ts/operators\";\n *\n * const stable = graph().initNode(distinctUntilChanged<number>(), [source]);\n * ```\n * @category operators\n */\nexport function distinctUntilChanged<S>(eq: (a: S, b: S) => boolean = Object.is): Operator<S, S> {\n\treturn {\n\t\tfactory: \"distinctUntilChanged\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst prev = ctx.state.get<{ v: S }>();\n\t\t\tlet last = prev?.v;\n\t\t\tlet hasLast = prev !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasLast && eq(last as S, v)) continue;\n\t\t\t\tlast = v;\n\t\t\t\thasLast = true;\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tif (hasLast) ctx.state.set({ v: last as S });\n\t\t},\n\t};\n}\n\n/**\n * merge: interleave several sources — emit each DATA from whichever dep fired. `partial:true`\n * (combine-family): fires on any single dep, not gated on all deps settling.\n *\n * @returns An operator that forwards DATA from any dependency.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { merge } from \"@graphrefly/ts/operators\";\n *\n * const merged = graph().initNode(merge<number>(), [left, right]);\n * ```\n * @category operators\n */\nexport function merge<T>(): Operator<T, T> {\n\treturn {\n\t\tfactory: \"merge\",\n\t\topts: { partial: true },\n\t\tbody: (ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b && b.length > 0) {\n\t\t\t\t\tfor (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * reduce: accumulate over the whole source, emit ONE final value on the source's COMPLETE\n * (RxJS `reduce`). Unlike {@link scan} (which emits every step), reduce stays quiet until the\n * source terminates. `completeWhenDepsComplete:false + terminalAsRealInput:true`: the fn fires on\n * the source COMPLETE (reading `terminal===true`) and emits the accumulator + COMPLETE. An empty\n * source emits the seed (RxJS parity). A source ERROR auto-forwards (errorWhenDepsError default).\n *\n * @param reducer - Reducer called with the accumulator and each upstream DATA value.\n * @param seed - Initial accumulator value emitted if the source completes empty.\n * @returns An operator that emits one accumulated value when the source completes.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { reduce } from \"@graphrefly/ts/operators\";\n *\n * const total = graph().initNode(reduce((sum: number, value: number) => sum + value, 0), [source]);\n * ```\n * @category operators\n */\nexport function reduce<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"reduce\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tif (b) for (const v of b) acc = reducer(acc, v as S);\n\t\t\tctx.state.set(acc);\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"DATA\", acc], [\"COMPLETE\"]]);\n\t\t\t// else (live DATA wave): no emit → substrate-synthesized undirty RESOLVED (D49).\n\t\t},\n\t};\n}\n\n/**\n * pairwise: emit `[previous, current]` for each consecutive pair; the very first value produces no\n * pair (quiet → undirty RESOLVED). Previous value is kept in `ctx.state`.\n * @returns A `Operator<S, readonly [S, S]>` value.\n * @category operators\n * @example\n * ```ts\n * import { pairwise } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function pairwise<S>(): Operator<S, readonly [S, S]> {\n\treturn {\n\t\tfactory: \"pairwise\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst st = ctx.state.get<{ prev: S }>();\n\t\t\tlet prev = st?.prev;\n\t\t\tlet hasPrev = st !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasPrev) ctx.down([[\"DATA\", [prev as S, v] as const]]);\n\t\t\t\tprev = v;\n\t\t\t\thasPrev = true;\n\t\t\t}\n\t\t\tif (hasPrev) ctx.state.set({ prev: prev as S });\n\t\t},\n\t};\n}\n\n/** skip: drop the first `n` DATA values, then pass the rest through.\n * @param n - n value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { skip } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function skip<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"skip\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count < n) {\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * takeWhile: emit values while `pred` holds; on the first value that fails `pred`, COMPLETE\n * WITHOUT emitting it (RxJS default, non-inclusive). Terminal-is-forever once it completes.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { takeWhile } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function takeWhile<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"takeWhile\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (pred(v)) ctx.down([[\"DATA\", v]]);\n\t\t\t\telse {\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * first: emit the first value matching `pred` (or simply the first value), then COMPLETE. EDGE\n * (RxJS divergence, flagged — same class as last/find/elementAt): if the source COMPLETEs with no\n * matching value, the substrate auto-cascades a bare COMPLETE (no value); RxJS `first()` throws\n * EmptyError. Could align to `[[ERROR, EmptyError]]` (expressible) if strict RxJS parity is wanted.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { first } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function first<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"first\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (!pred || pred(v)) {\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no match in this wave → undirty RESOLVED (await next match)\n\t\t},\n\t};\n}\n\n/**\n * last: emit the last value matching `pred` (or the last value) on the source's COMPLETE.\n * `completeWhenDepsComplete:false + terminalAsRealInput:true`. EDGE (RxJS divergence, flagged):\n * RxJS `last()` throws EmptyError when no value matched; we COMPLETE without a value (no throw) —\n * the clean-slate substrate has no \"complete-or-throw\" terminal and SENTINEL forbids emitting a\n * placeholder.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { last } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function last<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"last\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) for (const v of b) if (!pred || pred(v as S)) ctx.state.set({ v });\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) {\n\t\t\t\tconst st = ctx.state.get<{ v: S }>();\n\t\t\t\tctx.down(st ? [[\"DATA\", st.v], [\"COMPLETE\"]] : [[\"COMPLETE\"]]);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * find: emit the first value matching `pred`, then COMPLETE. EDGE (RxJS divergence, flagged): RxJS\n * `find` emits `undefined` then COMPLETE when nothing matched — but `undefined` IS the SENTINEL\n * (R-sentinel), so a not-found source COMPLETE here emits a bare COMPLETE (no value).\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { find } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function find<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"find\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (pred(v as S)) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // not found → bare COMPLETE\n\t\t},\n\t};\n}\n\n/**\n * elementAt: emit the value at zero-based `index`, then COMPLETE. EDGE (RxJS divergence, flagged):\n * RxJS throws ArgumentOutOfRangeError if the source completes before `index`; we COMPLETE without\n * a value (no throw), consistent with last/find.\n * @param index - index value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { elementAt } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function elementAt<S>(index: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"elementAt\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (count === index) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\tctx.state.set(count);\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // index out of range → bare COMPLETE\n\t\t},\n\t};\n}\n\n/** Observer object for {@link tap} — lifecycle-aware side effects (RxJS tap observer form). */\nexport interface TapObserver<T> {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n}\n\n/**\n * tap: invoke a side effect on each DATA (function form) or on data/error/complete (observer form);\n * values pass through unchanged. The observer form reads source terminals\n * (`completeWhenDepsComplete:false + errorWhenDepsError:false + terminalAsRealInput:true`) so it can\n * call `error`/`complete` then forward the terminal; the function form lets the substrate\n * auto-cascade terminals.\n * @param fnOrObserver - fn or observer value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { tap } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function tap<S>(fnOrObserver: ((v: S) => void) | TapObserver<S>): Operator<S, S> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\tconst fn = fnOrObserver;\n\t\treturn {\n\t\t\tfactory: \"tap\",\n\t\t\tbody: (ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\tif (b)\n\t\t\t\t\tfor (const v of b) {\n\t\t\t\t\t\tfn(v as S);\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\tconst obs = fnOrObserver;\n\treturn {\n\t\tfactory: \"tap\",\n\t\topts: {\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tobs.complete?.();\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(terminal)) {\n\t\t\t\tconst err = terminalErrorValue(terminal);\n\t\t\t\tobs.error?.(err);\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b)\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tobs.data?.(v as S);\n\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * onFirstData (alias `tapFirst`): invoke `fn` exactly once on the first qualifying value (default\n * `where: v => v != null` — null/undefined pass through without counting as \"first\"), then pass all\n * values through unchanged. The one-shot guard is per-node `ctx.state` (NOT a factory closure, so a\n * second instantiation of the same factory re-arms — R-ctx-state).\n * @param fn - Synchronous function invoked by the helper.\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { onFirstData } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function onFirstData<S>(\n\tfn: (v: S) => void,\n\topts?: { where?: (v: S) => boolean },\n): Operator<S, S> {\n\tconst where = opts?.where ?? ((v: S) => v != null);\n\treturn {\n\t\tfactory: \"onFirstData\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet fired = ctx.state.get<boolean>() ?? false;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (!fired && where(v as S)) {\n\t\t\t\t\tfired = true;\n\t\t\t\t\tfn(v as S);\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(fired);\n\t\t},\n\t};\n}\n\n/** tapFirst: alias of {@link onFirstData} (the one-shot companion to {@link tap}). */\nexport const tapFirst = onFirstData;\n\n/** Options for {@link settle}. */\nexport interface SettleOpts<S> {\n\t/** Consecutive no-change waves before declaring convergence + COMPLETE. */\n\tquietWaves: number;\n\t/** Optional hard cap on total waves before forced COMPLETE. */\n\tmaxWaves?: number;\n\t/** Optional comparator; a DATA equal to the previous one does NOT reset the quiet counter. */\n\tequals?: (a: S, b: S) => boolean;\n}\n\n/** Internal settle accumulator state (per-node, R-ctx-state). */\ninterface SettleState<S> {\n\tlast: S | undefined;\n\thasValue: boolean;\n\tquiet: number;\n\twaves: number;\n\tdone: boolean;\n}\n\n/**\n * settle: forward each DATA unchanged, watch for convergence, COMPLETE once the source has been\n * quiet for `quietWaves` consecutive waves (or `maxWaves` elapsed). \"Wave\" = one fn invocation\n * (a DATA batch OR a bare undirty RESOLVED end-of-wave). No polling (R-no-polling) — the counter\n * advances only on real upstream waves. `settle`'s own `equals` is a body comparator, NOT the\n * removed substrate `equals` (D49).\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { settle } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function settle<S>(opts: SettleOpts<S>): Operator<S, S> {\n\tconst { quietWaves, maxWaves, equals } = opts;\n\tif (!Number.isInteger(quietWaves) || quietWaves < 1) {\n\t\tthrow new RangeError(`settle: quietWaves must be a positive integer (got ${quietWaves})`);\n\t}\n\tif (maxWaves != null && (!Number.isInteger(maxWaves) || maxWaves < 1)) {\n\t\tthrow new RangeError(`settle: maxWaves must be a positive integer when set (got ${maxWaves})`);\n\t}\n\treturn {\n\t\tfactory: \"settle\",\n\t\tbody: (ctx) => {\n\t\t\tconst st: SettleState<S> = ctx.state.get<SettleState<S>>() ?? {\n\t\t\t\tlast: undefined,\n\t\t\t\thasValue: false,\n\t\t\t\tquiet: 0,\n\t\t\t\twaves: 0,\n\t\t\t\tdone: false,\n\t\t\t};\n\t\t\tif (st.done) return;\n\t\t\tst.waves++;\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet sawChange = false;\n\t\t\tif (b && b.length > 0) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tconst next = v as S;\n\t\t\t\t\tconst isChange = !st.hasValue || equals == null || !equals(st.last as S, next);\n\t\t\t\t\tif (isChange) sawChange = true;\n\t\t\t\t\tst.last = next;\n\t\t\t\t\tst.hasValue = true;\n\t\t\t\t\tctx.down([[\"DATA\", next]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.quiet = sawChange ? 0 : st.quiet + 1;\n\t\t\tconst settled = st.hasValue && st.quiet >= quietWaves;\n\t\t\tconst exhausted = maxWaves != null && st.waves >= maxWaves;\n\t\t\tif (settled || exhausted) {\n\t\t\t\tst.done = true;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t\t// A no-DATA wave that didn't converge → bare undirty RESOLVED is synthesized by the\n\t\t\t// substrate (D49); nothing to emit here.\n\t\t},\n\t};\n}\n\n// ── Slice 3 — error-handling control (CSP-2.7, D40) ──\n// rescue/catchError ABSORB the source ERROR (errorWhenDepsError:false) and read the error payload\n// from `depTerminal(ctx, 0)` (R-deps-terminal). They set completeWhenDepsComplete:false so a\n// normal source COMPLETE is forwarded explicitly — which ALSO sidesteps B40 (the\n// completeWhenDepsComplete:true × absorbed-errored-dep auto-complete gap): there is no auto-complete\n// to block. valve is a [source, control] gate (state-verb-legitimate control input).\n\n/**\n * rescue (alias `catchError`): replace an upstream ERROR with a recovered value. On source DATA →\n * forward; on source ERROR → emit `recover(err)` as DATA (if `recover` throws, forward THAT as\n * ERROR); on source COMPLETE → COMPLETE. After recovery the source is terminal-errored (dead) so no\n * further values flow — the recovered value is the final cached value (matches the frozen pure-ts\n * reference; it does NOT auto-COMPLETE, RxJS-`catchError(()=>of(x))` divergence, flagged).\n * @param recover - recover value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { rescue } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function rescue<S>(recover: (err: unknown) => S): Operator<S, S> {\n\treturn {\n\t\tfactory: \"rescue\",\n\t\topts: {\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (b) for (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t} else if (isTerminalError(terminal)) {\n\t\t\t\t// ERROR payload absorbed → recover.\n\t\t\t\ttry {\n\t\t\t\t\tctx.down([[\"DATA\", recover(terminalErrorValue(terminal))]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"rescue threw without a valid error payload\")]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** catchError: RxJS-named alias of {@link rescue}. */\nexport const catchError = rescue;\n\n/** Options for {@link valve}. */\nexport interface ValveOpts {\n\t/**\n\t * Optional AbortController (or a `() => AbortController | undefined` factory): on the control's\n\t * truthy→falsy edge, `valve` calls `controller.abort()` — cancel an in-flight async boundary\n\t * (LLM/fetch) the caller threaded `controller.signal` into. An external-resource cleanup (like\n\t * `ctx.onDeactivation`), NOT an imperative reactive trigger (R-no-imperative).\n\t */\n\tabortInFlight?: AbortController | (() => AbortController | undefined);\n}\n\n/**\n * valve: forward the source's DATA only while `control` (dep 1) is truthy; when closed, stay quiet\n * (undirty RESOLVED). `[source, control]` declared deps + `partial:true` (the control wave can fire\n * before the source ever delivers). `completeWhenDepsComplete:false` — closing the gate (control\n * terminating) does NOT complete the valve; only the SOURCE's terminal (read via\n * `terminalAsRealInput`) is forwarded. The `state`-verb control input is a legitimate external\n * boundary (D4 / D54), not a forbidden imperative trigger.\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { valve } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function valve<S>(opts?: ValveOpts): Operator<S, S> {\n\tconst abortInFlight = opts?.abortInFlight;\n\treturn {\n\t\tfactory: \"valve\",\n\t\topts: { partial: true, completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst ctlBatch = depBatch(ctx, 1);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\t\tconst controlValue = depLatest(ctx, 1) as boolean | undefined;\n\n\t\t\tif (abortInFlight != null) {\n\t\t\t\t// Fire abort on the truthy→falsy edge only (never on activation / no prior state).\n\t\t\t\tconst prev = ctx.state.get<{ ctl: boolean | undefined }>();\n\t\t\t\tif (prev?.ctl === true && !controlValue) {\n\t\t\t\t\tconst c = typeof abortInFlight === \"function\" ? abortInFlight() : abortInFlight;\n\t\t\t\t\tc?.abort();\n\t\t\t\t}\n\t\t\t\tctx.state.set({\n\t\t\t\t\tctl: controlValue === true ? true : controlValue == null ? undefined : false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Source terminal forwarding (control terminal is absorbed by completeWhenDepsComplete:false).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!controlValue) return; // gate closed → quiet (undirty RESOLVED)\n\n\t\t\tif (srcBatch && srcBatch.length > 0) {\n\t\t\t\tfor (const v of srcBatch) ctx.down([[\"DATA\", v]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Gate just opened this wave (control fired, source didn't): re-emit the last source value.\n\t\t\tconst srcLatest = depLatest(ctx, 0);\n\t\t\tif (ctlBatch && ctlBatch.length > 0 && srcLatest !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", srcLatest as S]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Async + sync sources (binding-layer sugar, D43 / D40 / feedback_async_sources_binding_layer).\n *\n * Sources are depless {@link Operator}`<never, T>` specs built on the `producer`/`node` path:\n * the body runs ONCE on activation (node `_activate`), schedules its work, and emits later via\n * the captured `ctx.down` (an external tier-3 emit → the leading DIRTY is synthesized for it,\n * R-dirty-before-data). Async lives ONLY here (R-no-raw-async / F-SYNC-CORE): `setTimeout` /\n * `Promise` / `for await` are confined to source bodies; the wave core stays sync. Cleanup is\n * `ctx.onDeactivation` (D28), NOT a returned object. Per-language (D6/D24), never in parity.\n *\n * Instantiate via `g.initNode(timer(1000), [])` (graph-bound, inspectable) or\n * {@link initNode}(timer(1000), []) (bare). Pool/pause defaults (D43): timer/interval =\n * sync + pausable:false (keep producing through PAUSE); fromPromise/fromAsyncIter = async\n * (default pausable, so a paused source buffers its late emits — R-async-paused).\n */\n\nimport type { Ctx } from \"../ctx/types.js\";\nimport type { Node, NodeOptions } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { toCheckpointJson } from \"./checkpoint.js\";\nimport type {\n\tDriverCancel,\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"./environment.js\";\nimport { initNode, type Operator } from \"./operators.js\";\n\n/**\n * Values accepted by {@link fromAny}: an existing Node, a Promise, an (a)sync iterable, or a\n * bare scalar. The universal coercion target for higher-order operators (CSP-2.7).\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Host-boundary options for {@link singleFromAny}. */\nexport interface SingleFromAnyOptions<K> {\n\t/**\n\t * Map a caller key to the in-flight dedupe key. Defaults to key identity; object keys dedupe only\n\t * when the same object reference is reused. Return a stable string/canonical value for structural\n\t * object-key dedupe.\n\t */\n\tkeyOf?: (key: K) => unknown;\n\t/** Treat a sync iterable result as a stream and take its first item. Defaults to scalar value. */\n\titer?: boolean;\n}\n\n/**\n * Internal: build a depless source spec. `setup` runs once on activation; its returned fn (if\n * any) is registered as the deactivation cleanup (clear timers / abort). `setup` schedules the\n * async work and emits via `ctx.down` — synchronously (sync sources) or later (async sources).\n */\nfunction source<T>(\n\tfactory: string,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: setup returns a cleanup fn OR nothing — the void arm keeps no-return source bodies (e.g. `of`/`fromIter`) ergonomic, same idiom as EffectFn.\n\tsetup: (ctx: Ctx) => void | (() => void),\n\topts?: Partial<NodeOptions<T>>,\n): Operator<never, T> {\n\treturn {\n\t\tfactory,\n\t\topts,\n\t\tbody: (ctx) => {\n\t\t\tlet cleanup: undefined | (() => void);\n\t\t\tlet deactivated = false;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tdeactivated = true;\n\t\t\t\tif (typeof cleanup === \"function\") cleanup();\n\t\t\t});\n\t\t\tconst maybeCleanup = setup(ctx);\n\t\t\tcleanup = typeof maybeCleanup === \"function\" ? maybeCleanup : undefined;\n\t\t\tif (deactivated && typeof cleanup === \"function\") cleanup();\n\t\t},\n\t};\n}\n\nfunction assertNonEmptyString(value: string, label: string): void {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new TypeError(`${label} must be a non-empty string`);\n\t}\n}\n\nfunction cleanupDriverWork(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n): void {\n\tactive.value = false;\n\tconst cancel = cancelSlot.value;\n\tcancelSlot.value = undefined;\n\tif (cancel !== undefined) runDriverCancel(cancel);\n}\n\nfunction installDriverCancel(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n\tcancel: DriverCancel,\n): void {\n\tif (active.value) cancelSlot.value = cancel;\n\telse runDriverCancel(cancel);\n}\n\nfunction runDriverCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cleanup is best-effort: it must not suppress graph-visible terminal delivery.\n\t}\n}\n\nfunction driverOneShotSource<T>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (result: DriverResult<T>) => void) => DriverCancel | undefined,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (result: DriverResult<T>) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\tif (result.ok) ctx.down([[\"DATA\", result.value], [\"COMPLETE\"]]);\n\t\t\t\telse ctx.down([[\"ERROR\", errorPayload(result.error)]]);\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction driverStreamSource<T, E extends { readonly kind: string }>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (event: E) => void) => DriverCancel | undefined,\n\tdataOf: (event: E) => T | undefined,\n\terrorOf: (event: E) => unknown,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (event: E) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\tconst value = dataOf(event);\n\t\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(errorOf(event))]]);\n\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\t\"cache\" in x &&\n\t\ttypeof (x as Node).subscribe === \"function\"\n\t);\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isAsyncIterable<T>(x: unknown): x is AsyncIterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nfunction isIterable<T>(x: unknown): x is Iterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\t);\n}\n\n/** Options shared by async/timer sources: an optional AbortSignal → ERROR on abort. */\nexport interface AsyncSourceOpts {\n\tsignal?: AbortSignal;\n}\n\nexport interface TimerSourceOpts extends AsyncSourceOpts {\n\tperiod?: number;\n}\n\n/** Options for {@link fromCron}. */\nexport interface FromCronOptions extends AsyncSourceOpts {\n\t/** Cron matcher polling interval in milliseconds. Default: 60_000. */\n\ttickMs?: number;\n\t/** IANA timezone used for wall-clock cron matching. Defaults to the host-local timezone. */\n\ttimezone?: string;\n\t/**\n\t * DST policy for timezone-aware matching. Current D484 defaults are explicit: nonexistent\n\t * wall-clock minutes are skipped, and repeated wall-clock minutes fire at most once.\n\t */\n\tdst?: {\n\t\treadonly nonexistent?: \"skip\";\n\t\treadonly repeated?: \"once\";\n\t};\n\t/**\n\t * Emitted value shape. `timestamp_ns` is a decimal string so it cannot lose precision as a\n\t * JavaScript number; use `timestamp_ms` when numeric millisecond precision is enough.\n\t */\n\toutput?: \"date\" | \"timestamp_ms\" | \"timestamp_ns\";\n}\n\n/** Minimal five-field cron schedule: minute hour day-of-month month day-of-week. */\nexport interface CronSchedule {\n\treadonly minutes: ReadonlySet<number>;\n\treadonly hours: ReadonlySet<number>;\n\treadonly daysOfMonth: ReadonlySet<number>;\n\treadonly months: ReadonlySet<number>;\n\treadonly daysOfWeek: ReadonlySet<number>;\n}\n\n/** DOM/EventEmitter-style target accepted by {@link fromEvent}. */\nexport interface EventTargetLike {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n}\n\nexport interface EventListenerOptionsLike {\n\tcapture?: boolean;\n\tpassive?: boolean;\n\tonce?: boolean;\n}\n\nexport type FromEventOptions = EventListenerOptionsLike;\n\n/** Host push registration callback accepted by {@link fromPushNotification}. */\nexport type PushUnsubscribe = () => void;\nexport type PushRegister<T> = (deliver: (payload: T) => void) => PushUnsubscribe | undefined;\n\nfunction parseCronField(field: string, min: number, max: number): Set<number> {\n\tif (field.length === 0) throw new Error(\"Invalid cron field: empty\");\n\tconst out = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tif (part.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tconst stepParts = part.split(\"/\");\n\t\tif (stepParts.length > 2) throw new Error(`Invalid cron step: ${part}`);\n\t\tconst [range, stepText] = stepParts;\n\t\tif (range == null || range.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (stepText === \"\") throw new Error(`Invalid cron step: ${part}`);\n\t\tconst step = stepText == null ? 1 : parseCronInt(stepText, `Invalid cron step: ${part}`);\n\t\tif (step < 1) throw new Error(`Invalid cron step: ${part}`);\n\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b, extra] = range.split(\"-\");\n\t\t\tif (extra !== undefined || a === \"\" || b === \"\")\n\t\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t\tstart = parseCronInt(a, `Invalid cron field: ${field}`);\n\t\t\tend = parseCronInt(b, `Invalid cron field: ${field}`);\n\t\t} else {\n\t\t\tstart = parseCronInt(range, `Invalid cron field: ${field}`);\n\t\t\tend = start;\n\t\t}\n\n\t\tif (!Number.isInteger(start) || !Number.isInteger(end)) {\n\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t}\n\t\tif (start < min || end > max) {\n\t\t\tthrow new RangeError(`Cron field out of range: ${field} (${min}-${max})`);\n\t\t}\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) out.add(i);\n\t}\n\treturn out;\n}\n\nfunction parseCronInt(text: string, message: string): number {\n\tif (!/^\\d+$/.test(text)) throw new Error(message);\n\tconst value = Number.parseInt(text, 10);\n\tif (!Number.isSafeInteger(value)) throw new Error(message);\n\treturn value;\n}\n\n/**\n * Parse a standard five-field cron expression.\n *\n * @param expr - Cron expression in `minute hour day month weekday` order.\n * @returns A normalized cron schedule with one set per field.\n * @example\n * ```ts\n * parseCron(\"0,5 * * * *\");\n * ```\n * @category sources\n */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5 || parts.some((part) => part.length === 0)) {\n\t\tthrow new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\t}\n\treturn {\n\t\tminutes: parseCronField(parts[0], 0, 59),\n\t\thours: parseCronField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseCronField(parts[2], 1, 31),\n\t\tmonths: parseCronField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseCronField(parts[4], 0, 6),\n\t};\n}\n\nexport interface CronMatchOptions {\n\t/** IANA timezone used for wall-clock projection. Defaults to the host-local timezone. */\n\ttimezone?: string;\n}\n\ninterface CronWallClockFields {\n\treadonly year: number;\n\treadonly month: number;\n\treadonly day: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly dayOfWeek: number;\n}\n\n/**\n * Test whether a date matches a parsed cron schedule.\n *\n * @param schedule - Parsed cron schedule to match against.\n * @param date - Date to test.\n * @param opts - Optional timezone override.\n * @returns `true` when the date satisfies all cron fields.\n * @example\n * ```ts\n * matchesCron(parseCron(\"0 * * * *\"), new Date());\n * ```\n * @category sources\n */\nexport function matchesCron(\n\tschedule: CronSchedule,\n\tdate: Date,\n\topts: CronMatchOptions = {},\n): boolean {\n\tconst fields = cronWallClockFields(date, opts.timezone);\n\treturn (\n\t\tschedule.minutes.has(fields.minute) &&\n\t\tschedule.hours.has(fields.hour) &&\n\t\tschedule.daysOfMonth.has(fields.day) &&\n\t\tschedule.months.has(fields.month) &&\n\t\tschedule.daysOfWeek.has(fields.dayOfWeek)\n\t);\n}\n\nfunction cronMinuteKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}-${fields.hour}-${fields.minute}`;\n}\n\nfunction cronDayKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}`;\n}\n\nfunction cronWallClockFields(date: Date, timezone?: string): CronWallClockFields {\n\tif (timezone === undefined) {\n\t\treturn {\n\t\t\tyear: date.getFullYear(),\n\t\t\tmonth: date.getMonth() + 1,\n\t\t\tday: date.getDate(),\n\t\t\thour: date.getHours(),\n\t\t\tminute: date.getMinutes(),\n\t\t\tdayOfWeek: date.getDay(),\n\t\t};\n\t}\n\tconst parts = timezoneFormatter(timezone).formatToParts(date);\n\tconst values: Record<string, number> = {};\n\tfor (const part of parts) {\n\t\tif (\n\t\t\tpart.type === \"year\" ||\n\t\t\tpart.type === \"month\" ||\n\t\t\tpart.type === \"day\" ||\n\t\t\tpart.type === \"hour\" ||\n\t\t\tpart.type === \"minute\"\n\t\t) {\n\t\t\tvalues[part.type] = Number.parseInt(part.value, 10);\n\t\t}\n\t}\n\tconst year = values.year;\n\tconst month = values.month;\n\tconst day = values.day;\n\tconst hour = values.hour;\n\tconst minute = values.minute;\n\tif (\n\t\tyear === undefined ||\n\t\tmonth === undefined ||\n\t\tday === undefined ||\n\t\thour === undefined ||\n\t\tminute === undefined\n\t) {\n\t\tthrow new Error(`fromCron: timezone projection failed for ${timezone}`);\n\t}\n\treturn {\n\t\tyear,\n\t\tmonth,\n\t\tday,\n\t\thour,\n\t\tminute,\n\t\tdayOfWeek: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),\n\t};\n}\n\nconst TIMEZONE_FORMATTERS = new Map<string, Intl.DateTimeFormat>();\n\nfunction timezoneFormatter(timezone: string): Intl.DateTimeFormat {\n\tconst existing = TIMEZONE_FORMATTERS.get(timezone);\n\tif (existing !== undefined) return existing;\n\tassertNonEmptyString(timezone, \"fromCron: timezone\");\n\ttry {\n\t\tconst formatter = new Intl.DateTimeFormat(\"en-US-u-ca-gregory-nu-latn\", {\n\t\t\ttimeZone: timezone,\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\thourCycle: \"h23\",\n\t\t});\n\t\tformatter.format(new Date(0));\n\t\tTIMEZONE_FORMATTERS.set(timezone, formatter);\n\t\treturn formatter;\n\t} catch (error) {\n\t\tthrow new RangeError(\n\t\t\t`fromCron: unsupported IANA timezone '${timezone}' (${error instanceof Error ? error.message : String(error)})`,\n\t\t);\n\t}\n}\n\nfunction dateToTimestampNs(date: Date): string {\n\treturn (BigInt(date.getTime()) * 1_000_000n).toString();\n}\n\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"date\" },\n): Operator<never, Date>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"timestamp_ms\" },\n): Operator<never, number>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions & { output?: \"timestamp_ns\" },\n): Operator<never, string>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions,\n): Operator<never, Date | number | string>;\n/**\n * Emit wall-clock cron ticks on a graph source.\n *\n * @param expr - Five-field cron expression.\n * @param opts - Cron polling, timezone, DST, abort, and output-shape options.\n * @returns A source operator that emits the current time when the schedule matches.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromCron } from \"@graphrefly/ts/sources\";\n *\n * const everyMinute = graph().initNode(fromCron(\"0 * * * *\"), []);\n * ```\n * @category sources\n */\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions = {},\n): Operator<never, Date | number | string> {\n\tconst schedule = parseCron(expr);\n\tconst { tickMs = 60_000, output = \"timestamp_ns\", signal, timezone } = opts;\n\tif (opts.dst?.nonexistent !== undefined && opts.dst.nonexistent !== \"skip\") {\n\t\tthrow new RangeError(\"fromCron: dst.nonexistent currently supports only 'skip'\");\n\t}\n\tif (opts.dst?.repeated !== undefined && opts.dst.repeated !== \"once\") {\n\t\tthrow new RangeError(\"fromCron: dst.repeated currently supports only 'once'\");\n\t}\n\tif (timezone !== undefined) timezoneFormatter(timezone);\n\tif (!Number.isFinite(tickMs) || tickMs <= 0) {\n\t\tthrow new RangeError(\"fromCron: tickMs must be a positive finite number\");\n\t}\n\treturn source<Date | number | string>(\n\t\t\"fromCron\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet lastFiredKey: string | undefined;\n\t\t\tlet firedTimezoneDay: string | undefined;\n\t\t\tconst firedTimezoneMinutes = new Set<string>();\n\t\t\tlet intervalId: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (intervalId !== undefined) clearInterval(intervalId);\n\t\t\t\tintervalId = undefined;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst emitNow = (now: Date) => {\n\t\t\t\tif (output === \"date\") ctx.down([[\"DATA\", now]]);\n\t\t\t\telse if (output === \"timestamp_ms\") ctx.down([[\"DATA\", now.getTime()]]);\n\t\t\t\telse ctx.down([[\"DATA\", dateToTimestampNs(now)]]);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key = cronMinuteKey(now, timezone);\n\t\t\t\tconst alreadyFired =\n\t\t\t\t\ttimezone === undefined ? key === lastFiredKey : firedTimezoneMinutes.has(key);\n\t\t\t\tif (!alreadyFired && matchesCron(schedule, now, { timezone })) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\tif (timezone !== undefined) {\n\t\t\t\t\t\tconst dayKey = cronDayKey(now, timezone);\n\t\t\t\t\t\tif (dayKey !== firedTimezoneDay) {\n\t\t\t\t\t\t\tfiredTimezoneDay = dayKey;\n\t\t\t\t\t\t\tfiredTimezoneMinutes.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfiredTimezoneMinutes.add(key);\n\t\t\t\t\t}\n\t\t\t\t\temitNow(now);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn cleanup;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tcheck();\n\t\t\tintervalId = setInterval(check, tickMs);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n}\n\n/**\n * Run a command and emit its process result once.\n *\n * @param program - Executable name or path.\n * @param args - Command-line arguments.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * runProcess(\"git\", [\"status\"]);\n * ```\n * @category sources\n */\nexport function runProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn runProcessWithOptions({ program, args });\n}\n\n/**\n * Emit a process result with the `fromProcess` source factory.\n *\n * @param program - Executable name or path.\n * @param args - Command-line arguments.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * fromProcess(\"git\", [\"status\"]);\n * ```\n * @category sources\n */\nexport function fromProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn processSource(\"fromProcess\", { program, args });\n}\n\n/**\n * Run a caller-supplied process command through the graph environment driver.\n *\n * @param command - Process command object consumed by the graph-local process driver.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * import { runProcessWithOptions } from \"@graphrefly/ts\";\n * import { graph } from \"@graphrefly/ts/graph\";\n *\n * const status = graph().initNode(runProcessWithOptions({ program: \"git\", args: [\"status\"] }), []);\n * ```\n * @category sources\n */\nexport function runProcessWithOptions(command: ProcessCommand): Operator<never, ProcessResult> {\n\treturn processSource(\"runProcess\", command);\n}\n\nfunction processSource(factory: string, command: ProcessCommand): Operator<never, ProcessResult> {\n\tassertNonEmptyString(command.program, `${factory}: program`);\n\treturn driverOneShotSource<ProcessResult>(\n\t\tfactory,\n\t\t`${factory}: missing process driver`,\n\t\t(ctx, callback) => ctx.environment().processDriver()?.run(command, callback),\n\t);\n}\n\n/**\n * Emit a single HTTP response for a GET request.\n *\n * @param url - Request URL.\n * @returns A source operator that emits one `HttpResponse`.\n * @example\n * ```ts\n * fromHttp(\"https://example.com\");\n * ```\n * @category sources\n */\nexport function fromHttp(url: string): Operator<never, HttpResponse> {\n\treturn fromHttpWithOptions({ method: \"GET\", url });\n}\n\n/**\n * Emit a single HTTP response using a caller-supplied request object.\n *\n * @param request - HTTP request to dispatch.\n * @returns A source operator that emits one `HttpResponse`.\n * @example\n * ```ts\n * fromHttpWithOptions({ method: \"GET\", url: \"https://example.com\" });\n * ```\n * @category sources\n */\nexport function fromHttpWithOptions(request: HttpRequest): Operator<never, HttpResponse> {\n\tassertNonEmptyString(request.url, \"fromHttp: url\");\n\tassertNonEmptyString(request.method, \"fromHttp: method\");\n\treturn driverOneShotSource<HttpResponse>(\n\t\t\"fromHttp\",\n\t\t\"fromHttp: missing http driver\",\n\t\t(ctx, callback) => ctx.environment().httpDriver()?.request(request, callback),\n\t);\n}\n\n/**\n * Emit server-sent events from a URL.\n *\n * @param url - SSE endpoint URL.\n * @returns A source operator that emits each SSE event.\n * @example\n * ```ts\n * fromSSE(\"https://example.com/events\");\n * ```\n * @category sources\n */\nexport function fromSSE(url: string): Operator<never, SseEvent> {\n\treturn fromSSEWithOptions({ url });\n}\n\n/**\n * Emit server-sent events using a caller-supplied request object.\n *\n * @param request - SSE request details.\n * @returns A source operator that emits each SSE event.\n * @example\n * ```ts\n * fromSSEWithOptions({ url: \"https://example.com/events\" });\n * ```\n * @category sources\n */\nexport function fromSSEWithOptions(request: SseRequest): Operator<never, SseEvent> {\n\tassertNonEmptyString(request.url, \"fromSSE: url\");\n\treturn driverStreamSource<SseEvent, SseDriverEvent>(\n\t\t\"fromSSE\",\n\t\t\"fromSSE: missing sse driver\",\n\t\t(ctx, callback) => ctx.environment().sseDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\n/**\n * Emit WebSocket events from a URL.\n *\n * @param url - WebSocket endpoint URL.\n * @returns A source operator that emits connection, message, and close events.\n * @example\n * ```ts\n * fromWebSocket(\"wss://example.com/socket\");\n * ```\n * @category sources\n */\nexport function fromWebSocket(url: string): Operator<never, WebSocketEvent> {\n\treturn fromWebSocketWithOptions({ url });\n}\n\n/**\n * Emit WebSocket events using a caller-supplied request object.\n *\n * @param request - WebSocket request details.\n * @returns A source operator that emits connection, message, and close events.\n * @example\n * ```ts\n * fromWebSocketWithOptions({ url: \"wss://example.com/socket\" });\n * ```\n * @category sources\n */\nexport function fromWebSocketWithOptions(\n\trequest: WebSocketRequest,\n): Operator<never, WebSocketEvent> {\n\tassertNonEmptyString(request.url, \"fromWebSocket: url\");\n\treturn driverStreamSource<WebSocketEvent, WebSocketDriverEvent>(\n\t\t\"fromWebSocket\",\n\t\t\"fromWebSocket: missing websocket driver\",\n\t\t(ctx, callback) => ctx.environment().webSocketDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\n/**\n * Emit webhook delivery events for a registration id.\n *\n * @param id - Webhook registration id.\n * @returns A source operator that emits each webhook delivery event.\n * @example\n * ```ts\n * fromWebhook(\"ingest-events\");\n * ```\n * @category sources\n */\nexport function fromWebhook(id: string): Operator<never, WebhookEvent> {\n\treturn fromWebhookWithOptions({ id });\n}\n\n/**\n * Emit webhook delivery events using a caller-supplied registration object.\n *\n * @param registration - Webhook registration details.\n * @returns A source operator that emits each webhook delivery event.\n * @example\n * ```ts\n * fromWebhookWithOptions({ id: \"ingest-events\", method: \"POST\" });\n * ```\n * @category sources\n */\nexport function fromWebhookWithOptions(\n\tregistration: WebhookRegistration,\n): Operator<never, WebhookEvent> {\n\tassertNonEmptyString(registration.id, \"fromWebhook: id\");\n\treturn driverStreamSource<WebhookEvent, WebhookDriverEvent>(\n\t\t\"fromWebhook\",\n\t\t\"fromWebhook: missing webhook driver\",\n\t\t(ctx, callback) => ctx.environment().webhookDriver()?.register(registration, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nfunction timerSource(factory: string, ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\tconst { period, signal } = opts ?? {};\n\tconst op = source<number>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet count = 0;\n\t\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst finish = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tif (period != null) {\n\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\t\tif (done) return;\n\t\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\t}, period);\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot: DATA then COMPLETE in one wave (terminal-is-forever).\n\t\t\t\t\tdone = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", count++], [\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tt = setTimeout(finish, ms);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n\tif (factory === \"timer\" && period === undefined && signal === undefined) {\n\t\treturn { ...op, restore: { ref: \"timer\", config: { ms: toCheckpointJson(ms, \"timer.ms\") } } };\n\t}\n\treturn op;\n}\n\n/**\n * Timer source: one-shot (first tick then COMPLETE) or periodic (`{period}` → 0, 1, 2, …).\n * sync pool + pausable:false (a timer keeps producing through PAUSE, R-pause-modes). Emits the\n * tick counter from 0; deactivation clears the timers.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { timer } from \"@graphrefly/ts/sources\";\n *\n * const tick = graph().initNode(timer(100), []);\n * ```\n * @category sources\n */\nexport function timer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"timer\", ms, opts);\n}\n\n/**\n * Create a timer source with the `fromTimer` source factory.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromTimer } from \"@graphrefly/ts/sources\";\n *\n * const tick = graph().initNode(fromTimer(100), []);\n * ```\n * @remarks **Factory name:** This preserves the real `fromTimer` factory name in `describe()`.\n * @category sources\n */\nexport function fromTimer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"fromTimer\", ms, opts);\n}\n\n/**\n * Emit periodic tick counters.\n *\n * @param ms - Delay before the first tick and between later ticks in milliseconds.\n * @returns A source operator that emits `0`, `1`, `2`, and so on.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { interval } from \"@graphrefly/ts/sources\";\n *\n * const ticks = graph().initNode(interval(1000), []);\n * ```\n * @category sources\n */\nexport function interval(ms: number): Operator<never, number> {\n\treturn timerSource(\"interval\", ms, { period: ms });\n}\n\n/**\n * Lift a Promise (or thenable) to a single-value stream: one DATA then COMPLETE, or ERROR on\n * rejection. async pool (default pausable → a paused source buffers its late emit). Optional\n * `signal` aborts to ERROR.\n *\n * @param p - Promise or thenable to lift into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits one DATA value and COMPLETE, or ERROR on rejection/abort.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromPromise } from \"@graphrefly/ts/sources\";\n *\n * const user = graph().initNode(fromPromise(fetch(\"/user\").then((res) => res.json())), []);\n * ```\n * @category sources\n */\nexport function fromPromise<T>(\n\tp: Promise<T> | PromiseLike<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst signal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromPromise\",\n\t\t(ctx) => {\n\t\t\tlet settled = false;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\t// onAbort only runs from a `signal` listener / the `signal.aborted` guard → signal is defined.\n\t\t\t\tctx.down([[\"ERROR\", errorPayload((signal as AbortSignal).reason)]]);\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid Promise.resolve(p).then(\n\t\t\t\t(v) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * Read an async iterable: each value → DATA; COMPLETE when done; ERROR on failure. async pool.\n * Optional `signal` aborts the pump.\n *\n * @param iterable - Async iterable to pump into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromAsyncIter } from \"@graphrefly/ts/sources\";\n *\n * const stream = graph().initNode(fromAsyncIter(events()), []);\n * ```\n * @category sources\n */\nexport function fromAsyncIter<T>(\n\titerable: AsyncIterable<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst outerSignal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromAsyncIter\",\n\t\t(ctx) => {\n\t\t\tconst ac = new AbortController();\n\t\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet done = false;\n\t\t\tconst pump = async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const v of iterable) {\n\t\t\t\t\t\tif (ac.signal.aborted) break;\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"COMPLETE\"]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t} finally {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tvoid pump();\n\t\t\treturn () => {\n\t\t\t\tif (!done) ac.abort();\n\t\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * of: synchronous values — each argument as DATA, then COMPLETE. `of()` is the EMPTY source.\n *\n * @param values - Values to emit synchronously on activation.\n * @returns A source operator that emits each value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { of } from \"@graphrefly/ts/sources\";\n *\n * const values = graph().initNode(of(1, 2, 3), []);\n * ```\n * @category sources\n */\nexport function of<T = never>(...values: T[]): Operator<never, T> {\n\treturn source<T>(\n\t\t\"of\",\n\t\t(ctx) => {\n\t\t\tfor (const value of values) ctx.down([[\"DATA\", value]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Emit every value from a synchronous iterable.\n *\n * @param iterable - Iterable whose values are emitted in order.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromIter } from \"@graphrefly/ts/sources\";\n *\n * const values = graph().initNode(fromIter([1, 2, 3]), []);\n * ```\n * @category sources\n */\nexport function fromIter<T>(iterable: Iterable<T>): Operator<never, T> {\n\treturn source<T>(\n\t\t\"fromIter\",\n\t\t(ctx) => {\n\t\t\tfor (const v of iterable) ctx.down([[\"DATA\", v]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Complete immediately without emitting DATA.\n *\n * @returns A source operator that emits COMPLETE on activation.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { empty } from \"@graphrefly/ts/sources\";\n *\n * const done = graph().initNode(empty(), []);\n * ```\n * @category sources\n */\nexport function empty<T = never>(): Operator<never, T> {\n\treturn source<T>(\n\t\t\"empty\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Activate and remain silent until deactivation.\n *\n * @returns A source operator that never emits DATA or terminal messages by itself.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { never } from \"@graphrefly/ts/sources\";\n *\n * const quiet = graph().initNode(never(), []);\n * ```\n * @category sources\n */\nexport function never<T = never>(): Operator<never, T> {\n\treturn source<T>(\"never\", () => undefined, { pool: \"sync\" });\n}\n\n/**\n * Terminate with ERROR on activation.\n *\n * @param err - Host-language error payload to normalize into a protocol ERROR payload.\n * @returns A source operator that emits ERROR.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { throwError } from \"@graphrefly/ts/sources\";\n *\n * const failed = graph().initNode(throwError(new Error(\"boom\")), []);\n * ```\n * @category sources\n */\nexport function throwError(err: unknown): Operator<never, never> {\n\treturn source<never>(\n\t\t\"throwError\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"ERROR\", errorPayload(err)]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a DOM-style event target. Each event becomes DATA; deactivation removes the listener.\n * External callbacks are source boundaries (D43), so no polling or operator-level async leaks in.\n *\n * @param target - Event target implementing `addEventListener` and `removeEventListener`.\n * @param type - Event type to subscribe to.\n * @param opts - Optional listener options and source options.\n * @returns A source operator that emits each event as DATA.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromEvent } from \"@graphrefly/ts/sources\";\n *\n * const clicks = graph().initNode(fromEvent<MouseEvent>(button, \"click\"), []);\n * ```\n * @category sources\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts: FromEventOptions = {},\n): Operator<never, T> {\n\tif (target == null || typeof target.addEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement addEventListener\");\n\t}\n\tif (typeof target.removeEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement removeEventListener\");\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new TypeError(\"fromEvent: event type must be a non-empty string\");\n\t}\n\treturn source<T>(\n\t\t\"fromEvent\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst handler = (event: unknown) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", event as T]]);\n\t\t\t};\n\t\t\ttarget.addEventListener(type, handler, opts);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\ttarget.removeEventListener(type, handler, opts);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a host push transport. The host owns network/native setup; this factory owns reactive\n * delivery and teardown only, preserving async-at-source-boundary discipline.\n * @param register - register value used by the helper.\n * @returns A Operator<never, T> value for the boundary or adapter.\n * @category sources\n * @example\n * ```ts\n * import { fromPushNotification } from \"@graphrefly/ts/sources\";\n * ```\n */\nexport function fromPushNotification<T = unknown>(register: PushRegister<T>): Operator<never, T> {\n\tif (typeof register !== \"function\") {\n\t\tthrow new TypeError(\"fromPushNotification: register must be a function\");\n\t}\n\treturn source<T>(\n\t\t\"fromPushNotification\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst deliver = (payload: T) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", payload]]);\n\t\t\t};\n\t\t\tconst unsubscribe = register(deliver);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (typeof unsubscribe === \"function\") unsubscribe();\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Coerce a {@link NodeInput}`<T>` to a `Node<T>` (D43 — coercion prerequisite for the CSP-2.7\n * higher-order operators). An existing Node passes through; a thenable → {@link fromPromise};\n * an async iterable → {@link fromAsyncIter}; with `{iter:true}` a sync iterable →\n * {@link fromIter}; everything else → {@link of}. Coerced nodes are bare (use\n * `opts.dispatcher` to bind one, default = process-global D26).\n * @param input - Input value to project or validate.\n * @param opts - Options that configure the helper.\n * @returns A Node<T> value for the boundary or adapter.\n * @category sources\n * @example\n * ```ts\n * import { fromAny } from \"@graphrefly/ts/sources\";\n * ```\n */\nexport function fromAny<T>(\n\tinput: NodeInput<T>,\n\topts: NodeOptions<T> & { iter?: boolean } = {},\n): Node<T> {\n\tif (isNode(input)) return input as Node<T>;\n\tconst { iter, ...nodeOpts } = opts;\n\tif (isThenable(input)) {\n\t\treturn initNode(fromPromise(input as PromiseLike<T>), [], nodeOpts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as {\n\t\t\t[Symbol.asyncIterator]?: unknown;\n\t\t\t[Symbol.iterator]?: unknown;\n\t\t};\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn initNode(fromAsyncIter(input as AsyncIterable<T>), [], nodeOpts);\n\t\t}\n\t\tif (iter === true && typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn initNode(fromIter(input as Iterable<T>), [], nodeOpts);\n\t\t}\n\t}\n\treturn initNode(of(input as T), [], nodeOpts);\n}\n\n/**\n * Resolve the first DATA from a Node as a Promise.\n *\n * @param source - Node to subscribe to.\n * @returns A Promise for the first DATA value, or a rejection on ERROR/early completion.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { firstValueFrom } from \"@graphrefly/ts/sources\";\n *\n * const g = graph();\n * await firstValueFrom(g.state(1));\n * ```\n * @remarks Host-boundary escape hatch only. Do not call it from reactive node bodies; use graph\n * deps/messages there so the topology remains declarative and inspectable.\n * @category sources\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet shouldUnsub = false;\n\t\tlet unsub: (() => void) | undefined;\n\t\tconst finish = (f: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tf();\n\t\t\tif (unsub) {\n\t\t\t\tunsub();\n\t\t\t\tunsub = undefined;\n\t\t\t} else {\n\t\t\t\tshouldUnsub = true;\n\t\t\t}\n\t\t};\n\t\tunsub = source.subscribe((msg) => {\n\t\t\tif (msg[0] === \"DATA\") {\n\t\t\t\tfinish(() => resolve(msg[1] as T));\n\t\t\t} else if (msg[0] === \"ERROR\") {\n\t\t\t\tfinish(() => reject(msg[1]));\n\t\t\t} else if (msg[0] === \"COMPLETE\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: completed without DATA\")));\n\t\t\t} else if (msg[0] === \"TEARDOWN\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: torn down without DATA\")));\n\t\t\t}\n\t\t});\n\t\tif (shouldUnsub) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t}\n\t});\n}\n\nfunction singleFromAnyValue<T>(value: T): T {\n\tif (value === undefined) {\n\t\tthrow new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\");\n\t}\n\treturn value;\n}\n\nasync function firstFromAsyncIterable<T>(input: AsyncIterable<T>): Promise<T> {\n\tconst iter = input[Symbol.asyncIterator]();\n\tconst { value, done } = await iter.next();\n\tif (done) {\n\t\tawait iter.return?.();\n\t\tthrow new Error(\"singleFromAny: factory returned empty async iterable\");\n\t}\n\ttry {\n\t\tawait iter.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn value as T;\n}\n\nfunction firstFromIterable<T>(input: Iterable<T>): Promise<T> {\n\tconst iter = input[Symbol.iterator]();\n\tconst { value, done } = iter.next();\n\tif (done) {\n\t\titer.return?.();\n\t\treturn Promise.reject(new Error(\"singleFromAny: factory returned empty iterable\"));\n\t}\n\ttry {\n\t\titer.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn Promise.resolve(value as T);\n}\n\nfunction nodeInputToPromise<T>(input: NodeInput<T>, opts: { iter?: boolean }): Promise<T> {\n\tif (isThenable(input)) return Promise.resolve(input as PromiseLike<T>).then(singleFromAnyValue);\n\tif (isNode(input)) return firstValueFrom(input as Node<T>).then(singleFromAnyValue);\n\tif (isAsyncIterable<T>(input)) return firstFromAsyncIterable(input).then(singleFromAnyValue);\n\tif (opts.iter === true && isIterable<T>(input)) {\n\t\treturn firstFromIterable(input).then(singleFromAnyValue);\n\t}\n\tif (input === undefined) {\n\t\treturn Promise.reject(new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\"));\n\t}\n\treturn Promise.resolve(singleFromAnyValue(input as T));\n}\n\n/**\n * Keyed singleflight over {@link NodeInput}.\n *\n * @param factory - Function that produces a value, iterable, promise, or node for each key.\n * @param opts - Optional key canonicalizer and iterable handling.\n * @returns A memoizing loader keyed by the transformed key.\n * @example\n * ```ts\n * const loadUser = singleFromAny((id: string) => fetch(`/api/users/${id}`).then((r) => r.json()));\n * ```\n * @remarks Host-boundary helper only. It deduplicates external calls and does not create graph\n * topology or act as a graph operator.\n * @category sources\n */\nexport function singleFromAny<K, T>(\n\tfactory: (key: K) => NodeInput<T>,\n\topts: SingleFromAnyOptions<K> = {},\n): (key: K) => Promise<T> {\n\tconst keyOf = opts.keyOf ?? ((key: K): unknown => key);\n\tconst inFlight = new Map<unknown, Promise<T>>();\n\n\treturn (key: K): Promise<T> => {\n\t\tconst dedupeKey = keyOf(key);\n\t\tconst existing = inFlight.get(dedupeKey);\n\t\tif (existing) return existing;\n\n\t\tlet resolvePending!: (value: T) => void;\n\t\tlet rejectPending!: (reason: unknown) => void;\n\t\tlet tracked!: Promise<T>;\n\t\tconst cleanup = (): void => {\n\t\t\tif (inFlight.get(dedupeKey) === tracked) inFlight.delete(dedupeKey);\n\t\t};\n\t\tconst pending = new Promise<T>((resolve, reject) => {\n\t\t\tresolvePending = resolve;\n\t\t\trejectPending = reject;\n\t\t});\n\t\ttracked = pending.then(\n\t\t\t(value) => {\n\t\t\t\tcleanup();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tcleanup();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tinFlight.set(dedupeKey, tracked);\n\t\ttry {\n\t\t\tnodeInputToPromise(factory(key), opts).then(resolvePending, rejectPending);\n\t\t} catch (e) {\n\t\t\trejectPending(e);\n\t\t}\n\t\treturn tracked;\n\t};\n}\n"],"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;;;AC2CO,IAAM,WAAW;AAWjB,SAAS,sBAAsB,GAAqB;AAC1D,SAAO,MAAM,YAAY,OAAO,MAAM;AACvC;AAYO,SAAS,aAAa,QAAiB,WAAW,iCAA0C;AAClG,SAAO,sBA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AK,kBAAkB;AAC3F,MAAI,KAAK,SAAS,QAAQ,WAAc,KAAK,GAAG;AAC/C,WAAO,kBAAkB,KAAK,EAAE,KAAK,kBAAkB;AAAA,EACxD;AACA,MAAI,UAAU,QAAW;AACxB,WAAO,QAAQ,OAAO,IAAI,UAAU,oDAAoD,CAAC;AAAA,EAC1F;AACA,SAAO,QAAQ,QAAQ,mBAAmB,KAAU,CAAC;AACtD;AAgBO,SAAS,cACf,SACA,OAAgC,CAAC,GACR;AACzB,QAAM,QAAQ,KAAK,UAAU,CAAC,QAAoB;AAClD,QAAM,WAAW,oBAAI,IAAyB;AAE9C,SAAO,CAAC,QAAuB;AAC9B,UAAM,YAAY,MAAM,GAAG;AAC3B,UAAM,WAAW,SAAS,IAAI,SAAS;AACvC,QAAI,SAAU,QAAO;AAErB,QAAI;AACJ,QAAI;AACJ,QAAI;AACJ,UAAM,UAAU,MAAY;AAC3B,UAAI,SAAS,IAAI,SAAS,MAAM,QAAS,UAAS,OAAO,SAAS;AAAA,IACnE;AACA,UAAM,UAAU,IAAI,QAAW,CAAC,SAAS,WAAW;AACnD,uBAAiB;AACjB,sBAAgB;AAAA,IACjB,CAAC;AACD,cAAU,QAAQ;AAAA,MACjB,CAAC,UAAU;AACV,gBAAQ;AACR,eAAO;AAAA,MACR;AAAA,MACA,CAAC,UAAU;AACV,gBAAQ;AACR,cAAM;AAAA,MACP;AAAA,IACD;AACA,aAAS,IAAI,WAAW,OAAO;AAC/B,QAAI;AACH,yBAAmB,QAAQ,GAAG,GAAG,IAAI,EAAE,KAAK,gBAAgB,aAAa;AAAA,IAC1E,SAAS,GAAG;AACX,oBAAc,CAAC;AAAA,IAChB;AACA,WAAO;AAAA,EACR;AACD;","names":["out","errors","active","source"]}
1
+ {"version":3,"sources":["../../src/sources/index.ts","../../src/protocol/messages.ts","../../src/json/codec.ts","../../src/graph/checkpoint.ts","../../src/ctx/types.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/graph/operators.ts","../../src/graph/sources.ts"],"sourcesContent":["export type {\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"../graph/environment.js\";\nexport {\n\ttype AsyncSourceOpts,\n\ttype CronSchedule,\n\ttype EventListenerOptionsLike,\n\ttype EventTargetLike,\n\tempty,\n\ttype FromCronOptions,\n\ttype FromEventOptions,\n\tfirstValueFrom,\n\tfromAny,\n\tfromAsyncIter,\n\tfromCron,\n\tfromEvent,\n\tfromHttp,\n\tfromHttpWithOptions,\n\tfromIter,\n\tfromPromise,\n\tfromPushNotification,\n\tfromSSE,\n\tfromSSEWithOptions,\n\tfromTimer,\n\tfromWebhook,\n\tfromWebhookWithOptions,\n\tfromWebSocket,\n\tfromWebSocketWithOptions,\n\tinterval,\n\tmatchesCron,\n\ttype NodeInput,\n\tnever,\n\tof,\n\ttype PushRegister,\n\ttype PushUnsubscribe,\n\tparseCron,\n\ttype SingleFromAnyOptions,\n\tsingleFromAny,\n\ttype TimerSourceOpts,\n\tthrowError,\n\ttimer,\n} from \"../graph/sources.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.\n * @param v - v value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isInvalidErrorPayload } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param reason - reason value used by the helper.\n * @param fallback - fallback value used by the helper.\n * @returns The error payload result.\n * @category core\n * @example\n * ```ts\n * import { errorPayload } from \"@graphrefly/ts/core\";\n * ```\n */\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\n/**\n * Look up the tier number for a message type.\n *\n * @param t - One of the closed-set protocol message tags.\n * @returns The tier assigned by the compile-time tier table.\n * @example\n * ```ts\n * messageTier(\"DATA\"); // 3\n * ```\n * @category core\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).\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isDeferredTier } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isValueTier } from \"@graphrefly/ts/core\";\n * ```\n */\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.\n * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isPauseBufferedTier } from \"@graphrefly/ts/core\";\n * ```\n */\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 * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isTerminal } from \"@graphrefly/ts/core\";\n * ```\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 * @param t - t value used by the helper.\n * @returns `true` when the value matches the expected shape.\n * @category core\n * @example\n * ```ts\n * import { isUpAllowed } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\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 deepFreezeStrictJson<T extends StrictJsonValue>(value: T): T {\n\tif (value !== null && typeof value === \"object\") {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) deepFreezeStrictJson(item);\n\t\t} else {\n\t\t\tfor (const item of Object.values(value)) deepFreezeStrictJson(item);\n\t\t}\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\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.\n * @param value - Unknown value to check or decode.\n * @returns A `string` value.\n * @category json\n * @example\n * ```ts\n * import { stableJsonString } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(cloneStrictJsonValue(value));\n}\n\n/** Build a JSON codec using stable object-key ordering.\n * @returns A `Codec<T>` value.\n * @category json\n * @example\n * ```ts\n * import { jsonCodecFor } from \"@graphrefly/ts/storage\";\n * ```\n */\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\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n\t\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\t\tassertNoUnpairedSurrogates(descriptor.value, 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\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\tassertNoUnpairedSurrogates(descriptor.value, seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction strictJsonDataErrorsInner(\n\tvalue: unknown,\n\tlabel: string,\n\tseen: Set<object>,\n): { readonly errors: readonly string[]; readonly value?: StrictJsonValue } {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n\t\tif (typeof value === \"string\" && hasUnpairedSurrogate(value)) {\n\t\t\treturn { errors: [`${label} must not contain unpaired surrogate strings`] };\n\t\t}\n\t\treturn { errors: [], value };\n\t}\n\tif (typeof value === \"number\") {\n\t\ttry {\n\t\t\tassertStrictJsonNumber(value, label);\n\t\t} catch (error) {\n\t\t\treturn { errors: [error instanceof Error ? error.message : String(error)] };\n\t\t}\n\t\treturn { errors: [], value };\n\t}\n\tif (typeof value !== \"object\") {\n\t\treturn { errors: [`${label} is not JSON-encodable`] };\n\t}\n\tif (seen.has(value)) return { errors: [`${label} must not contain circular references`] };\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\treturn { errors: [`stableJsonString: non-plain object at ${label}`] };\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst errors: string[] = [];\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\terrors.push(`${label} must not carry symbol keys`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\t\tif (descriptor === undefined) continue;\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 (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\t\terrors.push(`${label}.${key} must be a data property`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\terrors.push(`${label}.${key} must be an indexed data property`);\n\t\t\t\t}\n\t\t\t\tif (key !== \"length\" && isIndex && !descriptor.enumerable) {\n\t\t\t\t\terrors.push(`${label}.${key} must be enumerable`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: StrictJsonValue[] = [];\n\t\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, String(index));\n\t\t\t\tif (descriptor === undefined) {\n\t\t\t\t\terrors.push(`stableJsonString: sparse array hole at ${label}[${index}]`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\t\terrors.push(`${label}[${index}] must be a data property`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!descriptor.enumerable) {\n\t\t\t\t\terrors.push(`${label}[${index}] must be enumerable`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst nested = strictJsonDataErrorsInner(descriptor.value, `${label}[${index}]`, seen);\n\t\t\t\terrors.push(...nested.errors);\n\t\t\t\tif (nested.errors.length === 0 && nested.value !== undefined) out.push(nested.value);\n\t\t\t}\n\t\t\tif (errors.length > 0) return { errors };\n\t\t\treturn { errors: [], value: Object.freeze(out) };\n\t\t}\n\t\tconst errors: string[] = [];\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\terrors.push(`${label} must not carry symbol keys`);\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) continue;\n\t\t\tif (\"get\" in descriptor || \"set\" in descriptor) {\n\t\t\t\terrors.push(`${label}.${key} must be a data property`);\n\t\t\t}\n\t\t\tif (!descriptor.enumerable) {\n\t\t\t\terrors.push(`${label}.${key} must be enumerable`);\n\t\t\t}\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\terrors.push(`${label}.${key} must not contain unpaired surrogate keys`);\n\t\t\t}\n\t\t}\n\t\tconst out: Record<string, StrictJsonValue> = {};\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\tif (descriptor === undefined || \"get\" in descriptor || \"set\" in descriptor) continue;\n\t\t\tconst nested = strictJsonDataErrorsInner(descriptor.value, `${label}.${key}`, seen);\n\t\t\terrors.push(...nested.errors);\n\t\t\tif (nested.errors.length === 0 && nested.value !== undefined) {\n\t\t\t\tObject.defineProperty(out, key, {\n\t\t\t\t\tvalue: nested.value,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (errors.length > 0) return { errors };\n\t\treturn { errors: [], value: Object.freeze(out) };\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Descriptor-safe strict JSON validation errors.\n *\n * The scanner checks property descriptors before reading values, so accessor-backed\n * host objects are rejected without executing getters. It is shared by D585\n * passive store frames and metadata validators that must accept only ordinary DATA.\n * @param value - Unknown value to validate.\n * @param label - Human-readable label for returned issue paths.\n * @returns Validation errors; empty means the value can be cloned as strict JSON.\n * @category json\n */\nexport function strictJsonDataErrors(value: unknown, label = \"strictJsonValue\"): readonly string[] {\n\ttry {\n\t\treturn strictJsonDataErrorsInner(value, label, new Set<object>()).errors;\n\t} catch (error) {\n\t\treturn [error instanceof Error ? error.message : String(error)];\n\t}\n}\n\n/** Clone a host value into deep-frozen strict canonical JSON DATA.\n *\n * The clone is descriptor-safe: accessors, sparse arrays, symbols, non-enumerable\n * fields, circular references, and non-portable JSON numbers are rejected before\n * values are read through normal property access.\n * @param value - Unknown value to clone.\n * @param label - Human-readable label for errors.\n * @returns A deep-frozen strict JSON value with deterministically sorted object keys.\n * @category json\n */\nexport function cloneStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\tconst result = strictJsonDataErrorsInner(value, label, new Set<object>());\n\tif (result.errors.length > 0 || result.value === undefined) {\n\t\tthrow new TypeError(`${label}: ${result.errors.join(\"; \")}`);\n\t}\n\treturn deepFreezeStrictJson(result.value);\n}\n\n/** Clone a host object into a deep-frozen strict canonical JSON object.\n * @param value - Unknown value to clone.\n * @param label - Human-readable label for errors.\n * @returns A deep-frozen strict JSON object.\n * @category json\n */\nexport function cloneStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst cloned = cloneStrictJsonValue(value, label);\n\tif (cloned === null || typeof cloned !== \"object\" || Array.isArray(cloned)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn cloned as StrictJsonObject;\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 * @returns A `Codec<T>` value.\n * @category json\n * @example\n * ```ts\n * import { strictJsonCodecFor } from \"@graphrefly/ts/storage\";\n * ```\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.\n * @param value - Unknown value to check or decode.\n * @returns A `Uint8Array` value.\n * @category json\n * @example\n * ```ts\n * import { strictCanonicalJsonBytes } from \"@graphrefly/ts\";\n * ```\n */\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.\n * @param value - Unknown value to check or decode.\n * @param label - label value used by the helper.\n * @returns The narrowed, validated value.\n * @category json\n * @example\n * ```ts\n * import { assertStrictJsonValue } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn cloneStrictJsonValue(value, label);\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.\n * @param value - Unknown value to check or decode.\n * @param label - label value used by the helper.\n * @returns The narrowed, validated value.\n * @category json\n * @example\n * ```ts\n * import { assertStrictJsonObject } from \"@graphrefly/ts/storage\";\n * ```\n */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\treturn cloneStrictJsonObject(value, label);\n}\n","/**\n * Graph checkpoint public data shape (D83/D86/D90/D116).\n *\n * Checkpoint is a graph lifecycle snapshot: strict-JSON-compatible data, no storage I/O,\n * no observe-log replay, and no restore runtime in this first TS slice.\n */\n\nimport { type StrictJsonValue, strictJsonCodec } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { NodeVersionJson } from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\n\nexport const GRAPH_CHECKPOINT_VERSION = \"graphrefly.checkpoint.v1\" as const;\n\nexport type GraphCheckpointVersion = typeof GRAPH_CHECKPOINT_VERSION;\n\nexport type GraphCheckpointJson = StrictJsonValue;\n\nexport type GraphCheckpointValue =\n\t| { kind: \"SENTINEL\" }\n\t| { kind: \"DATA\"; data: GraphCheckpointJson };\n\nexport type GraphCheckpointTerminal =\n\t| { kind: \"none\" }\n\t| { kind: \"COMPLETE\" }\n\t| { kind: \"ERROR\"; error: GraphCheckpointJson };\n\nexport type GraphCheckpointFactory =\n\t| {\n\t\t\tkind: \"registry-ref\";\n\t\t\tref: string;\n\t\t\tconfig?: GraphCheckpointJson;\n\t\t\tconfigVersion?: GraphCheckpointJson;\n\t }\n\t| { kind: \"local-only\"; name: string; reason: string };\n\nexport interface GraphCheckpointNode {\n\tid: string;\n\tname?: string;\n\tfactory: GraphCheckpointFactory;\n\tstatus: string;\n\tdeps: string[];\n\tvalue: GraphCheckpointValue;\n\tbackendState?: GraphCheckpointJson;\n\tversion?: NodeVersionJson;\n\tterminal: GraphCheckpointTerminal;\n\tlifecycle: { activated: boolean; hasCalledFnOnce: boolean };\n\tctxState: { persist: boolean; value: GraphCheckpointValue };\n\tmeta?: { [key: string]: GraphCheckpointJson };\n}\n\nexport interface GraphCheckpointEdge {\n\tfrom: string;\n\tto: string;\n}\n\nexport interface GraphCheckpointMount {\n\tat: string;\n\tcheckpoint: GraphCheckpoint;\n}\n\nexport interface GraphCheckpoint {\n\tversion: GraphCheckpointVersion;\n\tname?: string;\n\tnodes: GraphCheckpointNode[];\n\tedges: GraphCheckpointEdge[];\n\tmounts?: GraphCheckpointMount[];\n}\n\nexport function toCheckpointJson(value: unknown, path = \"$\"): GraphCheckpointJson {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as GraphCheckpointJson;\n\t} catch (cause) {\n\t\tthrow new TypeError(`checkpoint: value at ${path} is not strict JSON compatible`, {\n\t\t\tcause,\n\t\t});\n\t}\n}\n\nexport function checkpointValue(\n\tvalue: unknown,\n\thasData: boolean,\n\tpath: string,\n): GraphCheckpointValue {\n\tif (!hasData || value === SENTINEL) return { kind: \"SENTINEL\" };\n\treturn { kind: \"DATA\", data: toCheckpointJson(value, path) };\n}\n\nexport function checkpointTerminal(value: unknown, path: string): GraphCheckpointTerminal {\n\tif (value === undefined) return { kind: \"none\" };\n\tif (value === true) return { kind: \"COMPLETE\" };\n\treturn { kind: \"ERROR\", error: toCheckpointJson(value, path) };\n}\n\ntype BackendStateContributor = () => unknown;\n\nconst backendStateContributors = new WeakMap<Node<unknown>, BackendStateContributor>();\n\n/** @internal D160: collection-owned backend checkpoint contributor for graph checkpoint. */\nexport function registerBackendStateContributor(\n\tnode: Node<unknown>,\n\tcontributor: BackendStateContributor,\n): void {\n\tbackendStateContributors.set(node, contributor);\n}\n\n/** @internal D160: capture a node's collection backend state when it has a contributor. */\nexport function checkpointBackendStateOfNode(\n\tnode: Node<unknown>,\n\tpath: string,\n): GraphCheckpointJson | undefined {\n\tconst contributor = backendStateContributors.get(node);\n\tif (contributor === undefined) return undefined;\n\treturn toCheckpointJson(contributor(), path);\n}\n","/**\n * 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\nexport interface CtxDepWaveOrigin {\n\treadonly live: readonly (readonly boolean[])[];\n}\n\nconst ctxDepWaveOrigins = new WeakMap<Ctx, CtxDepWaveOrigin>();\n\n/** @internal Attach per-dep wave-origin state without exposing it on the public Ctx shape. */\nexport function setCtxDepWaveOrigin(ctx: Ctx, origin: CtxDepWaveOrigin): void {\n\tctxDepWaveOrigins.set(ctx, origin);\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\n/**\n * Check whether a terminal slot carries COMPLETE.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is the COMPLETE shorthand `true`.\n * @example\n * ```ts\n * isTerminalComplete(true); // true\n * ```\n * @category core\n */\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\n/**\n * Check whether a terminal slot carries ERROR payload data.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is neither none nor COMPLETE.\n * @example\n * ```ts\n * isTerminalError(new Error(\"boom\")); // true\n * ```\n * @category core\n */\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\n/**\n * Read the terminal payload when the slot is an ERROR value.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns The payload when `t` is an ERROR slot, otherwise `undefined`.\n * @example\n * ```ts\n * terminalErrorValue(new Error(\"boom\"));\n * ```\n * @category core\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.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @returns A `number` value.\n * @category core\n * @example\n * ```ts\n * import { depCount } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/**\n * Check whether a terminal slot carries no terminal state.\n *\n * @param t - Terminal slot value from {@link Ctx.terminal}.\n * @returns `true` when the slot is `false` or `undefined`.\n * @example\n * ```ts\n * isTerminalNone(false); // true\n * ```\n * @category core\n */\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns A `readonly (readonly unknown[])[]` value.\n * @category core\n * @example\n * ```ts\n * import { depWaves } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for event-counting operator bodies; null = no wave.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns A `readonly unknown[] | null` value.\n * @category core\n * @example\n * ```ts\n * import { depBatch } from \"@graphrefly/ts/core\";\n * ```\n */\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/** Internal adapter helper: dep waves produced by live graph-event deliveries only. */\nexport function depLiveWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\tconst waves = depWaves(ctx, depIndex);\n\tconst live = ctxDepWaveOrigins.get(ctx)?.live[depIndex] ?? [];\n\treturn waves.filter((_, index) => live[index]);\n}\n\n/** Internal adapter helper: flattened DATA values from live-delivered dep waves only. */\nexport function depLiveBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depLiveWaves(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/**\n * Read the most recent DATA value from one upstream dependency during a node run.\n *\n * `depIndex` is positional: `0` reads the first dependency in `node([first, ...])`, `1` reads the\n * second dependency, and so on. If that dependency has not produced DATA in the current graph\n * lifecycle, the value is `undefined`.\n *\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - Zero-based dependency position in the node's dependency list.\n * @returns The latest DATA value for that dependency, or `undefined` when no DATA is available yet.\n * @category core\n * @example\n * ```ts\n * import { depLatest, node } from \"@graphrefly/ts/core\";\n *\n * const count = node<number>([], null, { initial: 1 });\n * const doubled = node<number>([count], (ctx) => {\n * const latest = depLatest(ctx, 0);\n * if (latest === undefined) return;\n * ctx.down([[\"DATA\", Number(latest) * 2]]);\n * });\n * ```\n */\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.\n * @param ctx - Node execution context supplied by the dispatcher.\n * @param depIndex - dep index value used by the helper.\n * @returns The dep terminal result.\n * @category core\n * @example\n * ```ts\n * import { depTerminal } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated retired handle-dispatch PoC (R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/** 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 dispatcherHandleStatKey = (h: Handle): string =>\n\tJSON.stringify([String(h.poolId), String(h.handleId)]);\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 * @example\n * ```ts\n * import { Dispatcher } from \"@graphrefly/ts/core\";\n *\n * const dispatcher = new Dispatcher();\n * ```\n * @category core\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(dispatcherHandleStatKey(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(dispatcherHandleStatKey(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 = dispatcherHandleStatKey(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\n/**\n * Graph-local bundle of environment drivers.\n *\n * Instances are immutable snapshots of the process, HTTP, SSE, WebSocket, and webhook\n * driver set consumed by source/adapter bodies.\n *\n * @example\n * ```ts\n * import { EnvironmentDrivers, fetchHttpDriver } from \"@graphrefly/ts/graph\";\n *\n * const drivers = new EnvironmentDrivers().withHttp(fetchHttpDriver());\n * ```\n * @category graph\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\n/**\n * Adapt a Fetch-like function into a graph-local HTTP driver.\n *\n * @param fetchFn - Fetch implementation that returns a response-like object.\n * @returns A driver that performs one-shot HTTP requests and reports a single result.\n * @example\n * ```ts\n * import { fetchHttpDriver } from \"@graphrefly/ts/graph\";\n *\n * const http = fetchHttpDriver(fetch);\n * ```\n * @category graph\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\n/**\n * Adapt a DOM/WebSocket constructor into a graph-local WebSocket driver.\n *\n * @param WebSocketCtor - WebSocket constructor used to open connections.\n * @returns A driver that can connect, send, and optionally stream live sessions.\n * @example\n * ```ts\n * import { domWebSocketDriver } from \"@graphrefly/ts/graph\";\n *\n * const ws = domWebSocketDriver(WebSocket);\n * ```\n * @category graph\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\twaveLive: boolean[][];\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\twaveLive: Array.from({ length: depCount }, () => []),\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\tsetCtxDepWaveOrigin,\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\twaveLive: self._dep.waveLive.map((waves) => [...waves]),\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?: {\n\t\twaveData: unknown[][][];\n\t\twaveLive?: boolean[][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t},\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\tsetCtxDepWaveOrigin(ctx, { live: snapshot?.waveLive ?? self._dep.waveLive });\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\tsetCtxDepWaveOrigin(ctx, { live: self._dep.waveLive });\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.waveLive[idx].push(delivery !== undefined);\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.waveLive[i] = [];\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?: {\n\t\twaveData: unknown[][][];\n\t\twaveLive?: boolean[][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): 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.waveLive[idx] = [];\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.waveLive = [];\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.waveLive[i] = [];\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 } from \"@graphrefly/ts/core\";\n * import { graph } from \"@graphrefly/ts/graph\";\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 * @param bytes - Canonical bytes to decode.\n * @returns A `string` value.\n * @category core\n * @example\n * ```ts\n * import { defaultNodeVersionHash } from \"@graphrefly/ts/core\";\n * ```\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\ttype NodeVersion,\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._dep.waveLive = newDeps.map(() => []);\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/core\";\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\twaveLive?: boolean[][];\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/core\";\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 * @param deps - Declared dependency node or nodes.\n * @param fn - Synchronous function invoked by the helper.\n * @param opts - Options that configure the helper.\n * @returns A `Node<T>` value.\n * @category core\n * @example\n * ```ts\n * import { dynamicNode } from \"@graphrefly/ts/core\";\n * ```\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","/**\n * Operators as free-standing factory definitions (D43 / D6 / D40 Catalog-first).\n *\n * Operators are `node` sugar (D6), NOT verbs (D4) and NEVER in parity (D24). Each is a\n * pure {@link Operator} spec — `{factory, body, opts}` — built on the bare `node` primitive\n * (NOT the `derived` verb): `body` reads ctx dep slots positionally and emits via\n * `ctx.down`. Two ways to instantiate:\n *\n * - {@link initNode}(op, deps, opts?) — bare, no Graph; returns a working `Node<T>`.\n * - `g.initNode(op, deps, opts?)` — graph-bound; the SAME call, plus inspection registration\n * (the real factory name lands in the graph's `_entries`, so describe/observe/profile\n * show it — D6/R-describe — while the node stays thin, R-node-thin).\n *\n * The D30 throw→ERROR boundary lives once, in the free {@link initNode} (which `g.initNode`\n * funnels through). The pure-ts `operatorOpts/partialOperatorOpts/gatedOperatorOpts` trio is\n * NOT ported: its sole job (`describeKind:\"derived\"`) is dead under D6/D39 (factory = the\n * REAL operator name); only the `partial`/`terminalAsRealInput` flags survive, carried\n * per-operator in `op.opts`.\n *\n * Config is folded into the factory (`map(fn)`, `scan(reducer, seed)`, `take(n)`, `merge()`),\n * so fn params are annotated where the source type can't be inferred (RxJS-pipe cost);\n * dep-type safety is recovered by the typed `g.initNode` overloads.\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepLatest,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { NodeCore } from \"../node/core.js\";\nimport { Node, type NodeOptions, withNodeCore } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { type GraphCheckpointJson, toCheckpointJson } from \"./checkpoint.js\";\nimport type { GraphRestoreDefinition, GraphRestoreEntry, GraphRestoreRegistry } from \"./restore.js\";\n\n/**\n * A free-standing operator definition (D43). `TIn` = the element type each dep delivers\n * (the operator reads `depLatest(ctx, i) as TIn`); `TOut` = the emitted value type.\n * `__in`/`__out` are phantom-only (never assigned) — they let `g.initNode` infer + check the\n * dep tuple against the operator without an explicit type argument.\n */\nexport interface Operator<TIn = unknown, TOut = unknown> {\n\t/** Real operator name shown in describe (D6/L1.5) — recorded at `_add` by `g.initNode`. */\n\treadonly factory: string;\n\t/** The ctx-body: reads ctx dep slots positionally, emits via `ctx.down`. */\n\treadonly body: (ctx: Ctx) => void;\n\t/** Behavioral node options the operator needs (e.g. `partial:true` for combine-family). */\n\treadonly opts?: Partial<NodeOptions<TOut>>;\n\t/**\n\t * D97/D100 restore metadata derived from a named definition or static built-in config.\n\t * This is semantic metadata only; dispatcher handles stay graph-local runtime state.\n\t */\n\treadonly restore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t};\n\t/** @internal phantom — never set; carries the dep element type for `g.initNode` inference. */\n\treadonly __in?: TIn;\n\t/** @internal phantom — never set; carries the output value type. */\n\treadonly __out?: TOut;\n}\n\ntype MutableRestoreRegistry = Map<string, GraphRestoreEntry> | Record<string, GraphRestoreEntry>;\n\nexport type RestoreRegistryEntry = GraphRestoreEntry;\n\nexport interface Definition<S = unknown, T = unknown> extends GraphRestoreDefinition<S, T> {\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport interface DefineOpts {\n\tregistry?: MutableRestoreRegistry;\n}\n\nfunction registryHas(registry: MutableRestoreRegistry, ref: string): boolean {\n\treturn registry instanceof Map ? registry.has(ref) : Object.hasOwn(registry, ref);\n}\n\nfunction registrySet(\n\tregistry: MutableRestoreRegistry,\n\tref: string,\n\tentry: GraphRestoreEntry,\n): void {\n\tif (registryHas(registry, ref)) {\n\t\tthrow new Error(`restoreRegistry: duplicate ref '${ref}'`);\n\t}\n\tif (registry instanceof Map) registry.set(ref, entry);\n\telse registry[ref] = entry;\n}\n\nexport function addToRestoreRegistry(\n\tregistry: MutableRestoreRegistry,\n\tentry: GraphRestoreEntry,\n): void {\n\tregistrySet(registry, entry.ref, entry);\n}\n\n/**\n * Merge restore registry entries into a duplicate-checking Map.\n *\n * @param entries - Additional restore entries to add.\n * @param base - Optional base registry to copy from.\n * @returns A Map keyed by restore ref.\n * @example\n * ```ts\n * restoreRegistry([define(\"trim\", (value: string) => value.trim())]);\n * ```\n * @category operators\n */\nexport function restoreRegistry(\n\tentries: readonly GraphRestoreEntry[] = [],\n\tbase?: GraphRestoreRegistry,\n): Map<string, GraphRestoreEntry> {\n\tconst out = new Map<string, GraphRestoreEntry>();\n\tif (base instanceof Map) {\n\t\tfor (const [ref, entry] of base) registrySet(out, ref, entry);\n\t} else if (base !== undefined) {\n\t\tfor (const [ref, entry] of Object.entries(base)) registrySet(out, ref, entry);\n\t}\n\tfor (const entry of entries) addToRestoreRegistry(out, entry);\n\treturn out;\n}\n\nfunction isDefinition<S, T>(fn: ((v: S) => T) | Definition<S, T>): fn is Definition<S, T> {\n\treturn typeof fn === \"object\" && fn !== null && (fn as Definition<S, T>).kind === \"definition\";\n}\n\n/**\n * Register a named restore definition.\n *\n * @param ref - Stable restore reference name.\n * @param fn - Pure transform function used during restoration.\n * @param opts - Optional registry to receive the new definition.\n * @returns A named definition record.\n * @example\n * ```ts\n * define(\"trim\", (value: string) => value.trim());\n * ```\n * @category operators\n */\nexport function define<S, T>(\n\tref: string,\n\tfn: (v: S) => T,\n\topts: DefineOpts = {},\n): Definition<S, T> {\n\tconst jsonRef = toCheckpointJson(ref, \"define.ref\");\n\tif (typeof jsonRef !== \"string\") throw new TypeError(\"define: ref must be a string\");\n\tconst definition: Definition<S, T> = {\n\t\tkind: \"definition\",\n\t\tref: jsonRef,\n\t\tfn,\n\t};\n\tif (opts.registry !== undefined) addToRestoreRegistry(opts.registry, definition);\n\treturn definition;\n}\n\n/**\n * Instantiate an operator as a bare `Node<T>` — NO Graph required (D43 bare-node path).\n * Wraps `op.body` in the D30 value-throw→ERROR boundary; merges `op.opts` with caller `opts`\n * (caller wins, so `partial`/`pool`/`dispatcher` overrides take effect). The\n * dispatcher defaults to the process-global (D26) unless `opts.dispatcher` is passed.\n *\n * `g.initNode` is the same call PLUS graph registration; graph inspection\n * (describe/observe/profile) requires that path — a node built bare here is not registered in\n * any graph's index.\n * @param op - op value used by the helper.\n * @param deps - Declared dependency node or nodes.\n * @param opts - Options that configure the helper.\n * @returns A `Node<TOut>` value.\n * @category operators\n * @example\n * ```ts\n * import { initNode } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function initNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn makeInitNode(op, deps, opts);\n}\n\n/** @internal Graph-bound operator instantiation into a graph-local B49 core. */\nexport function initNodeWithCore<TIn, TOut>(\n\tcore: NodeCore,\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn withNodeCore(core, () => makeInitNode(op, deps, opts));\n}\n\nfunction makeInitNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut>,\n): Node<TOut> {\n\tconst body = operatorNodeFn(op);\n\t// D43-reserved / D51: stamp the operator's real factory onto the bare node so a runtime *Map\n\t// inner (created here via fromAny, NOT registered in any graph) is named in describe's\n\t// auto-discovery. A graph-bound g.initNode also records it in `_entries` (entry.factory wins\n\t// there); this field is only read for a node absent from the graph index. Caller opts win.\n\treturn new Node<TOut>([...deps], body, { factory: op.factory, ...op.opts, ...opts });\n}\n\n/** @internal Build the dispatcher body for an Operator spec. */\nexport function operatorNodeFn<TIn, TOut>(op: Operator<TIn, TOut>): NodeFn {\n\treturn (ctx) => {\n\t\ttry {\n\t\t\top.body(ctx);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"operator threw without a valid error payload\")]]); // D30: value-level throw → ERROR\n\t\t}\n\t};\n}\n\n// ── Slice 1 — single-dep map / take / control (CSP-2.7 catalog re-derive, D40) ──\n// All read dep 0 positionally + emit via ctx.down. Under D49 every occurrence is DATA (no\n// equals-absorption); a body that returns WITHOUT emitting gets a substrate-synthesized undirty\n// RESOLVED (R-resolved-undirty) — so a \"skip this wave\" is a bare `return`. Terminal-emitting\n// operators (reduce/last/find/elementAt) read `depTerminal(ctx, 0)` via the\n// `completeWhenDepsComplete:false + terminalAsRealInput:true` flags (R-deps-terminal): the fn fires\n// on the source's COMPLETE and emits its final value. NOT 1:1 pure-ts ports — the frozen reference\n// (D41) uses a producer + internal `subscribeOr`, the D45-banned describe island; these are\n// declared-dep nodes whose single edge `describe` shows truthfully.\n\n/**\n * Transform each upstream DATA value with a synchronous mapping function.\n *\n * @param fn - Mapping function, or a named `define()` definition for checkpoint restoration.\n * @returns An operator that emits `fn(value)` for each upstream value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { map } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const count = g.state(1);\n * const doubled = g.initNode(map((value: number) => value * 2), [count]);\n * ```\n * @remarks **Restorable maps:** Passing a named `define()` registers semantic restore metadata.\n * @category operators\n */\nexport function map<S, T>(fn: ((v: S) => T) | Definition<S, T>): Operator<S, T> {\n\tif (isDefinition(fn)) {\n\t\treturn mapFromFunction(fn.fn, {\n\t\t\tref: \"map\",\n\t\t\tconfig: { fn: toCheckpointJson(fn.ref, `map.fn`) },\n\t\t});\n\t}\n\treturn mapFromFunction(fn);\n}\n\nfunction mapFromFunction<S, T>(\n\tfn: (v: S) => T,\n\trestore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t},\n): Operator<S, T> {\n\treturn {\n\t\tfactory: \"map\",\n\t\t...(restore ? { restore } : {}),\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) ctx.down([[\"DATA\", fn(v as S)]]);\n\t\t},\n\t};\n}\n\n/**\n * Pass through upstream values that satisfy a predicate.\n *\n * @param pred - Predicate evaluated for each upstream DATA value.\n * @returns An operator that emits matching values and stays quiet for non-matches.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { filter } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const count = g.state(0);\n * const even = g.initNode(filter((value: number) => value % 2 === 0), [count]);\n * ```\n * @category operators\n */\nexport function filter<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"filter\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) if (pred(v as S)) ctx.down([[\"DATA\", v]]);\n\t\t},\n\t};\n}\n\n/**\n * Accumulate upstream values and emit each intermediate accumulator.\n *\n * @param reducer - Reducer called with the previous accumulator and each upstream value.\n * @param seed - Initial accumulator value.\n * @returns An operator that emits the accumulator after every input value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { scan } from \"@graphrefly/ts/operators\";\n *\n * const g = graph();\n * const values = g.state(1);\n * const total = g.initNode(scan((sum: number, value: number) => sum + value, 0), [values]);\n * ```\n * @category operators\n */\nexport function scan<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"scan\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tfor (const v of b) {\n\t\t\t\tacc = reducer(acc, v as S);\n\t\t\t\tctx.down([[\"DATA\", acc]]);\n\t\t\t}\n\t\t\tctx.state.set(acc);\n\t\t},\n\t};\n}\n\n/**\n * Emit the first `n` upstream values, then complete.\n *\n * @param n - Number of DATA values to pass before completion.\n * @returns An operator that forwards at most `n` values and then emits COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { take } from \"@graphrefly/ts/operators\";\n *\n * const firstThree = graph().initNode(take<number>(3), [source]);\n * ```\n * @category operators\n */\nexport function take<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"take\",\n\t\trestore: { ref: \"take\", config: { n: toCheckpointJson(n, \"take.n\") } },\n\t\tbody: (ctx) => {\n\t\t\tif (n <= 0) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (count >= n) return; // already satisfied\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count >= n) break;\n\t\t\t\tcount += 1;\n\t\t\t\tctx.down(count >= n ? [[\"DATA\", v], [\"COMPLETE\"]] : [[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * Suppress consecutive duplicate values.\n *\n * @param eq - Equality predicate; defaults to `Object.is`.\n * @returns An operator that emits only when the next value differs from the previous emitted value.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { distinctUntilChanged } from \"@graphrefly/ts/operators\";\n *\n * const stable = graph().initNode(distinctUntilChanged<number>(), [source]);\n * ```\n * @category operators\n */\nexport function distinctUntilChanged<S>(eq: (a: S, b: S) => boolean = Object.is): Operator<S, S> {\n\treturn {\n\t\tfactory: \"distinctUntilChanged\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst prev = ctx.state.get<{ v: S }>();\n\t\t\tlet last = prev?.v;\n\t\t\tlet hasLast = prev !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasLast && eq(last as S, v)) continue;\n\t\t\t\tlast = v;\n\t\t\t\thasLast = true;\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tif (hasLast) ctx.state.set({ v: last as S });\n\t\t},\n\t};\n}\n\n/**\n * merge: interleave several sources — emit each DATA from whichever dep fired. `partial:true`\n * (combine-family): fires on any single dep, not gated on all deps settling.\n *\n * @returns An operator that forwards DATA from any dependency.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { merge } from \"@graphrefly/ts/operators\";\n *\n * const merged = graph().initNode(merge<number>(), [left, right]);\n * ```\n * @category operators\n */\nexport function merge<T>(): Operator<T, T> {\n\treturn {\n\t\tfactory: \"merge\",\n\t\topts: { partial: true },\n\t\tbody: (ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b && b.length > 0) {\n\t\t\t\t\tfor (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * reduce: accumulate over the whole source, emit ONE final value on the source's COMPLETE\n * (RxJS `reduce`). Unlike {@link scan} (which emits every step), reduce stays quiet until the\n * source terminates. `completeWhenDepsComplete:false + terminalAsRealInput:true`: the fn fires on\n * the source COMPLETE (reading `terminal===true`) and emits the accumulator + COMPLETE. An empty\n * source emits the seed (RxJS parity). A source ERROR auto-forwards (errorWhenDepsError default).\n *\n * @param reducer - Reducer called with the accumulator and each upstream DATA value.\n * @param seed - Initial accumulator value emitted if the source completes empty.\n * @returns An operator that emits one accumulated value when the source completes.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { reduce } from \"@graphrefly/ts/operators\";\n *\n * const total = graph().initNode(reduce((sum: number, value: number) => sum + value, 0), [source]);\n * ```\n * @category operators\n */\nexport function reduce<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"reduce\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tif (b) for (const v of b) acc = reducer(acc, v as S);\n\t\t\tctx.state.set(acc);\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"DATA\", acc], [\"COMPLETE\"]]);\n\t\t\t// else (live DATA wave): no emit → substrate-synthesized undirty RESOLVED (D49).\n\t\t},\n\t};\n}\n\n/**\n * pairwise: emit `[previous, current]` for each consecutive pair; the very first value produces no\n * pair (quiet → undirty RESOLVED). Previous value is kept in `ctx.state`.\n * @returns A `Operator<S, readonly [S, S]>` value.\n * @category operators\n * @example\n * ```ts\n * import { pairwise } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function pairwise<S>(): Operator<S, readonly [S, S]> {\n\treturn {\n\t\tfactory: \"pairwise\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst st = ctx.state.get<{ prev: S }>();\n\t\t\tlet prev = st?.prev;\n\t\t\tlet hasPrev = st !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasPrev) ctx.down([[\"DATA\", [prev as S, v] as const]]);\n\t\t\t\tprev = v;\n\t\t\t\thasPrev = true;\n\t\t\t}\n\t\t\tif (hasPrev) ctx.state.set({ prev: prev as S });\n\t\t},\n\t};\n}\n\n/** skip: drop the first `n` DATA values, then pass the rest through.\n * @param n - n value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { skip } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function skip<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"skip\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count < n) {\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * takeWhile: emit values while `pred` holds; on the first value that fails `pred`, COMPLETE\n * WITHOUT emitting it (RxJS default, non-inclusive). Terminal-is-forever once it completes.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { takeWhile } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function takeWhile<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"takeWhile\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (pred(v)) ctx.down([[\"DATA\", v]]);\n\t\t\t\telse {\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * first: emit the first value matching `pred` (or simply the first value), then COMPLETE. EDGE\n * (RxJS divergence, flagged — same class as last/find/elementAt): if the source COMPLETEs with no\n * matching value, the substrate auto-cascades a bare COMPLETE (no value); RxJS `first()` throws\n * EmptyError. Could align to `[[ERROR, EmptyError]]` (expressible) if strict RxJS parity is wanted.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { first } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function first<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"first\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (!pred || pred(v)) {\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no match in this wave → undirty RESOLVED (await next match)\n\t\t},\n\t};\n}\n\n/**\n * last: emit the last value matching `pred` (or the last value) on the source's COMPLETE.\n * `completeWhenDepsComplete:false + terminalAsRealInput:true`. EDGE (RxJS divergence, flagged):\n * RxJS `last()` throws EmptyError when no value matched; we COMPLETE without a value (no throw) —\n * GraphReFly has no \"complete-or-throw\" terminal and SENTINEL forbids emitting a\n * placeholder.\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { last } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function last<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"last\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) for (const v of b) if (!pred || pred(v as S)) ctx.state.set({ v });\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) {\n\t\t\t\tconst st = ctx.state.get<{ v: S }>();\n\t\t\t\tctx.down(st ? [[\"DATA\", st.v], [\"COMPLETE\"]] : [[\"COMPLETE\"]]);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * find: emit the first value matching `pred`, then COMPLETE. EDGE (RxJS divergence, flagged): RxJS\n * `find` emits `undefined` then COMPLETE when nothing matched — but `undefined` IS the SENTINEL\n * (R-sentinel), so a not-found source COMPLETE here emits a bare COMPLETE (no value).\n * @param pred - pred value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { find } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function find<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"find\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (pred(v as S)) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // not found → bare COMPLETE\n\t\t},\n\t};\n}\n\n/**\n * elementAt: emit the value at zero-based `index`, then COMPLETE. EDGE (RxJS divergence, flagged):\n * RxJS throws ArgumentOutOfRangeError if the source completes before `index`; we COMPLETE without\n * a value (no throw), consistent with last/find.\n * @param index - index value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { elementAt } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function elementAt<S>(index: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"elementAt\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (count === index) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\tctx.state.set(count);\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // index out of range → bare COMPLETE\n\t\t},\n\t};\n}\n\n/** Observer object for {@link tap} — lifecycle-aware side effects (RxJS tap observer form). */\nexport interface TapObserver<T> {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n}\n\n/**\n * tap: invoke a side effect on each DATA (function form) or on data/error/complete (observer form);\n * values pass through unchanged. The observer form reads source terminals\n * (`completeWhenDepsComplete:false + errorWhenDepsError:false + terminalAsRealInput:true`) so it can\n * call `error`/`complete` then forward the terminal; the function form lets the substrate\n * auto-cascade terminals.\n * @param fnOrObserver - fn or observer value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { tap } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function tap<S>(fnOrObserver: ((v: S) => void) | TapObserver<S>): Operator<S, S> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\tconst fn = fnOrObserver;\n\t\treturn {\n\t\t\tfactory: \"tap\",\n\t\t\tbody: (ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\tif (b)\n\t\t\t\t\tfor (const v of b) {\n\t\t\t\t\t\tfn(v as S);\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\tconst obs = fnOrObserver;\n\treturn {\n\t\tfactory: \"tap\",\n\t\topts: {\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tobs.complete?.();\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(terminal)) {\n\t\t\t\tconst err = terminalErrorValue(terminal);\n\t\t\t\tobs.error?.(err);\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b)\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tobs.data?.(v as S);\n\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * onFirstData (alias `tapFirst`): invoke `fn` exactly once on the first qualifying value (default\n * `where: v => v != null` — null/undefined pass through without counting as \"first\"), then pass all\n * values through unchanged. The one-shot guard is per-node `ctx.state` (NOT a factory closure, so a\n * second instantiation of the same factory re-arms — R-ctx-state).\n * @param fn - Synchronous function invoked by the helper.\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { onFirstData } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function onFirstData<S>(\n\tfn: (v: S) => void,\n\topts?: { where?: (v: S) => boolean },\n): Operator<S, S> {\n\tconst where = opts?.where ?? ((v: S) => v != null);\n\treturn {\n\t\tfactory: \"onFirstData\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet fired = ctx.state.get<boolean>() ?? false;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (!fired && where(v as S)) {\n\t\t\t\t\tfired = true;\n\t\t\t\t\tfn(v as S);\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(fired);\n\t\t},\n\t};\n}\n\n/** tapFirst: alias of {@link onFirstData} (the one-shot companion to {@link tap}). */\nexport const tapFirst = onFirstData;\n\n/** Options for {@link settle}. */\nexport interface SettleOpts<S> {\n\t/** Consecutive no-change waves before declaring convergence + COMPLETE. */\n\tquietWaves: number;\n\t/** Optional hard cap on total waves before forced COMPLETE. */\n\tmaxWaves?: number;\n\t/** Optional comparator; a DATA equal to the previous one does NOT reset the quiet counter. */\n\tequals?: (a: S, b: S) => boolean;\n}\n\n/** Internal settle accumulator state (per-node, R-ctx-state). */\ninterface SettleState<S> {\n\tlast: S | undefined;\n\thasValue: boolean;\n\tquiet: number;\n\twaves: number;\n\tdone: boolean;\n}\n\n/**\n * settle: forward each DATA unchanged, watch for convergence, COMPLETE once the source has been\n * quiet for `quietWaves` consecutive waves (or `maxWaves` elapsed). \"Wave\" = one fn invocation\n * (a DATA batch OR a bare undirty RESOLVED end-of-wave). No polling (R-no-polling) — the counter\n * advances only on real upstream waves. `settle`'s own `equals` is a body comparator, NOT the\n * removed substrate `equals` (D49).\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { settle } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function settle<S>(opts: SettleOpts<S>): Operator<S, S> {\n\tconst { quietWaves, maxWaves, equals } = opts;\n\tif (!Number.isInteger(quietWaves) || quietWaves < 1) {\n\t\tthrow new RangeError(`settle: quietWaves must be a positive integer (got ${quietWaves})`);\n\t}\n\tif (maxWaves != null && (!Number.isInteger(maxWaves) || maxWaves < 1)) {\n\t\tthrow new RangeError(`settle: maxWaves must be a positive integer when set (got ${maxWaves})`);\n\t}\n\treturn {\n\t\tfactory: \"settle\",\n\t\tbody: (ctx) => {\n\t\t\tconst st: SettleState<S> = ctx.state.get<SettleState<S>>() ?? {\n\t\t\t\tlast: undefined,\n\t\t\t\thasValue: false,\n\t\t\t\tquiet: 0,\n\t\t\t\twaves: 0,\n\t\t\t\tdone: false,\n\t\t\t};\n\t\t\tif (st.done) return;\n\t\t\tst.waves++;\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet sawChange = false;\n\t\t\tif (b && b.length > 0) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tconst next = v as S;\n\t\t\t\t\tconst isChange = !st.hasValue || equals == null || !equals(st.last as S, next);\n\t\t\t\t\tif (isChange) sawChange = true;\n\t\t\t\t\tst.last = next;\n\t\t\t\t\tst.hasValue = true;\n\t\t\t\t\tctx.down([[\"DATA\", next]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.quiet = sawChange ? 0 : st.quiet + 1;\n\t\t\tconst settled = st.hasValue && st.quiet >= quietWaves;\n\t\t\tconst exhausted = maxWaves != null && st.waves >= maxWaves;\n\t\t\tif (settled || exhausted) {\n\t\t\t\tst.done = true;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t\t// A no-DATA wave that didn't converge → bare undirty RESOLVED is synthesized by the\n\t\t\t// substrate (D49); nothing to emit here.\n\t\t},\n\t};\n}\n\n// ── Slice 3 — error-handling control (CSP-2.7, D40) ──\n// rescue/catchError ABSORB the source ERROR (errorWhenDepsError:false) and read the error payload\n// from `depTerminal(ctx, 0)` (R-deps-terminal). They set completeWhenDepsComplete:false so a\n// normal source COMPLETE is forwarded explicitly — which ALSO sidesteps B40 (the\n// completeWhenDepsComplete:true × absorbed-errored-dep auto-complete gap): there is no auto-complete\n// to block. valve is a [source, control] gate (state-verb-legitimate control input).\n\n/**\n * rescue (alias `catchError`): replace an upstream ERROR with a recovered value. On source DATA →\n * forward; on source ERROR → emit `recover(err)` as DATA (if `recover` throws, forward THAT as\n * ERROR); on source COMPLETE → COMPLETE. After recovery the source is terminal-errored (dead) so no\n * further values flow — the recovered value is the final cached value (matches the frozen pure-ts\n * reference; it does NOT auto-COMPLETE, RxJS-`catchError(()=>of(x))` divergence, flagged).\n * @param recover - recover value used by the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { rescue } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function rescue<S>(recover: (err: unknown) => S): Operator<S, S> {\n\treturn {\n\t\tfactory: \"rescue\",\n\t\topts: {\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (b) for (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t} else if (isTerminalError(terminal)) {\n\t\t\t\t// ERROR payload absorbed → recover.\n\t\t\t\ttry {\n\t\t\t\t\tctx.down([[\"DATA\", recover(terminalErrorValue(terminal))]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"rescue threw without a valid error payload\")]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** catchError: RxJS-named alias of {@link rescue}. */\nexport const catchError = rescue;\n\n/** Options for {@link valve}. */\nexport interface ValveOpts {\n\t/**\n\t * Optional AbortController (or a `() => AbortController | undefined` factory): on the control's\n\t * truthy→falsy edge, `valve` calls `controller.abort()` — cancel an in-flight async boundary\n\t * (LLM/fetch) the caller threaded `controller.signal` into. An external-resource cleanup (like\n\t * `ctx.onDeactivation`), NOT an imperative reactive trigger (R-no-imperative).\n\t */\n\tabortInFlight?: AbortController | (() => AbortController | undefined);\n}\n\n/**\n * valve: forward the source's DATA only while `control` (dep 1) is truthy; when closed, stay quiet\n * (undirty RESOLVED). `[source, control]` declared deps + `partial:true` (the control wave can fire\n * before the source ever delivers). `completeWhenDepsComplete:false` — closing the gate (control\n * terminating) does NOT complete the valve; only the SOURCE's terminal (read via\n * `terminalAsRealInput`) is forwarded. The `state`-verb control input is a legitimate external\n * boundary (D4 / D54), not a forbidden imperative trigger.\n * @param opts - Options that configure the helper.\n * @returns A `Operator<S, S>` value.\n * @category operators\n * @example\n * ```ts\n * import { valve } from \"@graphrefly/ts/operators\";\n * ```\n */\nexport function valve<S>(opts?: ValveOpts): Operator<S, S> {\n\tconst abortInFlight = opts?.abortInFlight;\n\treturn {\n\t\tfactory: \"valve\",\n\t\topts: { partial: true, completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst ctlBatch = depBatch(ctx, 1);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\t\tconst controlValue = depLatest(ctx, 1) as boolean | undefined;\n\n\t\t\tif (abortInFlight != null) {\n\t\t\t\t// Fire abort on the truthy→falsy edge only (never on activation / no prior state).\n\t\t\t\tconst prev = ctx.state.get<{ ctl: boolean | undefined }>();\n\t\t\t\tif (prev?.ctl === true && !controlValue) {\n\t\t\t\t\tconst c = typeof abortInFlight === \"function\" ? abortInFlight() : abortInFlight;\n\t\t\t\t\tc?.abort();\n\t\t\t\t}\n\t\t\t\tctx.state.set({\n\t\t\t\t\tctl: controlValue === true ? true : controlValue == null ? undefined : false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Source terminal forwarding (control terminal is absorbed by completeWhenDepsComplete:false).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!controlValue) return; // gate closed → quiet (undirty RESOLVED)\n\n\t\t\tif (srcBatch && srcBatch.length > 0) {\n\t\t\t\tfor (const v of srcBatch) ctx.down([[\"DATA\", v]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Gate just opened this wave (control fired, source didn't): re-emit the last source value.\n\t\t\tconst srcLatest = depLatest(ctx, 0);\n\t\t\tif (ctlBatch && ctlBatch.length > 0 && srcLatest !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", srcLatest as S]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Async + sync sources (binding-layer sugar, D43 / D40 / feedback_async_sources_binding_layer).\n *\n * Sources are depless {@link Operator}`<never, T>` specs built on the `producer`/`node` path:\n * the body runs ONCE on activation (node `_activate`), schedules its work, and emits later via\n * the captured `ctx.down` (an external tier-3 emit → the leading DIRTY is synthesized for it,\n * R-dirty-before-data). Async lives ONLY here (R-no-raw-async / F-SYNC-CORE): `setTimeout` /\n * `Promise` / `for await` are confined to source bodies; the wave core stays sync. Cleanup is\n * `ctx.onDeactivation` (D28), NOT a returned object. Per-language (D6/D24), never in parity.\n *\n * Instantiate via `g.initNode(timer(1000), [])` (graph-bound, inspectable) or\n * {@link initNode}(timer(1000), []) (bare). Pool/pause defaults (D43): timer/interval =\n * sync + pausable:false (keep producing through PAUSE); fromPromise/fromAsyncIter = async\n * (default pausable, so a paused source buffers its late emits — R-async-paused).\n */\n\nimport type { Ctx } from \"../ctx/types.js\";\nimport type { Node, NodeOptions } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { toCheckpointJson } from \"./checkpoint.js\";\nimport type {\n\tDriverCancel,\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"./environment.js\";\nimport { initNode, type Operator } from \"./operators.js\";\n\n/**\n * Values accepted by {@link fromAny}: an existing Node, a Promise, an (a)sync iterable, or a\n * bare scalar. The universal coercion target for higher-order operators (CSP-2.7).\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Host-boundary options for {@link singleFromAny}. */\nexport interface SingleFromAnyOptions<K> {\n\t/**\n\t * Map a caller key to the in-flight dedupe key. Defaults to key identity; object keys dedupe only\n\t * when the same object reference is reused. Return a stable string/canonical value for structural\n\t * object-key dedupe.\n\t */\n\tkeyOf?: (key: K) => unknown;\n\t/** Treat a sync iterable result as a stream and take its first item. Defaults to scalar value. */\n\titer?: boolean;\n}\n\n/**\n * Internal: build a depless source spec. `setup` runs once on activation; its returned fn (if\n * any) is registered as the deactivation cleanup (clear timers / abort). `setup` schedules the\n * async work and emits via `ctx.down` — synchronously (sync sources) or later (async sources).\n */\nfunction source<T>(\n\tfactory: string,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: setup returns a cleanup fn OR nothing — the void arm keeps no-return source bodies (e.g. `of`/`fromIter`) ergonomic, same idiom as EffectFn.\n\tsetup: (ctx: Ctx) => void | (() => void),\n\topts?: Partial<NodeOptions<T>>,\n): Operator<never, T> {\n\treturn {\n\t\tfactory,\n\t\topts,\n\t\tbody: (ctx) => {\n\t\t\tlet cleanup: undefined | (() => void);\n\t\t\tlet deactivated = false;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tdeactivated = true;\n\t\t\t\tif (typeof cleanup === \"function\") cleanup();\n\t\t\t});\n\t\t\tconst maybeCleanup = setup(ctx);\n\t\t\tcleanup = typeof maybeCleanup === \"function\" ? maybeCleanup : undefined;\n\t\t\tif (deactivated && typeof cleanup === \"function\") cleanup();\n\t\t},\n\t};\n}\n\nfunction assertNonEmptyString(value: string, label: string): void {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new TypeError(`${label} must be a non-empty string`);\n\t}\n}\n\nfunction cleanupDriverWork(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n): void {\n\tactive.value = false;\n\tconst cancel = cancelSlot.value;\n\tcancelSlot.value = undefined;\n\tif (cancel !== undefined) runDriverCancel(cancel);\n}\n\nfunction installDriverCancel(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n\tcancel: DriverCancel,\n): void {\n\tif (active.value) cancelSlot.value = cancel;\n\telse runDriverCancel(cancel);\n}\n\nfunction runDriverCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cleanup is best-effort: it must not suppress graph-visible terminal delivery.\n\t}\n}\n\nfunction driverOneShotSource<T>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (result: DriverResult<T>) => void) => DriverCancel | undefined,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (result: DriverResult<T>) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\tif (result.ok) ctx.down([[\"DATA\", result.value], [\"COMPLETE\"]]);\n\t\t\t\telse ctx.down([[\"ERROR\", errorPayload(result.error)]]);\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction driverStreamSource<T, E extends { readonly kind: string }>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (event: E) => void) => DriverCancel | undefined,\n\tdataOf: (event: E) => T | undefined,\n\terrorOf: (event: E) => unknown,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (event: E) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\tconst value = dataOf(event);\n\t\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(errorOf(event))]]);\n\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\t\"cache\" in x &&\n\t\ttypeof (x as Node).subscribe === \"function\"\n\t);\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isAsyncIterable<T>(x: unknown): x is AsyncIterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nfunction isIterable<T>(x: unknown): x is Iterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\t);\n}\n\n/** Options shared by async/timer sources: an optional AbortSignal → ERROR on abort. */\nexport interface AsyncSourceOpts {\n\tsignal?: AbortSignal;\n}\n\nexport interface TimerSourceOpts extends AsyncSourceOpts {\n\tperiod?: number;\n}\n\n/** Options for {@link fromCron}. */\nexport interface FromCronOptions extends AsyncSourceOpts {\n\t/** Cron matcher polling interval in milliseconds. Default: 60_000. */\n\ttickMs?: number;\n\t/** IANA timezone used for wall-clock cron matching. Defaults to the host-local timezone. */\n\ttimezone?: string;\n\t/**\n\t * DST policy for timezone-aware matching. Current D484 defaults are explicit: nonexistent\n\t * wall-clock minutes are skipped, and repeated wall-clock minutes fire at most once.\n\t */\n\tdst?: {\n\t\treadonly nonexistent?: \"skip\";\n\t\treadonly repeated?: \"once\";\n\t};\n\t/**\n\t * Emitted value shape. `timestamp_ns` is a decimal string so it cannot lose precision as a\n\t * JavaScript number; use `timestamp_ms` when numeric millisecond precision is enough.\n\t */\n\toutput?: \"date\" | \"timestamp_ms\" | \"timestamp_ns\";\n}\n\n/** Minimal five-field cron schedule: minute hour day-of-month month day-of-week. */\nexport interface CronSchedule {\n\treadonly minutes: ReadonlySet<number>;\n\treadonly hours: ReadonlySet<number>;\n\treadonly daysOfMonth: ReadonlySet<number>;\n\treadonly months: ReadonlySet<number>;\n\treadonly daysOfWeek: ReadonlySet<number>;\n}\n\n/** DOM/EventEmitter-style target accepted by {@link fromEvent}. */\nexport interface EventTargetLike {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n}\n\nexport interface EventListenerOptionsLike {\n\tcapture?: boolean;\n\tpassive?: boolean;\n\tonce?: boolean;\n}\n\nexport type FromEventOptions = EventListenerOptionsLike;\n\n/** Host push registration callback accepted by {@link fromPushNotification}. */\nexport type PushUnsubscribe = () => void;\nexport type PushRegister<T> = (deliver: (payload: T) => void) => PushUnsubscribe | undefined;\n\nfunction parseCronField(field: string, min: number, max: number): Set<number> {\n\tif (field.length === 0) throw new Error(\"Invalid cron field: empty\");\n\tconst out = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tif (part.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tconst stepParts = part.split(\"/\");\n\t\tif (stepParts.length > 2) throw new Error(`Invalid cron step: ${part}`);\n\t\tconst [range, stepText] = stepParts;\n\t\tif (range == null || range.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (stepText === \"\") throw new Error(`Invalid cron step: ${part}`);\n\t\tconst step = stepText == null ? 1 : parseCronInt(stepText, `Invalid cron step: ${part}`);\n\t\tif (step < 1) throw new Error(`Invalid cron step: ${part}`);\n\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b, extra] = range.split(\"-\");\n\t\t\tif (extra !== undefined || a === \"\" || b === \"\")\n\t\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t\tstart = parseCronInt(a, `Invalid cron field: ${field}`);\n\t\t\tend = parseCronInt(b, `Invalid cron field: ${field}`);\n\t\t} else {\n\t\t\tstart = parseCronInt(range, `Invalid cron field: ${field}`);\n\t\t\tend = start;\n\t\t}\n\n\t\tif (!Number.isInteger(start) || !Number.isInteger(end)) {\n\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t}\n\t\tif (start < min || end > max) {\n\t\t\tthrow new RangeError(`Cron field out of range: ${field} (${min}-${max})`);\n\t\t}\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) out.add(i);\n\t}\n\treturn out;\n}\n\nfunction parseCronInt(text: string, message: string): number {\n\tif (!/^\\d+$/.test(text)) throw new Error(message);\n\tconst value = Number.parseInt(text, 10);\n\tif (!Number.isSafeInteger(value)) throw new Error(message);\n\treturn value;\n}\n\n/**\n * Parse a standard five-field cron expression.\n *\n * @param expr - Cron expression in `minute hour day month weekday` order.\n * @returns A normalized cron schedule with one set per field.\n * @example\n * ```ts\n * parseCron(\"0,5 * * * *\");\n * ```\n * @category sources\n */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5 || parts.some((part) => part.length === 0)) {\n\t\tthrow new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\t}\n\treturn {\n\t\tminutes: parseCronField(parts[0], 0, 59),\n\t\thours: parseCronField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseCronField(parts[2], 1, 31),\n\t\tmonths: parseCronField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseCronField(parts[4], 0, 6),\n\t};\n}\n\nexport interface CronMatchOptions {\n\t/** IANA timezone used for wall-clock projection. Defaults to the host-local timezone. */\n\ttimezone?: string;\n}\n\ninterface CronWallClockFields {\n\treadonly year: number;\n\treadonly month: number;\n\treadonly day: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly dayOfWeek: number;\n}\n\n/**\n * Test whether a date matches a parsed cron schedule.\n *\n * @param schedule - Parsed cron schedule to match against.\n * @param date - Date to test.\n * @param opts - Optional timezone override.\n * @returns `true` when the date satisfies all cron fields.\n * @example\n * ```ts\n * matchesCron(parseCron(\"0 * * * *\"), new Date());\n * ```\n * @category sources\n */\nexport function matchesCron(\n\tschedule: CronSchedule,\n\tdate: Date,\n\topts: CronMatchOptions = {},\n): boolean {\n\tconst fields = cronWallClockFields(date, opts.timezone);\n\treturn (\n\t\tschedule.minutes.has(fields.minute) &&\n\t\tschedule.hours.has(fields.hour) &&\n\t\tschedule.daysOfMonth.has(fields.day) &&\n\t\tschedule.months.has(fields.month) &&\n\t\tschedule.daysOfWeek.has(fields.dayOfWeek)\n\t);\n}\n\nfunction cronMinuteKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}-${fields.hour}-${fields.minute}`;\n}\n\nfunction cronDayKey(date: Date, timezone?: string): string {\n\tconst fields = cronWallClockFields(date, timezone);\n\treturn `${fields.year}-${fields.month}-${fields.day}`;\n}\n\nfunction cronWallClockFields(date: Date, timezone?: string): CronWallClockFields {\n\tif (timezone === undefined) {\n\t\treturn {\n\t\t\tyear: date.getFullYear(),\n\t\t\tmonth: date.getMonth() + 1,\n\t\t\tday: date.getDate(),\n\t\t\thour: date.getHours(),\n\t\t\tminute: date.getMinutes(),\n\t\t\tdayOfWeek: date.getDay(),\n\t\t};\n\t}\n\tconst parts = timezoneFormatter(timezone).formatToParts(date);\n\tconst values: Record<string, number> = {};\n\tfor (const part of parts) {\n\t\tif (\n\t\t\tpart.type === \"year\" ||\n\t\t\tpart.type === \"month\" ||\n\t\t\tpart.type === \"day\" ||\n\t\t\tpart.type === \"hour\" ||\n\t\t\tpart.type === \"minute\"\n\t\t) {\n\t\t\tvalues[part.type] = Number.parseInt(part.value, 10);\n\t\t}\n\t}\n\tconst year = values.year;\n\tconst month = values.month;\n\tconst day = values.day;\n\tconst hour = values.hour;\n\tconst minute = values.minute;\n\tif (\n\t\tyear === undefined ||\n\t\tmonth === undefined ||\n\t\tday === undefined ||\n\t\thour === undefined ||\n\t\tminute === undefined\n\t) {\n\t\tthrow new Error(`fromCron: timezone projection failed for ${timezone}`);\n\t}\n\treturn {\n\t\tyear,\n\t\tmonth,\n\t\tday,\n\t\thour,\n\t\tminute,\n\t\tdayOfWeek: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),\n\t};\n}\n\nconst TIMEZONE_FORMATTERS = new Map<string, Intl.DateTimeFormat>();\n\nfunction timezoneFormatter(timezone: string): Intl.DateTimeFormat {\n\tconst existing = TIMEZONE_FORMATTERS.get(timezone);\n\tif (existing !== undefined) return existing;\n\tassertNonEmptyString(timezone, \"fromCron: timezone\");\n\ttry {\n\t\tconst formatter = new Intl.DateTimeFormat(\"en-US-u-ca-gregory-nu-latn\", {\n\t\t\ttimeZone: timezone,\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\thourCycle: \"h23\",\n\t\t});\n\t\tformatter.format(new Date(0));\n\t\tTIMEZONE_FORMATTERS.set(timezone, formatter);\n\t\treturn formatter;\n\t} catch (error) {\n\t\tthrow new RangeError(\n\t\t\t`fromCron: unsupported IANA timezone '${timezone}' (${error instanceof Error ? error.message : String(error)})`,\n\t\t);\n\t}\n}\n\nfunction dateToTimestampNs(date: Date): string {\n\treturn (BigInt(date.getTime()) * 1_000_000n).toString();\n}\n\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"date\" },\n): Operator<never, Date>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"timestamp_ms\" },\n): Operator<never, number>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions & { output?: \"timestamp_ns\" },\n): Operator<never, string>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions,\n): Operator<never, Date | number | string>;\n/**\n * Emit wall-clock cron ticks on a graph source.\n *\n * @param expr - Five-field cron expression.\n * @param opts - Cron polling, timezone, DST, abort, and output-shape options.\n * @returns A source operator that emits the current time when the schedule matches.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromCron } from \"@graphrefly/ts/sources\";\n *\n * const everyMinute = graph().initNode(fromCron(\"0 * * * *\"), []);\n * ```\n * @category sources\n */\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions = {},\n): Operator<never, Date | number | string> {\n\tconst schedule = parseCron(expr);\n\tconst { tickMs = 60_000, output = \"timestamp_ns\", signal, timezone } = opts;\n\tif (opts.dst?.nonexistent !== undefined && opts.dst.nonexistent !== \"skip\") {\n\t\tthrow new RangeError(\"fromCron: dst.nonexistent currently supports only 'skip'\");\n\t}\n\tif (opts.dst?.repeated !== undefined && opts.dst.repeated !== \"once\") {\n\t\tthrow new RangeError(\"fromCron: dst.repeated currently supports only 'once'\");\n\t}\n\tif (timezone !== undefined) timezoneFormatter(timezone);\n\tif (!Number.isFinite(tickMs) || tickMs <= 0) {\n\t\tthrow new RangeError(\"fromCron: tickMs must be a positive finite number\");\n\t}\n\treturn source<Date | number | string>(\n\t\t\"fromCron\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet lastFiredKey: string | undefined;\n\t\t\tlet firedTimezoneDay: string | undefined;\n\t\t\tconst firedTimezoneMinutes = new Set<string>();\n\t\t\tlet intervalId: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (intervalId !== undefined) clearInterval(intervalId);\n\t\t\t\tintervalId = undefined;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst emitNow = (now: Date) => {\n\t\t\t\tif (output === \"date\") ctx.down([[\"DATA\", now]]);\n\t\t\t\telse if (output === \"timestamp_ms\") ctx.down([[\"DATA\", now.getTime()]]);\n\t\t\t\telse ctx.down([[\"DATA\", dateToTimestampNs(now)]]);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key = cronMinuteKey(now, timezone);\n\t\t\t\tconst alreadyFired =\n\t\t\t\t\ttimezone === undefined ? key === lastFiredKey : firedTimezoneMinutes.has(key);\n\t\t\t\tif (!alreadyFired && matchesCron(schedule, now, { timezone })) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\tif (timezone !== undefined) {\n\t\t\t\t\t\tconst dayKey = cronDayKey(now, timezone);\n\t\t\t\t\t\tif (dayKey !== firedTimezoneDay) {\n\t\t\t\t\t\t\tfiredTimezoneDay = dayKey;\n\t\t\t\t\t\t\tfiredTimezoneMinutes.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfiredTimezoneMinutes.add(key);\n\t\t\t\t\t}\n\t\t\t\t\temitNow(now);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn cleanup;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tcheck();\n\t\t\tintervalId = setInterval(check, tickMs);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n}\n\n/**\n * Run a command and emit its process result once.\n *\n * @param program - Executable name or path.\n * @param args - Command-line arguments.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * runProcess(\"git\", [\"status\"]);\n * ```\n * @category sources\n */\nexport function runProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn runProcessWithOptions({ program, args });\n}\n\n/**\n * Emit a process result with the `fromProcess` source factory.\n *\n * @param program - Executable name or path.\n * @param args - Command-line arguments.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * fromProcess(\"git\", [\"status\"]);\n * ```\n * @category sources\n */\nexport function fromProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn processSource(\"fromProcess\", { program, args });\n}\n\n/**\n * Run a caller-supplied process command through the graph environment driver.\n *\n * @param command - Process command object consumed by the graph-local process driver.\n * @returns A source operator that emits one `ProcessResult`.\n * @example\n * ```ts\n * import { runProcessWithOptions } from \"@graphrefly/ts\";\n * import { graph } from \"@graphrefly/ts/graph\";\n *\n * const status = graph().initNode(runProcessWithOptions({ program: \"git\", args: [\"status\"] }), []);\n * ```\n * @category sources\n */\nexport function runProcessWithOptions(command: ProcessCommand): Operator<never, ProcessResult> {\n\treturn processSource(\"runProcess\", command);\n}\n\nfunction processSource(factory: string, command: ProcessCommand): Operator<never, ProcessResult> {\n\tassertNonEmptyString(command.program, `${factory}: program`);\n\treturn driverOneShotSource<ProcessResult>(\n\t\tfactory,\n\t\t`${factory}: missing process driver`,\n\t\t(ctx, callback) => ctx.environment().processDriver()?.run(command, callback),\n\t);\n}\n\n/**\n * Emit a single HTTP response for a GET request.\n *\n * @param url - Request URL.\n * @returns A source operator that emits one `HttpResponse`.\n * @example\n * ```ts\n * fromHttp(\"https://example.com\");\n * ```\n * @category sources\n */\nexport function fromHttp(url: string): Operator<never, HttpResponse> {\n\treturn fromHttpWithOptions({ method: \"GET\", url });\n}\n\n/**\n * Emit a single HTTP response using a caller-supplied request object.\n *\n * @param request - HTTP request to dispatch.\n * @returns A source operator that emits one `HttpResponse`.\n * @example\n * ```ts\n * fromHttpWithOptions({ method: \"GET\", url: \"https://example.com\" });\n * ```\n * @category sources\n */\nexport function fromHttpWithOptions(request: HttpRequest): Operator<never, HttpResponse> {\n\tassertNonEmptyString(request.url, \"fromHttp: url\");\n\tassertNonEmptyString(request.method, \"fromHttp: method\");\n\treturn driverOneShotSource<HttpResponse>(\n\t\t\"fromHttp\",\n\t\t\"fromHttp: missing http driver\",\n\t\t(ctx, callback) => ctx.environment().httpDriver()?.request(request, callback),\n\t);\n}\n\n/**\n * Emit server-sent events from a URL.\n *\n * @param url - SSE endpoint URL.\n * @returns A source operator that emits each SSE event.\n * @example\n * ```ts\n * fromSSE(\"https://example.com/events\");\n * ```\n * @category sources\n */\nexport function fromSSE(url: string): Operator<never, SseEvent> {\n\treturn fromSSEWithOptions({ url });\n}\n\n/**\n * Emit server-sent events using a caller-supplied request object.\n *\n * @param request - SSE request details.\n * @returns A source operator that emits each SSE event.\n * @example\n * ```ts\n * fromSSEWithOptions({ url: \"https://example.com/events\" });\n * ```\n * @category sources\n */\nexport function fromSSEWithOptions(request: SseRequest): Operator<never, SseEvent> {\n\tassertNonEmptyString(request.url, \"fromSSE: url\");\n\treturn driverStreamSource<SseEvent, SseDriverEvent>(\n\t\t\"fromSSE\",\n\t\t\"fromSSE: missing sse driver\",\n\t\t(ctx, callback) => ctx.environment().sseDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\n/**\n * Emit WebSocket events from a URL.\n *\n * @param url - WebSocket endpoint URL.\n * @returns A source operator that emits connection, message, and close events.\n * @example\n * ```ts\n * fromWebSocket(\"wss://example.com/socket\");\n * ```\n * @category sources\n */\nexport function fromWebSocket(url: string): Operator<never, WebSocketEvent> {\n\treturn fromWebSocketWithOptions({ url });\n}\n\n/**\n * Emit WebSocket events using a caller-supplied request object.\n *\n * @param request - WebSocket request details.\n * @returns A source operator that emits connection, message, and close events.\n * @example\n * ```ts\n * fromWebSocketWithOptions({ url: \"wss://example.com/socket\" });\n * ```\n * @category sources\n */\nexport function fromWebSocketWithOptions(\n\trequest: WebSocketRequest,\n): Operator<never, WebSocketEvent> {\n\tassertNonEmptyString(request.url, \"fromWebSocket: url\");\n\treturn driverStreamSource<WebSocketEvent, WebSocketDriverEvent>(\n\t\t\"fromWebSocket\",\n\t\t\"fromWebSocket: missing websocket driver\",\n\t\t(ctx, callback) => ctx.environment().webSocketDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\n/**\n * Emit webhook delivery events for a registration id.\n *\n * @param id - Webhook registration id.\n * @returns A source operator that emits each webhook delivery event.\n * @example\n * ```ts\n * fromWebhook(\"ingest-events\");\n * ```\n * @category sources\n */\nexport function fromWebhook(id: string): Operator<never, WebhookEvent> {\n\treturn fromWebhookWithOptions({ id });\n}\n\n/**\n * Emit webhook delivery events using a caller-supplied registration object.\n *\n * @param registration - Webhook registration details.\n * @returns A source operator that emits each webhook delivery event.\n * @example\n * ```ts\n * fromWebhookWithOptions({ id: \"ingest-events\", method: \"POST\" });\n * ```\n * @category sources\n */\nexport function fromWebhookWithOptions(\n\tregistration: WebhookRegistration,\n): Operator<never, WebhookEvent> {\n\tassertNonEmptyString(registration.id, \"fromWebhook: id\");\n\treturn driverStreamSource<WebhookEvent, WebhookDriverEvent>(\n\t\t\"fromWebhook\",\n\t\t\"fromWebhook: missing webhook driver\",\n\t\t(ctx, callback) => ctx.environment().webhookDriver()?.register(registration, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nfunction timerSource(factory: string, ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\tconst { period, signal } = opts ?? {};\n\tconst op = source<number>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet count = 0;\n\t\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst finish = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tif (period != null) {\n\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\t\tif (done) return;\n\t\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\t}, period);\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot: DATA then COMPLETE in one wave (terminal-is-forever).\n\t\t\t\t\tdone = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", count++], [\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tt = setTimeout(finish, ms);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n\tif (factory === \"timer\" && period === undefined && signal === undefined) {\n\t\treturn { ...op, restore: { ref: \"timer\", config: { ms: toCheckpointJson(ms, \"timer.ms\") } } };\n\t}\n\treturn op;\n}\n\n/**\n * Timer source: one-shot (first tick then COMPLETE) or periodic (`{period}` → 0, 1, 2, …).\n * sync pool + pausable:false (a timer keeps producing through PAUSE, R-pause-modes). Emits the\n * tick counter from 0; deactivation clears the timers.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { timer } from \"@graphrefly/ts/sources\";\n *\n * const tick = graph().initNode(timer(100), []);\n * ```\n * @category sources\n */\nexport function timer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"timer\", ms, opts);\n}\n\n/**\n * Create a timer source with the `fromTimer` source factory.\n *\n * @param ms - Delay before the first tick in milliseconds.\n * @param opts - Optional period and source options.\n * @returns A source operator that emits tick counters.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromTimer } from \"@graphrefly/ts/sources\";\n *\n * const tick = graph().initNode(fromTimer(100), []);\n * ```\n * @remarks **Factory name:** This preserves the real `fromTimer` factory name in `describe()`.\n * @category sources\n */\nexport function fromTimer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"fromTimer\", ms, opts);\n}\n\n/**\n * Emit periodic tick counters.\n *\n * @param ms - Delay before the first tick and between later ticks in milliseconds.\n * @returns A source operator that emits `0`, `1`, `2`, and so on.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { interval } from \"@graphrefly/ts/sources\";\n *\n * const ticks = graph().initNode(interval(1000), []);\n * ```\n * @category sources\n */\nexport function interval(ms: number): Operator<never, number> {\n\treturn timerSource(\"interval\", ms, { period: ms });\n}\n\n/**\n * Lift a Promise (or thenable) to a single-value stream: one DATA then COMPLETE, or ERROR on\n * rejection. async pool (default pausable → a paused source buffers its late emit). Optional\n * `signal` aborts to ERROR.\n *\n * @param p - Promise or thenable to lift into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits one DATA value and COMPLETE, or ERROR on rejection/abort.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromPromise } from \"@graphrefly/ts/sources\";\n *\n * const user = graph().initNode(fromPromise(fetch(\"/user\").then((res) => res.json())), []);\n * ```\n * @category sources\n */\nexport function fromPromise<T>(\n\tp: Promise<T> | PromiseLike<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst signal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromPromise\",\n\t\t(ctx) => {\n\t\t\tlet settled = false;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\t// onAbort only runs from a `signal` listener / the `signal.aborted` guard → signal is defined.\n\t\t\t\tctx.down([[\"ERROR\", errorPayload((signal as AbortSignal).reason)]]);\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid Promise.resolve(p).then(\n\t\t\t\t(v) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * Read an async iterable: each value → DATA; COMPLETE when done; ERROR on failure. async pool.\n * Optional `signal` aborts the pump.\n *\n * @param iterable - Async iterable to pump into the graph.\n * @param opts - Optional abort signal and async source options.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromAsyncIter } from \"@graphrefly/ts/sources\";\n *\n * const stream = graph().initNode(fromAsyncIter(events()), []);\n * ```\n * @category sources\n */\nexport function fromAsyncIter<T>(\n\titerable: AsyncIterable<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst outerSignal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromAsyncIter\",\n\t\t(ctx) => {\n\t\t\tconst ac = new AbortController();\n\t\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet done = false;\n\t\t\tconst pump = async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const v of iterable) {\n\t\t\t\t\t\tif (ac.signal.aborted) break;\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"COMPLETE\"]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t} finally {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tvoid pump();\n\t\t\treturn () => {\n\t\t\t\tif (!done) ac.abort();\n\t\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * of: synchronous values — each argument as DATA, then COMPLETE. `of()` is the EMPTY source.\n *\n * @param values - Values to emit synchronously on activation.\n * @returns A source operator that emits each value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { of } from \"@graphrefly/ts/sources\";\n *\n * const values = graph().initNode(of(1, 2, 3), []);\n * ```\n * @category sources\n */\nexport function of<T = never>(...values: T[]): Operator<never, T> {\n\treturn source<T>(\n\t\t\"of\",\n\t\t(ctx) => {\n\t\t\tfor (const value of values) ctx.down([[\"DATA\", value]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Emit every value from a synchronous iterable.\n *\n * @param iterable - Iterable whose values are emitted in order.\n * @returns A source operator that emits every iterable value and then COMPLETE.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromIter } from \"@graphrefly/ts/sources\";\n *\n * const values = graph().initNode(fromIter([1, 2, 3]), []);\n * ```\n * @category sources\n */\nexport function fromIter<T>(iterable: Iterable<T>): Operator<never, T> {\n\treturn source<T>(\n\t\t\"fromIter\",\n\t\t(ctx) => {\n\t\t\tfor (const v of iterable) ctx.down([[\"DATA\", v]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Complete immediately without emitting DATA.\n *\n * @returns A source operator that emits COMPLETE on activation.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { empty } from \"@graphrefly/ts/sources\";\n *\n * const done = graph().initNode(empty(), []);\n * ```\n * @category sources\n */\nexport function empty<T = never>(): Operator<never, T> {\n\treturn source<T>(\n\t\t\"empty\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Activate and remain silent until deactivation.\n *\n * @returns A source operator that never emits DATA or terminal messages by itself.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { never } from \"@graphrefly/ts/sources\";\n *\n * const quiet = graph().initNode(never(), []);\n * ```\n * @category sources\n */\nexport function never<T = never>(): Operator<never, T> {\n\treturn source<T>(\"never\", () => undefined, { pool: \"sync\" });\n}\n\n/**\n * Terminate with ERROR on activation.\n *\n * @param err - Host-language error payload to normalize into a protocol ERROR payload.\n * @returns A source operator that emits ERROR.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { throwError } from \"@graphrefly/ts/sources\";\n *\n * const failed = graph().initNode(throwError(new Error(\"boom\")), []);\n * ```\n * @category sources\n */\nexport function throwError(err: unknown): Operator<never, never> {\n\treturn source<never>(\n\t\t\"throwError\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"ERROR\", errorPayload(err)]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a DOM-style event target. Each event becomes DATA; deactivation removes the listener.\n * External callbacks are source boundaries (D43), so no polling or operator-level async leaks in.\n *\n * @param target - Event target implementing `addEventListener` and `removeEventListener`.\n * @param type - Event type to subscribe to.\n * @param opts - Optional listener options and source options.\n * @returns A source operator that emits each event as DATA.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { fromEvent } from \"@graphrefly/ts/sources\";\n *\n * const clicks = graph().initNode(fromEvent<MouseEvent>(button, \"click\"), []);\n * ```\n * @category sources\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts: FromEventOptions = {},\n): Operator<never, T> {\n\tif (target == null || typeof target.addEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement addEventListener\");\n\t}\n\tif (typeof target.removeEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement removeEventListener\");\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new TypeError(\"fromEvent: event type must be a non-empty string\");\n\t}\n\treturn source<T>(\n\t\t\"fromEvent\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst handler = (event: unknown) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", event as T]]);\n\t\t\t};\n\t\t\ttarget.addEventListener(type, handler, opts);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\ttarget.removeEventListener(type, handler, opts);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a host push transport. The host owns network/native setup; this factory owns reactive\n * delivery and teardown only, preserving async-at-source-boundary discipline.\n * @param register - register value used by the helper.\n * @returns A Operator<never, T> value for the boundary or adapter.\n * @category sources\n * @example\n * ```ts\n * import { fromPushNotification } from \"@graphrefly/ts/sources\";\n * ```\n */\nexport function fromPushNotification<T = unknown>(register: PushRegister<T>): Operator<never, T> {\n\tif (typeof register !== \"function\") {\n\t\tthrow new TypeError(\"fromPushNotification: register must be a function\");\n\t}\n\treturn source<T>(\n\t\t\"fromPushNotification\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst deliver = (payload: T) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", payload]]);\n\t\t\t};\n\t\t\tconst unsubscribe = register(deliver);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (typeof unsubscribe === \"function\") unsubscribe();\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Coerce a {@link NodeInput}`<T>` to a `Node<T>` (D43 — coercion prerequisite for the CSP-2.7\n * higher-order operators). An existing Node passes through; a thenable → {@link fromPromise};\n * an async iterable → {@link fromAsyncIter}; with `{iter:true}` a sync iterable →\n * {@link fromIter}; everything else → {@link of}. Coerced nodes are bare (use\n * `opts.dispatcher` to bind one, default = process-global D26).\n * @param input - Input value to project or validate.\n * @param opts - Options that configure the helper.\n * @returns A Node<T> value for the boundary or adapter.\n * @category sources\n * @example\n * ```ts\n * import { fromAny } from \"@graphrefly/ts/sources\";\n * ```\n */\nexport function fromAny<T>(\n\tinput: NodeInput<T>,\n\topts: NodeOptions<T> & { iter?: boolean } = {},\n): Node<T> {\n\tif (isNode(input)) return input as Node<T>;\n\tconst { iter, ...nodeOpts } = opts;\n\tif (isThenable(input)) {\n\t\treturn initNode(fromPromise(input as PromiseLike<T>), [], nodeOpts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as {\n\t\t\t[Symbol.asyncIterator]?: unknown;\n\t\t\t[Symbol.iterator]?: unknown;\n\t\t};\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn initNode(fromAsyncIter(input as AsyncIterable<T>), [], nodeOpts);\n\t\t}\n\t\tif (iter === true && typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn initNode(fromIter(input as Iterable<T>), [], nodeOpts);\n\t\t}\n\t}\n\treturn initNode(of(input as T), [], nodeOpts);\n}\n\n/**\n * Resolve the first DATA from a Node as a Promise.\n *\n * @param source - Node to subscribe to.\n * @returns A Promise for the first DATA value, or a rejection on ERROR/early completion.\n * @example\n * ```ts\n * import { graph } from \"@graphrefly/ts/graph\";\n * import { firstValueFrom } from \"@graphrefly/ts/sources\";\n *\n * const g = graph();\n * await firstValueFrom(g.state(1));\n * ```\n * @remarks Host-boundary escape hatch only. Do not call it from reactive node bodies; use graph\n * deps/messages there so the topology remains declarative and inspectable.\n * @category sources\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet shouldUnsub = false;\n\t\tlet unsub: (() => void) | undefined;\n\t\tconst finish = (f: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tf();\n\t\t\tif (unsub) {\n\t\t\t\tunsub();\n\t\t\t\tunsub = undefined;\n\t\t\t} else {\n\t\t\t\tshouldUnsub = true;\n\t\t\t}\n\t\t};\n\t\tunsub = source.subscribe((msg) => {\n\t\t\tif (msg[0] === \"DATA\") {\n\t\t\t\tfinish(() => resolve(msg[1] as T));\n\t\t\t} else if (msg[0] === \"ERROR\") {\n\t\t\t\tfinish(() => reject(msg[1]));\n\t\t\t} else if (msg[0] === \"COMPLETE\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: completed without DATA\")));\n\t\t\t} else if (msg[0] === \"TEARDOWN\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: torn down without DATA\")));\n\t\t\t}\n\t\t});\n\t\tif (shouldUnsub) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t}\n\t});\n}\n\nfunction singleFromAnyValue<T>(value: T): T {\n\tif (value === undefined) {\n\t\tthrow new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\");\n\t}\n\treturn value;\n}\n\nasync function firstFromAsyncIterable<T>(input: AsyncIterable<T>): Promise<T> {\n\tconst iter = input[Symbol.asyncIterator]();\n\tconst { value, done } = await iter.next();\n\tif (done) {\n\t\tawait iter.return?.();\n\t\tthrow new Error(\"singleFromAny: factory returned empty async iterable\");\n\t}\n\ttry {\n\t\tawait iter.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn value as T;\n}\n\nfunction firstFromIterable<T>(input: Iterable<T>): Promise<T> {\n\tconst iter = input[Symbol.iterator]();\n\tconst { value, done } = iter.next();\n\tif (done) {\n\t\titer.return?.();\n\t\treturn Promise.reject(new Error(\"singleFromAny: factory returned empty iterable\"));\n\t}\n\ttry {\n\t\titer.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn Promise.resolve(value as T);\n}\n\nfunction nodeInputToPromise<T>(input: NodeInput<T>, opts: { iter?: boolean }): Promise<T> {\n\tif (isThenable(input)) return Promise.resolve(input as PromiseLike<T>).then(singleFromAnyValue);\n\tif (isNode(input)) return firstValueFrom(input as Node<T>).then(singleFromAnyValue);\n\tif (isAsyncIterable<T>(input)) return firstFromAsyncIterable(input).then(singleFromAnyValue);\n\tif (opts.iter === true && isIterable<T>(input)) {\n\t\treturn firstFromIterable(input).then(singleFromAnyValue);\n\t}\n\tif (input === undefined) {\n\t\treturn Promise.reject(new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\"));\n\t}\n\treturn Promise.resolve(singleFromAnyValue(input as T));\n}\n\n/**\n * Keyed singleflight over {@link NodeInput}.\n *\n * @param factory - Function that produces a value, iterable, promise, or node for each key.\n * @param opts - Optional key canonicalizer and iterable handling.\n * @returns A memoizing loader keyed by the transformed key.\n * @example\n * ```ts\n * const loadUser = singleFromAny((id: string) => fetch(`/api/users/${id}`).then((r) => r.json()));\n * ```\n * @remarks Host-boundary helper only. It deduplicates external calls and does not create graph\n * topology or act as a graph operator.\n * @category sources\n */\nexport function singleFromAny<K, T>(\n\tfactory: (key: K) => NodeInput<T>,\n\topts: SingleFromAnyOptions<K> = {},\n): (key: K) => Promise<T> {\n\tconst keyOf = opts.keyOf ?? ((key: K): unknown => key);\n\tconst inFlight = new Map<unknown, Promise<T>>();\n\n\treturn (key: K): Promise<T> => {\n\t\tconst dedupeKey = keyOf(key);\n\t\tconst existing = inFlight.get(dedupeKey);\n\t\tif (existing) return existing;\n\n\t\tlet resolvePending!: (value: T) => void;\n\t\tlet rejectPending!: (reason: unknown) => void;\n\t\tlet tracked!: Promise<T>;\n\t\tconst cleanup = (): void => {\n\t\t\tif (inFlight.get(dedupeKey) === tracked) inFlight.delete(dedupeKey);\n\t\t};\n\t\tconst pending = new Promise<T>((resolve, reject) => {\n\t\t\tresolvePending = resolve;\n\t\t\trejectPending = reject;\n\t\t});\n\t\ttracked = pending.then(\n\t\t\t(value) => {\n\t\t\t\tcleanup();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tcleanup();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tinFlight.set(dedupeKey, tracked);\n\t\ttry {\n\t\t\tnodeInputToPromise(factory(key), opts).then(resolvePending, rejectPending);\n\t\t} catch (e) {\n\t\t\trejectPending(e);\n\t\t}\n\t\treturn tracked;\n\t};\n}\n"],"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;;;AC2CO,IAAM,WAAW;AAWjB,SAAS,sBAAsB,GAAqB;AAC1D,SAAO,MAAM,YAAY,OAAO,MAAM;AACvC;AAYO,SAAS,aAAa,QAAiB,WAAW,iCAA0C;AAClG,SAAO,sBAAsB,MAAM,IAAI,IAAI,MAAM,QAAQ,IAAI;AAC9D;AAEO,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAM7B,IAAM,OAAoC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,OAAO;AAAA,EACP,UAAU;AACX;AAaO,SAAS,YAAY,GAAwB;AACnD,SAAO,KAA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