@graphrefly/ts 0.0.0

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +9015 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +678 -0
  5. package/dist/adapters/index.d.ts +678 -0
  6. package/dist/adapters/index.js +2894 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/adapters/observe-storage.cjs +260 -0
  9. package/dist/adapters/observe-storage.cjs.map +1 -0
  10. package/dist/adapters/observe-storage.d.cts +77 -0
  11. package/dist/adapters/observe-storage.d.ts +77 -0
  12. package/dist/adapters/observe-storage.js +161 -0
  13. package/dist/adapters/observe-storage.js.map +1 -0
  14. package/dist/append-log-DisvEReb.d.cts +189 -0
  15. package/dist/append-log-DzKMmjxx.d.ts +189 -0
  16. package/dist/chunk-2ILL7HQI.js +1189 -0
  17. package/dist/chunk-2ILL7HQI.js.map +1 -0
  18. package/dist/chunk-4VLAQHZI.js +330 -0
  19. package/dist/chunk-4VLAQHZI.js.map +1 -0
  20. package/dist/chunk-6PHB5CJS.js +229 -0
  21. package/dist/chunk-6PHB5CJS.js.map +1 -0
  22. package/dist/chunk-COHO25CZ.js +2449 -0
  23. package/dist/chunk-COHO25CZ.js.map +1 -0
  24. package/dist/chunk-D6BG7U6A.js +161 -0
  25. package/dist/chunk-D6BG7U6A.js.map +1 -0
  26. package/dist/chunk-DJC4CHLQ.js +818 -0
  27. package/dist/chunk-DJC4CHLQ.js.map +1 -0
  28. package/dist/chunk-DK554R7P.js +67 -0
  29. package/dist/chunk-DK554R7P.js.map +1 -0
  30. package/dist/chunk-DKP56CSW.js +322 -0
  31. package/dist/chunk-DKP56CSW.js.map +1 -0
  32. package/dist/chunk-G4M3NHRJ.js +688 -0
  33. package/dist/chunk-G4M3NHRJ.js.map +1 -0
  34. package/dist/chunk-GAJW5I5P.js +1 -0
  35. package/dist/chunk-GAJW5I5P.js.map +1 -0
  36. package/dist/chunk-GDL26N2T.js +282 -0
  37. package/dist/chunk-GDL26N2T.js.map +1 -0
  38. package/dist/chunk-GTPCOEOZ.js +741 -0
  39. package/dist/chunk-GTPCOEOZ.js.map +1 -0
  40. package/dist/chunk-H2HTHFVN.js +1 -0
  41. package/dist/chunk-H2HTHFVN.js.map +1 -0
  42. package/dist/chunk-HDRL4VQQ.js +218 -0
  43. package/dist/chunk-HDRL4VQQ.js.map +1 -0
  44. package/dist/chunk-I3IHOHCJ.js +2267 -0
  45. package/dist/chunk-I3IHOHCJ.js.map +1 -0
  46. package/dist/chunk-JIMUDQN3.js +965 -0
  47. package/dist/chunk-JIMUDQN3.js.map +1 -0
  48. package/dist/chunk-JR4IKCR2.js +462 -0
  49. package/dist/chunk-JR4IKCR2.js.map +1 -0
  50. package/dist/chunk-K3FXTC3I.js +165 -0
  51. package/dist/chunk-K3FXTC3I.js.map +1 -0
  52. package/dist/chunk-OOEN33FB.js +65 -0
  53. package/dist/chunk-OOEN33FB.js.map +1 -0
  54. package/dist/chunk-PKVBHGBM.js +554 -0
  55. package/dist/chunk-PKVBHGBM.js.map +1 -0
  56. package/dist/chunk-RIIOUTGM.js +1857 -0
  57. package/dist/chunk-RIIOUTGM.js.map +1 -0
  58. package/dist/chunk-SCRFRCGR.js +33 -0
  59. package/dist/chunk-SCRFRCGR.js.map +1 -0
  60. package/dist/chunk-SWTLEQL6.js +53 -0
  61. package/dist/chunk-SWTLEQL6.js.map +1 -0
  62. package/dist/chunk-SZAETNNA.js +1 -0
  63. package/dist/chunk-SZAETNNA.js.map +1 -0
  64. package/dist/chunk-TEW47IVR.js +49 -0
  65. package/dist/chunk-TEW47IVR.js.map +1 -0
  66. package/dist/chunk-Y3ZLRGHC.js +1482 -0
  67. package/dist/chunk-Y3ZLRGHC.js.map +1 -0
  68. package/dist/chunk-Z2ANQ6JW.js +149 -0
  69. package/dist/chunk-Z2ANQ6JW.js.map +1 -0
  70. package/dist/codec-BB7p8fJc.d.cts +38 -0
  71. package/dist/codec-BB7p8fJc.d.ts +38 -0
  72. package/dist/composition/index.cjs +2505 -0
  73. package/dist/composition/index.cjs.map +1 -0
  74. package/dist/composition/index.d.cts +95 -0
  75. package/dist/composition/index.d.ts +95 -0
  76. package/dist/composition/index.js +19 -0
  77. package/dist/composition/index.js.map +1 -0
  78. package/dist/core/index.cjs +2475 -0
  79. package/dist/core/index.cjs.map +1 -0
  80. package/dist/core/index.d.cts +25 -0
  81. package/dist/core/index.d.ts +25 -0
  82. package/dist/core/index.js +74 -0
  83. package/dist/core/index.js.map +1 -0
  84. package/dist/cqrs/index.cjs +595 -0
  85. package/dist/cqrs/index.cjs.map +1 -0
  86. package/dist/cqrs/index.d.cts +200 -0
  87. package/dist/cqrs/index.d.ts +200 -0
  88. package/dist/cqrs/index.js +557 -0
  89. package/dist/cqrs/index.js.map +1 -0
  90. package/dist/data-structures/index.cjs +4277 -0
  91. package/dist/data-structures/index.cjs.map +1 -0
  92. package/dist/data-structures/index.d.cts +22 -0
  93. package/dist/data-structures/index.d.ts +22 -0
  94. package/dist/data-structures/index.js +31 -0
  95. package/dist/data-structures/index.js.map +1 -0
  96. package/dist/describe-BZb7AS2y.d.ts +57 -0
  97. package/dist/describe-Ciu8SUnN.d.cts +57 -0
  98. package/dist/graph/index.cjs +7832 -0
  99. package/dist/graph/index.cjs.map +1 -0
  100. package/dist/graph/index.d.cts +251 -0
  101. package/dist/graph/index.d.ts +251 -0
  102. package/dist/graph/index.js +131 -0
  103. package/dist/graph/index.js.map +1 -0
  104. package/dist/graph-DfdF9zy4.d.ts +666 -0
  105. package/dist/graph-s23RbbFO.d.cts +666 -0
  106. package/dist/index-CAEmLCYF.d.cts +166 -0
  107. package/dist/index-SnzZu3x7.d.ts +166 -0
  108. package/dist/index.cjs +15409 -0
  109. package/dist/index.cjs.map +1 -0
  110. package/dist/index.d.cts +23 -0
  111. package/dist/index.d.ts +23 -0
  112. package/dist/index.js +582 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/messages-BZqrGGm1.d.cts +55 -0
  115. package/dist/messages-BZqrGGm1.d.ts +55 -0
  116. package/dist/messaging/index.cjs +818 -0
  117. package/dist/messaging/index.cjs.map +1 -0
  118. package/dist/messaging/index.d.cts +235 -0
  119. package/dist/messaging/index.d.ts +235 -0
  120. package/dist/messaging/index.js +767 -0
  121. package/dist/messaging/index.js.map +1 -0
  122. package/dist/observe-event-log-0SVsx7JG.d.cts +88 -0
  123. package/dist/observe-event-log-Dnm76owp.d.ts +88 -0
  124. package/dist/operators/index.cjs +3774 -0
  125. package/dist/operators/index.cjs.map +1 -0
  126. package/dist/operators/index.d.cts +308 -0
  127. package/dist/operators/index.d.ts +308 -0
  128. package/dist/operators/index.js +112 -0
  129. package/dist/operators/index.js.map +1 -0
  130. package/dist/orchestration/index.cjs +3541 -0
  131. package/dist/orchestration/index.cjs.map +1 -0
  132. package/dist/orchestration/index.d.cts +302 -0
  133. package/dist/orchestration/index.d.ts +302 -0
  134. package/dist/orchestration/index.js +1004 -0
  135. package/dist/orchestration/index.js.map +1 -0
  136. package/dist/patterns/index.cjs +1045 -0
  137. package/dist/patterns/index.cjs.map +1 -0
  138. package/dist/patterns/index.d.cts +39 -0
  139. package/dist/patterns/index.d.ts +39 -0
  140. package/dist/patterns/index.js +33 -0
  141. package/dist/patterns/index.js.map +1 -0
  142. package/dist/reactive-collection-BxBqtIOE.d.cts +344 -0
  143. package/dist/reactive-collection-Cb1II1Fi.d.ts +344 -0
  144. package/dist/reactive-collection-storage-BNiEc-Gd.d.ts +217 -0
  145. package/dist/reactive-collection-storage-D-KmjE0J.d.cts +217 -0
  146. package/dist/reactive-map-BcB4KsQR.d.ts +256 -0
  147. package/dist/reactive-map-D-g3dv8I.d.cts +256 -0
  148. package/dist/read-through-B1CYPfq_.d.cts +82 -0
  149. package/dist/read-through-DwyJhGs1.d.ts +82 -0
  150. package/dist/render/index.cjs +250 -0
  151. package/dist/render/index.cjs.map +1 -0
  152. package/dist/render/index.d.cts +58 -0
  153. package/dist/render/index.d.ts +58 -0
  154. package/dist/render/index.js +20 -0
  155. package/dist/render/index.js.map +1 -0
  156. package/dist/resilience-Dig3Q7n0.d.cts +45 -0
  157. package/dist/resilience-Dig3Q7n0.d.ts +45 -0
  158. package/dist/semantic-memory-graph-BYoIlP35.d.cts +356 -0
  159. package/dist/semantic-memory-graph-CxyXLms3.d.ts +356 -0
  160. package/dist/solutions/index.cjs +3249 -0
  161. package/dist/solutions/index.cjs.map +1 -0
  162. package/dist/solutions/index.d.cts +520 -0
  163. package/dist/solutions/index.d.ts +520 -0
  164. package/dist/solutions/index.js +31 -0
  165. package/dist/solutions/index.js.map +1 -0
  166. package/dist/sources/browser.cjs +3095 -0
  167. package/dist/sources/browser.cjs.map +1 -0
  168. package/dist/sources/browser.d.cts +39 -0
  169. package/dist/sources/browser.d.ts +39 -0
  170. package/dist/sources/browser.js +137 -0
  171. package/dist/sources/browser.js.map +1 -0
  172. package/dist/sources/index.cjs +3021 -0
  173. package/dist/sources/index.cjs.map +1 -0
  174. package/dist/sources/index.d.cts +7 -0
  175. package/dist/sources/index.d.ts +7 -0
  176. package/dist/sources/index.js +63 -0
  177. package/dist/sources/index.js.map +1 -0
  178. package/dist/sources/node.cjs +675 -0
  179. package/dist/sources/node.cjs.map +1 -0
  180. package/dist/sources/node.d.cts +109 -0
  181. package/dist/sources/node.d.ts +109 -0
  182. package/dist/sources/node.js +639 -0
  183. package/dist/sources/node.js.map +1 -0
  184. package/dist/storage/browser.cjs +777 -0
  185. package/dist/storage/browser.cjs.map +1 -0
  186. package/dist/storage/browser.d.cts +40 -0
  187. package/dist/storage/browser.d.ts +40 -0
  188. package/dist/storage/browser.js +275 -0
  189. package/dist/storage/browser.js.map +1 -0
  190. package/dist/storage/index.cjs +1989 -0
  191. package/dist/storage/index.cjs.map +1 -0
  192. package/dist/storage/index.d.cts +92 -0
  193. package/dist/storage/index.d.ts +92 -0
  194. package/dist/storage/index.js +161 -0
  195. package/dist/storage/index.js.map +1 -0
  196. package/dist/storage/node.cjs +898 -0
  197. package/dist/storage/node.cjs.map +1 -0
  198. package/dist/storage/node.d.cts +66 -0
  199. package/dist/storage/node.d.ts +66 -0
  200. package/dist/storage/node.js +402 -0
  201. package/dist/storage/node.js.map +1 -0
  202. package/dist/testing/index.cjs +95 -0
  203. package/dist/testing/index.cjs.map +1 -0
  204. package/dist/testing/index.d.cts +20 -0
  205. package/dist/testing/index.d.ts +20 -0
  206. package/dist/testing/index.js +8 -0
  207. package/dist/testing/index.js.map +1 -0
  208. package/dist/types-bNMSWKqF.d.cts +732 -0
  209. package/dist/types-h12mNYbq.d.ts +732 -0
  210. package/package.json +250 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/orchestration/index.ts","../../src/protocol/messages.ts","../../src/ctx/types.ts","../../src/graph/resilience.ts","../../src/batch/boundary.ts","../../src/batch/batch.ts","../../src/dispatcher/index.ts","../../src/graph/environment.ts","../../src/node/core.ts","../../src/json/codec.ts","../../src/node/versioning.ts","../../src/node/node.ts","../../src/graph/checkpoint.ts","../../src/graph/operators.ts","../../src/graph/sources.ts","../../src/graph/time.ts"],"sourcesContent":["/**\n * Reusable application-infrastructure orchestration namespace.\n *\n * Retained root orchestration helpers land here only after B63 re-derives them\n * onto clean-slate graph surfaces.\n */\n\nimport { depBatch, type NodeFn } from \"../ctx/types.js\";\nimport type { Graph, TopologyGroup } from \"../graph/graph.js\";\nimport {\n\ttype BackoffPolicy,\n\tbackoffDelayMs,\n\tnextRetryDelayMs,\n\tnoBackoff,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tretryPolicy,\n\tshouldRetry,\n} from \"../graph/resilience.js\";\nimport { timeout as timeoutOperator } from \"../graph/time.js\";\nimport type { Node } from \"../node/node.js\";\n\nexport {\n\ttype BackoffPolicy,\n\tbackoffDelayMs,\n\tnoBackoff,\n\tnextRetryDelayMs,\n\tretryPolicy,\n\ttype RetryPolicy,\n\ttype RetryStatus,\n\tshouldRetry,\n};\n\nexport type ResilienceEvent =\n\t| { readonly kind: \"attempt\"; readonly attempt: number }\n\t| {\n\t\t\treadonly kind: \"retry\";\n\t\t\treadonly attempt: number;\n\t\t\treadonly delayMs: number;\n\t\t\treadonly error: unknown;\n\t }\n\t| { readonly kind: \"success\"; readonly attempt?: number }\n\t| { readonly kind: \"failure\"; readonly attempt?: number; readonly error: unknown }\n\t| { readonly kind: \"exhausted\"; readonly attempt: number; readonly error: unknown };\n\nexport interface RetryStatusBundle {\n\treadonly status: Node<RetryStatus>;\n\treadonly errors: Node<unknown>;\n}\n\nexport interface BreakerOptions {\n\treadonly failureThreshold: number;\n\treadonly resetAfterMs?: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface BreakerStatus {\n\treadonly state: \"closed\" | \"open\" | \"half-open\";\n\treadonly failures: number;\n\treadonly openedAtMs?: number;\n}\n\nexport interface BreakerBundle {\n\treadonly status: Node<BreakerStatus>;\n\treadonly allowed: Node<boolean>;\n}\n\nexport interface RateLimitOptions {\n\treadonly max: number;\n\treadonly windowMs: number;\n\treadonly now?: () => number;\n\treadonly name?: string;\n}\n\nexport interface RateLimitStatus {\n\treadonly allowed: number;\n\treadonly dropped: number;\n\treadonly remaining: number;\n\treadonly resetAtMs: number;\n}\n\nexport interface RateLimitBundle<T> {\n\treadonly allowed: Node<T>;\n\treadonly dropped: Node<T>;\n\treadonly status: Node<RateLimitStatus>;\n}\n\ntype RateLimitEvent<T> =\n\t| { readonly kind: \"allowed\"; readonly value: T; readonly status: RateLimitStatus }\n\t| { readonly kind: \"dropped\"; readonly value: T; readonly status: RateLimitStatus };\n\nexport interface TimeoutBundle<T> {\n\treadonly node: Node<T>;\n\treadonly status: Node<\"running\" | \"completed\" | \"errored\">;\n\treadonly errors: Node<unknown>;\n}\n\n/** D136 graph-visible process command fact. */\nexport interface ProcessCommand<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Event draft returned by a ProcessBundle reducer before runtime ordering. */\nexport interface ProcessEventDraft<T = unknown> {\n\treadonly id?: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Ordered process event fact. These are DATA facts, not protocol messages. */\nexport interface ProcessEvent<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly commandId: string;\n\treadonly commandType: string;\n\treadonly payload: T;\n\treadonly timestampMs: number;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Effect-request draft emitted by a ProcessBundle reducer for visible effect runners. */\nexport interface ProcessEffectRequestDraft<T = unknown> {\n\treadonly id?: string;\n\treadonly type: string;\n\treadonly payload: T;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\n/** Ordered effect-request fact. Effect runners consume this node in later slices. */\nexport interface ProcessEffectRequest<T = unknown> {\n\treadonly id: string;\n\treadonly type: string;\n\treadonly seq: number;\n\treadonly cursor: number;\n\treadonly commandId: string;\n\treadonly commandType: string;\n\treadonly payload: T;\n\treadonly timestampMs: number;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ProcessEffectCommandType =\n\t| \"effect.result\"\n\t| \"effect.failure\"\n\t| \"effect.cancel\"\n\t| \"effect.timeout\";\n\ninterface ProcessEffectOutcomeBase {\n\treadonly effectId: string;\n\treadonly effectType: string;\n\treadonly processId?: string;\n\treadonly correlationId?: string;\n\treadonly causationId?: string;\n\treadonly commandId?: string;\n\treadonly metadata?: Record<string, unknown>;\n}\n\nexport type ProcessEffectOutcome<TResult = unknown> =\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"result\"; readonly value: TResult })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"failure\"; readonly error: unknown })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"cancel\"; readonly reason?: string })\n\t| (ProcessEffectOutcomeBase & { readonly kind: \"timeout\"; readonly error: unknown });\n\nexport type ProcessEffectCommandPayload<TResult = unknown> =\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"result\";\n\t\t\treadonly value: TResult;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"failure\";\n\t\t\treadonly error: unknown;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"cancel\";\n\t\t\treadonly reason?: string;\n\t })\n\t| (Omit<ProcessEffectOutcomeBase, \"commandId\"> & {\n\t\t\treadonly kind: \"timeout\";\n\t\t\treadonly error: unknown;\n\t });\n\nexport type ProcessErrorCode =\n\t| \"malformed-command\"\n\t| \"reducer-threw\"\n\t| \"clock-threw\"\n\t| \"malformed-state\"\n\t| \"malformed-event\"\n\t| \"malformed-effect\";\n\n/** Graph-visible ProcessBundle error fact. These are DATA facts, not protocol ERROR. */\nexport interface ProcessError {\n\treadonly code: ProcessErrorCode;\n\treadonly message: string;\n\treadonly command?: unknown;\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly cursor: ProcessCursor;\n}\n\n/** Accepted/rejected command outcome projected from the ProcessBundle runtime. */\nexport interface ProcessStatus {\n\treadonly state: \"accepted\" | \"rejected\";\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly eventCount: number;\n\treadonly effectCount: number;\n\treadonly errorCode?: ProcessErrorCode;\n\treadonly cursor: ProcessCursor;\n}\n\nexport interface ProcessEffectRunnerStatus {\n\treadonly state: \"requested\" | \"commanded\" | \"rejected\";\n\treadonly effectId?: string;\n\treadonly effectType?: string;\n\treadonly commandId?: string;\n\treadonly commandType?: ProcessEffectCommandType;\n\treadonly requested: number;\n\treadonly commanded: number;\n\treadonly rejected: number;\n}\n\nexport interface ProcessEffectRunnerError {\n\treadonly code: \"malformed-outcome\";\n\treadonly message: string;\n\treadonly outcome?: unknown;\n\treadonly effectId?: string;\n\treadonly effectType?: string;\n}\n\n/** Ordered audit fact for one attempted command reduction. */\nexport interface ProcessAuditRecord {\n\treadonly seq: number;\n\treadonly commandId?: string;\n\treadonly commandType?: string;\n\treadonly outcome: \"success\" | \"failure\";\n\treadonly eventIds: readonly string[];\n\treadonly eventTypes: readonly string[];\n\treadonly effectIds: readonly string[];\n\treadonly effectTypes: readonly string[];\n\treadonly errorCode?: ProcessErrorCode;\n\treadonly errorMessage?: string;\n\treadonly cursor: ProcessCursor;\n}\n\n/** Monotonic graph-visible ProcessBundle cursor counters. */\nexport interface ProcessCursor {\n\treadonly eventSeq: number;\n\treadonly effectSeq: number;\n\treadonly commandCount: number;\n\treadonly errorCount: number;\n\treadonly auditSeq: number;\n}\n\n/** Internal runtime stream fact exposed through ProcessBundle projection nodes. */\ntype ProcessRuntimeFact<TState = unknown, TEvent = unknown, TEffect = unknown> =\n\t| { readonly kind: \"state\"; readonly state: TState; readonly cursor: ProcessCursor }\n\t| { readonly kind: \"event\"; readonly event: ProcessEvent<TEvent> }\n\t| { readonly kind: \"effect-request\"; readonly effect: ProcessEffectRequest<TEffect> }\n\t| { readonly kind: \"status\"; readonly status: ProcessStatus }\n\t| { readonly kind: \"error\"; readonly error: ProcessError }\n\t| { readonly kind: \"audit\"; readonly audit: ProcessAuditRecord }\n\t| { readonly kind: \"cursor\"; readonly cursor: ProcessCursor };\n\ntype ProcessEffectRunnerFact<TResult = unknown> =\n\t| { readonly kind: \"outcome\"; readonly outcome: ProcessEffectOutcome<TResult> }\n\t| {\n\t\t\treadonly kind: \"command\";\n\t\t\treadonly command: ProcessCommand<ProcessEffectCommandPayload<TResult>>;\n\t }\n\t| { readonly kind: \"error\"; readonly error: ProcessEffectRunnerError };\n\n/** Reducer result: next process state plus optional event/effect-request drafts. */\nexport interface ProcessReduction<TState = unknown, TEvent = unknown, TEffect = unknown> {\n\treadonly state: TState;\n\treadonly events?: readonly ProcessEventDraft<TEvent>[];\n\treadonly effects?: readonly ProcessEffectRequestDraft<TEffect>[];\n}\n\n/** Sync ProcessBundle reducer. Async effects belong in graph-visible adapters, not here. */\nexport type ProcessReducer<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> = (command: ProcessCommand<TCommand>, state: TState) => ProcessReduction<TState, TEvent, TEffect>;\n\n/** Options for a D136 facts-plus-reducer ProcessBundle. */\nexport interface ProcessBundleOptions<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> {\n\treadonly name?: string;\n\treadonly initialState: TState;\n\treadonly reduce: ProcessReducer<TCommand, TState, TEvent, TEffect>;\n\treadonly now?: () => number;\n}\n\n/** D136 facts-plus-reducer process bundle. It is not a workflow engine or hidden runtime owner. */\nexport interface ProcessBundle<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n> {\n\treadonly command: Node<ProcessCommand<TCommand>>;\n\treadonly events: Node<ProcessEvent<TEvent>>;\n\treadonly state: Node<TState>;\n\treadonly audit: Node<ProcessAuditRecord>;\n\treadonly effectRequests: Node<ProcessEffectRequest<TEffect>>;\n\treadonly status: Node<ProcessStatus>;\n\treadonly errors: Node<ProcessError>;\n\treadonly cursor: Node<ProcessCursor>;\n\tdispatch(command: ProcessCommand<TCommand>): ProcessCommand<TCommand>;\n\t/** Release only graph-owned retain roots; process facts/topology/cache/state remain ordinary graph data. */\n\trelease(): void;\n}\n\nexport interface ProcessEffectRunnerOptions<TResult = unknown> {\n\treadonly name?: string;\n\treadonly outcomes: readonly Node<ProcessEffectOutcome<TResult>>[];\n}\n\nexport interface ProcessEffectRunnerBundle<TEffect = unknown, TResult = unknown> {\n\treadonly requests: Node<ProcessEffectRequest<TEffect>>;\n\treadonly outcomes: Node<ProcessEffectOutcome<TResult>>;\n\treadonly commands: Node<ProcessCommand<ProcessEffectCommandPayload<TResult>>>;\n\treadonly status: Node<ProcessEffectRunnerStatus>;\n\treadonly errors: Node<ProcessEffectRunnerError>;\n\trelease(): void;\n}\n\ninterface AttachedProcessCommandSources<TCommand> {\n\tsources: Node<ProcessCommand<TCommand>>[];\n}\n\nconst processCommandSources = new WeakMap<\n\tProcessBundle<unknown, unknown, unknown, unknown>,\n\tAttachedProcessCommandSources<unknown>\n>();\n\nexport function retryStatusBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: { name?: string; policy?: RetryPolicy } = {},\n): RetryStatusBundle {\n\tconst policy = opts.policy ?? retryPolicy();\n\tconst name = opts.name ?? \"retry\";\n\tconst status = graph.node<RetryStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<RetryStatus>() ??\n\t\t\t\t({ state: \"idle\", attempt: 0, maxAttempts: policy.maxAttempts } satisfies RetryStatus);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"attempt\") {\n\t\t\t\t\tnext = { state: \"running\", attempt: event.attempt, maxAttempts: policy.maxAttempts };\n\t\t\t\t} else if (event.kind === \"retry\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"waiting\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: event.delayMs,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"success\") {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"succeeded\",\n\t\t\t\t\t\tattempt: event.attempt ?? next.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t};\n\t\t\t\t} else if (event.kind === \"failure\") {\n\t\t\t\t\tconst attempt = event.attempt ?? next.attempt;\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: shouldRetry(policy, attempt) ? \"failed\" : \"exhausted\",\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t\tdelayMs: shouldRetry(policy, attempt)\n\t\t\t\t\t\t\t? nextRetryDelayMs(policy, attempt + 1)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\tnext = {\n\t\t\t\t\t\tstate: \"exhausted\",\n\t\t\t\t\t\tattempt: event.attempt,\n\t\t\t\t\t\tmaxAttempts: policy.maxAttempts,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"retryStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (\"error\" in event) ctx.down([[\"DATA\", event.error]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"retryErrors\" },\n\t);\n\treturn { status, errors };\n}\n\nexport function breakerBundle(\n\tgraph: Graph,\n\tevents: Node<ResilienceEvent>,\n\topts: BreakerOptions,\n): BreakerBundle {\n\tif (!Number.isInteger(opts.failureThreshold) || opts.failureThreshold <= 0) {\n\t\tthrow new RangeError(\"breakerBundle: failureThreshold must be a positive integer\");\n\t}\n\tconst name = opts.name ?? \"breaker\";\n\tconst now = opts.now ?? Date.now;\n\tconst status = graph.node<BreakerStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tlet next =\n\t\t\t\tctx.state.get<BreakerStatus>() ??\n\t\t\t\t({ state: \"closed\", failures: 0 } satisfies BreakerStatus);\n\t\t\tif (\n\t\t\t\tnext.state === \"open\" &&\n\t\t\t\topts.resetAfterMs !== undefined &&\n\t\t\t\tnext.openedAtMs !== undefined &&\n\t\t\t\tnow() - next.openedAtMs >= opts.resetAfterMs\n\t\t\t) {\n\t\t\t\tnext = { ...next, state: \"half-open\" };\n\t\t\t}\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst event = raw as ResilienceEvent;\n\t\t\t\tif (event.kind === \"success\") {\n\t\t\t\t\tnext = { state: \"closed\", failures: 0 };\n\t\t\t\t} else if (event.kind === \"failure\" || event.kind === \"exhausted\") {\n\t\t\t\t\tconst failures = next.failures + 1;\n\t\t\t\t\tnext =\n\t\t\t\t\t\tfailures >= opts.failureThreshold\n\t\t\t\t\t\t\t? { state: \"open\", failures, openedAtMs: now() }\n\t\t\t\t\t\t\t: { ...next, failures };\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(next);\n\t\t\tctx.down([[\"DATA\", next]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"breakerStatus\" },\n\t);\n\tconst allowed = graph.node<boolean>(\n\t\t[status],\n\t\t(ctx) => {\n\t\t\tconst statusBatch = depBatch(ctx, 0) ?? [];\n\t\t\tfor (const value of statusBatch) {\n\t\t\t\tctx.down([[\"DATA\", (value as BreakerStatus).state !== \"open\"]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"breakerAllowed\" },\n\t);\n\treturn { status, allowed };\n}\n\nexport function rateLimitBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\topts: RateLimitOptions,\n): RateLimitBundle<T> {\n\tif (!Number.isInteger(opts.max) || opts.max <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: max must be a positive integer\");\n\t}\n\tif (!Number.isFinite(opts.windowMs) || opts.windowMs <= 0) {\n\t\tthrow new RangeError(\"rateLimitBundle: windowMs must be positive\");\n\t}\n\tconst now = opts.now ?? Date.now;\n\tconst name = opts.name ?? \"rateLimit\";\n\tconst events = graph.node<RateLimitEvent<T>>(\n\t\t[source],\n\t\t(ctx) => {\n\t\t\ttype State = { count: number; resetAtMs: number; allowed: number; dropped: number };\n\t\t\tconst current = now();\n\t\t\tlet state =\n\t\t\t\tctx.state.get<State>() ??\n\t\t\t\t({ count: 0, resetAtMs: current + opts.windowMs, allowed: 0, dropped: 0 } satisfies State);\n\t\t\tif (current >= state.resetAtMs) {\n\t\t\t\tstate = { ...state, count: 0, resetAtMs: current + opts.windowMs };\n\t\t\t}\n\t\t\tfor (const value of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst allowed = state.count < opts.max;\n\t\t\t\tstate = allowed\n\t\t\t\t\t? { ...state, count: state.count + 1, allowed: state.allowed + 1 }\n\t\t\t\t\t: { ...state, dropped: state.dropped + 1 };\n\t\t\t\tconst status = {\n\t\t\t\t\tallowed: state.allowed,\n\t\t\t\t\tdropped: state.dropped,\n\t\t\t\t\tremaining: Math.max(0, opts.max - state.count),\n\t\t\t\t\tresetAtMs: state.resetAtMs,\n\t\t\t\t} satisfies RateLimitStatus;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\tallowed\n\t\t\t\t\t\t\t? ({ kind: \"allowed\", value: value as T, status } satisfies RateLimitEvent<T>)\n\t\t\t\t\t\t\t: ({ kind: \"dropped\", value: value as T, status } satisfies RateLimitEvent<T>),\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{ name: `${name}/events`, factory: \"rateLimitEvents\" },\n\t);\n\tconst allowed = graph.node<T>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"allowed\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/allowed`, factory: \"rateLimitAllowed\" },\n\t);\n\tconst dropped = graph.node<T>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst typed = event as RateLimitEvent<T>;\n\t\t\t\tif (typed.kind === \"dropped\") ctx.down([[\"DATA\", typed.value]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/dropped`, factory: \"rateLimitDropped\" },\n\t);\n\tconst status = graph.node<RateLimitStatus>(\n\t\t[events],\n\t\t(ctx) => {\n\t\t\tfor (const event of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", (event as RateLimitEvent<T>).status]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"rateLimitStatus\" },\n\t);\n\treturn { allowed, dropped, status };\n}\n\nexport function timeoutBundle<T>(\n\tgraph: Graph,\n\tsource: Node<T>,\n\tms: number,\n\topts: { name?: string } = {},\n): TimeoutBundle<T> {\n\tconst name = opts.name ?? \"timeout\";\n\tconst node = timeoutOperator(source, ms);\n\tconst status = graph.node<\"running\" | \"completed\" | \"errored\">(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal === true) ctx.down([[\"DATA\", \"completed\"]]);\n\t\t\telse if (terminal !== false && terminal !== undefined) ctx.down([[\"DATA\", \"errored\"]]);\n\t\t\telse if ((depBatch(ctx, 0) ?? []).length > 0) ctx.down([[\"DATA\", \"running\"]]);\n\t\t},\n\t\t{ name: `${name}/status`, factory: \"timeoutStatus\" },\n\t);\n\tconst errors = graph.node<unknown>(\n\t\t[node],\n\t\t(ctx) => {\n\t\t\tconst terminal = ctx.terminal[0];\n\t\t\tif (terminal !== true && terminal !== false && terminal !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", terminal]]);\n\t\t\t}\n\t\t},\n\t\t{ name: `${name}/errors`, factory: \"timeoutErrors\" },\n\t);\n\treturn { node, status, errors };\n}\n\n/**\n * Build a D136 ProcessBundle from graph-visible command facts and a reducer.\n *\n * The bundle retains its runtime/projection nodes until `release()` is called.\n * Reducer and validation failures are emitted as DATA error/status/audit facts;\n * they do not mint protocol ERROR messages or own restore/hydration behavior.\n */\nexport function processBundle<\n\tTCommand = unknown,\n\tTState = unknown,\n\tTEvent = unknown,\n\tTEffect = unknown,\n>(\n\tgraph: Graph,\n\topts: ProcessBundleOptions<TCommand, TState, TEvent, TEffect>,\n): ProcessBundle<TCommand, TState, TEvent, TEffect> {\n\tif (typeof opts.reduce !== \"function\") {\n\t\tthrow new TypeError(\"processBundle: reduce must be a function\");\n\t}\n\tif (opts.initialState === undefined) {\n\t\tthrow new TypeError(\"processBundle: initialState must not be undefined\");\n\t}\n\tconst name = opts.name ?? \"process\";\n\tconst now = opts.now ?? Date.now;\n\tconst topology = graph.topologyGroup({ name: `${name}.process` });\n\tconst command = topology.node<ProcessCommand<TCommand>>([], null, {\n\t\tname: `${name}/command`,\n\t\tfactory: \"processCommand\",\n\t\tcompleteWhenDepsComplete: false,\n\t\terrorWhenDepsError: false,\n\t});\n\tconst runtime = topology.node<ProcessRuntimeFact<TState, TEvent, TEffect>>(\n\t\t[command],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessRuntimeState<TState>>() ??\n\t\t\t\t({\n\t\t\t\t\teventSeq: 0,\n\t\t\t\t\teffectSeq: 0,\n\t\t\t\t\tcommandCount: 0,\n\t\t\t\t\terrorCount: 0,\n\t\t\t\t\tauditSeq: 0,\n\t\t\t\t\tseenEventIds: [],\n\t\t\t\t\tseenEffectIds: [],\n\t\t\t\t\tstate: opts.initialState,\n\t\t\t\t} satisfies ProcessRuntimeState<TState>);\n\t\t\tctx.state.persist(true);\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = reduceProcessCommandFact(\n\t\t\t\t\traw,\n\t\t\t\t\tstate,\n\t\t\t\t\topts.reduce as ProcessReducer<unknown, TState, unknown, unknown>,\n\t\t\t\t\tnow,\n\t\t\t\t\t(fact) => ctx.down([[\"DATA\", fact as ProcessRuntimeFact<TState, TEvent, TEffect>]]),\n\t\t\t\t);\n\t\t\t\tctx.state.set(state);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processRuntime\",\n\t\t\tmeta: { process: \"facts-plus-reducer\", d: \"D136\" },\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst events = processProjection<ProcessEvent<TEvent>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/events`,\n\t\t\"processEvents\",\n\t\t(fact) => (fact.kind === \"event\" ? fact.event : undefined),\n\t);\n\tconst state = processProjection<TState, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/state`,\n\t\t\"processState\",\n\t\t(fact) => (fact.kind === \"state\" ? fact.state : undefined),\n\t);\n\tconst audit = processProjection<ProcessAuditRecord, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/audit`,\n\t\t\"processAudit\",\n\t\t(fact) => (fact.kind === \"audit\" ? fact.audit : undefined),\n\t);\n\tconst effectRequests = processProjection<ProcessEffectRequest<TEffect>, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/effectRequests`,\n\t\t\"processEffectRequests\",\n\t\t(fact) => (fact.kind === \"effect-request\" ? fact.effect : undefined),\n\t);\n\tconst status = processProjection<ProcessStatus, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/status`,\n\t\t\"processStatus\",\n\t\t(fact) => (fact.kind === \"status\" ? fact.status : undefined),\n\t);\n\tconst errors = processProjection<ProcessError, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst cursor = processProjection<ProcessCursor, TState, TEvent, TEffect>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/cursor`,\n\t\t\"processCursor\",\n\t\t(fact) => (fact.kind === \"cursor\" ? fact.cursor : undefined),\n\t);\n\tconst retainProcessNodes = () => [\n\t\tgraph.retain(runtime, { reason: `${name}.process.runtime` }),\n\t\tgraph.retain(events, { reason: `${name}.process.events` }),\n\t\tgraph.retain(state, { reason: `${name}.process.state` }),\n\t\tgraph.retain(audit, { reason: `${name}.process.audit` }),\n\t\tgraph.retain(effectRequests, { reason: `${name}.process.effectRequests` }),\n\t\tgraph.retain(status, { reason: `${name}.process.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.process.errors` }),\n\t\tgraph.retain(cursor, { reason: `${name}.process.cursor` }),\n\t];\n\tlet releaseRetains = retainProcessNodes();\n\tlet released = false;\n\tconst bundle: ProcessBundle<TCommand, TState, TEvent, TEffect> = {\n\t\tcommand,\n\t\tevents,\n\t\tstate,\n\t\taudit,\n\t\teffectRequests,\n\t\tstatus,\n\t\terrors,\n\t\tcursor,\n\t\tdispatch(next) {\n\t\t\tcommand.down([[\"DATA\", next]]);\n\t\t\treturn next;\n\t\t},\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.process.release` });\n\t\t\t\treleased = true;\n\t\t\t\tprocessCommandSources.delete(\n\t\t\t\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treleaseRetains = retainProcessNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n\tprocessCommandSources.set(\n\t\tbundle as unknown as ProcessBundle<unknown, unknown, unknown, unknown>,\n\t\t{ sources: [] },\n\t);\n\treturn bundle;\n}\n\n/**\n * Build a D156 graph-visible effect runner adapter over a ProcessBundle.\n *\n * The runner consumes visible effect-request and outcome facts, then publishes\n * ordinary ProcessCommand DATA facts back through process.command via a declared\n * graph edge. Async handlers, timers, and process state ownership stay outside\n * this helper.\n */\nexport function processEffectRunner<TEffect = unknown, TResult = unknown>(\n\tgraph: Graph,\n\tprocess: ProcessBundle<unknown, unknown, unknown, TEffect>,\n\topts: ProcessEffectRunnerOptions<TResult>,\n): ProcessEffectRunnerBundle<TEffect, TResult> {\n\tif (opts.outcomes.length === 0) {\n\t\tthrow new RangeError(\"processEffectRunner: outcomes must contain at least one node\");\n\t}\n\tconst name = opts.name ?? \"processEffectRunner\";\n\tconst topology = graph.topologyGroup({ name: `${name}.effectRunner` });\n\tconst requests = topology.node<ProcessEffectRequest<TEffect>>(\n\t\t[process.effectRequests],\n\t\t(ctx) => {\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", request as ProcessEffectRequest<TEffect>]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/requests`,\n\t\t\tfactory: \"processEffectRunnerRequests\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst runtime = topology.node<ProcessEffectRunnerFact<TResult>>(\n\t\t[...opts.outcomes],\n\t\t(ctx) => {\n\t\t\tfor (let i = 0; i < opts.outcomes.length; i += 1) {\n\t\t\t\tfor (const raw of depBatch(ctx, i) ?? []) {\n\t\t\t\t\tconst parsed = parseProcessEffectOutcome<TResult>(raw);\n\t\t\t\t\tif (typeof parsed === \"string\") {\n\t\t\t\t\t\tconst error = {\n\t\t\t\t\t\t\tcode: \"malformed-outcome\",\n\t\t\t\t\t\t\tmessage: parsed,\n\t\t\t\t\t\t\toutcome: raw,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerError;\n\t\t\t\t\t\tctx.down([[\"DATA\", { kind: \"error\", error }]]);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst outcome = parsed as ProcessEffectOutcome<TResult>;\n\t\t\t\t\tconst command = processEffectOutcomeCommand(outcome);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"outcome\", outcome }]]);\n\t\t\t\t\tctx.down([[\"DATA\", { kind: \"command\", command }]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname: `${name}/runtime`,\n\t\t\tfactory: \"processEffectRunner\",\n\t\t\tmeta: { process: \"effect-runner\", d: \"D156\" },\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst outcomes = processEffectRunnerProjection<ProcessEffectOutcome<TResult>, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/outcomes`,\n\t\t\"processEffectRunnerOutcomes\",\n\t\t(fact) => (fact.kind === \"outcome\" ? fact.outcome : undefined),\n\t);\n\tconst commands = processEffectRunnerProjection<\n\t\tProcessCommand<ProcessEffectCommandPayload<TResult>>,\n\t\tTResult\n\t>(topology, runtime, `${name}/commands`, \"processEffectRunnerCommands\", (fact) =>\n\t\tfact.kind === \"command\" ? fact.command : undefined,\n\t);\n\tconst errors = processEffectRunnerProjection<ProcessEffectRunnerError, TResult>(\n\t\ttopology,\n\t\truntime,\n\t\t`${name}/errors`,\n\t\t\"processEffectRunnerErrors\",\n\t\t(fact) => (fact.kind === \"error\" ? fact.error : undefined),\n\t);\n\tconst status = topology.node<ProcessEffectRunnerStatus>(\n\t\t[requests, runtime],\n\t\t(ctx) => {\n\t\t\tlet state =\n\t\t\t\tctx.state.get<ProcessEffectRunnerState>() ??\n\t\t\t\t({ requested: 0, commanded: 0, rejected: 0 } satisfies ProcessEffectRunnerState);\n\t\t\tfor (const request of depBatch(ctx, 0) ?? []) {\n\t\t\t\tstate = { ...state, requested: state.requested + 1 };\n\t\t\t\tconst typedRequest = request as ProcessEffectRequest<TEffect>;\n\t\t\t\tctx.down([\n\t\t\t\t\t[\n\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstate: \"requested\",\n\t\t\t\t\t\t\teffectId: typedRequest.id,\n\t\t\t\t\t\t\teffectType: typedRequest.type,\n\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t],\n\t\t\t\t]);\n\t\t\t}\n\t\t\tfor (const fact of depBatch(ctx, 1) ?? []) {\n\t\t\t\tconst typedFact = fact as ProcessEffectRunnerFact<TResult>;\n\t\t\t\tif (typedFact.kind === \"command\") {\n\t\t\t\t\tstate = { ...state, commanded: state.commanded + 1 };\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstate: \"commanded\",\n\t\t\t\t\t\t\t\teffectId: typedFact.command.payload.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.command.payload.effectType,\n\t\t\t\t\t\t\t\tcommandId: typedFact.command.id,\n\t\t\t\t\t\t\t\tcommandType: typedFact.command.type as ProcessEffectCommandType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tif (typedFact.kind === \"error\") {\n\t\t\t\t\tstate = { ...state, rejected: state.rejected + 1 };\n\t\t\t\t\tctx.down([\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"DATA\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tstate: \"rejected\",\n\t\t\t\t\t\t\t\teffectId: typedFact.error.effectId,\n\t\t\t\t\t\t\t\teffectType: typedFact.error.effectType,\n\t\t\t\t\t\t\t\trequested: state.requested,\n\t\t\t\t\t\t\t\tcommanded: state.commanded,\n\t\t\t\t\t\t\t\trejected: state.rejected,\n\t\t\t\t\t\t\t} satisfies ProcessEffectRunnerStatus,\n\t\t\t\t\t\t],\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.state.set(state);\n\t\t},\n\t\t{\n\t\t\tname: `${name}/status`,\n\t\t\tfactory: \"processEffectRunnerStatus\",\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n\tconst retainRunnerNodes = () => [\n\t\tgraph.retain(requests, { reason: `${name}.effectRunner.requests` }),\n\t\tgraph.retain(outcomes, { reason: `${name}.effectRunner.outcomes` }),\n\t\tgraph.retain(commands, { reason: `${name}.effectRunner.commands` }),\n\t\tgraph.retain(status, { reason: `${name}.effectRunner.status` }),\n\t\tgraph.retain(errors, { reason: `${name}.effectRunner.errors` }),\n\t];\n\tlet releaseRetains = retainRunnerNodes();\n\ttry {\n\t\tattachProcessCommandSource(process, commands);\n\t} catch (error) {\n\t\tfor (const releaseRetain of releaseRetains) releaseRetain();\n\t\treleaseRetains = [];\n\t\ttopology.release({ reason: `${name}.effectRunner.failedAttach` });\n\t\tthrow error;\n\t}\n\tlet released = false;\n\treturn {\n\t\trequests,\n\t\toutcomes,\n\t\tcommands,\n\t\tstatus,\n\t\terrors,\n\t\trelease() {\n\t\t\tif (released) return;\n\t\t\tconst activeRetains = releaseRetains;\n\t\t\treleaseRetains = [];\n\t\t\tfor (const releaseRetain of activeRetains) releaseRetain();\n\t\t\tdetachProcessCommandSource(process, commands);\n\t\t\ttry {\n\t\t\t\ttopology.release({ reason: `${name}.effectRunner.release` });\n\t\t\t\treleased = true;\n\t\t\t} catch (error) {\n\t\t\t\tattachProcessCommandSource(process, commands);\n\t\t\t\treleaseRetains = retainRunnerNodes();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function constantBackoff(delayMs: number): BackoffPolicy {\n\treturn { kind: \"constant\", delayMs };\n}\n\ninterface ProcessEffectRunnerState {\n\trequested: number;\n\tcommanded: number;\n\trejected: number;\n}\n\ninterface ProcessRuntimeState<TState> {\n\teventSeq: number;\n\teffectSeq: number;\n\tcommandCount: number;\n\terrorCount: number;\n\tauditSeq: number;\n\tseenEventIds: string[];\n\tseenEffectIds: string[];\n\tstate: TState;\n}\n\nfunction processEffectRunnerProjection<T, TResult>(\n\ttopology: TopologyGroup,\n\truntime: Node<ProcessEffectRunnerFact<TResult>>,\n\tname: string,\n\tfactory: string,\n\tpick: (fact: ProcessEffectRunnerFact<TResult>) => T | undefined,\n): Node<T> {\n\treturn topology.node<T>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const fact of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst value = pick(fact as ProcessEffectRunnerFact<TResult>);\n\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\tname,\n\t\t\tfactory,\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t},\n\t);\n}\n\nfunction parseProcessEffectOutcome<TResult>(raw: unknown): ProcessEffectOutcome<TResult> | string {\n\tif (!isObjectRecord(raw)) return \"processEffectRunner: outcome must be an object\";\n\tif (typeof raw.kind !== \"string\") {\n\t\treturn \"processEffectRunner: outcome kind must be a string\";\n\t}\n\tif (\n\t\traw.kind !== \"result\" &&\n\t\traw.kind !== \"failure\" &&\n\t\traw.kind !== \"cancel\" &&\n\t\traw.kind !== \"timeout\"\n\t) {\n\t\treturn \"processEffectRunner: outcome kind must be result, failure, cancel, or timeout\";\n\t}\n\tif (typeof raw.effectId !== \"string\" || raw.effectId.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectId must be a non-empty string\";\n\t}\n\tif (typeof raw.effectType !== \"string\" || raw.effectType.length === 0) {\n\t\treturn \"processEffectRunner: outcome effectType must be a non-empty string\";\n\t}\n\tif (\"commandId\" in raw && raw.commandId !== undefined) {\n\t\tif (typeof raw.commandId !== \"string\" || raw.commandId.length === 0) {\n\t\t\treturn \"processEffectRunner: outcome commandId must be a non-empty string\";\n\t\t}\n\t}\n\tfor (const key of [\"processId\", \"correlationId\", \"causationId\"] as const) {\n\t\tif (key in raw && raw[key] !== undefined && typeof raw[key] !== \"string\") {\n\t\t\treturn `processEffectRunner: outcome ${key} must be a string`;\n\t\t}\n\t}\n\tif (\"metadata\" in raw && raw.metadata !== undefined && !isObjectRecord(raw.metadata)) {\n\t\treturn \"processEffectRunner: outcome metadata must be a plain object\";\n\t}\n\tif (raw.kind === \"result\" && !(\"value\" in raw)) {\n\t\treturn \"processEffectRunner: result outcome must carry value\";\n\t}\n\tif ((raw.kind === \"failure\" || raw.kind === \"timeout\") && !(\"error\" in raw)) {\n\t\treturn `processEffectRunner: ${raw.kind} outcome must carry error`;\n\t}\n\tif (\n\t\traw.kind === \"cancel\" &&\n\t\t\"reason\" in raw &&\n\t\traw.reason !== undefined &&\n\t\ttypeof raw.reason !== \"string\"\n\t) {\n\t\treturn \"processEffectRunner: cancel outcome reason must be a string\";\n\t}\n\treturn raw as unknown as ProcessEffectOutcome<TResult>;\n}\n\nfunction processEffectOutcomeCommand<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessCommand<ProcessEffectCommandPayload<TResult>> {\n\tconst commandType = processEffectCommandType(outcome.kind);\n\treturn {\n\t\tid: outcome.commandId ?? `${outcome.effectId}:${commandType}`,\n\t\ttype: commandType,\n\t\tpayload: processEffectCommandPayload(outcome),\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n}\n\nfunction processEffectCommandType(kind: ProcessEffectOutcome[\"kind\"]): ProcessEffectCommandType {\n\tswitch (kind) {\n\t\tcase \"result\":\n\t\t\treturn \"effect.result\";\n\t\tcase \"failure\":\n\t\t\treturn \"effect.failure\";\n\t\tcase \"cancel\":\n\t\t\treturn \"effect.cancel\";\n\t\tcase \"timeout\":\n\t\t\treturn \"effect.timeout\";\n\t}\n}\n\nfunction processEffectCommandPayload<TResult>(\n\toutcome: ProcessEffectOutcome<TResult>,\n): ProcessEffectCommandPayload<TResult> {\n\tconst base = {\n\t\teffectId: outcome.effectId,\n\t\teffectType: outcome.effectType,\n\t\tprocessId: outcome.processId,\n\t\tcorrelationId: outcome.correlationId,\n\t\tcausationId: outcome.causationId,\n\t\tmetadata: outcome.metadata,\n\t};\n\tswitch (outcome.kind) {\n\t\tcase \"result\":\n\t\t\treturn { ...base, kind: \"result\", value: outcome.value };\n\t\tcase \"failure\":\n\t\t\treturn { ...base, kind: \"failure\", error: outcome.error };\n\t\tcase \"cancel\":\n\t\t\treturn { ...base, kind: \"cancel\", reason: outcome.reason };\n\t\tcase \"timeout\":\n\t\t\treturn { ...base, kind: \"timeout\", error: outcome.error };\n\t}\n}\n\nfunction attachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\n\tconst previousSources = [...sources];\n\tif (!sources.includes(source)) sources.push(source);\n\ttry {\n\t\tprocess.command.replaceDeps([...sources], processCommandSourceFn(sources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction detachProcessCommandSource(\n\tprocess: ProcessBundle<unknown, unknown, unknown, unknown>,\n\tsource: Node<ProcessCommand<unknown>>,\n): void {\n\tconst attached = processCommandSources.get(process);\n\tif (attached === undefined) {\n\t\tthrow new Error(\"processEffectRunner: process command source registry missing\");\n\t}\n\tconst sources = attached.sources as Node<ProcessCommand<unknown>>[];\n\tif (!sources.includes(source)) return;\n\tconst previousSources = [...sources];\n\tconst nextSources = sources.filter((candidate) => candidate !== source);\n\tsources.splice(0, sources.length, ...nextSources);\n\ttry {\n\t\tprocess.command.replaceDeps([...nextSources], processCommandSourceFn(nextSources.length));\n\t} catch (error) {\n\t\tsources.splice(0, sources.length, ...previousSources);\n\t\tprocess.command.replaceDeps(\n\t\t\t[...previousSources],\n\t\t\tprocessCommandSourceFn(previousSources.length),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nfunction processCommandSourceFn(sourceCount: number) {\n\treturn (ctx: Parameters<NodeFn>[0]) => {\n\t\tfor (let i = 0; i < sourceCount; i += 1) {\n\t\t\tfor (const command of depBatch(ctx, i) ?? []) {\n\t\t\t\tctx.down([[\"DATA\", command as ProcessCommand<unknown>]]);\n\t\t\t}\n\t\t}\n\t};\n}\n\nfunction processRuntimeDraft<TState>(\n\tstate: ProcessRuntimeState<TState>,\n): ProcessRuntimeState<TState> {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t\tseenEventIds: [...state.seenEventIds],\n\t\tseenEffectIds: [...state.seenEffectIds],\n\t\tstate: state.state,\n\t};\n}\n\nfunction reduceProcessCommandFact<TState>(\n\traw: unknown,\n\tstate: ProcessRuntimeState<TState>,\n\treduce: ProcessReducer<unknown, TState, unknown, unknown>,\n\tnow: () => number,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n): ProcessRuntimeState<TState> {\n\tconst draft = processRuntimeDraft(state);\n\tdraft.commandCount += 1;\n\tconst parsed = parseProcessCommand(raw);\n\tif (typeof parsed === \"string\") {\n\t\temitProcessFailure(draft, emit, raw, undefined, \"malformed-command\", parsed);\n\t\treturn draft;\n\t}\n\tconst command = parsed as ProcessCommand<unknown>;\n\tlet reduction: ProcessReduction<TState, unknown, unknown>;\n\tconst reducerState = cloneProcessState(state.state);\n\tif (!reducerState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", reducerState.message);\n\t\treturn draft;\n\t}\n\ttry {\n\t\treduction = reduce(command, reducerState.value);\n\t} catch (error) {\n\t\trethrowGraphRuntimeInvariant(error);\n\t\temitProcessFailure(draft, emit, command, command, \"reducer-threw\", errorMessage(error));\n\t\treturn draft;\n\t}\n\tif (!isObjectRecord(reduction) || !(\"state\" in reduction)) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer must return { state, events?, effects? }\",\n\t\t);\n\t\treturn draft;\n\t}\n\tif (reduction.state === undefined) {\n\t\temitProcessFailure(\n\t\t\tdraft,\n\t\t\temit,\n\t\t\tcommand,\n\t\t\tcommand,\n\t\t\t\"malformed-state\",\n\t\t\t\"processBundle: reducer state must not be undefined\",\n\t\t);\n\t\treturn draft;\n\t}\n\tconst privateState = cloneProcessState(reduction.state);\n\tif (!privateState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", privateState.message);\n\t\treturn draft;\n\t}\n\tconst visibleState = cloneProcessState(privateState.value);\n\tif (!visibleState.ok) {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-state\", visibleState.message);\n\t\treturn draft;\n\t}\n\tconst preparedEvents = prepareProcessEvents(command, draft, reduction.events ?? []);\n\tif (typeof preparedEvents === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-event\", preparedEvents);\n\t\treturn draft;\n\t}\n\tconst preparedEffects = prepareProcessEffects(command, draft, reduction.effects ?? []);\n\tif (typeof preparedEffects === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"malformed-effect\", preparedEffects);\n\t\treturn draft;\n\t}\n\tconst timestampMs = readTimestampMs(now);\n\tif (typeof timestampMs === \"string\") {\n\t\temitProcessFailure(draft, emit, command, command, \"clock-threw\", timestampMs);\n\t\treturn draft;\n\t}\n\tdraft.state = privateState.value;\n\temit({ kind: \"state\", state: visibleState.value, cursor: processCursorOf(draft) });\n\tconst events: ProcessEvent<unknown>[] = [];\n\tfor (const eventDraft of preparedEvents) {\n\t\tdraft.eventSeq += 1;\n\t\tdraft.seenEventIds.push(eventDraft.id);\n\t\tconst event: ProcessEvent<unknown> = {\n\t\t\tid: eventDraft.id,\n\t\t\ttype: eventDraft.type,\n\t\t\tseq: draft.eventSeq,\n\t\t\tcursor: draft.eventSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: eventDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(eventDraft.processId === undefined ? {} : { processId: eventDraft.processId }),\n\t\t\t...(eventDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: eventDraft.correlationId }),\n\t\t\t...(eventDraft.causationId === undefined ? {} : { causationId: eventDraft.causationId }),\n\t\t\t...(eventDraft.metadata === undefined ? {} : { metadata: eventDraft.metadata }),\n\t\t};\n\t\tevents.push(event);\n\t\temit({ kind: \"event\", event });\n\t}\n\tconst effects: ProcessEffectRequest<unknown>[] = [];\n\tfor (const effectDraft of preparedEffects) {\n\t\tdraft.effectSeq += 1;\n\t\tdraft.seenEffectIds.push(effectDraft.id);\n\t\tconst effect: ProcessEffectRequest<unknown> = {\n\t\t\tid: effectDraft.id,\n\t\t\ttype: effectDraft.type,\n\t\t\tseq: draft.effectSeq,\n\t\t\tcursor: draft.effectSeq,\n\t\t\tcommandId: command.id,\n\t\t\tcommandType: command.type,\n\t\t\tpayload: effectDraft.payload,\n\t\t\ttimestampMs,\n\t\t\t...(effectDraft.processId === undefined ? {} : { processId: effectDraft.processId }),\n\t\t\t...(effectDraft.correlationId === undefined\n\t\t\t\t? {}\n\t\t\t\t: { correlationId: effectDraft.correlationId }),\n\t\t\t...(effectDraft.causationId === undefined ? {} : { causationId: effectDraft.causationId }),\n\t\t\t...(effectDraft.metadata === undefined ? {} : { metadata: effectDraft.metadata }),\n\t\t};\n\t\teffects.push(effect);\n\t\temit({ kind: \"effect-request\", effect });\n\t}\n\temitProcessStatus(draft, emit, command, \"accepted\", events.length, effects.length);\n\temitProcessAudit(draft, emit, command, \"success\", events, effects, undefined, undefined);\n\temit({ kind: \"cursor\", cursor: processCursorOf(draft) });\n\treturn draft;\n}\n\nfunction processProjection<TOut, TState, TEvent, TEffect>(\n\tgraph: Graph | TopologyGroup,\n\truntime: Node<ProcessRuntimeFact<TState, TEvent, TEffect>>,\n\tname: string,\n\tfactory: string,\n\tselect: (fact: ProcessRuntimeFact<TState, TEvent, TEffect>) => TOut | undefined,\n): Node<TOut> {\n\treturn graph.node<TOut>(\n\t\t[runtime],\n\t\t(ctx) => {\n\t\t\tfor (const raw of depBatch(ctx, 0) ?? []) {\n\t\t\t\tconst selected = select(raw as ProcessRuntimeFact<TState, TEvent, TEffect>);\n\t\t\t\tif (selected !== undefined) ctx.down([[\"DATA\", selected]]);\n\t\t\t}\n\t\t},\n\t\t{ name, factory, completeWhenDepsComplete: false, errorWhenDepsError: false },\n\t);\n}\n\nfunction parseProcessCommand(value: unknown): ProcessCommand<unknown> | string {\n\tif (!isObjectRecord(value)) return \"processBundle: command fact must be an object\";\n\tif (typeof value.id !== \"string\" || value.id.length === 0) {\n\t\treturn \"processBundle: command id must be a non-empty string\";\n\t}\n\tif (typeof value.type !== \"string\" || value.type.length === 0) {\n\t\treturn \"processBundle: command type must be a non-empty string\";\n\t}\n\treturn {\n\t\tid: value.id,\n\t\ttype: value.type,\n\t\tpayload: value.payload,\n\t\t...(typeof value.processId === \"string\" ? { processId: value.processId } : {}),\n\t\t...(typeof value.correlationId === \"string\" ? { correlationId: value.correlationId } : {}),\n\t\t...(typeof value.causationId === \"string\" ? { causationId: value.causationId } : {}),\n\t\t...(isObjectRecord(value.metadata) ? { metadata: value.metadata } : {}),\n\t};\n}\n\nfunction prepareProcessEvents(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEventDraft<unknown>[],\n): Array<ProcessEventDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: events must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEventDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: event draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:event:${state.eventSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate event '${id}'`;\n\t\tif (state.seenEventIds.includes(id)) return `processBundle: duplicate event '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction prepareProcessEffects(\n\tcommand: ProcessCommand<unknown>,\n\tstate: ProcessRuntimeState<unknown>,\n\tdrafts: readonly ProcessEffectRequestDraft<unknown>[],\n): Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> | string {\n\tif (!Array.isArray(drafts)) return \"processBundle: effects must be an array\";\n\tconst seen = new Set<string>();\n\tconst out: Array<ProcessEffectRequestDraft<unknown> & { readonly id: string }> = [];\n\tfor (let i = 0; i < drafts.length; i += 1) {\n\t\tconst draft = drafts[i];\n\t\tif (!isObjectRecord(draft) || typeof draft.type !== \"string\" || draft.type.length === 0) {\n\t\t\treturn \"processBundle: effect draft must have a non-empty type\";\n\t\t}\n\t\tconst id =\n\t\t\ttypeof draft.id === \"string\" && draft.id.length > 0\n\t\t\t\t? draft.id\n\t\t\t\t: `${command.id}:effect:${state.effectSeq + i + 1}`;\n\t\tif (seen.has(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tif (state.seenEffectIds.includes(id)) return `processBundle: duplicate effect '${id}'`;\n\t\tseen.add(id);\n\t\tout.push({\n\t\t\tid,\n\t\t\ttype: draft.type,\n\t\t\tpayload: draft.payload,\n\t\t\t...(typeof draft.processId === \"string\" ? { processId: draft.processId } : {}),\n\t\t\t...(typeof draft.correlationId === \"string\" ? { correlationId: draft.correlationId } : {}),\n\t\t\t...(typeof draft.causationId === \"string\" ? { causationId: draft.causationId } : {}),\n\t\t\t...(isObjectRecord(draft.metadata) ? { metadata: draft.metadata } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\nfunction emitProcessFailure<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\traw: unknown,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tcode: ProcessErrorCode,\n\tmessage: string,\n): void {\n\tstate.errorCount += 1;\n\tconst cursor = processCursorOf(state);\n\tconst error: ProcessError = {\n\t\tcode,\n\t\tmessage,\n\t\tcommand: raw,\n\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\tcursor,\n\t};\n\temit({ kind: \"error\", error });\n\temitProcessStatus(state, emit, command, \"rejected\", 0, 0, code);\n\temitProcessAudit(state, emit, command, \"failure\", [], [], code, message);\n\temit({ kind: \"cursor\", cursor: processCursorOf(state) });\n}\n\nfunction emitProcessStatus<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\tstatusState: ProcessStatus[\"state\"],\n\teventCount: number,\n\teffectCount: number,\n\terrorCode?: ProcessErrorCode,\n): void {\n\temit({\n\t\tkind: \"status\",\n\t\tstatus: {\n\t\t\tstate: statusState,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\teventCount,\n\t\t\teffectCount,\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction emitProcessAudit<TState>(\n\tstate: ProcessRuntimeState<TState>,\n\temit: (fact: ProcessRuntimeFact<TState, unknown, unknown>) => void,\n\tcommand: ProcessCommand<unknown> | undefined,\n\toutcome: ProcessAuditRecord[\"outcome\"],\n\tevents: readonly ProcessEvent<unknown>[],\n\teffects: readonly ProcessEffectRequest<unknown>[],\n\terrorCode: ProcessErrorCode | undefined,\n\terrorMessage: string | undefined,\n): void {\n\tstate.auditSeq += 1;\n\temit({\n\t\tkind: \"audit\",\n\t\taudit: {\n\t\t\tseq: state.auditSeq,\n\t\t\t...(command === undefined ? {} : { commandId: command.id, commandType: command.type }),\n\t\t\toutcome,\n\t\t\teventIds: events.map((event) => event.id),\n\t\t\teventTypes: events.map((event) => event.type),\n\t\t\teffectIds: effects.map((effect) => effect.id),\n\t\t\teffectTypes: effects.map((effect) => effect.type),\n\t\t\t...(errorCode === undefined ? {} : { errorCode }),\n\t\t\t...(errorMessage === undefined ? {} : { errorMessage }),\n\t\t\tcursor: processCursorOf(state),\n\t\t},\n\t});\n}\n\nfunction processCursorOf(state: ProcessRuntimeState<unknown>): ProcessCursor {\n\treturn {\n\t\teventSeq: state.eventSeq,\n\t\teffectSeq: state.effectSeq,\n\t\tcommandCount: state.commandCount,\n\t\terrorCount: state.errorCount,\n\t\tauditSeq: state.auditSeq,\n\t};\n}\n\ntype CloneProcessStateResult<TState> =\n\t| { readonly ok: true; readonly value: TState }\n\t| { readonly ok: false; readonly message: string };\n\nfunction cloneProcessState<TState>(state: TState): CloneProcessStateResult<TState> {\n\tif (typeof state !== \"object\" || state === null) return { ok: true, value: state };\n\ttry {\n\t\tif (typeof globalThis.structuredClone === \"function\") {\n\t\t\treturn { ok: true, value: globalThis.structuredClone(state) as TState };\n\t\t}\n\t\treturn { ok: true, value: JSON.parse(JSON.stringify(state)) as TState };\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: `processBundle: state must be cloneable before reducer execution (${errorMessage(error)})`,\n\t\t};\n\t}\n}\n\nfunction readTimestampMs(now: () => number): number | string {\n\ttry {\n\t\tconst timestampMs = now();\n\t\tif (!Number.isFinite(timestampMs)) return \"processBundle: now() must return a finite number\";\n\t\treturn timestampMs;\n\t} catch (error) {\n\t\treturn errorMessage(error);\n\t}\n}\n\nfunction rethrowGraphRuntimeInvariant(error: unknown): void {\n\tconst message = errorMessage(error);\n\tif (\n\t\tmessage.includes(\"R-reentrancy\") ||\n\t\tmessage.includes(\"R-rewire\") ||\n\t\tmessage.includes(\"R-graph-domain\") ||\n\t\tmessage.includes(\"D37\") ||\n\t\tmessage.includes(\"D22\") ||\n\t\tmessage.includes(\"different graph\") ||\n\t\tmessage.includes(\"cross-graph\") ||\n\t\tmessage.includes(\"wire bridge\") ||\n\t\tmessage.includes(\"mid-fn topology mutation\") ||\n\t\tmessage.includes(\"reentrant dep mutation\") ||\n\t\tmessage.includes(\"feedback cycle\")\n\t) {\n\t\tthrow error;\n\t}\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n","/**\n * Wave-protocol message types and the tier const table.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-msg-format, R-msg-closed-set, R-tier (D34), R-data-payload, R-sentinel.\n */\n\n/** Opaque pause-lock identifier (R-pause-lockset). */\nexport type LockId = string | symbol;\n\n/**\n * The CLOSED set of 10 message types (R-msg-closed-set / D9 + 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\n/** One array of messages delivered in one call = one Wave (R-wave-boundary). */\nexport type Wave = readonly Message[];\n\n/** The message-type tag (the first tuple element). */\nexport type MessageType = Message[0];\n\n/**\n * SENTINEL = absence-of-DATA (R-sentinel / D16). TS representation is `undefined`.\n * Never a valid DATA payload; `null` IS a valid DATA value (domain-level absence).\n */\nexport const SENTINEL = undefined;\n\n/** R-data-payload: ERROR payloads must not collide with terminal metadata shorthand. */\nexport function isInvalidErrorPayload(v: unknown): boolean {\n\treturn v === SENTINEL || typeof v === \"boolean\";\n}\n\n/** R-data-payload / D78: host-language failures that collide with ctx.terminal shorthand become diagnostics. */\nexport function errorPayload(reason: unknown, fallback = \"error without a valid payload\"): unknown {\n\treturn isInvalidErrorPayload(reason) ? new Error(fallback) : reason;\n}\n\nexport const TIER_START = 0;\nexport const TIER_CONTROL = 1;\nexport const TIER_NOTIFICATION = 2;\nexport const TIER_VALUE = 3;\nexport const TIER_SETTLE = 4;\nexport const TIER_TERMINAL = 5;\nexport const TIER_TEARDOWN = 6;\n\n/**\n * Tier const table (R-tier / D34). Tiers below value dispatch immediately; value\n * and above are batch-deferred. This is a compile-time const table (D18), not runtime config.\n */\nconst TIER: Record<MessageType, number> = {\n\tSTART: TIER_START,\n\tPAUSE: TIER_CONTROL,\n\tRESUME: TIER_CONTROL,\n\tDIRTY: TIER_NOTIFICATION,\n\tDATA: TIER_VALUE,\n\tRESOLVED: TIER_VALUE,\n\tINVALIDATE: TIER_SETTLE,\n\tCOMPLETE: TIER_TERMINAL,\n\tERROR: TIER_TERMINAL,\n\tTEARDOWN: TIER_TEARDOWN,\n};\n\nexport function messageTier(t: MessageType): number {\n\treturn TIER[t];\n}\n\n/** Value and above are deferred inside a batch (DATA/RESOLVED/INVALIDATE/terminal/teardown). */\nexport function isDeferredTier(t: MessageType): boolean {\n\treturn TIER[t] >= TIER_VALUE;\n}\n\n/** Value-tier messages (DATA/RESOLVED) occupy the tier-3 slot. */\nexport function isValueTier(t: MessageType): boolean {\n\treturn TIER[t] === TIER_VALUE;\n}\n\n/** The pause buffer holds the settle slice only: value-tier DATA/RESOLVED plus INVALIDATE. */\nexport function isPauseBufferedTier(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier === TIER_VALUE || tier === TIER_SETTLE;\n}\n\n/**\n * A TERMINAL message = tier 5 (COMPLETE | ERROR), R-tier / D34. Detected via the CENTRAL tier\n * table, NOT a per-variant `=== \"COMPLETE\" || === \"ERROR\"` check — so terminal routing stays\n * driven by the one const table (feedback_use_tier_for_signal_routing); discriminate COMPLETE vs\n * ERROR within the tier by the message type only where the handling actually differs.\n */\nexport function isTerminal(t: MessageType): boolean {\n\treturn TIER[t] === TIER_TERMINAL;\n}\n\n/**\n * ctx.up carries control tiers only (R-ctx-up / DR-5): DIRTY, PAUSE, RESUME,\n * INVALIDATE, TEARDOWN. DATA/RESOLVED (tier 3) and COMPLETE/ERROR (tier 5) are\n * down-only.\n */\nexport function isUpAllowed(t: MessageType): boolean {\n\tconst tier = TIER[t];\n\treturn tier !== TIER_VALUE && tier !== TIER_TERMINAL;\n}\n","/**\n * The fn-invocation context and per-dep input shapes.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-fn-contract (D8/D27), R-ctx-state (D23/D29), R-cleanup-hooks (D28), R-ctx-up.\n */\n\nimport type { Dispatcher } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport type { Node } from \"../node/node.js\";\nimport { type Message, SENTINEL, type Wave } from \"../protocol/messages.js\";\n\n/** A downstream sink callback (the only way to connect to a node's output). */\nexport type Sink = (msg: Message, delivery?: DeliveryMeta) => void;\n\n/** Internal delivery metadata used to preserve the upstream `ctx.down(msgs)` wave boundary. */\nexport interface DeliveryMeta {\n\treadonly wave: object;\n\treadonly last: boolean;\n}\n\n/**\n * Internal current-value reader. It is deliberately a symbol-backed implementation detail:\n * raw ctx exposes `waveData` + `terminal`; helpers below derive from that plus this dep cache.\n */\nexport const CTX_DEP_CACHE: unique symbol = Symbol(\"graphrefly.ctx.depCache\");\n\nexport interface CtxDepCache {\n\treadonly latest: readonly unknown[];\n}\n\n/** Internal node-construction binding for graph-local helper-created deps. */\nexport const CTX_NODE_BINDING: unique symbol = Symbol(\"graphrefly.ctx.nodeBinding\");\n\nexport interface CtxNodeBinding {\n\treadonly dispatcher: Dispatcher;\n\tcreate<T>(factory: () => Node<T>): Node<T>;\n}\n\n/** Per-dep wave projections: dep -> waves -> values/SENTINEL markers. */\nexport type WaveData = readonly (readonly (readonly unknown[])[])[];\n\n/** Terminal metadata parallel to `waveData`: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport type TerminalData = readonly unknown[];\n\nexport function isTerminalNone(t: unknown): boolean {\n\treturn t === false || t === undefined;\n}\n\nexport function isTerminalComplete(t: unknown): t is true {\n\treturn t === true;\n}\n\nexport function isTerminalError(t: unknown): boolean {\n\treturn !isTerminalNone(t) && !isTerminalComplete(t);\n}\n\nexport function terminalErrorValue(t: unknown): unknown {\n\treturn isTerminalError(t) ? t : undefined;\n}\n\n/**\n * Per-node private cross-wave state (R-ctx-state / D23,D29). Default fresh-lifecycle\n * wipe; `persist(true)` keeps it across lifecycle transitions.\n */\nexport interface CtxState {\n\tget<S = unknown>(): S | undefined;\n\tset<S = unknown>(v: S): void;\n\tpersist(on?: boolean): void;\n}\n\n/**\n * Deferred SELF-rewire (R-rewire-deferred / D47). A node fn may, DURING its run, request a\n * mutation of its OWN dep set; the request is QUEUED and applied at the committed wave boundary\n * (after the current wave settles / batch commit / final-lock RESUME) as a fresh wave, reusing\n * R-rewire surgical/Option-C semantics (D42). This is the ONLY legal self-triggered rewire — an\n * IMMEDIATE in-fn `node.subscribeDep/unsubscribeDep/replaceDeps` is the D37 mid-fn feedback-cycle ERROR. An\n * added cached dep pushes `[DIRTY,DATA]` on the boundary wave (R-push-subscribe); a removed dep\n * is drained and, if it loses its last subscriber, `_deactivate`s + fires `onDeactivation`\n * (input-side teardown — the basis for higher-order operator cancellation / abortInFlight).\n */\nexport interface RewireNext {\n\t/** Defer subscribing to a dep (paired with the re-supplied fn — positional fn-deps lock, SD-1). */\n\tsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer unsubscribing from a dep (its source is torn down if it loses its last subscriber). */\n\tunsubscribeDep(dep: Node<unknown>, fn: NodeFn): void;\n\t/** Defer replacing the whole dep set (surgical: kept deps untouched, removed drained, added fresh-subscribe). */\n\treplaceDeps(deps: Node<unknown>[], fn: NodeFn): void;\n}\n\n/**\n * The single argument to a node fn: `(ctx) => void` (R-fn-contract / D8). All emission\n * is explicit via `ctx.down`; there is no return-value framing.\n */\nexport interface Ctx {\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). IMMEDIATE. `towardDep` (a dep index)\n\t * routes the wave up ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t * A pull DEMAND is `up([[RESUME, pullId]])` — but for a SELF-demand (demanding a dep this fn also\n\t * 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/**\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([[RESUME, pullId]])` to demand a pull dep it\n\t * ALSO reads — the cone-routed RESUME reaches the pullId-holder, whose delivery loops back as a\n\t * FRESH wave (not a mid-fn re-entry → no D37). The consumer accepts one-wave latency (the\n\t * HTTP-request model). No node reference needed: the author writes the pullId verbatim.\n\t */\n\tupNext(msgs: Wave, towardDep?: number): void;\n\t/**\n\t * Read a dep's latest value by index (dynamicNode only, R-dynamic-node / D35).\n\t * Present only on dynamicNode fns; all declared deps still participate in wave\n\t * tracking. Under D49/R-resolved-undirty an unread dep's change still fires the fn,\n\t * which re-emits its (unchanged) output as a DATA occurrence — there is NO equals-\n\t * absorption; pair with distinctUntilChanged to suppress unchanged re-emits (opt-in).\n\t */\n\ttrack?(depIndex: number): unknown;\n\t[CTX_DEP_CACHE]?: CtxDepCache;\n\t[CTX_NODE_BINDING]?: CtxNodeBinding;\n}\n\n/** A node fn (R-fn-contract). Registered in a dispatcher pool, indexed by Handle. */\nexport type NodeFn = (ctx: Ctx) => void;\n\n/** Number of declared dep slots visible in this invocation. */\nexport function depCount(ctx: Ctx): number {\n\treturn ctx.waveData.length;\n}\n\n/** DATA/SENTINEL projection batches delivered by one dep in this invocation. */\nexport function depWaves(ctx: Ctx, depIndex: number): readonly (readonly unknown[])[] {\n\treturn ctx.waveData[depIndex] ?? [];\n}\n\n/** Flattened DATA projection for old event-counting operator bodies; null = no wave. */\nexport function depBatch(ctx: Ctx, depIndex: number): readonly unknown[] | null {\n\tconst waves = depWaves(ctx, depIndex);\n\tif (waves.length === 0) return null;\n\tconst flattened = waves.flat().filter((v) => v !== SENTINEL);\n\treturn flattened.length === 0 ? [] : flattened;\n}\n\n/** Latest cached DATA for a dep, derived from implementation-owned dep cache. */\nexport function depLatest(ctx: Ctx, depIndex: number): unknown {\n\treturn ctx[CTX_DEP_CACHE]?.latest[depIndex];\n}\n\n/** Terminal metadata for one dep: false = none, true = COMPLETE, otherwise ERROR payload. */\nexport function depTerminal(ctx: Ctx, depIndex: number): unknown {\n\tconst t = ctx.terminal[depIndex];\n\treturn t === undefined ? false : t;\n}\n","/**\n * Passive resilience policy helpers for graph-visible adapters (D130/D132).\n *\n * These helpers never schedule work and never own graph state. Drivers/adapters\n * consume them, while graph-visible bundles expose attempts/status/errors.\n */\n\nexport type BackoffPolicy =\n\t| { readonly kind: \"none\" }\n\t| { readonly kind: \"constant\"; readonly delayMs: number }\n\t| {\n\t\t\treadonly kind: \"linear\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly stepMs: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| {\n\t\t\treadonly kind: \"exponential\";\n\t\t\treadonly initialMs: number;\n\t\t\treadonly factor: number;\n\t\t\treadonly maxMs?: number;\n\t }\n\t| { readonly kind: \"fibonacci\"; readonly unitMs: number; readonly maxMs?: number };\n\nexport interface RetryPolicy {\n\t/** Total attempts including the first try. */\n\treadonly maxAttempts: number;\n\treadonly backoff: BackoffPolicy;\n}\n\nexport type RetryState = \"idle\" | \"running\" | \"waiting\" | \"succeeded\" | \"failed\" | \"exhausted\";\n\nexport interface RetryStatus {\n\treadonly attempt: number;\n\treadonly maxAttempts: number;\n\treadonly delayMs?: number;\n\treadonly state: RetryState;\n}\n\nexport const noBackoff: BackoffPolicy = Object.freeze({ kind: \"none\" });\n\nexport function retryPolicy(maxAttempts = 1, backoff: BackoffPolicy = noBackoff): RetryPolicy {\n\tif (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n\t\tthrow new RangeError(\"retryPolicy: maxAttempts must be a positive integer\");\n\t}\n\treturn Object.freeze({ maxAttempts, backoff });\n}\n\nexport function shouldRetry(policy: RetryPolicy, failedAttempt: number): boolean {\n\treturn failedAttempt < policy.maxAttempts;\n}\n\nexport function nextRetryDelayMs(policy: RetryPolicy, nextAttempt: number): number | undefined {\n\tif (!Number.isInteger(nextAttempt) || nextAttempt <= 0 || nextAttempt > policy.maxAttempts) {\n\t\treturn undefined;\n\t}\n\treturn backoffDelayMs(policy.backoff, nextAttempt);\n}\n\nexport function backoffDelayMs(policy: BackoffPolicy, attempt: number): number {\n\tconst safeAttempt = Math.max(1, Math.trunc(attempt));\n\tswitch (policy.kind) {\n\t\tcase \"none\":\n\t\t\treturn 0;\n\t\tcase \"constant\":\n\t\t\treturn nonNegative(policy.delayMs);\n\t\tcase \"linear\":\n\t\t\treturn cap(\n\t\t\t\tnonNegative(policy.initialMs) + nonNegative(policy.stepMs) * (safeAttempt - 1),\n\t\t\t\tpolicy.maxMs,\n\t\t\t);\n\t\tcase \"exponential\": {\n\t\t\tconst factor = Math.max(1, Math.trunc(policy.factor));\n\t\t\treturn cap(nonNegative(policy.initialMs) * factor ** (safeAttempt - 1), policy.maxMs);\n\t\t}\n\t\tcase \"fibonacci\":\n\t\t\treturn cap(nonNegative(policy.unitMs) * fibonacci(safeAttempt), policy.maxMs);\n\t}\n}\n\nfunction cap(value: number, max: number | undefined): number {\n\tif (max === undefined) return value;\n\treturn Math.min(value, nonNegative(max));\n}\n\nfunction nonNegative(value: number): number {\n\tif (!Number.isFinite(value)) return 0;\n\treturn Math.max(0, value);\n}\n\nfunction fibonacci(n: number): number {\n\tif (n <= 1) return 1;\n\tlet prev = 1;\n\tlet curr = 1;\n\tfor (let i = 2; i <= n; i += 1) {\n\t\tconst next = prev + curr;\n\t\tprev = curr;\n\t\tcurr = next;\n\t}\n\treturn curr;\n}\n","/**\n * The wave-owner boundary + deferred self-rewire drain (R-rewire-deferred / D47).\n *\n * `ctx.rewireNext` defers a node's OWN dep-set mutation to the COMMITTED wave boundary.\n * The substrate has no such boundary on the raw call stack, so this module establishes one:\n * a module-global re-entrant DEPTH counter — the TS analogue of the Rust `WaveScope` /\n * `with_wave_owner` (graphrefly-rs B25, flagged forward-load-bearing for exactly this). JS is\n * single-threaded and waves are synchronous, so one cascade is on the stack at a time (same\n * rationale as `batch.ts`'s module-global `active`).\n *\n * Every EXTERNAL wave origin brackets its synchronous cascade with {@link enterWave} /\n * {@link exitWave}: `Node.subscribe`/`Node.down`/`Node.up` (activation, state.set, control),\n * the async-pool `ctx.down`/`ctx.up` re-entry (which enters via the stashed ctx, NOT the public\n * method), and `batch()` (so the drain fires AFTER commit). Re-entrant (nested) calls just\n * inc/dec the counter; only the OUTERMOST exit (depth → 0) DRAINS the deferred-rewire queue.\n *\n * B49 migration: the deferred thunks now live on the graph-local NodeCore, not in this module.\n * This module keeps only the JS call-stack wave-owner depth plus a small FIFO of cores that\n * have work to drain. Per D22, a graph is the supported single-thread domain; cross-domain\n * coordination is the async wire bridge (D32), so the queued work for one legal synchronous cascade\n * belongs to one graph-local core. Standalone nodes keep their private core. Within a core, FIFO\n * issue order still gives the R-rewire-deferred drain order, and the scheduler records one core\n * token per queued task so mixed-core legal batches keep their enqueue order. Each queued mutation\n * runs as a fresh wave whose own `ctx.rewireNext` calls re-enqueue and drain in the same loop.\n *\n * C-25 / D110: queued boundary work is tagged with the batch frame that caused it (when any)\n * plus an owner-readiness predicate. The drain applies only committed, unpaused tasks; rollback\n * drops the batch's tasks, and paused owners re-schedule their core on final RESUME.\n * Zero behavior change when no `ctx.rewireNext`/`ctx.upNext` is ever called: the drain is one\n * empty-queue check per outermost wave (F-PERF).\n */\n\nimport type { NodeCore } from \"../node/core.js\";\n\nlet depth = 0;\nconst pendingCores: NodeCore[] = [];\nlet pendingHead = 0;\n\n/** Enter a wave cascade (re-entrant). Pair with {@link exitWave} in a try/finally. */\nexport function enterWave(): void {\n\tdepth++;\n}\n\n/** Exit a wave cascade; the OUTERMOST exit (depth → 0) drains the deferred-rewire queue. */\nexport function exitWave(): void {\n\tdepth--;\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\nexport interface DeferredBoundaryOptions {\n\treadonly batchToken?: object;\n\treadonly isReady?: () => boolean;\n}\n\n/**\n * Queue a deferred self-rewire application, drained at the committed boundary\n * (R-rewire-deferred). The thunk applies one queued mutation to its owning node.\n */\nexport function deferRewire(\n\tcore: NodeCore,\n\tapply: () => void,\n\toptions: DeferredBoundaryOptions = {},\n): void {\n\tcore.enqueueBoundaryTask({ apply, batchToken: options.batchToken, isReady: options.isReady });\n\tpendingCores.push(core);\n}\n\n/** Re-schedule an existing core queue, used when a final RESUME opens a paused boundary gate. */\nexport function scheduleBoundaryDrain(core: NodeCore): void {\n\tfor (let i = 0; i < core.boundaryTaskCount(); i++) pendingCores.push(core);\n\tif (depth === 0 && pendingHead < pendingCores.length) drain();\n}\n\n/** D110: an uncommitted batch cannot leak queued boundary effects. */\nexport function dropBoundaryTasksForBatch(batchToken: object): void {\n\tconst seen = new Set<NodeCore>();\n\tfor (let i = pendingHead; i < pendingCores.length; i++) {\n\t\tconst core = pendingCores[i] as NodeCore;\n\t\tif (seen.has(core)) continue;\n\t\tseen.add(core);\n\t\tcore.dropBoundaryTasksForBatch(batchToken);\n\t}\n}\n\nfunction drain(): void {\n\t// Each applied rewire runs a fresh wave (its own depth-bracketed cascade) which may itself\n\t// enqueue more rewireNext requests — appended and drained by this same FIFO loop\n\t// (DrainExactlyOnce). The depth++ around apply() prevents the fresh wave's own outermost\n\t// exit from re-entering drain (this loop owns the draining). A net-changing op re-issued\n\t// every boundary (oscillation) is a user-level runaway, like an infinite producer — NOT a\n\t// substrate-detected error (D47).\n\t//\n\t// Per-thunk isolation: a thunk whose application throws (e.g. its _applyRewireNext error-route\n\t// reaches a throwing external sink) must NOT abandon the rest of the queue — otherwise the\n\t// stranded thunks would linger in this module-global queue and drain at an unrelated LATER\n\t// wave boundary (a stale, misattributed rewire). Drain every thunk; re-surface the FIRST\n\t// escape once the queue is empty so the error stays visible without corrupting the queue.\n\tlet escaped: { e: unknown } | null = null;\n\twhile (pendingHead < pendingCores.length) {\n\t\tconst core = pendingCores[pendingHead++] as NodeCore;\n\t\tconst task = core.shiftBoundaryTask();\n\t\tif (task === undefined) continue;\n\t\tif (task.batchToken !== undefined) {\n\t\t\t// A stale token means the batch never reached the committed boundary (D110). Rollback\n\t\t\t// normally removes these before drain; this guard covers commit failures before the\n\t\t\t// batch frame marks itself committed.\n\t\t\tconst committed = (task.batchToken as { committed?: boolean }).committed === true;\n\t\t\tif (!committed) continue;\n\t\t}\n\t\tif (task.isReady !== undefined && !task.isReady()) {\n\t\t\tcore.unshiftBoundaryTask(task);\n\t\t\tcontinue;\n\t\t}\n\t\tdepth++;\n\t\ttry {\n\t\t\ttask.apply();\n\t\t} catch (e) {\n\t\t\tif (escaped === null) escaped = { e };\n\t\t} finally {\n\t\t\tdepth--;\n\t\t}\n\t}\n\tpendingCores.length = 0;\n\tpendingHead = 0;\n\tif (escaped !== null) throw escaped.e;\n}\n","/**\n * Declarative batch (R-batch-coalesce / D12).\n *\n * Inside a batch, DIRTY propagates immediately but the tier-3 settle slice\n * (DATA/RESOLVED/INVALIDATE) is deferred to commit, so a shared downstream\n * recomputes ONCE after all batched sources settle. Success -> commit; a thrown\n * error -> rollback; `bctx.rollback()` is the explicit escape hatch.\n *\n * Coalescing note: this kernel coalesces multiple emits to the SAME node within\n * one batch to the latest tier-3 wave (last-value-wins). Full per-item batch-array\n * delivery (downstream fn receiving [v1..vK]) is a documented refinement — the\n * dominant use (coalescing a diamond join to one recompute) is exact here.\n */\n\nimport type { Wave } from \"../protocol/messages.js\";\nimport { dropBoundaryTasksForBatch, enterWave, exitWave } from \"./boundary.js\";\n\n/** A node target the batch can commit/rollback against (structural, avoids an import cycle). */\nexport interface BatchTarget {\n\t__commitBatchedWave(wave: Wave): void;\n\t__rollbackBatched(): void;\n\t__deferBoundary(fn: () => void, batchToken?: object): void;\n}\n\nexport interface BatchCtx {\n\t/** Discard all deferred emissions in this batch instead of committing. */\n\trollback(): void;\n}\n\ninterface ActiveBatch {\n\torder: BatchTarget[];\n\tdeferred: Map<BatchTarget, Wave>;\n\tcommitted: boolean;\n\trolledBack: boolean;\n}\n\nlet active: ActiveBatch | null = null;\nlet boundaryOwner: ActiveBatch | null = null;\n\nexport function currentBatch(): boolean {\n\treturn active !== null;\n}\n\nexport function currentBoundaryBatchToken(): object | undefined {\n\treturn active ?? boundaryOwner ?? undefined;\n}\n\n/**\n * Defer a node's tier-3 settle slice into the active batch. Returns true if a batch\n * captured it; false if there is no active batch (caller emits normally).\n */\nexport function deferToBatch(target: BatchTarget, tier3Wave: Wave): boolean {\n\tif (active === null) return false;\n\tif (!active.deferred.has(target)) active.order.push(target);\n\tactive.deferred.set(target, tier3Wave); // last-value coalescing\n\treturn true;\n}\n\n/**\n * Defer a topology mutation until after the active batch has committed/rolled back,\n * but only when this target has an uncommitted settle slice in the current batch.\n */\nexport function deferAfterBatchForTarget(target: BatchTarget, fn: () => void): boolean {\n\tif (active === null || !active.deferred.has(target)) return false;\n\tconst owner = active;\n\ttarget.__deferBoundary(() => {\n\t\tif (owner.committed) fn();\n\t}, owner);\n\treturn true;\n}\n\nfunction commit(b: ActiveBatch): void {\n\tconst prev = boundaryOwner;\n\tboundaryOwner = b;\n\ttry {\n\t\tfor (const target of b.order) {\n\t\t\tconst wave = b.deferred.get(target);\n\t\t\tif (wave) target.__commitBatchedWave(wave);\n\t\t}\n\t\tb.committed = true;\n\t} catch (e) {\n\t\tdropBoundaryTasksForBatch(b);\n\t\tthrow e;\n\t} finally {\n\t\tboundaryOwner = prev;\n\t}\n}\n\nfunction rollback(b: ActiveBatch): void {\n\tdropBoundaryTasksForBatch(b);\n\tfor (const target of b.order) target.__rollbackBatched();\n}\n\n/** Run `fn` as a batch (D12). DATA deferred to commit; throw/rollback discards. */\nexport function batch<R>(fn: (bctx: BatchCtx) => R): R {\n\t// Wave-owner boundary (R-rewire-deferred / D47): bracket the whole batch (fn + commit) so a\n\t// ctx.rewireNext issued by a fn that runs during COMMIT drains AFTER the commit, never on the\n\t// un-committed view. Inner waves (state.set, commit cascade) nest under this owner.\n\tenterWave();\n\ttry {\n\t\tif (active !== null) {\n\t\t\t// Nested batch joins the outer frame (one commit at the outermost exit).\n\t\t\tconst outer = active;\n\t\t\treturn fn({\n\t\t\t\trollback: () => {\n\t\t\t\t\touter.rolledBack = true;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconst b: ActiveBatch = { order: [], deferred: new Map(), committed: false, rolledBack: false };\n\t\tactive = b;\n\t\tconst bctx: BatchCtx = {\n\t\t\trollback: () => {\n\t\t\t\tb.rolledBack = true;\n\t\t\t},\n\t\t};\n\t\tlet result: R;\n\t\ttry {\n\t\t\tresult = fn(bctx);\n\t\t} catch (e) {\n\t\t\tactive = null;\n\t\t\trollback(b);\n\t\t\tthrow e;\n\t\t}\n\t\tactive = null;\n\t\tif (b.rolledBack) rollback(b);\n\t\telse {\n\t\t\tcommit(b);\n\t\t}\n\t\treturn result;\n\t} finally {\n\t\texitWave();\n\t}\n}\n","/**\n * Dispatcher, pools, and the pure-data Handle.\n *\n * Canonical authority: ~/src/graphrefly/spec/rules.jsonl\n * R-handle (D7), R-dispatch-all (D21), R-sync-core (D20/D21).\n *\n * Lifted from the validated handle-dispatch PoC (packages/pure-ts r8-poc, R8/R9):\n * fn lives in an external pool, indexed by handle; `dispatcher.invoke` is uniformly\n * SYNC void — async/remote behavior lives in the fn body (it kicks off async work\n * and emits later via `ctx.down`), not in a different call mechanism.\n */\n\nimport type { Ctx, NodeFn } from \"../ctx/types.js\";\n\n/** A pool kind label. LocalSync + LocalAsync ship in 1.0 (D20). */\nexport type PoolKind = \"sync\" | \"async\";\n\n/**\n * Handle = pure data `(poolId, handleId)`, NO methods (R-handle / D7). A serializable\n * index into a pool's dispatch table. node != handle.\n */\nexport interface Handle {\n\treadonly poolId: number;\n\treadonly handleId: number;\n}\n\n/** A dispatch pool: a flat fn table + an array-indexed sync invoke. */\nexport interface Pool {\n\treadonly kind: PoolKind;\n\tregister(fn: NodeFn): number;\n\t/** Free a handle's slot so its fn closure is GC'd and the id is reused (B15). */\n\tunregister(handleId: number): void;\n\tinvoke(handleId: number, ctx: Ctx): void;\n}\n\n/**\n * Array-indexed fn table with a free-list (B15). `register` reuses a freed slot before\n * growing the array, so a rewire-heavy graph (fn-swap on every replaceDeps/subscribeDep/unsubscribeDep,\n * e.g. CSP-2.7 higher-order *Map operators) keeps the table bounded to its peak live size\n * instead of leaking a slot + closure per swap. `unregister` tombstones the slot (drops the\n * closure reference for GC) and offers the id for reuse. handleId reuse is safe: the graph is\n * a single causal domain (D22) and D37 forbids a fn rewiring its own handle mid-run, so a\n * freed id is never re-registered while an invoke of it is in flight. The hot path stays a\n * raw array index (F-PERF).\n */\nclass PoolTable implements Pool {\n\tconstructor(readonly kind: PoolKind) {}\n\tprivate fns: (NodeFn | undefined)[] = [];\n\tprivate free: number[] = [];\n\tregister(fn: NodeFn): number {\n\t\tconst reused = this.free.pop();\n\t\tif (reused !== undefined) {\n\t\t\tthis.fns[reused] = fn;\n\t\t\treturn reused;\n\t\t}\n\t\tconst id = this.fns.length;\n\t\tthis.fns.push(fn);\n\t\treturn id;\n\t}\n\tunregister(handleId: number): void {\n\t\tif (this.fns[handleId] === undefined) return; // already free → idempotent\n\t\tthis.fns[handleId] = undefined; // drop the closure (GC)\n\t\tthis.free.push(handleId); // offer the slot for reuse (bounded growth)\n\t}\n\tinvoke(handleId: number, ctx: Ctx): void {\n\t\t// A live handle always resolves to a fn; a dead/unregistered id throws (TypeError —\n\t\t// invoking an unregistered handle is a bug, surfaced loudly). Cast keeps the hot path\n\t\t// a raw index with no extra branch (F-PERF).\n\t\t(this.fns[handleId] as NodeFn)(ctx);\n\t}\n}\n\n/**\n * First-class dispatcher (D21). Owns pools; graph binds to one (default = process-global,\n * D26 — the only global singleton). Pool trait is pluggable for WorkerPool/RemotePool (D20).\n */\n/** Per-handle profiling counters (D39 / R-profile). Lives on the dispatcher — the invoke\n * funnel (F-DISPATCH-ALL) — NEVER on the thin node (R-node-thin). */\nexport interface HandleStat {\n\tinvokes: number;\n\ttotalDurationNs: number;\n\tlastDurationNs: number;\n}\n\nconst statKey = (h: Handle): string => `${h.poolId}:${h.handleId}`;\n\nexport class Dispatcher {\n\tprivate pools: Pool[] = [];\n\treadonly syncPoolId: number;\n\treadonly asyncPoolId: number;\n\n\t// opt-in profile recorder (default OFF → zero overhead, F-PERF).\n\tprivate _recording = false;\n\tprivate _stats = new Map<string, HandleStat>();\n\tprivate _totalInvokes = 0;\n\n\tconstructor() {\n\t\tthis.syncPoolId = this.addPool(new PoolTable(\"sync\"));\n\t\tthis.asyncPoolId = this.addPool(new PoolTable(\"async\"));\n\t}\n\n\t/** Turn the profile recorder on/off (D39). Off = zero overhead on invoke. */\n\tsetRecording(on: boolean): void {\n\t\tthis._recording = on;\n\t}\n\t/** Reset accumulated profiling counters. */\n\tclearStats(): void {\n\t\tthis._stats.clear();\n\t\tthis._totalInvokes = 0;\n\t}\n\t/** Read a handle's accumulated counters (undefined if it never ran while recording). */\n\tstatFor(handle: Handle): HandleStat | undefined {\n\t\treturn this._stats.get(statKey(handle));\n\t}\n\t/** Total fn invocations recorded across the dispatcher. */\n\tget totalInvokes(): number {\n\t\treturn this._totalInvokes;\n\t}\n\n\taddPool(pool: Pool): number {\n\t\tconst id = this.pools.length;\n\t\tthis.pools.push(pool);\n\t\treturn id;\n\t}\n\n\t/** Register a fn in a pool, returning its Handle. Default pool = sync (R-sync-core). */\n\tregister(fn: NodeFn, pool: PoolKind | number = \"sync\"): Handle {\n\t\tconst poolId = pool === \"sync\" ? this.syncPoolId : pool === \"async\" ? this.asyncPoolId : pool;\n\t\tconst handleId = this.pools[poolId].register(fn);\n\t\treturn { poolId, handleId };\n\t}\n\n\t/**\n\t * Release a handle (B15): frees the pool slot (closure GC'd, id reusable) and drops any\n\t * accumulated profile stat so a reused id never inherits the previous tenant's counters.\n\t * Called on rewire fn-swap (node._rewire) — the old handle is dropped before the node\n\t * adopts the new one. Idempotent. NOT called on deactivate (a node's handle survives\n\t * activate↔deactivate and is reused on reactivation; only a rewire swaps it).\n\t */\n\tunregister(handle: Handle): void {\n\t\tthis.pools[handle.poolId].unregister(handle.handleId);\n\t\t// Drop the stat UNCONDITIONALLY (QA F2.1), not only while recording: if recording was\n\t\t// OFF at unregister time the key would linger, and a later register reusing this id (the\n\t\t// free-list) would inherit the prior tenant's counters once recording resumes. delete of\n\t\t// an absent key is a cheap no-op; unregister is off the hot invoke path (F-PERF intact).\n\t\tthis._stats.delete(statKey(handle));\n\t}\n\n\t/** Uniform sync-void invoke (R-sync-core / R-dispatch-all). */\n\tinvoke(handle: Handle, ctx: Ctx): void {\n\t\tif (!this._recording) {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t\treturn;\n\t\t}\n\t\tthis._totalInvokes++;\n\t\tconst t0 = performance.now();\n\t\ttry {\n\t\t\tthis.pools[handle.poolId].invoke(handle.handleId, ctx);\n\t\t} finally {\n\t\t\tconst dur = (performance.now() - t0) * 1e6; // ms → ns\n\t\t\tconst key = statKey(handle);\n\t\t\tconst s = this._stats.get(key) ?? {\n\t\t\t\tinvokes: 0,\n\t\t\t\ttotalDurationNs: 0,\n\t\t\t\tlastDurationNs: 0,\n\t\t\t};\n\t\t\ts.invokes++;\n\t\t\ts.lastDurationNs = dur;\n\t\t\ts.totalDurationNs += dur;\n\t\t\tthis._stats.set(key, s);\n\t\t}\n\t}\n\n\tpoolKind(poolId: number): PoolKind {\n\t\treturn this.pools[poolId].kind;\n\t}\n}\n\n/** The only global singleton (D26). Overridable by passing an explicit dispatcher. */\nexport const defaultDispatcher = new Dispatcher();\n","/**\n * Graph-owned environment driver bag (D130/D131).\n *\n * Drivers host process/network/messaging/runtime boundary work outside the synchronous wave core.\n * The bag is graph-local and is read from ctx by source/adapter bodies.\n */\n\nexport type DriverCancel = () => void;\n\nexport type DriverResult<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly error: unknown };\n\nexport interface ProcessCommand {\n\treadonly program: string;\n\treadonly args: readonly string[];\n\treadonly cwd?: string;\n\treadonly env?: readonly (readonly [string, string])[];\n}\n\nexport interface ProcessResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n\treadonly exitCode: number | null;\n\treadonly signal: string | null;\n}\n\nexport interface HttpRequest {\n\treadonly method: string;\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n\treadonly body?: Uint8Array | string;\n}\n\nexport interface HttpResponse {\n\treadonly status: number;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport interface SseRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport interface SseEvent {\n\treadonly event?: string;\n\treadonly data: string;\n\treadonly id?: string;\n\treadonly retryMs?: number;\n}\n\nexport type SseDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: SseEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebSocketRequest {\n\treadonly url: string;\n\treadonly headers?: readonly (readonly [string, string])[];\n}\n\nexport type WebSocketEvent =\n\t| { readonly kind: \"open\" }\n\t| { readonly kind: \"text\"; readonly data: string }\n\t| { readonly kind: \"binary\"; readonly data: Uint8Array }\n\t| { readonly kind: \"close\"; readonly code?: number; readonly reason?: string };\n\nexport interface WebSocketSend {\n\treadonly data: string | Uint8Array;\n}\n\nexport interface WebSocketSendResult {\n\treadonly sent: true;\n}\n\n/** Live WebSocket session handle for D133 SessionBundle adapters. */\nexport interface WebSocketSessionHandle {\n\tsend(\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\tclose(code?: number, reason?: string): void;\n\tcancel(): void;\n}\n\nexport type WebSocketDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebSocketEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface WebhookRegistration {\n\treadonly id: string;\n\treadonly method?: string;\n\treadonly path?: string;\n}\n\nexport interface WebhookEvent {\n\treadonly registrationId: string;\n\treadonly method: string;\n\treadonly path: string;\n\treadonly headers: readonly (readonly [string, string])[];\n\treadonly query: readonly (readonly [string, string])[];\n\treadonly body: Uint8Array;\n}\n\nexport type WebhookDriverEvent =\n\t| { readonly kind: \"event\"; readonly event: WebhookEvent }\n\t| { readonly kind: \"error\"; readonly error: unknown }\n\t| { readonly kind: \"complete\" };\n\nexport interface LocalProcessDriver {\n\trun(\n\t\tcommand: ProcessCommand,\n\t\tcallback: (result: DriverResult<ProcessResult>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalHttpDriver {\n\trequest(\n\t\trequest: HttpRequest,\n\t\tcallback: (result: DriverResult<HttpResponse>) => void,\n\t): DriverCancel;\n}\n\nexport interface LocalSseDriver {\n\tconnect(request: SseRequest, callback: (event: SseDriverEvent) => void): DriverCancel;\n}\n\nexport interface LocalWebSocketDriver {\n\tconnect(request: WebSocketRequest, callback: (event: WebSocketDriverEvent) => void): DriverCancel;\n\tsend?(\n\t\trequest: WebSocketRequest,\n\t\tmessage: WebSocketSend,\n\t\tcallback: (result: DriverResult<WebSocketSendResult>) => void,\n\t): DriverCancel;\n\t/** Open a live bidirectional session; unlike send(), outbound messages use this same connection. */\n\tconnectSession?(\n\t\trequest: WebSocketRequest,\n\t\tcallback: (event: WebSocketDriverEvent) => void,\n\t): WebSocketSessionHandle;\n}\n\nexport interface LocalWebhookDriver {\n\tregister(\n\t\tregistration: WebhookRegistration,\n\t\tcallback: (event: WebhookDriverEvent) => void,\n\t): DriverCancel;\n}\n\nexport interface FetchResponseLike {\n\treadonly status: number;\n\treadonly headers?: { forEach?(fn: (value: string, key: string) => void): void };\n\tarrayBuffer(): PromiseLike<ArrayBuffer>;\n}\n\nexport type FetchLike = (\n\turl: string,\n\tinit?: {\n\t\treadonly method?: string;\n\t\treadonly headers?: readonly (readonly [string, string])[];\n\t\treadonly body?: Uint8Array | string;\n\t\treadonly signal?: AbortSignal;\n\t},\n) => PromiseLike<FetchResponseLike>;\n\nexport interface WebSocketLike {\n\tsend(data: string | Uint8Array): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n\tremoveEventListener(\n\t\ttype: \"open\" | \"message\" | \"error\" | \"close\",\n\t\tlistener: (event: unknown) => void,\n\t): void;\n}\n\nexport type WebSocketConstructorLike = new (url: string) => WebSocketLike;\n\nexport interface EnvironmentDriversInit {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n}\n\nexport class EnvironmentDrivers {\n\treadonly process?: LocalProcessDriver;\n\treadonly http?: LocalHttpDriver;\n\treadonly sse?: LocalSseDriver;\n\treadonly websocket?: LocalWebSocketDriver;\n\treadonly webhook?: LocalWebhookDriver;\n\n\tconstructor(init: EnvironmentDriversInit = {}) {\n\t\tthis.process = init.process;\n\t\tthis.http = init.http;\n\t\tthis.sse = init.sse;\n\t\tthis.websocket = init.websocket;\n\t\tthis.webhook = init.webhook;\n\t\tObject.freeze(this);\n\t}\n\n\tstatic empty(): EnvironmentDrivers {\n\t\treturn EMPTY_ENVIRONMENT;\n\t}\n\n\twithProcess(driver: LocalProcessDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, process: driver });\n\t}\n\n\twithHttp(driver: LocalHttpDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, http: driver });\n\t}\n\n\twithSse(driver: LocalSseDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, sse: driver });\n\t}\n\n\twithWebSocket(driver: LocalWebSocketDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, websocket: driver });\n\t}\n\n\twithWebhook(driver: LocalWebhookDriver): EnvironmentDrivers {\n\t\treturn new EnvironmentDrivers({ ...this, webhook: driver });\n\t}\n\n\tprocessDriver(): LocalProcessDriver | undefined {\n\t\treturn this.process;\n\t}\n\n\thttpDriver(): LocalHttpDriver | undefined {\n\t\treturn this.http;\n\t}\n\n\tsseDriver(): LocalSseDriver | undefined {\n\t\treturn this.sse;\n\t}\n\n\twebSocketDriver(): LocalWebSocketDriver | undefined {\n\t\treturn this.websocket;\n\t}\n\n\twebhookDriver(): LocalWebhookDriver | undefined {\n\t\treturn this.webhook;\n\t}\n}\n\nconst EMPTY_ENVIRONMENT = new EnvironmentDrivers();\n\nexport function fetchHttpDriver(fetchFn: FetchLike = requireGlobalFetch()): LocalHttpDriver {\n\treturn {\n\t\trequest(request, callback) {\n\t\t\tconst controller = new AbortController();\n\t\t\tvoid Promise.resolve(\n\t\t\t\tfetchFn(request.url, {\n\t\t\t\t\tmethod: request.method,\n\t\t\t\t\theaders: request.headers,\n\t\t\t\t\tbody: request.body,\n\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t}),\n\t\t\t).then(\n\t\t\t\tasync (response) => {\n\t\t\t\t\tconst headers: Array<readonly [string, string]> = [];\n\t\t\t\t\tresponse.headers?.forEach?.((value, key) => {\n\t\t\t\t\t\theaders.push([key, value]);\n\t\t\t\t\t});\n\t\t\t\t\tconst body = new Uint8Array(await response.arrayBuffer());\n\t\t\t\t\tcallback({ ok: true, value: { status: response.status, headers, body } });\n\t\t\t\t},\n\t\t\t\t(error) => callback({ ok: false, error }),\n\t\t\t);\n\t\t\treturn () => controller.abort();\n\t\t},\n\t};\n}\n\nexport function domWebSocketDriver(\n\tWebSocketCtor: WebSocketConstructorLike = requireGlobalWebSocket(),\n): LocalWebSocketDriver {\n\treturn {\n\t\tconnect(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tsend(request, message, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet settled = false;\n\t\t\tconst finish = (result: DriverResult<WebSocketSendResult>) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcallback(result);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t\tconst onOpen = () => {\n\t\t\t\ttry {\n\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\tfinish({ ok: true, value: { sent: true } });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinish({ ok: false, error });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => finish({ ok: false, error: event });\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.close();\n\t\t\t};\n\t\t},\n\t\tconnectSession(request, callback) {\n\t\t\tconst socket = new WebSocketCtor(request.url);\n\t\t\tlet active = true;\n\t\t\tconst onOpen = () => callback({ kind: \"event\", event: { kind: \"open\" } });\n\t\t\tconst onMessage = (event: unknown) => {\n\t\t\t\tconst data = (event as { data?: unknown }).data;\n\t\t\t\tif (typeof data === \"string\") callback({ kind: \"event\", event: { kind: \"text\", data } });\n\t\t\t\telse if (data instanceof Uint8Array) {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"binary\", data } });\n\t\t\t\t} else {\n\t\t\t\t\tcallback({ kind: \"event\", event: { kind: \"text\", data: String(data ?? \"\") } });\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst onError = (event: unknown) => callback({ kind: \"error\", error: event });\n\t\t\tconst onClose = (event: unknown) => {\n\t\t\t\tconst close = event as { code?: number; reason?: string };\n\t\t\t\tcallback({\n\t\t\t\t\tkind: \"event\",\n\t\t\t\t\tevent: { kind: \"close\", code: close.code, reason: close.reason },\n\t\t\t\t});\n\t\t\t\tcallback({ kind: \"complete\" });\n\t\t\t};\n\t\t\tconst removeListeners = () => {\n\t\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\t};\n\t\t\tsocket.addEventListener(\"open\", onOpen);\n\t\t\tsocket.addEventListener(\"message\", onMessage);\n\t\t\tsocket.addEventListener(\"error\", onError);\n\t\t\tsocket.addEventListener(\"close\", onClose);\n\t\t\treturn {\n\t\t\t\tsend(message, sendCallback) {\n\t\t\t\t\tlet canceled = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsocket.send(message.data);\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: true, value: { sent: true } });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!canceled) sendCallback({ ok: false, error });\n\t\t\t\t\t}\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tclose(code, reason) {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t},\n\t\t\t\tcancel() {\n\t\t\t\t\tif (!active) return;\n\t\t\t\t\tactive = false;\n\t\t\t\t\tremoveListeners();\n\t\t\t\t\tsocket.close();\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction requireGlobalFetch(): FetchLike {\n\tconst fetchFn = (globalThis as { fetch?: FetchLike }).fetch;\n\tif (fetchFn === undefined) throw new Error(\"fetchHttpDriver: global fetch is not available\");\n\treturn fetchFn;\n}\n\nfunction requireGlobalWebSocket(): WebSocketConstructorLike {\n\tconst ctor = (globalThis as { WebSocket?: WebSocketConstructorLike }).WebSocket;\n\tif (ctor === undefined) throw new Error(\"domWebSocketDriver: global WebSocket is not available\");\n\treturn ctor;\n}\n","import type { Ctx, Sink } from \"../ctx/types.js\";\nimport type { Dispatcher, Handle } from \"../dispatcher/index.js\";\nimport type { EnvironmentDrivers } from \"../graph/environment.js\";\nimport { type LockId, SENTINEL, type Wave } from \"../protocol/messages.js\";\nimport type { Node, Status } from \"./node.js\";\nimport type { NodeVersion, ResolvedNodeVersioningPolicy } from \"./versioning.js\";\n\nexport type NodeId = number & { readonly __nodeId: unique symbol };\n\nexport interface DepBookkeeping {\n\tbatch: Array<unknown[] | null>;\n\twaveData: unknown[][][];\n\twaveTokens: Array<object | undefined>;\n\tprev: unknown[];\n\thasData: boolean[];\n\tdirty: boolean[];\n\ttier: number[];\n\tterminal: Array<true | unknown | undefined>;\n\tterminalInput: Array<true | unknown | undefined>;\n\tunsubs: Array<() => void>;\n\tidxBoxes: Array<{ v: number }>;\n}\n\nexport interface ValueState<T> {\n\tcache: T | undefined;\n\thasData: boolean;\n\tstatus: Status;\n\tterminal: true | unknown | undefined;\n\thasTorndown: boolean;\n\treplayRing: T[];\n}\n\nexport interface VersionState {\n\tpolicy: ResolvedNodeVersioningPolicy;\n\tvalue: NodeVersion | undefined;\n}\n\nexport interface WaveState {\n\tpending: number;\n\thasCalledFnOnce: boolean;\n\temittedDirtyThisWave: boolean;\n\temittedSettleThisWave: boolean;\n\tinsideRunWave: boolean;\n\tinDepMutation: boolean;\n\trewireRunPending: boolean;\n\tbatchDirtyOwed: boolean;\n}\n\nexport interface ControlState {\n\tpauseLockset: Set<unknown>;\n\tpausedDepWaveOccurred: boolean;\n\tpauseBuffer: Wave[];\n\tdemandOwed: boolean;\n\tinDeliverDemand: boolean;\n}\n\nexport interface PrivateState {\n\tvalue: unknown;\n\tpersist: boolean;\n}\n\nexport interface CleanupHooks {\n\tonDeactivation: Array<() => void>;\n\tonInvalidate: Array<() => void>;\n}\n\nexport interface SyncCtxState {\n\tvalue: Ctx | null;\n}\n\nexport interface LifecycleState {\n\tsubscribers: Set<Sink>;\n\tactivated: boolean;\n}\n\nexport interface BoundaryTask {\n\tapply: () => void;\n\tbatchToken?: object;\n\tisReady?: () => boolean;\n}\n\nexport interface BoundaryState {\n\tqueue: BoundaryTask[];\n\thead: number;\n}\n\nexport interface NodeSlot<_T> {\n\tid: NodeId;\n\tdeps: Node<unknown>[];\n\thandle: Handle | null;\n\tpool: \"sync\" | \"async\";\n\tdispatcher: Dispatcher;\n\tenvironment: EnvironmentDrivers;\n\tpartial: boolean;\n\tterminalAsRealInput: boolean;\n\tcompleteWhenDepsComplete: boolean;\n\terrorWhenDepsError: boolean;\n\tresubscribable: boolean;\n\tresetOnTeardown: boolean;\n\tpausable: boolean | \"resumeAll\";\n\tpull: boolean;\n\tpullLock: LockId | undefined;\n\treplayN: number;\n\tdynamic: boolean;\n\tname?: string;\n\tfactory?: string;\n}\n\nexport interface NodeState<T> {\n\tdep: DepBookkeeping;\n\tlifecycle: LifecycleState;\n\tvalue: ValueState<T>;\n\tversion: VersionState;\n\twave: WaveState;\n\tcontrol: ControlState;\n\tprivateState: PrivateState;\n\thooks: CleanupHooks;\n\tsyncCtx: SyncCtxState;\n}\n\nexport class NodeCore {\n\tprivate nextId = 0;\n\tprivate readonly slots: Array<NodeSlot<unknown> | undefined> = [];\n\tprivate readonly values: Array<ValueState<unknown> | undefined> = [];\n\tprivate readonly waves: Array<WaveState | undefined> = [];\n\tprivate readonly controls: Array<ControlState | undefined> = [];\n\tprivate readonly lifecycles: Array<LifecycleState | undefined> = [];\n\tprivate readonly depStates: Array<DepBookkeeping | undefined> = [];\n\tprivate readonly privateStates: Array<PrivateState | undefined> = [];\n\tprivate readonly hooks: Array<CleanupHooks | undefined> = [];\n\tprivate readonly syncCtxs: Array<SyncCtxState | undefined> = [];\n\tprivate readonly versionStates: Array<VersionState | undefined> = [];\n\tprivate readonly boundary: BoundaryState = { queue: [], head: 0 };\n\n\tcreateSlot<T>(\n\t\tslot: Omit<NodeSlot<T>, \"id\">,\n\t\tstate: NodeState<T>,\n\t): { id: NodeId; slot: NodeSlot<T> } {\n\t\tconst id = this.nextId++ as NodeId;\n\t\tconst full = { ...slot, id };\n\t\tthis.slots[id] = full as NodeSlot<unknown>;\n\t\tthis.depStates[id] = state.dep;\n\t\tthis.lifecycles[id] = state.lifecycle;\n\t\tthis.values[id] = state.value as ValueState<unknown>;\n\t\tthis.waves[id] = state.wave;\n\t\tthis.controls[id] = state.control;\n\t\tthis.privateStates[id] = state.privateState;\n\t\tthis.hooks[id] = state.hooks;\n\t\tthis.syncCtxs[id] = state.syncCtx;\n\t\tthis.versionStates[id] = state.version;\n\t\treturn { id, slot: full };\n\t}\n\n\tget<T>(id: NodeId): NodeSlot<T> {\n\t\tconst slot = this.slots[id];\n\t\tif (slot === undefined) throw new Error(\"NodeCore: unknown node slot\");\n\t\treturn slot as NodeSlot<T>;\n\t}\n\n\tgetValue<T>(id: NodeId): ValueState<T> {\n\t\tconst value = this.values[id];\n\t\tif (value === undefined) throw new Error(\"NodeCore: unknown node value state\");\n\t\treturn value as ValueState<T>;\n\t}\n\n\tgetWave(id: NodeId): WaveState {\n\t\tconst wave = this.waves[id];\n\t\tif (wave === undefined) throw new Error(\"NodeCore: unknown node wave state\");\n\t\treturn wave;\n\t}\n\n\tgetControl(id: NodeId): ControlState {\n\t\tconst control = this.controls[id];\n\t\tif (control === undefined) throw new Error(\"NodeCore: unknown node control state\");\n\t\treturn control;\n\t}\n\n\tgetLifecycle(id: NodeId): LifecycleState {\n\t\tconst lifecycle = this.lifecycles[id];\n\t\tif (lifecycle === undefined) throw new Error(\"NodeCore: unknown node lifecycle state\");\n\t\treturn lifecycle;\n\t}\n\n\tgetDep(id: NodeId): DepBookkeeping {\n\t\tconst dep = this.depStates[id];\n\t\tif (dep === undefined) throw new Error(\"NodeCore: unknown node dep state\");\n\t\treturn dep;\n\t}\n\n\tgetPrivateState(id: NodeId): PrivateState {\n\t\tconst state = this.privateStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node private state\");\n\t\treturn state;\n\t}\n\n\tgetHooks(id: NodeId): CleanupHooks {\n\t\tconst hooks = this.hooks[id];\n\t\tif (hooks === undefined) throw new Error(\"NodeCore: unknown node cleanup hooks\");\n\t\treturn hooks;\n\t}\n\n\tgetSyncCtx(id: NodeId): SyncCtxState {\n\t\tconst state = this.syncCtxs[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node ctx state\");\n\t\treturn state;\n\t}\n\n\tgetVersion(id: NodeId): VersionState {\n\t\tconst state = this.versionStates[id];\n\t\tif (state === undefined) throw new Error(\"NodeCore: unknown node version state\");\n\t\treturn state;\n\t}\n\n\t/** @internal D122: release graph-owned ephemeral node runtime state from core retention. */\n\treleaseSlot(id: NodeId): void {\n\t\tthis.slots[id] = undefined;\n\t\tthis.depStates[id] = undefined;\n\t\tthis.lifecycles[id] = undefined;\n\t\tthis.values[id] = undefined;\n\t\tthis.waves[id] = undefined;\n\t\tthis.controls[id] = undefined;\n\t\tthis.privateStates[id] = undefined;\n\t\tthis.hooks[id] = undefined;\n\t\tthis.syncCtxs[id] = undefined;\n\t\tthis.versionStates[id] = undefined;\n\t}\n\n\t/** @internal B49: graph-local deferred-boundary queue (rewireNext/upNext/batch-after-commit). */\n\tenqueueBoundaryTask(task: BoundaryTask): void {\n\t\tthis.boundary.queue.push(task);\n\t}\n\n\t/** @internal */\n\thasBoundaryTasks(): boolean {\n\t\treturn this.boundary.head < this.boundary.queue.length;\n\t}\n\n\t/** @internal */\n\tboundaryTaskCount(): number {\n\t\treturn this.boundary.queue.length - this.boundary.head;\n\t}\n\n\t/** @internal */\n\tshiftBoundaryTask(): BoundaryTask | undefined {\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst task = this.boundary.queue[this.boundary.head++];\n\t\tif (!this.hasBoundaryTasks()) {\n\t\t\tthis.boundary.queue = [];\n\t\t\tthis.boundary.head = 0;\n\t\t}\n\t\treturn task;\n\t}\n\n\t/** @internal Put a not-yet-ready task back at this core's FIFO head. */\n\tunshiftBoundaryTask(task: BoundaryTask): void {\n\t\tconst remaining = this.boundary.queue.slice(this.boundary.head);\n\t\tthis.boundary.queue = [task, ...remaining];\n\t\tthis.boundary.head = 0;\n\t}\n\n\t/** @internal D110: discard all pending tasks caused by an uncommitted batch. */\n\tdropBoundaryTasksForBatch(batchToken: object): void {\n\t\tconst remaining = this.boundary.queue\n\t\t\t.slice(this.boundary.head)\n\t\t\t.filter((task) => task.batchToken !== batchToken);\n\t\tthis.boundary.queue = remaining;\n\t\tthis.boundary.head = 0;\n\t}\n}\n\nexport function makeDepBookkeeping(depCount: number): DepBookkeeping {\n\treturn {\n\t\tbatch: new Array(depCount).fill(null),\n\t\twaveData: Array.from({ length: depCount }, () => []),\n\t\twaveTokens: new Array(depCount).fill(undefined),\n\t\tprev: new Array(depCount).fill(SENTINEL),\n\t\thasData: new Array(depCount).fill(false),\n\t\tdirty: new Array(depCount).fill(false),\n\t\ttier: new Array(depCount).fill(0),\n\t\tterminal: new Array(depCount).fill(undefined),\n\t\tterminalInput: new Array(depCount).fill(undefined),\n\t\tunsubs: [],\n\t\tidxBoxes: [],\n\t};\n}\n","/**\n * Neutral JSON/encoding utilities (D96).\n *\n * Shared by graph checkpoints and storage bindings; neither layer owns the strict JSON\n * scanner/canonicalization contract.\n */\n\n/** Typed byte codec for D82 storage binding helpers and D96 shared JSON surfaces. */\nexport interface Codec<T> {\n\tencode(value: T): Uint8Array;\n\tdecode(bytes: Uint8Array): T;\n}\n\nexport type StrictJsonScalar = null | boolean | number | string;\nexport type StrictJsonValue =\n\t| StrictJsonScalar\n\t| readonly StrictJsonValue[]\n\t| { readonly [key: string]: StrictJsonValue };\nexport type StrictJsonObject = Readonly<Record<string, StrictJsonValue>>;\n\ntype JsonValue = StrictJsonValue;\n\nconst JS_MIN_NORMAL_NUMBER = 2 ** -1022;\n\nfunction assertStableJsonNumber(value: number, path: string): void {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new TypeError(`stableJsonString: non-finite number at ${path}`);\n\t}\n}\n\nfunction assertStrictJsonNumber(value: number, path: string): void {\n\tassertStableJsonNumber(value, path);\n\tif (Object.is(value, -0)) {\n\t\tthrow new TypeError(`stableJsonString: non-canonical number at ${path}`);\n\t}\n\tconst abs = Math.abs(value);\n\tif (abs > 0 && abs < JS_MIN_NORMAL_NUMBER) {\n\t\tthrow new TypeError(`stableJsonString: subnormal number at ${path}`);\n\t}\n\tif (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n\t\tthrow new TypeError(`stableJsonString: integer outside safe range at ${path}`);\n\t}\n}\n\nfunction sortedJsonValue(\n\tvalue: unknown,\n\tseen = new Set<object>(),\n\tpath = \"$\",\n\tstrictNumbers = false,\n): JsonValue {\n\tif (value === null) return null;\n\tif (typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") {\n\t\tif (strictNumbers) assertStrictJsonNumber(value, path);\n\t\telse assertStableJsonNumber(value, path);\n\t\treturn value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow new TypeError(`stableJsonString: value at ${path} is not JSON-encodable`);\n\t}\n\tif (seen.has(value)) throw new TypeError(`stableJsonString: circular reference at ${path}`);\n\tconst proto = Object.getPrototypeOf(value);\n\tif (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {\n\t\tthrow new TypeError(`stableJsonString: non-plain object at ${path}`);\n\t}\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t\t}\n\t\t\tfor (const key of Object.getOwnPropertyNames(value)) {\n\t\t\t\tconst isIndex =\n\t\t\t\t\t/^(0|[1-9]\\d*)$/.test(key) &&\n\t\t\t\t\tNumber.isSafeInteger(Number(key)) &&\n\t\t\t\t\tNumber(key) < value.length;\n\t\t\t\tif (key !== \"length\" && !isIndex) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: non-index array property at ${path}.${key}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst out: JsonValue[] = [];\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tif (!(i in value)) {\n\t\t\t\t\tthrow new TypeError(`stableJsonString: sparse array hole at ${path}[${i}]`);\n\t\t\t\t}\n\t\t\t\tout.push(sortedJsonValue(value[i], seen, `${path}[${i}]`, strictNumbers));\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\t\tif (Object.getOwnPropertySymbols(value).length > 0) {\n\t\t\tthrow new TypeError(`stableJsonString: symbol-keyed properties at ${path}`);\n\t\t}\n\t\tconst out: Record<string, JsonValue> = Object.create(null);\n\t\tfor (const key of Object.keys(value as Record<string, unknown>).sort()) {\n\t\t\tout[key] = sortedJsonValue(\n\t\t\t\t(value as Record<string, unknown>)[key],\n\t\t\t\tseen,\n\t\t\t\t`${path}.${key}`,\n\t\t\t\tstrictNumbers,\n\t\t\t);\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\n/** Stable JSON string: object keys sort by code-unit order for deterministic storage/checkpoint bytes. */\nexport function stableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value));\n}\n\nfunction strictStableJsonString(value: unknown): string {\n\treturn JSON.stringify(sortedJsonValue(value, new Set<object>(), \"$\", true));\n}\n\n/** Build a JSON codec using stable object-key ordering. */\nexport function jsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder();\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\treturn encoder.encode(stableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\treturn JSON.parse(decoder.decode(bytes)) as T;\n\t\t},\n\t};\n}\n\n/** Default stable JSON codec for unknown values. */\nexport const jsonCodec: Codec<unknown> = jsonCodecFor<unknown>();\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a.byteLength !== b.byteLength) return false;\n\tfor (let i = 0; i < a.byteLength; i += 1) {\n\t\tif (a[i] !== b[i]) return false;\n\t}\n\treturn true;\n}\n\nfunction hasUnpairedSurrogate(value: string): boolean {\n\tfor (let i = 0; i < value.length; i += 1) {\n\t\tconst code = value.charCodeAt(i);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = value.charCodeAt(i + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (code >= 0xdc00 && code <= 0xdfff) return true;\n\t}\n\treturn false;\n}\n\nfunction assertNoUnpairedSurrogates(value: unknown, seen = new Set<object>(), path = \"$\"): void {\n\tif (typeof value === \"string\") {\n\t\tif (hasUnpairedSurrogate(value)) {\n\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (value === null || typeof value !== \"object\") return;\n\tif (seen.has(value)) return;\n\tseen.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i += 1) {\n\t\t\t\tassertNoUnpairedSurrogates(value[i], seen, `${path}[${i}]`);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tfor (const key of Object.keys(value as Record<string, unknown>)) {\n\t\t\tif (hasUnpairedSurrogate(key)) {\n\t\t\t\tthrow new TypeError(`strictJsonCodec: unpaired surrogate at ${path}.${key}`);\n\t\t\t}\n\t\t\tassertNoUnpairedSurrogates((value as Record<string, unknown>)[key], seen, `${path}.${key}`);\n\t\t}\n\t} finally {\n\t\tseen.delete(value);\n\t}\n}\n\nfunction assertNoDuplicateJsonObjectKeys(text: string): void {\n\tlet index = 0;\n\n\tfunction fail(message: string): never {\n\t\tthrow new TypeError(`strictJsonCodec: ${message}`);\n\t}\n\n\tfunction skipWhitespace(): void {\n\t\twhile (/\\s/.test(text[index] ?? \"\")) index += 1;\n\t}\n\n\tfunction readJsonString(): string {\n\t\tconst start = index;\n\t\tindex += 1;\n\t\twhile (index < text.length) {\n\t\t\tconst ch = text[index];\n\t\t\tif (ch === '\"') {\n\t\t\t\tindex += 1;\n\t\t\t\ttry {\n\t\t\t\t\treturn JSON.parse(text.slice(start, index)) as string;\n\t\t\t\t} catch {\n\t\t\t\t\tfail(\"malformed JSON string\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ch === \"\\\\\") {\n\t\t\t\tindex += 2;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t\tfail(\"unterminated JSON string\");\n\t}\n\n\tfunction consumeLiteral(literal: string): void {\n\t\tif (text.slice(index, index + literal.length) !== literal) {\n\t\t\tfail(`malformed JSON near byte ${index}`);\n\t\t}\n\t\tindex += literal.length;\n\t}\n\n\tfunction consumeNumber(): void {\n\t\tconst match = /^-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/.exec(text.slice(index));\n\t\tif (!match) fail(`malformed JSON number near byte ${index}`);\n\t\tindex += match[0].length;\n\t}\n\n\tfunction parseValue(path: string): void {\n\t\tskipWhitespace();\n\t\tconst ch = text[index];\n\t\tif (ch === \"{\") {\n\t\t\tparseObject(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"[\") {\n\t\t\tparseArray(path);\n\t\t\treturn;\n\t\t}\n\t\tif (ch === '\"') {\n\t\t\treadJsonString();\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"t\") {\n\t\t\tconsumeLiteral(\"true\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"f\") {\n\t\t\tconsumeLiteral(\"false\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"n\") {\n\t\t\tconsumeLiteral(\"null\");\n\t\t\treturn;\n\t\t}\n\t\tif (ch === \"-\" || (ch !== undefined && ch >= \"0\" && ch <= \"9\")) {\n\t\t\tconsumeNumber();\n\t\t\treturn;\n\t\t}\n\t\tfail(`malformed JSON near byte ${index}`);\n\t}\n\n\tfunction parseObject(path: string): void {\n\t\tconst keys = new Set<string>();\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"}\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\twhile (index < text.length) {\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== '\"') fail(`expected object key near byte ${index}`);\n\t\t\tconst key = readJsonString();\n\t\t\tif (keys.has(key)) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`strictJsonCodec: duplicate object key ${JSON.stringify(key)} at ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tkeys.add(key);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] !== \":\") fail(`expected ':' after object key near byte ${index}`);\n\t\t\tindex += 1;\n\t\t\tparseValue(`${path}.${key}`);\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"}\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or '}' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON object\");\n\t}\n\n\tfunction parseArray(path: string): void {\n\t\tindex += 1;\n\t\tskipWhitespace();\n\t\tif (text[index] === \"]\") {\n\t\t\tindex += 1;\n\t\t\treturn;\n\t\t}\n\t\tlet item = 0;\n\t\twhile (index < text.length) {\n\t\t\tparseValue(`${path}[${item}]`);\n\t\t\titem += 1;\n\t\t\tskipWhitespace();\n\t\t\tif (text[index] === \",\") {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (text[index] === \"]\") {\n\t\t\t\tindex += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfail(`expected ',' or ']' near byte ${index}`);\n\t\t}\n\t\tfail(\"unterminated JSON array\");\n\t}\n\n\tparseValue(\"$\");\n\tskipWhitespace();\n\tif (index !== text.length) fail(`trailing JSON token near byte ${index}`);\n}\n\n/**\n * Build a strict canonical JSON codec (D84/D87/D96).\n * The strict surface rejects malformed UTF-8, duplicate object keys, non-canonical bytes,\n * unpaired surrogates, and values that cannot round-trip through stable JSON.\n */\nexport function strictJsonCodecFor<T>(): Codec<T> {\n\tconst encoder = new TextEncoder();\n\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\treturn {\n\t\tencode(value: T): Uint8Array {\n\t\t\tassertNoUnpairedSurrogates(value);\n\t\t\treturn encoder.encode(strictStableJsonString(value));\n\t\t},\n\t\tdecode(bytes: Uint8Array): T {\n\t\t\tconst text = decoder.decode(bytes);\n\t\t\tassertNoDuplicateJsonObjectKeys(text);\n\t\t\tconst decoded = JSON.parse(text) as unknown;\n\t\t\tassertNoUnpairedSurrogates(decoded);\n\t\t\tconst canonical = encoder.encode(strictStableJsonString(decoded));\n\t\t\tif (!bytesEqual(bytes, canonical)) {\n\t\t\t\tthrow new TypeError(\"strictJsonCodec: bytes are not canonical stable JSON\");\n\t\t\t}\n\t\t\treturn decoded as T;\n\t\t},\n\t};\n}\n\n/** Default strict canonical JSON codec for unknown values. */\nexport const strictJsonCodec: Codec<unknown> = strictJsonCodecFor<unknown>();\n\n/** D113 neutral helper for strict canonical JSON UTF-8 bytes. */\nexport function strictCanonicalJsonBytes(value: unknown): Uint8Array {\n\treturn strictJsonCodec.encode(value);\n}\n\n/** Validate and normalize a host value into strict canonical JSON data. */\nexport function assertStrictJsonValue(value: unknown, label = \"strictJsonValue\"): StrictJsonValue {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as StrictJsonValue;\n\t} catch (cause) {\n\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\tthrow new TypeError(`${label}: value is not strict JSON compatible: ${message}`, { cause });\n\t}\n}\n\n/** Validate and normalize a host value into a strict canonical JSON object. */\nexport function assertStrictJsonObject(\n\tvalue: unknown,\n\tlabel = \"strictJsonObject\",\n): StrictJsonObject {\n\tconst normalized = assertStrictJsonValue(value, label);\n\tif (normalized === null || typeof normalized !== \"object\" || Array.isArray(normalized)) {\n\t\tthrow new TypeError(`${label}: value must be a strict JSON object`);\n\t}\n\treturn normalized as StrictJsonObject;\n}\n","import { strictCanonicalJsonBytes, strictJsonCodec } from \"../json/codec.js\";\n\nexport type NodeVersioningLevel = 0 | 1;\n\n/**\n * D112 V1 node-version hash callback.\n *\n * The callback receives strict canonical JSON UTF-8 DATA bytes, not the raw host value.\n * Runtime V1 versioning encodes DATA with `strictCanonicalJsonBytes(value)` before calling hash.\n */\nexport type NodeVersionHashFn = (bytes: Uint8Array) => string;\n\nexport type NodeVersioningPolicy =\n\t| false\n\t| 0\n\t| 1\n\t| {\n\t\t\tlevel: NodeVersioningLevel;\n\t\t\thash?: NodeVersionHashFn;\n\t };\n\nexport type ResolvedNodeVersioningPolicy =\n\t| { readonly enabled: false }\n\t| { readonly enabled: true; readonly level: 0 }\n\t| { readonly enabled: true; readonly level: 1; readonly hash: NodeVersionHashFn };\n\nexport type NodeVersionV0 = {\n\treadonly level: 0;\n\treadonly counter: number;\n};\n\nexport type NodeVersionV1 = {\n\treadonly level: 1;\n\treadonly counter: number;\n\treadonly cid: string;\n\treadonly prev: string | null;\n};\n\nexport type NodeVersion = NodeVersionV0 | NodeVersionV1;\n\nexport type NodeVersionJson = NodeVersion;\n\nconst ABSENT_V1_SEED = Object.freeze({\n\t\"@graphrefly/node-version\": \"v1-absent\",\n});\n\nfunction fnv1a64(input: Uint8Array): string {\n\tlet hash = 0xcbf29ce484222325n;\n\tconst prime = 0x100000001b3n;\n\tfor (const byte of input) {\n\t\thash ^= BigInt(byte);\n\t\thash = BigInt.asUintN(64, hash * prime);\n\t}\n\treturn hash.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Default synchronous D112 V1 node-version hash over strict canonical JSON UTF-8 bytes.\n *\n * When hashing a host value directly, encode first:\n * `defaultNodeVersionHash(strictCanonicalJsonBytes(value))`.\n */\nexport function defaultNodeVersionHash(bytes: Uint8Array): string {\n\treturn `fnv1a64:${fnv1a64(bytes)}`;\n}\n\nfunction computeV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\tvalue: unknown,\n): string {\n\treturn policy.hash(strictCanonicalJsonBytes(value));\n}\n\nexport function assertNodeVersionDataCompatible(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): void {\n\tif (!policy.enabled || policy.level === 0) return;\n\tstrictCanonicalJsonBytes(value);\n}\n\nexport function snapshotNodeVersionData(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): unknown {\n\tif (!policy.enabled || policy.level === 0) return value;\n\tconst bytes = strictCanonicalJsonBytes(value);\n\treturn strictJsonCodec.decode(bytes);\n}\n\nexport function resolveNodeVersioningPolicy(\n\tpolicy: NodeVersioningPolicy | undefined,\n): ResolvedNodeVersioningPolicy {\n\tif (policy === false) return { enabled: false };\n\tif (policy === undefined || policy === 0) return { enabled: true, level: 0 };\n\tif (policy === 1) return { enabled: true, level: 1, hash: defaultNodeVersionHash };\n\tif (typeof policy === \"object\" && policy !== null) {\n\t\tif (policy.level === 0) return { enabled: true, level: 0 };\n\t\tif (policy.level === 1) {\n\t\t\treturn { enabled: true, level: 1, hash: policy.hash ?? defaultNodeVersionHash };\n\t\t}\n\t}\n\tthrow new Error(\"node: versioning level must be 0 or 1; V2/V3 are not locked yet (D109)\");\n}\n\nexport function createNodeVersion(\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tinitialValue: unknown = ABSENT_V1_SEED,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (policy.level === 0) return Object.freeze({ level: 0, counter: 0 });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: 0,\n\t\tcid: computeV1Cid(policy, initialValue),\n\t\tprev: null,\n\t});\n}\n\nexport function advanceNodeVersion(\n\tcurrent: NodeVersion | undefined,\n\tpolicy: ResolvedNodeVersioningPolicy,\n\tvalue: unknown,\n): NodeVersion | undefined {\n\tif (!policy.enabled) return undefined;\n\tif (current === undefined) return createNodeVersion(policy, value);\n\tif (policy.level === 0) {\n\t\treturn Object.freeze({ level: 0, counter: current.counter + 1 });\n\t}\n\tconst previous = current.level === 1 ? current.cid : null;\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: current.counter + 1,\n\t\tcid: computeV1Cid(policy, value),\n\t\tprev: previous,\n\t});\n}\n\nexport function cloneNodeVersion(version: NodeVersion | undefined): NodeVersion | undefined {\n\tif (version === undefined) return undefined;\n\tif (version.level === 0) return Object.freeze({ level: 0, counter: version.counter });\n\treturn Object.freeze({\n\t\tlevel: 1,\n\t\tcounter: version.counter,\n\t\tcid: version.cid,\n\t\tprev: version.prev,\n\t});\n}\n\nexport function restoredV1Cid(\n\tpolicy: Extract<ResolvedNodeVersioningPolicy, { enabled: true; level: 1 }>,\n\thasData: boolean,\n\tcache: unknown,\n): string {\n\treturn computeV1Cid(policy, hasData ? cache : ABSENT_V1_SEED);\n}\n\nexport function validateNodeVersionJson(value: unknown, path: string): NodeVersionJson {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new Error(`restoreGraph: ${path} must be an object`);\n\t}\n\tconst record = value as Record<string, unknown>;\n\tif (record.level === 0) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\treturn Object.freeze({ level: 0, counter: record.counter as number });\n\t}\n\tif (record.level === 1) {\n\t\tif (!Number.isSafeInteger(record.counter) || (record.counter as number) < 0) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.counter must be a non-negative safe integer`);\n\t\t}\n\t\tif (typeof record.cid !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.cid must be a string`);\n\t\t}\n\t\tif (record.prev !== null && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string or null`);\n\t\t}\n\t\tif ((record.counter as number) === 0 && record.prev !== null) {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be null when counter is 0`);\n\t\t}\n\t\tif ((record.counter as number) > 0 && typeof record.prev !== \"string\") {\n\t\t\tthrow new Error(`restoreGraph: ${path}.prev must be a string when counter is > 0`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tlevel: 1,\n\t\t\tcounter: record.counter as number,\n\t\t\tcid: record.cid,\n\t\t\tprev: record.prev,\n\t\t});\n\t}\n\tthrow new Error(`restoreGraph: ${path}.level must be 0 or 1`);\n}\n","/**\n * The node primitive — the thinnest substrate object (R-node-thin / D5).\n *\n * Holds a fn handle + deps + the wave state machine; ZERO inspection cruft\n * (naming/find/describe are the graph layer, CSP-2). Canonical authority:\n * ~/src/graphrefly/spec/rules.jsonl (R-node-*, R-two-phase, R-diamond, R-resolved-undirty,\n * R-first-run-gate, R-push-subscribe, R-rom-ram, R-fn-contract, R-initial, R-ctx-up).\n *\n * Slice 1 = core wave: state node, compute node, two-phase DIRTY->DATA, diamond\n * pending-counter join, first-run gate, substrate-synthesized undirty RESOLVED\n * (R-resolved-undirty / D49 — no equals-substitution; every occurrence is DATA),\n * push-on-subscribe, lazy activation, ROM/RAM. Lifecycle (terminal/INVALIDATE/cleanup),\n * control (PAUSE/async), batch, and dynamicNode land in later slices.\n */\n\nimport {\n\tcurrentBatch,\n\tcurrentBoundaryBatchToken,\n\tdeferAfterBatchForTarget,\n\tdeferToBatch,\n} from \"../batch/batch.js\";\nimport { deferRewire, enterWave, exitWave, scheduleBoundaryDrain } from \"../batch/boundary.js\";\nimport {\n\tCTX_DEP_CACHE,\n\tCTX_NODE_BINDING,\n\ttype Ctx,\n\ttype CtxState,\n\ttype DeliveryMeta,\n\ttype NodeFn,\n\ttype Sink,\n\ttype TerminalData,\n\ttype WaveData,\n} from \"../ctx/types.js\";\nimport { type Dispatcher, defaultDispatcher, type Handle } from \"../dispatcher/index.js\";\nimport { EnvironmentDrivers } from \"../graph/environment.js\";\nimport {\n\terrorPayload,\n\tisDeferredTier,\n\tisInvalidErrorPayload,\n\tisPauseBufferedTier,\n\tisTerminal,\n\tisUpAllowed,\n\tisValueTier,\n\ttype LockId,\n\ttype Message,\n\tmessageTier,\n\tSENTINEL,\n\ttype Wave,\n} from \"../protocol/messages.js\";\nimport {\n\ttype CleanupHooks,\n\ttype ControlState,\n\ttype DepBookkeeping,\n\ttype LifecycleState,\n\tmakeDepBookkeeping,\n\tNodeCore,\n\ttype NodeId,\n\ttype NodeSlot,\n\ttype PrivateState,\n\ttype SyncCtxState,\n\ttype ValueState,\n\ttype VersionState,\n\ttype WaveState,\n} from \"./core.js\";\nimport {\n\tadvanceNodeVersion,\n\tassertNodeVersionDataCompatible,\n\tcloneNodeVersion,\n\tcreateNodeVersion,\n\ttype NodeVersion,\n\ttype NodeVersioningPolicy,\n\tresolveNodeVersioningPolicy,\n\trestoredV1Cid,\n\tsnapshotNodeVersionData,\n} from \"./versioning.js\";\n\nexport type Status =\n\t| \"sentinel\"\n\t| \"pending\"\n\t| \"dirty\"\n\t| \"settled\"\n\t| \"resolved\"\n\t| \"completed\"\n\t| \"errored\";\n\nexport interface NodeOptions<T = unknown> {\n\t/** Pre-populate cache; source pushes [DATA, initial] on subscribe (R-initial). `null` is valid. */\n\tinitial?: T | null;\n\t/** First-run gate off when true; fn body must guard SENTINEL per dep (R-first-run-gate). */\n\tpartial?: boolean;\n\t/** A dep terminal also settles the first-run gate (Reduce-class, R-first-run-gate). */\n\tterminalAsRealInput?: boolean;\n\t/** Auto-emit COMPLETE when ALL deps complete (R-deps-terminal). Default true. */\n\tcompleteWhenDepsComplete?: boolean;\n\t/** Auto-emit ERROR when any dep errors (R-deps-terminal). Default true. */\n\terrorWhenDepsError?: boolean;\n\t/** Allow re-activation after terminal; late subscribe resets the lifecycle (R-terminal). Default false. */\n\tresubscribable?: boolean;\n\t/** Clear cached value on TEARDOWN. Default false. */\n\tresetOnTeardown?: boolean;\n\t/** PAUSE/RESUME behavior (R-pause-modes). Default true. */\n\tpausable?: boolean | \"resumeAll\";\n\t/**\n\t * Pull-mode node (R-pull / D55,D59): a quiet-until-demanded source, identified by this\n\t * author-supplied `pullId` (a unique LockId — a `Symbol` recommended; NOT the node name, NOT a\n\t * bare string which collides with a same-string pause lock). The node self-holds the pullId as\n\t * its demand lock. QUIET by default: it ABSORBS an upstream DIRTY WITHOUT relaying it downstream\n\t * (the wedge fix) and does NOT push-on-subscribe its cached value (START only). A DEMAND = a\n\t * cone-routed `RESUME` of this pullId (R-up-routing — NO new message type): a downstream consumer\n\t * issues `ctx.up([[RESUME, pullId]])` (broadcast up the declared cone) or `ctx.up(msgs, towardDep)`\n\t * (directed) WITHOUT holding this node's reference; the RESUME travels up to the pullId-holder,\n\t * which fires EXACTLY ONE delivery (DIRTY-before-DATA) then RE-QUIETS (1:1). Delivery content =\n\t * the orthogonal `pausable` mode: `true` → coalesced LATEST (one DATA); `'resumeAll'` → buffered\n\t * BACKLOG. `pullId` + `pausable:false` is REJECTED at construction. A SELF-triggered demand (a\n\t * consumer demanding a dep it ALSO reads) must defer via {@link Ctx.upNext} (R-rewire-deferred /\n\t * D37). Author the pullId as a shared module const used at both this node and the demander's fn.\n\t */\n\tpullId?: LockId;\n\t/** Buffer the last N outgoing DATA for late subscribers (R-replay-buffer). */\n\treplayBuffer?: number;\n\t/**\n\t * D109 node runtime versioning policy. Default is nodev0 (`{level:0,counter}`); `false`\n\t * disables runtime version metadata for this node.\n\t */\n\tversioning?: NodeVersioningPolicy;\n\t/** Mark this as a dynamicNode — fn gets ctx.track(i) for read-selection (R-dynamic-node / D35). */\n\tdynamic?: boolean;\n\t/** Dispatch pool for the fn (R-sync-core). Default sync. */\n\tpool?: \"sync\" | \"async\";\n\t/** Dispatcher to register/invoke against. Default = process-global (D26). */\n\tdispatcher?: Dispatcher;\n\t/** Optional debug name (graph layer owns real naming/inspection). */\n\tname?: string;\n\t/**\n\t * Real operator/source factory name for a STANDALONE graph-less node (D43-reserved; D51).\n\t * The graph index (`_entries`) carries the factory for g.*-registered nodes, so this is only\n\t * read for a node NOT in any graph index — a runtime *Map inner (bare `fromAny`/`initNode`\n\t * node) auto-discovered by `describe` (R-describe / R-edges-derived / D51). Off the canonical\n\t * wave path (R-node-thin intact — a pure annotation, never touched by the wave machinery).\n\t */\n\tfactory?: string;\n}\n\nexport interface NodeCheckpointState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly terminal: true | unknown | undefined;\n\treadonly activated: boolean;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | undefined;\n\treadonly handle: Handle | null;\n}\n\nexport interface NodeRestoreState {\n\treadonly cache: unknown;\n\treadonly hasData: boolean;\n\treadonly status: Status;\n\treadonly terminal: true | unknown | undefined;\n\treadonly hasCalledFnOnce: boolean;\n\treadonly ctxState: { readonly value: unknown; readonly persist: boolean };\n\treadonly version: NodeVersion | false;\n}\n\ntype TopologyDepsChangedObserver = (\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n) => void;\n\nlet constructingCore: NodeCore | undefined;\nlet constructingEnvironment: EnvironmentDrivers | undefined;\nconst ownerTokens = new WeakMap<Node<unknown>, unknown>();\nconst topologyDepsChangedObservers = new WeakMap<Node<unknown>, TopologyDepsChangedObserver>();\nconst checkpointReaders = new WeakMap<Node<unknown>, () => NodeCheckpointState>();\nconst restoreWriters = new WeakMap<Node<unknown>, (state: NodeRestoreState) => void>();\nconst runtimeReleasers = new WeakMap<Node<unknown>, () => void>();\nconst runtimeQuiescenceReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst subscriberCountReaders = new WeakMap<Node<unknown>, () => number>();\nconst activationReaders = new WeakMap<Node<unknown>, () => boolean>();\nconst releasedNodes = new WeakSet<Node<unknown>>();\n\n/** @internal Run a Node/StateNode constructor against a graph-local core without widening the public constructor. */\nexport function withNodeCore<TNode extends Node<unknown>>(\n\tcore: NodeCore,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingCore;\n\tconstructingCore = core;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingCore = prev;\n\t}\n}\n\n/** @internal Run a Node/StateNode constructor with graph-owned environment drivers (D130/D131). */\nexport function withEnvironmentDrivers<TNode extends Node<unknown>>(\n\tenvironment: EnvironmentDrivers,\n\tcreate: () => TNode,\n): TNode {\n\tconst prev = constructingEnvironment;\n\tconstructingEnvironment = environment;\n\ttry {\n\t\treturn create();\n\t} finally {\n\t\tconstructingEnvironment = prev;\n\t}\n}\n\n/** @internal Graph-domain ownership token for D22 intra-graph guards. */\nexport function getNodeOwner(n: Node<unknown>): unknown {\n\treturn ownerTokens.get(n);\n}\n\n/** @internal Assign graph-domain ownership after graph registration. */\nexport function setNodeOwner(n: Node<unknown>, owner: unknown): void {\n\townerTokens.set(n, owner);\n}\n\n/** @internal Graph-layer D145 topology egress hook. */\nexport function setNodeTopologyDepsChangedObserver(\n\tn: Node<unknown>,\n\tobserver: TopologyDepsChangedObserver,\n): void {\n\ttopologyDepsChangedObservers.set(n, observer);\n}\n\nfunction notifyTopologyDepsChanged(\n\tnode: Node<unknown>,\n\tprevDeps: readonly Node<unknown>[],\n\tdeps: readonly Node<unknown>[],\n): void {\n\ttopologyDepsChangedObservers.get(node)?.(node, prevDeps, deps);\n}\n\n/** @internal Graph checkpoint inspection, kept as a module helper so Node stays method-thin. */\nexport function checkpointStateOfNode(n: Node<unknown>): NodeCheckpointState {\n\tconst read = checkpointReaders.get(n);\n\tif (read === undefined) throw new Error(\"checkpoint: unknown node state\");\n\treturn read();\n}\n\n/** @internal D94 restore commit: install runtime state without a protocol wave or subscription. */\nexport function restoreStateOfNode(n: Node<unknown>, state: NodeRestoreState): void {\n\tconst write = restoreWriters.get(n);\n\tif (write === undefined) throw new Error(\"restoreGraph: unknown node state\");\n\twrite(state);\n}\n\n/** @internal D122 graph-owned ephemeral lifecycle release. */\nexport function releaseRuntimeOfNode(n: Node<unknown>): void {\n\truntimeReleasers.get(n)?.();\n}\n\n/** @internal D124 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeQuiescentForRelease(n: Node<unknown>): boolean {\n\treturn runtimeQuiescenceReaders.get(n)?.() ?? false;\n}\n\n/** @internal D124 graph-owned release subscriber accounting. */\nexport function subscriberCountOfNode(n: Node<unknown>): number {\n\treturn subscriberCountReaders.get(n)?.() ?? 0;\n}\n\n/** @internal D124 graph-owned release internal-subscriber accounting. */\nexport function isNodeActiveForRelease(n: Node<unknown>): boolean {\n\treturn activationReaders.get(n)?.() ?? false;\n}\n\n/** @internal D122 guard for graph-owned ephemeral lifecycle release. */\nexport function isNodeRuntimeReleased(n: Node<unknown>): boolean {\n\treturn releasedNodes.has(n);\n}\n\nfunction terminalView(t: unknown): unknown {\n\treturn t === undefined ? false : t;\n}\n\nfunction validateDownPayloads(msgs: Wave): void {\n\tfor (const m of msgs) {\n\t\tif (m[0] === \"DATA\" && m[1] === undefined) {\n\t\t\tthrow new Error(\"down: DATA requires a non-SENTINEL payload (R-data-payload)\");\n\t\t}\n\t\tif (m[0] === \"ERROR\" && isInvalidErrorPayload(m[1])) {\n\t\t\tthrow new Error(\"down: ERROR requires a non-SENTINEL, non-boolean payload (R-data-payload)\");\n\t\t}\n\t}\n}\n\n/** A queued deferred self-rewire op (R-rewire-deferred / D47), drained at the wave boundary. */\ntype RewireOp =\n\t| { kind: \"add\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"remove\"; dep: Node<unknown>; fn: NodeFn }\n\t| { kind: \"set\"; deps: Node<unknown>[]; fn: NodeFn };\n\n/** Internal routing state for one up-going control wave. */\ntype UpRouteState = {\n\tdemandFired: Map<LockId, Set<Node<unknown>>>;\n};\n\nexport class Node<T = unknown> {\n\tprivate readonly _core: NodeCore;\n\tprivate readonly _id: NodeId;\n\tprivate readonly _slot: NodeSlot<T>;\n\tprivate readonly _dep: DepBookkeeping;\n\tprivate readonly _value: ValueState<T>;\n\tprivate readonly _wave: WaveState;\n\tprivate readonly _control: ControlState;\n\tprivate readonly _lifecycle: LifecycleState;\n\tprivate readonly _privateState: PrivateState;\n\tprivate readonly _hooks: CleanupHooks;\n\tprivate readonly _syncCtxState: SyncCtxState;\n\tprivate readonly _version: VersionState;\n\tprivate _restoredActivationPending = false;\n\tprivate _released = false;\n\n\tprivate get _syncCtx(): Ctx | null {\n\t\treturn this._syncCtxState.value;\n\t}\n\n\tprivate set _syncCtx(ctx: Ctx | null) {\n\t\tthis._syncCtxState.value = ctx;\n\t}\n\n\tconstructor(\n\t\tdeps: Node<unknown>[],\n\t\thandleOrFn: Handle | NodeFn | null,\n\t\topts: NodeOptions<T> = {},\n\t) {\n\t\tconst core = constructingCore;\n\t\tconstructingCore = undefined;\n\t\tconst dispatcher = opts.dispatcher ?? defaultDispatcher;\n\t\tconst environment = constructingEnvironment ?? EnvironmentDrivers.empty();\n\t\tconstructingEnvironment = undefined;\n\t\tconst pool = opts.pool ?? \"sync\";\n\t\tconst pausable = opts.pausable ?? true;\n\t\tconst pullLock = opts.pullId;\n\t\tconst pull = opts.pullId !== undefined;\n\t\t// R-pull (D55/D59): pull-mode is keyed by an author-supplied pullId (its demand lock).\n\t\t// R-pull (D55, pin 3): pull needs RESUME as the demand signal — pausable:false (which\n\t\t// ignores PAUSE/RESUME entirely, R-pause-modes) is a contradiction. 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 is demanded via RESUME, which pausable:false ignores (R-pull / R-pause-modes / D55,D59)\",\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\tif (pull) pauseLockset.add(pullLock as LockId);\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: 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 = false;\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t\tthis._control.pauseLockset.clear();\n\t\t\tif (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock as LockId);\n\t\t\tthis._privateState.value = state.ctxState.value;\n\t\t\tthis._privateState.persist = state.ctxState.persist;\n\t\t\tif (state.version === false) {\n\t\t\t\tthis._version.policy = { enabled: false };\n\t\t\t\tthis._version.value = undefined;\n\t\t\t} else if (state.version.level === 0) {\n\t\t\t\tthis._version.policy = { enabled: true, level: 0 };\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t} else {\n\t\t\t\tif (!this._version.policy.enabled || this._version.policy.level !== 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`restoreGraph: checkpoint node version level ${state.version.level} requires matching node versioning policy`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// D109: V1 restore must match the selected hash lane. After DATA then\n\t\t\t\t// INVALIDATE/resetOnTeardown, cache is absent while cid remains the last DATA cid;\n\t\t\t\t// without the DATA value, restore cannot verify the lane, so fail honestly.\n\t\t\t\tif (!state.hasData && state.version.counter > 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid cannot be verified without current DATA under V1 versioning (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst expectedCid = restoredV1Cid(this._version.policy, state.hasData, state.cache);\n\t\t\t\tif (expectedCid !== state.version.cid) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"restoreGraph: checkpoint node version cid does not match the selected node versioning hash policy (D109)\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis._version.value = cloneNodeVersion(state.version);\n\t\t\t}\n\t\t\tthis._syncCtx = null;\n\t\t\tthis._resetDepState();\n\t\t\t// A fresh restored graph has no subscribers before return. Keep activation closed so the\n\t\t\t// first real subscriber wires deps normally; D94's preserved lifecycle bit is the first-run\n\t\t\t// gate (`hasCalledFnOnce`), not a hidden subscription graph.\n\t\t\tthis._lifecycle.activated = false;\n\t\t\tthis._lifecycle.subscribers.clear();\n\t\t\tthis._restoredActivationPending = true;\n\t\t});\n\t\truntimeReleasers.set(this as Node<unknown>, () => this._releaseRuntime());\n\t\truntimeQuiescenceReaders.set(this as Node<unknown>, () => this._isRuntimeQuiescentForRelease());\n\t\tsubscriberCountReaders.set(this as Node<unknown>, () => this._subscriberCount());\n\t\tactivationReaders.set(this as Node<unknown>, () => this._lifecycle.activated);\n\t}\n\n\t/** R-pull (D55): true while a pull node is quiet (holds its own pullId/demand lock). */\n\tprivate _isPullQuiet(): boolean {\n\t\treturn this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock);\n\t}\n\n\t/**\n\t * R-pull (D55/D59): this pull node's pullId (pure data, like {@link cache}/{@link handle} — never\n\t * triggers computation). A consumer demands one delivery by cone-routing a RESUME of it (no node\n\t * reference): `ctx.up([[\"RESUME\", pullId]])` (immediate; loops back → D37 for a self-read dep) or\n\t * `ctx.upNext([[\"RESUME\", pullId]])` (boundary-deferred self-demand, R-up-routing/R-rewire-deferred).\n\t * Undefined for a non-pull node. The author writes the pullId verbatim, so this getter is mainly\n\t * for inspection/describe; routing matches by the pullId value carried in the RESUME, 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// the transient quiet-lock _isPullQuiet) so a REACTIVATED pull node — whose lockset is\n\t\t\t\t// briefly empty before _activate re-holds the demand lock — still does not leak its\n\t\t\t\t// cache (matters for a depless pull state node, whose cache survives _deactivate).\n\t\t\t\tsink([\"DATA\", this._value.cache]);\n\t\t\t} else if (this._value.status === \"dirty\" && !this._slot.pull) {\n\t\t\t\tsink([\"DIRTY\"]);\n\t\t\t}\n\n\t\t\tif (!this._lifecycle.activated) this._activate();\n\n\t\t\treturn () => {\n\t\t\t\tif (!this._lifecycle.subscribers.delete(sink)) return;\n\t\t\t\tif (this._lifecycle.subscribers.size === 0) this._deactivate();\n\t\t\t};\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/** External emission toward sinks (state-node push, or async late-emit). One call = one wave. */\n\tdown(msgs: Wave): void {\n\t\tthis._assertNotReleased(\"down\");\n\t\t// Wave-owner boundary (D47): a state.set / external push that drives a fn issuing\n\t\t// ctx.rewireNext drains at this outermost exit.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._down(msgs);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t/**\n\t * Emit upstream toward deps — control tiers only (R-ctx-up). `towardDep` (a dep index) routes up\n\t * ONE declared edge (R-up-routing directed-up); omitted = broadcast up all deps.\n\t */\n\tup(msgs: Wave, towardDep?: number): void {\n\t\tthis._assertNotReleased(\"up\");\n\t\t// Wave-owner boundary (D47). Internal dep-forwarding calls dep.up() nest under this.\n\t\tenterWave();\n\t\ttry {\n\t\t\tthis._up(msgs, towardDep);\n\t\t} finally {\n\t\t\texitWave();\n\t\t}\n\t}\n\n\t// ── deferred self-rewire (R-rewire-deferred / D47): ctx.rewireNext drain support ──\n\n\t/**\n\t * Enqueue a deferred self-rewire op (issued from this node's fn via `ctx.rewireNext`).\n\t * Applied at the committed wave boundary (boundary.ts drain), never in place — the in-fn\n\t * immediate path (`subscribeDep`/`replaceDeps`/`unsubscribeDep`) still throws mid-run (D37/R-reentrancy).\n\t */\n\tprivate _requestRewireNext(op: RewireOp): void {\n\t\tdeferRewire(this._core, () => this._applyRewireNext(op), {\n\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n\n\t/**\n\t * Enqueue a deferred up-going control wave (R-up-routing / R-pull / D59): at the committed wave\n\t * boundary, route `msgs` up from THIS node (broadcast, or up the single `towardDep` edge). The\n\t * deferred form of `ctx.up` — the SELF-demand path: a consumer issues `ctx.upNext([[RESUME,\n\t * pullId]])` to demand a dep it ALSO reads; the demand applies at the boundary (not mid-fn), so\n\t * the pull node's delivery loops back as a FRESH wave rather than re-entering the consumer (D37 /\n\t * R-reentrancy). Rides the same R-rewire-deferred (D47) drain as ctx.rewireNext.\n\t */\n\tprivate _requestUpNext(msgs: Wave, towardDep?: number): void {\n\t\tdeferRewire(\n\t\t\tthis._core,\n\t\t\t() => {\n\t\t\t\tif (!this._released) this._up(msgs, towardDep);\n\t\t\t},\n\t\t\t{\n\t\t\t\tbatchToken: currentBoundaryBatchToken(),\n\t\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t\t},\n\t\t);\n\t}\n\n\t/** Apply one queued self-rewire at the boundary (drain thunk). */\n\tprivate _applyRewireNext(op: RewireOp): void {\n\t\tif (this._released) return;\n\t\ttry {\n\t\t\t// D62 / R-rewire-deferred: terminal seals output but does NOT cancel queued topology.\n\t\t\t// Public/immediate rewire of a terminal node still rejects; the exception is only for\n\t\t\t// self-triggered ops already issued before terminal and now draining at the boundary.\n\t\t\tif (op.kind === \"add\") {\n\t\t\t\tconst next = this._slot.deps.includes(op.dep)\n\t\t\t\t\t? [...this._slot.deps]\n\t\t\t\t\t: [...this._slot.deps, op.dep];\n\t\t\t\tthis._rewire(next, op.fn, { allowTerminalOwner: true });\n\t\t\t} else if (op.kind === \"remove\") {\n\t\t\t\tthis._rewire(\n\t\t\t\t\tthis._slot.deps.filter((d) => d !== op.dep),\n\t\t\t\t\top.fn,\n\t\t\t\t\t{ allowTerminalOwner: true },\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis._rewire(this._dedupDeps(op.deps), op.fn, { allowTerminalOwner: true });\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// An invalid deferred op (cycle / self / non-resubscribable terminal dep) surfaces as\n\t\t\t// an ERROR on this node (D30-consistent) rather than stranding the rest of the drain\n\t\t\t// queue. Reachable only on misuse — higher-order operator inners are fresh, acyclic\n\t\t\t// leaf sources. Coerce a SENTINEL reason (a rewire fn that `throw undefined`s) to a real\n\t\t\t// Error so _down's R-data-payload guard does not itself throw out of the drain.\n\t\t\tthis._down([[\"ERROR\", errorPayload(e, \"rewireNext op failed\")]]);\n\t\t}\n\t}\n\n\t// ── rewire (R-rewire / D42): intra-graph runtime topology mutation ──\n\n\t/**\n\t * Replace this node's deps atomically (surgical, Option-C). Requires an explicit\n\t * `fn` (SD-1 fn-deps pairing — user fns read dep input positionally). Kept deps\n\t * keep their subscription + per-dep state; only removed deps unsubscribe and only\n\t * added deps fresh-subscribe (push-on-subscribe for an added cached dep). The\n\t * first-run gate and cache are PRESERVED (R-rewire Q2/Q7). Intra-graph only (D22).\n\t */\n\treplaceDeps(newDeps: Node<unknown>[], fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"replaceDeps\");\n\t\tthis._rewire(this._dedupDeps(newDeps), fn);\n\t}\n\n\t/** Subscribe to one dep (special case of replaceDeps); returns its index. fn required (SD-1). */\n\tsubscribeDep(depNode: Node<unknown>, fn: NodeFn): number {\n\t\tthis._assertNotReleased(\"subscribeDep\");\n\t\tconst next = this._slot.deps.includes(depNode)\n\t\t\t? [...this._slot.deps]\n\t\t\t: [...this._slot.deps, depNode];\n\t\tconst deferred = this._rewire(next, fn);\n\t\treturn deferred ? next.indexOf(depNode) : this._slot.deps.indexOf(depNode);\n\t}\n\n\t/** Unsubscribe from one dep (special case of replaceDeps); idempotent if absent (fn swap still applies). */\n\tunsubscribeDep(depNode: Node<unknown>, fn: NodeFn): void {\n\t\tthis._assertNotReleased(\"unsubscribeDep\");\n\t\tthis._rewire(\n\t\t\tthis._slot.deps.filter((d) => d !== depNode),\n\t\t\tfn,\n\t\t);\n\t}\n\n\tprivate _dedupDeps(deps: Node<unknown>[]): Node<unknown>[] {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst out: Node<unknown>[] = [];\n\t\tfor (const d of deps)\n\t\t\tif (!seen.has(d)) {\n\t\t\t\tseen.add(d);\n\t\t\t\tout.push(d);\n\t\t\t}\n\t\treturn out;\n\t}\n\n\t/** Is `target` reachable upstream from `from` (following deps)? Cycle-prevention DFS. */\n\tprivate _reachableUpstream(from: Node<unknown>, target: Node<unknown>): boolean {\n\t\tconst seen = new Set<Node<unknown>>();\n\t\tconst stack: Node<unknown>[] = [from];\n\t\twhile (stack.length > 0) {\n\t\t\tconst n = stack.pop();\n\t\t\tif (n === undefined) continue;\n\t\t\tif (n === target) return true;\n\t\t\tif (seen.has(n)) continue;\n\t\t\tseen.add(n);\n\t\t\tfor (const d of n._slot.deps) stack.push(d);\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _assertRewireDepOwner(dep: Node<unknown>): void {\n\t\tconst selfOwner = getNodeOwner(this as unknown as Node<unknown>);\n\t\tconst depOwner = getNodeOwner(dep);\n\t\tif (selfOwner !== undefined && depOwner !== undefined && selfOwner !== depOwner) {\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: dep belongs to a different graph; cross-graph deps require a wire bridge (D22 / R-graph-domain)\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate _rewire(\n\t\tnewDeps: Node<unknown>[],\n\t\tfn: NodeFn,\n\t\topts: { allowTerminalOwner?: boolean } = {},\n\t): boolean {\n\t\t// ── rejects (R-rewire / D42) ──\n\t\tif (this._value.terminal !== undefined && !opts.allowTerminalOwner)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: node is terminal (completed/errored) — cannot rewire (R-rewire / D42)\",\n\t\t\t);\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: mid-fn topology mutation — a fn mutating its own deps mid-wave is the feedback cycle (R-rewire / D37)\",\n\t\t\t);\n\t\tif (this._wave.inDepMutation)\n\t\t\tthrow new Error(\n\t\t\t\t\"rewire: reentrant dep mutation — another replaceDeps/subscribeDep/unsubscribeDep is in flight (R-rewire)\",\n\t\t\t);\n\t\tif (newDeps.includes(this as unknown as Node<unknown>))\n\t\t\tthrow new Error(\"rewire: self-dependency rejected (R-rewire / D42)\");\n\t\tconst oldDeps = this._slot.deps;\n\t\tconst added = newDeps.filter((d) => !oldDeps.includes(d));\n\t\tfor (const d of added) {\n\t\t\tif (this._reachableUpstream(d, this as unknown as Node<unknown>))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: would create a cycle — dep already transitively depends on this node (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tif (d._value.terminal !== undefined && !d._slot.resubscribable)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"rewire: cannot add a non-resubscribable terminal dep — would wedge (R-rewire / D42)\",\n\t\t\t\t);\n\t\t\tthis._assertRewireDepOwner(d);\n\t\t}\n\n\t\tif (\n\t\t\tdeferAfterBatchForTarget(this, () => {\n\t\t\t\tthis._rewire(newDeps, fn, { ...opts, allowTerminalOwner: true });\n\t\t\t})\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!this._lifecycle.activated) this._restoredActivationPending = false;\n\n\t\tthis._wave.inDepMutation = true;\n\t\tthis._wave.rewireRunPending = false;\n\t\tlet zeroDepUnDirty = false;\n\t\ttry {\n\t\t\t// fn swap (SD-1): re-register against the same pool, then release the old handle\n\t\t\t// (B15) so the rewired-away fn closure is GC'd and its dispatcher slot is reused —\n\t\t\t// a rewire-heavy graph (CSP-2.7 *Map) no longer leaks a handle per swap. Register\n\t\t\t// first, then unregister the old: this._slot.handle never points at a freed slot, and a\n\t\t\t// null old handle (a passthrough/state node gaining a fn) has nothing to free.\n\t\t\tconst oldHandle = this._slot.handle;\n\t\t\tthis._slot.handle = this._slot.dispatcher.register(fn, this._slot.pool);\n\t\t\tif (oldHandle !== null) this._slot.dispatcher.unregister(oldHandle);\n\n\t\t\tconst removed = oldDeps.filter((d) => !newDeps.includes(d));\n\t\t\tlet removedDirtyContributor = false;\n\t\t\tfor (const d of removed) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(d);\n\t\t\t\tif (this._dep.dirty[oldIdx]) {\n\t\t\t\t\tremovedDirtyContributor = true;\n\t\t\t\t\tthis._wave.pending--;\n\t\t\t\t}\n\t\t\t\tif (this._lifecycle.activated) {\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = -1; // drain: any stale in-flight callback drops\n\t\t\t\t\tconst unsub = this._dep.unsubs[oldIdx];\n\t\t\t\t\tif (unsub) unsub(); // stops the removed dep's edge — no further delivery\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rebuild per-dep parallel arrays in newDeps order; kept deps carry their state\n\t\t\t// + subscription, added deps start fresh (R-rewire Q1/Q4).\n\t\t\tconst n = newDeps.length;\n\t\t\tconst newBatch: Array<unknown[] | null> = new Array(n).fill(null);\n\t\t\tconst newPrev: unknown[] = new Array(n).fill(SENTINEL);\n\t\t\tconst newHasData: boolean[] = new Array(n).fill(false);\n\t\t\tconst newDirty: boolean[] = new Array(n).fill(false);\n\t\t\tconst newTier: number[] = new Array(n).fill(0);\n\t\t\tconst newTerminal: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newTerminalInput: Array<true | unknown | undefined> = new Array(n).fill(undefined);\n\t\t\tconst newUnsubs: Array<() => void> = new Array(n);\n\t\t\tconst newBoxes: Array<{ v: number }> = new Array(n);\n\t\t\tfor (let j = 0; j < n; j++) {\n\t\t\t\tconst oldIdx = oldDeps.indexOf(newDeps[j]);\n\t\t\t\tif (oldIdx !== -1) {\n\t\t\t\t\tnewBatch[j] = this._dep.batch[oldIdx];\n\t\t\t\t\tnewPrev[j] = this._dep.prev[oldIdx];\n\t\t\t\t\tnewHasData[j] = this._dep.hasData[oldIdx];\n\t\t\t\t\tnewDirty[j] = this._dep.dirty[oldIdx];\n\t\t\t\t\tnewTier[j] = this._dep.tier[oldIdx];\n\t\t\t\t\tnewTerminal[j] = this._dep.terminal[oldIdx];\n\t\t\t\t\tnewUnsubs[j] = this._dep.unsubs[oldIdx];\n\t\t\t\t\t// carry the kept dep's subscription box and point it at the new index (O(1) reroute)\n\t\t\t\t\tconst box = this._dep.idxBoxes[oldIdx];\n\t\t\t\t\tif (box) box.v = j;\n\t\t\t\t\tnewBoxes[j] = box;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._slot.deps = newDeps;\n\t\t\tthis._dep.batch = newBatch;\n\t\t\tthis._dep.prev = newPrev;\n\t\t\tthis._dep.hasData = newHasData;\n\t\t\tthis._dep.dirty = newDirty;\n\t\t\tthis._dep.tier = newTier;\n\t\t\tthis._dep.terminal = newTerminal;\n\t\t\tthis._dep.terminalInput = newTerminalInput;\n\t\t\tthis._dep.unsubs = newUnsubs;\n\t\t\tthis._dep.idxBoxes = newBoxes;\n\t\t\tthis._dep.waveData = newDeps.map(() => []);\n\t\t\tthis._dep.waveTokens = new Array(newDeps.length).fill(undefined);\n\t\t\tthis._syncCtx = null;\n\n\t\t\t// Subscribe added deps — push-on-subscribe (R-push-subscribe) delivers a cached\n\t\t\t// dep's DATA here, which drives _maybeRun; a SENTINEL dep delivers START only.\n\t\t\tif (this._lifecycle.activated) {\n\t\t\t\tfor (const d of added) this._subscribeDepAt(d);\n\t\t\t}\n\t\t\tnotifyTopologyDepsChanged(this as unknown as Node<unknown>, oldDeps, newDeps);\n\n\t\t\t// Q6 auto-settle: removing the sole dirty contributor closes the wave. With deps\n\t\t\t// remaining, request the atomic settle (recompute → DATA for a value; a no-emit fn\n\t\t\t// gets a substrate-synthesized undirty RESOLVED per R-resolved-undirty/D49 — NOT\n\t\t\t// equals-absorption, which is gone). With zero deps the node is inert (degenerate\n\t\t\t// fn-no-deps) — just un-dirty downstream. Cache is preserved either way (Q7).\n\t\t\tif (removedDirtyContributor && this._wave.pending === 0 && this._value.status === \"dirty\") {\n\t\t\t\tif (newDeps.length > 0) this._wave.rewireRunPending = true;\n\t\t\t\telse zeroDepUnDirty = true;\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._wave.inDepMutation = false;\n\t\t}\n\n\t\t// Atomic post-mutation settle (outside the reentrancy guard so a fresh wave runs\n\t\t// normally): ONE two-phase DIRTY→DATA recompute if any added dep delivered data or a\n\t\t// sole-dirty dep was removed; else the zero-dep un-dirty via _down (pause/batch-safe).\n\t\tif (this._wave.rewireRunPending) {\n\t\t\tthis._wave.rewireRunPending = false;\n\t\t\tthis._settleRewire();\n\t\t} else if (zeroDepUnDirty) {\n\t\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t\t\telse this._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\treturn false;\n\t}\n\n\t// ── activation / deactivation (lazy; R-rom-ram) ──\n\n\tprivate _activate(): void {\n\t\tthis._lifecycle.activated = true;\n\t\tconst seedRestoredDeps = this._restoredActivationPending;\n\t\tthis._restoredActivationPending = false;\n\t\t// R-pull (D55): (re)enter QUIET before wiring deps — _deactivate cleared the lockset, so a\n\t\t// reactivation must re-hold the pullId/demand lock; doing it here (pre-subscribe) means each\n\t\t// dep's push-on-subscribe DIRTY/DATA is absorbed quietly (the wedge fix), not relayed downstream.\n\t\tif (this._slot.pull) this._control.pauseLockset.add(this._slot.pullLock as LockId);\n\t\tthis._dep.unsubs = new Array(this._slot.deps.length);\n\t\tthis._dep.idxBoxes = new Array(this._slot.deps.length);\n\t\tfor (const dep of this._slot.deps)\n\t\t\tthis._subscribeDepAt(dep, { seedRestored: seedRestoredDeps });\n\t\t// Depless producer (fn, no deps): run once on activation.\n\t\tif (this._slot.deps.length === 0 && this._slot.handle !== null && !this._wave.hasCalledFnOnce) {\n\t\t\tthis._runWave();\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to a dep. The dispatch callback reads the dep's CURRENT index from a\n\t * mutable box (O(1)); a surgical rewire that reorders kept deps just updates the box\n\t * (R-rewire Option-C / D42) — no re-subscribe, no per-message indexOf scan. A removed\n\t * dep's box is set to -1 so any stale in-flight callback drops (drain).\n\t */\n\tprivate _subscribeDepAt(depNode: Node<unknown>, opts: { seedRestored?: boolean } = {}): void {\n\t\tconst idx0 = this._slot.deps.indexOf(depNode);\n\t\tconst box = { v: idx0 };\n\t\tlet ignoreInitialPush = opts.seedRestored === true;\n\t\tif (ignoreInitialPush && idx0 !== -1) {\n\t\t\tthis._seedRestoredDepAt(idx0, depNode);\n\t\t\tif (depNode._value.terminal !== undefined && !depNode._slot.resubscribable) {\n\t\t\t\tthis._dep.unsubs[idx0] = () => {};\n\t\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst unsub = depNode.subscribe((msg, delivery) => {\n\t\t\tif (ignoreInitialPush && delivery === undefined) return;\n\t\t\tif (ignoreInitialPush) ignoreInitialPush = false;\n\t\t\tif (box.v === -1) return; // dep removed — stale callback, drop (drain)\n\t\t\tthis._receiveFromDep(box.v, msg, delivery);\n\t\t});\n\t\tif (ignoreInitialPush && idx0 !== -1 && box.v !== -1) this._seedRestoredDepAt(idx0, depNode);\n\t\tignoreInitialPush = false;\n\t\tif (idx0 !== -1) {\n\t\t\tthis._dep.unsubs[idx0] = unsub;\n\t\t\tthis._dep.idxBoxes[idx0] = box;\n\t\t}\n\t}\n\n\tprivate _seedRestoredDepAt(idx: number, depNode: Node<unknown>): void {\n\t\tconst seedData = depNode._value.hasData && !depNode._slot.pull;\n\t\tthis._dep.batch[idx] = null;\n\t\tthis._dep.waveData[idx] = [];\n\t\tthis._dep.waveTokens[idx] = undefined;\n\t\tthis._dep.prev[idx] = seedData ? depNode._value.cache : SENTINEL;\n\t\tthis._dep.hasData[idx] = seedData;\n\t\tthis._dep.dirty[idx] = false;\n\t\tthis._dep.tier[idx] = seedData ? 3 : 0;\n\t\tthis._dep.terminal[idx] = depNode._value.terminal;\n\t\tthis._dep.terminalInput[idx] = undefined;\n\t}\n\n\tprivate _deactivate(): void {\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tfor (const fn of this._hooks.onDeactivation) fn();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\t// RAM: compute nodes clear cache; reconnect re-runs fn fresh.\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t}\n\t\tthis._resetDepState();\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = false; // R-pull (D55): drop any deferred demand\n\t\tthis._value.replayRing = []; // BH6: don't replay stale values to a post-reactivation subscriber\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _assertNotReleased(op: string): void {\n\t\tif (this._released)\n\t\t\tthrow new Error(`${op}: node has been released from its graph lifecycle (D122)`);\n\t}\n\n\tprivate _subscriberCount(): number {\n\t\treturn this._lifecycle.subscribers.size;\n\t}\n\n\tprivate _isRuntimeQuiescentForRelease(): boolean {\n\t\tconst allowedPullQuietLock =\n\t\t\tthis._slot.pull &&\n\t\t\tthis._control.pauseLockset.size === 1 &&\n\t\t\tthis._control.pauseLockset.has(this._slot.pullLock);\n\t\treturn (\n\t\t\t!this._released &&\n\t\t\tthis._value.status !== \"dirty\" &&\n\t\t\tthis._value.status !== \"pending\" &&\n\t\t\tthis._wave.pending === 0 &&\n\t\t\t!this._wave.insideRunWave &&\n\t\t\t!this._wave.inDepMutation &&\n\t\t\t!this._wave.rewireRunPending &&\n\t\t\t!this._wave.batchDirtyOwed &&\n\t\t\tthis._dep.dirty.every((dirty) => !dirty) &&\n\t\t\tthis._control.pauseBuffer.length === 0 &&\n\t\t\t!this._control.pausedDepWaveOccurred &&\n\t\t\t!this._control.demandOwed &&\n\t\t\t!this._control.inDeliverDemand &&\n\t\t\t(this._control.pauseLockset.size === 0 || allowedPullQuietLock)\n\t\t);\n\t}\n\n\tprivate _releaseRuntime(): void {\n\t\tif (this._released) return;\n\t\tthis._released = true;\n\t\treleasedNodes.add(this as Node<unknown>);\n\t\tlet releaseError: unknown;\n\t\tconst recordReleaseError = (error: unknown): void => {\n\t\t\tif (releaseError === undefined) releaseError = error;\n\t\t};\n\t\tthis._lifecycle.activated = false;\n\t\tfor (const u of this._dep.unsubs) {\n\t\t\ttry {\n\t\t\t\tu();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release is graph-owned and atomic; user cleanup must not split commit.\n\t\t\t}\n\t\t}\n\t\tfor (const fn of this._hooks.onDeactivation) {\n\t\t\ttry {\n\t\t\t\tfn();\n\t\t\t} catch (error) {\n\t\t\t\trecordReleaseError(error);\n\t\t\t\t// D124 release cleans runtime without synthesizing protocol ERROR/COMPLETE.\n\t\t\t}\n\t\t}\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tif (this._slot.handle !== null) {\n\t\t\tthis._slot.dispatcher.unregister(this._slot.handle);\n\t\t\tthis._slot.handle = null;\n\t\t}\n\t\tthis._slot.deps = [];\n\t\tthis._dep.batch = [];\n\t\tthis._dep.waveData = [];\n\t\tthis._dep.waveTokens = [];\n\t\tthis._dep.prev = [];\n\t\tthis._dep.hasData = [];\n\t\tthis._dep.dirty = [];\n\t\tthis._dep.tier = [];\n\t\tthis._dep.terminal = [];\n\t\tthis._dep.terminalInput = [];\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.replayRing = [];\n\t\tthis._privateState.value = SENTINEL;\n\t\tthis._privateState.persist = false;\n\t\tthis._syncCtx = null;\n\t\tthis._resetDepState();\n\t\tthis._hooks.onDeactivation = [];\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = false;\n\t\tthis._restoredActivationPending = false;\n\t\tcheckpointReaders.delete(this as Node<unknown>);\n\t\trestoreWriters.delete(this as Node<unknown>);\n\t\truntimeReleasers.delete(this as Node<unknown>);\n\t\truntimeQuiescenceReaders.delete(this as Node<unknown>);\n\t\tsubscriberCountReaders.delete(this as Node<unknown>);\n\t\tactivationReaders.delete(this as Node<unknown>);\n\t\townerTokens.delete(this as Node<unknown>);\n\t\ttopologyDepsChangedObservers.delete(this as Node<unknown>);\n\t\tthis._core.releaseSlot(this._id);\n\t\tif (releaseError !== undefined) throw releaseError;\n\t}\n\n\tprivate _resetDepState(): void {\n\t\tconst n = this._slot.deps.length;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.prev[i] = SENTINEL;\n\t\t\tthis._dep.hasData[i] = false;\n\t\t\tthis._dep.dirty[i] = false;\n\t\t\tthis._dep.tier[i] = 0;\n\t\t\tthis._dep.terminal[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.pending = 0;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── upstream wave receive (two-phase + diamond) ──\n\n\tprivate _recordDepProjection(idx: number, delivery: DeliveryMeta | undefined): unknown[] {\n\t\tconst token = delivery?.wave ?? {};\n\t\tif (this._dep.waveTokens[idx] !== token) {\n\t\t\tthis._dep.waveData[idx].push([]);\n\t\t\tthis._dep.waveTokens[idx] = token;\n\t\t}\n\t\treturn this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t}\n\n\tprivate _depProjectionHasData(idx: number): boolean {\n\t\tconst projection = this._dep.waveData[idx][this._dep.waveData[idx].length - 1];\n\t\treturn projection?.some((v) => v !== SENTINEL) ?? false;\n\t}\n\n\tprivate _receiveFromDep(idx: number, msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\tconst t = msg[0];\n\t\tif (t === \"START\") return;\n\t\tconst isLastInDeliveredWave = delivery?.last ?? true;\n\t\t// Terminal-is-forever, except terminal intermediates still relay upstream TEARDOWN\n\t\t// downstream for lifecycle unwire (R-teardown-terminal-relay / D65).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (t === \"TEARDOWN\") this._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"INVALIDATE\") {\n\t\t\tconst projection = this._recordDepProjection(idx, delivery);\n\t\t\tprojection.push(SENTINEL);\n\t\t\tif (projection.some((v) => v !== SENTINEL) && isLastInDeliveredWave) this._maybeRun();\n\t\t\t// The dep's value is gone — drop our cached latest view to SENTINEL so the\n\t\t\t// never-emitted detector reads correctly, C-3) and cascade (idempotent).\n\t\t\tthis._dep.prev[idx] = SENTINEL;\n\t\t\tthis._dep.hasData[idx] = false;\n\t\t\tthis._dep.batch[idx] = null;\n\t\t\t// EC3: un-wedge the dirty bookkeeping if this dep had gone DIRTY first, so an\n\t\t\t// INVALIDATE-before-DATA doesn't strand _pending / downstream forever\n\t\t\t// (R-invalidate-idempotent — exists to prevent the wedged-DIRTY deadlock).\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\t// D50 / R-paused-invalidate: this INVALIDATE SUPERSEDES the dep's buffered\n\t\t\t// paused dep-wave (_depBatch[idx] just cleared). Re-derive the paused-recompute\n\t\t\t// flag — if no dep still carries a buffered DATA, CANCEL the paused recompute\n\t\t\t// (attributed cancellation; the node has settled to SENTINEL via its own\n\t\t\t// INVALIDATE, so a RESUME must not recompute against a now-SENTINEL dep). A\n\t\t\t// surviving dep keeps it set; a later DATA re-arms it ([DATA,INVALIDATE,DATA2]).\n\t\t\tif (this._control.pausedDepWaveOccurred && this._dep.batch.every((b) => b === null)) {\n\t\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\t}\n\t\t\tconst hadData = this._value.hasData;\n\t\t\tthis._invalidate(); // cascades INVALIDATE iff populated; no-op otherwise\n\t\t\t// If we broadcast DIRTY this wave but _invalidate produced no settle (the node\n\t\t\t// was never populated, so the cascade is suppressed per the rule), un-dirty\n\t\t\t// downstream with a RESOLVED once all deps have settled.\n\t\t\tif (this._wave.pending === 0 && this._wave.emittedDirtyThisWave) {\n\t\t\t\tif (!hadData) this._down([[\"RESOLVED\"]]);\n\t\t\t\telse this._wave.emittedDirtyThisWave = false;\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): an INVALIDATE settle can drain _pending → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (isTerminal(t)) {\n\t\t\t// Tier 5 (R-tier / D34): COMPLETE | ERROR — ONE branch routed by the CENTRAL tier table,\n\t\t\t// not a per-variant string check (feedback_use_tier_for_signal_routing). The shared terminal\n\t\t\t// bookkeeping (record the terminal + release the in-wave DIRTY) runs for ANY tier-5 message;\n\t\t\t// only the COMPLETE-vs-ERROR cascade differs, so discriminate by the type within the tier.\n\t\t\tconst isError = t === \"ERROR\";\n\t\t\tconst errPayload = isError ? (msg as readonly [\"ERROR\", unknown])[1] : undefined;\n\t\t\tthis._dep.terminal[idx] = isError ? errPayload : true;\n\t\t\tthis._dep.terminalInput[idx] = isError ? errPayload : true;\n\t\t\t// R-terminal-settles-dirty (B35): a terminal RELEASES this dep's outstanding in-wave DIRTY\n\t\t\t// contribution (the exactly-one-settle invariant) — exactly as DATA/RESOLVED/INVALIDATE do\n\t\t\t// (a dirty-then-terminal-without-DATA dep would otherwise strand _pending and wedge the node,\n\t\t\t// the deadlock R-invalidate-idempotent prevents for INVALIDATE).\n\t\t\tthis._releaseDepDirty(idx);\n\t\t\tconst ranValueBeforeTerminal = this._depProjectionHasData(idx) && isLastInDeliveredWave;\n\t\t\tif (ranValueBeforeTerminal) this._maybeRun();\n\t\t\tif (isError && this._slot.errorWhenDepsError) {\n\t\t\t\tthis._down([[\"ERROR\", errPayload]]); // auto-cascade ERROR → node itself terminal\n\t\t\t} else if (this._slot.terminalAsRealInput) {\n\t\t\t\tif (ranValueBeforeTerminal) {\n\t\t\t\t\tthis._fireOwedDemandIfReady();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis._maybeRun(); // rescue/reduce/catch/*Map: the fn reads depTerminal(ctx, idx)\n\t\t\t} else if (this._slot.completeWhenDepsComplete && this._allDepsTerminal()) {\n\t\t\t\t// R-deps-terminal auto-COMPLETE + B42: COMPLETE once ALL deps are TERMINAL (each COMPLETE\n\t\t\t\t// or an absorbed ERROR) — so an absorbed-error dep terminating LAST still fires the\n\t\t\t\t// cascade. terminalAsRealInput is checked FIRST so a rescue recovers via _maybeRun rather\n\t\t\t\t// than being preempted (no operator sets both completeWhenDepsComplete:true + tari:true).\n\t\t\t\tthis._down([[\"COMPLETE\"]]);\n\t\t\t} else {\n\t\t\t\t// absorbed terminal, NOT an input + not auto-completing: the dep's signalled change did\n\t\t\t\t// not materialise (no DATA) → un-dirty downstream, keep cache (R-resolved-undirty balance).\n\t\t\t\tthis._settleAfterAbsorbedTerminal();\n\t\t\t}\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull (D59/B1/F6): a dep terminal can drain _pending → fire a deferred demand (no-op if this node went terminal)\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"TEARDOWN\") {\n\t\t\tthis._down([[\"TEARDOWN\"]]);\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DIRTY\") {\n\t\t\tif (!this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = true;\n\t\t\t\tthis._wave.pending++;\n\t\t\t\tthis._dep.tier[idx] = 2;\n\t\t\t\tthis._markDirty();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"DATA\") {\n\t\t\tconst v = msg[1];\n\t\t\tthis._recordDepProjection(idx, delivery).push(v);\n\t\t\tconst b = this._dep.batch[idx];\n\t\t\tif (b === null) this._dep.batch[idx] = [v];\n\t\t\telse b.push(v);\n\t\t\tthis._dep.prev[idx] = v;\n\t\t\tthis._dep.hasData[idx] = true;\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\n\t\tif (t === \"RESOLVED\") {\n\t\t\tthis._recordDepProjection(idx, delivery);\n\t\t\tthis._dep.tier[idx] = 3;\n\t\t\tif (this._dep.dirty[idx]) {\n\t\t\t\tthis._dep.dirty[idx] = false;\n\t\t\t\tthis._wave.pending--;\n\t\t\t}\n\t\t\tif (isLastInDeliveredWave) this._maybeRun();\n\t\t\tthis._fireOwedDemandIfReady(); // R-pull pin 5: settle-ready now → fire a deferred demand\n\t\t\treturn;\n\t\t}\n\t\t// PAUSE / RESUME are not delivered downstream to a dep-subscriber; a node is\n\t\t// paused via its own up() (lockset), not by an upstream dep.\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): release a dep's outstanding in-wave DIRTY contribution.\n\t * A settle-class event for that dep (DATA/RESOLVED inline above, INVALIDATE, and now\n\t * COMPLETE/ERROR) clears its dirty flag + decrements _pending. No-op if the dep already\n\t * settled this wave (DATA/RESOLVED ran first) — so the normal DATA-then-COMPLETE flow is\n\t * unaffected. This makes the exactly-one-settle invariant a single, shared step.\n\t */\n\tprivate _releaseDepDirty(idx: number): void {\n\t\tif (this._dep.dirty[idx]) {\n\t\t\tthis._dep.dirty[idx] = false;\n\t\t\tthis._wave.pending--;\n\t\t}\n\t}\n\n\t/**\n\t * R-terminal-settles-dirty (B35): settle a node whose dirtied dep was released by an ABSORBED\n\t * terminal that is NOT a real input (a plain derived/effect — the common default-node case when\n\t * one of several deps completes while others stay live). Runs only when the release drained\n\t * _pending while the node still owes a downstream settle (it broadcast DIRTY this wave):\n\t * - if some OTHER dep delivered real DATA this wave (a value occurred) → recompute (→ DATA);\n\t * - else the terminal's signalled change did not materialise (no value) → one undirty RESOLVED\n\t * (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t * A terminalAsRealInput node instead recomputes unconditionally (its fn reads the terminal).\n\t */\n\tprivate _settleAfterAbsorbedTerminal(): void {\n\t\tif (this._wave.pending !== 0 || !this._wave.emittedDirtyThisWave) return;\n\t\t// A real value occurred this wave (some OTHER dep delivered DATA) → recompute. _maybeRun\n\t\t// runs the fn ONLY if it's not gated (first-run gate open, not paused); it may emit DATA, a\n\t\t// fn-synthesized undirty RESOLVED, or nothing (gated / gate still holds).\n\t\tconst sawData = this._dep.batch.some((b) => b !== null && b.length > 0);\n\t\tif (sawData) this._maybeRun();\n\t\t// If after that the node STILL owes a downstream settle (no DATA occurred, OR the recompute\n\t\t// was gated — e.g. the first-run gate holds because the terminated dep never delivered and\n\t\t// terminalAsRealInput is false), balance the broadcast DIRTY with one undirty RESOLVED\n\t\t// (R-resolved-undirty), keeping the cache (a terminal, unlike INVALIDATE, leaves the value).\n\t\t// Without this fallback a DIRTY-then-terminal-without-DATA dep on a pre-first-run multi-dep\n\t\t// node would strand the DIRTY → downstream wedged (the B35 class, in the gate-holds corner).\n\t\tif (this._wave.emittedDirtyThisWave) this._down([[\"RESOLVED\"]]);\n\t}\n\n\tprivate _markDirty(): void {\n\t\tthis._value.status = \"dirty\";\n\t\t// SPIKE (protocol-pull): while quiet, ABSORB the upstream DIRTY — do NOT relay it downstream.\n\t\t// This is the P0b wedge fix: a quiet pull node that relayed DIRTY but withheld the settle\n\t\t// (coalesced by pause) wedged every downstream's two-phase _pending. The downstream learns of\n\t\t// changes via the push STREAM port, not the silent snapshot port; on demand the pull node\n\t\t// emits a fresh wave. Internal dep dirty-accounting (the DIRTY-branch _pending++) is untouched.\n\t\tif (this._isPullQuiet()) return;\n\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._emitToSubs([\"DIRTY\"]);\n\t\t}\n\t}\n\n\tprivate _maybeRun(): void {\n\t\t// R-rewire: an added cached dep's push-on-subscribe lands here mid-mutation. Defer\n\t\t// the fn-run to ONE atomic two-phase settle after every added dep is wired, so the\n\t\t// fn never fires on a partially-populated added-dep view (multi-add) — _settleRewire\n\t\t// drains this flag.\n\t\tif (this._wave.inDepMutation) {\n\t\t\tthis._wave.rewireRunPending = true;\n\t\t\treturn;\n\t\t}\n\t\t// R-pause-modes (default): while paused, skip dep-driven fn re-execution and\n\t\t// coalesce — fire once with the latest dep values on final-lock RESUME.\n\t\tif (this._slot.pausable === true && this._isPaused()) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tthis._tryRun();\n\t}\n\n\t/**\n\t * R-rewire atomic settle (after a rewire that warrants a recompute): emit a proper\n\t * two-phase DIRTY→DATA wave (R-dirty-before-data — a rewire-triggered settle is a wave),\n\t * once, with every added dep already wired. Mirrors _maybeRun/_tryRun's pause + gate +\n\t * pending guards, then injects the phase-1 DIRTY the added dep's [START,DATA] handshake\n\t * did not carry.\n\t */\n\tprivate _settleRewire(): void {\n\t\tif (this._slot.pausable === true && this._isPaused()) {\n\t\t\tthis._control.pausedDepWaveOccurred = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce && !(this._slot.partial || this._allDepsSettled())) return;\n\t\tthis._markDirty(); // phase 1 (no-op if already dirty, e.g. unsubscribeDep auto-settle)\n\t\tthis._runWave(); // phase 2: fn → DATA/RESOLVED\n\t}\n\n\tprivate _tryRun(): void {\n\t\tif (this._wave.pending > 0) return;\n\t\tif (this._slot.handle === null) {\n\t\t\t// Passthrough wire (deps, no fn): forward the latest dep DATA downstream.\n\t\t\tthis._passthroughEmit();\n\t\t\treturn;\n\t\t}\n\t\tif (!this._wave.hasCalledFnOnce) {\n\t\t\tif (this._slot.partial || this._allDepsSettled()) this._runWave();\n\t\t\t// else: first-run gate holds fn until every dep has settled (R-first-run-gate).\n\t\t\treturn;\n\t\t}\n\t\tthis._runWave();\n\t}\n\n\tprivate _allDepsSettled(): boolean {\n\t\tfor (let i = 0; i < this._slot.deps.length; i++) {\n\t\t\tif (this._dep.hasData[i]) continue;\n\t\t\tif (this._slot.terminalAsRealInput && this._dep.terminal[i] !== undefined) continue;\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate _passthroughEmit(): void {\n\t\t// Single-dep wire: relay dep 0's latest batch value as DATA.\n\t\tconst b = this._dep.batch[0];\n\t\tif (b !== null && b.length > 0) {\n\t\t\tthis._down([[\"DATA\", b[b.length - 1]]]);\n\t\t} else if (this._wave.emittedDirtyThisWave) {\n\t\t\t// R-resolved-undirty (D49): the dep settled via an undirty RESOLVED (no DATA in the\n\t\t\t// batch), but this wire already broadcast DIRTY downstream this wave — balance it with\n\t\t\t// a RESOLVED so downstream un-dirties instead of wedging. Routed through _down (NOT a\n\t\t\t// bare _emitToSubs) so the balance respects batch-defer (D12) + pause-buffer, matching\n\t\t\t// the zero-dep un-dirty path. Without this, a passthrough over a filter-reject /\n\t\t\t// distinctUntilChanged-dup leaves a dangling DIRTY (the wedge D49 made common).\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\t\tthis._dep.batch[0] = null;\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _runWave(): void {\n\t\t// R-reentrancy (D37): a fn that re-drives its own dep mid-wave re-enters here while\n\t\t// _insideRunWave is still set — a synchronous feedback cycle. Reject (throw); the graph\n\t\t// layer catches it and converts to [[ERROR, e]] (D30). The try/finally resets the flag\n\t\t// on every frame as the throw unwinds, leaving the graph clean for the catch. Detection\n\t\t// is node-local and free — it reuses the existing _insideRunWave flag (no new structure,\n\t\t// dispatcher stays a pure funnel).\n\t\tif (this._wave.insideRunWave)\n\t\t\tthrow new Error(\n\t\t\t\t\"synchronous feedback cycle: node fn re-entered its own wave (R-reentrancy / D37)\",\n\t\t\t);\n\t\tthis._wave.hasCalledFnOnce = true;\n\t\t// R-cleanup-hooks per-run lifecycle (D28 clarification): clear BOTH hook lists\n\t\t// before the fn runs; the fn body re-registers the current run's hooks. Only the\n\t\t// latest run's registrations are live — a re-run supersedes the prior run's hooks,\n\t\t// discarded WITHOUT firing (no fire-on-rerun; onRerun stays cut). Fixes the push-only\n\t\t// accumulation (K stale hooks fired after K runs). C-14.\n\t\tthis._hooks.onInvalidate = [];\n\t\tthis._hooks.onDeactivation = [];\n\t\tconst ctx = this._buildCtx();\n\t\tconst wasDirty = this._wave.emittedDirtyThisWave;\n\t\tthis._wave.emittedSettleThisWave = false;\n\t\tthis._wave.insideRunWave = true;\n\t\ttry {\n\t\t\tthis._slot.dispatcher.invoke(this._slot.handle as Handle, ctx);\n\t\t} finally {\n\t\t\tthis._wave.insideRunWave = false;\n\t\t}\n\n\t\t// R-resolved-undirty (D49): a SYNC fn DIRTY'd in phase 1 that produced NO tier-3 value\n\t\t// this wave (filter-reject / distinctUntilChanged-dup / any no-emit fn) gets a substrate-\n\t\t// SYNTHESIZED undirty RESOLVED to clear the downstream dirty — operator bodies stay\n\t\t// protocol-clean (R-primary-api-clean). Status reflects cache freshness: a carried value\n\t\t// -> resolved, never-valued -> sentinel. EXEMPT: terminal/INVALIDATE waves (they set\n\t\t// _emittedSettleThisWave and balance their own dirty), and ASYNC-pool nodes — an async fn\n\t\t// that returns without emitting has DEFERRED its result (it emits later via the stashed\n\t\t// ctx), NOT rejected; synthesizing here would prematurely settle a still-pending diamond\n\t\t// leg (R-async-paused / C-4). The eventual async ctx.down carries its own DIRTY balance.\n\t\tif (\n\t\t\twasDirty &&\n\t\t\t!this._wave.emittedSettleThisWave &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._isAsyncPool()\n\t\t) {\n\t\t\tthis._down([[\"RESOLVED\"]]);\n\t\t}\n\n\t\t// roll wave-local state forward\n\t\tfor (let i = 0; i < this._dep.batch.length; i++) {\n\t\t\tthis._dep.batch[i] = null;\n\t\t\tthis._dep.waveData[i] = [];\n\t\t\tthis._dep.waveTokens[i] = undefined;\n\t\t\tthis._dep.terminalInput[i] = undefined;\n\t\t}\n\t\tthis._wave.emittedDirtyThisWave = false;\n\t}\n\n\t// ── ctx construction (L3-Q5: sync = node-stable reused ctx; async = per-invocation) ──\n\n\tprivate _buildCtx(): Ctx {\n\t\tconst kind = this._slot.handle\n\t\t\t? this._slot.dispatcher.poolKind(this._slot.handle.poolId)\n\t\t\t: \"sync\";\n\t\tif (kind === \"sync\") {\n\t\t\tif (this._syncCtx === null) this._syncCtx = this._makeCtx();\n\t\t\tthis._refreshCtx(this._syncCtx);\n\t\t\treturn this._syncCtx;\n\t\t}\n\t\t// async: snapshot dep inputs so a deferred late-emit reads this wave's view.\n\t\treturn this._makeCtx({\n\t\t\twaveData: this._dep.waveData.map((waves) => waves.map((w) => [...w])),\n\t\t\tterminal: this._dep.terminalInput.map(terminalView),\n\t\t\tlatest: [...this._dep.prev],\n\t\t});\n\t}\n\n\tprivate _makeCtx(snapshot?: {\n\t\twaveData: unknown[][][];\n\t\tterminal: unknown[];\n\t\tlatest: unknown[];\n\t}): Ctx {\n\t\tconst ctx: Ctx = {\n\t\t\t// Wave-owner boundary (D47): a SYNC fn's emit nests under the public entry that drove\n\t\t\t// it (cheap inc/dec, no early drain); an ASYNC-pool fn re-enters here from its stashed\n\t\t\t// ctx at depth 0, so this is the boundary that drains any rewireNext it issued.\n\t\t\tup: (msgs, towardDep) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._up(msgs, towardDep);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\tdown: (msgs) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tenterWave();\n\t\t\t\ttry {\n\t\t\t\t\tthis._down(msgs);\n\t\t\t\t} finally {\n\t\t\t\t\texitWave();\n\t\t\t\t}\n\t\t\t},\n\t\t\twaveData: snapshot?.waveData ?? this._dep.waveData,\n\t\t\tterminal: snapshot?.terminal ?? this._dep.terminalInput.map(terminalView),\n\t\t\tstate: this._makeState(),\n\t\t\tonDeactivation: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onDeactivation.push(fn);\n\t\t\t},\n\t\t\tonInvalidate: (fn) => {\n\t\t\t\tif (this._released) return;\n\t\t\t\tthis._hooks.onInvalidate.push(fn);\n\t\t\t},\n\t\t\tenvironment: () => this._slot.environment,\n\t\t\t// R-rewire-deferred (D47): defer a self-dep-set mutation to the committed boundary.\n\t\t\trewireNext: {\n\t\t\t\tsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"add\", dep, fn }),\n\t\t\t\tunsubscribeDep: (dep, fn) => this._requestRewireNext({ kind: \"remove\", dep, fn }),\n\t\t\t\treplaceDeps: (deps, fn) => this._requestRewireNext({ kind: \"set\", deps, fn }),\n\t\t\t},\n\t\t\t// R-up-routing / R-pull (D59): deferred up — route a control wave (e.g. a RESUME pull\n\t\t\t// DEMAND) up the declared cone at the committed boundary. The SELF-demand path: an\n\t\t\t// immediate ctx.up whose delivery loops back re-enters this fn (D37 / R-reentrancy).\n\t\t\tupNext: (msgs, towardDep) => this._requestUpNext(msgs, towardDep),\n\t\t\t[CTX_DEP_CACHE]: { latest: snapshot?.latest ?? this._dep.prev },\n\t\t\t[CTX_NODE_BINDING]: {\n\t\t\t\tdispatcher: this._slot.dispatcher,\n\t\t\t\tcreate: <U>(factory: () => Node<U>) =>\n\t\t\t\t\twithEnvironmentDrivers(this._slot.environment, () => withNodeCore(this._core, factory)),\n\t\t\t},\n\t\t};\n\t\tif (this._slot.dynamic) {\n\t\t\t// R-dynamic-node: read a dep's latest by index. Untracked deps still drive waves and\n\t\t\t// re-run the fn; under D49 (no equals-substitution) the fn re-emits its current value\n\t\t\t// as DATA — to suppress redundant downstream propagation, pair with distinctUntilChanged.\n\t\t\tctx.track = (i: number) => ctx[CTX_DEP_CACHE]?.latest[i];\n\t\t}\n\t\treturn ctx;\n\t}\n\n\tprivate _refreshCtx(ctx: Ctx): void {\n\t\t(ctx as { waveData: WaveData }).waveData = this._dep.waveData;\n\t\t(ctx as { terminal: TerminalData }).terminal = this._dep.terminalInput.map(terminalView);\n\t\tctx[CTX_DEP_CACHE] = { latest: this._dep.prev };\n\t}\n\n\tprivate _makeState(): CtxState {\n\t\treturn {\n\t\t\tget: <S>() => this._privateState.value as S | undefined,\n\t\t\tset: <S>(v: S) => {\n\t\t\t\tthis._privateState.value = v;\n\t\t\t},\n\t\t\tpersist: (on = true) => {\n\t\t\t\tthis._privateState.persist = on;\n\t\t\t},\n\t\t};\n\t}\n\n\t// ── downstream emission pipeline (the unified waist) ──\n\n\tprivate _down(msgs: Wave): void {\n\t\tif (this._released) return;\n\t\tvalidateDownPayloads(msgs);\n\t\tconst deliveryWave = {};\n\t\tconst assertVersionDataCompatible = (wave: readonly Message[]) => {\n\t\t\tfor (const m of wave) {\n\t\t\t\tif (m[0] === \"DATA\") assertNodeVersionDataCompatible(this._version.policy, m[1]);\n\t\t\t}\n\t\t};\n\t\tconst snapshotVersionData = (wave: readonly Message[]): Message[] =>\n\t\t\twave.map((m) =>\n\t\t\t\tm[0] === \"DATA\"\n\t\t\t\t\t? ([\"DATA\", snapshotNodeVersionData(this._version.policy, m[1])] as Message)\n\t\t\t\t\t: m,\n\t\t\t);\n\t\tassertVersionDataCompatible(msgs);\n\t\t// Terminal-is-forever (R-terminal / D17 / B30): once COMPLETE/ERROR has been emitted the\n\t\t// node is final — a self-emit (state.set / ctx.down) in a LATER wave is a no-op, never\n\t\t// resurrecting the cache or re-emitting. The COMPLETE/ERROR arms below also self-guard\n\t\t// against a double terminal, but DATA/RESOLVED/INVALIDATE had no entry guard, so a\n\t\t// post-terminal set() would overwrite cache + emit DATA. R-teardown-terminal-relay / D65\n\t\t// carves out the only post-terminal exception: TEARDOWN still relays downstream for unwire\n\t\t// without reopening value output. A single wave that goes terminal mid-loop (e.g.\n\t\t// [COMPLETE, TEARDOWN]) is unaffected: _terminal is still undefined at entry.\n\t\t// Resubscribable reset clears _terminal before any re-emit.\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tif (!msgs.some((m) => m[0] === \"TEARDOWN\")) return;\n\t\t\tthis._value.hasTorndown = true;\n\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\tthis._value.hasData = false;\n\t\t\t}\n\t\t\tthis._emitToSubs([\"TEARDOWN\"], { wave: deliveryWave, last: true });\n\t\t\treturn;\n\t\t}\n\t\tlet sorted: Message[] = [...msgs].sort((a, b) => messageTier(a[0]) - messageTier(b[0]));\n\t\t// R-same-wave-merge: collapse repeated INVALIDATE in one wave (Q9) so the\n\t\t// cleanup hook + downstream broadcast fire at most once.\n\t\tconst firstInvalidate = sorted.findIndex((m) => m[0] === \"INVALIDATE\");\n\t\tif (firstInvalidate !== -1) {\n\t\t\tsorted = sorted.filter((m, i) => m[0] !== \"INVALIDATE\" || i === firstInvalidate);\n\t\t}\n\t\t// R-teardown-complete: a TEARDOWN reaching a non-terminal node synthesizes a\n\t\t// COMPLETE prefix (so firstValueFrom-style bridges resolve), unless the wave\n\t\t// already carries a terminal or the node already tore down.\n\t\tconst hasTeardown = sorted.some((m) => m[0] === \"TEARDOWN\");\n\t\tconst hasTerminal = sorted.some((m) => m[0] === \"COMPLETE\" || m[0] === \"ERROR\");\n\t\tif (\n\t\t\thasTeardown &&\n\t\t\t!hasTerminal &&\n\t\t\tthis._value.terminal === undefined &&\n\t\t\t!this._value.hasTorndown\n\t\t) {\n\t\t\tsorted = [[\"COMPLETE\"], ...sorted];\n\t\t}\n\t\t// R-batch-coalesce (D12): inside a batch, emit DIRTY immediately but defer the\n\t\t// tier-3 settle slice to commit so a shared downstream recomputes once. Only\n\t\t// external emits defer (fn emits during commit run normally).\n\t\tif (!this._wave.insideRunWave && currentBatch()) {\n\t\t\tconst deferred = snapshotVersionData(sorted.filter((m) => isDeferredTier(m[0])));\n\t\t\tif (deferred.length > 0) {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t\t\t}\n\t\t\t\tthis._wave.batchDirtyOwed = true; // BH1: owe a balancing RESOLVED on rollback\n\t\t\t\tdeferToBatch(this, deferred);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// R-pause-modes / R-async-paused: defer the settle slice (tier 3/4) into the\n\t\t// pause buffer while paused; tier 0-2 (DIRTY/PAUSE/RESUME), tier 5 (terminal),\n\t\t// tier 6 (TEARDOWN) bypass so end-of-stream + control always reach observers.\n\t\tif (this._shouldBufferOnPause()) {\n\t\t\tconst buffered = snapshotVersionData(sorted.filter((m) => isPauseBufferedTier(m[0])));\n\t\t\tif (buffered.length > 0) {\n\t\t\t\t// B36 / R-resolved-undirty: buffering a settle slice still means this fn wave\n\t\t\t\t// produced a settle. Without this, _runWave sees \"dirty + no settle\" and\n\t\t\t\t// synthesizes a RESOLVED that pierces the pause while the DATA waits in the buffer.\n\t\t\t\tthis._wave.emittedSettleThisWave = true;\n\t\t\t\tthis._control.pauseBuffer.push(buffered);\n\t\t\t}\n\t\t\tsorted = sorted.filter((m) => !isPauseBufferedTier(m[0]));\n\t\t\tif (sorted.length === 0) return;\n\t\t}\n\t\tlet dataCount = 0;\n\t\tlet hasTier3 = false;\n\t\tlet hasResolved = false;\n\t\tfor (const m of sorted) {\n\t\t\tif (m[0] === \"DATA\") dataCount++;\n\t\t\tif (m[0] === \"RESOLVED\") hasResolved = true;\n\t\t\tif (isValueTier(m[0])) hasTier3 = true;\n\t\t}\n\t\t// EC2 / R-resolved-undirty tier-3 exclusivity: a wave's tier-3 slot is >=1 DATA\n\t\t// (occurrence) XOR exactly 1 RESOLVED (undirty) — never mixed. Reject fail-fast.\n\t\tif (dataCount >= 1 && hasResolved) {\n\t\t\tthrow new Error(\n\t\t\t\t\"down: a wave cannot mix DATA and RESOLVED (tier-3 exclusivity, R-resolved-undirty)\",\n\t\t\t);\n\t\t}\n\t\tconst plannedVersions: Array<NodeVersion | undefined> = new Array(sorted.length);\n\t\tif (dataCount > 0) {\n\t\t\tlet plannedVersion = this._version.value;\n\t\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\t\tconst m = sorted[i];\n\t\t\t\tif (m[0] !== \"DATA\") continue;\n\t\t\t\tplannedVersion = advanceNodeVersion(plannedVersion, this._version.policy, m[1]);\n\t\t\t\tplannedVersions[i] = plannedVersion;\n\t\t\t}\n\t\t}\n\n\t\t// Synthesize a leading DIRTY for an EXTERNAL tier-3 emit (R-dirty-before-data).\n\t\t// Inside runWave the DIRTY was already propagated (or the wave is activation-exempt).\n\t\tif (hasTier3 && !this._wave.insideRunWave && !this._wave.emittedDirtyThisWave) {\n\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\tthis._value.status = \"dirty\";\n\t\t\tthis._emitToSubs([\"DIRTY\"], { wave: deliveryWave, last: false });\n\t\t}\n\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst m = sorted[i];\n\t\t\tconst delivery = { wave: deliveryWave, last: i === sorted.length - 1 };\n\t\t\t// R-resolved-undirty (D49): a tier-3+ emit this wave means the fn produced a settle,\n\t\t\t// so no synthesized undirty RESOLVED is owed (see _runWave).\n\t\t\tif (isDeferredTier(m[0])) this._wave.emittedSettleThisWave = true;\n\t\t\tif (m[0] === \"DIRTY\") {\n\t\t\t\tif (!this._wave.emittedDirtyThisWave) {\n\t\t\t\t\tthis._wave.emittedDirtyThisWave = true;\n\t\t\t\t\tthis._value.status = \"dirty\";\n\t\t\t\t\tthis._emitToSubs([\"DIRTY\"], delivery);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"DATA\") {\n\t\t\t\tconst v = m[1] as T;\n\t\t\t\t// R-resolved-undirty (D49): every value-occurrence is emitted as DATA — the\n\t\t\t\t// substrate never substitutes DATA->RESOLVED on value-equality. Dedup is opt-in\n\t\t\t\t// at the operator layer (distinctUntilChanged), never a substrate behavior.\n\t\t\t\tthis._value.cache = v;\n\t\t\t\tthis._value.hasData = true;\n\t\t\t\tthis._value.status = \"settled\";\n\t\t\t\tthis._version.value = plannedVersions[i];\n\t\t\t\tif (this._slot.replayN > 0) {\n\t\t\t\t\tthis._value.replayRing.push(v);\n\t\t\t\t\tif (this._value.replayRing.length > this._slot.replayN) this._value.replayRing.shift();\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"DATA\", v], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"RESOLVED\") {\n\t\t\t\tthis._value.status = this._value.hasData ? \"resolved\" : \"sentinel\";\n\t\t\t\tthis._emitToSubs([\"RESOLVED\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"INVALIDATE\") {\n\t\t\t\tthis._invalidate(delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"COMPLETE\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = true;\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"completed\";\n\t\t\t\tthis._emitToSubs([\"COMPLETE\"], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"ERROR\") {\n\t\t\t\tif (this._value.terminal !== undefined) continue;\n\t\t\t\tthis._value.terminal = m[1];\n\t\t\t\tthis._control.pauseBuffer = []; // BH3: terminal discards buffered settle slices\n\t\t\t\tthis._value.status = \"errored\";\n\t\t\t\tthis._emitToSubs([\"ERROR\", m[1]], delivery);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (m[0] === \"TEARDOWN\") {\n\t\t\t\tthis._value.hasTorndown = true;\n\t\t\t\tif (this._slot.resetOnTeardown) {\n\t\t\t\t\tthis._value.cache = SENTINEL;\n\t\t\t\t\tthis._value.hasData = false;\n\t\t\t\t}\n\t\t\t\tthis._emitToSubs([\"TEARDOWN\"], delivery);\n\t\t\t}\n\t\t\t// PAUSE / RESUME — control slice.\n\t\t}\n\n\t\tif (!this._wave.insideRunWave) this._wave.emittedDirtyThisWave = false;\n\t}\n\n\tprivate _up(msgs: Wave, towardDep?: number, route?: UpRouteState): void {\n\t\tif (this._released) return;\n\t\tconst routeState = route ?? { demandFired: new Map() };\n\t\tfor (const m of msgs) {\n\t\t\tif (!isUpAllowed(m[0])) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`ctx.up: ${m[0]} is down-only (tier ${messageTier(m[0])}); up carries control tiers only (R-ctx-up)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tfor (const m of msgs) {\n\t\t\tif (m[0] === \"PAUSE\") {\n\t\t\t\t// PAUSE is NODE-TARGETED (R-up-routing): it ACQUIRES a lock, so there is no\n\t\t\t\t// pre-existing holder to route to — a controller targets the node directly.\n\t\t\t\tthis._pauseAcquire(m[1]);\n\t\t\t} else if (m[0] === \"RESUME\") {\n\t\t\t\t// R-up-routing (D59): RELEASE-IF-HELD-ELSE-FORWARD-UP.\n\t\t\t\tif (this._slot.pull && m[1] === this._slot.pullLock) {\n\t\t\t\t\t// a cone-routed RESUME of OUR pullId = a DEMAND (R-pull). Fire (or owe).\n\t\t\t\t\tif (!this._markDemandRouted(m[1], routeState)) this._onDemand();\n\t\t\t\t} else if (this._control.pauseLockset.has(m[1])) {\n\t\t\t\t\t// a pause lock held HERE → release LOCALLY (normal pause/resume, R-pause-lockset).\n\t\t\t\t\tthis._pauseRelease(m[1]);\n\t\t\t\t} else {\n\t\t\t\t\t// not held here → forward UP the declared cone to find the holder.\n\t\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t\t}\n\t\t\t} else if (this._slot.deps.length === 0) {\n\t\t\t\t// R-up-at-source (D38): a depless source is the terminus of upstream control.\n\t\t\t\t// INVALIDATE → HONOR the invalidate-request. Routed through _down (NOT a direct\n\t\t\t\t// _invalidate call, QA A-2) so the invalidate-request respects batch-defer (D12)\n\t\t\t\t// and pause-buffer exactly like a downstream-originated INVALIDATE; _down's\n\t\t\t\t// INVALIDATE branch calls _invalidate() (clear cache → SENTINEL, fire onInvalidate,\n\t\t\t\t// broadcast downstream). Outside batch/pause it is identical to a direct call.\n\t\t\t\t// DIRTY / TEARDOWN → DROP (no coherent terminus action; self-dirty would wedge\n\t\t\t\t// downstream awaiting a settle that never comes; source lifecycle is source-owned).\n\t\t\t\tif (m[0] === \"INVALIDATE\") this._down([[\"INVALIDATE\"]]);\n\t\t\t} else {\n\t\t\t\t// dep-bearing intermediate: forward DIRTY/INVALIDATE/TEARDOWN up toward deps.\n\t\t\t\tthis._forwardUp(m, towardDep, routeState);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _markDemandRouted(lockId: LockId, route: UpRouteState): boolean {\n\t\tlet holders = route.demandFired.get(lockId);\n\t\tif (holders === undefined) {\n\t\t\tholders = new Set();\n\t\t\troute.demandFired.set(lockId, holders);\n\t\t}\n\t\tif (holders.has(this as unknown as Node<unknown>)) return true;\n\t\tholders.add(this as unknown as Node<unknown>);\n\t\treturn false;\n\t}\n\n\t/**\n\t * Forward one up-going control message toward deps (R-up-routing): up the single declared edge\n\t * `towardDep` (directed — prunes other branches; only meaningful on the issuer's FIRST hop) or\n\t * broadcast up ALL deps. A depless source has no deps → the message DROPS here (the terminus —\n\t * e.g. a cone-routed RESUME whose pullId no node up this cone holds, R-up-at-source). Recursive\n\t * forwarding carries the same per-wave route state and no `towardDep` → broadcast beyond the\n\t * first hop.\n\t */\n\tprivate _forwardUp(m: Message, towardDep: number | undefined, route: UpRouteState): void {\n\t\tif (this._slot.deps.length === 0) return; // depless source terminus → drop\n\t\tif (towardDep !== undefined) {\n\t\t\tconst d = this._slot.deps[towardDep];\n\t\t\tif (d !== undefined) d._up([m], undefined, route);\n\t\t} else {\n\t\t\tfor (const dep of this._slot.deps) dep._up([m], undefined, route);\n\t\t}\n\t}\n\n\t// ── PAUSE/RESUME lockset (R-pause-lockset) + modes (R-pause-modes) ──\n\n\tprivate _isPaused(): boolean {\n\t\treturn this._control.pauseLockset.size > 0;\n\t}\n\n\tprivate _hasBoundaryPauseLock(): boolean {\n\t\tif (this._slot.pausable === false) return false;\n\t\tlet locks = this._control.pauseLockset.size;\n\t\tif (this._slot.pull && this._control.pauseLockset.has(this._slot.pullLock)) locks--;\n\t\treturn locks > 0;\n\t}\n\n\tprivate _isAsyncPool(): boolean {\n\t\treturn (\n\t\t\tthis._slot.handle !== null &&\n\t\t\tthis._slot.dispatcher.poolKind(this._slot.handle.poolId) === \"async\"\n\t\t);\n\t}\n\n\tprivate _pauseAcquire(lockId: unknown): void {\n\t\tthis._control.pauseLockset.add(lockId); // Set => same-id repeat PAUSE is idempotent\n\t}\n\n\tprivate _pauseRelease(lockId: unknown): void {\n\t\tif (!this._control.pauseLockset.has(lockId)) return; // unknown id => no-op\n\t\tthis._control.pauseLockset.delete(lockId);\n\t\t// R-pull (D59 / F4-F5): releasing an EXTERNAL pause lock can unblock a demand owed while the\n\t\t// node was externally paused — fire it if now able, even though the node still self-holds its\n\t\t// pullId (so the lockset is not empty). A pull node's OWN demand never routes here (it goes\n\t\t// through _onDemand); this only sees external pause/resume locks.\n\t\tif (this._slot.pull && this._control.demandOwed) this._fireOwedDemandIfReady();\n\t\tif (this._hasBoundaryPauseLock()) return; // another external lock still held => stay paused\n\t\tscheduleBoundaryDrain(this._core);\n\t\tif (this._control.pauseLockset.size > 0) return; // pull's own quiet lock remains held\n\t\tthis._onResume();\n\t}\n\n\tprivate _onResume(): void {\n\t\t// BH3: a node that terminated while paused discards its buffer and never\n\t\t// replays/recomputes (terminal-is-forever).\n\t\tif (this._value.terminal !== undefined) {\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._control.demandOwed = false;\n\t\t\treturn;\n\t\t}\n\t\t// Non-pull pause/resume (R-pause-modes): drain buffered settle slices (resumeAll /\n\t\t// async-at-paused, R-async-paused), then fire a coalesced dep-wave once (default mode).\n\t\t// A PULL node never reaches here (D59): it always self-holds its pullId, so its lockset never\n\t\t// EMPTIES via _pauseRelease — a pull DEMAND fires through _onDemand, not _onResume.\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t}\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._tryRun();\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D59): can this pull node fire a demand NOW? — not terminal, settle-ready (_pending===0),\n\t * and no OTHER (non-pullId) lock holds it paused. The gate that decides fire-now vs OWE.\n\t */\n\tprivate _canFireDemand(): boolean {\n\t\tif (this._value.terminal !== undefined || this._wave.pending > 0) return false;\n\t\tconst own = this._control.pauseLockset.has(this._slot.pullLock) ? 1 : 0; // discount our own pullId/quiet lock\n\t\treturn this._control.pauseLockset.size <= own; // no external pause lock co-held\n\t}\n\n\t/**\n\t * R-pull (D59): deliver ONE demand pulse — release the pullId so the demand wave RELAYS (not\n\t * absorbed), fire it, then RE-QUIET (1:1). The pullId re-add + the re-entrancy flag are in a\n\t * `finally` so a throwing pull fn (graph-less node, no D30 catch) cannot leave the node\n\t * permanently non-quiet (the wedge-fix silently disabled) — QA-found robustness fix.\n\t */\n\tprivate _deliverPullDemand(): void {\n\t\tthis._control.demandOwed = false;\n\t\tthis._control.inDeliverDemand = true;\n\t\tthis._control.pauseLockset.delete(this._slot.pullLock as LockId);\n\t\ttry {\n\t\t\tthis._firePullDemand();\n\t\t} finally {\n\t\t\tthis._control.pauseLockset.add(this._slot.pullLock as LockId); // re-quiet (even on a throwing fn)\n\t\t\tthis._control.inDeliverDemand = false;\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D59): a cone-routed RESUME of THIS node's pullId arrived (R-up-routing) = a DEMAND.\n\t * Fire immediately if able; else OWE it — pin-5 (a dep DIRTY in flight, _pending>0) or F4/F5 (an\n\t * external PAUSE lock co-holds the node) — and fire when the node next becomes able. A demand\n\t * arriving WHILE a delivery is in flight (synchronous re-entry) is DROPPED (1:1, QA guard).\n\t */\n\tprivate _onDemand(): void {\n\t\tif (this._control.inDeliverDemand) return; // re-entrant demand during an active delivery → drop (1:1)\n\t\tif (this._canFireDemand()) this._deliverPullDemand();\n\t\telse this._control.demandOwed = true;\n\t}\n\n\t/**\n\t * R-pull (D55): service ONE demand. Delivery content = the orthogonal pausable mode:\n\t * - 'resumeAll' → drain the buffered BACKLOG (each `_down` re-synthesizes a leading DIRTY, so\n\t * the per-entry replay is DIRTY-before-DATA — R-pause-modes per-entry arrival order);\n\t * - true → deliver the coalesced LATEST as ONE DIRTY-before-DATA wave (pin 2: the quiet absorb\n\t * suppressed the dep's original DIRTY, so the demand wave restores it before the value).\n\t * Neither branch fires when nothing changed since the last demand → the demand is SILENT.\n\t * Called by `_deliverPullDemand` only when settle-ready; the caller has released the pullId, so\n\t * `_markDirty` relays the leading DIRTY (not absorbed).\n\t */\n\tprivate _firePullDemand(): void {\n\t\tif (this._control.pauseBuffer.length > 0) {\n\t\t\tconst buf = this._control.pauseBuffer;\n\t\t\tthis._control.pauseBuffer = [];\n\t\t\tfor (const wave of buf) this._down(wave);\n\t\t}\n\t\tif (this._control.pausedDepWaveOccurred) {\n\t\t\t// QA-B2: only deliver if the fn can actually run this wave (settle-ready + first-run gate\n\t\t\t// open). A gated run emits no DATA, so emitting the leading DIRTY would STRAND downstream\n\t\t\t// — the exact wedge this feature exists to prevent (NoWedgeWhileQuiet). When gated, stay\n\t\t\t// SILENT and KEEP _pausedDepWaveOccurred so a later demand (once every dep has settled)\n\t\t\t// delivers. Mirrors _settleRewire's pre-_markDirty gate.\n\t\t\tconst gated =\n\t\t\t\tthis._slot.handle !== null &&\n\t\t\t\t!this._wave.hasCalledFnOnce &&\n\t\t\t\t!(this._slot.partial || this._allDepsSettled());\n\t\t\tif (this._wave.pending > 0 || gated) return;\n\t\t\tthis._control.pausedDepWaveOccurred = false;\n\t\t\tthis._markDirty(); // pin 2: leading DIRTY (lock released → relays)\n\t\t\tthis._tryRun(); // fn → DATA, balancing the DIRTY\n\t\t}\n\t}\n\n\t/**\n\t * R-pull (D55/D59): fire a demand that was OWED (deferred at demand time) once the node becomes\n\t * able — called from the dep-settle arms (DATA/RESOLVED/INVALIDATE/terminal drain _pending, pin-5\n\t * + B1/F6) and from `_pauseRelease` (an external PAUSE lock releases, F4/F5).\n\t */\n\tprivate _fireOwedDemandIfReady(): void {\n\t\tif (this._control.inDeliverDemand) return; // don't re-enter during an active delivery (1:1, QA guard)\n\t\tif (this._slot.pull && this._control.demandOwed && this._canFireDemand())\n\t\t\tthis._deliverPullDemand();\n\t}\n\n\t/** Should an outgoing settle slice be deferred into the pause buffer? */\n\tprivate _shouldBufferOnPause(): boolean {\n\t\t// D44: pausable mode is the OUTER gate over R-async-paused buffering.\n\t\t// false: ignore PAUSE/RESUME ENTIRELY — never buffer, keep producing (R-pause-modes; resolves B20).\n\t\tif (this._slot.pausable === false) return false;\n\t\tif (!this._isPaused()) return false;\n\t\t// resumeAll: production-gating — buffer the node's own (sync/async) settle slice too.\n\t\tif (this._slot.pausable === \"resumeAll\") return true;\n\t\t// true (default): PAUSE gates recomputation/propagation, NOT a leaf source's own production.\n\t\t// An async COMPUTE node's (deps>0) in-flight result buffers (R-async-paused / C-2); a depless\n\t\t// async leaf source's own production delivers immediately (R-pause-modes / C-10).\n\t\tif (!this._wave.insideRunWave && this._isAsyncPool() && this._slot.deps.length > 0) return true;\n\t\treturn false;\n\t}\n\n\t/** R-invalidate-idempotent: clear cache + flush + cascade; no-op if nothing cached. */\n\tprivate _invalidate(delivery?: DeliveryMeta): void {\n\t\tif (!this._value.hasData) return; // never-populated or already-reset → no-op\n\t\tthis._value.cache = SENTINEL;\n\t\tthis._value.hasData = false;\n\t\tthis._value.status = \"sentinel\";\n\t\tthis._value.replayRing = []; // BH6: invalidated values are stale — don't replay them\n\t\tfor (const fn of this._hooks.onInvalidate) fn();\n\t\tthis._emitToSubs([\"INVALIDATE\"], delivery);\n\t}\n\n\t// B42 (R-deps-terminal): ALL deps TERMINAL = every dep has reached COMPLETE *or* an ABSORBED\n\t// ERROR. Block only on a LIVE dep (_depTerminal[i] === undefined); an errored dep (terminal = the\n\t// error payload, which R-data-payload guarantees is !== undefined and non-boolean) COUNTS as\n\t// terminal-done. Was\n\t// `tm !== true`, which wedged a node whose errorWhenDepsError:false dep ERRORed (it never\n\t// auto-completed even after every other dep completed). Drives the completeWhenDepsComplete cascade.\n\tprivate _allDepsTerminal(): boolean {\n\t\tif (this._slot.deps.length === 0) return false;\n\t\tfor (const tm of this._dep.terminal) if (tm === undefined) return false;\n\t\treturn true;\n\t}\n\n\t/** R-terminal: resubscribable reset clears terminal + dep state + re-arms the gate. */\n\tprivate _resetLifecycle(): void {\n\t\tfor (const u of this._dep.unsubs) if (u) u();\n\t\tthis._dep.unsubs = [];\n\t\tthis._dep.idxBoxes = [];\n\t\tthis._lifecycle.subscribers.clear();\n\t\tthis._lifecycle.activated = false;\n\t\tthis._value.terminal = undefined;\n\t\tthis._value.hasTorndown = false;\n\t\tthis._wave.hasCalledFnOnce = false;\n\t\tthis._resetDepState();\n\t\tthis._control.pauseLockset.clear();\n\t\tthis._control.pauseBuffer = [];\n\t\tthis._control.pausedDepWaveOccurred = false;\n\t\tthis._control.demandOwed = false; // R-pull (D55): drop any deferred demand\n\t\tthis._value.replayRing = []; // BH6\n\t\tconst isCompute = this._slot.handle !== null || this._slot.deps.length > 0;\n\t\tif (isCompute) {\n\t\t\tthis._value.cache = SENTINEL;\n\t\t\tthis._value.hasData = false;\n\t\t\tthis._value.status = \"sentinel\";\n\t\t} else {\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t}\n\t\tif (!this._privateState.persist) this._privateState.value = SENTINEL;\n\t}\n\n\tprivate _emitToSubs(msg: Message, delivery?: DeliveryMeta): void {\n\t\tif (this._released) return;\n\t\t// Copy guards against subscribe/unsubscribe during iteration.\n\t\tconst subs = [...this._lifecycle.subscribers];\n\t\tfor (const sink of subs) sink(msg, delivery);\n\t}\n\n\t/** Batch commit (R-batch-coalesce): deliver the deferred tier-3 wave now. */\n\t__commitBatchedWave(wave: Wave): void {\n\t\tthis._wave.batchDirtyOwed = false; // commit delivers the real settle (BH1)\n\t\tthis._down(wave); // batch is inactive at commit -> processes normally\n\t}\n\n\t/** Batch rollback: balance the immediate DIRTY with a RESOLVED so downstream un-dirties. */\n\t__rollbackBatched(): void {\n\t\t// BH1: keyed on _batchDirtyOwed (not _emittedDirtyThisWave, which a fn wave between\n\t\t// defer and rollback would have reset) so the balancing RESOLVED is never skipped.\n\t\tif (this._wave.batchDirtyOwed) {\n\t\t\tthis._wave.batchDirtyOwed = false;\n\t\t\tthis._wave.emittedDirtyThisWave = false;\n\t\t\tthis._value.status = this._value.hasData ? \"settled\" : \"sentinel\";\n\t\t\tthis._emitToSubs([\"RESOLVED\"]);\n\t\t}\n\t}\n\n\t/** B49: enqueue a committed-boundary task on this node's graph-local core. */\n\t__deferBoundary(fn: () => void, batchToken?: object): void {\n\t\tdeferRewire(this._core, fn, {\n\t\t\tbatchToken,\n\t\t\tisReady: () => !this._hasBoundaryPauseLock(),\n\t\t});\n\t}\n}\n\n/**\n * Construct a node (R-node-iface / D5 / L1.9 deps-first).\n * node([], null, { initial }) — state node (manual source; emit via .down)\n * node([], fn) — producer (runs on activation)\n * node([a, b], fn) — compute / derived\n * node([dep]) — passthrough wire\n */\nexport function node<T = unknown>(\n\tdeps: Node<unknown>[] = [],\n\thandleOrFn: Handle | NodeFn | null = null,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, handleOrFn, opts);\n}\n\n/**\n * Construct a dynamicNode (R-dynamic-node / D35) — a node variant whose fn reads a\n * subset of a fixed superset of deps per invocation via `ctx.track(i)`. All declared\n * deps participate in wave tracking; an unread dep's change re-runs the fn, which re-emits\n * its current value as DATA (D49 removed equals-absorption — dedup is opt-in via\n * distinctUntilChanged). Intra-graph only (D22).\n */\nexport function dynamicNode<T = unknown>(\n\tdeps: Node<unknown>[],\n\tfn: NodeFn,\n\topts: NodeOptions<T> = {},\n): Node<T> {\n\treturn new Node<T>(deps, fn, { ...opts, dynamic: true });\n}\n","/**\n * Graph checkpoint public data shape (D83/D86/D90/D116).\n *\n * Checkpoint is a graph lifecycle snapshot: strict-JSON-compatible data, no storage I/O,\n * no observe-log replay, and no restore runtime in this first TS slice.\n */\n\nimport { type StrictJsonValue, strictJsonCodec } from \"../json/codec.js\";\nimport type { Node } from \"../node/node.js\";\nimport type { NodeVersionJson } from \"../node/versioning.js\";\nimport { SENTINEL } from \"../protocol/messages.js\";\n\nexport const GRAPH_CHECKPOINT_VERSION = \"graphrefly.checkpoint.v1\" as const;\n\nexport type GraphCheckpointVersion = typeof GRAPH_CHECKPOINT_VERSION;\n\nexport type GraphCheckpointJson = StrictJsonValue;\n\nexport type GraphCheckpointValue =\n\t| { kind: \"SENTINEL\" }\n\t| { kind: \"DATA\"; data: GraphCheckpointJson };\n\nexport type GraphCheckpointTerminal =\n\t| { kind: \"none\" }\n\t| { kind: \"COMPLETE\" }\n\t| { kind: \"ERROR\"; error: GraphCheckpointJson };\n\nexport type GraphCheckpointFactory =\n\t| {\n\t\t\tkind: \"registry-ref\";\n\t\t\tref: string;\n\t\t\tconfig?: GraphCheckpointJson;\n\t\t\tconfigVersion?: GraphCheckpointJson;\n\t }\n\t| { kind: \"local-only\"; name: string; reason: string };\n\nexport interface GraphCheckpointNode {\n\tid: string;\n\tname?: string;\n\tfactory: GraphCheckpointFactory;\n\tstatus: string;\n\tdeps: string[];\n\tvalue: GraphCheckpointValue;\n\tbackendState?: GraphCheckpointJson;\n\tversion?: NodeVersionJson;\n\tterminal: GraphCheckpointTerminal;\n\tlifecycle: { activated: boolean; hasCalledFnOnce: boolean };\n\tctxState: { persist: boolean; value: GraphCheckpointValue };\n\tmeta?: { [key: string]: GraphCheckpointJson };\n}\n\nexport interface GraphCheckpointEdge {\n\tfrom: string;\n\tto: string;\n}\n\nexport interface GraphCheckpointMount {\n\tat: string;\n\tcheckpoint: GraphCheckpoint;\n}\n\nexport interface GraphCheckpoint {\n\tversion: GraphCheckpointVersion;\n\tname?: string;\n\tnodes: GraphCheckpointNode[];\n\tedges: GraphCheckpointEdge[];\n\tmounts?: GraphCheckpointMount[];\n}\n\nexport function toCheckpointJson(value: unknown, path = \"$\"): GraphCheckpointJson {\n\ttry {\n\t\treturn strictJsonCodec.decode(strictJsonCodec.encode(value)) as GraphCheckpointJson;\n\t} catch (cause) {\n\t\tthrow new TypeError(`checkpoint: value at ${path} is not strict JSON compatible`, {\n\t\t\tcause,\n\t\t});\n\t}\n}\n\nexport function checkpointValue(\n\tvalue: unknown,\n\thasData: boolean,\n\tpath: string,\n): GraphCheckpointValue {\n\tif (!hasData || value === SENTINEL) return { kind: \"SENTINEL\" };\n\treturn { kind: \"DATA\", data: toCheckpointJson(value, path) };\n}\n\nexport function checkpointTerminal(value: unknown, path: string): GraphCheckpointTerminal {\n\tif (value === undefined) return { kind: \"none\" };\n\tif (value === true) return { kind: \"COMPLETE\" };\n\treturn { kind: \"ERROR\", error: toCheckpointJson(value, path) };\n}\n\ntype BackendStateContributor = () => unknown;\n\nconst backendStateContributors = new WeakMap<Node<unknown>, BackendStateContributor>();\n\n/** @internal D160: collection-owned backend checkpoint contributor for graph checkpoint. */\nexport function registerBackendStateContributor(\n\tnode: Node<unknown>,\n\tcontributor: BackendStateContributor,\n): void {\n\tbackendStateContributors.set(node, contributor);\n}\n\n/** @internal D160: capture a node's collection backend state when it has a contributor. */\nexport function checkpointBackendStateOfNode(\n\tnode: Node<unknown>,\n\tpath: string,\n): GraphCheckpointJson | undefined {\n\tconst contributor = backendStateContributors.get(node);\n\tif (contributor === undefined) return undefined;\n\treturn toCheckpointJson(contributor(), path);\n}\n","/**\n * Operators as free-standing factory definitions (D43 / D6 / D40 Catalog-first).\n *\n * Operators are `node` sugar (D6), NOT verbs (D4) and NEVER in parity (D24). Each is a\n * pure {@link Operator} spec — `{factory, body, opts}` — built on the bare `node` primitive\n * (NOT the `derived` verb): `body` reads ctx dep slots positionally and emits via\n * `ctx.down`. Two ways to instantiate:\n *\n * - {@link initNode}(op, deps, opts?) — bare, no Graph; returns a working `Node<T>`.\n * - `g.initNode(op, deps, opts?)` — graph-bound; the SAME call, plus inspection registration\n * (the real factory name lands in the graph's `_entries`, so describe/observe/profile\n * show it — D6/R-describe — while the node stays thin, R-node-thin).\n *\n * The D30 throw→ERROR boundary lives once, in the free {@link initNode} (which `g.initNode`\n * funnels through). The pure-ts `operatorOpts/partialOperatorOpts/gatedOperatorOpts` trio is\n * NOT ported: its sole job (`describeKind:\"derived\"`) is dead under D6/D39 (factory = the\n * REAL operator name); only the `partial`/`terminalAsRealInput` flags survive, carried\n * per-operator in `op.opts`.\n *\n * Config is folded into the factory (`map(fn)`, `scan(reducer, seed)`, `take(n)`, `merge()`),\n * so fn params are annotated where the source type can't be inferred (RxJS-pipe cost);\n * dep-type safety is recovered by the typed `g.initNode` overloads.\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepCount,\n\tdepLatest,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { NodeCore } from \"../node/core.js\";\nimport { Node, type NodeOptions, withNodeCore } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { type GraphCheckpointJson, toCheckpointJson } from \"./checkpoint.js\";\nimport type { GraphRestoreDefinition, GraphRestoreEntry, GraphRestoreRegistry } from \"./restore.js\";\n\n/**\n * A free-standing operator definition (D43). `TIn` = the element type each dep delivers\n * (the operator reads `depLatest(ctx, i) as TIn`); `TOut` = the emitted value type.\n * `__in`/`__out` are phantom-only (never assigned) — they let `g.initNode` infer + check the\n * dep tuple against the operator without an explicit type argument.\n */\nexport interface Operator<TIn = unknown, TOut = unknown> {\n\t/** Real operator name shown in describe (D6/L1.5) — recorded at `_add` by `g.initNode`. */\n\treadonly factory: string;\n\t/** The ctx-body: reads ctx dep slots positionally, emits via `ctx.down`. */\n\treadonly body: (ctx: Ctx) => void;\n\t/** Behavioral node options the operator needs (e.g. `partial:true` for combine-family). */\n\treadonly opts?: Partial<NodeOptions<TOut>>;\n\t/**\n\t * D97/D100 restore metadata derived from a named definition or static built-in config.\n\t * This is semantic metadata only; dispatcher handles stay graph-local runtime state.\n\t */\n\treadonly restore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t};\n\t/** @internal phantom — never set; carries the dep element type for `g.initNode` inference. */\n\treadonly __in?: TIn;\n\t/** @internal phantom — never set; carries the output value type. */\n\treadonly __out?: TOut;\n}\n\ntype MutableRestoreRegistry = Map<string, GraphRestoreEntry> | Record<string, GraphRestoreEntry>;\n\nexport type RestoreRegistryEntry = GraphRestoreEntry;\n\nexport interface Definition<S = unknown, T = unknown> extends GraphRestoreDefinition<S, T> {\n\treadonly ref: string;\n\treadonly fn: (v: S) => T;\n}\n\nexport interface DefineOpts {\n\tregistry?: MutableRestoreRegistry;\n}\n\nfunction registryHas(registry: MutableRestoreRegistry, ref: string): boolean {\n\treturn registry instanceof Map ? registry.has(ref) : Object.hasOwn(registry, ref);\n}\n\nfunction registrySet(\n\tregistry: MutableRestoreRegistry,\n\tref: string,\n\tentry: GraphRestoreEntry,\n): void {\n\tif (registryHas(registry, ref)) {\n\t\tthrow new Error(`restoreRegistry: duplicate ref '${ref}'`);\n\t}\n\tif (registry instanceof Map) registry.set(ref, entry);\n\telse registry[ref] = entry;\n}\n\nexport function addToRestoreRegistry(\n\tregistry: MutableRestoreRegistry,\n\tentry: GraphRestoreEntry,\n): void {\n\tregistrySet(registry, entry.ref, entry);\n}\n\nexport function restoreRegistry(\n\tentries: readonly GraphRestoreEntry[] = [],\n\tbase?: GraphRestoreRegistry,\n): Map<string, GraphRestoreEntry> {\n\tconst out = new Map<string, GraphRestoreEntry>();\n\tif (base instanceof Map) {\n\t\tfor (const [ref, entry] of base) registrySet(out, ref, entry);\n\t} else if (base !== undefined) {\n\t\tfor (const [ref, entry] of Object.entries(base)) registrySet(out, ref, entry);\n\t}\n\tfor (const entry of entries) addToRestoreRegistry(out, entry);\n\treturn out;\n}\n\nfunction isDefinition<S, T>(fn: ((v: S) => T) | Definition<S, T>): fn is Definition<S, T> {\n\treturn typeof fn === \"object\" && fn !== null && (fn as Definition<S, T>).kind === \"definition\";\n}\n\nexport function define<S, T>(\n\tref: string,\n\tfn: (v: S) => T,\n\topts: DefineOpts = {},\n): Definition<S, T> {\n\tconst jsonRef = toCheckpointJson(ref, \"define.ref\");\n\tif (typeof jsonRef !== \"string\") throw new TypeError(\"define: ref must be a string\");\n\tconst definition: Definition<S, T> = {\n\t\tkind: \"definition\",\n\t\tref: jsonRef,\n\t\tfn,\n\t};\n\tif (opts.registry !== undefined) addToRestoreRegistry(opts.registry, definition);\n\treturn definition;\n}\n\n/**\n * Instantiate an operator as a bare `Node<T>` — NO Graph required (D43 bare-node path).\n * Wraps `op.body` in the D30 value-throw→ERROR boundary; merges `op.opts` with caller `opts`\n * (caller wins, so `partial`/`pool`/`dispatcher` overrides take effect). The\n * dispatcher defaults to the process-global (D26) unless `opts.dispatcher` is passed.\n *\n * `g.initNode` is the same call PLUS graph registration; graph inspection\n * (describe/observe/profile) requires that path — a node built bare here is not registered in\n * any graph's index.\n */\nexport function initNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn makeInitNode(op, deps, opts);\n}\n\n/** @internal Graph-bound operator instantiation into a graph-local B49 core. */\nexport function initNodeWithCore<TIn, TOut>(\n\tcore: NodeCore,\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut> = {},\n): Node<TOut> {\n\treturn withNodeCore(core, () => makeInitNode(op, deps, opts));\n}\n\nfunction makeInitNode<TIn, TOut>(\n\top: Operator<TIn, TOut>,\n\tdeps: readonly Node<unknown>[],\n\topts: NodeOptions<TOut>,\n): Node<TOut> {\n\tconst body = operatorNodeFn(op);\n\t// D43-reserved / D51: stamp the operator's real factory onto the bare node so a runtime *Map\n\t// inner (created here via fromAny, NOT registered in any graph) is named in describe's\n\t// auto-discovery. A graph-bound g.initNode also records it in `_entries` (entry.factory wins\n\t// there); this field is only read for a node absent from the graph index. Caller opts win.\n\treturn new Node<TOut>([...deps], body, { factory: op.factory, ...op.opts, ...opts });\n}\n\n/** @internal Build the dispatcher body for an Operator spec. */\nexport function operatorNodeFn<TIn, TOut>(op: Operator<TIn, TOut>): NodeFn {\n\treturn (ctx) => {\n\t\ttry {\n\t\t\top.body(ctx);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"operator threw without a valid error payload\")]]); // D30: value-level throw → ERROR\n\t\t}\n\t};\n}\n\n// ── Slice 1 — single-dep map / take / control (CSP-2.7 catalog re-derive, D40) ──\n// All read dep 0 positionally + emit via ctx.down. Under D49 every occurrence is DATA (no\n// equals-absorption); a body that returns WITHOUT emitting gets a substrate-synthesized undirty\n// RESOLVED (R-resolved-undirty) — so a \"skip this wave\" is a bare `return`. Terminal-emitting\n// operators (reduce/last/find/elementAt) read `depTerminal(ctx, 0)` via the\n// `completeWhenDepsComplete:false + terminalAsRealInput:true` flags (R-deps-terminal): the fn fires\n// on the source's COMPLETE and emits its final value. NOT 1:1 pure-ts ports — the frozen reference\n// (D41) uses a producer + internal `subscribeOr`, the D45-banned describe island; these are\n// declared-dep nodes whose single edge `describe` shows truthfully.\n\n/** map: emit fn(value). A named {@link define} makes the map restorable via the map descriptor (D101). */\nexport function map<S, T>(fn: ((v: S) => T) | Definition<S, T>): Operator<S, T> {\n\tif (isDefinition(fn)) {\n\t\treturn mapFromFunction(fn.fn, {\n\t\t\tref: \"map\",\n\t\t\tconfig: { fn: toCheckpointJson(fn.ref, `map.fn`) },\n\t\t});\n\t}\n\treturn mapFromFunction(fn);\n}\n\nfunction mapFromFunction<S, T>(\n\tfn: (v: S) => T,\n\trestore?: {\n\t\tref: string;\n\t\tconfig?: GraphCheckpointJson;\n\t\tconfigVersion?: GraphCheckpointJson;\n\t},\n): Operator<S, T> {\n\treturn {\n\t\tfactory: \"map\",\n\t\t...(restore ? { restore } : {}),\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) ctx.down([[\"DATA\", fn(v as S)]]);\n\t\t},\n\t};\n}\n\n/** filter: emit value only when pred(value) (else skip the wave). */\nexport function filter<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"filter\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b) if (pred(v as S)) ctx.down([[\"DATA\", v]]);\n\t\t},\n\t};\n}\n\n/** scan: stateful accumulator over the upstream (acc seeded once, kept in ctx.state). */\nexport function scan<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"scan\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tfor (const v of b) {\n\t\t\t\tacc = reducer(acc, v as S);\n\t\t\t\tctx.down([[\"DATA\", acc]]);\n\t\t\t}\n\t\t\tctx.state.set(acc);\n\t\t},\n\t};\n}\n\n/** take: emit the first n values, then COMPLETE (terminal-is-forever). */\nexport function take<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"take\",\n\t\trestore: { ref: \"take\", config: { n: toCheckpointJson(n, \"take.n\") } },\n\t\tbody: (ctx) => {\n\t\t\tif (n <= 0) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (count >= n) return; // already satisfied\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count >= n) break;\n\t\t\t\tcount += 1;\n\t\t\t\tctx.down(count >= n ? [[\"DATA\", v], [\"COMPLETE\"]] : [[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/** distinctUntilChanged: emit only when the value differs from the previous emit. */\nexport function distinctUntilChanged<S>(eq: (a: S, b: S) => boolean = Object.is): Operator<S, S> {\n\treturn {\n\t\tfactory: \"distinctUntilChanged\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst prev = ctx.state.get<{ v: S }>();\n\t\t\tlet last = prev?.v;\n\t\t\tlet hasLast = prev !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasLast && eq(last as S, v)) continue;\n\t\t\t\tlast = v;\n\t\t\t\thasLast = true;\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tif (hasLast) ctx.state.set({ v: last as S });\n\t\t},\n\t};\n}\n\n/**\n * merge: interleave several sources — emit each DATA from whichever dep fired. `partial:true`\n * (combine-family): fires on any single dep, not gated on all deps settling.\n */\nexport function merge<T>(): Operator<T, T> {\n\treturn {\n\t\tfactory: \"merge\",\n\t\topts: { partial: true },\n\t\tbody: (ctx) => {\n\t\t\tfor (let i = 0; i < depCount(ctx); i++) {\n\t\t\t\tconst b = depBatch(ctx, i);\n\t\t\t\tif (b && b.length > 0) {\n\t\t\t\t\tfor (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * reduce: accumulate over the whole source, emit ONE final value on the source's COMPLETE\n * (RxJS `reduce`). Unlike {@link scan} (which emits every step), reduce stays quiet until the\n * source terminates. `completeWhenDepsComplete:false + terminalAsRealInput:true`: the fn fires on\n * the source COMPLETE (reading `terminal===true`) and emits the accumulator + COMPLETE. An empty\n * source emits the seed (RxJS parity). A source ERROR auto-forwards (errorWhenDepsError default).\n */\nexport function reduce<S, T>(reducer: (acc: T, v: S) => T, seed: T): Operator<S, T> {\n\treturn {\n\t\tfactory: \"reduce\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet acc = ctx.state.get<T>() ?? seed;\n\t\t\tif (b) for (const v of b) acc = reducer(acc, v as S);\n\t\t\tctx.state.set(acc);\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"DATA\", acc], [\"COMPLETE\"]]);\n\t\t\t// else (live DATA wave): no emit → substrate-synthesized undirty RESOLVED (D49).\n\t\t},\n\t};\n}\n\n/**\n * pairwise: emit `[previous, current]` for each consecutive pair; the very first value produces no\n * pair (quiet → undirty RESOLVED). Previous value is kept in `ctx.state`.\n */\nexport function pairwise<S>(): Operator<S, readonly [S, S]> {\n\treturn {\n\t\tfactory: \"pairwise\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tconst st = ctx.state.get<{ prev: S }>();\n\t\t\tlet prev = st?.prev;\n\t\t\tlet hasPrev = st !== undefined;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (hasPrev) ctx.down([[\"DATA\", [prev as S, v] as const]]);\n\t\t\t\tprev = v;\n\t\t\t\thasPrev = true;\n\t\t\t}\n\t\t\tif (hasPrev) ctx.state.set({ prev: prev as S });\n\t\t},\n\t};\n}\n\n/** skip: drop the first `n` DATA values, then pass the rest through. */\nexport function skip<S>(n: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"skip\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (count < n) {\n\t\t\t\t\tcount += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(count);\n\t\t},\n\t};\n}\n\n/**\n * takeWhile: emit values while `pred` holds; on the first value that fails `pred`, COMPLETE\n * WITHOUT emitting it (RxJS default, non-inclusive). Terminal-is-forever once it completes.\n */\nexport function takeWhile<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"takeWhile\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (pred(v)) ctx.down([[\"DATA\", v]]);\n\t\t\t\telse {\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * first: emit the first value matching `pred` (or simply the first value), then COMPLETE. EDGE\n * (RxJS divergence, flagged — same class as last/find/elementAt): if the source COMPLETEs with no\n * matching value, the substrate auto-cascades a bare COMPLETE (no value); RxJS `first()` throws\n * EmptyError. Could align to `[[ERROR, EmptyError]]` (expressible) if strict RxJS parity is wanted.\n */\nexport function first<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"first\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tfor (const v of b as readonly S[]) {\n\t\t\t\tif (!pred || pred(v)) {\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no match in this wave → undirty RESOLVED (await next match)\n\t\t},\n\t};\n}\n\n/**\n * last: emit the last value matching `pred` (or the last value) on the source's COMPLETE.\n * `completeWhenDepsComplete:false + terminalAsRealInput:true`. EDGE (RxJS divergence, flagged):\n * RxJS `last()` throws EmptyError when no value matched; we COMPLETE without a value (no throw) —\n * the clean-slate substrate has no \"complete-or-throw\" terminal and SENTINEL forbids emitting a\n * placeholder.\n */\nexport function last<S>(pred?: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"last\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) for (const v of b) if (!pred || pred(v as S)) ctx.state.set({ v });\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) {\n\t\t\t\tconst st = ctx.state.get<{ v: S }>();\n\t\t\t\tctx.down(st ? [[\"DATA\", st.v], [\"COMPLETE\"]] : [[\"COMPLETE\"]]);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * find: emit the first value matching `pred`, then COMPLETE. EDGE (RxJS divergence, flagged): RxJS\n * `find` emits `undefined` then COMPLETE when nothing matched — but `undefined` IS the SENTINEL\n * (R-sentinel), so a not-found source COMPLETE here emits a bare COMPLETE (no value).\n */\nexport function find<S>(pred: (v: S) => boolean): Operator<S, S> {\n\treturn {\n\t\tfactory: \"find\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (pred(v as S)) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // not found → bare COMPLETE\n\t\t},\n\t};\n}\n\n/**\n * elementAt: emit the value at zero-based `index`, then COMPLETE. EDGE (RxJS divergence, flagged):\n * RxJS throws ArgumentOutOfRangeError if the source completes before `index`; we COMPLETE without\n * a value (no throw), consistent with last/find.\n */\nexport function elementAt<S>(index: number): Operator<S, S> {\n\treturn {\n\t\tfactory: \"elementAt\",\n\t\topts: { completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet count = ctx.state.get<number>() ?? 0;\n\t\t\tif (b) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tif (count === index) {\n\t\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\tctx.state.set(count);\n\t\t\t}\n\t\t\tif (isTerminalComplete(depTerminal(ctx, 0))) ctx.down([[\"COMPLETE\"]]); // index out of range → bare COMPLETE\n\t\t},\n\t};\n}\n\n/** Observer object for {@link tap} — lifecycle-aware side effects (RxJS tap observer form). */\nexport interface TapObserver<T> {\n\tdata?: (value: T) => void;\n\terror?: (err: unknown) => void;\n\tcomplete?: () => void;\n}\n\n/**\n * tap: invoke a side effect on each DATA (function form) or on data/error/complete (observer form);\n * values pass through unchanged. The observer form reads source terminals\n * (`completeWhenDepsComplete:false + errorWhenDepsError:false + terminalAsRealInput:true`) so it can\n * call `error`/`complete` then forward the terminal; the function form lets the substrate\n * auto-cascade terminals.\n */\nexport function tap<S>(fnOrObserver: ((v: S) => void) | TapObserver<S>): Operator<S, S> {\n\tif (typeof fnOrObserver === \"function\") {\n\t\tconst fn = fnOrObserver;\n\t\treturn {\n\t\t\tfactory: \"tap\",\n\t\t\tbody: (ctx) => {\n\t\t\t\tconst b = depBatch(ctx, 0);\n\t\t\t\tif (b)\n\t\t\t\t\tfor (const v of b) {\n\t\t\t\t\t\tfn(v as S);\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n\tconst obs = fnOrObserver;\n\treturn {\n\t\tfactory: \"tap\",\n\t\topts: {\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tobs.complete?.();\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(terminal)) {\n\t\t\t\tconst err = terminalErrorValue(terminal);\n\t\t\t\tobs.error?.(err);\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (b)\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tobs.data?.(v as S);\n\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * onFirstData (alias `tapFirst`): invoke `fn` exactly once on the first qualifying value (default\n * `where: v => v != null` — null/undefined pass through without counting as \"first\"), then pass all\n * values through unchanged. The one-shot guard is per-node `ctx.state` (NOT a factory closure, so a\n * second instantiation of the same factory re-arms — R-ctx-state).\n */\nexport function onFirstData<S>(\n\tfn: (v: S) => void,\n\topts?: { where?: (v: S) => boolean },\n): Operator<S, S> {\n\tconst where = opts?.where ?? ((v: S) => v != null);\n\treturn {\n\t\tfactory: \"onFirstData\",\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tif (!b) return;\n\t\t\tlet fired = ctx.state.get<boolean>() ?? false;\n\t\t\tfor (const v of b) {\n\t\t\t\tif (!fired && where(v as S)) {\n\t\t\t\t\tfired = true;\n\t\t\t\t\tfn(v as S);\n\t\t\t\t}\n\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t}\n\t\t\tctx.state.set(fired);\n\t\t},\n\t};\n}\n\n/** tapFirst: alias of {@link onFirstData} (the one-shot companion to {@link tap}). */\nexport const tapFirst = onFirstData;\n\n/** Options for {@link settle}. */\nexport interface SettleOpts<S> {\n\t/** Consecutive no-change waves before declaring convergence + COMPLETE. */\n\tquietWaves: number;\n\t/** Optional hard cap on total waves before forced COMPLETE. */\n\tmaxWaves?: number;\n\t/** Optional comparator; a DATA equal to the previous one does NOT reset the quiet counter. */\n\tequals?: (a: S, b: S) => boolean;\n}\n\n/** Internal settle accumulator state (per-node, R-ctx-state). */\ninterface SettleState<S> {\n\tlast: S | undefined;\n\thasValue: boolean;\n\tquiet: number;\n\twaves: number;\n\tdone: boolean;\n}\n\n/**\n * settle: forward each DATA unchanged, watch for convergence, COMPLETE once the source has been\n * quiet for `quietWaves` consecutive waves (or `maxWaves` elapsed). \"Wave\" = one fn invocation\n * (a DATA batch OR a bare undirty RESOLVED end-of-wave). No polling (R-no-polling) — the counter\n * advances only on real upstream waves. `settle`'s own `equals` is a body comparator, NOT the\n * removed substrate `equals` (D49).\n */\nexport function settle<S>(opts: SettleOpts<S>): Operator<S, S> {\n\tconst { quietWaves, maxWaves, equals } = opts;\n\tif (!Number.isInteger(quietWaves) || quietWaves < 1) {\n\t\tthrow new RangeError(`settle: quietWaves must be a positive integer (got ${quietWaves})`);\n\t}\n\tif (maxWaves != null && (!Number.isInteger(maxWaves) || maxWaves < 1)) {\n\t\tthrow new RangeError(`settle: maxWaves must be a positive integer when set (got ${maxWaves})`);\n\t}\n\treturn {\n\t\tfactory: \"settle\",\n\t\tbody: (ctx) => {\n\t\t\tconst st: SettleState<S> = ctx.state.get<SettleState<S>>() ?? {\n\t\t\t\tlast: undefined,\n\t\t\t\thasValue: false,\n\t\t\t\tquiet: 0,\n\t\t\t\twaves: 0,\n\t\t\t\tdone: false,\n\t\t\t};\n\t\t\tif (st.done) return;\n\t\t\tst.waves++;\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tlet sawChange = false;\n\t\t\tif (b && b.length > 0) {\n\t\t\t\tfor (const v of b) {\n\t\t\t\t\tconst next = v as S;\n\t\t\t\t\tconst isChange = !st.hasValue || equals == null || !equals(st.last as S, next);\n\t\t\t\t\tif (isChange) sawChange = true;\n\t\t\t\t\tst.last = next;\n\t\t\t\t\tst.hasValue = true;\n\t\t\t\t\tctx.down([[\"DATA\", next]]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.quiet = sawChange ? 0 : st.quiet + 1;\n\t\t\tconst settled = st.hasValue && st.quiet >= quietWaves;\n\t\t\tconst exhausted = maxWaves != null && st.waves >= maxWaves;\n\t\t\tif (settled || exhausted) {\n\t\t\t\tst.done = true;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t\t// A no-DATA wave that didn't converge → bare undirty RESOLVED is synthesized by the\n\t\t\t// substrate (D49); nothing to emit here.\n\t\t},\n\t};\n}\n\n// ── Slice 3 — error-handling control (CSP-2.7, D40) ──\n// rescue/catchError ABSORB the source ERROR (errorWhenDepsError:false) and read the error payload\n// from `depTerminal(ctx, 0)` (R-deps-terminal). They set completeWhenDepsComplete:false so a\n// normal source COMPLETE is forwarded explicitly — which ALSO sidesteps B40 (the\n// completeWhenDepsComplete:true × absorbed-errored-dep auto-complete gap): there is no auto-complete\n// to block. valve is a [source, control] gate (state-verb-legitimate control input).\n\n/**\n * rescue (alias `catchError`): replace an upstream ERROR with a recovered value. On source DATA →\n * forward; on source ERROR → emit `recover(err)` as DATA (if `recover` throws, forward THAT as\n * ERROR); on source COMPLETE → COMPLETE. After recovery the source is terminal-errored (dead) so no\n * further values flow — the recovered value is the final cached value (matches the frozen pure-ts\n * reference; it does NOT auto-COMPLETE, RxJS-`catchError(()=>of(x))` divergence, flagged).\n */\nexport function rescue<S>(recover: (err: unknown) => S): Operator<S, S> {\n\treturn {\n\t\tfactory: \"rescue\",\n\t\topts: {\n\t\t\terrorWhenDepsError: false,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t\tbody: (ctx) => {\n\t\t\tconst b = depBatch(ctx, 0);\n\t\t\tconst terminal = depTerminal(ctx, 0);\n\t\t\tif (b) for (const v of b) ctx.down([[\"DATA\", v]]);\n\t\t\tif (isTerminalComplete(terminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t} else if (isTerminalError(terminal)) {\n\t\t\t\t// ERROR payload absorbed → recover.\n\t\t\t\ttry {\n\t\t\t\t\tctx.down([[\"DATA\", recover(terminalErrorValue(terminal))]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"rescue threw without a valid error payload\")]]);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** catchError: RxJS-named alias of {@link rescue}. */\nexport const catchError = rescue;\n\n/** Options for {@link valve}. */\nexport interface ValveOpts {\n\t/**\n\t * Optional AbortController (or a `() => AbortController | undefined` factory): on the control's\n\t * truthy→falsy edge, `valve` calls `controller.abort()` — cancel an in-flight async boundary\n\t * (LLM/fetch) the caller threaded `controller.signal` into. An external-resource cleanup (like\n\t * `ctx.onDeactivation`), NOT an imperative reactive trigger (R-no-imperative).\n\t */\n\tabortInFlight?: AbortController | (() => AbortController | undefined);\n}\n\n/**\n * valve: forward the source's DATA only while `control` (dep 1) is truthy; when closed, stay quiet\n * (undirty RESOLVED). `[source, control]` declared deps + `partial:true` (the control wave can fire\n * before the source ever delivers). `completeWhenDepsComplete:false` — closing the gate (control\n * terminating) does NOT complete the valve; only the SOURCE's terminal (read via\n * `terminalAsRealInput`) is forwarded. The `state`-verb control input is a legitimate external\n * boundary (D4 / D54), not a forbidden imperative trigger.\n */\nexport function valve<S>(opts?: ValveOpts): Operator<S, S> {\n\tconst abortInFlight = opts?.abortInFlight;\n\treturn {\n\t\tfactory: \"valve\",\n\t\topts: { partial: true, completeWhenDepsComplete: false, terminalAsRealInput: true },\n\t\tbody: (ctx) => {\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst ctlBatch = depBatch(ctx, 1);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\t\tconst controlValue = depLatest(ctx, 1) as boolean | undefined;\n\n\t\t\tif (abortInFlight != null) {\n\t\t\t\t// Fire abort on the truthy→falsy edge only (never on activation / no prior state).\n\t\t\t\tconst prev = ctx.state.get<{ ctl: boolean | undefined }>();\n\t\t\t\tif (prev?.ctl === true && !controlValue) {\n\t\t\t\t\tconst c = typeof abortInFlight === \"function\" ? abortInFlight() : abortInFlight;\n\t\t\t\t\tc?.abort();\n\t\t\t\t}\n\t\t\t\tctx.state.set({\n\t\t\t\t\tctl: controlValue === true ? true : controlValue == null ? undefined : false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Source terminal forwarding (control terminal is absorbed by completeWhenDepsComplete:false).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!controlValue) return; // gate closed → quiet (undirty RESOLVED)\n\n\t\t\tif (srcBatch && srcBatch.length > 0) {\n\t\t\t\tfor (const v of srcBatch) ctx.down([[\"DATA\", v]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Gate just opened this wave (control fired, source didn't): re-emit the last source value.\n\t\t\tconst srcLatest = depLatest(ctx, 0);\n\t\t\tif (ctlBatch && ctlBatch.length > 0 && srcLatest !== undefined) {\n\t\t\t\tctx.down([[\"DATA\", srcLatest as S]]);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * Async + sync sources (binding-layer sugar, D43 / D40 / feedback_async_sources_binding_layer).\n *\n * Sources are depless {@link Operator}`<never, T>` specs built on the `producer`/`node` path:\n * the body runs ONCE on activation (node `_activate`), schedules its work, and emits later via\n * the captured `ctx.down` (an external tier-3 emit → the leading DIRTY is synthesized for it,\n * R-dirty-before-data). Async lives ONLY here (R-no-raw-async / F-SYNC-CORE): `setTimeout` /\n * `Promise` / `for await` are confined to source bodies; the wave core stays sync. Cleanup is\n * `ctx.onDeactivation` (D28), NOT a returned object. Per-language (D6/D24), never in parity.\n *\n * Instantiate via `g.initNode(timer(1000), [])` (graph-bound, inspectable) or\n * {@link initNode}(timer(1000), []) (bare). Pool/pause defaults (D43): timer/interval =\n * sync + pausable:false (keep producing through PAUSE); fromPromise/fromAsyncIter = async\n * (default pausable, so a paused source buffers its late emits — R-async-paused).\n */\n\nimport type { Ctx } from \"../ctx/types.js\";\nimport type { Node, NodeOptions } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { toCheckpointJson } from \"./checkpoint.js\";\nimport type {\n\tDriverCancel,\n\tDriverResult,\n\tHttpRequest,\n\tHttpResponse,\n\tProcessCommand,\n\tProcessResult,\n\tSseDriverEvent,\n\tSseEvent,\n\tSseRequest,\n\tWebhookDriverEvent,\n\tWebhookEvent,\n\tWebhookRegistration,\n\tWebSocketDriverEvent,\n\tWebSocketEvent,\n\tWebSocketRequest,\n} from \"./environment.js\";\nimport { initNode, type Operator } from \"./operators.js\";\n\n/**\n * Values accepted by {@link fromAny}: an existing Node, a Promise, an (a)sync iterable, or a\n * bare scalar. The universal coercion target for higher-order operators (CSP-2.7).\n */\nexport type NodeInput<T> = Node<T> | PromiseLike<T> | AsyncIterable<T> | Iterable<T> | T;\n\n/** Host-boundary options for {@link singleFromAny}. */\nexport interface SingleFromAnyOptions<K> {\n\t/**\n\t * Map a caller key to the in-flight dedupe key. Defaults to key identity; object keys dedupe only\n\t * when the same object reference is reused. Return a stable string/canonical value for structural\n\t * object-key dedupe.\n\t */\n\tkeyOf?: (key: K) => unknown;\n\t/** Treat a sync iterable result as a stream and take its first item. Defaults to scalar value. */\n\titer?: boolean;\n}\n\n/**\n * Internal: build a depless source spec. `setup` runs once on activation; its returned fn (if\n * any) is registered as the deactivation cleanup (clear timers / abort). `setup` schedules the\n * async work and emits via `ctx.down` — synchronously (sync sources) or later (async sources).\n */\nfunction source<T>(\n\tfactory: string,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: setup returns a cleanup fn OR nothing — the void arm keeps no-return source bodies (e.g. `of`/`fromIter`) ergonomic, same idiom as EffectFn.\n\tsetup: (ctx: Ctx) => void | (() => void),\n\topts?: Partial<NodeOptions<T>>,\n): Operator<never, T> {\n\treturn {\n\t\tfactory,\n\t\topts,\n\t\tbody: (ctx) => {\n\t\t\tlet cleanup: undefined | (() => void);\n\t\t\tlet deactivated = false;\n\t\t\tctx.onDeactivation(() => {\n\t\t\t\tdeactivated = true;\n\t\t\t\tif (typeof cleanup === \"function\") cleanup();\n\t\t\t});\n\t\t\tconst maybeCleanup = setup(ctx);\n\t\t\tcleanup = typeof maybeCleanup === \"function\" ? maybeCleanup : undefined;\n\t\t\tif (deactivated && typeof cleanup === \"function\") cleanup();\n\t\t},\n\t};\n}\n\nfunction assertNonEmptyString(value: string, label: string): void {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new TypeError(`${label} must be a non-empty string`);\n\t}\n}\n\nfunction cleanupDriverWork(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n): void {\n\tactive.value = false;\n\tconst cancel = cancelSlot.value;\n\tcancelSlot.value = undefined;\n\tif (cancel !== undefined) runDriverCancel(cancel);\n}\n\nfunction installDriverCancel(\n\tactive: { value: boolean },\n\tcancelSlot: { value: DriverCancel | undefined },\n\tcancel: DriverCancel,\n): void {\n\tif (active.value) cancelSlot.value = cancel;\n\telse runDriverCancel(cancel);\n}\n\nfunction runDriverCancel(cancel: DriverCancel): void {\n\ttry {\n\t\tcancel();\n\t} catch {\n\t\t// Driver cleanup is best-effort: it must not suppress graph-visible terminal delivery.\n\t}\n}\n\nfunction driverOneShotSource<T>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (result: DriverResult<T>) => void) => DriverCancel | undefined,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (result: DriverResult<T>) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\tif (result.ok) ctx.down([[\"DATA\", result.value], [\"COMPLETE\"]]);\n\t\t\t\telse ctx.down([[\"ERROR\", errorPayload(result.error)]]);\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction driverStreamSource<T, E extends { readonly kind: string }>(\n\tfactory: string,\n\tmissing: string,\n\tstart: (ctx: Ctx, callback: (event: E) => void) => DriverCancel | undefined,\n\tdataOf: (event: E) => T | undefined,\n\terrorOf: (event: E) => unknown,\n): Operator<never, T> {\n\treturn source<T>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tconst active = { value: true };\n\t\t\tconst cancelSlot: { value: DriverCancel | undefined } = { value: undefined };\n\t\t\tconst callback = (event: E) => {\n\t\t\t\tif (!active.value) return;\n\t\t\t\tif (event.kind === \"event\") {\n\t\t\t\t\tconst value = dataOf(event);\n\t\t\t\t\tif (value !== undefined) ctx.down([[\"DATA\", value]]);\n\t\t\t\t} else if (event.kind === \"error\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(errorOf(event))]]);\n\t\t\t\t} else if (event.kind === \"complete\") {\n\t\t\t\t\tcleanupDriverWork(active, cancelSlot);\n\t\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tlet cancel: DriverCancel | undefined;\n\t\t\ttry {\n\t\t\t\tcancel = start(ctx, callback);\n\t\t\t} catch (e) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cancel === undefined) {\n\t\t\t\tactive.value = false;\n\t\t\t\tctx.down([[\"ERROR\", missing]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tinstallDriverCancel(active, cancelSlot, cancel);\n\t\t\treturn () => cleanupDriverWork(active, cancelSlot);\n\t\t},\n\t\t{ pool: \"async\", pausable: false },\n\t);\n}\n\nfunction isNode(x: unknown): x is Node {\n\treturn (\n\t\tx != null &&\n\t\ttypeof x === \"object\" &&\n\t\t\"cache\" in x &&\n\t\ttypeof (x as Node).subscribe === \"function\"\n\t);\n}\n\nfunction isThenable(x: unknown): x is PromiseLike<unknown> {\n\treturn x != null && typeof (x as PromiseLike<unknown>).then === \"function\";\n}\n\nfunction isAsyncIterable<T>(x: unknown): x is AsyncIterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\"\n\t);\n}\n\nfunction isIterable<T>(x: unknown): x is Iterable<T> {\n\treturn (\n\t\tx !== null &&\n\t\tx !== undefined &&\n\t\ttypeof (x as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\t);\n}\n\n/** Options shared by async/timer sources: an optional AbortSignal → ERROR on abort. */\nexport interface AsyncSourceOpts {\n\tsignal?: AbortSignal;\n}\n\nexport interface TimerSourceOpts extends AsyncSourceOpts {\n\tperiod?: number;\n}\n\n/** Options for {@link fromCron}. */\nexport interface FromCronOptions extends AsyncSourceOpts {\n\t/** Cron matcher polling interval in milliseconds. Default: 60_000. */\n\ttickMs?: number;\n\t/**\n\t * Emitted value shape. `timestamp_ns` is a decimal string so it cannot lose precision as a\n\t * JavaScript number; use `timestamp_ms` when numeric millisecond precision is enough.\n\t */\n\toutput?: \"date\" | \"timestamp_ms\" | \"timestamp_ns\";\n}\n\n/** Minimal five-field cron schedule: minute hour day-of-month month day-of-week. */\nexport interface CronSchedule {\n\treadonly minutes: ReadonlySet<number>;\n\treadonly hours: ReadonlySet<number>;\n\treadonly daysOfMonth: ReadonlySet<number>;\n\treadonly months: ReadonlySet<number>;\n\treadonly daysOfWeek: ReadonlySet<number>;\n}\n\n/** DOM/EventEmitter-style target accepted by {@link fromEvent}. */\nexport interface EventTargetLike {\n\taddEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n\tremoveEventListener(\n\t\ttype: string,\n\t\tlistener: (event: unknown) => void,\n\t\toptions?: EventListenerOptionsLike,\n\t): void;\n}\n\nexport interface EventListenerOptionsLike {\n\tcapture?: boolean;\n\tpassive?: boolean;\n\tonce?: boolean;\n}\n\nexport type FromEventOptions = EventListenerOptionsLike;\n\n/** Host push registration callback accepted by {@link fromPushNotification}. */\nexport type PushUnsubscribe = () => void;\nexport type PushRegister<T> = (deliver: (payload: T) => void) => PushUnsubscribe | undefined;\n\nfunction parseCronField(field: string, min: number, max: number): Set<number> {\n\tif (field.length === 0) throw new Error(\"Invalid cron field: empty\");\n\tconst out = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\tif (part.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tconst stepParts = part.split(\"/\");\n\t\tif (stepParts.length > 2) throw new Error(`Invalid cron step: ${part}`);\n\t\tconst [range, stepText] = stepParts;\n\t\tif (range == null || range.length === 0) throw new Error(`Invalid cron field: ${field}`);\n\t\tif (stepText === \"\") throw new Error(`Invalid cron step: ${part}`);\n\t\tconst step = stepText == null ? 1 : parseCronInt(stepText, `Invalid cron step: ${part}`);\n\t\tif (step < 1) throw new Error(`Invalid cron step: ${part}`);\n\n\t\tlet start: number;\n\t\tlet end: number;\n\t\tif (range === \"*\") {\n\t\t\tstart = min;\n\t\t\tend = max;\n\t\t} else if (range.includes(\"-\")) {\n\t\t\tconst [a, b, extra] = range.split(\"-\");\n\t\t\tif (extra !== undefined || a === \"\" || b === \"\")\n\t\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t\tstart = parseCronInt(a, `Invalid cron field: ${field}`);\n\t\t\tend = parseCronInt(b, `Invalid cron field: ${field}`);\n\t\t} else {\n\t\t\tstart = parseCronInt(range, `Invalid cron field: ${field}`);\n\t\t\tend = start;\n\t\t}\n\n\t\tif (!Number.isInteger(start) || !Number.isInteger(end)) {\n\t\t\tthrow new Error(`Invalid cron field: ${field}`);\n\t\t}\n\t\tif (start < min || end > max) {\n\t\t\tthrow new RangeError(`Cron field out of range: ${field} (${min}-${max})`);\n\t\t}\n\t\tif (start > end) throw new Error(`Invalid cron range: ${start}-${end} in ${field}`);\n\t\tfor (let i = start; i <= end; i += step) out.add(i);\n\t}\n\treturn out;\n}\n\nfunction parseCronInt(text: string, message: string): number {\n\tif (!/^\\d+$/.test(text)) throw new Error(message);\n\tconst value = Number.parseInt(text, 10);\n\tif (!Number.isSafeInteger(value)) throw new Error(message);\n\treturn value;\n}\n\n/** Parse a standard five-field cron expression. */\nexport function parseCron(expr: string): CronSchedule {\n\tconst parts = expr.trim().split(/\\s+/);\n\tif (parts.length !== 5 || parts.some((part) => part.length === 0)) {\n\t\tthrow new Error(`Invalid cron: expected 5 fields, got ${parts.length}`);\n\t}\n\treturn {\n\t\tminutes: parseCronField(parts[0], 0, 59),\n\t\thours: parseCronField(parts[1], 0, 23),\n\t\tdaysOfMonth: parseCronField(parts[2], 1, 31),\n\t\tmonths: parseCronField(parts[3], 1, 12),\n\t\tdaysOfWeek: parseCronField(parts[4], 0, 6),\n\t};\n}\n\n/** Test whether a local Date matches a parsed cron schedule. */\nexport function matchesCron(schedule: CronSchedule, date: Date): boolean {\n\treturn (\n\t\tschedule.minutes.has(date.getMinutes()) &&\n\t\tschedule.hours.has(date.getHours()) &&\n\t\tschedule.daysOfMonth.has(date.getDate()) &&\n\t\tschedule.months.has(date.getMonth() + 1) &&\n\t\tschedule.daysOfWeek.has(date.getDay())\n\t);\n}\n\nfunction cronMinuteKey(date: Date): string {\n\treturn `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${date.getHours()}-${date.getMinutes()}`;\n}\n\nfunction dateToTimestampNs(date: Date): string {\n\treturn (BigInt(date.getTime()) * 1_000_000n).toString();\n}\n\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"date\" },\n): Operator<never, Date>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions & { output: \"timestamp_ms\" },\n): Operator<never, number>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions & { output?: \"timestamp_ns\" },\n): Operator<never, string>;\nexport function fromCron(\n\texpr: string,\n\topts?: FromCronOptions,\n): Operator<never, Date | number | string>;\nexport function fromCron(\n\texpr: string,\n\topts: FromCronOptions = {},\n): Operator<never, Date | number | string> {\n\tconst schedule = parseCron(expr);\n\tconst { tickMs = 60_000, output = \"timestamp_ns\", signal } = opts;\n\tif (!Number.isFinite(tickMs) || tickMs <= 0) {\n\t\tthrow new RangeError(\"fromCron: tickMs must be a positive finite number\");\n\t}\n\treturn source<Date | number | string>(\n\t\t\"fromCron\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet lastFiredKey: string | undefined;\n\t\t\tlet intervalId: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (intervalId !== undefined) clearInterval(intervalId);\n\t\t\t\tintervalId = undefined;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst emitNow = (now: Date) => {\n\t\t\t\tif (output === \"date\") ctx.down([[\"DATA\", now]]);\n\t\t\t\telse if (output === \"timestamp_ms\") ctx.down([[\"DATA\", now.getTime()]]);\n\t\t\t\telse ctx.down([[\"DATA\", dateToTimestampNs(now)]]);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst key = cronMinuteKey(now);\n\t\t\t\tif (key !== lastFiredKey && matchesCron(schedule, now)) {\n\t\t\t\t\tlastFiredKey = key;\n\t\t\t\t\temitNow(now);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn cleanup;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tcheck();\n\t\t\tintervalId = setInterval(check, tickMs);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n}\n\nexport function runProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn runProcessWithOptions({ program, args });\n}\n\nexport function fromProcess(\n\tprogram: string,\n\targs: readonly string[] = [],\n): Operator<never, ProcessResult> {\n\treturn processSource(\"fromProcess\", { program, args });\n}\n\nexport function runProcessWithOptions(command: ProcessCommand): Operator<never, ProcessResult> {\n\treturn processSource(\"runProcess\", command);\n}\n\nfunction processSource(factory: string, command: ProcessCommand): Operator<never, ProcessResult> {\n\tassertNonEmptyString(command.program, `${factory}: program`);\n\treturn driverOneShotSource<ProcessResult>(\n\t\tfactory,\n\t\t`${factory}: missing process driver`,\n\t\t(ctx, callback) => ctx.environment().processDriver()?.run(command, callback),\n\t);\n}\n\nexport function fromHttp(url: string): Operator<never, HttpResponse> {\n\treturn fromHttpWithOptions({ method: \"GET\", url });\n}\n\nexport function fromHttpWithOptions(request: HttpRequest): Operator<never, HttpResponse> {\n\tassertNonEmptyString(request.url, \"fromHttp: url\");\n\tassertNonEmptyString(request.method, \"fromHttp: method\");\n\treturn driverOneShotSource<HttpResponse>(\n\t\t\"fromHttp\",\n\t\t\"fromHttp: missing http driver\",\n\t\t(ctx, callback) => ctx.environment().httpDriver()?.request(request, callback),\n\t);\n}\n\nexport function fromSSE(url: string): Operator<never, SseEvent> {\n\treturn fromSSEWithOptions({ url });\n}\n\nexport function fromSSEWithOptions(request: SseRequest): Operator<never, SseEvent> {\n\tassertNonEmptyString(request.url, \"fromSSE: url\");\n\treturn driverStreamSource<SseEvent, SseDriverEvent>(\n\t\t\"fromSSE\",\n\t\t\"fromSSE: missing sse driver\",\n\t\t(ctx, callback) => ctx.environment().sseDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebSocket(url: string): Operator<never, WebSocketEvent> {\n\treturn fromWebSocketWithOptions({ url });\n}\n\nexport function fromWebSocketWithOptions(\n\trequest: WebSocketRequest,\n): Operator<never, WebSocketEvent> {\n\tassertNonEmptyString(request.url, \"fromWebSocket: url\");\n\treturn driverStreamSource<WebSocketEvent, WebSocketDriverEvent>(\n\t\t\"fromWebSocket\",\n\t\t\"fromWebSocket: missing websocket driver\",\n\t\t(ctx, callback) => ctx.environment().webSocketDriver()?.connect(request, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nexport function fromWebhook(id: string): Operator<never, WebhookEvent> {\n\treturn fromWebhookWithOptions({ id });\n}\n\nexport function fromWebhookWithOptions(\n\tregistration: WebhookRegistration,\n): Operator<never, WebhookEvent> {\n\tassertNonEmptyString(registration.id, \"fromWebhook: id\");\n\treturn driverStreamSource<WebhookEvent, WebhookDriverEvent>(\n\t\t\"fromWebhook\",\n\t\t\"fromWebhook: missing webhook driver\",\n\t\t(ctx, callback) => ctx.environment().webhookDriver()?.register(registration, callback),\n\t\t(event) => (event.kind === \"event\" ? event.event : undefined),\n\t\t(event) => (event.kind === \"error\" ? event.error : undefined),\n\t);\n}\n\nfunction timerSource(factory: string, ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\tconst { period, signal } = opts ?? {};\n\tconst op = source<number>(\n\t\tfactory,\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tlet count = 0;\n\t\t\tlet t: ReturnType<typeof setTimeout> | undefined;\n\t\t\tlet iv: ReturnType<typeof setInterval> | undefined;\n\t\t\tconst cleanup = () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (t !== undefined) clearTimeout(t);\n\t\t\t\tif (iv !== undefined) clearInterval(iv);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tcleanup();\n\t\t\t\tctx.down([[\"ERROR\", errorPayload(signal?.reason)]]);\n\t\t\t};\n\t\t\tconst finish = () => {\n\t\t\t\tif (done) return;\n\t\t\t\tif (period != null) {\n\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\tiv = setInterval(() => {\n\t\t\t\t\t\tif (done) return;\n\t\t\t\t\t\tctx.down([[\"DATA\", count++]]);\n\t\t\t\t\t}, period);\n\t\t\t\t} else {\n\t\t\t\t\t// One-shot: DATA then COMPLETE in one wave (terminal-is-forever).\n\t\t\t\t\tdone = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", count++], [\"COMPLETE\"]]);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tt = setTimeout(finish, ms);\n\t\t\treturn cleanup;\n\t\t},\n\t\t{ pool: \"sync\", pausable: false },\n\t);\n\tif (factory === \"timer\" && period === undefined && signal === undefined) {\n\t\treturn { ...op, restore: { ref: \"timer\", config: { ms: toCheckpointJson(ms, \"timer.ms\") } } };\n\t}\n\treturn op;\n}\n\n/**\n * Timer source: one-shot (first tick then COMPLETE) or periodic (`{period}` → 0, 1, 2, …).\n * sync pool + pausable:false (a timer keeps producing through PAUSE, R-pause-modes). Emits the\n * tick counter from 0; deactivation clears the timers.\n */\nexport function timer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"timer\", ms, opts);\n}\n\n/** Frozen pure-ts name for {@link timer}; preserves the real factory name in describe(). */\nexport function fromTimer(ms: number, opts?: TimerSourceOpts): Operator<never, number> {\n\treturn timerSource(\"fromTimer\", ms, opts);\n}\n\n/** interval: periodic ticks (0, 1, 2, …), first at `ms`, then every `ms` (RxJS semantics). */\nexport function interval(ms: number): Operator<never, number> {\n\treturn timerSource(\"interval\", ms, { period: ms });\n}\n\n/**\n * Lift a Promise (or thenable) to a single-value stream: one DATA then COMPLETE, or ERROR on\n * rejection. async pool (default pausable → a paused source buffers its late emit). Optional\n * `signal` aborts to ERROR.\n */\nexport function fromPromise<T>(\n\tp: Promise<T> | PromiseLike<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst signal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromPromise\",\n\t\t(ctx) => {\n\t\t\tlet settled = false;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\t// onAbort only runs from a `signal` listener / the `signal.aborted` guard → signal is defined.\n\t\t\t\tctx.down([[\"ERROR\", errorPayload((signal as AbortSignal).reason)]]);\n\t\t\t};\n\t\t\tif (signal?.aborted) {\n\t\t\t\tonAbort();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tvoid Promise.resolve(p).then(\n\t\t\t\t(v) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"DATA\", v], [\"COMPLETE\"]]);\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn () => {\n\t\t\t\tsettled = true;\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * Read an async iterable: each value → DATA; COMPLETE when done; ERROR on failure. async pool.\n * Optional `signal` aborts the pump.\n */\nexport function fromAsyncIter<T>(\n\titerable: AsyncIterable<T>,\n\topts?: AsyncSourceOpts,\n): Operator<never, T> {\n\tconst outerSignal = opts?.signal;\n\treturn source<T>(\n\t\t\"fromAsyncIter\",\n\t\t(ctx) => {\n\t\t\tconst ac = new AbortController();\n\t\t\tconst onOuterAbort = () => ac.abort(outerSignal?.reason);\n\t\t\touterSignal?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\t\t\tlet done = false;\n\t\t\tconst pump = async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor await (const v of iterable) {\n\t\t\t\t\t\tif (ac.signal.aborted) break;\n\t\t\t\t\t\tctx.down([[\"DATA\", v]]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"COMPLETE\"]]);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (!ac.signal.aborted) ctx.down([[\"ERROR\", errorPayload(e)]]);\n\t\t\t\t} finally {\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\tvoid pump();\n\t\t\treturn () => {\n\t\t\t\tif (!done) ac.abort();\n\t\t\t\touterSignal?.removeEventListener(\"abort\", onOuterAbort);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"async\" },\n\t);\n}\n\n/**\n * of: synchronous values — each argument as DATA, then COMPLETE. `of()` is the EMPTY source.\n */\nexport function of<T = never>(...values: T[]): Operator<never, T> {\n\treturn source<T>(\n\t\t\"of\",\n\t\t(ctx) => {\n\t\t\tfor (const value of values) ctx.down([[\"DATA\", value]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** fromIter: a sync iterable — each value → DATA (in order), then COMPLETE, on activation. */\nexport function fromIter<T>(iterable: Iterable<T>): Operator<never, T> {\n\treturn source<T>(\n\t\t\"fromIter\",\n\t\t(ctx) => {\n\t\t\tfor (const v of iterable) ctx.down([[\"DATA\", v]]);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** EMPTY analogue: complete immediately with no DATA. */\nexport function empty<T = never>(): Operator<never, T> {\n\treturn source<T>(\n\t\t\"empty\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/** NEVER analogue: activate and remain silent until deactivation. */\nexport function never<T = never>(): Operator<never, T> {\n\treturn source<T>(\"never\", () => undefined, { pool: \"sync\" });\n}\n\n/** Error source: terminate with ERROR on activation, coercing invalid host-language payloads. */\nexport function throwError(err: unknown): Operator<never, never> {\n\treturn source<never>(\n\t\t\"throwError\",\n\t\t(ctx) => {\n\t\t\tctx.down([[\"ERROR\", errorPayload(err)]]);\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a DOM-style event target. Each event becomes DATA; deactivation removes the listener.\n * External callbacks are source boundaries (D43), so no polling or operator-level async leaks in.\n */\nexport function fromEvent<T = unknown>(\n\ttarget: EventTargetLike,\n\ttype: string,\n\topts: FromEventOptions = {},\n): Operator<never, T> {\n\tif (target == null || typeof target.addEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement addEventListener\");\n\t}\n\tif (typeof target.removeEventListener !== \"function\") {\n\t\tthrow new TypeError(\"fromEvent: target must implement removeEventListener\");\n\t}\n\tif (typeof type !== \"string\" || type.length === 0) {\n\t\tthrow new TypeError(\"fromEvent: event type must be a non-empty string\");\n\t}\n\treturn source<T>(\n\t\t\"fromEvent\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst handler = (event: unknown) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", event as T]]);\n\t\t\t};\n\t\t\ttarget.addEventListener(type, handler, opts);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\ttarget.removeEventListener(type, handler, opts);\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Wrap a host push transport. The host owns network/native setup; this factory owns reactive\n * delivery and teardown only, preserving async-at-source-boundary discipline.\n */\nexport function fromPushNotification<T = unknown>(register: PushRegister<T>): Operator<never, T> {\n\tif (typeof register !== \"function\") {\n\t\tthrow new TypeError(\"fromPushNotification: register must be a function\");\n\t}\n\treturn source<T>(\n\t\t\"fromPushNotification\",\n\t\t(ctx) => {\n\t\t\tlet done = false;\n\t\t\tconst deliver = (payload: T) => {\n\t\t\t\tif (!done) ctx.down([[\"DATA\", payload]]);\n\t\t\t};\n\t\t\tconst unsubscribe = register(deliver);\n\t\t\treturn () => {\n\t\t\t\tdone = true;\n\t\t\t\tif (typeof unsubscribe === \"function\") unsubscribe();\n\t\t\t};\n\t\t},\n\t\t{ pool: \"sync\" },\n\t);\n}\n\n/**\n * Coerce a {@link NodeInput}`<T>` to a `Node<T>` (D43 — coercion prerequisite for the CSP-2.7\n * higher-order operators). An existing Node passes through; a thenable → {@link fromPromise};\n * an async iterable → {@link fromAsyncIter}; with `{iter:true}` a sync iterable →\n * {@link fromIter}; everything else → {@link of}. Coerced nodes are bare (use\n * `opts.dispatcher` to bind one, default = process-global D26).\n */\nexport function fromAny<T>(\n\tinput: NodeInput<T>,\n\topts: NodeOptions<T> & { iter?: boolean } = {},\n): Node<T> {\n\tif (isNode(input)) return input as Node<T>;\n\tconst { iter, ...nodeOpts } = opts;\n\tif (isThenable(input)) {\n\t\treturn initNode(fromPromise(input as PromiseLike<T>), [], nodeOpts);\n\t}\n\tif (input !== null && input !== undefined) {\n\t\tconst candidate = input as {\n\t\t\t[Symbol.asyncIterator]?: unknown;\n\t\t\t[Symbol.iterator]?: unknown;\n\t\t};\n\t\tif (typeof candidate[Symbol.asyncIterator] === \"function\") {\n\t\t\treturn initNode(fromAsyncIter(input as AsyncIterable<T>), [], nodeOpts);\n\t\t}\n\t\tif (iter === true && typeof candidate[Symbol.iterator] === \"function\") {\n\t\t\treturn initNode(fromIter(input as Iterable<T>), [], nodeOpts);\n\t\t}\n\t}\n\treturn initNode(of(input as T), [], nodeOpts);\n}\n\n/**\n * Resolve the first DATA from a Node as a Promise. This is a host-boundary escape hatch, not a\n * graph operator; do not call it from reactive node bodies. ERROR rejects, and COMPLETE before DATA\n * rejects because no value exists.\n */\nexport function firstValueFrom<T>(source: Node<T>): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet shouldUnsub = false;\n\t\tlet unsub: (() => void) | undefined;\n\t\tconst finish = (f: () => void): void => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tf();\n\t\t\tif (unsub) {\n\t\t\t\tunsub();\n\t\t\t\tunsub = undefined;\n\t\t\t} else {\n\t\t\t\tshouldUnsub = true;\n\t\t\t}\n\t\t};\n\t\tunsub = source.subscribe((msg) => {\n\t\t\tif (msg[0] === \"DATA\") {\n\t\t\t\tfinish(() => resolve(msg[1] as T));\n\t\t\t} else if (msg[0] === \"ERROR\") {\n\t\t\t\tfinish(() => reject(msg[1]));\n\t\t\t} else if (msg[0] === \"COMPLETE\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: completed without DATA\")));\n\t\t\t} else if (msg[0] === \"TEARDOWN\") {\n\t\t\t\tfinish(() => reject(new Error(\"firstValueFrom: torn down without DATA\")));\n\t\t\t}\n\t\t});\n\t\tif (shouldUnsub) {\n\t\t\tunsub?.();\n\t\t\tunsub = undefined;\n\t\t}\n\t});\n}\n\nfunction singleFromAnyValue<T>(value: T): T {\n\tif (value === undefined) {\n\t\tthrow new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\");\n\t}\n\treturn value;\n}\n\nasync function firstFromAsyncIterable<T>(input: AsyncIterable<T>): Promise<T> {\n\tconst iter = input[Symbol.asyncIterator]();\n\tconst { value, done } = await iter.next();\n\tif (done) {\n\t\tawait iter.return?.();\n\t\tthrow new Error(\"singleFromAny: factory returned empty async iterable\");\n\t}\n\ttry {\n\t\tawait iter.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn value as T;\n}\n\nfunction firstFromIterable<T>(input: Iterable<T>): Promise<T> {\n\tconst iter = input[Symbol.iterator]();\n\tconst { value, done } = iter.next();\n\tif (done) {\n\t\titer.return?.();\n\t\treturn Promise.reject(new Error(\"singleFromAny: factory returned empty iterable\"));\n\t}\n\ttry {\n\t\titer.return?.();\n\t} catch {\n\t\t// The first value is the bridge result; close failures after that are cleanup-only.\n\t}\n\treturn Promise.resolve(value as T);\n}\n\nfunction nodeInputToPromise<T>(input: NodeInput<T>, opts: { iter?: boolean }): Promise<T> {\n\tif (isThenable(input)) return Promise.resolve(input as PromiseLike<T>).then(singleFromAnyValue);\n\tif (isNode(input)) return firstValueFrom(input as Node<T>).then(singleFromAnyValue);\n\tif (isAsyncIterable<T>(input)) return firstFromAsyncIterable(input).then(singleFromAnyValue);\n\tif (opts.iter === true && isIterable<T>(input)) {\n\t\treturn firstFromIterable(input).then(singleFromAnyValue);\n\t}\n\tif (input === undefined) {\n\t\treturn Promise.reject(new TypeError(\"singleFromAny: undefined is the substrate SENTINEL\"));\n\t}\n\treturn Promise.resolve(singleFromAnyValue(input as T));\n}\n\n/**\n * Keyed singleflight over {@link NodeInput}. Concurrent calls with the same key share one Promise;\n * once that input resolves/rejects, the in-flight entry is cleared and a later call re-runs the\n * factory. Host-boundary helper only; it does not create graph topology.\n */\nexport function singleFromAny<K, T>(\n\tfactory: (key: K) => NodeInput<T>,\n\topts: SingleFromAnyOptions<K> = {},\n): (key: K) => Promise<T> {\n\tconst keyOf = opts.keyOf ?? ((key: K): unknown => key);\n\tconst inFlight = new Map<unknown, Promise<T>>();\n\n\treturn (key: K): Promise<T> => {\n\t\tconst dedupeKey = keyOf(key);\n\t\tconst existing = inFlight.get(dedupeKey);\n\t\tif (existing) return existing;\n\n\t\tlet resolvePending!: (value: T) => void;\n\t\tlet rejectPending!: (reason: unknown) => void;\n\t\tlet tracked!: Promise<T>;\n\t\tconst cleanup = (): void => {\n\t\t\tif (inFlight.get(dedupeKey) === tracked) inFlight.delete(dedupeKey);\n\t\t};\n\t\tconst pending = new Promise<T>((resolve, reject) => {\n\t\t\tresolvePending = resolve;\n\t\t\trejectPending = reject;\n\t\t});\n\t\ttracked = pending.then(\n\t\t\t(value) => {\n\t\t\t\tcleanup();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tcleanup();\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t\tinFlight.set(dedupeKey, tracked);\n\t\ttry {\n\t\t\tnodeInputToPromise(factory(key), opts).then(resolvePending, rejectPending);\n\t\t} catch (e) {\n\t\t\trejectPending(e);\n\t\t}\n\t\treturn tracked;\n\t};\n}\n","/**\n * Wall-clock time operators (CSP-2.7 / D52 / B23). Authored as COMPOSITIONS over the already-active\n * higher-order *Map machinery (D47) + the `timer` source — NO raw `setTimeout` in any operator body\n * (R-no-raw-async / check-no-raw-async; `setTimeout` stays confined to `sources.ts`'s `timer`). The\n * timer source's `onDeactivation` clearTimeout IS the reset/cancel: switchMap's unsubscribeDep on a new\n * source value tears the in-flight timer down (the declarative equivalent of the frozen reference's\n * imperative clearTimeout-then-setTimeout). Per-language (D6/D24), never in parity.\n *\n * Shipped this cut (clean *Map+timer):\n * - delay = mergeMap(v → timer(ms)→v) (every value delayed ms, ALL kept, order preserved)\n * - debounce(Time) = switchMap(v → timer(ms)→v) (cancel-and-restart; emit the latest after quiet ms)\n * - throttle(Time) = exhaustMap(v → [v now, alive ms]) (leading edge: emit v, ignore for ms)\n *\n * Behavior on source COMPLETE (per-operator, NOT a uniform DROP): debounce/debounceTime EMIT their\n * pending trailing value — switchMap does not cancel the in-flight inner on source COMPLETE (only a\n * superseding source value cancels it via unsubscribeDep→onDeactivation→clearTimeout), so the timer still\n * fires at `ms`, emits the debounced value, and only THEN does the operator COMPLETE (RxJS\n * debounceTime parity). delay emits every still-pending delayed value then COMPLETEs (mergeMap keeps\n * all inners). throttle/throttleTime have NO trailing value (leading-edge only, RxJS default\n * trailing:false) — an open window inner is dropped when the operator completes.\n *\n * B41 tail (landed 2026-05-31, the two shapes reflect WHEN the clock arms):\n * - audit / auditTime — VALUE-TRIGGERED trailing edge: a source value opens a duration window\n * (`audit(durationSelector)` = the general/notifier form, mirroring the *Map\n * `Project` idiom + D46; `auditTime(ms)` = `audit(() => timer(ms))`), emits the\n * window's LATEST value at the window's close. Self-wires the notifier via\n * ctx.rewireNext — a normal `g.initNode(audit(sel), [source])` operator.\n * - timeout / bufferTime — SUBSCRIBE-ARMED (RxJS-cold): the clock must run from activation, before\n * any source value, so the timer/interval is a CONSTRUCTION-time dep (a depless\n * source arms lazily on subscribe per node `_activate`). A dep-bearing operator\n * body never runs at activation (only depless nodes do, node.ts), so these ship\n * as graph composition HELPERS `timeout(source, ms)` / `bufferTime(source, ms)`\n * returning a Node — NOT `g.initNode(op, [deps])` operators. timeout resets its\n * idle timer per source value via ctx.rewireNext (ERROR on the gap); bufferTime\n * is buffer-over-interval with terminal cleanup via ctx.rewireNext.\n *\n * NOT ported (D58): window/windowCount/windowTime — the Node<Node<T>> higher-order forms are a D45\n * describe island; the array forms (buffer/bufferCount/bufferTime) are the graph-first equivalent.\n *\n * Inspection caveat (timeout/bufferTime): the helper returns a BARE node (free initNode) self-carrying\n * its factory for describe auto-discovery (D51), but it is NOT in a graph's _entries — so g.describe()\n * lists it only when it is a live dep of a registered node (a first-cut limit, like the *Map inners).\n */\n\nimport {\n\ttype Ctx,\n\tdepBatch,\n\tdepTerminal,\n\tisTerminalComplete,\n\tisTerminalError,\n\ttype NodeFn,\n\tterminalErrorValue,\n} from \"../ctx/types.js\";\nimport type { Node } from \"../node/node.js\";\nimport { errorPayload } from \"../protocol/messages.js\";\nimport { exhaustMap, mergeMap, switchMap } from \"./higher-order.js\";\nimport { filter, initNode, map, merge, type Operator } from \"./operators.js\";\nimport { fromAny, interval, type NodeInput, of, timer } from \"./sources.js\";\n\n/** A bare inner that emits `v` once after `ms`, then COMPLETEs (timer(ms)→map(v); auto-completes). */\nfunction delayedValue<S>(v: S, ms: number): Node<S> {\n\treturn initNode(\n\t\tmap(() => v),\n\t\t[initNode(timer(ms), [])],\n\t);\n}\n\n/**\n * An inner that emits `v` IMMEDIATELY (on activation) and stays alive for `ms` (then COMPLETEs),\n * emitting nothing more — the leading-edge throttle window. `merge(of(v), silentTimer)`: `of(v)`\n * emits v + COMPLETE at t=0; `filter(()=>false)` over `timer(ms)` emits no DATA and COMPLETEs at\n * t=ms; merge forwards v at t=0 and COMPLETEs (all deps complete) at t=ms.\n */\nfunction throttleWindow<S>(v: S, ms: number): Node<S> {\n\tconst silentTimer = initNode(\n\t\tfilter<number>(() => false),\n\t\t[initNode(timer(ms), [])],\n\t) as Node<S>;\n\treturn initNode(merge<S>(), [initNode(of(v), []), silentTimer]);\n}\n\n/**\n * delay: shift every value by `ms`, preserving all values + order. `mergeMap` keeps every inner\n * timer live (equal `ms`, so they fire in arrival order).\n */\nexport function delay<S>(ms: number): Operator<S, S> {\n\treturn { ...mergeMap<S, S>((v) => delayedValue(v, ms)), factory: \"delay\" };\n}\n\n/**\n * debounce (alias `debounceTime`): emit the latest value only after `ms` of quiet. `switchMap`\n * cancels the prior timer (its onDeactivation clearTimeout) on each new source value and restarts —\n * the declarative debounce.\n *\n * RxJS-7 divergence (reference rxjs@7.8, B44): RxJS `debounceTime` FLUSHES the pending value\n * IMMEDIATELY when the source COMPLETEs (its `_complete` calls `debouncedNext()` before\n * `complete()`). This composition instead emits the pending value when the in-flight `timer(ms)`\n * fires — i.e. at `(last-value-time + ms)` — so if the source completes mid-window the trailing\n * value arrives up to `ms` later than RxJS. Inherent to the `*Map`+`timer` form (the composition\n * cannot flush early without detecting COMPLETE inside the switchMap inner); accepted, not a bug.\n */\nexport function debounce<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounce\" };\n}\n\n/** debounceTime: RxJS-named alias of {@link debounce}. */\nexport function debounceTime<S>(ms: number): Operator<S, S> {\n\treturn { ...switchMap<S, S>((v) => delayedValue(v, ms)), factory: \"debounceTime\" };\n}\n\n/**\n * throttle (alias `throttleTime`): leading-edge — emit a value immediately, then ignore the source\n * for `ms`. `exhaustMap` drops new source values while the current window inner is alive; the\n * window emits v at its leading edge and stays alive `ms`.\n *\n * Matches the RxJS-7 `throttleTime` DEFAULT (leading:true, trailing:false). The leading/trailing\n * OPTIONS RxJS exposes are NOT provided (a capability gap, not a behavior divergence; B44) — add a\n * trailing-window form if a consumer needs it.\n */\nexport function throttle<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttle\" };\n}\n\n/** throttleTime: RxJS-named alias of {@link throttle}. */\nexport function throttleTime<S>(ms: number): Operator<S, S> {\n\treturn { ...exhaustMap<S, S>((v) => throttleWindow(v, ms)), factory: \"throttleTime\" };\n}\n\n// ── B41 tail: value-triggered (audit) + subscribe-armed (timeout/bufferTime) ──\n\n/** Per-node bookkeeping for {@link audit}: the open window's notifier + the latest value seen. */\ninterface AuditState<S> {\n\twindowOpen: boolean;\n\tlatest: { v: S } | undefined;\n\tnotifier: Node<unknown> | null;\n}\n\n/**\n * audit: VALUE-TRIGGERED trailing throttle. A source value (when no window is open) opens a duration\n * window via `durationSelector(value)` → a notifier `NodeInput` wired as dep 1 with `ctx.rewireNext`\n * (D47 — the *Map self-rewire idiom, NOT an internal subscribe, D45); during the window new source\n * values only UPDATE the tracked latest (no emit); when the notifier fires (its first DATA / COMPLETE)\n * the window closes and the LATEST value is emitted. This is throttle's trailing-edge twin\n * (throttle emits the window's FIRST value at the leading edge; audit emits the LAST at the close).\n *\n * `durationSelector` is the general/notifier form (mirrors the *Map `Project` idiom + D46); the source\n * is dep 0, the live notifier (if any) is dep 1. On source COMPLETE the pending latest is FLUSHED then\n * COMPLETE (RxJS-7 audit flush-on-complete, B44). A source/notifier ERROR is read as a real terminal\n * input so the live notifier can be removed before ERROR. Self-catching (D30); re-supplies its body on\n * every rewire.\n */\nexport function audit<S>(durationSelector: (v: S) => NodeInput<unknown>): Operator<S, S> {\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: AuditState<S> = ctx.state.get<AuditState<S>>() ?? {\n\t\t\t\twindowOpen: false,\n\t\t\t\tlatest: undefined,\n\t\t\t\tnotifier: null,\n\t\t\t};\n\t\t\tconst sourceBatch = depBatch(ctx, 0);\n\t\t\tconst notifierBatch = depBatch(ctx, 1); // live duration notifier while a window is open\n\t\t\tconst sourceTerminal = depTerminal(ctx, 0);\n\t\t\tconst notifierTerminal = depTerminal(ctx, 1);\n\n\t\t\t// every source value updates the window's latest (the value emitted at the window's close).\n\t\t\tconst sb = sourceBatch as readonly S[] | null;\n\t\t\tif (sb) for (const v of sb) st.latest = { v };\n\n\t\t\t// the window closes when its duration notifier fires (DATA or COMPLETE) → emit the latest.\n\t\t\tconst notifierFired =\n\t\t\t\tst.windowOpen &&\n\t\t\t\t((notifierBatch != null && notifierBatch.length > 0) ||\n\t\t\t\t\tisTerminalComplete(notifierTerminal));\n\t\t\tif (notifierFired) {\n\t\t\t\tif (st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tconst old = st.notifier;\n\t\t\t\tst.windowOpen = false;\n\t\t\t\tst.notifier = null;\n\t\t\t\tst.latest = undefined;\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body);\n\t\t\t}\n\n\t\t\t// source/notifier ERROR → forward ERROR, but first remove the helper-owned notifier.\n\t\t\tconst sourceError = isTerminalError(sourceTerminal);\n\t\t\tconst notifierError = isTerminalError(notifierTerminal);\n\t\t\tif (sourceError || notifierError) {\n\t\t\t\tconst err = terminalErrorValue(sourceError ? sourceTerminal : notifierTerminal);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"ERROR\", err]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// source COMPLETE → flush the pending latest (B44 audit flush-on-complete) then COMPLETE.\n\t\t\tif (isTerminalComplete(sourceTerminal)) {\n\t\t\t\tif (st.windowOpen && st.latest !== undefined) ctx.down([[\"DATA\", st.latest.v]]);\n\t\t\t\tif (st.notifier) ctx.rewireNext.unsubscribeDep(st.notifier, body);\n\t\t\t\tctx.state.set({ windowOpen: false, latest: undefined, notifier: null });\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// a fresh source value with no open window → open one (value-triggered, trailing edge).\n\t\t\tif (!st.windowOpen && sb != null && sb.length > 0 && st.latest !== undefined) {\n\t\t\t\tconst n = fromAny<unknown>(durationSelector(st.latest.v), { iter: true });\n\t\t\t\tst.windowOpen = true;\n\t\t\t\tst.notifier = n;\n\t\t\t\tctx.rewireNext.subscribeDep(n, body); // (a same-wave close+reopen issues remove-before-add)\n\t\t\t}\n\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"audit threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn {\n\t\tfactory: \"audit\",\n\t\tbody,\n\t\topts: {\n\t\t\tpartial: true,\n\t\t\tcompleteWhenDepsComplete: false,\n\t\t\terrorWhenDepsError: false,\n\t\t\tterminalAsRealInput: true,\n\t\t},\n\t};\n}\n\n/** auditTime: the `ms`-specialization of {@link audit} — the window is a `timer(ms)`. */\nexport function auditTime<S>(ms: number): Operator<S, S> {\n\treturn { ...audit<S>(() => initNode(timer(ms), [])), factory: \"auditTime\" };\n}\n\n/** Per-node bookkeeping for {@link timeout}: the live idle timer (reset on each source value). */\ninterface TimeoutState {\n\ttimer: Node<unknown> | null;\n}\n\n/**\n * timeout: idle watchdog — forward every source value, but ERROR if more than `ms` elapses with no\n * value (RxJS `timeout(ms)`, `first === each === ms`). SUBSCRIBE-ARMED: the first `timer(ms)` is a\n * CONSTRUCTION-time dep, so it arms when `timeout`'s node is subscribed/activated (a depless source\n * runs lazily on `_activate`) — i.e. a source that never emits its FIRST value within `ms` still\n * errors. A dep-bearing operator body never runs at activation (only depless nodes do, node.ts), which\n * is why this is a HELPER returning a Node, not a `g.initNode(op, [source])` operator.\n *\n * Each source value forwards as-is and RESETS the idle timer (unsubscribeDep the current `timer(ms)`,\n * subscribeDep a fresh one — its `onDeactivation` clearTimeout cancels the prior countdown). The timer\n * firing (its DATA/COMPLETE) is the timeout → `[[ERROR]]`. Source COMPLETE forwards COMPLETE (no\n * error) and removes the idle timer during the terminal wave (D62 terminal-drains-queued-rewire);\n * a source ERROR forwards likewise. The idle timer is also torn down when the consumer unsubscribes\n * (timeout deactivates → dep unsub → timer onDeactivation). Self-catching (D30).\n */\nexport function timeout<S>(source: Node<S>, ms: number): Node<S> {\n\tconst makeTimer = (): Node<unknown> => initNode(timer(ms), []);\n\tconst initial = makeTimer();\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\ttry {\n\t\t\tconst st: TimeoutState = ctx.state.get<TimeoutState>() ?? { timer: initial };\n\t\t\tconst srcBatch = depBatch(ctx, 0);\n\t\t\tconst srcTerminal = depTerminal(ctx, 0);\n\n\t\t\t// a source value forwards as-is and resets the idle window.\n\t\t\tconst sb = srcBatch as readonly S[] | null;\n\t\t\tif (sb != null && sb.length > 0) {\n\t\t\t\tfor (const v of sb) ctx.down([[\"DATA\", v]]);\n\t\t\t\tconst old = st.timer;\n\t\t\t\tconst next = makeTimer();\n\t\t\t\tst.timer = next;\n\t\t\t\tctx.state.set(st);\n\t\t\t\tif (old) ctx.rewireNext.unsubscribeDep(old, body); // remove-before-add (alignment)\n\t\t\t\tctx.rewireNext.subscribeDep(next, body);\n\t\t\t\treturn; // a value-bearing wave is never also a timeout-fire wave\n\t\t\t}\n\n\t\t\t// source COMPLETE → forward COMPLETE (no timeout fires).\n\t\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// source ERROR (absorbed via errorWhenDepsError:false) → forward it.\n\t\t\tif (isTerminalError(srcTerminal)) {\n\t\t\t\tif (st.timer) ctx.rewireNext.unsubscribeDep(st.timer, body);\n\t\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise this wave is the idle timer firing → timeout ERROR.\n\t\t\tconst timerBatch = depBatch(ctx, 1);\n\t\t\tif (\n\t\t\t\t(timerBatch != null && timerBatch.length > 0) ||\n\t\t\t\tisTerminalComplete(depTerminal(ctx, 1))\n\t\t\t) {\n\t\t\t\tctx.down([[\"ERROR\", new Error(`timeout: no value within ${ms}ms`)]]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tctx.state.set(st);\n\t\t} catch (e) {\n\t\t\tctx.down([[\"ERROR\", errorPayload(e, \"timeout threw without a valid error payload\")]]);\n\t\t}\n\t};\n\treturn initNode<S, S>(\n\t\t{\n\t\t\tfactory: \"timeout\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, initial],\n\t);\n}\n\n/**\n * bufferTime: buffer source values and flush them as an array every `ms` (RxJS `bufferTime(ms)`).\n * SUBSCRIBE-ARMED: the `interval(ms)` notifier is a CONSTRUCTION-time dep (arms on subscribe), so an\n * empty window flushes `[]` even before the first source value — matching the landed {@link buffer}\n * (which flushes on every notifier signal). On source COMPLETE the remainder flushes then COMPLETE\n * (B44), and D62 lets the terminal wave still drain `unsubscribeDep(interval)` so the helper-owned\n * interval source deactivates instead of ticking forever.\n */\nexport function bufferTime<S>(source: Node<S>, ms: number): Node<S[]> {\n\tconst iv: Node<unknown> = initNode(interval(ms), []);\n\tconst body: NodeFn = (ctx: Ctx) => {\n\t\tconst srcBatch = depBatch(ctx, 0);\n\t\tconst tickBatch = depBatch(ctx, 1);\n\t\tconst srcTerminal = depTerminal(ctx, 0);\n\t\tconst buf = ctx.state.get<S[]>() ?? [];\n\t\tif (srcBatch) for (const v of srcBatch) buf.push(v as S);\n\t\tif (isTerminalComplete(srcTerminal)) {\n\t\t\tif (buf.length > 0) ctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"COMPLETE\"]]);\n\t\t\treturn;\n\t\t}\n\t\tif (isTerminalError(srcTerminal)) {\n\t\t\tctx.state.set([]);\n\t\t\tctx.rewireNext.unsubscribeDep(iv, body);\n\t\t\tctx.down([[\"ERROR\", terminalErrorValue(srcTerminal)]]);\n\t\t\treturn;\n\t\t}\n\t\tif (tickBatch && tickBatch.length > 0) {\n\t\t\tctx.down([[\"DATA\", [...buf]]]);\n\t\t\tctx.state.set([]);\n\t\t\treturn;\n\t\t}\n\t\tctx.state.set(buf);\n\t};\n\treturn initNode<unknown, S[]>(\n\t\t{\n\t\t\tfactory: \"bufferTime\",\n\t\t\tbody,\n\t\t\topts: {\n\t\t\t\tpartial: true,\n\t\t\t\tcompleteWhenDepsComplete: false,\n\t\t\t\terrorWhenDepsError: false,\n\t\t\t\tterminalAsRealInput: true,\n\t\t\t},\n\t\t},\n\t\t[source as Node<unknown>, iv],\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoCO,IAAM,WAAW;AAGjB,SAAS,sBAAsB,GAAqB;AAC1D,SAAO,MAAM,YAAY,OAAO,MAAM;AACvC;AAGO,SAAS,aAAa,QAAiB,WAAW,iCAA0C;AAClG,SAAO,sBAAsB,MAAM,IAAI,IAAI,MAAM,QAAQ,IAAI;AAC9D;AAEO,IAAM,aAAa;AACnB,IAAM,eAAe;AACrB,IAAM,oBAAoB;AAC1B,IAAM,aAAa;AACnB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAM7B,IAAM,OAAoC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AAAA,EACV,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