dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -12,7 +12,7 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Functions (22 exported functions)
15
+ * TABLE OF CONTENTS - Grid Functions (23 exported functions)
16
16
  * ===============================================================================
17
17
  *
18
18
  * CONFIGURATION & CALCULATION (2 functions)
@@ -34,8 +34,11 @@
34
34
  * GRID RECALCULATION (1 function - async)
35
35
  * 7. recalculateGrid(manager, opts) - Recalculate grid based on current state
36
36
  *
37
- * GRID STATE CHECKING (1 function)
38
- * 8. checkAndUpdateGridIfNeeded(manager) - Check if grid needs update
37
+ * GRID STATE CHECKING (2 functions)
38
+ * 8. checkAndUpdateGridIfNeeded(manager) - Complete fund trigger: available-
39
+ * funds ratio + over-allocation + on-chain committed-drift legs
40
+ * 8b. checkCommittedSizeDrift(manager) - Async committed-drift-only accessor
41
+ * (the drift core is folded into checkAndUpdateGridIfNeeded)
39
42
  *
40
43
  * BLOCKCHAIN SYNCHRONIZATION (2 functions - async)
41
44
  * 9. _recalculateGridOrderSizesFromBlockchain(manager, orderType, options) - Recalculate sizes from blockchain
@@ -89,13 +92,35 @@
89
92
  */
90
93
  import { createRequire } from 'node:module';
91
94
  const require = createRequire(import.meta.url);
92
- import { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, PIPELINE_TIMING, MARKET_ADAPTER, INCREMENT_BOUNDS } from '../constants.js';
95
+ import { ORDER_TYPES, ORDER_STATES, COW_ACTIONS, COW_ORIGINS, DEFAULT_CONFIG, GRID_LIMITS, TIMING, PIPELINE_TIMING, MARKET_ADAPTER, INCREMENT_BOUNDS } from '../constants.js';
93
96
  import * as Format from './format.js';
94
97
  import { resolveMaxAsymmetryFactor, applyAsymmetricBounds, applyNarrowingSideGuard, } from '../../market_adapter/core/asymmetric_bounds.js';
95
98
  // FIX: Extract magic numbers to named constants for maintainability
96
99
  const GRID_CONSTANTS = {
97
100
  RMS_PERCENTAGE_SCALE: 100, // Convert RMS percentage threshold from percent to decimal
98
101
  };
102
+ /**
103
+ * Fold a prepared correction (or the absence of one) into the stall cause the
104
+ * caller reports. A plan that existed but funded nothing ('unfunded'), or a
105
+ * zero sizing budget ('stallHint: unfunded'), is a FUND condition. The named
106
+ * structural causes ('cold-book', 'unmatched-orders', 'readiness-gate') are
107
+ * preserved verbatim; anything else is 'no-candidates'. The two sides are
108
+ * merged with this so an unfunded plan on one side is never masked by an empty
109
+ * plan on the other (e.g. chosen side planned 1 / placed 0, opposite 0).
110
+ */
111
+ function classifySpreadStall(c) {
112
+ const hint = c?.stallHint;
113
+ // A plan that existed but funded nothing is a FUND condition and must win
114
+ // over any structural hint (those are only set on empty returns today, but
115
+ // the precedence is explicit so a future hint can never mask 'unfunded').
116
+ if (Number(c?.plannedCount || 0) > 0 || hint === 'unfunded')
117
+ return 'unfunded';
118
+ // Preserve the readiness-gate causes verbatim; they are operationally
119
+ // distinct and the targeted-sync reason states them literally.
120
+ if (hint === 'cold-book' || hint === 'unmatched-orders' || hint === 'readiness-gate')
121
+ return hint;
122
+ return 'no-candidates';
123
+ }
99
124
  /**
100
125
  * Central resolution for the RMS structural-divergence threshold (percent).
101
126
  * Single source of truth: per-bot override wins, global GRID_COMPARISON default
@@ -117,8 +142,8 @@ function _snapshotFundState(manager) {
117
142
  };
118
143
  }
119
144
  import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, priceSlotEqual, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
120
- import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
121
- import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot } from './utils/system.js';
145
+ import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
146
+ import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice } from './utils/system.js';
122
147
  import * as MathUtils from './utils/math.js';
123
148
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
124
149
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
@@ -217,13 +242,9 @@ export function clearGridBloatFlag(manager) {
217
242
  * @returns {Promise<any|null>}
218
243
  * @private
219
244
  */
220
- export async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
245
+ function _computeSizingContextSync(manager, side) {
221
246
  if (!manager || !manager.assets)
222
247
  return null;
223
- // 1. Ensure fund state is fresh before sizing
224
- if (!skipRecalc) {
225
- await manager.recalculateFunds();
226
- }
227
248
  const snap = manager.getChainFundsSnapshot ? manager.getChainFundsSnapshot() : {};
228
249
  const isBuy = side === 'buy';
229
250
  const type = isBuy ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
@@ -234,8 +255,8 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
234
255
  // BTS fees are paid for ALL order operations regardless of side, so the
235
256
  // BTS-holding side reserves fees for both buy and sell target counts.
236
257
  if (budget > 0) {
237
- const targetBuy = Math.max(0, manager.config.activeOrders?.buy ?? 1) + resolveReserveCount(manager.config, 'buy');
238
- const targetSell = Math.max(0, manager.config.activeOrders?.sell ?? 1) + resolveReserveCount(manager.config, 'sell');
258
+ const targetBuy = Math.max(0, manager.config.coreOrders?.buy ?? 1) + resolveEdgeCount(manager.config, 'buy');
259
+ const targetSell = Math.max(0, manager.config.coreOrders?.sell ?? 1) + resolveEdgeCount(manager.config, 'sell');
239
260
  const totalTarget = targetBuy + targetSell;
240
261
  const btsOrderType = getBtsSide(manager.config?.assetA, manager.config?.assetB);
241
262
  const isBtsSide = isBuy ? (btsOrderType === ORDER_TYPES.BUY) : (btsOrderType === ORDER_TYPES.SELL);
@@ -256,6 +277,19 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
256
277
  config: manager.config
257
278
  };
258
279
  }
