@orangecharts/wrun-chart-host 0.9.0 → 0.11.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 (252) hide show
  1. package/README.md +2 -0
  2. package/dist/constants/feature-flags.constants.d.ts +15 -1
  3. package/dist/constants/feature-flags.constants.js +130 -24
  4. package/dist/constants/governed-exchanges.constants.d.ts +12 -0
  5. package/dist/constants/governed-exchanges.constants.js +16 -0
  6. package/dist/constants/opra-compliance.constants.d.ts +3 -2
  7. package/dist/constants/opra-compliance.constants.js +3 -2
  8. package/dist/constants/option-venues.constants.d.ts +2 -2
  9. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +26 -0
  10. package/dist/constants/scriptEditor/builtin-script-snippets.js +6 -0
  11. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.d.ts +15 -0
  12. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.js +17 -0
  13. package/dist/constants/venue-presets.constants.d.ts +20 -20
  14. package/dist/constants/venue-presets.constants.js +24 -26
  15. package/dist/host-env.d.ts +21 -5
  16. package/dist/host-env.js +6 -0
  17. package/dist/host-ports.types.d.ts +102 -19
  18. package/dist/index.d.ts +18 -0
  19. package/dist/index.js +18 -0
  20. package/dist/interfaces/cancel-reason.interface.d.ts +1 -1
  21. package/dist/interfaces/cme-realtime.interface.d.ts +16 -9
  22. package/dist/interfaces/cme-realtime.interface.js +6 -3
  23. package/dist/interfaces/kscript-diagnostics.interface.d.ts +12 -0
  24. package/dist/interfaces/opra-realtime.interface.d.ts +1 -5
  25. package/dist/interfaces/prediction-market.interface.d.ts +7 -0
  26. package/dist/interfaces/replay.interface.d.ts +8 -0
  27. package/dist/interfaces/stocks-realtime.interface.d.ts +57 -0
  28. package/dist/interfaces/stocks-realtime.interface.js +32 -0
  29. package/dist/interfaces/wrun-runtime.interface.d.ts +18 -2
  30. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +62 -94
  31. package/dist/kscript-data/controls/live-trades-merge.util.js +106 -171
  32. package/dist/market-data/billing.interface.d.ts +174 -36
  33. package/dist/market-data/billing.interface.js +58 -8
  34. package/dist/market-data/venue.d.ts +152 -7
  35. package/dist/market-data/venues/cme.contract.copy.json +66 -0
  36. package/dist/market-data/venues/cme.d.ts +126 -0
  37. package/dist/market-data/venues/cme.js +133 -0
  38. package/dist/market-data/venues/index.d.ts +294 -7
  39. package/dist/market-data/venues/index.js +49 -6
  40. package/dist/market-data/venues/opra.contract.copy.json +3 -2
  41. package/dist/market-data/venues/opra.d.ts +2 -2
  42. package/dist/market-data/venues/opra.js +5 -2
  43. package/dist/market-data/venues/stocks.contract.copy.json +64 -0
  44. package/dist/market-data/venues/stocks.d.ts +130 -0
  45. package/dist/market-data/venues/stocks.js +117 -0
  46. package/dist/settings-templates/footprint-rows.js +35 -2
  47. package/dist/settings-templates/form-rows.d.ts +2 -1
  48. package/dist/settings-templates/index.js +7 -3
  49. package/dist/settings-templates/indicator-fields.d.ts +5 -4
  50. package/dist/settings-templates/indicator-fields.js +79 -10
  51. package/dist/settings-templates/tool-rules.d.ts +32 -15
  52. package/dist/settings-templates/tool-rules.js +33 -11
  53. package/dist/settings-templates/tool-tables.generated.js +95 -31
  54. package/dist/utility/chart/book-live-bucket.util.d.ts +15 -0
  55. package/dist/utility/chart/book-live-bucket.util.js +47 -0
  56. package/dist/utility/chart/cme-cache-context.util.d.ts +5 -3
  57. package/dist/utility/chart/cme-cache-context.util.js +10 -6
  58. package/dist/utility/chart/cme-realtime.util.js +10 -0
  59. package/dist/utility/chart/cme-user-scripts-gate.util.d.ts +83 -0
  60. package/dist/utility/chart/cme-user-scripts-gate.util.js +142 -0
  61. package/dist/utility/chart/effective-chart-session.util.d.ts +14 -0
  62. package/dist/utility/chart/effective-chart-session.util.js +39 -0
  63. package/dist/utility/chart/host-bar-placement.util.d.ts +28 -0
  64. package/dist/utility/chart/host-bar-placement.util.js +170 -30
  65. package/dist/utility/chart/index-host-tier.util.d.ts +3 -1
  66. package/dist/utility/chart/index-host-tier.util.js +7 -2
  67. package/dist/utility/chart/index-mode-admission.util.js +30 -3
  68. package/dist/utility/chart/kscript-apply-fingerprint.util.js +1 -1
  69. package/dist/utility/chart/kscript-drawing-safe-area.util.d.ts +35 -11
  70. package/dist/utility/chart/kscript-drawing-safe-area.util.js +145 -35
  71. package/dist/utility/chart/kscript-live-coalesce.util.d.ts +9 -7
  72. package/dist/utility/chart/kscript-live-coalesce.util.js +13 -8
  73. package/dist/utility/chart/kscript-live-source-identity.util.d.ts +9 -0
  74. package/dist/utility/chart/kscript-live-source-identity.util.js +10 -1
  75. package/dist/utility/chart/kscript-provenance-keys.util.js +13 -0
  76. package/dist/utility/chart/kscript-standin-identity.leaf.d.ts +5 -1
  77. package/dist/utility/chart/kscript-titancharts-render-keys.constants.d.ts +32 -2
  78. package/dist/utility/chart/kscript-titancharts-render-keys.constants.js +45 -0
  79. package/dist/utility/chart/kscript-venue-policy.util.d.ts +156 -43
  80. package/dist/utility/chart/kscript-venue-policy.util.js +249 -59
  81. package/dist/utility/chart/live-bucket.util.d.ts +24 -8
  82. package/dist/utility/chart/live-bucket.util.js +85 -27
  83. package/dist/utility/chart/market-session-schedule.util.d.ts +10 -0
  84. package/dist/utility/chart/market-session-schedule.util.js +16 -0
  85. package/dist/utility/chart/marketKind.util.js +5 -0
  86. package/dist/utility/chart/mixed-mode.util.d.ts +7 -0
  87. package/dist/utility/chart/mixed-mode.util.js +14 -0
  88. package/dist/utility/chart/opra-read-access.leaf.d.ts +5 -3
  89. package/dist/utility/chart/opra-read-access.leaf.js +5 -3
  90. package/dist/utility/chart/opra-user-scripts-gate.util.d.ts +11 -16
  91. package/dist/utility/chart/opra-user-scripts-gate.util.js +12 -28
  92. package/dist/utility/chart/rth-session.util.d.ts +12 -10
  93. package/dist/utility/chart/rth-session.util.js +25 -21
  94. package/dist/utility/chart/trading-day.util.d.ts +17 -0
  95. package/dist/utility/chart/trading-day.util.js +59 -0
  96. package/dist/utility/chart/window-geometry.leaf.d.ts +8 -0
  97. package/dist/utility/chart/window-geometry.leaf.js +22 -6
  98. package/dist/utility/chart/window-owner.leaf.d.ts +23 -2
  99. package/dist/utility/chart/window-owner.leaf.js +45 -3
  100. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +33 -15
  101. package/dist/utility/chart/wrun-bar-session-facts.util.js +70 -20
  102. package/dist/utility/chart/wrun-run-result.util.d.ts +12 -0
  103. package/dist/utility/chart/wrun-run-result.util.js +141 -6
  104. package/dist/utility/intl-locale.util.js +5 -0
  105. package/dist/utility/options/option-bar-anchor.util.d.ts +145 -0
  106. package/dist/utility/options/option-bar-anchor.util.js +340 -0
  107. package/dist/utility/options/option-venue.util.d.ts +18 -0
  108. package/dist/utility/options/option-venue.util.js +27 -0
  109. package/dist/utility/scriptEditor/wrun-runtime-diagnostics.leaf.js +4 -0
  110. package/dist/utility/v2/gate-plane.util.d.ts +12 -3
  111. package/dist/utility/v2/gate-plane.util.js +30 -4
  112. package/dist/utility/v2/gate-session-latch.util.js +1 -1
  113. package/dist/utility/v2/stocks-governed.util.d.ts +16 -0
  114. package/dist/utility/v2/stocks-governed.util.js +34 -0
  115. package/dist/utility/wrun/derived-roots.leaf.d.ts +13 -0
  116. package/dist/utility/wrun/derived-roots.leaf.js +27 -0
  117. package/dist/utility/wrun/derived-roots.util.d.ts +205 -0
  118. package/dist/utility/wrun/derived-roots.util.js +451 -0
  119. package/dist/utility/wrun/run-schedule/wrun-chart-gate-reader.util.d.ts +43 -7
  120. package/dist/utility/wrun/run-schedule/wrun-chart-gate-reader.util.js +89 -19
  121. package/dist/utility/wrun/run-schedule/wrun-gate-reader-warm.util.d.ts +9 -4
  122. package/dist/utility/wrun/run-schedule/wrun-gate-reader-warm.util.js +47 -6
  123. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.d.ts +4 -2
  124. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.js +4 -2
  125. package/dist/utility/wrun/run-schedule/wrun-own-candles.util.d.ts +24 -3
  126. package/dist/utility/wrun/run-schedule/wrun-own-candles.util.js +46 -10
  127. package/dist/utility/wrun/sources/lanes/option_daily.js +5 -2
  128. package/dist/utility/wrun/sources/lanes/options_flow.js +5 -2
  129. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +64 -19
  130. package/dist/utility/wrun/sources/opra-option-lanes.util.js +105 -35
  131. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +2 -1
  132. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +2 -1
  133. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +3 -0
  134. package/dist/utility/wrun/sources/row-lanes/option_prints.js +19 -4
  135. package/dist/utility/wrun/sources/row-lanes/option_strike_flow.js +17 -4
  136. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +52 -13
  137. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +88 -19
  138. package/dist/utility/wrun/sources/row-lanes/option_surface.js +2 -1
  139. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +19 -0
  140. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +24 -9
  141. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +41 -10
  142. package/dist/utility/wrun/sources/wrun-row-lane-add-memo.util.d.ts +111 -0
  143. package/dist/utility/wrun/sources/wrun-row-lane-add-memo.util.js +133 -0
  144. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.d.ts +15 -3
  145. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.js +22 -3
  146. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +31 -0
  147. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +197 -13
  148. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +761 -27
  149. package/dist/utility/wrun/wrun-browser-sources.leaf.js +1 -2
  150. package/dist/utility/wrun/wrun-builtin-twin.util.d.ts +12 -0
  151. package/dist/utility/wrun/wrun-builtin-twin.util.js +21 -0
  152. package/dist/utility/wrun/wrun-chart-market-facts.util.d.ts +60 -16
  153. package/dist/utility/wrun/wrun-chart-market-facts.util.js +113 -61
  154. package/dist/utility/wrun/wrun-color-settings.util.d.ts +9 -0
  155. package/dist/utility/wrun/wrun-color-settings.util.js +33 -0
  156. package/dist/utility/wrun/wrun-download-meter.util.d.ts +15 -0
  157. package/dist/utility/wrun/wrun-download-meter.util.js +14 -2
  158. package/dist/utility/wrun/wrun-download-plan.util.d.ts +99 -0
  159. package/dist/utility/wrun/wrun-download-plan.util.js +118 -0
  160. package/dist/utility/wrun/wrun-draft-legend-note.util.d.ts +11 -3
  161. package/dist/utility/wrun/wrun-draft-legend-note.util.js +26 -4
  162. package/dist/utility/wrun/wrun-frames.d.ts +27 -6
  163. package/dist/utility/wrun/wrun-frames.js +73 -10
  164. package/dist/utility/wrun/wrun-handles.util.d.ts +7 -3
  165. package/dist/utility/wrun/wrun-handles.util.js +9 -8
  166. package/dist/utility/wrun/wrun-hosted-wire.util.d.ts +7 -1
  167. package/dist/utility/wrun/wrun-hosted-wire.util.js +12 -2
  168. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +18 -4
  169. package/dist/utility/wrun/wrun-hud-looks.util.js +45 -13
  170. package/dist/utility/wrun/wrun-input-requirements.leaf.d.ts +68 -0
  171. package/dist/utility/wrun/wrun-input-requirements.leaf.js +163 -7
  172. package/dist/utility/wrun/wrun-latest-snapshot.d.ts +11 -0
  173. package/dist/utility/wrun/wrun-leg-close.util.d.ts +59 -23
  174. package/dist/utility/wrun/wrun-leg-close.util.js +186 -28
  175. package/dist/utility/wrun/wrun-live-intake.util.d.ts +35 -15
  176. package/dist/utility/wrun/wrun-live-intake.util.js +243 -126
  177. package/dist/utility/wrun/wrun-live-tick.util.d.ts +13 -5
  178. package/dist/utility/wrun/wrun-live-tick.util.js +279 -99
  179. package/dist/utility/wrun/wrun-market-facts.util.d.ts +13 -3
  180. package/dist/utility/wrun/wrun-market-facts.util.js +13 -3
  181. package/dist/utility/wrun/wrun-market-size-defaults.leaf.d.ts +60 -11
  182. package/dist/utility/wrun/wrun-market-size-defaults.leaf.js +70 -5
  183. package/dist/utility/wrun/wrun-market-size-defaults.util.js +31 -5
  184. package/dist/utility/wrun/wrun-opra-lane.util.d.ts +17 -4
  185. package/dist/utility/wrun/wrun-opra-lane.util.js +6 -4
  186. package/dist/utility/wrun/wrun-option-book-rows.util.d.ts +56 -0
  187. package/dist/utility/wrun/wrun-option-book-rows.util.js +96 -0
  188. package/dist/utility/wrun/wrun-option-strike-flow-forecast.util.d.ts +31 -0
  189. package/dist/utility/wrun/wrun-option-strike-flow-forecast.util.js +119 -0
  190. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.d.ts +23 -6
  191. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.js +47 -11
  192. package/dist/utility/wrun/wrun-option-strike-flow.util.d.ts +86 -19
  193. package/dist/utility/wrun/wrun-option-strike-flow.util.js +168 -62
  194. package/dist/utility/wrun/wrun-option-views.util.d.ts +323 -28
  195. package/dist/utility/wrun/wrun-option-views.util.js +484 -71
  196. package/dist/utility/wrun/wrun-options-chain.util.d.ts +3 -3
  197. package/dist/utility/wrun/wrun-options-chain.util.js +2 -0
  198. package/dist/utility/wrun/wrun-output-style.util.d.ts +6 -2
  199. package/dist/utility/wrun/wrun-output-style.util.js +20 -2
  200. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +32 -2
  201. package/dist/utility/wrun/wrun-overlay-drivers.util.js +13 -3
  202. package/dist/utility/wrun/wrun-overlay-lifecycle.util.d.ts +10 -1
  203. package/dist/utility/wrun/wrun-overlay-lifecycle.util.js +52 -4
  204. package/dist/utility/wrun/wrun-overlay-recovery.util.js +3 -1
  205. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +160 -42
  206. package/dist/utility/wrun/wrun-overlay-run.util.js +1244 -209
  207. package/dist/utility/wrun/wrun-pane-format.util.d.ts +2 -1
  208. package/dist/utility/wrun/wrun-pane-format.util.js +7 -3
  209. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +9 -0
  210. package/dist/utility/wrun/wrun-panel-mount.util.js +114 -19
  211. package/dist/utility/wrun/wrun-panel-style.util.d.ts +10 -9
  212. package/dist/utility/wrun/wrun-panel-style.util.js +58 -9
  213. package/dist/utility/wrun/wrun-param-map.util.d.ts +14 -11
  214. package/dist/utility/wrun/wrun-param-map.util.js +10 -5
  215. package/dist/utility/wrun/wrun-param-values.util.d.ts +14 -4
  216. package/dist/utility/wrun/wrun-param-values.util.js +4 -0
  217. package/dist/utility/wrun/wrun-pin-spelling.util.d.ts +15 -2
  218. package/dist/utility/wrun/wrun-pin-spelling.util.js +39 -14
  219. package/dist/utility/wrun/wrun-refusal-surface.util.d.ts +50 -0
  220. package/dist/utility/wrun/wrun-refusal-surface.util.js +68 -0
  221. package/dist/utility/wrun/wrun-refusal.util.d.ts +3 -2
  222. package/dist/utility/wrun/wrun-refusal.util.js +22 -0
  223. package/dist/utility/wrun/wrun-refused-latest.util.d.ts +10 -0
  224. package/dist/utility/wrun/wrun-refused-latest.util.js +12 -0
  225. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +26 -0
  226. package/dist/utility/wrun/wrun-registry-errors.util.js +34 -0
  227. package/dist/utility/wrun/wrun-replay-lane.util.js +3 -2
  228. package/dist/utility/wrun/wrun-row-source.d.ts +11 -0
  229. package/dist/utility/wrun/wrun-run-interval-session.util.d.ts +20 -6
  230. package/dist/utility/wrun/wrun-run-interval-session.util.js +22 -7
  231. package/dist/utility/wrun/wrun-run-interval.util.d.ts +43 -9
  232. package/dist/utility/wrun/wrun-run-interval.util.js +58 -15
  233. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +45 -1
  234. package/dist/utility/wrun/wrun-script-inputs.util.js +112 -4
  235. package/dist/utility/wrun/wrun-setting-words.util.d.ts +7 -3
  236. package/dist/utility/wrun/wrun-setting-words.util.js +13 -5
  237. package/dist/utility/wrun/wrun-socket-row-source.d.ts +27 -2
  238. package/dist/utility/wrun/wrun-socket-row-source.js +118 -8
  239. package/dist/utility/wrun/wrun-source-rows.util.d.ts +29 -18
  240. package/dist/utility/wrun/wrun-source-rows.util.js +61 -27
  241. package/dist/utility/wrun/wrun-style-words.util.js +6 -4
  242. package/dist/utility/wrun/wrun-table-chrome.util.d.ts +3 -2
  243. package/dist/utility/wrun/wrun-table-chrome.util.js +19 -11
  244. package/dist/utility/wrun/wrun-tape-per-order.util.d.ts +2 -0
  245. package/dist/utility/wrun/wrun-tape-per-order.util.js +7 -0
  246. package/dist/utility/wrun/wrun-tape-source.util.d.ts +17 -9
  247. package/dist/utility/wrun/wrun-tape-source.util.js +20 -12
  248. package/dist/utils/replay/replay-buffer-math.d.ts +53 -2
  249. package/dist/utils/replay/replay-buffer-math.js +227 -20
  250. package/dist/workers/constants/socket-slots.d.ts +91 -6
  251. package/dist/workers/constants/socket-slots.js +85 -6
  252. package/package.json +5 -5
@@ -69,6 +69,7 @@ import { isWrunBatchedMarksKind, readWrunBatchedSections, wrunBatchedChildId, wr
69
69
  import { isPackedOhlcvRows, unpackOhlcvRows } from '../../instances/script-engine-worker-ohlcv-transfer.js';
70
70
  import { Intervals } from '../../constants/interval.constants.js';
71
71
  import { mountedPlotSetMatchesRunResult } from '../chart/kscript-mounted-plot-set.leaf.js';
72
+ import { isPredictionExchangeName } from '../chart/prediction-identity.util.js';
72
73
  import { resolveLazyMergePlan } from '../chart/kscript-integration-decision.leaf.js';
73
74
  import { KSCRIPT_CONTAINER_OUTPUT_KEY } from '../chart/kscript-titancharts-container.util.js';
74
75
  import { normalizeKScriptRunResultForTitanCharts } from '../chart/kscript-run-result-normalize.util.js';
@@ -80,12 +81,14 @@ import { standInIdentityOf, wrunStandInTag, } from '../chart/kscript-standin-ide
80
81
  import { isWrunOverlayHeldForRun, requestWrunOverlayRerun, withWrunOverlayExecutionMeasure, } from './wrun-overlay-lifecycle.util.js';
81
82
  import { armWrunSourceRecovery, requestWrunCasualtyRebuilds, retireWrunSourceRecovery, wrunOverlayHold, } from './wrun-overlay-recovery.util.js';
82
83
  import { gateSessionHeldElsewhere } from '../v2/gate-session-latch.util.js';
84
+ import { isStocksTapeGoverned } from '../v2/stocks-governed.util.js';
83
85
  import { noteWrunGatePlaneStopped, noteWrunGatePlanesRead } from './wrun-gate-plane-readers.util.js';
84
86
  import { wrunGateLatchedThunks, wrunLaneGatePlanes, wrunLaneGateStopOf, wrunSessionStopPlaneOf, } from './wrun-options-stop.util.js';
85
87
  import { annotateWrunRunFailedIdentity, noteWrunRunRetained, wrunRunIdentityOf } from './wrun-cap-notice.util.js';
86
88
  import { wrunIntegrationRoute } from './wrun-integration-route.util.js';
87
89
  import { placeWrunTablesOnChart } from './wrun-table-chrome.util.js';
88
90
  import { projectKScriptRunResultOntoChartBars } from '../chart/kscript-run-interval-projection.util.js';
91
+ import { runBarSpan } from '../chart/indicator-run-interval.util.js';
89
92
  import { GESTURE_LINGER_MS, HEAVY_APPLY_GESTURE_CEILING_MS } from '../chart/gesture-timing.leaf.js';
90
93
  import { getChartDataFetchGeneration } from '../chart/chart-data-fetch-generation.util.js';
91
94
  import { isWrunWindowOwner } from '../chart/window-owner.leaf.js';
@@ -104,12 +107,12 @@ import { attachWrunStrategy, isWrunStrategySheet, wrunStrategyOf } from './wrun-
104
107
  import { withWrunDeadline, WRUN_SOURCE_FETCH_DEADLINE_MS } from './wrun-deadline.util.js';
105
108
  import { noteWrunLateRead, takeWrunLateRead, wrunJoinLateReads } from './run-schedule/wrun-late-reads.util.js';
106
109
  import { scheduleWrunLaneGroups } from './run-schedule/wrun-lane-groups.util.js';
107
- import { serveWrunOwnCandles } from './run-schedule/wrun-own-candles.util.js';
110
+ import { serveWrunOwnCandles, wrunChartCandleVenue, wrunMainCandleSourceOf, } from './run-schedule/wrun-own-candles.util.js';
108
111
  import { wrunPollClassReadsChain, wrunRowClassReadsChain } from './run-schedule/wrun-gate-reader-warm.util.js';
109
112
  import { wrunPollLaneByKey, wrunPollLanesOfClass } from './sources/registry.js';
110
- import { wrunRowLaneByKey, wrunRowLaneOfClass } from './sources/row-lane-registry.js';
113
+ import { wrunRowLaneByKey, wrunRowLaneOfClass, wrunRowLanes } from './sources/row-lane-registry.js';
111
114
  import { isWrunRowLaneId } from './sources/wrun-row-lane.types.js';
112
- import { fetchWrunRowLaneRows, planWrunRowLanes, wrunRowLaneChainAsk, wrunRowLaneFetchOptions, wrunRowLaneInstanceReadsOpra, wrunRowLaneRequired, wrunRunSourceReachFromMs, } from './sources/wrun-row-lanes.util.js';
115
+ import { fetchWrunRowLaneRows, planWrunRowLanes, wrunRowLaneChainAsk, wrunRowLaneAddKey, wrunRowLaneFetchOptions, wrunRowLaneInstanceReadsOpra, wrunRowLaneRequired, wrunRowLanesReplayBounded, wrunRunSourceReachFromMs, } from './sources/wrun-row-lanes.util.js';
113
116
  import { wrunOpraLanePayloadFields } from './wrun-opra-lane.util.js';
114
117
  import { WRUN_LANE_REFUSED_SETTLE_REASON, wrunLaneRefusedCodeOf } from './wrun-lane-refusal.leaf.js';
115
118
  import { TRADES_HISTORY_MAX_CELLS } from '../../kscript-data/controls/live-trades-merge.util.js';
@@ -118,7 +121,7 @@ import { liveBucketStartsInRange, liveBucketVenueOf } from '../chart/live-bucket
118
121
  import { hostBucketResolverFor } from '../chart/host-bar-placement.util.js';
119
122
  import { indexHostFetchTierMs, sourceRowsStraddleHostBars } from '../chart/index-host-tier.util.js';
120
123
  import { isWrunPollLaneId, wrunPollCoinGateSeed, } from './sources/wrun-poll-lane.types.js';
121
- import { fetchWrunPollLaneHostGridRows, planWrunPollLanes, wrunLaneRowsRequired, wrunPollLaneChainAsk, wrunPollLaneFetchFrom, wrunPollLaneFetchOptions, wrunPollLaneFetchTo, wrunPollLaneInstanceReadsOpra, wrunPollLaneRequired, wrunPollLaneValuelessInput, } from './sources/wrun-poll-lanes.util.js';
124
+ import { assertWrunLaneChainPlaneReadable, fetchWrunPollLaneHostGridRows, planWrunPollLanes, resolveWrunOptionSettingKnobs, wrunChainLaneContext, wrunLaneRowsRequired, wrunPollLaneChainAsk, wrunPollLaneFetchFrom, wrunPollLaneFetchOptions, wrunPollLaneFetchTo, wrunPollLaneInstanceReadsOpra, wrunPollLaneRequired, wrunPollLaneValuelessInput, } from './sources/wrun-poll-lanes.util.js';
122
125
  import { wrunDailyLaneFetchFrom, wrunDailyLaneFetchTo } from './wrun-daily-lane.util.js';
123
126
  import { assertWrunEtfFlowCoin, planWrunEtfFlowColumns, planWrunEtfFlowLane, resolveWrunEtfFlowTickers, WRUN_ETF_FLOW_INTERVAL_KEY, wrunEtfFlowAnswer, zipWrunEtfFlowRows, } from './wrun-etf-flow-lane.util.js';
124
127
  import { planWrunOptionSummaryLane, WRUN_OPTION_SUMMARY_LANES, wrunOptionSummaryAskExtras, wrunOptionSummaryAskKey, zipWrunOptionSummaryRows, } from './wrun-option-summary-lane.util.js';
@@ -147,7 +150,7 @@ import { assertWrunBrowserSources, getWrunBrowserHost, } from './wrun-host.servi
147
150
  import { applyWrunInertLegendState } from './wrun-inert-legend.util.js';
148
151
  import { annotateWrunErrorRefusal, attachWrunRefusal, serializeWrunRefusal, stampWrunRefusalTelemetry, wrunAuthorRuleSeed, wrunLeftOutRefusalSeed, wrunOptionsStopSeed, wrunOverlayEditable, wrunRefusalFor, wrunRefusalOf, wrunRefusalSeedFor, wrunRefusalSeedOf, WRUN_REFUSAL_EVENT_MARKET_KEY, } from './wrun-refusal.util.js';
149
152
  import { claimWrunRefusalNotice, emitWrunRefusalChange, liveWrunRefusalAttempt, projectWrunRefusal, retractWrunRefusal, } from './wrun-refusal-surface.util.js';
150
- import { WRUN_ETF_COVERED_COINS, wrunInputReadsFillOverEmptyLane, wrunInputRequirements, wrunUnservedLanes, } from './wrun-input-requirements.leaf.js';
153
+ import { WRUN_ETF_COVERED_COINS, wrunInputReadsFillOverEmptyLane, wrunInputRequirements, wrunPredictionMarketWalledInput, wrunRunMarketReadOfFetchType, wrunSheetReadsRunMarket, wrunUnservedLanes, } from './wrun-input-requirements.leaf.js';
151
154
  import { getWrunOverlayMetadata, rememberWrunOverlayMetadata } from './wrun-overlay-metadata.util.js';
152
155
  import { setWrunOverlayAlertOutputs } from './wrun-alert-outputs.registry.js';
153
156
  import { buildWrunScriptInputs, wrunParamValuesFromSettings, wrunRunOverlayPalette, } from './wrun-script-inputs.util.js';
@@ -157,10 +160,12 @@ import { wrunSheetWithSettings, wrunVisibilityOwnedOutputs } from './wrun-color-
157
160
  import { wrunSheetDrawsOnlyStatsStrip, wrunStatsStripSettings } from './wrun-stats-strip.util.js';
158
161
  import { planWrunHeldLanes } from './wrun-held-lanes.util.js';
159
162
  import { createWrunDownloadMeter, wrunDownloadAnswerSize, } from './wrun-download-meter.util.js';
163
+ import { createWrunLaneDownloadMeter, wrunDownloadKitInterval, wrunDownloadMarketOf, wrunDownloadPlanKeyOf, wrunDownloadPlanReadBytes, wrunRunDownloadMode, wrunRunDownloadReads, } from './wrun-download-plan.util.js';
164
+ import { FeatureFlag } from '../../constants/feature-flags.constants.js';
160
165
  import { clearedColorCustomizationFlags } from '../chart/color-customization.leaf.js';
161
166
  import { WRUN_LATEST_HISTORY_LENGTH } from './wrun-latest-history.leaf.js';
162
167
  import { resolveChartPricePrecision } from '../chart/price-precision.util.js';
163
- import { currentWrunOverlayLiveGeneration, getWrunOverlayLiveContext, isWrunOverlayReplacementPending, markWrunOverlayComputeSucceeded, nextWrunOverlayLiveGeneration, noteWrunOverlayRunSettle, noteWrunOverlayWholeWindowDrawn, onWrunOverlayLiveTeardown, rerunWrunOverlayForChartWave, setWrunOverlayLiveContext, setWrunPrefixRuntime, setWrunUnansweredDropSurface, suspendWrunOverlayLiveSession, withWrunOverlaySessionLock, wrunChartMarketIdentity, } from './wrun-overlay-drivers.util.js';
168
+ import { currentWrunOverlayLiveGeneration, getWrunOverlayLiveContext, isWrunOverlayFullRerunInFlight, isWrunOverlayReplacementPending, markWrunOverlayComputeSucceeded, nextWrunOverlayLiveGeneration, noteWrunOverlayRunSettle, noteWrunOverlayWholeWindowDrawn, onWrunOverlayLiveTeardown, rerunWrunOverlayForChartWave, setWrunOverlayLiveContext, setWrunPrefixRuntime, setWrunUnansweredDropSurface, suspendWrunOverlayLiveSession, withWrunOverlaySessionLock, wrunChartMarketIdentity, } from './wrun-overlay-drivers.util.js';
164
169
  import { claimWrunWarmupHead, readWrunWarmupHeadBars, readWrunWarmupHeadSpan, storeWrunWarmupHeadSpan, wrunWarmupHeadStored, } from './wrun-warmup-head-store.util.js';
165
170
  import { protectedKScriptMountedRowCount } from '../chart/protected-kscript-empty-output.util.js';
166
171
  import { kScriptSettingsRevision } from '../chart/kscript-settings-revision.leaf.js';
@@ -174,9 +179,11 @@ import { getMarketKind } from '../chart/marketKind.util.js';
174
179
  import { isCmeGoverned } from '../chart/cme-realtime.util.js';
175
180
  import { wrunBarSessionFactsResolver, wrunBarVenueOf } from '../chart/wrun-bar-session-facts.util.js';
176
181
  import { wrunPresentIsPartial } from './wrun-present-bits.util.js';
177
- import { assertWrunPinnedLegVenues, partitionWrunLegsByVenue, wrunLegFetchedRowReaders, wrunLegRidesNativeRows, wrunPinnedLegRefusalOf, wrunPinVenueVerdict, } from './wrun-pin-venues.util.js';
178
- import { annotateWrunErrorFailureRow, annotateWrunErrorIndicatorId, isWrunOverlayPausedError, isWrunQuarantinedError, isWrunWorkerPoisonError, WrunChartGoneError, WrunDeadlineError, WrunIntegrationError, WrunNoBarsError, WrunOverlayPausedError, WrunSourceDataUnavailableError, WrunVenueBlockedError, } from './wrun-registry-errors.util.js';
179
- import { createKScriptVenueBlockedError, isKScriptDisplayBlockedOnExchange, isOfficialWrunOverlay, isOpraUserScriptRun, } from '../chart/kscript-venue-policy.util.js';
182
+ import { assertWrunPinnedLegVenues, partitionWrunLegsByVenue, wrunLegFetchedRowReaders, wrunLegRidesNativeRows, wrunPinMarketsOf, wrunPinnedLegRefusalOf, wrunPinVenueVerdict, } from './wrun-pin-venues.util.js';
183
+ import { annotateWrunErrorFailureRow, annotateWrunErrorIndicatorId, isWrunOverlayPausedError, isWrunQuarantinedError, isWrunWorkerPoisonError, WrunChartGoneError, WrunDeadlineError, WrunIntegrationError, WrunNoBarsError, WrunOverlayPausedError, WrunPredictionMarketBlockedError, WrunSourceDataUnavailableError, WrunStrategyVenueBlockedError, WrunVenueBlockedError, } from './wrun-registry-errors.util.js';
184
+ import { createKScriptVenueBlockedError, isCmeUserScriptCandidate, isCmeUserScriptRun, isKScriptDisplayBlockedOnExchange, isOfficialWrunOverlay, isOpraUserScriptCandidate, isOpraUserScriptRun, payloadTouchesCmeVenue, payloadTouchesOpraVenue, } from '../chart/kscript-venue-policy.util.js';
185
+ import { isOpraUserScriptsFlagOn } from '../chart/opra-user-scripts-gate.util.js';
186
+ import { captureCmeStudyAuth, cmeStudyStopReason, isCmeStudyAuthCurrent, isCmeUserScriptsFlagOn, } from '../chart/cme-user-scripts-gate.util.js';
180
187
  import { governedMarketDataTier, governedOptionSummaryTier } from '../v2/governed-tier.leaf.js';
181
188
  import { awaitWrunChildOverlays, mountWrunChildOverlays, prepareWrunHeatmapWindowLanding, WrunStaleLandingError, } from './wrun-panel-mount.util.js';
182
189
  import { planWrunFormingPreRoll, planWrunIntrabarLegFetch, planWrunLegFetch, wrunClampedLegDiagnostics, wrunIntrabarServedNotes, wrunLegFetchReads, } from './wrun-leg-fetch.util.js';
@@ -185,6 +192,8 @@ import { resolveWrunTapeAcquisition, WRUN_TAPE_INTERVAL_UNSUPPORTED_CODE, WRUN_T
185
192
  import { wrunChartSession, wrunLegCandleClose, wrunPrimaryRowBounds } from './wrun-leg-close.util.js';
186
193
  import { isWrunRowSourceTransientError, wrunRowBatchDeliveredSheet, wrunRowSourceSettingsLeftBy, } from './wrun-row-source.js';
187
194
  import { wrunOverlayOpraStamped } from './wrun-cloud-opra-stamp.util.js';
195
+ // The run's one options market (the row lanes' planner holds the module on this graph already).
196
+ import { decideWrunRunOptionsMarket, noteWrunRunOptionsMarket, wrunDecidedOptionsExchange, } from './derived-roots.util.js';
188
197
  import { wrunRowSourceFor } from './wrun-row-source-factory.js';
189
198
  import { __resetWrunSocketSessionLossesForTests, noteWrunSocketSessionLoss, wrunSocketSessionLossCause, wrunSocketSessionLossCount, } from './wrun-socket-session-losses.util.js';
190
199
  import { isWrunRunMountOnChart, raiseWrunSandboxLoading, wrunRowBatchCellRows, } from './wrun-sandbox-row-source.js';
@@ -194,10 +203,9 @@ import { isWrunOptionsChainCryptoVenueWord, WRUN_OPTIONS_CHAIN_ONE_VENUE_CODE, W
194
203
  import { adoptWrunLiveIntakeGeneration, markWrunLiveGap, noteWrunLiveIntakeEvent, wrunPushEligible, } from './wrun-live-intake.util.js';
195
204
  import { openWrunPollLaneLiveChannels } from './wrun-series-stream.util.js';
196
205
  import { serverNowMs } from '../auth/server-clock.util.js';
197
- import { aggregateOhlcvRows } from '../../utils/replay/replay-buffer-math.js';
198
206
  import { isWrunReplayRunCurrent, noteWrunReplayRun, wrunReplayRunPlanOf, } from './wrun-replay-lane.util.js';
199
207
  import { cutWrunReplayRowsAfterApply } from './wrun-replay-rows.util.js';
200
- import { builtinTwinOf } from './wrun-builtin-twin.util.js';
208
+ import { builtinPortOf } from './wrun-builtin-twin.util.js';
201
209
  import { WRUN_HISTORY_WARMUP_MAX_BARS, wrunDeclaredWarmupBars, wrunDeclaredWarmupEndTs, wrunHistoryWarmupBars, } from './wrun-declared-warmup.util.js';
202
210
  import { wrunLaneWarmupBars, wrunLaneWarmupFromMs } from './wrun-lane-warmup.util.js';
203
211
  import { orderWrunFirstRunHistory } from './wrun-first-run-depth.util.js';
@@ -238,6 +246,12 @@ export const WRUN_ODDS_SEED_LEG_BARS = 1440;
238
246
  * Cold, the gateway answered a 290-bar Polymarket window in 2.6 to 4.6 s and
239
247
  * the serial 1440-bar seed that followed it in up to 12.5 s. */
240
248
  export const WRUN_ODDS_SHORT_SEED_LEG_BARS = 250;
249
+ /** A candle ask's rows market when the chart's rows came from another (the full run's door and the tick's agree). */
250
+ export function wrunCandleAskSource(chartMetadata, provenance) {
251
+ // A reader that threw reads as the chart's own, as the walls read it (wrunChartCandleVenue).
252
+ const source = wrunMainCandleSourceOf(chartMetadata) ?? null;
253
+ return { source, walled: source !== null && isKScriptDisplayBlockedOnExchange(source.exchange, provenance) };
254
+ }
241
255
  /**
242
256
  * A pinned leg's fetch payload extras over the current-market placeholders:
243
257
  * its market (absent = the chart's own), plus the K_OHLCV prediction flag
@@ -346,6 +360,19 @@ function wrunLiveLaneOfFetchKey(key) {
346
360
  return (WRUN_LIVE_LANE_OF_FETCH_KEY[key] ??
347
361
  (isWrunPollLaneId(key) || isWrunRowLaneId(key) || isWrunTradesLegLane(key) ? key : undefined));
348
362
  }
363
+ /** THE run market: where the chart's trades print for this run (a Trades chart's tape), null for the chart's own. */
364
+ async function decideWrunRunMarket(chartMetadata, settings) {
365
+ try {
366
+ const port = (await wrunChartHostEnv().chart.loadTitanCharts());
367
+ const market = (await port.kscriptStockTapeTradesMarket?.(chartMetadata, settings)) ?? null;
368
+ const chart = chartMetadata;
369
+ // The chart's own market back (a miss, a failed lookup, a run the venue policy keeps off the tape) moves nothing.
370
+ return market !== null && (market.exchange !== chart?.exchange || market.symbol !== chart?.symbol) ? market : null;
371
+ }
372
+ catch {
373
+ return null;
374
+ }
375
+ }
349
376
  /** Recompute one mounted WRUN overlay over the chart's CURRENT loaded rows
350
377
  * and integrate the result through the shared adapter path. */
351
378
  export async function runWrunOverlayOnChart(target) {
@@ -387,12 +414,15 @@ export async function runWrunOverlayOnChart(target) {
387
414
  downloadNoted = true;
388
415
  wrunChartHostEnv().diagnostics.noteAttemptDownload(attempt, computed.download.summary());
389
416
  };
390
- // The run is still the overlay's own: the chart and the overlay it computed for stand, and the
391
- // attempt it resolved is still the live one (a teardown, a restore or a later request retires it).
417
+ // The run is still the overlay's own: the chart and the overlay it computed for stand, the
418
+ // attempt it resolved is still the live one (a teardown, a restore or a later request retires it),
419
+ // and a CME chart study still computes under the authorisation its head captured (`computed.cmeAuth`:
420
+ // a move of the viewer's access since retires it, the superseded path's `not-current`).
392
421
  const isCurrent = () => mount.tc !== undefined &&
393
422
  mount.meta !== undefined &&
394
423
  isWrunRunMountOnChart(target.chartIndex, mount) &&
395
- wrunRefusalAttemptStands(target.chartIndex, target.indicatorId, refusalAttempt);
424
+ wrunRefusalAttemptStands(target.chartIndex, target.indicatorId, refusalAttempt) &&
425
+ wrunCmeStudyAuthStands(computed);
396
426
  // The market this run computes for (C4), set once the head read it: with the data generation and
397
427
  // the compute revision above, what a failure is judged against (wrunRunSupersededReason).
398
428
  let market;
@@ -454,24 +484,100 @@ export async function runWrunOverlayOnChart(target) {
454
484
  chartMetadata,
455
485
  });
456
486
  const provenance = meta.settings;
457
- // A run reading options that list on OPRA waits, bounded, for the `opra` flag the plane and its stop
458
- // reasons are judged by (FE-REASON-CHIPS review): a restore can run before the map hydrates, and
459
- // unhydrated, the map would read the plane closed and the lanes "not on your account". No run waits for
460
- // the `opra-user-scripts` flag: no OPRA wall honours it any more (the compliance round, plan row D3), so
461
- // a user run on an OPRA chart is refused at once, whatever the map says.
487
+ // The run's console provenance, captured before anything computes (`computed.opra`): a run on an OPRA contract
488
+ // chart reads OPRA candles whatever its lanes read.
489
+ if (payloadTouchesOpraVenue(chartExchange))
490
+ computed.opra = true;
491
+ // The same on a CME chart (`computed.cme`): every run there reads CME candles, an OpenMarket package's too (the mark
492
+ // is the output's provenance, never a permission).
493
+ if (payloadTouchesCmeVenue(chartExchange))
494
+ computed.cme = true;
495
+ // A run reading options decides its ONE options market here (derived-roots.util `decideWrunRunOptionsMarket`):
496
+ // where the options list on OPRA (a stock, an OPRA contract, a known stock twin) or the overlay's last read was
497
+ // OPRA's (its provenance stamp), it waits, bounded, for the `opra` flag the plane and its stop reasons are judged
498
+ // by (FE-REASON-CHIPS review): a restore can run before the map hydrates, and unhydrated, the map would read the
499
+ // plane closed and the lanes "not on your account". Under a lit flag (or the stamp) it waits, bounded, for the
500
+ // chart's stock twin answer, so a twin restored before its answer reads its stock's OPRA chain; then the market,
501
+ // its plane and its stop are read once, and every planner, the options chain lane, the download plan and the host
502
+ // fill of this run read that decision (a run never mixes planes; a later twin answer reruns it).
462
503
  const readsOpraOptions = target.metadata.inputs.some((input) => target.metadata.inputSources[input.name]?.source === 'options_chain') ||
463
504
  wrunSheetReadsOpraLane(target.metadata);
464
- if (readsOpraOptions) {
465
- const opraGate = await wrunChartHostEnv().market.loadOptionsGate();
466
- const waitsOpra = opraGate.opraFlagDecidesChartOptions({
467
- exchange: typeof chartExchange === 'string' ? chartExchange : undefined,
468
- });
469
- if (waitsOpra)
470
- await opraGate.awaitOpraFlagHydration();
471
- }
472
- if (isKScriptDisplayBlockedOnExchange(chartExchange, provenance)) {
473
- throw new WrunVenueBlockedError(createKScriptVenueBlockedError(String(chartExchange)).message);
474
- }
505
+ // A run the `opra-user-scripts` flag may open the OPRA plane to (a browser run the viewer wrote or added) waits,
506
+ // bounded, for the flag map before an OPRA wall reads it, where one stands ahead: on an OPRA contract chart (the
507
+ // display wall), or where the run's options decision rides the OPRA plane (the chain wall: a US stock or ETF
508
+ // chart, a stock twin). A restore can run before the map hydrates, and an unhydrated map reads closed. The wait
509
+ // starts beside the options decision (both ride the one flag fetch); every other run never waits on the map.
510
+ const userScriptsHydration = isOpraUserScriptCandidate(provenance) && (payloadTouchesOpraVenue(chartExchange) || readsOpraOptions)
511
+ ? wrunChartHostEnv()
512
+ .market.loadOptionsGate()
513
+ .then(async (gate) => {
514
+ await gate.awaitOpraUserScriptsFlagHydration();
515
+ return gate;
516
+ })
517
+ .catch(() => undefined)
518
+ : undefined;
519
+ const options = readsOpraOptions
520
+ ? await decideWrunRunOptionsMarket(chartMetadata, wrunOverlayOpraStamped(meta))
521
+ : undefined;
522
+ if (userScriptsHydration !== undefined && (payloadTouchesOpraVenue(chartExchange) || options?.plane === 'opra')) {
523
+ const gate = await userScriptsHydration;
524
+ // The bound ran out with the flag still dark: the walls refuse this run now, and a flag that lands later judges
525
+ // the walled user-script overlays again (web: opra-options-gate.util `armOpraUserScriptsRejudge`).
526
+ if (!isOpraUserScriptsFlagOn())
527
+ gate?.armOpraUserScriptsRejudge?.();
528
+ }
529
+ // A run the `cme-user-scripts` gate may open the CME plane to (a browser run the viewer wrote or added) that the
530
+ // CME display wall refuses on this chart waits, bounded, for the flag map (the port's
531
+ // `awaitCmeUserScriptsFlagHydration`), and the wall is asked again below: a restore can run before the map
532
+ // hydrates, and an unhydrated map reads closed. Every other run never waits on the map. The bound ran out with the
533
+ // flag still dark: the wall refuses this run now, and a gate that opens later judges the walled CME studies again
534
+ // (`armCmeUserScriptsRejudge`). A host that binds neither port judges by the map as it stands.
535
+ if (isCmeUserScriptCandidate(provenance) &&
536
+ payloadTouchesCmeVenue(chartExchange) &&
537
+ isKScriptDisplayBlockedOnExchange(chartExchange, provenance)) {
538
+ const gate = await wrunChartHostEnv()
539
+ .market.loadOptionsGate()
540
+ .then(async (loaded) => {
541
+ await loaded.awaitCmeUserScriptsFlagHydration?.();
542
+ return loaded;
543
+ })
544
+ .catch(() => undefined);
545
+ if (!isCmeUserScriptsFlagOn())
546
+ gate?.armCmeUserScriptsRejudge?.();
547
+ }
548
+ // The market the candles came from: a chart riding a tape walls what that tape's own chart walls.
549
+ const candleVenue = wrunChartCandleVenue(chartMetadata);
550
+ if (isKScriptDisplayBlockedOnExchange(candleVenue, provenance)) {
551
+ throw withCmeStudyStopSeed(new WrunVenueBlockedError(createKScriptVenueBlockedError(String(candleVenue)).message), target.chartIndex, target.indicatorId, candleVenue);
552
+ }
553
+ // Strategy testing is no CME chart study (Kyle 2026-10-29): on a CME chart every strategy sheet is refused, an
554
+ // OpenMarket package's included, here at the head before the loader is raised, a lane is asked or the sandbox is
555
+ // touched (the broker feed, `wrunStrategyRunInputFor`, is never built), on every lane. A venue refusal held like
556
+ // the wall's, with its own record on the legend (`cme-wall` `strategy`: no wall painter stands behind it).
557
+ if (payloadTouchesCmeVenue(chartExchange) && isWrunStrategySheet(target.metadata)) {
558
+ throw attachWrunRefusal(new WrunStrategyVenueBlockedError(createKScriptVenueBlockedError(String(chartExchange)).message), WRUN_CME_STRATEGY_REFUSAL_SEED);
559
+ }
560
+ // The prediction-market wall (Kyle 2026-10-29: options indicators on a Polymarket chart make no sense): on a
561
+ // Polymarket or HIP4 chart an input read by the chart's coin (the options chain and its lanes, a provider lane, a
562
+ // coin leg) would read another market under the odds (wrunPredictionMarketWalledInput: the coin is no asset the
563
+ // price follows), so the sheet is refused here at the head, before the loader is raised or a lane is asked,
564
+ // whatever fill it declares. Judged on the sheet the run reads there: its settings applied (a `when` setting that
565
+ // is off leaves its input undemanded) and its lane demand at the market's size unit (`needed_by`). Held like the
566
+ // strategy refusal, with its own record (`cme-wall` `prediction`): the run after the chart leaves the prediction
567
+ // market computes.
568
+ const predictionWalled = typeof chartExchange === 'string' && isPredictionExchangeName(chartExchange)
569
+ ? wrunPredictionMarketWalledInput(wrunSheetWithLaneDemand(wrunSheetWithSettings(target.metadata, meta.settings), wrunChartSizeUnit(chartMetadata)), chartExchange)
570
+ : undefined;
571
+ if (predictionWalled !== undefined) {
572
+ throw attachWrunRefusal(new WrunPredictionMarketBlockedError(`Input '${predictionWalled.name}' (${predictionWalled.sourceClass}) reads by the chart's coin, which ${String(chartExchange)} does not have`), WRUN_PREDICTION_MARKET_REFUSAL_SEED);
573
+ }
574
+ // A CME chart study (`isCmeUserScriptRun`: the gate opened the CME plane to this browser run) computes under the
575
+ // authorisation the wall just read, captured in the same task (cme-user-scripts-gate.util `captureCmeStudyAuth`):
576
+ // a move of the viewer's access since (the account, the CME data terms, the served access, the flag, the session)
577
+ // retires the run (`isCurrent`), and its answer never lands (`assertWrunCmeStudyAuthCurrent`). An OpenMarket
578
+ // package reads CME as first-party: the mark alone, no token.
579
+ if (computed.cme === true && isCmeUserScriptRun(provenance))
580
+ computed.cmeAuth = captureCmeStudyAuth();
475
581
  // The package's provenance, read once beside the wall's door: an OpenMarket package reads the US
476
582
  // options chain of a stock, ETF or OPRA contract chart, and so does a package the viewer wrote or
477
583
  // added from the community while the `opra-user-scripts` flag opens the plane to it
@@ -541,7 +647,14 @@ export async function runWrunOverlayOnChart(target) {
541
647
  }
542
648
  }
543
649
  else {
544
- await computeWrunOverlayOverLiveContext(marketTarget, (runTarget) => computeAndIntegrateWrunOverlay(runTarget, tc, meta, refusal, computed, { chartIndex: target.chartIndex, mountEpoch, tc }, { chartMetadata, isCurrent, official, opraUserScripts }));
650
+ await computeWrunOverlayOverLiveContext(marketTarget, (runTarget) => computeAndIntegrateWrunOverlay(runTarget, tc, meta, refusal, computed, { chartIndex: target.chartIndex, mountEpoch, tc }, {
651
+ chartMetadata,
652
+ isCurrent,
653
+ official,
654
+ opraUserScripts,
655
+ ...(isCmeUserScriptCandidate(provenance) ? { cmeUserStudy: true } : {}),
656
+ ...(options !== undefined ? { options } : {}),
657
+ }));
545
658
  }
546
659
  integrated = true;
547
660
  computed.stage = 'applied';
@@ -627,6 +740,8 @@ export async function runWrunOverlayOnChart(target) {
627
740
  else {
628
741
  await surfaceWrunRunFailureOnLegend(target.chartIndex, target.indicatorId, error, {
629
742
  outputNames,
743
+ opra: computed.opra === true,
744
+ cme: computed.cme === true,
630
745
  refusalContext: refusal.ctx,
631
746
  token: refusalAttempt,
632
747
  isCurrent,
@@ -710,6 +825,74 @@ function wrunRunRejectionAsSettled(error, run) {
710
825
  dropped.cause = WRUN_SUPERSEDED_RUN_CAUSE;
711
826
  return dropped;
712
827
  }
828
+ /** The record seed of a strategy sheet the run head refuses on a CME chart (`WrunStrategyVenueBlockedError`): the CME
829
+ * wall's `strategy` variant ("Strategy testing isn't available on CME markets"), its way out the class's own (switch
830
+ * the market, or the works-on list). */
831
+ const WRUN_CME_STRATEGY_REFUSAL_SEED = Object.freeze({ cls: 'cme-wall', variant: 'strategy' });
832
+ /** The record seed of a sheet the run head refuses on a prediction market (`WrunPredictionMarketBlockedError`, the rule
833
+ * wrunPredictionMarketWalls): the wall family's `prediction` variant, its way out the class's own (switch the market,
834
+ * or the works-on list). */
835
+ const WRUN_PREDICTION_MARKET_REFUSAL_SEED = Object.freeze({ cls: 'cme-wall', variant: 'prediction' });
836
+ /** The `cme-wall` record row of a study the gate's lifecycle stopped in place, by the stopped-study register's reason
837
+ * (cme-user-scripts-gate.util `cmeStudyStopReason`): `stopped` (the viewer's access moved) or `studies-off` (the flag
838
+ * went dark). */
839
+ const WRUN_CME_STOP_VARIANT = Object.freeze({
840
+ 'access-changed': 'stopped',
841
+ 'studies-off': 'studies-off',
842
+ });
843
+ /**
844
+ * The display wall's refusal at the run head for a CME chart study the lifecycle stopped in place: it carries the
845
+ * stopped row's seed (`WRUN_CME_STOP_VARIANT`), the words Door H paints over the same study, so a rerun (a pan, an
846
+ * interval change, an access recheck) reads why it stopped wherever its record is made (the editor console, the
847
+ * loader's catch), never today's wall. Any other wall refusal rides no seed: every reader words it as the wall, as
848
+ * before. The register is main-thread state; a study it holds no row for has none.
849
+ */
850
+ function withCmeStudyStopSeed(error, chartIndex, indicatorId, exchange) {
851
+ if (!payloadTouchesCmeVenue(exchange))
852
+ return error;
853
+ const reason = cmeStudyStopReason(chartIndex, indicatorId);
854
+ return reason === undefined
855
+ ? error
856
+ : attachWrunRefusal(error, { cls: 'cme-wall', variant: WRUN_CME_STOP_VARIANT[reason] });
857
+ }
858
+ /** Whether a run still computes under the authorisation its head captured: always for a run that captured none (every
859
+ * run but a CME chart study), else while the gate's epoch has not moved (`isCmeStudyAuthCurrent`). */
860
+ function wrunCmeStudyAuthStands(computed) {
861
+ return computed.cmeAuth === undefined || isCmeStudyAuthCurrent(computed.cmeAuth);
862
+ }
863
+ /** A CME chart study's answer lands only under the authorisation its head captured: asserted in the task that lands it
864
+ * (the integrate, a prefix page's commit), so an answer from before a move of the viewer's access is dropped as
865
+ * superseded (the quiet WrunChartGoneError: no chip, no toast, nothing applied). A no-op for every other run. */
866
+ function assertWrunCmeStudyAuthCurrent(computed, indicatorId) {
867
+ if (!wrunCmeStudyAuthStands(computed)) {
868
+ throw new WrunChartGoneError(`wrun overlay '${indicatorId}' was superseded during its run (cme-auth)`);
869
+ }
870
+ }
871
+ /** The console provenance a run's outputs carry (`setIndicatorPrintOutputs`): its OPRA fact always, its CME fact only
872
+ * when set, so an output of a run that read no CME reads exactly as before. */
873
+ function wrunRunOutputProvenance(computed) {
874
+ return { opra: computed.opra === true, ...(computed.cme === true ? { cme: true } : {}) };
875
+ }
876
+ /** Whether a venue refusal is the display wall's (its painter stamped the one standing legend message, so the run
877
+ * adds no record, chip or console row of its own): every `WrunVenueBlockedError` but the strategy and the
878
+ * prediction-market refusals, which no painter stands behind and which project their own records (`cme-wall`
879
+ * `strategy`, `prediction`). */
880
+ function isWrunVenueWallPainted(error) {
881
+ return (error instanceof WrunVenueBlockedError &&
882
+ !(error instanceof WrunStrategyVenueBlockedError) &&
883
+ !(error instanceof WrunPredictionMarketBlockedError));
884
+ }
885
+ /** A run's runtime trap row with the run's console provenance on it (`RuntimeDiagnostic.opra` and `.cme`): the row as
886
+ * it is for a run that read neither plane. */
887
+ function wrunTrapRowWithProvenance(trap, provenance) {
888
+ if (provenance.opra !== true && provenance.cme !== true)
889
+ return trap;
890
+ return {
891
+ ...trap,
892
+ ...(provenance.opra === true ? { opra: true } : {}),
893
+ ...(provenance.cme === true ? { cme: true } : {}),
894
+ };
895
+ }
713
896
  /**
714
897
  * The run's failure in the debug ring (`wrun-run-failed`, retained past the ring's cap as an anomaly): the overlay, the
715
898
  * run's reason, the stage it failed in and the error as it reads (its class, its message: a frame the host refused
@@ -757,10 +940,11 @@ function wrunRunSettleOf(error) {
757
940
  }
758
941
  /** Whether a failed run's rejection carries a refusal record: every one but the quiet rejections
759
942
  * whose surface is elsewhere (a chart that is gone or a superseded run, the venue wall's painter,
760
- * the Paused state, a source hold's degrade chip). */
943
+ * the Paused state, a source hold's degrade chip). The strategy refusal on a CME chart carries one:
944
+ * no painter stands behind it (`isWrunVenueWallPainted`). */
761
945
  function wrunRunFailureCarriesRefusal(error) {
762
946
  return (!(error instanceof WrunChartGoneError) &&
763
- !(error instanceof WrunVenueBlockedError) &&
947
+ !isWrunVenueWallPainted(error) &&
764
948
  !isWrunOverlayPausedError(error) &&
765
949
  !isWrunSourceHold(error));
766
950
  }
@@ -788,8 +972,9 @@ export async function surfaceWrunRunFailureOnLegend(chartIndex, indicatorId, err
788
972
  return;
789
973
  // The venue wall's painter already put its standing message on this
790
974
  // legend (and hid the plot): the refusal adds no chip, no console row and
791
- // no Retry of its own, so that message stays the only one.
792
- if (error instanceof WrunVenueBlockedError)
975
+ // no Retry of its own, so that message stays the only one. The strategy
976
+ // refusal on a CME chart has no painter behind it: its record goes on.
977
+ if (isWrunVenueWallPainted(error))
793
978
  return;
794
979
  // The same for a paused overlay (the legend shows Paused) and a source
795
980
  // hold (the degrade registry's chip, FE_SOURCE_LOADING / FE_SOURCE_DEGRADED,
@@ -811,8 +996,9 @@ export async function surfaceWrunRunFailureOnLegend(chartIndex, indicatorId, err
811
996
  const trap = wrunRuntimeTrapDiagnostic(error, context);
812
997
  if (trap && WRUN_RUN_FAILURE_ROW_CODES.has(trap.code)) {
813
998
  // The write waits on the store's module, so the rejection can outrun it: it rides the error, and the
814
- // editor's Run awaits it before it reads the row (wrunErrorFailureRowWritten).
815
- const written = publishWrunRuntimeTrapDiagnostic(chartIndex, indicatorId, trap);
999
+ // editor's Run awaits it before it reads the row (wrunErrorFailureRowWritten). The author's abort text can
1000
+ // carry what the run computed: a run over OPRA or CME data marks the row (every console export strips it).
1001
+ const written = publishWrunRuntimeTrapDiagnostic(chartIndex, indicatorId, wrunTrapRowWithProvenance(trap, context));
816
1002
  annotateWrunErrorFailureRow(error, written);
817
1003
  await written;
818
1004
  if (isCurrent())
@@ -947,6 +1133,19 @@ const WRUN_CRYPTO_VENUE_KINDS = new Set(['crypto', 'dex', 'hip3', 'hip4']);
947
1133
  /** Whether a sheet reads, or may read, an OPRA source lane: a poll lane's `opra`, a row lane's `governed: 'opra'`, a
948
1134
  * chain lane of either kind (its chain lists on OPRA on a US stock or OPRA contract chart). The run head's flag wait,
949
1135
  * the OPRA-plane predicate a lane's admission and wall read, and the OPRA provenance writer follow it. */
1136
+ /** Whether a pin names a market on the OPRA plane: any market its `exchange|symbol` names (a literal pin is one). */
1137
+ function wrunPinReadsOpra(market) {
1138
+ if (market === undefined)
1139
+ return false;
1140
+ return wrunPinMarketsOf(market.exchange ?? '', market.symbol ?? '').some((leg) => payloadTouchesOpraVenue(leg.exchange));
1141
+ }
1142
+ /** Whether a pin names a market on the CME plane (`wrunPinReadsOpra`'s twin): only a CME chart's own family admits one
1143
+ * (the kit refuses a CME pin from any other chart, whoever wrote the package). */
1144
+ function wrunPinReadsCme(market) {
1145
+ if (market === undefined)
1146
+ return false;
1147
+ return wrunPinMarketsOf(market.exchange ?? '', market.symbol ?? '').some((leg) => payloadTouchesCmeVenue(leg.exchange));
1148
+ }
950
1149
  function wrunSheetReadsOpraLane(metadata) {
951
1150
  return wrunPollPlanReadsChain(metadata) || wrunRowPlanReadsChain(metadata);
952
1151
  }
@@ -989,17 +1188,20 @@ function mergeWrunLanePlans(a, b) {
989
1188
  };
990
1189
  }
991
1190
  /** The OPRA-plane predicate an OPRA lane's admission reads (`governedOptionPlane(metadata) === 'opra'`: a US stock or
992
- * ETF chart under either venue spelling while the `opra` flag is lit, an OPRA contract chart) and, beside it, the
993
- * known reason a chart whose options list on OPRA is off the plane (`opraOptionPlaneStop`: the flag check's `flag-off`,
994
- * the plane router's `chart-kind`), which the planners' notes and refusals say instead of "no such feed here". Loaded
995
- * only when the sheet reads such a lane (the gate module reaches the flag store). */
996
- async function wrunOpraPlaneFacts(metadata) {
1191
+ * ETF chart under either venue spelling while the `opra` flag is lit, an OPRA contract chart, a stock twin reading its
1192
+ * stock's chain) and, beside it, the known reason a chart whose options list on OPRA is off the plane
1193
+ * (`opraOptionPlaneStop`: the flag check's `flag-off`, the plane router's `chart-kind`), which the planners' notes and
1194
+ * refusals say instead of "no such feed here". Both judge a market by its exchange and symbol: the run's own chart
1195
+ * market reads the run's one decision (`options`, the head's), never the seam again, and any other market is judged
1196
+ * through the gate. Loaded only when the sheet reads such a lane (the gate module reaches the flag store). */
1197
+ async function wrunOpraPlaneFacts(metadata, options) {
997
1198
  if (!wrunSheetReadsOpraLane(metadata))
998
1199
  return undefined;
999
1200
  const { governedOptionPlane, opraOptionPlaneStop } = await wrunChartHostEnv().market.loadOptionsGate();
1201
+ const decided = (exchange, symbol) => options !== undefined && (options.chart.exchange ?? '') === exchange && (options.chart.symbol ?? '') === symbol;
1000
1202
  return {
1001
- isOpraPlaneExchange: (exchange) => governedOptionPlane({ exchange }) === 'opra',
1002
- opraPlaneStop: (exchange) => opraOptionPlaneStop({ exchange }),
1203
+ isOpraPlaneExchange: (exchange, symbol) => decided(exchange, symbol) ? options?.plane === 'opra' : governedOptionPlane({ exchange, symbol }) === 'opra',
1204
+ opraPlaneStop: (exchange, symbol) => decided(exchange, symbol) ? options?.opraStop : opraOptionPlaneStop({ exchange, symbol }),
1003
1205
  };
1004
1206
  }
1005
1207
  export function isWrunCryptoVenueExchange(exchange) {
@@ -1118,13 +1320,257 @@ function wrunSeededRefusal(seed, details, ctx, stamp) {
1118
1320
  const raised = attachWrunRefusal(new Error(details), seed);
1119
1321
  return wrunRefusalFor(stamp === undefined ? raised : stampWrunRefusalTelemetry(raised, stamp), ctx);
1120
1322
  }
1121
- /** The note rows a run owns (its legs, its health, its skipped draw calls, its respelled pins): a failed run drops
1122
- * them with its verdict. */
1323
+ /** A row lane's read its row budget cut (`onBudgetCut`, wrun-row-lanes.util): the newest bars that fit read whole,
1324
+ * the older ones partial, so the run drew fewer bars of that lane than the chart shows. */
1325
+ export const WRUN_ROW_BUDGET_CUT_CODE = 'WRUN_ROW_BUDGET_CUT';
1326
+ /** The rows the run seam owns for its row budget cuts: replaced by every full run, cleared by a run that cut nothing. */
1327
+ export const WRUN_ROW_BUDGET_ROW_CODES = new Set([WRUN_ROW_BUDGET_CUT_CODE]);
1328
+ /** The legend's localized sentence of a cut over its facts (`{ n }`, the bars kept, its plural choice). */
1329
+ export const WRUN_ROW_BUDGET_CUT_NOTE_KEY = 'wrun.rowBudget.cut';
1330
+ /**
1331
+ * The legend note rows of a run's row budget cuts, one per row lane instance its budget cut: warnings in the run-owned
1332
+ * set `WRUN_ROW_BUDGET_ROW_CODES`, `message` the technical words (Copy details, the console), `details` the facts the
1333
+ * legend's sentence reads (`WRUN_ROW_BUDGET_CUT_NOTE_KEY`: `{ n }`) beside the lane and the cut. A note, never a
1334
+ * refusal: the run drew its newest bars, and without it a package that drew 30 bars of a long chart (Strike
1335
+ * Footprint) said nothing about why. Empty for no cut, which is what clears the rows of an earlier run.
1336
+ */
1337
+ export function wrunRowBudgetCutDiagnostics(cuts) {
1338
+ return [...cuts].map((cut) => ({
1339
+ stage: 'compute',
1340
+ severity: 'warning',
1341
+ code: WRUN_ROW_BUDGET_CUT_CODE,
1342
+ type: 'execution',
1343
+ message: `Row lane '${cut.laneKey}' kept the newest ${cut.keptBars} bars inside its read budget (${cut.maxRows} rows); ` +
1344
+ `${cut.cutBars} older bars read partial, with no cells`,
1345
+ details: {
1346
+ feed: cut.laneKey,
1347
+ n: cut.keptBars,
1348
+ cutBars: cut.cutBars,
1349
+ maxRows: cut.maxRows,
1350
+ ...(cut.keptFromTs !== undefined ? { keptFromTs: cut.keptFromTs } : {}),
1351
+ },
1352
+ }));
1353
+ }
1354
+ /** The indicator download budget's two chips (OPTLOAD W3 R2), the source chip family's run-owned codes
1355
+ * (kscript-source-degrade.util `FE_SOURCE_TRIMMED_CODE`, `FE_SOURCE_HEAVY_CODE`, spelled here because the package
1356
+ * names no web module; tests/utility/wrun/wrun-overlay-run.download-budget.spec.ts pins them equal): replaced by every
1357
+ * full run, cleared by a run that kept its budget. */
1358
+ export const WRUN_DOWNLOAD_TRIMMED_CODE = 'FE_SOURCE_TRIMMED';
1359
+ export const WRUN_DOWNLOAD_HEAVY_CODE = 'FE_SOURCE_HEAVY';
1360
+ export const WRUN_DOWNLOAD_BUDGET_ROW_CODES = new Set([
1361
+ WRUN_DOWNLOAD_TRIMMED_CODE,
1362
+ WRUN_DOWNLOAD_HEAVY_CODE,
1363
+ ]);
1364
+ /** Bytes as the download chips write them, 1,000,000 a MB: "1 MB", "1.2 MB", "17 MB". */
1365
+ export function wrunDownloadMbText(bytes) {
1366
+ const mb = Math.max(0, bytes) / 1_000_000;
1367
+ const text = mb >= 10 ? String(Math.round(mb)) : String(Math.round(mb * 10) / 10);
1368
+ return `${text} MB`;
1369
+ }
1370
+ /** A bar's stamp as the trimmed chip names it, on the UTC clock: "2026-10-22 14:00 UTC". */
1371
+ function wrunDownloadDateText(ts) {
1372
+ const iso = new Date(ts).toISOString();
1373
+ return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
1374
+ }
1375
+ /**
1376
+ * The download budget's legend rows of one full run (R2), info rows in the run-owned set
1377
+ * `WRUN_DOWNLOAD_BUDGET_ROW_CODES`, still text in the source chip family's coverage group (never a spinner, never a
1378
+ * toast; runtime-diagnostics.util words them from `details`, the feeds by `feedKeys` where a lane has feed words):
1379
+ * - `FE_SOURCE_TRIMMED` ("Newest bars only"), when the budget cut a read: the feeds it cut, the oldest bar all of them
1380
+ * still read (`date`, `keptFromTs`: the newest of the cuts' oldest kept bars) and the budget;
1381
+ * - `FE_SOURCE_HEAVY` ("Large download"), when the run downloaded more than its budget and cut nothing (one snapshot):
1382
+ * the feed that downloaded the most, the size and the budget.
1383
+ * Empty with the flag off, or for a run that kept its budget: what clears an earlier run's rows.
1384
+ */
1385
+ export function wrunDownloadBudgetDiagnostics(args) {
1386
+ if (!args.on)
1387
+ return [];
1388
+ const cuts = [...args.cuts].filter((cut) => cut.budget === 'download' && cut.cutBars > 0);
1389
+ const feedFacts = (feeds) => ({
1390
+ feeds: feeds.map((feed) => feed.label).join(', '),
1391
+ feedKeys: feeds.map((feed) => feed.key ?? feed.label),
1392
+ });
1393
+ if (cuts.length > 0) {
1394
+ const named = new Map(cuts.map((cut) => [cut.laneKey, args.feedOf(cut.laneKey)]));
1395
+ const facts = feedFacts([...named.values()]);
1396
+ const kept = cuts.flatMap((cut) => (cut.keptFromTs !== undefined ? [cut.keptFromTs] : []));
1397
+ const keptFromTs = kept.length > 0 ? Math.max(...kept) : undefined;
1398
+ const cutBars = cuts.reduce((sum, cut) => sum + cut.cutBars, 0);
1399
+ const budgetText = wrunDownloadMbText(args.summary?.budgetBytes ?? 1_000_000);
1400
+ return [
1401
+ {
1402
+ stage: 'fetch',
1403
+ severity: 'info',
1404
+ code: WRUN_DOWNLOAD_TRIMMED_CODE,
1405
+ type: 'execution',
1406
+ message: `${facts.feeds}: ${cutBars} older bars were not loaded` +
1407
+ (keptFromTs !== undefined ? ` (before ${wrunDownloadDateText(keptFromTs)})` : '') +
1408
+ `; loading them would download more than the ${budgetText} one indicator may`,
1409
+ details: {
1410
+ ...facts,
1411
+ budget: budgetText,
1412
+ cutBars,
1413
+ ...(keptFromTs !== undefined ? { keptFromTs, date: wrunDownloadDateText(keptFromTs) } : {}),
1414
+ },
1415
+ },
1416
+ ];
1417
+ }
1418
+ const summary = args.summary;
1419
+ if (summary === undefined || !summary.over)
1420
+ return [];
1421
+ const facts = feedFacts([args.feedOf(summary.topSource ?? '')]);
1422
+ const size = wrunDownloadMbText(summary.bytes);
1423
+ const budgetText = wrunDownloadMbText(summary.budgetBytes);
1424
+ return [
1425
+ {
1426
+ stage: 'fetch',
1427
+ severity: 'info',
1428
+ code: WRUN_DOWNLOAD_HEAVY_CODE,
1429
+ type: 'execution',
1430
+ message: `${facts.feeds} downloaded ${size}, more than the ${budgetText} one indicator should`,
1431
+ details: { ...facts, size, budget: budgetText, bytes: summary.bytes },
1432
+ },
1433
+ ];
1434
+ }
1435
+ /** A feed as the download chips name it: a row lane's (by its key, or the K type it asks) label and feed words (the i18n
1436
+ * key the legend says it in), else the source type in words ("orderbook", "volume profile"). */
1437
+ function wrunDownloadFeedOf(laneKeyOrType) {
1438
+ const lane = wrunRowLaneByKey(laneKeyOrType) ?? wrunRowLanes().find((row) => row.kType === laneKeyOrType);
1439
+ if (lane !== undefined)
1440
+ return { label: lane.label, ...(lane.feedWords !== undefined ? { key: lane.feedWords } : {}) };
1441
+ return { label: laneKeyOrType === '' ? 'sources' : laneKeyOrType.replace(/_/g, ' ') };
1442
+ }
1443
+ /** Whether the download budget's cut is on (`FeatureFlag.WrunDownloadBudgetCut`); a host whose flag store is not up
1444
+ * reads off. */
1445
+ export function wrunDownloadBudgetCutOn() {
1446
+ try {
1447
+ return wrunChartHostEnv().user.isFeatureOn(FeatureFlag.WrunDownloadBudgetCut);
1448
+ }
1449
+ catch {
1450
+ return false;
1451
+ }
1452
+ }
1453
+ /** The chart's own celled classes (the row builder's, not a row lane's): history reads the plan shares the budget with,
1454
+ * asked whole for now (the order-flow templates keep their named exceptions; docs/features/kscript/wrun/
1455
+ * wrun-browser-runtime.md, "The download budget"). */
1456
+ const WRUN_DOWNLOAD_BUILTIN_HISTORY_CLASSES = new Set([
1457
+ 'book',
1458
+ 'volume_profile',
1459
+ 'tape',
1460
+ 'intrabar',
1461
+ 'trade_volume_by_size',
1462
+ ]);
1463
+ /**
1464
+ * The run's download plan before any fetch (R2, wrun-download-plan.util): the reads of every input the market demands,
1465
+ * priced with the kit's rule on the run's window and market; a read whose lane forecasts a browser fold
1466
+ * (`WrunRowLaneDescriptor.download.forecastBytes`, FE-FOLD-CAP) priced at the fold's contract rows beside its declared
1467
+ * read, against the chain the chart's options list on (a CME chart's own exchange, the OPRA plane's on a US stock or
1468
+ * ETF chart and on a stock twin reading its stock's chain, a crypto venue's plain chain): the run head's one decision
1469
+ * (`options`) when it holds one, else the chart market judged through the gate. A forecast a refusal stops (an input
1470
+ * refused by name) prices nothing: the plan refuses it by name later.
1471
+ */
1472
+ async function planWrunRunDownload(args) {
1473
+ const { metadata, window, chart } = args;
1474
+ const inputs = [...metadata.inputs]
1475
+ .sort((a, b) => a.index - b.index)
1476
+ .filter((input) => {
1477
+ const source = metadata.inputSources[input.name];
1478
+ return source !== undefined && source.undemanded !== true && source.source !== 'time';
1479
+ });
1480
+ const reads = wrunRunDownloadReads(metadata, { fromMs: window.fromMs, toMs: window.toMs, intervalMs: window.intervalMs }, inputs.map((input) => input.name), (name) => args.paramValues[name]);
1481
+ const market = wrunDownloadMarketOf({ cme: chart.cme, indexMode: chart.indexMode });
1482
+ const priceWindow = { intervalMs: window.intervalMs, market };
1483
+ // The chain the chart's options list on, for a lane's fold forecast (read once, only when a lane forecasts).
1484
+ let chain;
1485
+ const chainOf = () => {
1486
+ chain ??= (async () => {
1487
+ if (chart.cme)
1488
+ return { chainExchange: chart.exchange, servedTier: governedMarketDataTier(chart.exchange) };
1489
+ const plane = args.options !== undefined
1490
+ ? args.options.plane
1491
+ : (await wrunChartHostEnv().market.loadOptionsGate()).governedOptionPlane({
1492
+ exchange: chart.exchange,
1493
+ symbol: chart.symbol,
1494
+ coin: chart.coin,
1495
+ });
1496
+ if (plane === 'opra')
1497
+ return { chainExchange: 'OPRA', servedTier: governedMarketDataTier('OPRA') };
1498
+ return chart.indexMode ? undefined : { chainExchange: chart.exchange };
1499
+ })();
1500
+ return chain;
1501
+ };
1502
+ const params = metadata.params ?? [];
1503
+ const planReads = [];
1504
+ for (const read of reads) {
1505
+ const lane = wrunRowLaneOfClass(read.class);
1506
+ const history = lane !== undefined ? lane.landing.kind !== 'latest' : WRUN_DOWNLOAD_BUILTIN_HISTORY_CLASSES.has(read.class);
1507
+ let projectedBytes;
1508
+ const forecast = lane?.download?.forecastBytes;
1509
+ const inputName = read.inputs[0];
1510
+ const source = inputName === undefined ? undefined : metadata.inputSources[inputName];
1511
+ if (forecast !== undefined && lane !== undefined && source !== undefined && inputName !== undefined) {
1512
+ try {
1513
+ const found = await chainOf();
1514
+ if (found !== undefined) {
1515
+ const chartCtx = {
1516
+ coin: chart.coin,
1517
+ exchange: chart.exchange,
1518
+ symbol: chart.symbol,
1519
+ ...(chart.category !== undefined ? { category: chart.category } : {}),
1520
+ intervalMs: window.intervalMs,
1521
+ inputName,
1522
+ sourceClass: lane.sourceClass,
1523
+ indexMode: chart.indexMode,
1524
+ cryptoVenue: isWrunCryptoVenueExchange(chart.exchange),
1525
+ official: args.facts.official,
1526
+ opraUserScripts: args.facts.opraUserScripts,
1527
+ };
1528
+ // A chain lane forecasts the chain its plan reads, under the run's one decision (a twin's stock by its ticker).
1529
+ const ctx = lane.chain !== undefined ? wrunChainLaneContext(chartCtx, args.options) : chartCtx;
1530
+ const resolved = resolveWrunOptionSettingKnobs(ctx, source, params, args.paramValues);
1531
+ const folded = await forecast(resolved, ctx, {
1532
+ chainExchange: found.chainExchange,
1533
+ coin: ctx.coin,
1534
+ ...(found.servedTier !== undefined ? { servedTier: found.servedTier } : {}),
1535
+ barOpens: window.barOpens,
1536
+ intervalMs: window.intervalMs,
1537
+ barGrid: window.barGrid,
1538
+ nowMs: window.nowMs,
1539
+ });
1540
+ if (folded !== undefined && folded > 0)
1541
+ projectedBytes = wrunDownloadPlanReadBytes(read, priceWindow) + folded;
1542
+ }
1543
+ }
1544
+ catch {
1545
+ // A knob refused by name prices nothing here: the lane's plan refuses the input by name.
1546
+ }
1547
+ }
1548
+ planReads.push({ ...read, history, ...(projectedBytes !== undefined ? { projectedBytes } : {}) });
1549
+ }
1550
+ const mode = wrunRunDownloadMode(planReads, { bars: args.windowBars, ...priceWindow });
1551
+ const keyOfInput = new Map();
1552
+ const barRows = new Map();
1553
+ const interval = wrunDownloadKitInterval(window.intervalMs);
1554
+ for (const read of planReads) {
1555
+ const key = wrunDownloadPlanKeyOf(read);
1556
+ for (const name of read.inputs)
1557
+ keyOfInput.set(name, key);
1558
+ const cost = wrunChartHostEnv().sharedHost().wrunDownloadReadCost(read, market, interval);
1559
+ const rows = cost.readsPerBar * cost.rowsPerRead;
1560
+ if (Number.isFinite(rows) && rows > 0)
1561
+ barRows.set(key, rows);
1562
+ }
1563
+ return { mode, keyOfInput, barRows };
1564
+ }
1565
+ /** The note rows a run owns (its legs, its health, its skipped draw calls, its respelled pins, its row budget cuts, its
1566
+ * download budget's chips): a failed run drops them with its verdict. */
1123
1567
  const WRUN_REFUSAL_NOTE_ROW_CODES = new Set([
1124
1568
  ...WRUN_LEG_ROW_CODES,
1125
1569
  ...WRUN_RUN_HEALTH_ROW_CODES,
1126
1570
  ...WRUN_DRAW_SKIPPED_ROW_CODES,
1127
1571
  ...WRUN_PIN_ROW_CODES,
1572
+ ...WRUN_ROW_BUDGET_ROW_CODES,
1573
+ ...WRUN_DOWNLOAD_BUDGET_ROW_CODES,
1128
1574
  ]);
1129
1575
  /** Whether an output shows on the chart as the settings paint it: the Style page's Visible row,
1130
1576
  * else the sheet's `visible`, the sheet alone for an output a boolean param owns (`owned`); a
@@ -1192,11 +1638,14 @@ const WRUN_SERIES_LANE_FETCH_KEYS = new Map([
1192
1638
  * its ask (never a declined one, `unsettled`), one feed-missing note per lane naming its readers.
1193
1639
  * The run publishes them only when an output went silent over the window.
1194
1640
  */
1195
- function wrunEmptySeriesFeeds(laneRun, unsettled, metadata, cryptoVenue, exchange) {
1641
+ function wrunEmptySeriesFeeds(laneRun, unsettled, metadata, cryptoVenue,
1642
+ // The market each lane was asked on (its acquisition's: the run market on a Trades chart), else the chart's.
1643
+ exchangeOf) {
1196
1644
  return laneRun.outcomes.flatMap(({ lane, outcome }) => {
1197
1645
  const key = WRUN_SERIES_LANE_FETCH_KEYS.get(lane);
1198
1646
  if (key === undefined || outcome.kind !== 'rows' || outcome.rows.length > 0 || unsettled.has(key))
1199
1647
  return [];
1648
+ const exchange = exchangeOf(lane);
1200
1649
  // The lane's own readers: a trades input pinned to another market reads its leg lane instead.
1201
1650
  const readers = wrunInputNamesOfClass(metadata, lane, (source) => !isWrunTradesLegLane(wrunSourceLane(source)));
1202
1651
  const type = WRUN_BUILTIN_LANE_FETCH_TYPES[lane];
@@ -1475,6 +1924,8 @@ async function settleWrunRefusalsOnSuccess(guardKey, target, refusal, chartStand
1475
1924
  try {
1476
1925
  if (chartStands)
1477
1926
  await retractWrunRefusal(target, 'all');
1927
+ if (refusal.superseded)
1928
+ return;
1478
1929
  const watch = setWrunTerminalDegradeWatch(guardKey, target, refusal.degraded);
1479
1930
  const terminal = watch ? wrunTerminalDegradeRefusalOf(guardKey, watch) : undefined;
1480
1931
  if (terminal)
@@ -1492,6 +1943,8 @@ async function settleWrunRefusalsOnSuccess(guardKey, target, refusal, chartStand
1492
1943
  */
1493
1944
  async function settleWrunRefusalsOnHold(guardKey, target, refusal, token, isCurrent) {
1494
1945
  try {
1946
+ if (refusal.superseded)
1947
+ return;
1495
1948
  const watch = setWrunTerminalDegradeWatch(guardKey, target, refusal.degraded);
1496
1949
  const terminal = watch ? wrunTerminalDegradeRefusalOf(guardKey, watch) : undefined;
1497
1950
  if (terminal) {
@@ -1868,6 +2321,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
1868
2321
  if (module === null) {
1869
2322
  throw new Error(`wrun overlay '${passTarget.indicatorId}': its row source holds no module for the browser lanes`);
1870
2323
  }
2324
+ // The browser computes this run under the head's one options market: the facts read beside it follow that decision.
2325
+ if (head.options !== undefined)
2326
+ noteWrunRunOptionsMarket(head.chartMetadata, head.options);
1871
2327
  await orderWrunFirstRunHistoryIfOwed(passTarget, tc, meta, head.chartMetadata, head.isCurrent);
1872
2328
  // The browser lanes read the overlay's own settings, never the record the source holds: a patch it
1873
2329
  // holds carries the same values (the pass derives it from them), and a paint-only save since it
@@ -1925,6 +2381,12 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
1925
2381
  // The open-interest lane's units (`currency` on the `oi` inputs, wrun-oi-lane.util): "Coin" asks the lane in the
1926
2382
  // market's native units, USD asks it exactly as before (no extras); two units refuse by name here.
1927
2383
  const oiLane = wrunOiLaneExtras(target.metadata);
2384
+ // Asked again before the rows leave: a flip onto a tape since the head must not hand that tape's bars over.
2385
+ const candleSource = wrunMainCandleSourceOf(head.chartMetadata);
2386
+ const provenance = view.settings;
2387
+ if (candleSource && isKScriptDisplayBlockedOnExchange(candleSource.exchange, provenance)) {
2388
+ throw new WrunVenueBlockedError(createKScriptVenueBlockedError(candleSource.exchange).message);
2389
+ }
1928
2390
  const loadedRows = wrunChartCandleRows(tc);
1929
2391
  if (loadedRows.length === 0)
1930
2392
  throw new WrunNoBarsError('chart has no candle rows yet');
@@ -1980,6 +2442,10 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
1980
2442
  if (tape !== undefined) {
1981
2443
  await assertWrunTapeServedOnInterval(target.metadata, tape.inputNames[0], typeof chartMetadata?.interval === 'string' ? chartMetadata.interval : '');
1982
2444
  }
2445
+ // The ONE run market, asked only by a sheet over the chart's trades (no other run waits on a ticker's tape answer).
2446
+ const runMarketDecided = wrunSheetReadsRunMarket(target.metadata)
2447
+ ? decideWrunRunMarket(chartMetadata, view.settings)
2448
+ : Promise.resolve(null);
1983
2449
  // A dollar tape (C-DOLLAR) prices its live prints in its history's unit: the dollar unit of the market's own facts
1984
2450
  // (wrunMarketDollarUnit: a CME contract's registry point value, else the point value on a market quoted in dollars).
1985
2451
  // Its reads are the directory row's quote and the instrument registry's units, each waited on once
@@ -2096,14 +2562,16 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2096
2562
  // Timeframe is coarser than the chart computes AT it, on that interval's candles fetched with a
2097
2563
  // warm-up below the chart's first bar, its rows projected onto the chart's bars by the adapter.
2098
2564
  // Read ONCE here: the clock, the rows, the init args, the integrate and the session this run
2099
- // installs (its ticks and reseeds) all follow this stamp. Null keeps the chart's own bars.
2565
+ // installs (its ticks and reseeds) all follow this stamp. Null keeps the chart's own bars. A replay
2566
+ // run reads it too where the run bars ride a session calendar (the chart's session, its symbol and
2567
+ // session type: isWrunRunIntervalSessionMarket), so a twin computes on the live run's bars.
2100
2568
  const chartTransformations = typeof chartMetadata?.transformations === 'string' ? chartMetadata.transformations : undefined;
2101
- const run = overlayWrunRunInterval(target.chartIndex, view, chartInterval, chartExchange, chartTransformations);
2569
+ const run = overlayWrunRunInterval(target.chartIndex, view, chartInterval, chartExchange, chartTransformations, chartMetadata);
2102
2570
  // A replay run on the chart's own bars starts where the kScript replay window does: the candles
2103
2571
  // before the chart's first bar ride the K_OHLCV lane the kScript engine fetches them on (a run at
2104
2572
  // another interval warms up on its run bars, the live rule).
2105
2573
  const replayHeadRows = replay && !run && replay.fromMs < chartRows[0][0]
2106
- ? await fetchWrunReplayHeadRows(target, view, replay.fromMs, chartRows[0][0], download)
2574
+ ? await fetchWrunReplayHeadRows(target, view, replay.fromMs, chartRows[0][0], download, candleSource ?? undefined)
2107
2575
  : [];
2108
2576
  // Joined ahead of the chart's bars with their missing bars kept (a spread drops them).
2109
2577
  chartRows = wrunChartCandleRowsAfterHead(replayHeadRows, chartRows);
@@ -2332,8 +2800,10 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2332
2800
  // The run's OPRA facts reach every lane's plan (`ctx.official`, `ctx.opraUserScripts`): an OPRA lane is refused
2333
2801
  // by name before its plan for a run that may not read the plane (`mayReadOpra`, opra-official-only:<class>).
2334
2802
  // The OPRA-plane predicate an OPRA lane is admitted by (loaded only when the sheet reads one).
2335
- const opraPlaneFacts = wrunOpraPlaneFacts(target.metadata);
2803
+ const opraPlaneFacts = wrunOpraPlaneFacts(target.metadata, head.options);
2336
2804
  const opraFacts = { official: head.official, opraUserScripts: head.opraUserScripts };
2805
+ // Every chain lane plans under the head's one decision: its plane, and a stock twin's lane market (`head.options`).
2806
+ const runOptions = head.options;
2337
2807
  // The overlay's current setting values, read once for both planners: an option knob naming a setting
2338
2808
  // (`min_premium: "@floor"`) asks with the setting's value, and a settings change re-plans with the new one
2339
2809
  // (wrun-poll-lanes.util `resolveWrunOptionSettingKnobs`, before a poll lane's plan and a row lane's facets).
@@ -2349,7 +2819,12 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2349
2819
  symbol: pickText(chartMetadata?.symbol),
2350
2820
  category: chartMetadata?.category,
2351
2821
  intervalMs: clock.intervalMs,
2352
- }, checkIsIndexMode, isWrunCryptoVenueExchange, { ...opraFacts, ...(opraPlane !== undefined ? opraPlane : {}), paramValues: laneParamValues }));
2822
+ }, checkIsIndexMode, isWrunCryptoVenueExchange, {
2823
+ ...opraFacts,
2824
+ ...(opraPlane !== undefined ? opraPlane : {}),
2825
+ paramValues: laneParamValues,
2826
+ ...(runOptions !== undefined ? { options: runOptions } : {}),
2827
+ }));
2353
2828
  };
2354
2829
  // The row lanes' plan (sources/row-lane-registry.ts: one celled descriptor per class), before any of its fetches,
2355
2830
  // beside the poll lanes': the OPRA wall, the chart's admission (a governed OPRA lane where the chart's
@@ -2374,7 +2849,11 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2374
2849
  isCryptoVenueExchange: isWrunCryptoVenueExchange,
2375
2850
  isOpraPlaneExchange: opraPlane?.isOpraPlaneExchange,
2376
2851
  opraPlaneStop: opraPlane?.opraPlaneStop,
2377
- }, { ...opraFacts, paramValues: laneParamValues }));
2852
+ }, {
2853
+ ...opraFacts,
2854
+ paramValues: laneParamValues,
2855
+ ...(runOptions !== undefined ? { options: runOptions } : {}),
2856
+ }));
2378
2857
  };
2379
2858
  const pollPlannedLocal = planPollLanes(false);
2380
2859
  const rowPlannedLocal = planRowLanes(false);
@@ -2387,7 +2866,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2387
2866
  // The options_chain lane's identity (wrunOptionsChainLaneExtrasFor), decided before its own fetch like every plan:
2388
2867
  // a refusal by name fails the run, never reads as a degraded lane.
2389
2868
  const optionsChainPlanned = declaredClasses.has('options_chain')
2390
- ? wrunOptionsChainLaneExtrasFor(target.metadata, chartMetadata, head.official, head.opraUserScripts)
2869
+ ? wrunOptionsChainLaneExtrasFor(target.metadata, chartMetadata, head.official, head.opraUserScripts, laneParamValues, head.options, head.cmeUserStudy === true)
2391
2870
  : Promise.resolve(undefined);
2392
2871
  // The OPRA provenance the native options overlays carry (`settings.metaExchange`, the field the chart read
2393
2872
  // withholds an overlay by and the tier moves refetch it by, options-overlay-provenance.util): every OPRA lane
@@ -2524,6 +3003,18 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2524
3003
  // bars (a grid leg, a trades leg) and opens a live session at the chart's newest bar: a leg's row still forming
2525
3004
  // past that bar lands in it. A replay, a clamped window and a run with no live session have none: their last bar
2526
3005
  // is closed.
3006
+ // A leg pinned to the OPRA plane (an option contract's candles or its trades: a run the flag opened the plane to may
3007
+ // pin one, and the dataFetch door admits it) reads OPRA data like the chart's own market would: the run's console
3008
+ // provenance from here (`computed.opra`), before anything computes. A soft-refused trades leg is never asked.
3009
+ if (legs.some((leg) => wrunPinReadsOpra(leg.market)) ||
3010
+ tradeLegLanes.some((lane) => !softRefusedTradeLegs.has(lane) && wrunPinReadsOpra(wrunTradesLegOf(lane)))) {
3011
+ computed.opra = true;
3012
+ }
3013
+ // The same for a leg on the CME plane (`computed.cme`): a leg the run admitted reads CME data.
3014
+ if (legs.some((leg) => wrunPinReadsCme(leg.market)) ||
3015
+ tradeLegLanes.some((lane) => !softRefusedTradeLegs.has(lane) && wrunPinReadsCme(wrunTradesLegOf(lane)))) {
3016
+ computed.cme = true;
3017
+ }
2527
3018
  const formingBarTs = live && replay === undefined && wrunLandsLegsOnBars(legs, tradeLegLanes)
2528
3019
  ? await wrunFormingBarTsOf(target.chartIndex, clock.intervalMs, chartMetadata)
2529
3020
  : null;
@@ -2540,6 +3031,91 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2540
3031
  // A replay run's lanes reach the window's end (the replay's forward runway, as the kScript
2541
3032
  // engine's sources do), so its steps read them without a fetch; its bars stop at the cutoff.
2542
3033
  const to = replay ? Math.max(chartLastTs, replay.toMs) : chartLastTs;
3034
+ // The download budget's plan (OPTLOAD W3 R2 and FE-FOLD-CAP, `planWrunRunDownload`), behind
3035
+ // `wrun-download-budget-cut` and decided before any lane fetch (`fetchLane` and the row lanes wait on it): at or under
3036
+ // the run's budget the run is whole, today's asks; over it, each history read takes its share and asks its newest
3037
+ // slice first (`rowLaneDownloadOf`). Off, a replay, or a plan that cannot price the sheet: whole, and nothing waits.
3038
+ const downloadBudgetCut = wrunDownloadBudgetCutOn() && replay === undefined;
3039
+ const downloadPlanned = downloadBudgetCut
3040
+ ? (async () => {
3041
+ const barGrid = liveBucketVenueOf(chartMetadata);
3042
+ return planWrunRunDownload({
3043
+ metadata: target.metadata,
3044
+ window: {
3045
+ fromMs: from,
3046
+ toMs: barEndMs(to, clock.intervalMs),
3047
+ intervalMs: clock.intervalMs,
3048
+ barOpens: liveBucketStartsInRange(from, to, clock.intervalMs, barGrid),
3049
+ barGrid,
3050
+ nowMs: clock.nowMs,
3051
+ },
3052
+ // The meter's window: the run's budget is the meter's.
3053
+ windowBars: download.summary().windowBars,
3054
+ chart: {
3055
+ exchange: chartExchange ?? '',
3056
+ coin: chartCoin,
3057
+ symbol: chartSymbol,
3058
+ ...(typeof chartCategory === 'number' ? { category: chartCategory } : {}),
3059
+ cme: isCmeGoverned(chartExchange),
3060
+ indexMode: checkIsIndexMode(chartExchange ?? ''),
3061
+ },
3062
+ paramValues: laneParamValues,
3063
+ facts: { official: head.official, opraUserScripts: head.opraUserScripts },
3064
+ ...(head.options !== undefined ? { options: head.options } : {}),
3065
+ });
3066
+ })().then((plan) => {
3067
+ if (plan.mode.mode === 'budgeted')
3068
+ download.noteBudget({ budgeted: true });
3069
+ if (wrunChartHostEnv().diagnostics.debugEnabled()) {
3070
+ wrunChartHostEnv().diagnostics.debug('wrun-download-plan', {
3071
+ chartIndex: target.chartIndex,
3072
+ indicatorId: target.indicatorId,
3073
+ mode: plan.mode.mode,
3074
+ projectedBytes: Math.round(plan.mode.projectedBytes),
3075
+ budgetBytes: download.budgetBytes,
3076
+ ...(plan.mode.mode === 'budgeted' ? { shares: Object.fromEntries(plan.mode.shares) } : {}),
3077
+ });
3078
+ }
3079
+ return plan;
3080
+ }, (error) => {
3081
+ // The plan is advisory: a sheet it cannot price runs whole, as with the flag off.
3082
+ if (wrunChartHostEnv().diagnostics.debugEnabled()) {
3083
+ wrunChartHostEnv().diagnostics.debug('wrun-download-plan-failed', {
3084
+ chartIndex: target.chartIndex,
3085
+ indicatorId: target.indicatorId,
3086
+ error: error instanceof Error ? error.message : String(error),
3087
+ });
3088
+ }
3089
+ return undefined;
3090
+ })
3091
+ : undefined;
3092
+ // A budgeted run's hold on one row lane instance (wrun-row-lanes.util `WrunRowLaneDownload`): the shares of the
3093
+ // inputs it serves, the rows a bar they declare, the lane's fold cap and the read's own meter beside the run's.
3094
+ const rowLaneDownloadOf = (instance, plan) => {
3095
+ if (plan === undefined || plan.mode.mode !== 'budgeted')
3096
+ return undefined;
3097
+ const lane = wrunRowLaneByKey(instance.laneKey);
3098
+ if (lane === undefined || lane.landing.kind === 'latest')
3099
+ return undefined;
3100
+ const keys = new Set(instance.inputIndexes.flatMap((index) => {
3101
+ const key = plan.keyOfInput.get(inputNameAt(index));
3102
+ return key === undefined ? [] : [key];
3103
+ }));
3104
+ if (keys.size === 0)
3105
+ return undefined;
3106
+ let share = 0;
3107
+ let barRows = 0;
3108
+ for (const key of keys) {
3109
+ share += plan.mode.shares.get(key) ?? 0;
3110
+ barRows = Math.max(barRows, plan.barRows.get(key) ?? 0);
3111
+ }
3112
+ return {
3113
+ share,
3114
+ meter: createWrunLaneDownloadMeter(download),
3115
+ ...(barRows > 0 ? { declaredBarRows: barRows } : {}),
3116
+ ...(lane.download?.fold !== undefined ? { fold: lane.download.fold } : {}),
3117
+ };
3118
+ };
2543
3119
  // The lanes the demanded classes read: a trades input asking `currency: "USD"` reads the buy/sell
2544
3120
  // lane asked in dollars (`trades_usd`), any other the coin lane (`trades`), so a sheet with a
2545
3121
  // units setting fetches each unit it declares, once.
@@ -2560,8 +3136,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2560
3136
  // The trades leg lanes the rule judged unserved on their own market: never dispatched.
2561
3137
  const unservedTradeLegs = new Set();
2562
3138
  const judgeLaneService = (verdicts) => {
2563
- for (const { lane, type, service, holding, inputNames: readers, market } of verdicts) {
2564
- const reason = wrunUnservedLaneReason(type, market?.exchange ?? chartExchange, chartCoin, service);
3139
+ for (const { lane, type, service, holding, inputNames: readers, market, judgedExchange } of verdicts) {
3140
+ // Named by the market the lane was judged on: a leg's own, the run market (a Trades chart's tape), the chart's.
3141
+ const reason = wrunUnservedLaneReason(type, market?.exchange ?? judgedExchange ?? chartExchange, chartCoin, service);
2565
3142
  if (holding !== undefined) {
2566
3143
  const fill = holding.celled ? 'empty' : 'nan';
2567
3144
  // A leg stream reads its leg or nothing (it declares no fill): the market's lane is its only source.
@@ -2600,7 +3177,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2600
3177
  // network decides its verdict (a row lane's class is no admission lane, so the row plan's native classes change no
2601
3178
  // verdict). The options chain's verdict waits for its identity (a governed chain rides its plane's rows on the
2602
3179
  // native-rows path) and is judged right before the chain lane dispatches.
2603
- judgeLaneService(wrunUnservedLanes(target.metadata, { exchange: chartExchange, coin: chartCoin }).filter((verdict) => verdict.lane !== 'options_chain'));
3180
+ // Awaited once here: a class over the chart's trades is judged and asked where they print, never the stored market.
3181
+ const runMarket = await runMarketDecided;
3182
+ judgeLaneService(wrunUnservedLanes(target.metadata, { exchange: chartExchange, coin: chartCoin }, { runMarket }).filter((verdict) => verdict.lane !== 'options_chain'));
2604
3183
  // Each declared source class rides the SAME kScript fetch lane the local
2605
3184
  // engine uses for the original script, so A/B comparisons see one data set.
2606
3185
  // Deadline-raced: a source lane resolves only when its V2 stream completes
@@ -2629,7 +3208,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2629
3208
  fromTs: from,
2630
3209
  window,
2631
3210
  ...(reason === 'settings' && declaredClasses.has('volume_profile')
2632
- ? { volumeProfileGrid: await resolveWrunVolumeProfileGrid(target.chartIndex) }
3211
+ ? { volumeProfileGrid: await resolveWrunVolumeProfileGrid(target.chartIndex, runMarket) }
2633
3212
  : {}),
2634
3213
  });
2635
3214
  const heldCoverage = {};
@@ -2644,6 +3223,24 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2644
3223
  heldCoverage[lane] = held.coveredThroughTs;
2645
3224
  return held.rows;
2646
3225
  };
3226
+ // The market an ask naming no pin of its own reads, by its fetch type (WRUN_RUN_MARKET_READS): nothing else moves.
3227
+ const askMarketOf = (type, payloadExtras) => {
3228
+ if (payloadExtras?.exchange !== undefined || payloadExtras?.symbol !== undefined)
3229
+ return {};
3230
+ const read = wrunRunMarketReadOfFetchType(type);
3231
+ if (read === 'run-market')
3232
+ return runMarket ?? {};
3233
+ if (read !== 'candle-source')
3234
+ return {};
3235
+ const { source, walled } = wrunCandleAskSource(chartMetadata, provenance);
3236
+ if (source === null)
3237
+ return {};
3238
+ // A flip onto a tape the run may not read since the rows handoff walls the ask, as the handoff itself does.
3239
+ if (walled)
3240
+ throw new WrunVenueBlockedError(createKScriptVenueBlockedError(source.exchange).message);
3241
+ // The series ref alone (the main stream's rule): the session, the index mode and the bar grid stay the chart's.
3242
+ return { candleSource: source };
3243
+ };
2647
3244
  const fetchLane = async (type, key, fetchOptions,
2648
3245
  // Lane-specific payload fields beyond the current-market placeholders
2649
3246
  // (the Deribit option-summary lanes key by coin, skew also by delta),
@@ -2654,7 +3251,13 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2654
3251
  // intrabar leg's closes one chart bar past the last row (the forming
2655
3252
  // row's finer bars).
2656
3253
  fromTs = from, toTs = to) => {
2657
- const payload = { symbol: 'currentSymbol', exchange: 'currentExchange', ...payloadExtras };
3254
+ // No ask leaves before the download budget's plan decided the run's mode (R2; absent with the flag off).
3255
+ if (downloadPlanned !== undefined)
3256
+ await downloadPlanned;
3257
+ const meter = fetchOptions?.meter ?? download;
3258
+ // The market every ask naming no pin of its own reads (its acquisition keeps it, so the reconcile and live agree).
3259
+ const askExtras = { ...askMarketOf(type, payloadExtras), ...payloadExtras };
3260
+ const payload = { symbol: 'currentSymbol', exchange: 'currentExchange', ...askExtras };
2658
3261
  const lane = wrunLiveLaneOfFetchKey(key);
2659
3262
  if (lane !== undefined)
2660
3263
  acquisitionByLane[lane] = payload;
@@ -2666,12 +3269,15 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2666
3269
  const own = fetchOptions?.ownFetch === undefined
2667
3270
  ? serveWrunOwnCandles({
2668
3271
  type,
2669
- ...(payloadExtras !== undefined ? { payloadExtras } : {}),
3272
+ payloadExtras: askExtras,
2670
3273
  interval: run && fetchOptions?.interval === undefined ? run.interval : fetchOptions?.interval,
2671
3274
  replay: replay !== undefined,
2672
3275
  fromTs,
2673
3276
  toTs,
2674
3277
  chart: {
3278
+ // The host's candle-source reader reads the chart's metadata whole (a US stock's feed decides whether
3279
+ // its rows came from the tape): the market fields below stand on it.
3280
+ ...chartMetadata,
2675
3281
  exchange: chartExchange,
2676
3282
  symbol: chartSymbol,
2677
3283
  interval: chartInterval,
@@ -2682,7 +3288,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2682
3288
  : null;
2683
3289
  if (own !== null) {
2684
3290
  // The chart's own rows answer the ask: it downloaded nothing.
2685
- download.charge({
3291
+ meter.charge({
2686
3292
  key: `${target.fetchKey}-${key}`,
2687
3293
  kType: type,
2688
3294
  verdict: {
@@ -2712,15 +3318,15 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2712
3318
  // A run at another interval: a source naming no interval of its own rides the run interval
2713
3319
  // (the kScript engine's rule, runIntervalForSource), one naming its own keeps it.
2714
3320
  run && fetchOptions?.interval === undefined
2715
- ? { ...fetchOptions, interval: run.interval, ...sendNotices, meter: download }
2716
- : { ...fetchOptions, ...sendNotices, meter: download });
3321
+ ? { ...fetchOptions, interval: run.interval, ...sendNotices, meter }
3322
+ : { ...fetchOptions, ...sendNotices, meter });
2717
3323
  const label = `wrun source fetch '${type}' for '${target.fetchKey}'`;
2718
3324
  const fetched = await (request === undefined
2719
3325
  ? withWrunDeadline(asked, WRUN_SOURCE_FETCH_DEADLINE_MS, label)
2720
3326
  : raceWrunSendDeadline(asked, request.bound, label));
2721
3327
  // A relay feed's own fetch rides no chart transport and no stamp measures it: its rows are charged their cell bytes.
2722
3328
  if (fetchOptions?.ownFetch) {
2723
- download.charge({ key: `${target.fetchKey}-${key}`, kType: type, ...wrunDownloadAnswerSize(fetched) });
3329
+ meter.charge({ key: `${target.fetchKey}-${key}`, kType: type, ...wrunDownloadAnswerSize(fetched) });
2724
3330
  }
2725
3331
  // Packed-lane SUCCESS arrives as the packed transport object (only the
2726
3332
  // kScript engine worker consumes it un-unpacked); unpack it here, or a
@@ -2988,9 +3594,12 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
2988
3594
  // The native-rows path the leg records (`legs` above): its rows at their own stamps.
2989
3595
  const native = leg.nativeRows === true ? { nativeRows: true } : undefined;
2990
3596
  const { gate, readers } = wrunLegGate(leg, plannedWires);
2991
- // A leg whose bars its venue closes off their open plus the span (a CME session bar) keeps a
2992
- // candle out until its own close.
2993
- const closeMs = wrunLegCandleClose(leg, chartExchange, chartSessionType);
3597
+ // A leg whose bars its venue closes off their open plus the span (a CME session bar, an RTH stub at the session
3598
+ // close) keeps a candle out until its own close.
3599
+ const closeMs = wrunLegCandleClose(leg, chartExchange, chartSessionType, {
3600
+ symbol: chartMetadata?.symbol,
3601
+ interval: clock.intervalMs,
3602
+ });
2994
3603
  const readsLiveCandle = wrunLegReadsLiveCandle(leg, plannedWires);
2995
3604
  // Recorded even for a leg the wall leaves nothing to ask of: the reconcile refreshes the legs it finds here.
2996
3605
  if (readsLiveCandle)
@@ -3012,7 +3621,10 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3012
3621
  // trade-date label, `wrunPrimaryRowBounds`), so the ask starts there, else at the head.
3013
3622
  const headMs = wrunChartHostEnv()
3014
3623
  .sharedHost()
3015
- .wrunLegRowBoundsMs(from, clock.intervalMs, wrunPrimaryRowBounds(chartExchange, clock.intervalMs)).openMs;
3624
+ .wrunLegRowBoundsMs(from, clock.intervalMs, wrunPrimaryRowBounds(chartExchange, clock.intervalMs, {
3625
+ symbol: chartMetadata?.symbol,
3626
+ sessionType: chartSessionType,
3627
+ })).openMs;
3016
3628
  // kScript's ltf(): the chart's window asked whole, the gateway trimming it at the viewer's
3017
3629
  // wall, and a source that fails or answers nothing stored as no rows while the script runs
3018
3630
  // over empty cells (dataManager's failed fetch: `{ data: [], success: false }`, logged). So
@@ -3229,6 +3841,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3229
3841
  // Each row lane that drew its first slice alone, by the slice's first bar: the live session's reconcile never lands
3230
3842
  // rows before it until the fill (`rowLaneFilling`, wrun-live-tick.util `mergeWrunReconcileAnswer`).
3231
3843
  const firstSliceFrom = new Map();
3844
+ // Each row lane instance's read its row budget cut (the latest read's, by instance id): the integrate publishes one
3845
+ // legend note per cut (`wrunRowBudgetCutDiagnostics`).
3846
+ const rowBudgetCuts = new Map();
3232
3847
  // A first slice's shape in the debug ring (`wrun-row-lane-first-slice`): where the slice starts, how many bars it drew
3233
3848
  // from data and how many it holds back as partial until the fill.
3234
3849
  const ringFirstSlice = (lane, rows, sliceFromTs) => {
@@ -3260,27 +3875,77 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3260
3875
  : wrunRowLaneChainAsk(lane, instance.extras, governedMarketDataTier);
3261
3876
  const laneFetch = lane.fetch;
3262
3877
  const tradeDateOf = chartTradeDateOf();
3263
- const rows = await fetchWrunRowLaneRows(lane, extras, tradeDateOf === undefined ? hostGridWindow() : { ...hostGridWindow(), tradeDateOf }, { fromTs: from, toTs: to }, async (askExtras, fromTs, toTs) => ((await fetchLane(lane.kType, instance.key, laneFetch
3264
- ? {
3265
- ownFetch: async (askFrom, askTo) => (await laneFetch({
3266
- extras: askExtras,
3267
- fromTs: askFrom,
3268
- toTs: askTo,
3269
- intervalMs: clock.intervalMs,
3270
- })),
3271
- }
3272
- : wrunRowLaneFetchOptions(lane), { ...askExtras }, fromTs, toTs)) ?? []),
3273
- // The slice's own rows always hold one with data (an empty slice has no early answer), so a lane that must
3274
- // answer rows never paints off an empty one.
3275
- tradeDateOf === undefined || early === undefined || !firstSlicePaint
3276
- ? undefined
3277
- : {
3278
- onFirstSlice: (sliceRows, sliceFromTs) => {
3279
- firstSliceFrom.set(instance.key, sliceFromTs);
3280
- ringFirstSlice(instance.key, sliceRows, sliceFromTs);
3281
- early(sliceRows);
3878
+ // A budgeted run's hold on the read (R2): its share, its slice's declared rows, its fold cap and its own meter.
3879
+ const laneDownload = downloadPlanned === undefined ? undefined : rowLaneDownloadOf(instance, await downloadPlanned);
3880
+ const rows = await fetchWrunRowLaneRows(lane, extras,
3881
+ // A replay run's per-bar lanes end at the replay's cursor (wrun-row-lanes.util `replayCursorMs`).
3882
+ {
3883
+ ...hostGridWindow(),
3884
+ ...(tradeDateOf !== undefined ? { tradeDateOf } : {}),
3885
+ ...(replay !== undefined ? { replayCursorMs: replay.cutoffTs } : {}),
3886
+ }, { fromTs: from, toTs: to }, async (askExtras, fromTs, toTs, whole) => {
3887
+ // The ask's completion for the read's memo (wrun-row-lanes.util `ask`): the chart fetch's verdict, heard on the
3888
+ // download charge it makes at its answer (the read's meter, always bound); none heard is not whole. A lane's own
3889
+ // fetch rides no chart transport (no synthetic completion): its answer is whole once it resolved.
3890
+ let heard;
3891
+ const own = { answered: false };
3892
+ const meter = laneDownload?.meter ?? download;
3893
+ const verdictMeter = {
3894
+ charge: (charge) => {
3895
+ if (charge.verdict !== undefined)
3896
+ heard = charge.verdict;
3897
+ meter.charge(charge);
3282
3898
  },
3283
- });
3899
+ };
3900
+ const rows = (await fetchLane(lane.kType, instance.key, laneFetch
3901
+ ? {
3902
+ ownFetch: async (askFrom, askTo) => {
3903
+ const answered = (await laneFetch({
3904
+ extras: askExtras,
3905
+ fromTs: askFrom,
3906
+ toTs: askTo,
3907
+ intervalMs: clock.intervalMs,
3908
+ }));
3909
+ own.answered = true;
3910
+ return answered;
3911
+ },
3912
+ meter: verdictMeter,
3913
+ }
3914
+ : { ...wrunRowLaneFetchOptions(lane), meter: verdictMeter }, { ...askExtras }, fromTs, toTs)) ?? [];
3915
+ whole?.(own.answered || wrunSourceVerdictWhole(heard));
3916
+ return rows;
3917
+ }, {
3918
+ onBudgetCut: (cut) => {
3919
+ rowBudgetCuts.set(instance.key, cut);
3920
+ // The download budget's cut rides the add's attempt (the bars it left unread, the bytes the run spent so far),
3921
+ // and leaves the warm-up evidence unsettled: an output empty over the bars it left unread is no reason to
3922
+ // buy older candles.
3923
+ if (cut.budget === 'download') {
3924
+ download.noteBudget({ cutBars: cut.cutBars, plannedBytes: download.spentBytes() });
3925
+ unsettledLanes.add(instance.key);
3926
+ }
3927
+ },
3928
+ ...(laneDownload !== undefined ? { download: laneDownload } : {}),
3929
+ // One record per add (wrun-row-lane-add-memo.util), whatever the budget: every run leaves the add a memo of
3930
+ // the bars it landed whole and final, and a later read of the add (a loaded-range refresh, the live start, each
3931
+ // live reconcile) reuses them and asks only the rest. A budgeted run's memo also holds what its budget cut and
3932
+ // spent; a whole run asks the cut bars again. A replay run's read keeps its own memo (`replayCursorMs`).
3933
+ addMemo: {
3934
+ key: wrunRowLaneAddKey(target.chartIndex, target.indicatorId, instance.key),
3935
+ role: 'run',
3936
+ },
3937
+ // The slice's own rows always hold one with data (an empty slice has no early answer), so a lane that must
3938
+ // answer rows never paints off an empty one.
3939
+ ...(tradeDateOf === undefined || early === undefined || !firstSlicePaint
3940
+ ? {}
3941
+ : {
3942
+ onFirstSlice: (sliceRows, sliceFromTs) => {
3943
+ firstSliceFrom.set(instance.key, sliceFromTs);
3944
+ ringFirstSlice(instance.key, sliceRows, sliceFromTs);
3945
+ early(sliceRows);
3946
+ },
3947
+ }),
3948
+ });
3284
3949
  const laneRows = rows;
3285
3950
  return wrunRowLaneRequired(target.metadata, instance)
3286
3951
  ? requireDegradableRows(lane.kType, lane.label, laneRows, instance.key)
@@ -3436,7 +4101,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3436
4101
  const extras = volumeProfileLane !== undefined ? { ...volumeProfileLane } : undefined;
3437
4102
  const [rows, minimumBarHeight] = await Promise.all([
3438
4103
  fetchDegradableLane('volume_profile', 'vp', 'Volume profile', extras),
3439
- resolveWrunVolumeProfileGrid(target.chartIndex),
4104
+ resolveWrunVolumeProfileGrid(target.chartIndex, runMarket),
3440
4105
  ]);
3441
4106
  if (minimumBarHeight !== undefined) {
3442
4107
  acquisitionByLane.volume_profile = { ...acquisitionByLane.volume_profile, minimumBarHeight };
@@ -3474,7 +4139,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3474
4139
  // The options_chain lane dispatches in its own group, once its identity resolved (below).
3475
4140
  etf_flow: etfLanePlan !== undefined ? () => fetchEtfFlowRows(etfLanePlan) : undefined,
3476
4141
  // The trade tape (C2): the K_TRADES lane asked for the large-print table (`large: true`, the
3477
- // TRADE_LARGE type) at the acquisition's facets, the one floor pushed down to the gateway
4142
+ // TRADE_LARGE type) wherever the table holds the market the tape reads, else for the raw tape (a
4143
+ // CME root the collector does not copy: two hours and the raw live channel, wrunTapeLaneExtras),
4144
+ // at the acquisition's facets, the one floor pushed down to the gateway
3478
4145
  // (`minSize` as `minAmount`, a dollar `minValue` as `minQuoteAmount`, C-DOLLAR) and `history`
3479
4146
  // passed as declared: the control serves the history start aligned to the bar inside the
3480
4147
  // chart's window, clamped to the table's 90-day retention. A history of "0" answers EMPTY by
@@ -3485,7 +4152,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3485
4152
  // market facts' dollar unit, so a live print is priced in the history's unit, never guessed)
3486
4153
  // and the reconcile's re-ask.
3487
4154
  tape: tape !== undefined
3488
- ? async () => (await fetchLane('trades', 'tp', undefined, wrunTapeLaneExtras(tape, tapeValuePerUnit))) ?? []
4155
+ ? async () =>
4156
+ // The lane follows the market the tape reads (the run market fetchLane writes, else the chart's).
4157
+ (await fetchLane('trades', 'tp', undefined, wrunTapeLaneExtras(tape, tapeValuePerUnit, runMarket ?? chartMetadata))) ?? []
3489
4158
  : undefined,
3490
4159
  // The trades leg lanes (kit 0.77.0), one thunk per (quote, market): K_BUY_SELL_VOLUME asked on
3491
4160
  // the leg's market in its quote, under the lane id as its fetch key (its own cache entry and
@@ -3674,7 +4343,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3674
4343
  if (extras === undefined)
3675
4344
  return undefined;
3676
4345
  const governed = wrunOptionsChainExtrasGoverned(extras);
3677
- judgeLaneService(wrunUnservedLanes(target.metadata, { exchange: chartExchange, coin: chartCoin }, { nativeLanes: governed ? ['options_chain'] : [] }).filter((verdict) => verdict.lane === 'options_chain'));
4346
+ judgeLaneService(wrunUnservedLanes(target.metadata, { exchange: chartExchange, coin: chartCoin }, { nativeLanes: governed ? ['options_chain'] : [], runMarket }).filter((verdict) => verdict.lane === 'options_chain'));
3678
4347
  if (unservedLanes.includes('options_chain'))
3679
4348
  return undefined;
3680
4349
  await stampWrunOpraProvenance(extras.chainVenue === 'opra');
@@ -3722,6 +4391,18 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3722
4391
  const readsOpraPlane = optionsChainExtras?.chainVenue === 'opra' ||
3723
4392
  pollLanes.some(pollInstanceReadsOpra) ||
3724
4393
  rowLanes.some(rowInstanceReadsOpra);
4394
+ // The plan reads the OPRA plane: the run's console provenance, set before the module computes (`computed.opra`).
4395
+ if (readsOpraPlane)
4396
+ computed.opra = true;
4397
+ // A lane the plans kept on the CME plane (a CME root's chain an OpenMarket package reads, whatever the chart: the
4398
+ // chain wall keeps every other run off it) reads CME data: the run's CME provenance too (`computed.cme`).
4399
+ const gatePlanes = wrunLaneGatePlanes({
4400
+ pollLanes,
4401
+ rowLanes,
4402
+ ...(optionsChainExtras !== undefined ? { optionsChainExtras } : {}),
4403
+ });
4404
+ if ([...gatePlanes.values()].includes('cme'))
4405
+ computed.cme = true;
3725
4406
  const writeOpraProvenance = await opraProvenanceWriter;
3726
4407
  // A degrade entry of a lane this run does not dispatch is settled now: a trades leg the coin switch moved, or a lane
3727
4408
  // a setting gate, a unit pick, `needed_by` or the capability rule dropped. No later run of this sheet asks that lane
@@ -3745,6 +4426,10 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3745
4426
  });
3746
4427
  noteWrunGatePlanesRead(target.chartIndex, target.indicatorId, laneGatePlanes.values());
3747
4428
  const laneRun = await schedule.settled();
4429
+ // A switch keeps the mount and attempt (`isCurrent` stays true) but bumps the data generation; its cancelled reads are no verdict on the new market.
4430
+ const runStands = head.isCurrent() && getChartDataFetchGeneration(target.chartIndex) === planGeneration;
4431
+ if (!runStands)
4432
+ refusal.superseded = true;
3748
4433
  // A degraded lane on a plane another screen holds (stopped at dispatch, or the latch came while its read was out)
3749
4434
  // stopped for that reason: it says so, and no ladder re-asks it (only the take-back serves it).
3750
4435
  const gateStops = new Map(laneRun.degraded.flatMap(({ lane, outcome }) => {
@@ -3784,7 +4469,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3784
4469
  }),
3785
4470
  }));
3786
4471
  for (const { lane, outcome } of laneRun.outcomes) {
3787
- if (outcome.kind === 'rows')
4472
+ if (runStands && outcome.kind === 'rows')
3788
4473
  wrunChartHostEnv().chart.markSourceRecovered(guardKey, lane);
3789
4474
  }
3790
4475
  // The row lanes that answered their first-paint slice alone (`firstSlicePaint`): their older bars are still out, a
@@ -3802,6 +4487,8 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3802
4487
  }));
3803
4488
  for (const entry of degraded) {
3804
4489
  unsettledLanes.add(entry.lane);
4490
+ if (!runStands)
4491
+ continue;
3805
4492
  wrunChartHostEnv().chart.markSourceDegraded(guardKey,
3806
4493
  // A picture stays up (this run's, or the last good one a hold keeps):
3807
4494
  // the chip says the source is missing from it; with nothing drawn yet
@@ -3854,7 +4541,7 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
3854
4541
  // A replay run's run bars as of its cutoff: the closed ones as fetched, the forming one folded
3855
4542
  // from the completed chart bars in its bucket (the fetched one holds trades past the playhead).
3856
4543
  const runBars = replay && run && fetchedRunBars
3857
- ? wrunReplayRunBars(fetchedRunBars, replayChartRows, replay.cutoffTs, run.intervalMs, chartIntervalMs)
4544
+ ? wrunReplayRunBars(fetchedRunBars, replayChartRows, replay.cutoffTs, run, chartIntervalMs)
3858
4545
  : fetchedRunBars;
3859
4546
  // The primary rows: the chart's candles, or the run bars the package computes over (with wait
3860
4547
  // for close on, the closed ones only: wrunRunIntervalComputeRows). A replay run's newest chart
@@ -4058,7 +4745,10 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
4058
4745
  // (`wrunSessionClock`: the candle closes and opens of the legs whose venue closes a bar off its
4059
4746
  // open plus the span, CME or a US listing on regular hours, and the bounds of the chart's own
4060
4747
  // CME session rows).
4061
- session: wrunChartSession(chartExchange, chartSessionType),
4748
+ session: wrunChartSession(chartExchange, chartSessionType, {
4749
+ symbol: chartMetadata?.symbol,
4750
+ interval: clock.intervalMs,
4751
+ }),
4062
4752
  // The chart's market at the run's interval: the `time.trade_date` / `time.session` facts are read for it.
4063
4753
  venue: wrunBarVenueOf(chartMetadata, clock.intervalMs),
4064
4754
  // A leg's row still forming past the chart's newest bar lands in the forming bar (a live run's alone).
@@ -4091,7 +4781,9 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
4091
4781
  await marketFactsReady;
4092
4782
  if (earningsFactsReady !== undefined)
4093
4783
  await earningsFactsReady;
4094
- const hostFill = wrunHostFillContextFor(tc, chartMetadata?.exchange, clock.intervalMs, wrunReadsMarketFacts(target.metadata) ? chartMetadata : undefined, wrunReadsEarningsFacts(target.metadata) ? chartMetadata : undefined);
4784
+ const hostFill = wrunHostFillContextFor(tc, chartMetadata?.exchange, clock.intervalMs,
4785
+ // The option multiplier follows the chain this run reads (the head's one options market).
4786
+ wrunReadsMarketFacts(target.metadata) ? wrunRunFactsMarket(chartMetadata, head.options) : undefined, wrunReadsEarningsFacts(target.metadata) ? chartMetadata : undefined);
4095
4787
  // The generation this run computes with (C1): the params, the init args and the text settings
4096
4788
  // are read under it in this synchronous block, after the lanes fetched.
4097
4789
  computed.generation = kScriptSettingsRevision(view.settings);
@@ -4277,6 +4969,11 @@ async function prepareWrunSandboxRun(passTarget, tc, meta, refusal, computed, ow
4277
4969
  // The pin step's notes and respelled pins: the integrate publishes the notes and lays the pins on its paint.
4278
4970
  pinNotes,
4279
4971
  respelledPins,
4972
+ // The row budget's cuts of this run's row lane reads: the integrate publishes one note per cut (the download
4973
+ // budget's, `budget: 'download'`, as the trimmed chip).
4974
+ rowBudgetCuts,
4975
+ // The download budget's cut was on for this run (R2): the integrate publishes its chips.
4976
+ downloadBudgetCut,
4280
4977
  };
4281
4978
  }
4282
4979
  /** The refusal seed of an ask its row source merged nothing from (`WrunRowSourceTransientError`): the run
@@ -4728,6 +5425,25 @@ function stopWrunHeldRowSourceRouting(chartIndex, indicatorId) {
4728
5425
  }
4729
5426
  /** Specs only: forget every held source (none is released), the socket's losses and the pending asks (none is
4730
5427
  * cancelled). */
5428
+ /** The sheet draws price canvases (a heatmap or a profile): their cells are the session's to hand a rebuild. */
5429
+ function wrunSheetDrawsCanvases(metadata) {
5430
+ return (metadata.heatmaps?.length ?? 0) > 0 || (metadata.profiles?.length ?? 0) > 0;
5431
+ }
5432
+ /** The context holds lane buffers a rebuild reads the price canvases' cells from (wrunCellRowsOf). */
5433
+ function wrunHoldsCanvasCells(context) {
5434
+ return (context.bookRows !== undefined || context.volumeProfileRows !== undefined || context.intrabarRows !== undefined);
5435
+ }
5436
+ /** Spec seam: hold `source` as the overlay's row source (as a landed cloud run does), so a spec can reach what
5437
+ * reads the held source without running one. */
5438
+ export function __holdWrunRowSourceForTests(indicatorId, source) {
5439
+ wrunHeldRowSources.set(indicatorId, {
5440
+ source,
5441
+ identity: {},
5442
+ settings: {},
5443
+ slot: { run: {} },
5444
+ routes: true,
5445
+ });
5446
+ }
4731
5447
  export function __resetWrunHeldRowSourcesForTests() {
4732
5448
  wrunHeldRowSources.clear();
4733
5449
  __resetWrunSocketSessionLossesForTests();
@@ -4881,10 +5597,13 @@ async function computeAndIntegrateWrunOverlay(runTarget, tc, meta, refusal, comp
4881
5597
  // The run produced rows: its debug log reaches the editor console now, before the render
4882
5598
  // verdict, the way a kScript run's print() output does (a refused integrate or render charge
4883
5599
  // still shows the lines that explain it). A hidden head's rows are cut first (D4): the log
4884
- // reads the landed rows, as everything after it does.
5600
+ // reads the landed rows, as everything after it does. A CME chart study whose authorisation moved since its head
5601
+ // publishes nothing: its integrate drops it as superseded (`assertWrunCmeStudyAuthCurrent`).
4885
5602
  answered: (rows) => {
5603
+ if (!wrunCmeStudyAuthStands(computed))
5604
+ return Promise.resolve();
4886
5605
  const ran = host.prepared;
4887
- return publishWrunDebugOutput(runTarget.chartIndex, runTarget.indicatorId, ran.request.metadata, wrunSandboxLandedRows(ran, rows));
5606
+ return publishWrunDebugOutput(runTarget.chartIndex, runTarget.indicatorId, ran.request.metadata, wrunSandboxLandedRows(ran, rows), wrunRunOutputProvenance(computed));
4888
5607
  },
4889
5608
  };
4890
5609
  const record = wrunRowSourceRecordOf(runTarget.metadata, meta);
@@ -4923,7 +5642,7 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
4923
5642
  await integrateWrunRowSourceBatch(runTarget, tc, meta, refusal, computed, owner, head, ask, batch);
4924
5643
  return;
4925
5644
  }
4926
- const { acquisitionByLane, writeOpraProvenance, readsOpraPlane, bookRows, buySellVolumeRows, buySellVolumeUsdRows, chartExchange, chartFirstTs, chartInterval, chartIntervalMs, chartMetadata, chartNames, chartRows, clampedLegs, clock, computeIdentity, computeSourceRows, cryptoVenue, degraded, emptyLegs, etfFlowRows, evaluatedCandles, fetchedRunBars, fillingFrom, fillingLanes, formingPreRoll, from, fundingRateRows, generationAtStart, hasGoodResult, hasIntrabarLegs, hasLiveCandleLegs, hasPinnedLegs, headWarm, heldCoverage, impliedVolatilityRows, initArgs, intrabarRows, laneHead, laneRun, legs, liquidationRows, live, loadedRows, marketIdentity, missingFeeds, ohlcvRows, openInterestRows, optionsChainRows, paramValues, pinnedCandleRows, pinnedLiveCandleRows, planGeneration, pollLaneRows, pollLanes, rowLaneRows, rowLanes, projection, reason, replay, replayChartRows, replayHeadRows, retainedRowsCap, retainedWindow, rows, run, runBars, runBlockRowsCap, runKey, runRowsPlan, skewRows, strategy, tapeRows, target, textParams, to, tradeLegRows, tradeVolumeBySizeRows, twinAtChart, unservedLanes, unservedLegs, unservedTradeLegs, unsettledLanes, volumeProfileRows, warmupBarsNow, warmupHead, warmupMiss, warmupWall, window, headsDeferred, epoch: generation, pinNotes, respelledPins, } = prepared;
5645
+ const { acquisitionByLane, writeOpraProvenance, readsOpraPlane, bookRows, buySellVolumeRows, buySellVolumeUsdRows, chartExchange, chartFirstTs, chartInterval, chartIntervalMs, chartMetadata, chartNames, chartRows, clampedLegs, clock, computeIdentity, computeSourceRows, cryptoVenue, degraded, emptyLegs, etfFlowRows, evaluatedCandles, fetchedRunBars, fillingFrom, fillingLanes, formingPreRoll, from, fundingRateRows, generationAtStart, hasGoodResult, hasIntrabarLegs, hasLiveCandleLegs, hasPinnedLegs, headWarm, heldCoverage, impliedVolatilityRows, initArgs, intrabarRows, laneHead, laneRun, legs, liquidationRows, live, loadedRows, marketIdentity, missingFeeds, ohlcvRows, openInterestRows, optionsChainRows, paramValues, pinnedCandleRows, pinnedLiveCandleRows, planGeneration, pollLaneRows, pollLanes, rowLaneRows, rowLanes, projection, reason, replay, replayChartRows, replayHeadRows, retainedRowsCap, retainedWindow, rows, run, runBars, runBlockRowsCap, runKey, runRowsPlan, skewRows, strategy, tapeRows, target, textParams, to, tradeLegRows, tradeVolumeBySizeRows, twinAtChart, unservedLanes, unservedLegs, unservedTradeLegs, unsettledLanes, volumeProfileRows, warmupBarsNow, warmupHead, warmupMiss, warmupWall, window, headsDeferred, epoch: generation, pinNotes, respelledPins, rowBudgetCuts, downloadBudgetCut, } = prepared;
4927
5646
  // The filling chip (`fillingLanes`, a first-slice picture): raised right before the integrate, lowered if the run
4928
5647
  // fails after it.
4929
5648
  const fillingGuardKey = overlayExecutionGuardKey(target.chartIndex, target.indicatorId);
@@ -5012,6 +5731,8 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5012
5731
  });
5013
5732
  fillingRaised = true;
5014
5733
  }
5734
+ // A CME chart study lands only under the authorisation its head captured, judged in the task that applies it.
5735
+ assertWrunCmeStudyAuthCurrent(computed, target.indicatorId);
5015
5736
  const runSerial = nextWrunCanvasRunSerial(target.indicatorId);
5016
5737
  const integration = integrateWrunRunThroughRoute({
5017
5738
  ...integrateOptions,
@@ -5107,7 +5828,12 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5107
5828
  // lower-pane children mounted): nested output visibility from the sheet
5108
5829
  // and the Style page, and the latest-values snapshot the HUD, the legend
5109
5830
  // and the hover inspector read.
5110
- presentWrunIntegration(target.chartIndex, target.indicatorId, sheetNow, meta.settings, outputRows, tc, initArgs, chartNames, run);
5831
+ presentWrunIntegration(target.chartIndex, target.indicatorId, sheetNow, meta.settings, outputRows, tc, initArgs, chartNames, run, 'run',
5832
+ // The result the chart shows: applied, or skipped as rendering equal to the mount. Any other skip (a transient
5833
+ // empty answer, nothing to paint) and a sparse run the mounted rows outranked keep the previous picture.
5834
+ integration.applied || (route.action === 'skip' && route.reason === 'render-equal')
5835
+ ? { emptyTargets: runResult.emptyTargets, partial: window?.partial === true }
5836
+ : undefined);
5111
5837
  await publishWrunStrategyRunResult(target.chartIndex, target.indicatorId, runResult, { tc, meta });
5112
5838
  // A run that drew nothing says so: every bar warm-up, or a line NaN on every ready bar,
5113
5839
  // used to print the green check over an empty pane. Published on EVERY run (WRUN-REFUSALS
@@ -5118,7 +5844,10 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5118
5844
  // only the outputs a viewer sees are watched, and none while a source the run reads is absent
5119
5845
  // on this market (its own note says so once).
5120
5846
  const draft = isWrunDraftOverlaySettings(meta.settings);
5121
- const emptySeries = wrunEmptySeriesFeeds(laneRun, unsettledLanes, target.metadata, cryptoVenue, chartExchange);
5847
+ const emptySeries = wrunEmptySeriesFeeds(laneRun, unsettledLanes, target.metadata, cryptoVenue, (lane) => {
5848
+ const asked = acquisitionByLane[lane]?.exchange;
5849
+ return typeof asked === 'string' && asked !== 'currentExchange' ? asked : chartExchange;
5850
+ });
5122
5851
  // A source counts as absent only when it says so itself (a feed-missing note, the degrade chip,
5123
5852
  // a leg note, the empty-series note): an empty window with no note of its own (a quiet
5124
5853
  // liquidations window, a loaded-empty ETF day) never hides an unrelated silent output.
@@ -5147,6 +5876,19 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5147
5876
  ...wrunEmptyLegDiagnostics(emptyLegs, refusal.ctx),
5148
5877
  ...wrunFeedMissingDiagnostics([...missingFeeds, ...(watched.silentOutputs.length > 0 ? emptySeries : [])], refusal.ctx),
5149
5878
  ]);
5879
+ // A row lane's read its budget cut says so: one note per cut ("Older bars cut by the read budget: showing the
5880
+ // newest N bars"), replaced by every full run and cleared by a run that cut nothing. A read the download budget cut
5881
+ // instead says so through the trimmed chip below (the smaller cut wins, one note per read).
5882
+ const budgetCuts = [...rowBudgetCuts.values()];
5883
+ await publishWrunOwnedDiagnostics(target.chartIndex, target.indicatorId, WRUN_ROW_BUDGET_ROW_CODES, wrunRowBudgetCutDiagnostics(budgetCuts.filter((cut) => cut.budget !== 'download')));
5884
+ // The download budget's chip (R2, behind its flag): "Newest bars only" when it cut a read, "Large download" when
5885
+ // the run passed its budget with nothing to cut; replaced by every full run and cleared by one that kept it.
5886
+ await publishWrunOwnedDiagnostics(target.chartIndex, target.indicatorId, WRUN_DOWNLOAD_BUDGET_ROW_CODES, wrunDownloadBudgetDiagnostics({
5887
+ on: downloadBudgetCut,
5888
+ cuts: budgetCuts,
5889
+ summary: computed.download?.summary(),
5890
+ feedOf: wrunDownloadFeedOf,
5891
+ }));
5150
5892
  // A pinned market the run respelled says so (one note per spelling, the saved value unchanged), replaced by
5151
5893
  // every run and cleared by a run that respelled nothing.
5152
5894
  await publishWrunOwnedDiagnostics(target.chartIndex, target.indicatorId, WRUN_PIN_ROW_CODES, wrunPinRespelledDiagnostics(pinNotes));
@@ -5197,12 +5939,16 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5197
5939
  // asking its tail while the source ladder owns the window.
5198
5940
  const degradedLanes = new Set(degraded.map((entry) => entry.lane));
5199
5941
  const coveredThroughTs = {};
5942
+ // A replay run read its flow and snapshot row lanes through its cursor (wrun-row-lanes.util `replayCursorMs`):
5943
+ // their coverage is the cursor, and each replay step extends them from there (wrun-live-tick.util).
5944
+ const replayBound = replay === undefined ? undefined : wrunRowLanesReplayBounded(rowLanes);
5200
5945
  for (const lane of Object.keys(acquisitionByLane)) {
5201
5946
  if (degradedLanes.has(lane))
5202
5947
  continue;
5203
5948
  // A held lane keeps its session's watermark (the reconcile re-asks from there).
5204
5949
  const heldThrough = heldCoverage[lane];
5205
- coveredThroughTs[lane] = heldThrough !== undefined ? Math.min(heldThrough, to) : to;
5950
+ const laneTo = replay !== undefined && replayBound?.has(lane) === true ? Math.min(to, replay.cutoffTs) : to;
5951
+ coveredThroughTs[lane] = heldThrough !== undefined ? Math.min(heldThrough, laneTo) : laneTo;
5206
5952
  }
5207
5953
  // A leg's coverage is the clock the run fetched under: every candle
5208
5954
  // closed by then is in the buffer (the forming one is dropped).
@@ -5210,6 +5956,9 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5210
5956
  const liveContext = {
5211
5957
  chartIndex: target.chartIndex,
5212
5958
  indicatorId: target.indicatorId,
5959
+ // The run's console provenance: every debug line the session's ticks and reseeds publish states it.
5960
+ ...(computed.opra === true ? { opraRead: true } : {}),
5961
+ ...(computed.cme === true ? { cmeRead: true } : {}),
5213
5962
  // The current paint (above): the ticks and the reseeds keep the look.
5214
5963
  metadata: sheetNow,
5215
5964
  title: target.title,
@@ -5221,6 +5970,10 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5221
5970
  fetchKey: target.fetchKey,
5222
5971
  outputRows,
5223
5972
  computeIdentity,
5973
+ // The version this run executed and the settings revision it computed with: the switch's stand-in capture
5974
+ // stores the picture only under that pin and while the row still carries that revision.
5975
+ version: target.version,
5976
+ settingsRevision: computed.generation,
5224
5977
  draft,
5225
5978
  runHealthWarned,
5226
5979
  marketIdentity,
@@ -5455,7 +6208,7 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5455
6208
  const session = live ? getWrunOverlayLiveContext(target.indicatorId) : undefined;
5456
6209
  if (session !== undefined) {
5457
6210
  // A live session: its CURRENT rows and buffers (ticks moved them since the run), under its lock.
5458
- await withWrunOverlaySessionLock(target.indicatorId, () => reintegrateWrunSessionCanvases(target.indicatorId, session, fill, () => wrunTpoRefineCurrent(request)));
6211
+ await withWrunOverlaySessionLock(target.indicatorId, () => reintegrateWrunSession(target.indicatorId, session, fill, () => wrunTpoRefineCurrent(request)));
5459
6212
  return;
5460
6213
  }
5461
6214
  // A wrun run never draws over replay rows (the run's own replay lock).
@@ -5480,7 +6233,9 @@ async function integrateWrunRunAsk(runTarget, tc, meta, refusal, computed, owner
5480
6233
  return;
5481
6234
  }
5482
6235
  await publishWrunCanvasNotices(target.chartIndex, target.indicatorId, refined);
5483
- presentWrunIntegration(target.chartIndex, target.indicatorId, sheetAtRefine, mounted.settings, outputRows, chart, initArgs, chartNames, run);
6236
+ presentWrunIntegration(target.chartIndex, target.indicatorId, sheetAtRefine, mounted.settings, outputRows, chart, initArgs, chartNames, run,
6237
+ // A later refine of this run's rows: a full run refused since keeps its snapshot.
6238
+ 'republish', { emptyTargets: refined.emptyTargets, partial: window?.partial === true });
5484
6239
  },
5485
6240
  };
5486
6241
  scheduleWrunTpoBlockRefine(request);
@@ -5768,6 +6523,16 @@ async function persistWrunSourceDecidedSide(chartIndex, tc, indicatorId, meta, s
5768
6523
  console.warn(`[wrun] the side of '${indicatorId}' was not persisted on its record:`, error);
5769
6524
  }
5770
6525
  }
6526
+ /** The receipt a cloud batch's legend word reads (contract opra-server-lanes C4): the receipt of the rows the batch was
6527
+ * computed from, only while the batch carries the OPRA mark (a result without it is a re-plan off OPRA: no word). */
6528
+ function wrunBatchOpraServed(batch) {
6529
+ return batch.opra === true ? batch.opraServed : undefined;
6530
+ }
6531
+ /** The context field a Cloud session installs with: its receipt (`wrunBatchOpraServed`), or none. */
6532
+ function withWrunCloudOpraServed(batch) {
6533
+ const served = wrunBatchOpraServed(batch);
6534
+ return served !== undefined ? { cloudOpraServed: { ...served } } : {};
6535
+ }
5771
6536
  /**
5772
6537
  * A batch no browser lane prepared (contract C7: the socket row source's, which the cloud
5773
6538
  * computed) integrates from the batch and the chart alone, through the steps every batch takes:
@@ -5836,7 +6601,9 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
5836
6601
  const delivered = wrunRowBatchDeliveredSheet(batch.sheet ?? runTarget.metadata, batch.refusals, sectionKinds);
5837
6602
  if (wrunReadsMarketFacts(delivered))
5838
6603
  await warmWrunMarketFacts(chartMetadata);
5839
- const hostFill = wrunHostFillContextFor(tc, chartExchange, chartIntervalMs, wrunReadsMarketFacts(delivered) ? chartMetadata : undefined);
6604
+ const hostFill = wrunHostFillContextFor(tc, chartExchange, chartIntervalMs,
6605
+ // No browser lane prepared this batch (contract C7): the cloud computed it off the chart's own market's facts.
6606
+ wrunReadsMarketFacts(delivered) ? wrunCloudFactsMarket(chartMetadata) : undefined);
5840
6607
  const chartNames = await resolveWrunChartNames(chartIndex);
5841
6608
  const canvasFill = wrunCanvasFillWithSessionBlock(await wrunCanvasHostFillFor(delivered, chartMetadata), delivered, indicatorId, chartMetadata);
5842
6609
  const identityLeft = await wrunRunIdentityLeft(chartIndex, tc, meta, marketIdentity);
@@ -5861,6 +6628,9 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
5861
6628
  if (batch.opra === true && !(writeOpraProvenance?.(true) === true && wrunOverlayOpraStamped(meta))) {
5862
6629
  throw new WrunChartGoneError(`wrun overlay '${indicatorId}' left its chart before its OPRA provenance was stamped (superseded)`);
5863
6630
  }
6631
+ // The cloud read OPRA for these rows (its mark): the run's console provenance from here (`computed.opra`).
6632
+ if (batch.opra === true)
6633
+ computed.opra = true;
5864
6634
  const heldContext = getWrunOverlayLiveContext(indicatorId);
5865
6635
  const window = runTarget.window;
5866
6636
  nextWrunCanvasRunSerial(indicatorId);
@@ -5879,6 +6649,10 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
5879
6649
  fills: runTarget.fills,
5880
6650
  candles: runTarget.candles,
5881
6651
  chartNames,
6652
+ // The legend's served word is the receipt of the rows the cloud computed this batch from (contract
6653
+ // opra-server-lanes C4), as a browser run's is its acquisition records': none for a batch without the mark (a
6654
+ // re-plan off OPRA clears it) or naming no tier, never the account's tier.
6655
+ legendNote: wrunOverlayLegendNote(meta.settings, undefined, undefined, wrunBatchOpraServed(batch)),
5882
6656
  // The market's size unit (an output its `visible_by` leaves out here mounts nothing) and its dollar unit, as on
5883
6657
  // the own run.
5884
6658
  ...wrunResultMarketUnits(chartMetadata),
@@ -5931,16 +6705,21 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
5931
6705
  // The stamp stands until a later result can clear it.
5932
6706
  }
5933
6707
  }
5934
- presentWrunIntegration(chartIndex, indicatorId, sheetNow, meta.settings, outputRows, tc, wrunSourceInitArgsOf(sheetNow, paramValues), chartNames, null);
6708
+ presentWrunIntegration(chartIndex, indicatorId, sheetNow, meta.settings, outputRows, tc, wrunSourceInitArgsOf(sheetNow, paramValues), chartNames, null, 'run',
6709
+ // The picture the chart shows, as on the browser lane (integrateWrunRunAsk).
6710
+ integration.applied || (route.action === 'skip' && route.reason === 'render-equal')
6711
+ ? { emptyTargets: runResult.emptyTargets, partial: window?.partial === true }
6712
+ : undefined);
5935
6713
  await publishWrunStrategyRunResult(chartIndex, indicatorId, runResult, { tc, meta });
5936
- await publishWrunDebugOutput(chartIndex, indicatorId, sheetNow, outputRows);
6714
+ await publishWrunDebugOutput(chartIndex, indicatorId, sheetNow, outputRows, wrunRunOutputProvenance(computed));
5937
6715
  const draft = isWrunDraftOverlaySettings(meta.settings);
5938
6716
  const { health } = wrunChartRunHealth(sheetNow, meta.settings, outputRows, false, wrunChartSizeUnit(chartMetadata));
5939
6717
  const runHealthWarned = await publishWrunRunHealth(chartIndex, indicatorId, wrunRunHealthRowsFor(health, draft, wrunNothingReadyRefusal(health, refusal.ctx)));
5940
- // A run computed elsewhere served every leg it read: no leg note of an earlier run stands, and no pin note
5941
- // this lane respelled (the cloud resolves its own pins).
6718
+ // A run computed elsewhere served every leg it read: no leg note of an earlier run stands, no pin note this
6719
+ // lane respelled (the cloud resolves its own pins), and no row budget cut of a browser read.
5942
6720
  await publishWrunUnservedLegDiagnostics(chartIndex, indicatorId, []);
5943
6721
  await publishWrunOwnedDiagnostics(chartIndex, indicatorId, WRUN_PIN_ROW_CODES, []);
6722
+ await publishWrunOwnedDiagnostics(chartIndex, indicatorId, WRUN_ROW_BUDGET_ROW_CODES, []);
5944
6723
  const indicatorName = typeof delivered.name === 'string' ? delivered.name : '';
5945
6724
  await publishWrunSourceVerdict(chartIndex, indicatorId, meta, batch, indicatorName);
5946
6725
  await publishWrunCanvasNotices(chartIndex, indicatorId, runResult);
@@ -6028,6 +6807,8 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
6028
6807
  fetchKey: runTarget.fetchKey,
6029
6808
  outputRows: sessionRows,
6030
6809
  computeIdentity,
6810
+ version: runTarget.version,
6811
+ settingsRevision: computed.generation,
6031
6812
  draft,
6032
6813
  runHealthWarned,
6033
6814
  marketIdentity,
@@ -6037,6 +6818,11 @@ async function integrateWrunRowSourceBatch(asked, tc, meta, refusal, computed, o
6037
6818
  generation: nextWrunOverlayLiveGeneration(indicatorId),
6038
6819
  intervalMs: chartIntervalMs,
6039
6820
  acquisition: {},
6821
+ // The receipt the session holds now (its newest answer's): every tick's legend word reads it.
6822
+ ...withWrunCloudOpraServed(session ?? batch),
6823
+ // The run's console provenance: every debug line the session's ticks publish states it.
6824
+ ...(computed.opra === true ? { opraRead: true } : {}),
6825
+ ...(computed.cme === true ? { cmeRead: true } : {}),
6040
6826
  carrySeed: emptyWrunInputCarry(),
6041
6827
  fedBuckets: {},
6042
6828
  pushEligible: false,
@@ -6273,7 +7059,7 @@ function askWrunWarmupBackfillIfOwed(args) {
6273
7059
  ringDetails.unsettledLanes = [...unsettledLanes];
6274
7060
  const { sheet, paramValues, runRows, intervalMs } = args.declaredWarmup;
6275
7061
  const creditedBars = args.declaredWarmup.creditedBars ?? 0;
6276
- const declaredWarmupBars = builtinTwinOf(meta.settings) === undefined ? wrunDeclaredWarmupBars(sheet, paramValues) : null;
7062
+ const declaredWarmupBars = builtinPortOf(meta.settings) === undefined ? wrunDeclaredWarmupBars(sheet, paramValues) : null;
6277
7063
  if (declaredWarmupBars !== null)
6278
7064
  ringDetails.declaredWarmupBars = declaredWarmupBars;
6279
7065
  if (declaredWarmupBars !== null && creditedBars > 0)
@@ -6524,10 +7310,11 @@ function wrunChartIntervalMs(chartInterval, ohlcvRows) {
6524
7310
  }
6525
7311
  /** The run-interval state of the overlay's current live session on this chart, the run bars a
6526
7312
  * full run may reuse (planWrunRunIntervalRows); none for a suspended session (its buffers stopped
6527
- * following the market). */
7313
+ * following the market) or a replay one (its forming bar folds the replay's bars as of its cutoff,
7314
+ * and a run after the exit computes on the live run bars, never on that fold). */
6528
7315
  function heldWrunRunIntervalSession(chartIndex, indicatorId) {
6529
7316
  const context = getWrunOverlayLiveContext(indicatorId);
6530
- if (!context || context.chartIndex !== chartIndex || context.liveSuspended)
7317
+ if (!context || context.chartIndex !== chartIndex || context.liveSuspended || context.replay)
6531
7318
  return undefined;
6532
7319
  return wrunRunIntervalSessionOf(context);
6533
7320
  }
@@ -6571,8 +7358,10 @@ function assertWrunRunMayPaint(chartIndex, indicatorId, replay) {
6571
7358
  /** The kScript replay window's warm-up candles before the chart's first bar,
6572
7359
  * on the K_OHLCV lane the kScript engine fetches them on (deadline-raced like
6573
7360
  * every lane): [fromMs, beforeMs). */
6574
- async function fetchWrunReplayHeadRows(target, meta, fromMs, beforeMs, meter) {
6575
- const fetched = await withWrunDeadline(wrunChartHostEnv().transport.fetchSource(target.chartIndex, 'ohlcv', { symbol: 'currentSymbol', exchange: 'currentExchange' }, fromMs, beforeMs, meta, `${target.fetchKey}-replay-head`, false, { meter }), WRUN_SOURCE_FETCH_DEADLINE_MS, `wrun replay head for '${target.fetchKey}'`);
7361
+ async function fetchWrunReplayHeadRows(target, meta, fromMs, beforeMs, meter,
7362
+ // The market the chart's rows came from (the rows handoff's walled read): the head joins those rows.
7363
+ candleSource) {
7364
+ const fetched = await withWrunDeadline(wrunChartHostEnv().transport.fetchSource(target.chartIndex, 'ohlcv', { symbol: 'currentSymbol', exchange: 'currentExchange', ...(candleSource ? { candleSource } : {}) }, fromMs, beforeMs, meta, `${target.fetchKey}-replay-head`, false, { meter }), WRUN_SOURCE_FETCH_DEADLINE_MS, `wrun replay head for '${target.fetchKey}'`);
6576
7365
  const rows = isPackedOhlcvRows(fetched)
6577
7366
  ? unpackOhlcvRows(fetched)
6578
7367
  : Array.isArray(fetched)
@@ -6589,33 +7378,58 @@ async function fetchWrunReplayHeadRows(target, meta, fromMs, beforeMs, meter) {
6589
7378
  /**
6590
7379
  * A replay run's run bars as of its cutoff (WRUN-PARITY-REST B1): the run
6591
7380
  * bars the window fetched hold every bucket in full, the one the playhead is
6592
- * in included. The bucket holding the newest completed chart bar is folded
6593
- * from the completed chart bars inside it (the replay's own candle fold,
6594
- * `aggregateOhlcvRows`) until the cutoff bar closes it, the buckets before it
6595
- * stay as fetched, and none after it is kept: a run bar shows only what the
6596
- * replay revealed, the live rule (live, the forming run bar folds the candles
6597
- * as they trade and the closed one is the fetched one).
7381
+ * in included. It keeps the bars open by the cutoff bar (the newest completed
7382
+ * chart bar), none after, each span read on the run's calendar (runBarSpan:
7383
+ * an RTH hour opens at its session-anchored stamp, a CME trade date at the
7384
+ * evening open before its 00:00Z stamp). The newest one is folded from the
7385
+ * completed chart bars inside its span until the cutoff bar closes it, and
7386
+ * the bars before it stay as fetched: a run bar shows only what the replay
7387
+ * revealed, the live rule (live, the forming run bar folds the candles as
7388
+ * they trade and the closed one is the fetched one). A forming bar with no
7389
+ * revealed chart bar is left out, as live opens one on its first trade.
6598
7390
  */
6599
- export function wrunReplayRunBars(runBars, chartRows, cutoffTs, runIntervalMs, chartIntervalMs) {
6600
- let formingAt = -1;
6601
- for (let at = 0; at < runBars.length; at += 1) {
6602
- if (Number(runBars[at][0]) <= cutoffTs)
6603
- formingAt = at;
7391
+ export function wrunReplayRunBars(runBars, chartRows, cutoffTs, run, chartIntervalMs) {
7392
+ // The first bar stamped past the cutoff (stamps ascending), then each one after it already open
7393
+ // by the cutoff bar (a session bar opens before its stamp).
7394
+ let lo = 0;
7395
+ let hi = runBars.length;
7396
+ while (lo < hi) {
7397
+ const mid = (lo + hi) >> 1;
7398
+ if (Number(runBars[mid][0]) <= cutoffTs)
7399
+ lo = mid + 1;
6604
7400
  else
6605
- break;
7401
+ hi = mid;
6606
7402
  }
6607
- if (formingAt < 0)
7403
+ let end = lo;
7404
+ while (end < runBars.length && runBarSpan(Number(runBars[end][0]), run).open <= cutoffTs)
7405
+ end += 1;
7406
+ if (end === 0)
6608
7407
  return [];
6609
- const formingTs = Number(runBars[formingAt][0]);
6610
- const kept = runBars.slice(0, formingAt + 1);
6611
- // The cutoff bar is the bucket's last: the bucket closed, as fetched.
6612
- if (formingTs + runIntervalMs <= cutoffTs + chartIntervalMs)
7408
+ const kept = runBars.slice(0, end);
7409
+ const formingTs = Number(kept[end - 1][0]);
7410
+ const span = runBarSpan(formingTs, run);
7411
+ // The cutoff bar is the bar's last: the bar closed, as fetched.
7412
+ if (span.close <= cutoffTs + chartIntervalMs)
6613
7413
  return kept;
6614
- const inBucket = chartRows
6615
- .filter((row) => Number(row[0]) >= formingTs && Number(row[0]) <= cutoffTs)
6616
- .map((row) => Array.from(row));
6617
- const [folded] = aggregateOhlcvRows(inBucket, runIntervalMs, formingTs, cutoffTs, { originMs: formingTs });
6618
7414
  kept.pop();
7415
+ let folded;
7416
+ for (const row of chartRows) {
7417
+ const ts = Number(row[0]);
7418
+ if (ts > cutoffTs)
7419
+ break;
7420
+ if (ts < span.open)
7421
+ continue;
7422
+ const volume = Number(row[5]);
7423
+ const traded = Number.isFinite(volume) ? volume : 0;
7424
+ if (folded === undefined) {
7425
+ folded = [formingTs, Number(row[1]), Number(row[2]), Number(row[3]), Number(row[4]), traded];
7426
+ continue;
7427
+ }
7428
+ folded[2] = Math.max(folded[2], Number(row[2]));
7429
+ folded[3] = Math.min(folded[3], Number(row[3]));
7430
+ folded[4] = Number(row[4]);
7431
+ folded[5] += traded;
7432
+ }
6619
7433
  if (folded)
6620
7434
  kept.push(folded);
6621
7435
  return kept;
@@ -6702,6 +7516,8 @@ async function writeWrunStandIn(args) {
6702
7516
  interval: args.chartMetadata?.interval,
6703
7517
  transformations: args.chartMetadata?.transformations,
6704
7518
  account: wrunChartHostEnv().user.standInAccount(),
7519
+ sessionType: args.chartMetadata?.sessionType,
7520
+ adjusted: args.chartMetadata?.adjusted,
6705
7521
  },
6706
7522
  engineScript: wrunStandInTag(identity.package, identity.version),
6707
7523
  runResult: args.runResult,
@@ -6821,11 +7637,13 @@ function wrunEvaluatedMainTail(ohlcvRows) {
6821
7637
  * (re-bucketed) row geometry, exactly the control's own fallback. Lazy: the
6822
7638
  * metadata service drags the auth and cache graph, which only a profile
6823
7639
  * package needs here. */
6824
- async function resolveWrunVolumeProfileGrid(chartIndex) {
7640
+ async function resolveWrunVolumeProfileGrid(chartIndex,
7641
+ // The run market the profile lane is asked on (a Trades chart's tape): its lattice is that market's, not the chart's.
7642
+ runMarket) {
6825
7643
  try {
6826
7644
  const chartMetadata = await wrunChartMetadataFor(chartIndex);
6827
- const exchange = typeof chartMetadata?.exchange === 'string' ? chartMetadata.exchange : '';
6828
- const symbol = typeof chartMetadata?.symbol === 'string' ? chartMetadata.symbol : '';
7645
+ const exchange = runMarket?.exchange ?? (typeof chartMetadata?.exchange === 'string' ? chartMetadata.exchange : '');
7646
+ const symbol = runMarket?.symbol ?? (typeof chartMetadata?.symbol === 'string' ? chartMetadata.symbol : '');
6829
7647
  if (!exchange || !symbol)
6830
7648
  return undefined;
6831
7649
  const { default: metadataService } = await wrunChartHostEnv().market.loadMetadataService();
@@ -7112,7 +7930,10 @@ export async function reseedWrunOverlayFromBuffers(indicatorId, reason, options
7112
7930
  intrabarRows: context.intrabarRows,
7113
7931
  formingPreRoll: context.formingPreRoll,
7114
7932
  // The session the run was computed under: the row builder's session calendar answers.
7115
- session: wrunChartSession(context.market?.exchange, context.market?.sessionType),
7933
+ session: wrunChartSession(context.market?.exchange, context.market?.sessionType, {
7934
+ symbol: context.market?.symbol,
7935
+ interval: clock.intervalMs,
7936
+ }),
7116
7937
  // The market the session was computed on (the eligibility gate above matched it to the chart).
7117
7938
  venue: wrunBarVenueOf(context.market, clock.intervalMs),
7118
7939
  formingBarTs,
@@ -7296,8 +8117,11 @@ export async function reseedWrunOverlayFromBuffers(indicatorId, reason, options
7296
8117
  noteWrunLiveIntakeEvent(indicatorId, { kind: 'reseed' });
7297
8118
  noteWrunLiveIntakeEvent(indicatorId, { kind: 'session-start', live: wrunLiveOf(outputRows) });
7298
8119
  // The committed rows' debug log, published with the rows (a failed
7299
- // render below owes a repaint, not a console rewrite).
7300
- await publishWrunDebugOutput(context.chartIndex, indicatorId, context.metadata, outputRows);
8120
+ // render below owes a repaint, not a console rewrite), under the session's own provenance.
8121
+ await publishWrunDebugOutput(context.chartIndex, indicatorId, context.metadata, outputRows, {
8122
+ opra: context.opraRead === true,
8123
+ ...(context.cmeRead === true ? { cme: true } : {}),
8124
+ });
7301
8125
  try {
7302
8126
  // The canvas fill (G1) for the session's market; a mirror entry that aged
7303
8127
  // out keeps the block the session was drawn with (same market, same grid).
@@ -7350,7 +8174,7 @@ export async function reseedWrunOverlayFromBuffers(indicatorId, reason, options
7350
8174
  cutWrunReplayRowsAfterApply(tc, indicatorId);
7351
8175
  }
7352
8176
  rememberWrunSessionCanvasFill(context, canvasFill);
7353
- presentWrunIntegration(context.chartIndex, indicatorId, context.metadata, meta.settings, outputRows, tc, context.sessionSeed?.initArgs, chartNames, runSession?.run);
8177
+ presentWrunIntegration(context.chartIndex, indicatorId, context.metadata, meta.settings, outputRows, tc, context.sessionSeed?.initArgs, chartNames, runSession?.run, 'run', { emptyTargets: runResult.emptyTargets, partial: clamped !== undefined });
7354
8178
  // The committed result's canvas notices replace the published ones (none clears them).
7355
8179
  await publishWrunSessionCanvasNotices(context, runResult);
7356
8180
  // The session's retained range on the "Cells capped" row (design 5); a clamped window's session keeps it.
@@ -7716,6 +8540,16 @@ function wrunUnservedLaneReason(type, exchange, coin, service) {
7716
8540
  return (`the ${type} source lane answers nothing on ${market} (a quote-priced perpetual market serves its quote ` +
7717
8541
  'candles, funding and open interest only)');
7718
8542
  }
8543
+ // The kind table's tape row (index-mode-admission.util): the stocks gate serves a tape's trades alone.
8544
+ if (isStocksTapeGoverned(exchange)) {
8545
+ return (`the ${type} source lane answers nothing on ${market} (a US stock tape serves its trades alone: candles, ` +
8546
+ 'buy/sell volume, the volume profile and the size flow, no order book, open interest, liquidations or funding)');
8547
+ }
8548
+ // The kind table's US equity row (index-mode-admission.util): a stock print has no aggressor side.
8549
+ if (getMarketKind(exchange) === 'tradfi') {
8550
+ return (`the ${type} source lane answers nothing on ${market} (a US equity market's prints carry no aggressor ` +
8551
+ 'side, so it serves no buy/sell volume)');
8552
+ }
7719
8553
  return (`the ${type} source lane answers nothing on ${market} (a forex or commodity market serves no volume ` +
7720
8554
  'profile, buy/sell volume, order book, implied volatility or skew)');
7721
8555
  case 'coin':
@@ -7861,29 +8695,43 @@ function wrunOptionsChainExtrasGoverned(extras) {
7861
8695
  * today's scope itself only for an answer that is not B's rows. A crypto
7862
8696
  * chain keeps its plain reader (OPTLOAD W3 decision 1): its payload is
7863
8697
  * today's, byte for byte.
8698
+ *
8699
+ * Contract F: an input whose `underlying` names another root (a setting
8700
+ * naming one read through `paramValues`) reads that root's chain instead
8701
+ * (derived-roots.util `wrunUnderlyingOptionsChainDecision`), its identity
8702
+ * naming the root (`chainUnderlying`).
8703
+ *
8704
+ * A stock twin (`options`, the run head's one decision, derived-roots.util
8705
+ * `decideWrunRunOptionsMarket`): its chain is its stock's, held on the OPRA
8706
+ * plane by the twin's ticker (the lane market, `options.lane`) and decided
8707
+ * over the twin's stock (`auto` reads OPRA, and so meets the OPRA wall for a
8708
+ * user script; a pinned crypto word still reads that venue's chain of the
8709
+ * coin). Without a decision the chart's own market reads exactly as before.
7864
8710
  */
7865
- async function wrunOptionsChainLaneExtrasFor(metadata, chartMetadata, official, opraUserScripts) {
7866
- const [{ decideWrunLaneChainIdentity, resolveWrunChartChain }, { hasDeribitOptions }, { resolveWrunOptionsChainCryptoVenues }, { WRUN_OPTION_VIEWS_ONE_ASK_CODE, WRUN_OPTION_VIEWS_ONE_EXPIRIES_CODE, wrunHeldOpraPlaneChain, wrunOptionsChainImplicitViewFields, wrunOptionViewLaneFields, wrunOptionViewsOfSource, wrunOptionViewsUnion, },] = await Promise.all([
8711
+ async function wrunOptionsChainLaneExtrasFor(metadata, chartMetadata, official, opraUserScripts, paramValues, options, cmeUserStudy = false) {
8712
+ const [{ decideWrunLaneChainIdentity, resolveWrunChartChain }, { hasDeribitOptions }, { resolveWrunOptionsChainCryptoVenues }, { WRUN_OPTION_VIEWS_ONE_ASK_CODE, WRUN_OPTION_VIEWS_ONE_EXPIRIES_CODE, wrunHeldOpraPlaneChain, wrunOptionsChainImplicitViewFields, wrunOptionViewLaneFields, wrunOptionViewsOfSource, wrunOptionViewsUnion, }, { wrunUnderlyingOptionsChainDecision },] = await Promise.all([
7867
8713
  import('./sources/opra-option-lanes.util.js'),
7868
8714
  wrunChartHostEnv().market.loadDeribitOptions(),
7869
8715
  wrunChartHostEnv().market.loadOptionsChainVenues(),
7870
8716
  import('./wrun-option-views.util.js'),
8717
+ import('./derived-roots.util.js'),
7871
8718
  ]);
7872
8719
  const market = chartMetadata;
7873
8720
  const pick = (value) => (typeof value === 'string' ? value : undefined);
7874
- const chartMarket = {
7875
- exchange: pick(market?.exchange) ?? '',
7876
- symbol: pick(market?.symbol) ?? '',
7877
- coin: pick(market?.coin) ?? '',
7878
- };
8721
+ // The market the chain is read as: a stock twin's lane market (its stock on the OPRA plane), else the chart's own.
8722
+ const lane = options?.lane;
8723
+ const chartMarket = lane !== undefined
8724
+ ? { exchange: lane.exchange, symbol: lane.symbol, coin: lane.coin }
8725
+ : { exchange: pick(market?.exchange) ?? '', symbol: pick(market?.symbol) ?? '', coin: pick(market?.coin) ?? '' };
7879
8726
  // The chart's chain by the ONE resolution every chain class reads (opra-option-lanes.util `resolveWrunChartChain`,
7880
- // over the chart's own metadata, its category included: `option_surface` reads the same one). A chain directory's
7881
- // own failure on a chart its plane governs (CME futures; a US stock, ETF or OPRA contract chart under the opra flag)
7882
- // is the decision's evidence for `cme-directory` or `opra-directory` (a service that did not answer, Retry), never a
7883
- // guess at another chain; any other resolver failure fails the run as before. On the OPRA plane the chain is the
7884
- // plane's own by coin, read off the plane itself (O1): no directory read stands before the lane's ask.
7885
- const held = await wrunHeldOpraPlaneChain(chartMarket.exchange, chartMarket.coin);
7886
- const chain = held ?? (await resolveWrunChartChain(chartMetadata));
8727
+ // over the chart's own metadata, its category included: `option_surface` reads the same one, and over the run's one
8728
+ // options market when the head decided it). A chain directory's own failure on a chart its plane governs (CME
8729
+ // futures; a US stock, ETF or OPRA contract chart under the opra flag) is the decision's evidence for `cme-directory`
8730
+ // or `opra-directory` (a service that did not answer, Retry), never a guess at another chain; any other resolver
8731
+ // failure fails the run as before. On the OPRA plane the chain is the plane's own by coin, read off the plane itself
8732
+ // (O1): no directory read stands before the lane's ask. The plane verdict is the head's when it decided one.
8733
+ const held = await wrunHeldOpraPlaneChain(chartMarket.exchange, chartMarket.coin, options !== undefined ? options.plane === 'opra' : undefined, chartMarket.symbol);
8734
+ const chain = held ?? (await resolveWrunChartChain(chartMetadata, options));
7887
8735
  const { chartSource } = chain;
7888
8736
  const marketLabel = `${pick(market?.exchange) ?? 'currentExchange'}/${pick(market?.symbol) ?? 'currentSymbol'}`;
7889
8737
  const chainInputs = metadata.inputs.filter((input) => metadata.inputSources[input.name]?.source === 'options_chain');
@@ -7894,20 +8742,16 @@ async function wrunOptionsChainLaneExtrasFor(metadata, chartMetadata, official,
7894
8742
  .filter(isWrunOptionsChainCryptoVenueWord)),
7895
8743
  ],
7896
8744
  chartSource,
7897
- chartCoin: pick(market?.coin),
8745
+ // A stock twin's crypto venue words ask the listing for its stock's ticker (the lane market's coin).
8746
+ chartCoin: lane?.coin ?? pick(market?.coin),
7898
8747
  });
7899
8748
  let resolved;
7900
8749
  for (const input of chainInputs) {
7901
8750
  const source = metadata.inputSources[input.name];
8751
+ const who = { ...chartMarket, inputName: input.name, official, opraUserScripts, marketLabel };
7902
8752
  // The ONE venue decision every chain class reads (`decideWrunLaneChainIdentity`), so a package reading
7903
- // `option_surface` beside the chain reads one venue.
7904
- const decision = decideWrunLaneChainIdentity({ chain, cryptoVenues, deribitListed: hasDeribitOptions }, source.venue, {
7905
- ...chartMarket,
7906
- inputName: input.name,
7907
- official,
7908
- opraUserScripts,
7909
- marketLabel,
7910
- });
8753
+ // `option_surface` beside the chain reads one venue; over another root's chain for an `underlying` root.
8754
+ const decision = (await wrunUnderlyingOptionsChainDecision(source, who, metadata.params ?? [], paramValues, chain)) ?? decideWrunLaneChainIdentity({ chain, cryptoVenues, deribitListed: hasDeribitOptions }, source.venue, who);
7911
8755
  // The decision's reason picks the record's seed (WRUN-REFUSALS U3a step 6).
7912
8756
  if (!decision.ok)
7913
8757
  throw wrunOptionsChainRefusalError(decision);
@@ -7920,6 +8764,14 @@ async function wrunOptionsChainLaneExtrasFor(metadata, chartMetadata, official,
7920
8764
  if (resolved === undefined)
7921
8765
  throw new Error(`WRUN ${metadata.id}: no options_chain input to resolve a chain for`);
7922
8766
  const { identity } = resolved;
8767
+ // The CME chain wall of every chain lane (`assertWrunLaneChainPlaneReadable`), here too: a CME chain is CME options
8768
+ // data, OpenMarket's own whatever the `cme-user-scripts` gate says. Before that gate no run but a first-party one
8769
+ // reached a CME chart's chain (the display wall refused every other at the head); the runs the gate brings there
8770
+ // (`cmeUserStudy`, a browser user run) read their chart's futures data, never CME options data (no implied
8771
+ // expansion), refused by name before any fetch with the wall's own words and record.
8772
+ if (identity.venue === 'cme' && cmeUserStudy) {
8773
+ assertWrunLaneChainPlaneReadable('cme', identity.exchange, { official, opraUserScripts }, { inputName: resolved.inputName, sourceClass: 'options_chain' });
8774
+ }
7923
8775
  const laneInputs = chainInputs.map((input) => ({
7924
8776
  expiries: wrunOptionsChainExpiries(metadata.inputSources[input.name]?.expiries),
7925
8777
  maxCells: input.max_cells,
@@ -8132,12 +8984,42 @@ function wrunInferredMainTick(tc) {
8132
8984
  * a price unit: it only picks the axis precision here. With `market` (the
8133
8985
  * chart metadata), the market's facts ride too (`kind`, `pointValue`, `zone`,
8134
8986
  * `quoteIsUsd`, `sessionOpen`: wrunMarketFactsFor, over the directory row a
8135
- * run of a package declaring `kind` or `quote_is_usd` awaited first). With
8987
+ * run of a package declaring `kind` or `quote_is_usd` awaited first), the
8988
+ * option multiplier read off the market whose options the chart reads: the
8989
+ * market's own `optionsExchange` when the caller names it (a run's one
8990
+ * decision), else the one the latest run on that chart market decided
8991
+ * (derived-roots.util `wrunDecidedOptionsExchange`: a stock twin reading its
8992
+ * stock's OPRA chain reads 100 on its live ticks too). With
8136
8993
  * `earnings` (the chart metadata, passed for a sheet that declares an
8137
8994
  * earnings fact), the issuer's earnings facts ride too (`earningsNextMs`,
8138
8995
  * `earningsPrevMs`, `earningsSession`: wrunEarningsFactsFor, over the earnings
8139
8996
  * window a run of such a package warmed first).
8140
8997
  */
8998
+ /** A facts market with the exchange its options read (`WrunFactsMarket.optionsExchange`): the caller's when it names
8999
+ * one, else the latest run's decision on that chart market (`wrunDecidedOptionsExchange`), else none (its own). */
9000
+ function wrunFactsMarketWithOptions(market) {
9001
+ if (market.optionsExchange !== undefined)
9002
+ return market;
9003
+ const optionsExchange = wrunDecidedOptionsExchange(market);
9004
+ return optionsExchange === undefined ? market : { ...market, optionsExchange };
9005
+ }
9006
+ /** The chart metadata as the facts read it beside the run's one options market (the head's decision): the exchange the
9007
+ * chart's options read rides along, so `market.option_multiplier()` follows the chain the run reads. */
9008
+ function wrunRunFactsMarket(chartMetadata, options) {
9009
+ const optionsExchange = options?.market.exchange;
9010
+ return chartMetadata === undefined || typeof optionsExchange !== 'string'
9011
+ ? chartMetadata
9012
+ : { ...chartMetadata, optionsExchange };
9013
+ }
9014
+ /** The chart metadata as a batch the cloud computed reads its facts (`integrateWrunRowSourceBatch`): the chart's own
9015
+ * market's, named outright so no browser run's decision on the chart stands in (`wrunDecidedOptionsExchange`). The
9016
+ * server resolves the chain of the chart market it is sent (follow-up: the backend's stock twin rule). */
9017
+ export function wrunCloudFactsMarket(chartMetadata) {
9018
+ const exchange = chartMetadata?.exchange;
9019
+ return chartMetadata === undefined || typeof exchange !== 'string'
9020
+ ? chartMetadata
9021
+ : { ...chartMetadata, optionsExchange: exchange };
9022
+ }
8141
9023
  export function wrunHostFillContextFor(tc, chartExchange, intervalMs, market, earnings) {
8142
9024
  const engine = tc;
8143
9025
  let engineTick;
@@ -8156,7 +9038,7 @@ export function wrunHostFillContextFor(tc, chartExchange, intervalMs, market, ea
8156
9038
  ...(tickSize !== undefined ? { tickSize } : {}),
8157
9039
  pricePrecision,
8158
9040
  ...wrunChartContextHostFill(tc, intervalMs),
8159
- ...(market !== undefined ? wrunMarketFactsFor(market) : {}),
9041
+ ...(market !== undefined ? wrunMarketFactsFor(wrunFactsMarketWithOptions(market)) : {}),
8160
9042
  // The issuer's earnings facts: the browser run's alone (a hosted lane's host fill never carries them).
8161
9043
  ...(earnings !== undefined ? wrunEarningsFactsFor(earnings) : {}),
8162
9044
  };
@@ -8232,16 +9114,35 @@ export function wrunOutputRowsOnChartBars(outputRows, chart, run) {
8232
9114
  }
8233
9115
  return shown;
8234
9116
  }
9117
+ /**
9118
+ * The Style targets the latest-values snapshot names as drawing nothing (WrunLatestSnapshot.emptyTargets, the Style
9119
+ * page's silent lines): the applied result's own, judged over the whole loaded range. A result computed over a
9120
+ * window of it (`partial`) speaks for that window only, and the mount keeps its rows outside, so it can clear a
9121
+ * target (values in the window) but never mark one: the previous snapshot's targets it still finds empty. A
9122
+ * republish that built no result (`applied` absent) carries the previous snapshot's forward.
9123
+ */
9124
+ export function wrunSnapshotEmptyTargets(previous, applied) {
9125
+ if (applied === undefined)
9126
+ return [...(previous ?? [])];
9127
+ const judged = applied.emptyTargets ?? [];
9128
+ if (applied.partial !== true)
9129
+ return [...judged];
9130
+ const kept = new Set(previous ?? []);
9131
+ return judged.filter((target) => kept.has(target));
9132
+ }
8235
9133
  /**
8236
9134
  * What follows every successful integrate, the full run's, the reseed's and
8237
9135
  * the tick's (after the lower-pane children mounted): the nested output
8238
9136
  * visibility the sheet (`visible: false`) and the Style page's Visible rows
8239
9137
  * ask for (U9's `applyWrunOutputVisibility`, parent and children), and the
8240
9138
  * latest-values snapshot the HUD layer, the legend and the hover inspector
8241
- * read (`publishWrunLatestValues`), then the Indicator store's seen note for
8242
- * a registry Indicator (`noteWrunRegistryRun`: once a page and day, the maker's
8243
- * private reach; both row sources pass here). Presentation only: a failure here
8244
- * is logged, never a second failure over a run that rendered.
9139
+ * read (`publishWrunLatestValues`; a republish leaves a refused full run's
9140
+ * snapshot as it is, `WrunLatestPublishOrigin`) with the applied result's
9141
+ * `emptyTargets` (the Style page dims those lines), then the Indicator store's
9142
+ * seen note for a registry Indicator (`noteWrunRegistryRun`: once a page and
9143
+ * day, the maker's private reach; both row sources pass here). Presentation
9144
+ * only: a failure here is logged, never a second failure over a run that
9145
+ * rendered.
8245
9146
  */
8246
9147
  export function presentWrunIntegration(chartIndex, indicatorId, metadata, settings, outputRows, chart, initArgs,
8247
9148
  // The chart names the run's text was integrated with (the session's own):
@@ -8250,7 +9151,10 @@ chartNames,
8250
9151
  // The run's stamp when it ran at another interval than the chart: the
8251
9152
  // snapshot reads the chart's newest bar as the projection shows it (the
8252
9153
  // run bar before the forming one, with wait for close on).
8253
- runInterval) {
9154
+ runInterval, origin = 'run',
9155
+ // What the integrate applied, for the snapshot's `emptyTargets` (wrunSnapshotEmptyTargets): absent for a
9156
+ // republish that built no result (a landed pan page).
9157
+ applied) {
8254
9158
  try {
8255
9159
  // Guarded like the tick lane's seams: a node spec that mocks the adapter
8256
9160
  // module partially leaves the export out (production always has it).
@@ -8262,13 +9166,22 @@ runInterval) {
8262
9166
  console.warn(`[wrun] output visibility failed for '${indicatorId}' (chart ${chartIndex}):`, error);
8263
9167
  }
8264
9168
  try {
8265
- const snapshot = wrunLatestSnapshotOf(metadata, runInterval ? wrunOutputRowsOnChartBars(outputRows, chart, runInterval) : outputRows, chartNames);
8266
- // A tick republish carries the run's init args forward (the args a tick evaluates with are the
8267
- // session seed's, unchanged since the last full run or reseed).
8268
- const carried = initArgs ?? wrunChartHostEnv().chart.latestSnapshot(chartIndex, indicatorId)?.initArgs;
8269
- if (carried)
8270
- snapshot.initArgs = [...carried];
8271
- wrunChartHostEnv().chart.publishLatestValues(chartIndex, indicatorId, snapshot);
9169
+ const shown = wrunChartHostEnv().chart.latestSnapshot(chartIndex, indicatorId);
9170
+ // A refused full run's snapshot stands until a verdict that supersedes it publishes (a full run, a reseed):
9171
+ // a republish would bring back the numbers of the computation the refusal superseded.
9172
+ if (origin === 'run' || shown?.refused === undefined) {
9173
+ const snapshot = wrunLatestSnapshotOf(metadata, runInterval ? wrunOutputRowsOnChartBars(outputRows, chart, runInterval) : outputRows, chartNames);
9174
+ // A tick republish carries the run's init args forward (the args a tick evaluates with are the
9175
+ // session seed's, unchanged since the last full run or reseed).
9176
+ const carried = initArgs ?? shown?.initArgs;
9177
+ if (carried)
9178
+ snapshot.initArgs = [...carried];
9179
+ // The Style targets the chart shows nothing for: the Style page dims their lines.
9180
+ const empty = wrunSnapshotEmptyTargets(shown?.emptyTargets, applied);
9181
+ if (empty.length > 0)
9182
+ snapshot.emptyTargets = empty;
9183
+ wrunChartHostEnv().chart.publishLatestValues(chartIndex, indicatorId, snapshot);
9184
+ }
8272
9185
  }
8273
9186
  catch (error) {
8274
9187
  console.warn(`[wrun] latest values publish failed for '${indicatorId}' (chart ${chartIndex}):`, error);
@@ -8446,35 +9359,42 @@ function wrunCanvasFillWithSessionBlock(fill, metadata, indicatorId, market) {
8446
9359
  return held === undefined ? fill : { ...fill, tpoBlockSize: held };
8447
9360
  }
8448
9361
  /**
8449
- * A live session's CURRENT rows integrated again with a refined canvas fill
8450
- * (the served TPO block answered after the run): the reseed's integrate over
8451
- * the session's own outputs and buffers, no worker call, then the fill is
8452
- * the session's (its ticks build on the refined grid). Called under the
8453
- * overlay's session lock; it applies only while the session is the
8454
- * registered one, live, its run the newest (`current`) and the reseed's gates
8455
- * hold, the complete market identity among them: an interval or market
8456
- * switch while the load or the lock was pending leaves the old context
8457
- * registered until the replacement installs, and that context applies nothing.
9362
+ * A live session's CURRENT rows integrated again, no worker call: the reseed's
9363
+ * integrate over the session's own outputs and buffers, under its context's
9364
+ * sheet (`context.metadata`) and with the canvas fill `fill`, which is the
9365
+ * session's from then on (its ticks build on it). Two callers: the TPO block
9366
+ * refine (the served block answered after the run: a refined fill) and the
9367
+ * style-only save's repaint (repaintWrunSessionUnderSheet: a new sheet, the
9368
+ * fill the session was drawn with). Called under the overlay's session lock;
9369
+ * it applies only while the session is the registered one, live, `current()`
9370
+ * holds and the reseed's gates hold, the complete market identity among them:
9371
+ * an interval or market switch while the load or the lock was pending leaves
9372
+ * the old context registered until the replacement installs, and that context
9373
+ * applies nothing. A replay session's paint keeps to the replay's bars, as the
9374
+ * reseed's does. `keepOverlaySettings` (a gesture's preview) writes nothing to
9375
+ * the overlay's settings; `cellRowsOf` (a session a row source feeds) reads the
9376
+ * price canvases' cells from that source, never from buffers the context holds.
9377
+ * True once the integrate presented; false when it stood down.
8458
9378
  */
8459
- async function reintegrateWrunSessionCanvases(indicatorId, context, fill, current) {
9379
+ async function reintegrateWrunSession(indicatorId, context, fill, current, options = {}) {
8460
9380
  const registered = () => getWrunOverlayLiveContext(indicatorId) === context && !context.liveSuspended && current();
8461
9381
  if (!registered())
8462
- return;
9382
+ return false;
8463
9383
  const tc = wrunChartHostEnv().chart.instance(context.chartIndex);
8464
9384
  const meta = tc?.metadata?.find((candidate) => candidate.id === indicatorId);
8465
9385
  if (!tc || !meta)
8466
- return;
9386
+ return false;
8467
9387
  if (!(await wrunReseedEligible(context, meta, undefined)) || !registered())
8468
- return;
9388
+ return false;
8469
9389
  const chartRows = wrunChartCandleRows(tc);
8470
9390
  if (chartRows.length === 0)
8471
- return;
9391
+ return false;
8472
9392
  // A clamped session keeps the reseed's rule: its rows from its head, the
8473
9393
  // mounted rows outside its window kept by the integrate.
8474
9394
  const clamped = context.window?.partial ? context.window : undefined;
8475
9395
  const sessionRows = clamped ? chartRows.filter((row) => row[0] >= clamped.fromMs) : chartRows;
8476
9396
  if (sessionRows.length === 0)
8477
- return;
9397
+ return false;
8478
9398
  const runSession = wrunRunIntervalSessionOf(context);
8479
9399
  const ohlcvRows = runSession
8480
9400
  ? wrunRunIntervalComputeRows(runSession.run, runSession.rows, chartRows[chartRows.length - 1][0])
@@ -8486,7 +9406,7 @@ async function reintegrateWrunSessionCanvases(indicatorId, context, fill, curren
8486
9406
  volumeProfileRows: context.volumeProfileRows,
8487
9407
  intrabarRows: context.intrabarRows,
8488
9408
  };
8489
- // The refine redraws the session: the tick's applied result no longer describes the mount.
9409
+ // The integrate redraws the session: the tick's applied result no longer describes the mount.
8490
9410
  context.liveApplied = undefined;
8491
9411
  const runResult = integrateWrunOutputRows({
8492
9412
  tc,
@@ -8508,25 +9428,101 @@ async function reintegrateWrunSessionCanvases(indicatorId, context, fill, curren
8508
9428
  ? { projection: wrunRunIntervalProjectionOf(runSession.run, context.chartIndex, context.market?.exchange) }
8509
9429
  : {}),
8510
9430
  // A session holding a retained range (WRUN-MARKS-CONTRACT design 5) refines over the bars it calculated: the
8511
- // chart's older loaded candles and the rows its buffers hold before its first row stay out, as on its ticks.
8512
- cellRows: wrunCellRowsOf(context.metadata, context.retained !== undefined ? wrunRetainedCanvasSources(sessionSources, context.firstRowTs) : sessionSources, context.pinnedLegs ?? []),
9431
+ // chart's older loaded candles and the rows its buffers hold before its first row stay out, as on its ticks. A
9432
+ // session a row source feeds holds no buffers: its cells are the source's, as its full run's and its frames' are.
9433
+ cellRows: options.cellRowsOf !== undefined
9434
+ ? options.cellRowsOf(sessionRows)
9435
+ : wrunCellRowsOf(context.metadata, context.retained !== undefined
9436
+ ? wrunRetainedCanvasSources(sessionSources, context.firstRowTs)
9437
+ : sessionSources, context.pinnedLegs ?? []),
8513
9438
  intervalMs: context.intervalMs,
8514
9439
  ...(context.market?.exchange !== undefined ? { exchange: context.market.exchange } : {}),
8515
9440
  ...withPriceTick(wrunHostFillContextFor(tc, context.market?.exchange, context.intervalMs).tickSize),
8516
9441
  ...withCanvasHostFill(fill),
8517
9442
  ...(clamped ? { window: { fromMs: clamped.fromMs, toMs: context.lastRowTs, partial: true } } : {}),
9443
+ ...(options.keepOverlaySettings === true ? { keepOverlaySettings: true } : {}),
8518
9444
  });
8519
- if (runResult.childOverlays !== undefined && !(await awaitWrunChildOverlays(tc, indicatorId)))
8520
- return;
9445
+ if (context.replay)
9446
+ cutWrunReplayRowsAfterApply(tc, indicatorId);
9447
+ if (runResult.childOverlays !== undefined) {
9448
+ if (!(await awaitWrunChildOverlays(tc, indicatorId)))
9449
+ return false;
9450
+ if (context.replay)
9451
+ cutWrunReplayRowsAfterApply(tc, indicatorId);
9452
+ }
8521
9453
  if (getWrunOverlayLiveContext(indicatorId) !== context)
8522
- return;
9454
+ return false;
8523
9455
  rememberWrunSessionCanvasFill(context, fill);
8524
9456
  await publishWrunSessionCanvasNotices(context, runResult);
8525
9457
  if (getWrunOverlayLiveContext(indicatorId) !== context)
8526
- return;
8527
- presentWrunIntegration(context.chartIndex, indicatorId, context.metadata, meta.settings, context.outputRows, tc, context.sessionSeed?.initArgs, chartNames, runSession?.run);
9458
+ return false;
9459
+ presentWrunIntegration(context.chartIndex, indicatorId, context.metadata, meta.settings, context.outputRows, tc, context.sessionSeed?.initArgs, chartNames, runSession?.run,
9460
+ // The session's rows again: a full run refused since keeps its snapshot.
9461
+ 'republish', { emptyTargets: runResult.emptyTargets, partial: clamped !== undefined });
8528
9462
  context.paintedThroughTs = context.lastRowTs;
8529
9463
  context.repaintOwed = false;
9464
+ return true;
9465
+ }
9466
+ /**
9467
+ * A repaint of the mounted session under a new sheet: the style-only save's
9468
+ * door (wrun-style-patch.util) for the paint its in-place plot patch cannot
9469
+ * reach. A `skip` target's Visible row (the selection builds the target again
9470
+ * from the session's rows, whose frames the module writes whatever the sheet
9471
+ * hides, or leaves it out), the colour of a level, a renderer or a batched
9472
+ * section, a band, a fill, a box, a segment, and every look the adapter
9473
+ * derives from an output's colour. The caller swaps the new sheet into the
9474
+ * context first (`context.metadata`); this integrates the session's own rows
9475
+ * and buffers under it with the canvas fill the session was drawn with (no
9476
+ * worker call, no fetch: reintegrateWrunSession) and presents the result as
9477
+ * a republish, under the overlay's session lock. A full run in flight
9478
+ * replaces the session when it lands, so the repaint stands down and the
9479
+ * save's rerun joins that run. False (the save keeps its rerun): no live
9480
+ * session, the context replaced or suspended, a full run in flight, the
9481
+ * reseed's gates refuse the chart (replay, protection, the pane budget, the
9482
+ * pause, the market), no candle to land on, or a failed integrate (the
9483
+ * session then owes its repaint, as after a failed tick). `preview` (a
9484
+ * settings gesture's frame, under the previewed sheet) writes nothing to the
9485
+ * overlay's settings. A replay session stands down too: only its lane bounds
9486
+ * its candles at the replay's cutoff (the run and the tick paths), so the save
9487
+ * reruns there. A session whose row source holds its own session (a cloud
9488
+ * run) repaints with the cells that source keeps (`cellRowsOf`, as its full
9489
+ * run and its frames read them); a sheet drawing price canvases whose cells
9490
+ * neither such a source nor the context's lane buffers hold stands down.
9491
+ */
9492
+ export async function repaintWrunSessionUnderSheet(indicatorId, context, options = {}) {
9493
+ const standing = () => getWrunOverlayLiveContext(indicatorId) === context && !isWrunOverlayFullRerunInFlight(indicatorId);
9494
+ if (!standing() || context.replay === true)
9495
+ return false;
9496
+ return withWrunOverlaySessionLock(indicatorId, async () => {
9497
+ try {
9498
+ // The session's cells (its price canvases' rows), read through the row source interface: a source whose own
9499
+ // session feeds the context keeps them (a cloud run's grids, as its full run and its frames read them); else
9500
+ // the context's lane buffers hold them (a browser run, whose source holds no session of its own). A sheet
9501
+ // drawing price canvases with neither stands down: an empty canvas is never a repaint.
9502
+ const held = wrunHeldRowSources.get(indicatorId);
9503
+ const sessionSource = held !== undefined && held.source.holdsSession() ? held.source : undefined;
9504
+ if (sessionSource === undefined && wrunSheetDrawsCanvases(context.metadata) && !wrunHoldsCanvasCells(context)) {
9505
+ return false;
9506
+ }
9507
+ // The row builder reads the shared host (the run that installed this context loaded it).
9508
+ const hostLoading = ensureWrunChartHostSharedHost();
9509
+ if (hostLoading)
9510
+ await hostLoading;
9511
+ const fill = wrunSessionCanvasFillOf(context) ?? (await wrunCanvasHostFillFor(context.metadata, context.market));
9512
+ return await reintegrateWrunSession(indicatorId, context, fill, standing, {
9513
+ keepOverlaySettings: options.preview === true,
9514
+ ...(sessionSource !== undefined
9515
+ ? { cellRowsOf: (ohlcvRows) => sessionSource.cellRowsOf(ohlcvRows) }
9516
+ : {}),
9517
+ });
9518
+ }
9519
+ catch (error) {
9520
+ if (getWrunOverlayLiveContext(indicatorId) === context)
9521
+ context.repaintOwed = true;
9522
+ console.warn(`[wrun] style repaint failed for '${indicatorId}' (the save reruns):`, error);
9523
+ return false;
9524
+ }
9525
+ });
8530
9526
  }
8531
9527
  /** Drop an overlay's canvas run state (its refine latches, its run serial):
8532
9528
  * called from the live tick lane's teardown hook beside the canvas cache. */
@@ -8625,11 +9621,11 @@ export async function publishWrunStrategyRunResult(chartIndex, indicatorId, runR
8625
9621
  * lines were ever written for it and there is nothing to clear, and the
8626
9622
  * store stays out of every run of a package without a debug log. The store
8627
9623
  * is loaded lazily like the strategy publish. */
8628
- async function publishWrunDebugOutput(chartIndex, indicatorId, metadata, rows) {
9624
+ async function publishWrunDebugOutput(chartIndex, indicatorId, metadata, rows, provenance) {
8629
9625
  if (wrunDebugSlotIndex(metadata) === undefined)
8630
9626
  return;
8631
9627
  const { useChartStore } = await wrunChartHostEnv().chart.loadChartStore();
8632
- useChartStore().setIndicatorPrintOutputs(chartIndex, indicatorId, selectWrunDebugLines(metadata, rows));
9628
+ useChartStore().setIndicatorPrintOutputs(chartIndex, indicatorId, selectWrunDebugLines(metadata, rows), provenance);
8633
9629
  }
8634
9630
  /**
8635
9631
  * A sheet with colour settings: the overlay palette (the collapsed-legend
@@ -8796,6 +9792,25 @@ function wrunMountMemoOf(meta) {
8796
9792
  }
8797
9793
  return memo;
8798
9794
  }
9795
+ /**
9796
+ * The result a mounted overlay shows now, as it was built, with the window it was computed over (the
9797
+ * workspace switch's stand-in capture stores it, kscript-standin-switch.util): the live tick's last
9798
+ * applied build (`liveApplied`), else the result this lane's last full integrate applied while its
9799
+ * rows are still the ones mounted (the mount memo: a tick's whole integrate, a blank or a stand-in
9800
+ * replaces them), else undefined. While a repaint is owed the chart lags the session, so nothing on
9801
+ * it is known to show: undefined. Nothing is rebuilt or patched here.
9802
+ */
9803
+ export function wrunMountedRunResultOf(indicatorId, meta) {
9804
+ const context = getWrunOverlayLiveContext(indicatorId);
9805
+ if (context?.repaintOwed)
9806
+ return undefined;
9807
+ if (context?.liveApplied)
9808
+ return { runResult: context.liveApplied.result, window: context.window };
9809
+ const memo = wrunMountMemos.get(meta);
9810
+ if (memo?.lastResult === undefined || memo.lastRows !== meta.rawData)
9811
+ return undefined;
9812
+ return { runResult: memo.lastResult, window: memo.lastWindow };
9813
+ }
8799
9814
  /** The result renders equal to the one this lane applied last, and that one is still what the
8800
9815
  * overlay shows: the same window recomputed (a page lands its children's rows inside it, so another
8801
9816
  * window is never the same apply), the parent equal (`kscriptRunResultsRenderEqual`: rows, drawings,
@@ -9061,8 +10076,10 @@ function integrateWrunRunThroughRouteOnce(options, childMount) {
9061
10076
  // Read before any chart mutation: a strip word off the vocabulary refuses the run by name.
9062
10077
  const stripSettings = wrunStatsStripSettings(options.metadata);
9063
10078
  applyWrunIntegrationBudget(runResult, chartIndex, indicatorId);
9064
- syncWrunRunOverlayPalette(tc, indicatorId, meta, options.metadata);
9065
- syncWrunRunStripSettings(tc, indicatorId, meta, stripSettings);
10079
+ if (options.keepOverlaySettings !== true) {
10080
+ syncWrunRunOverlayPalette(tc, indicatorId, meta, options.metadata);
10081
+ syncWrunRunStripSettings(tc, indicatorId, meta, stripSettings);
10082
+ }
9066
10083
  const placed = placeWrunResultTables(tc, indicatorId, meta, runResult, { chartIndex, projection });
9067
10084
  const render = () => {
9068
10085
  tc.renderService?.renderOnce?.();
@@ -9450,8 +10467,14 @@ async function wrunWarmupHeadRequestOf(chart) {
9450
10467
  },
9451
10468
  tokenSessionTypes: lane.mainCandleTokenSessionTypes(context),
9452
10469
  projection: lane.mainCandleRowsProjection(facts),
10470
+ ...wrunWarmupHeadCandleSource(chart),
9453
10471
  };
9454
10472
  }
10473
+ /** The head's `candleSource`: the rows it joins came from there (a reader that threw names none, as the walls read). */
10474
+ function wrunWarmupHeadCandleSource(chart) {
10475
+ const candleSource = wrunMainCandleSourceOf(chart);
10476
+ return candleSource ? { candleSource } : {};
10477
+ }
9455
10478
  /** A head page's transport ids: never a `main<i>` id (no main load state, no main queue rule), one per page. */
9456
10479
  let wrunWarmupHeadPageSerial = 0;
9457
10480
  /**
@@ -9467,6 +10490,8 @@ async function fetchWrunWarmupHeadPage(chartIndex, request, fromTs, toTs, meter,
9467
10490
  const from = Math.floor(fromTs / 1000);
9468
10491
  const payload = {
9469
10492
  ...request.lane.buildMainCandleBasePayload({ ...request.identity, ovId }),
10493
+ // The chart's identity keeps the shape; the rows' own market rides the series ref alone (fetchMainData's rule).
10494
+ ...(request.candleSource ? { candleSource: request.candleSource } : {}),
9470
10495
  period: Math.max(1, Math.ceil(toTs / 1000) - from),
9471
10496
  from,
9472
10497
  ...(request.tokenSessionTypes !== undefined ? { tokenSessionTypes: request.tokenSessionTypes } : {}),
@@ -11173,7 +12198,10 @@ async function prepareWrunPrefixRun(runTarget, tc, meta, window, landings, start
11173
12198
  ...(bookRows !== undefined ? { bookRows } : {}),
11174
12199
  // Every other lane field the row builder reads, as the whole run's row build hands them (the window split).
11175
12200
  ...laneWindow.sourceRows,
11176
- session: wrunChartSession(chartExchange, chartMetadata?.sessionType),
12201
+ session: wrunChartSession(chartExchange, chartMetadata?.sessionType, {
12202
+ symbol: chartMetadata?.symbol,
12203
+ interval: clock.intervalMs,
12204
+ }),
11177
12205
  venue: wrunBarVenueOf(chartMetadata, clock.intervalMs),
11178
12206
  formingBarTs,
11179
12207
  };
@@ -11807,7 +12835,12 @@ async function runWrunPrefixOverlay(runTarget, tc, meta, window, refusal, owner,
11807
12835
  }
11808
12836
  else {
11809
12837
  prepared = ready;
11810
- outcome = await withWrunOverlaySessionLock(indicatorId, () => commitWrunPrefixRun(ready, tc, meta, owner, indicatorId));
12838
+ outcome = await withWrunOverlaySessionLock(indicatorId, () => {
12839
+ // A CME chart study's page lands only under the authorisation its head captured (a refusal here goes to the
12840
+ // full run, which judges the wall again).
12841
+ assertWrunCmeStudyAuthCurrent(computed, indicatorId);
12842
+ return commitWrunPrefixRun(ready, tc, meta, owner, indicatorId);
12843
+ });
11811
12844
  }
11812
12845
  }
11813
12846
  catch (error) {
@@ -11892,7 +12925,9 @@ async function followWrunPrefixLanded(runTarget, tc, meta, prepared, refusal) {
11892
12925
  const { chartIndex, indicatorId } = runTarget;
11893
12926
  const { context, sheetNow } = prepared;
11894
12927
  markWrunOverlayComputeSucceeded(indicatorId);
11895
- presentWrunIntegration(chartIndex, indicatorId, sheetNow, meta.settings, context.outputRows, tc, context.sessionSeed?.initArgs, wrunSessionChartNamesOf(context), null);
12928
+ presentWrunIntegration(chartIndex, indicatorId, sheetNow, meta.settings, context.outputRows, tc, context.sessionSeed?.initArgs, wrunSessionChartNamesOf(context), null,
12929
+ // The session's rows with older bars: a full run refused since keeps its snapshot.
12930
+ 'republish');
11896
12931
  try {
11897
12932
  const health = wrunSessionRunHealth(context, meta.settings, context.outputRows);
11898
12933
  context.runHealthWarned = await publishWrunRunHealth(chartIndex, indicatorId, wrunRunHealthRowsFor(health, context.draft === true, wrunNothingReadyRefusal(health, refusal.ctx)));