280
+ /**
281
+ * Async sizing-context accessor. Refreshes funds unless `skipRecalc`, then
282
+ * delegates to the sync core. Both divergence legs (ratio and committed
283
+ * drift) size through the sync core so they read one fund snapshot.
284
+ */
285
+ export async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
286
+ if (!manager || !manager.assets)
287
+ return null;
288
+ if (!skipRecalc) {
289
+ await manager.recalculateFunds();
290
+ }
291
+ return _computeSizingContextSync(manager, side);
292
+ }
259
293
  /**
260
294
  * Create the initial order grid structure based on configuration.
261
295
  *
@@ -1120,22 +1154,22 @@ export async function initializeGrid(manager) {
1120
1154
  const startPriceWasDerived = typeof mpRaw !== 'number' || Number.isNaN(Number(mpRaw));
1121
1155
  const centerIsLive = startPriceWasDerived || gpSource === 'ama';
1122
1156
  if (owedCrawls.length > 0 && !centerIsLive) {
1123
- // Reserve fills never crawl (static insurance). Classify them
1157
+ // Edge fills never crawl (static insurance). Classify them
1124
1158
  // against the OLD generation (manager.orders is replaced below)
1125
1159
  // with the same live anchors the runtime derivation uses, so the
1126
- // fold can never be driven by a reserve fill.
1160
+ // fold can never be driven by an edge fill.
1127
1161
  const oldSlots = Array.from(manager.orders.values());
1128
1162
  const edgeAnchors = {
1129
- buy: resolveLiveReserveEdgeAnchorPrice(manager, 'buy'),
1130
- sell: resolveLiveReserveEdgeAnchorPrice(manager, 'sell')
1163
+ buy: resolveLiveEdgeAnchorPrice(manager, 'buy'),
1164
+ sell: resolveLiveEdgeAnchorPrice(manager, 'sell')
1131
1165
  };
1132
- const reserveBuyIds = reserveEdgeIdSet(oldSlots, manager.config, ORDER_TYPES.BUY, edgeAnchors.buy, liveWindowIdSet(manager, ORDER_TYPES.BUY));
1133
- const reserveSellIds = reserveEdgeIdSet(oldSlots, manager.config, ORDER_TYPES.SELL, edgeAnchors.sell, liveWindowIdSet(manager, ORDER_TYPES.SELL));
1166
+ const edgeBuyIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.BUY, edgeAnchors.buy, liveWindowIdSet(manager, ORDER_TYPES.BUY));
1167
+ const edgeSellIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.SELL, edgeAnchors.sell, liveWindowIdSet(manager, ORDER_TYPES.SELL));
1134
1168
  let netShift = 0;
1135
1169
  for (const e of owedCrawls) {
1136
- if (e?.side === ORDER_TYPES.BUY && reserveBuyIds?.has(e.slotId))
1170
+ if (e?.side === ORDER_TYPES.BUY && edgeBuyIds?.has(e.slotId))
1137
1171
  continue;
1138
- if (e?.side === ORDER_TYPES.SELL && reserveSellIds?.has(e.slotId))
1172
+ if (e?.side === ORDER_TYPES.SELL && edgeSellIds?.has(e.slotId))
1139
1173
  continue;
1140
1174
  if (e?.side === ORDER_TYPES.SELL)
1141
1175
  netShift++;
@@ -1432,14 +1466,14 @@ export function checkAndUpdateGridIfNeeded(manager) {
1432
1466
  for (const s of sides) {
1433
1467
  if (s.grid <= 0)
1434
1468
  continue;
1435
- const feeActiveOrders = manager.config.activeOrders && typeof manager.config.activeOrders === 'object'
1469
+ const feeCoreOrders = manager.config.coreOrders && typeof manager.config.coreOrders === 'object'
1436
1470
  ? {
1437
- ...manager.config.activeOrders,
1438
- buy: Math.max(0, Number(manager.config.activeOrders.buy) || 0) + resolveReserveCount(manager.config, 'buy'),
1439
- sell: Math.max(0, Number(manager.config.activeOrders.sell) || 0) + resolveReserveCount(manager.config, 'sell'),
1471
+ ...manager.config.coreOrders,
1472
+ buy: Math.max(0, Number(manager.config.coreOrders.buy) || 0) + resolveEdgeCount(manager.config, 'buy'),
1473
+ sell: Math.max(0, Number(manager.config.coreOrders.sell) || 0) + resolveEdgeCount(manager.config, 'sell'),
1440
1474
  }
1441
- : manager.config.activeOrders;
1442
- const availableFunds = calculateAvailableFundsValue(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB, feeActiveOrders, manager.config.min_BTS_value, manager.config.feeParams ?? null);
1475
+ : manager.config.coreOrders;
1476
+ const availableFunds = calculateAvailableFundsValue(s.name, manager.accountTotals, manager.funds, manager.config.assetA, manager.config.assetB, feeCoreOrders, manager.config.min_BTS_value, manager.config.feeParams ?? null);
1443
1477
  // Denominator: side's allocated capital (or chain total fallback).
1444
1478
  const allocated = s.name === 'buy' ? chainSnap.allocatedBuy : chainSnap.allocatedSell;
1445
1479
  const denominator = (allocated > 0) ? allocated : (s.grid + availableFunds);
@@ -1451,8 +1485,11 @@ export function checkAndUpdateGridIfNeeded(manager) {
1451
1485
  // chain-total drops: a normal fill moves value across sides (pays one
1452
1486
  // asset, receives the other), so one side's total routinely drops >=3%
1453
1487
  // on ordinary fills — and the fill pipeline already re-sizes from the
1454
- // post-fill budget. External removal is caught here because the
1455
- // committed/planned grid stays put while the allocation sinks.
1488
+ // post-fill budget. External removal is caught here only while the plan
1489
+ // still carries the old budget; once the fill pipeline re-derives
1490
+ // VIRTUAL downward the overAlloc gap closes (grid == allocated), and the
1491
+ // committed-drift leg folded in below is what catches it. The two
1492
+ // together cover the pre- and post-pipeline phases.
1456
1493
  // NOTE: with an explicit 0 allocation the shared fallback denominator
1457
1494
  // yields overAlloc ≈ +100%, i.e. a 0%-funded side holding size always
1458
1495
  // triggers — which is the desired unwind (zero budget sizes everything
@@ -1478,8 +1515,174 @@ export function checkAndUpdateGridIfNeeded(manager) {
1478
1515
  }
1479
1516
  }
1480
1517
  }
1518
+ // Fold the committed-drift legs into this single entry so the trigger is
1519
+ // complete on its own. Both numerators above track `virtual` (the grow
1520
+ // denominator via `availableFunds`, the shrink base via `total.grid`), so
1521
+ // an external deposit/withdrawal already folded into the plan by the
1522
+ // fill pipeline is invisible to them. The on-chain committed delta closes
1523
+ // that gap in both directions. Callers must refresh funds first
1524
+ // (monitorDivergence does; direct callers own that responsibility).
1525
+ const driftResult = _computeCommittedSizeDriftSync(manager);
1526
+ result.buyUpdated = result.buyUpdated || driftResult.buyUpdated;
1527
+ result.sellUpdated = result.sellUpdated || driftResult.sellUpdated;
1528
+ result.buyShrink = result.buyShrink || driftResult.buyShrink;
1529
+ result.sellShrink = result.sellShrink || driftResult.sellShrink;
1481
1530
  return result;
1482
1531
  }
1532
+ /**
1533
+ * Committed-size drift check (fund trigger blind-spot closure).
1534
+ *
1535
+ * checkAndUpdateGridIfNeeded measures available funds as
1536
+ * `chainFree - virtualReservation`. The fill/rotation sizing pipeline
1537
+ * re-derives VIRTUAL slot sizes from the live budget, so a deposit (or an
1538
+ * external withdrawal) is folded into the virtual reservation on the first
1539
+ * rotation after it lands. chainFree and virtual then move together, the
1540
+ * ratio stays pinned at the unallocated remainder, and a side whose
1541
+ * on-chain (ACTIVE/PARTIAL) orders still carry the pre-deposit sizes is
1542
+ * never flagged — the full-side resize waits for an unrelated full resync
1543
+ * (RMS or AMA recenter).
1544
+ *
1545
+ * This leg closes that blind spot: it computes the geometric ideal for
1546
+ * every side slot from the current budget and measures the gap against the
1547
+ * sizes actually committed on chain, applying the resize path's own
1548
+ * free-balance growth cap so the metric equals the on-chain delta a resize
1549
+ * would really produce. A side whose committed orders would change by
1550
+ * >= GRID_REGENERATION_PERCENTAGE of the committed size is flagged for the
1551
+ * same COW resize path (applyGridDivergenceCorrections), which updates
1552
+ * every changed on-chain order — i.e. the full side.
1553
+ *
1554
+ * Only on-chain slots contribute: VIRTUAL slots are the plan (already sized
1555
+ * by the fill pipeline) and SPREAD placeholders carry no commitment.
1556
+ * Non-slot-N shelf/manual orders are excluded (never resized by the
1557
+ * geometric pass; same gate as _recalculateGridOrderSizesFromBlockchain).
1558
+ *
1559
+ * @param {import('./types').OrderManager} manager - Manager instance with order state
1560
+ * @returns {{ buyUpdated: boolean; sellUpdated: boolean; buyShrink: boolean; sellShrink: boolean }}
1561
+ */
1562
+ function _computeCommittedSizeDriftSync(manager) {
1563
+ const result = { buyUpdated: false, sellUpdated: false, buyShrink: false, sellShrink: false };
1564
+ if (!manager || !manager.assets || !manager.orders)
1565
+ return result;
1566
+ const rawThreshold = manager.config?.gridLimits?.GRID_REGENERATION_PERCENTAGE;
1567
+ // Same fallback contract as checkAndUpdateGridIfNeeded: a configured 0 or
1568
+ // non-numeric value falls back to the global default rather than disabling.
1569
+ const threshold = (Number.isFinite(Number(rawThreshold)) && Number(rawThreshold) > 0)
1570
+ ? Number(rawThreshold)
1571
+ : GRID_LIMITS.GRID_REGENERATION_PERCENTAGE;
1572
+ const sides = [
1573
+ { name: 'buy', orderType: ORDER_TYPES.BUY },
1574
+ { name: 'sell', orderType: ORDER_TYPES.SELL }
1575
+ ];
1576
+ for (const s of sides) {
1577
+ // Sync core: checkAndUpdateGridIfNeeded is sync and expects funds to
1578
+ // already be fresh (monitorDivergence / checkCommittedSizeDrift recalc).
1579
+ const ctx = _computeSizingContextSync(manager, s.name);
1580
+ if (!ctx || !(ctx.budget > 0))
1581
+ continue;
1582
+ // Must match _recalculateGridOrderSizesFromBlockchain exactly: same
1583
+ // source (manager.orders), same ASC price sort, same denominator set.
1584
+ const allSideSlots = Array.from(manager.orders.values())
1585
+ .filter((o) => o.type === s.orderType)
1586
+ .sort((a, b) => a.price - b.price);
1587
+ if (allSideSlots.length === 0)
1588
+ continue;
1589
+ let newSizes;
1590
+ try {
1591
+ newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, s.orderType, manager.config, 0, ctx.precision);
1592
+ }
1593
+ catch (_err) {
1594
+ continue;
1595
+ }
1596
+ // Replay the resize path's free-balance cap so `growth` is exactly the
1597
+ // committed growth the resize could apply (VIRTUAL slots do not consume
1598
+ // free balance; shrink releases it back for later slots). The cap uses
1599
+ // the float delta (matching the resize), but the reported drift is gated
1600
+ // on the same blockchain-integer change test the resize uses to decide
1601
+ // whether an on-chain UPDATE is emitted.
1602
+ const freeKey = s.name === 'buy' ? 'buyFree' : 'sellFree';
1603
+ let sideFreeAvailable = Number(manager.accountTotals?.[freeKey] || 0);
1604
+ let growth = 0;
1605
+ let shrink = 0;
1606
+ let committedTotal = 0;
1607
+ for (let i = 0; i < allSideSlots.length; i++) {
1608
+ const slot = allSideSlots[i];
1609
+ if (!isOrderOnChain(slot) || !hasOnChainId(slot))
1610
+ continue;
1611
+ if (parseSlotIndex(slot.id) === null)
1612
+ continue;
1613
+ const ideal = Number(newSizes?.[i] || 0);
1614
+ const current = Number(slot.size || 0);
1615
+ committedTotal += current;
1616
+ let newSize = ideal;
1617
+ const delta = ideal - current;
1618
+ if (delta > 0) {
1619
+ const affordableDelta = Math.min(delta, Math.max(0, sideFreeAvailable));
1620
+ if (affordableDelta < delta)
1621
+ newSize = current + affordableDelta;
1622
+ sideFreeAvailable = Math.max(0, sideFreeAvailable - affordableDelta);
1623
+ }
1624
+ else if (delta < 0) {
1625
+ sideFreeAvailable += Math.abs(delta);
1626
+ }
1627
+ // Match the resize's integer-space change gate: a slot whose size
1628
+ // rounds to the same blockchain integer emits no UPDATE and must not
1629
+ // count toward the drift metric (otherwise the leg would re-trigger
1630
+ // against a no-op resize every tick).
1631
+ const currentInt = floatToBlockchainInt(current, ctx.precision);
1632
+ const newInt = floatToBlockchainInt(newSize, ctx.precision);
1633
+ if (currentInt === newInt)
1634
+ continue;
1635
+ const applied = newSize - current;
1636
+ if (applied > 0)
1637
+ growth += applied;
1638
+ else if (applied < 0)
1639
+ shrink += Math.abs(applied);
1640
+ }
1641
+ // Baseline is the on-chain committed size, NOT the whole allocation:
1642
+ // a deposit's active-window share is a small slice of the allocation
1643
+ // (the far rail holds most of the plan), so an `allocated` denominator
1644
+ // would never reach 3% while the committed side is genuinely ~12%
1645
+ // under-sized. Relative to the committed side, a normal fill moves the
1646
+ // budget by well under the threshold, so this stays quiet in steady
1647
+ // state. No on-chain orders -> nothing to resize.
1648
+ if (!(committedTotal > 0))
1649
+ continue;
1650
+ const growthPct = (growth / committedTotal) * 100;
1651
+ const shrinkPct = (shrink / committedTotal) * 100;
1652
+ const growTrigger = growthPct >= threshold;
1653
+ const shrinkTrigger = shrinkPct >= threshold;
1654
+ manager.logger?.log?.(`[DIVERGENCE] ${s.name.toUpperCase()} committed-drift check: committedTotal=${committedTotal.toFixed(5)}, committedGrowth=${growth.toFixed(5)}, committedShrink=${shrink.toFixed(5)}, growth=${growthPct.toFixed(4)}% (threshold=${threshold}%) → ${growTrigger ? 'TRIGGER-GROW' : 'no trigger'} | shrink=${shrinkPct.toFixed(4)}% → ${shrinkTrigger ? 'TRIGGER-SHRINK' : 'no trigger'}`, 'debug');
1655
+ if (growTrigger || shrinkTrigger) {
1656
+ if (!(manager._gridSidesUpdated instanceof Set))
1657
+ manager._gridSidesUpdated = new Set();
1658
+ manager._gridSidesUpdated.add(s.orderType);
1659
+ if (s.name === 'buy') {
1660
+ result.buyUpdated = true;
1661
+ if (shrinkTrigger)
1662
+ result.buyShrink = true;
1663
+ }
1664
+ else {
1665
+ result.sellUpdated = true;
1666
+ if (shrinkTrigger)
1667
+ result.sellShrink = true;
1668
+ }
1669
+ }
1670
+ }
1671
+ return result;
1672
+ }
1673
+ /**
1674
+ * Async committed-drift accessor: refresh funds, then run the sync core.
1675
+ * Public for callers/tests that want the drift-only result; the complete
1676
+ * trigger is checkAndUpdateGridIfNeeded, which folds this core in.
1677
+ * Naming mirrors the sizing pair: _computeCommittedSizeDriftSync is the
1678
+ * private computation, checkCommittedSizeDrift the public accessor.
1679
+ */
1680
+ export async function checkCommittedSizeDrift(manager) {
1681
+ if (manager && typeof manager.recalculateFunds === 'function') {
1682
+ await manager.recalculateFunds();
1683
+ }
1684
+ return _computeCommittedSizeDriftSync(manager);
1685
+ }
1483
1686
  /**
1484
1687
  * Standardize grid sizes using blockchain total context.
1485
1688
  *
@@ -1568,11 +1771,11 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
1568
1771
  // geometric progression including empties, then re-type the picked slot
1569
1772
  // to BUY/SELL before placement. The COW boundary-shift path re-types
1570
1773
  // the working grid by geometry first, so crossers stay in the correct
1571
- // side's denominator. Reserve edge slots are included here like any
1774
+ // side's denominator. Edge order slots are included here like any
1572
1775
  // other slot-N side slot: this geometric curve sizes them too, and the
1573
- // activation picker (_pickEdgeReserveSlots) only ever places a reserve
1776
+ // activation picker (_pickEdgeSlots) only ever places an edge order
1574
1777
  // with the stored size the target-grid sizing pipeline already wrote
1575
- // (exact values, one sizing rule). Skipping reserves in this pass
1778
+ // (exact values, one sizing rule). Skipping edge orders in this pass
1576
1779
  // would make the divergence resize disagree with that pipeline. Only
1577
1780
  // non-slot-N shelf/manual ids are skipped below.
1578
1781
  const orderSource = collectActions ? workingGrid : manager.orders;
@@ -1595,7 +1798,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
1595
1798
  const slot = allSideSlots[i];
1596
1799
  // Shelf/manual orders (non-slot-N ids, e.g. fork-kept deep-*
1597
1800
  // below the rail) sit outside window accounting: geometric
1598
- // ideals must never resize them on-chain. Same gate as reserve
1801
+ // ideals must never resize them on-chain. Same gate as edge
1599
1802
  // classification and startup cancel candidates (issue #27
1600
1803
  // follow-up). No-op upstream (grids only mint slot-N).
1601
1804
  // NB: they stay in the denominator above (budget math
@@ -1906,24 +2109,35 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
1906
2109
  * @returns {Promise<any>}
1907
2110
  */
1908
2111
  export async function monitorDivergence(manager, calculatedGrid, persistedGrid) {
1909
- // 1. Check ratio-based divergence (available funds vs allocated)
2112
+ // Refresh once so every leg sizes from one snapshot. The trigger itself
2113
+ // is sync and already folds the committed-drift legs in (see
2114
+ // checkAndUpdateGridIfNeeded), so there is no separate drift call here.
2115
+ if (manager && typeof manager.recalculateFunds === 'function') {
2116
+ await manager.recalculateFunds();
2117
+ }
2118
+ // 1. Ratio + committed-drift divergence (available funds /
2119
+ // over-allocation / on-chain committed delta).
1910
2120
  const ratioResult = checkAndUpdateGridIfNeeded(manager);
1911
- if (ratioResult.buyUpdated || ratioResult.sellUpdated) {
2121
+ const ratioBuy = ratioResult.buyUpdated;
2122
+ const ratioSell = ratioResult.sellUpdated;
2123
+ const buyShrink = ratioResult.buyShrink === true;
2124
+ const sellShrink = ratioResult.sellShrink === true;
2125
+ if (ratioBuy || ratioSell) {
1912
2126
  return {
1913
2127
  needsUpdate: true,
1914
- buy: { updated: ratioResult.buyUpdated, ratio: ratioResult.buyUpdated, rms: false, metric: 0, shrink: ratioResult.buyShrink === true },
1915
- sell: { updated: ratioResult.sellUpdated, ratio: ratioResult.sellUpdated, rms: false, metric: 0, shrink: ratioResult.sellShrink === true },
1916
- orderType: getOrderTypeFromUpdatedFlags(ratioResult.buyUpdated, ratioResult.sellUpdated)
2128
+ buy: { updated: ratioBuy, ratio: ratioBuy, rms: false, metric: 0, shrink: buyShrink },
2129
+ sell: { updated: ratioSell, ratio: ratioSell, rms: false, metric: 0, shrink: sellShrink },
2130
+ orderType: getOrderTypeFromUpdatedFlags(ratioBuy, ratioSell)
1917
2131
  };
1918
2132
  }
1919
2133
  // 2. Check RMS-based divergence (structural deviation)
1920
2134
  const rmsResult = await compareGrids(calculatedGrid, persistedGrid, manager);
1921
- const buyUpdated = ratioResult.buyUpdated || rmsResult.buy.updated;
1922
- const sellUpdated = ratioResult.sellUpdated || rmsResult.sell.updated;
2135
+ const buyUpdated = rmsResult.buy.updated;
2136
+ const sellUpdated = rmsResult.sell.updated;
1923
2137
  return {
1924
2138
  needsUpdate: buyUpdated || sellUpdated,
1925
- buy: { updated: buyUpdated, ratio: ratioResult.buyUpdated, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: ratioResult.buyShrink === true },
1926
- sell: { updated: sellUpdated, ratio: ratioResult.sellUpdated, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: ratioResult.sellShrink === true },
2139
+ buy: { updated: buyUpdated, ratio: false, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: false },
2140
+ sell: { updated: sellUpdated, ratio: false, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: false },
1927
2141
  orderType: getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated),
1928
2142
  thresholdPct: rmsResult.thresholdPct
1929
2143
  };
@@ -1936,7 +2150,7 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
1936
2150
  */
1937
2151
  function _getOnChainOrders(manager) {
1938
2152
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
1939
- // deep-*) sit outside window accounting — same gate as reserve
2153
+ // deep-*) sit outside window accounting — same gate as edge
1940
2154
  // classification and startup cancel candidates (issue #27 follow-up).
1941
2155
  // Without this, a live shelf masks an empty window side (oneSideEmpty
1942
2156
  // stays false) and skews the spread inputs. No-op on grids that only
@@ -1989,10 +2203,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
1989
2203
  // This prevents concurrent fill processing from modifying funds while we're making decisions
1990
2204
  let correction = null;
1991
2205
  let shouldApplyCorrection = false;
1992
- // Set when determineOrderSideByFunds finds no side to fund: the caller
1993
- // refreshes account totals + open orders so the next cycle re-checks
1994
- // against fresh balances instead of recycling resting orders.
1995
- let fundsExhausted = false;
2206
+ // Why no effective order landed, when that happens. The caller uses the
2207
+ // exact cause (not a boolean) to decide whether a funds/open-orders
2208
+ // refresh can help and to log the truth: 'no-candidates' is structural
2209
+ // and owned by the out-of-spread staleness watchdog, while the fund and
2210
+ // batch causes are what a refresh actually repairs.
2211
+ let stall;
1996
2212
  if (!manager._gridLock) {
1997
2213
  manager.logger?.log?.('Spread check skipped: no grid lock available', 'warn');
1998
2214
  return { ordersPlaced: 0, partialsMoved: 0 };
@@ -2006,6 +2222,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2006
2222
  const lastPrice = (bestBuy !== null && bestSell !== null)
2007
2223
  ? (bestBuy + bestSell) / 2
2008
2224
  : Number(manager.config.startPrice) || 0;
2225
+ // Keep the crossing floor current: refresh the cached live market price
2226
+ // when it is stale, paced to one read per freshness window. The planner
2227
+ // then uses current market truth instead of a possibly days-old fill,
2228
+ // which is what removes the need for a distance heuristic. Best-effort;
2229
+ // on failure the fill anchor remains the fallback.
2230
+ await maybeRefreshLiveMarketPrice(manager, _BitShares);
2009
2231
  // Lock guard is handled at function entry — if _gridLock is absent we return early.
2010
2232
  let fundSnapshot = null;
2011
2233
  // Detect empty-side condition: when one side has zero on-chain orders,
@@ -2034,6 +2256,34 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2034
2256
  manager.outOfSpread = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
2035
2257
  if (manager.outOfSpread === 0)
2036
2258
  return false;
2259
+ // P-A cold book: the orchestration short-circuit, evaluated in the
2260
+ // shared readiness gate so the planner, the crossing filter and the
2261
+ // COW bypass all reason from one verdict. This early return keeps
2262
+ // the cold classification ahead of the one-sided boundary branch.
2263
+ // The planner re-evaluates the gate per call (including the re-plan
2264
+ // path, which deliberately re-reads fresh state), so this is not a
2265
+ // duplicated verdict but the same rule at two points in the cycle.
2266
+ //
2267
+ // A cold book has no realized spread to repair — the "spread" is
2268
+ // synthetic (an empty side plus the startPrice fallback) and a
2269
+ // correction here can only guess a side and place through an unseen
2270
+ // market (issue #31). The reconcile path owns the first window;
2271
+ // 'cold-book' is a structural stall that arms the targeted sync.
2272
+ // Degraded causes (stale/unmatched) keep ok=true. A null reason is
2273
+ // a gate failure (correct-by-refusal) and stalls as 'readiness-gate'.
2274
+ const readiness = evaluateSpreadCorrectionReadiness(manager, {
2275
+ onChainOrders: { buys: onChainBuys, sells: onChainSells }
2276
+ });
2277
+ if (!readiness.ok) {
2278
+ const cold = readiness.reason === 'cold-book';
2279
+ manager.logger?.log?.((cold
2280
+ ? `[SPREAD] Book is cold (no live BUY or SELL on chain); skipping spread correction — ` +
2281
+ `the reconcile path owns the first window.`
2282
+ : `[SPREAD] Spread-correction readiness gate failed; skipping this cycle.`) +
2283
+ ` Requesting a targeted chain sync.`, 'warn');
2284
+ stall = cold ? 'cold-book' : 'readiness-gate';
2285
+ return false;
2286
+ }
2037
2287
  // Check whether the empty side is caused by boundary-at-rail-edge.
2038
2288
  // When the boundary crawl has clamped to 0 or allSlots.length-1,
2039
2289
  // fill pressure can wipe out one entire side. Spread correction
@@ -2085,18 +2335,27 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2085
2335
  catch { /* best-effort */ }
2086
2336
  const decision = determineOrderSideByFunds(manager, lastPrice);
2087
2337
  if (!decision.side) {
2088
- fundsExhausted = true;
2338
+ stall = 'no-free-funds';
2089
2339
  return false;
2090
2340
  }
2091
2341
  // Perform spread correction by placing orders on the chosen side.
2092
2342
  correction = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
2093
- if (!correction)
2343
+ if (!correction) {
2344
+ stall = 'no-candidates';
2094
2345
  return false;
2346
+ }
2095
2347
  let placeCount = correction.ordersToPlace?.length || 0;
2096
- let updateCount = correction.ordersToUpdate?.length || 0;
2348
+ // Fold each side into the stall cause; merge (never overwrite) across
2349
+ // the starvation fallback so an UNFUNDED plan on the chosen side is
2350
+ // not masked by an empty plan on the opposite side. The old code
2351
+ // overwrote plannedCount with the opposite side's 0, so a
2352
+ // planned-1/placed-0 side followed by a planned-0 opposite reported
2353
+ // 'no-candidates' and the maintenance refresh never armed — exactly
2354
+ // the stale-balance case the refresh exists for.
2355
+ let sideStall = classifySpreadStall(correction);
2097
2356
  // STARVATION FALLBACK: If the selected side has no correctable slots (e.g.
2098
2357
  // all SPREAD slots already filled or misaligned), try the opposite side.
2099
- if ((placeCount + updateCount) === 0) {
2358
+ if (placeCount === 0) {
2100
2359
  const oppositeSide = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2101
2360
  manager.logger?.log?.(`[SPREAD] Side ${decision.side} produced zero candidates; ` +
2102
2361
  `trying opposite side ${oppositeSide}.`, 'debug');
@@ -2104,20 +2363,26 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2104
2363
  if (oppositeCorrection) {
2105
2364
  correction = oppositeCorrection;
2106
2365
  placeCount = oppositeCorrection.ordersToPlace?.length || 0;
2107
- updateCount = oppositeCorrection.ordersToUpdate?.length || 0;
2366
+ const oppositeStall = classifySpreadStall(oppositeCorrection);
2367
+ sideStall = (sideStall === 'unfunded' || oppositeStall === 'unfunded')
2368
+ ? 'unfunded'
2369
+ : 'no-candidates';
2108
2370
  }
2109
2371
  }
2110
2372
  // Capture fund snapshot under lock for pre-flight verification before broadcast
2111
2373
  fundSnapshot = _snapshotFundState(manager);
2112
- // No executable correction on EITHER side: the balances/holds may be a
2113
- // stale snapshot (the grid does not lose funds, it holds them in
2114
- // resting/virtual slots), so ask the caller to refresh account totals +
2115
- // open orders instead of re-deriving the identical starved plan next
2116
- // tick. Previously only the "no side at all" case set this flag, so a
2117
- // fund-constrained plan on a chosen side never triggered a refresh.
2118
- if ((placeCount + updateCount) === 0)
2119
- fundsExhausted = true;
2120
- return (placeCount + updateCount) > 0;
2374
+ // No executable correction on EITHER side. Carry the exact cause so the
2375
+ // caller refreshes only when a refresh can actually repair something:
2376
+ // * 'no-candidates' — no spread-tightening slot exists at all. This is
2377
+ // structural; the out-of-spread staleness watchdog escalates it to a
2378
+ // re-center, so it must NOT re-arm the per-cooldown fund/open-orders
2379
+ // refresh (previously every zero-placement did, churning a full
2380
+ // account + open-orders reload on a structurally stalled grid).
2381
+ // * 'unfunded' — a plan existed but free funds could not fund any of it;
2382
+ // the balances/holds may be a stale snapshot, so a refresh is warranted.
2383
+ if (placeCount === 0)
2384
+ stall = sideStall;
2385
+ return placeCount > 0;
2121
2386
  };
2122
2387
  try {
2123
2388
  shouldApplyCorrection = await manager._gridLock.acquire(executeSpreadCheck);
@@ -2165,11 +2430,11 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2165
2430
  manager.logger?.log?.(`[SPREAD] Fund state changed; no side has sufficient funds for re-plan. Skipping cycle.`, 'warn');
2166
2431
  // Same no-free-funds condition as the initial decision:
2167
2432
  // signal the caller to refresh account totals/open orders.
2168
- fundsExhausted = true;
2169
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2433
+ stall = 'no-free-funds';
2434
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2170
2435
  }
2171
2436
  const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
2172
- if (rePlanCorrection && ((rePlanCorrection.ordersToPlace?.length || 0) + (rePlanCorrection.ordersToUpdate?.length || 0) > 0)) {
2437
+ if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
2173
2438
  activeCorrection = rePlanCorrection;
2174
2439
  activeSnapshot = currentFunds;
2175
2440
  manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
@@ -2177,7 +2442,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2177
2442
  }
2178
2443
  else {
2179
2444
  manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
2180
- return { ordersPlaced: 0, partialsMoved: 0 };
2445
+ // A plan existed before the fund change but the re-plan found
2446
+ // nothing executable. Carry the cause here too (F2): this is the
2447
+ // most fund-relevant outcome of all, so it must not silently skip
2448
+ // the refresh request while every sibling branch signals it.
2449
+ stall = classifySpreadStall(rePlanCorrection);
2450
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2181
2451
  }
2182
2452
  }
2183
2453
  try {
@@ -2187,19 +2457,18 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2187
2457
  // Nothing landed: ask the caller to refresh account totals +
2188
2458
  // open orders (stale holds/balances can make the same plan
2189
2459
  // re-derive every cycle).
2190
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
2460
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed' };
2191
2461
  }
2192
2462
  await manager.recalculateFunds();
2193
2463
  const placed = activeCorrection.ordersToPlace?.length || 0;
2194
- const updated = activeCorrection.ordersToUpdate?.length || 0;
2195
- return { ordersPlaced: placed + updated, partialsMoved: updated };
2464
+ return { ordersPlaced: placed, partialsMoved: 0 };
2196
2465
  }
2197
2466
  catch (err) {
2198
2467
  manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
2199
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
2468
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
2200
2469
  }
2201
2470
  }
2202
- return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
2471
+ return { ordersPlaced: 0, partialsMoved: 0, stall };
2203
2472
  }
2204
2473
  /**
2205
2474
  * Grid health check for structural violations.
@@ -2506,7 +2775,7 @@ function resolveMinSpreadOrdersReserve(manager) {
2506
2775
  // DEFENSE-IN-DEPTH WALK BOUNDS: the loop itself also stops
2507
2776
  // MIN_SPREAD_ORDERS short of the opposite rail edge (idx <= sellStartIdx−1−
2508
2777
  // reserve for BUY / idx >= buyEndIdx+1+reserve for SELL), so even if the
2509
- // cap above is ever miscomputed the walk cannot consume the reserved gap.
2778
+ // cap above is ever miscomputed the walk cannot consume the edged gap.
2510
2779
  // When bandSize <= reserve the bound disables promotion entirely.
2511
2780
  function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, quota, spreadReserve, maxDepth) {
2512
2781
  const isBuy = railType === ORDER_TYPES.BUY;
@@ -2548,6 +2817,32 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2548
2817
  throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
2549
2818
  }
2550
2819
  const ordersToPlace = [];
2820
+ // SHARED READINESS GATE (P-A/P-B/P-C): one verdict for the planner, the
2821
+ // crossing filter and the COW bypass. Hard refusal (cold book) returns
2822
+ // before any planning; degraded causes (stale/unmatched) keep planning
2823
+ // but withhold the bypass and drive the collision filter below.
2824
+ const onChainView = _getOnChainOrders(manager);
2825
+ const readiness = evaluateSpreadCorrectionReadiness(manager, {
2826
+ onChainOrders: { buys: onChainView.onChainBuys, sells: onChainView.onChainSells }
2827
+ });
2828
+ if (!readiness.ok) {
2829
+ // Only 'cold-book' is a named hard-refusal premise; a null reason is
2830
+ // a gate failure and gets its own stall so triage logs are precise.
2831
+ // Either way the targeted sync arms via the stall.
2832
+ const hardRefusalStall = readiness.reason === 'cold-book'
2833
+ ? 'cold-book'
2834
+ : 'readiness-gate';
2835
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing cycle: ${readiness.reason ?? 'readiness-gate-error'} — a targeted sync will re-evaluate`, 'warn');
2836
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: hardRefusalStall, origin: COW_ORIGINS.SPREAD_CORRECTION };
2837
+ }
2838
+ // Empty-candidate stall cause: name the collision case when unmatched
2839
+ // orders are present, so the targeted-sync reason states the truth.
2840
+ // Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
2841
+ // stale > unmatched), so a stale+unmatched cycle reports 'stale-snapshot'
2842
+ // and would otherwise mask the collision cause.
2843
+ const refusalStallHint = readiness.unmatched.length > 0
2844
+ ? 'unmatched-orders'
2845
+ : 'no-candidates';
2551
2846
  const railType = preferredSide;
2552
2847
  const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
2553
2848
  const configuredMissingSlots = Number(outOfSpread || 0);
@@ -2629,7 +2924,9 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2629
2924
  // market-nearest comparator that replaced it fixed that case but sorts
2630
2925
  // the FAR end first when the empties sit BELOW the window (the normal
2631
2926
  // post-fill state), which is the same class of bug mirrored.
2632
- const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2927
+ // Reuse the gate's view: one slot-gated scan per planner call feeds both
2928
+ // the readiness verdict and the live window edges below.
2929
+ const { onChainBuys, onChainSells } = onChainView;
2633
2930
  const railBestIsMax = railType === ORDER_TYPES.BUY;
2634
2931
  const bestLiveOnRail = railBestIsMax
2635
2932
  ? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
@@ -2676,23 +2973,88 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2676
2973
  // With no live order on the side there is no reference to improve, so
2677
2974
  // the market-nearest slot is by definition the best available and the
2678
2975
  // guard stays open.
2976
+ // F3: a null/non-finite price must never enter a candidate pool. The
2977
+ // pools are sorted by distance and sliced to missingSlots BEFORE the
2978
+ // duplicate-price filter drops null prices, so a null-price orphan would
2979
+ // otherwise consume a quota seat (JS coerces null to 0, sorting it first
2980
+ // on a SELL rail) and evict the window-nearest valid slot. Rejecting it
2981
+ // here is the single chokepoint both pools already pass through.
2679
2982
  const tightensSpread = (c) => {
2680
- if (bestLiveOnRail == null || c?.price == null)
2983
+ if (c?.price == null || !Number.isFinite(c.price))
2984
+ return false;
2985
+ if (bestLiveOnRail == null)
2681
2986
  return true;
2682
2987
  return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
2683
2988
  };
2989
+ // MARKET-CROSSING GUARD: never place a SELL at/below (or a BUY at/above)
2990
+ // the last price the account actually traded at. On a one-sided or
2991
+ // freshly-regenerated book the local anchor is absent, so without this
2992
+ // the correction happily sells under a market it cannot see (issue
2993
+ // #31). Fail-open when no real fill is known — never guess from grid
2994
+ // geometry. This complements tightensSpread (which is anchor-relative)
2995
+ // with an absolute, market-relative floor.
2996
+ // Crossing floor from the shared readiness verdict: a fresh live market
2997
+ // read when available, else the fill-derived reference. No distance
2998
+ // heuristic — the floor is kept current rather than judged stale.
2999
+ const marketRef = readiness.marketRef;
3000
+ const doesNotCrossMarket = (c) => {
3001
+ if (marketRef == null || c?.price == null || !Number.isFinite(c.price))
3002
+ return true;
3003
+ return railBestIsMax ? c.price < marketRef : c.price > marketRef;
3004
+ };
3005
+ // P-C COLLISION FILTER: when the gate saw fresh unmatched chain orders,
3006
+ // drop candidates whose price level they already occupy — placing
3007
+ // another order at the same level would duplicate a live order the
3008
+ // grid has not adopted yet. Price-level only: the unmatched row carries
3009
+ // no side, and a duplicate at a level is a duplicate regardless.
3010
+ //
3011
+ // Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
3012
+ // stale > unmatched), so a stale+unmatched cycle reports
3013
+ // 'stale-snapshot' while the unmatched list is fully populated. The
3014
+ // P4 protection must not expire with snapshot staleness — those chain
3015
+ // orders only clear on the next sync.
3016
+ const unmatchedPrices = readiness.unmatched.length > 0
3017
+ ? readiness.unmatched.map((u) => Number(u?.price)).filter((p) => Number.isFinite(p) && p > 0)
3018
+ : [];
3019
+ const doesNotCollideUnmatched = (c) => {
3020
+ if (unmatchedPrices.length === 0 || c?.price == null || !Number.isFinite(c.price))
3021
+ return true;
3022
+ const precision = railType === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
3023
+ return !unmatchedPrices.some((p) => {
3024
+ try {
3025
+ return priceSlotEqual(p, c.price, precision);
3026
+ }
3027
+ catch {
3028
+ return Math.abs(p - c.price) / c.price <= ((manager.config.incrementPercent ?? 0) / 100);
3029
+ }
3030
+ });
3031
+ };
3032
+ if (unmatchedPrices.length > 0) {
3033
+ manager.logger?.log?.(`[SPREAD-CORRECTION] ${unmatchedPrices.length} known-unmatched chain price level(s) excluded from ${sideName} candidates — sync will adopt them first`, 'warn');
3034
+ }
2684
3035
  const typedSpreadCandidates = allOrders
2685
3036
  .filter((o) => o.type === ORDER_TYPES.SPREAD
2686
3037
  && isSlotAvailable(o)
2687
3038
  && getSlotCorrectType(o) === railType)
2688
3039
  .filter(tightensSpread)
3040
+ .filter(doesNotCrossMarket)
3041
+ .filter(doesNotCollideUnmatched)
2689
3042
  .sort(sortCandidates)
2690
3043
  .slice(0, missingSlots);
2691
3044
  // Secondary candidates: orphaned virtual slots that have lost their
2692
3045
  // order (e.g. stale-cleaned after a race condition during a crash, or a
2693
3046
  // lowest-sell slot dust-cancelled and then left unplaced after a
2694
- // boundary shift). These sit inside the active window and are invisible
2695
- // to the gap-band SPREAD filter above.
3047
+ // boundary shift). They are invisible to the gap-band SPREAD filter
3048
+ // above because they are stored as railType (not SPREAD).
3049
+ //
3050
+ // SCOPE (F4): this path repairs only orphans at the window's market
3051
+ // edge — the tightensSpread guard below keeps a SELL below the lowest
3052
+ // live sell and a BUY above the highest live buy. An orphan that sits
3053
+ // in the rail INTERIOR (between two live orders) leaves bestBuy/bestSell
3054
+ // bit-for-bit unchanged, so it is deliberately excluded here; interior
3055
+ // holes are a divergence/reconcile concern, not a spread repair. Do not
3056
+ // "fix" the guard to admit them — filling them would not tighten a
3057
+ // spread and would fight the window-contiguous placement strategy.
2696
3058
  //
2697
3059
  // Empty slots are stored SPREAD (side-neutral) after normalization, so
2698
3060
  // the stored type can be railType OR SPREAD — what matters is that the
@@ -2719,6 +3081,8 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2719
3081
  && !o.orderId
2720
3082
  && getSlotCorrectType(o) === railType)
2721
3083
  .filter(tightensSpread)
3084
+ .filter(doesNotCrossMarket)
3085
+ .filter(doesNotCollideUnmatched)
2722
3086
  .sort(sortCandidates)
2723
3087
  .slice(0, missingSlots);
2724
3088
  // If the funded rail is full, the spread itself may be stale: the
@@ -2763,6 +3127,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2763
3127
  if (boundaryKnown && orphanedVirtualCandidates.length + typedSpreadCandidates.length < missingSlots) {
2764
3128
  const rawQuota = missingSlots - orphanedVirtualCandidates.length - typedSpreadCandidates.length;
2765
3129
  promotedCandidates.push(..._collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, rawQuota, spreadReserve, maxPromotionDepth));
3130
+ // A boundary promotion moves the window into the spread band. If
3131
+ // any of the contiguous run would land through the last real fill,
3132
+ // the whole promotion is refused (dropping only the first slot
3133
+ // would break the run's contiguity and the boundary derivation).
3134
+ const crossingPromoted = marketRef == null
3135
+ ? []
3136
+ : promotedCandidates.filter((c) => !doesNotCrossMarket(c));
3137
+ const collidingPromoted = promotedCandidates.filter((c) => !doesNotCollideUnmatched(c));
3138
+ if (marketRef != null && crossingPromoted.length > 0) {
3139
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
3140
+ `${crossingPromoted.length} slot(s) would cross the last market fill ` +
3141
+ `${Format.formatPrice6(marketRef)}`, 'warn');
3142
+ promotedCandidates.length = 0;
3143
+ }
3144
+ else if (collidingPromoted.length > 0) {
3145
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
3146
+ `${collidingPromoted.length} slot(s) collide with known-unmatched chain orders`, 'warn');
3147
+ promotedCandidates.length = 0;
3148
+ }
2766
3149
  if (promotedCandidates.length > 0) {
2767
3150
  manager.logger?.log?.(`[SPREAD-CORRECTION] ${promotedCandidates.length} gap slot(s) available for boundary promotion on ${sideName}`, 'info');
2768
3151
  }
@@ -2850,7 +3233,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2850
3233
  manager.logger?.log?.(bestLiveOnRail == null
2851
3234
  ? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
2852
3235
  : `[SPREAD-CORRECTION] No spread-tightening slot on ${sideName} (best live ${bestLiveOnRail}); every remaining empty slot sits beyond the live window and cannot narrow the spread. Skipping.`, 'warn');
2853
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
3236
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: refusalStallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
2854
3237
  }
2855
3238
  const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
2856
3239
  const sideSlots = allOrders
@@ -2862,7 +3245,12 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2862
3245
  ].sort((a, b) => a.price - b.price);
2863
3246
  const ctx = await _getSizingContext(manager, sideName);
2864
3247
  if (!ctx || ctx.budget <= 0 || syntheticSideSlots.length === 0) {
2865
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
3248
+ // A zero sizing budget is a FUND condition (stale/empty free balance),
3249
+ // not a structural one — mark it 'unfunded' so the caller keeps
3250
+ // arming the refresh for it. A missing context or an empty rail is
3251
+ // genuinely structural.
3252
+ const stallHint = (ctx && Number(ctx.budget) <= 0) ? 'unfunded' : 'no-candidates';
3253
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
2866
3254
  }
2867
3255
  const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
2868
3256
  const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
@@ -2901,7 +3289,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2901
3289
  }
2902
3290
  }
2903
3291
  if (prioritizedTargets.length === 0) {
2904
- return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
3292
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
2905
3293
  }
2906
3294
  let remainingBudget = availableFund;
2907
3295
  // FUNDING PROBE (diagnostic): one line per correction cycle showing the
@@ -2981,7 +3369,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2981
3369
  // inside the implied band. All real constraints — the
2982
3370
  // MIN_SPREAD_ORDERS reserve and opposite-rail stranding — are
2983
3371
  // enforced UPSTREAM as walk-depth caps. This backstop only
2984
- // verifies array limits plus the reserve ceiling; any
3372
+ // verifies array limits plus the edge ceiling; any
2985
3373
  // violation signals an internal inconsistency, so promotion is
2986
3374
  // refused loudly instead of silently re-geometried.
2987
3375
  const maxIdx = allSlotsByPrice.length - 1;
@@ -3013,6 +3401,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3013
3401
  if (ordersToPlace.length > 0) {
3014
3402
  manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
3015
3403
  }
3016
- return { ordersToPlace, ordersToUpdate: [], ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: 'spread-correction' };
3404
+ return { ordersToPlace, ordersToUpdate: [], plannedCount: prioritizedTargets.length, ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: COW_ORIGINS.SPREAD_CORRECTION };
3017
3405
  }
3018
3406
  //# sourceMappingURL=grid.js.map