dexbot 1.6.13 → 1.6.15

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 (114) hide show
  1. package/CHANGELOG.md +66 -4
  2. package/README.md +2 -2
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_catalog.ts +8 -4
  9. package/claw/modules/dexbot_profiles.ts +59 -15
  10. package/claw/modules/types.ts +2 -1
  11. package/claw/package.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  14. package/claw/skills/margin-trading/SKILL.md +1 -1
  15. package/claw/skills/margin-trading/references/position-management.md +1 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
  17. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  18. package/dist/dexbot.js +23 -3
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  20. package/dist/modules/account_bots.d.ts +10 -6
  21. package/dist/modules/account_bots.js +13 -10
  22. package/dist/modules/account_orders.d.ts +36 -4
  23. package/dist/modules/account_orders.js +76 -5
  24. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  25. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  26. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  27. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  28. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  29. package/dist/modules/bot_defaults.d.ts +29 -4
  30. package/dist/modules/bot_defaults.js +65 -10
  31. package/dist/modules/bot_settings.d.ts +4 -0
  32. package/dist/modules/bot_settings.js +58 -21
  33. package/dist/modules/config.js +6 -1
  34. package/dist/modules/constants.d.ts +13 -5
  35. package/dist/modules/constants.js +36 -5
  36. package/dist/modules/credit_runtime.d.ts +35 -5
  37. package/dist/modules/credit_runtime.js +219 -38
  38. package/dist/modules/dexbot_class.d.ts +23 -0
  39. package/dist/modules/dexbot_class.js +60 -17
  40. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  41. package/dist/modules/dexbot_cow_runtime.js +350 -64
  42. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  43. package/dist/modules/dexbot_credential_client.js +1 -1
  44. package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
  45. package/dist/modules/dexbot_fill_runtime.js +16 -8
  46. package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
  47. package/dist/modules/dexbot_maintenance_runtime.js +104 -70
  48. package/dist/modules/dexbot_startup_runtime.js +15 -2
  49. package/dist/modules/dexbot_state_recovery.js +17 -1
  50. package/dist/modules/key_store.d.ts +0 -5
  51. package/dist/modules/key_store.js +1 -1
  52. package/dist/modules/order/accounting.js +11 -11
  53. package/dist/modules/order/export.js +4 -4
  54. package/dist/modules/order/format.d.ts +15 -1
  55. package/dist/modules/order/format.js +19 -1
  56. package/dist/modules/order/genesis_policy.d.ts +1 -1
  57. package/dist/modules/order/genesis_policy.js +1 -1
  58. package/dist/modules/order/grid.d.ts +141 -12
  59. package/dist/modules/order/grid.js +666 -92
  60. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  61. package/dist/modules/order/grid_reconcile.js +9 -8
  62. package/dist/modules/order/grid_reconcile_internal.js +61 -58
  63. package/dist/modules/order/index.d.ts +37 -9
  64. package/dist/modules/order/logger.js +2 -2
  65. package/dist/modules/order/manager.d.ts +10 -2
  66. package/dist/modules/order/manager.js +56 -31
  67. package/dist/modules/order/strategy.d.ts +2 -2
  68. package/dist/modules/order/strategy.js +51 -21
  69. package/dist/modules/order/sync_engine.js +22 -9
  70. package/dist/modules/order/utils/math.d.ts +101 -29
  71. package/dist/modules/order/utils/math.js +215 -84
  72. package/dist/modules/order/utils/order.d.ts +58 -58
  73. package/dist/modules/order/utils/order.js +135 -106
  74. package/dist/modules/order/utils/system.d.ts +193 -6
  75. package/dist/modules/order/utils/system.js +394 -31
  76. package/dist/modules/order/utils/validate.d.ts +1 -1
  77. package/dist/modules/order/utils/validate.js +71 -59
  78. package/dist/modules/runtime_settings.d.ts +1 -1
  79. package/dist/modules/runtime_settings.js +3 -3
  80. package/dist/modules/types.d.ts +55 -4
  81. package/dist/scripts/analyze-credit.js +44 -27
  82. package/dist/scripts/analyze-orders.d.ts +1 -1
  83. package/dist/scripts/analyze-orders.js +4 -4
  84. package/dist/scripts/diagnose-pool-history.js +35 -30
  85. package/dist/scripts/divergence-calc.js +6 -6
  86. package/dist/scripts/pnl.js +1 -1
  87. package/dist/scripts/rich_list.d.ts +18 -0
  88. package/dist/scripts/rich_list.js +461 -0
  89. package/dist/scripts/run-tests.js +80 -4
  90. package/dist/scripts/validate_bots.d.ts +1 -1
  91. package/dist/scripts/validate_bots.js +3 -3
  92. package/dist/unlock.d.ts +2 -1
  93. package/dist/unlock.js +11 -5
  94. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  95. package/docs/COW_INVARIANTS.md +12 -6
  96. package/docs/DEXBOT_COMPARISON.md +7 -7
  97. package/docs/EVOLUTION.md +10 -8
  98. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  99. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  100. package/docs/GRID_RECALCULATION.md +4 -1
  101. package/docs/GRID_RECONCILE.md +4 -4
  102. package/docs/LIFECYCLE.md +11 -11
  103. package/docs/LOGGING.md +30 -1
  104. package/docs/MPA_CREDIT_USAGE.md +11 -6
  105. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
  106. package/docs/README.md +3 -3
  107. package/docs/WORKFLOW.md +1 -0
  108. package/docs/architecture.md +62 -8
  109. package/docs/developer_guide.md +12 -3
  110. package/market_adapter/README.md +4 -4
  111. package/modules/README.md +1 -1
  112. package/package.json +2 -1
  113. package/scripts/README.md +59 -32
  114. package/tests/README.md +12 -3
@@ -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
@@ -99,16 +102,212 @@ const GRID_CONSTANTS = {
99
102
  /**
100
103
  * Fold a prepared correction (or the absence of one) into the stall cause the
101
104
  * caller reports. A plan that existed but funded nothing ('unfunded'), or a
102
- * zero sizing budget ('stallHint: unfunded'), is a FUND condition; anything
103
- * else is a structural 'no-candidates'. The two sides are merged with this so
104
- * an unfunded plan on one side is never masked by an empty plan on the other
105
- * (e.g. chosen side planned 1 / placed 0, opposite side planned 0).
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).
106
110
  */
107
111
  function classifySpreadStall(c) {
108
- if (Number(c?.plannedCount || 0) > 0 || c?.stallHint === 'unfunded')
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')
109
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;
110
122
  return 'no-candidates';
111
123
  }
124
+ /**
125
+ * Spread-correction refusal causes — the single vocabulary shared by
126
+ * classifySpreadRefusalCause, the retry/transience decision and the
127
+ * spreadCorrectionRefusalCauses metric key. Keep every reader/writer keyed off
128
+ * this map so a new cause cannot leave classification and transience out of
129
+ * sync.
130
+ */
131
+ export const SPREAD_CORRECTION_REFUSAL = Object.freeze({
132
+ /** Post-broadcast working-grid commit rejected (orders may already be on chain). */
133
+ COMMIT_REFUSED: 'commit-refused',
134
+ /** Plan went stale / skipped before broadcast (base-version mismatch). */
135
+ VERSION_MISMATCH: 'version-mismatch',
136
+ /** A tracked UPDATE target was gone on chain (COW pre-broadcast guard). */
137
+ UPDATE_TARGET_MISSING: 'update-target-missing',
138
+ /** Destination slot already held an active order (plan-time dedupe). */
139
+ CREATE_COLLISION: 'create-collision',
140
+ /** Unmatched chain orders blocked the CREATE batch. */
141
+ UNMATCHED_CHAIN_ORDERS: 'unmatched-chain-orders',
142
+ /** Shutdown began while the batch was in flight. */
143
+ SHUTDOWN: 'shutdown',
144
+ /** Unclassified non-execution (fallback). */
145
+ BATCH_NOT_EXECUTED: 'batch-not-executed'
146
+ });
147
+ /**
148
+ * Causes the bounded in-cycle re-plan can heal. `commit-refused` is deliberately
149
+ * EXCLUDED: the batch reached the chain (chain adoption runs), so it is not a
150
+ * clean pre-broadcast staleness a fresh-master re-plan repairs — it should count
151
+ * toward the persistent-stale watchdog instead.
152
+ */
153
+ const TRANSIENT_SPREAD_CORRECTION_REFUSALS = new Set([
154
+ SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH,
155
+ SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION,
156
+ SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED
157
+ ]);
158
+ /**
159
+ * Whether a refusal cause is retryable by the bounded spread-correction re-plan.
160
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
161
+ * @returns {boolean}
162
+ */
163
+ export function isTransientSpreadRefusal(cause) {
164
+ return TRANSIENT_SPREAD_CORRECTION_REFUSALS.has(cause);
165
+ }
166
+ /**
167
+ * P0 observability: classify WHY a spread-correction batch did not land
168
+ * (executed !== true) from the COW batch result. Counter-only — never gates
169
+ * placement. Returns a SPREAD_CORRECTION_REFUSAL value so the metric key, the
170
+ * retry decision and the log all share one vocabulary.
171
+ * @param {Object|null} batchResult - The COW batch result
172
+ * @returns {string} A SPREAD_CORRECTION_REFUSAL value
173
+ */
174
+ export function classifySpreadRefusalCause(batchResult) {
175
+ const r = (batchResult ?? {});
176
+ const reason = String(r.reason ?? '').toUpperCase();
177
+ if (r.commitRefused === true)
178
+ return SPREAD_CORRECTION_REFUSAL.COMMIT_REFUSED;
179
+ if (reason === 'UPDATE_TARGET_MISSING')
180
+ return SPREAD_CORRECTION_REFUSAL.UPDATE_TARGET_MISSING;
181
+ if (reason === 'UNMATCHED_CHAIN_ORDERS')
182
+ return SPREAD_CORRECTION_REFUSAL.UNMATCHED_CHAIN_ORDERS;
183
+ if (reason === 'SHUTDOWN_IN_PROGRESS')
184
+ return SPREAD_CORRECTION_REFUSAL.SHUTDOWN;
185
+ if (r.skippedStalePlan === true || reason.includes('STALE') || reason.includes('MISMATCH') || reason.includes('BASE VERSION'))
186
+ return SPREAD_CORRECTION_REFUSAL.VERSION_MISMATCH;
187
+ if (reason.includes('COLLISION') || reason.includes('EXISTING') || reason.includes('DUPLICATE'))
188
+ return SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION;
189
+ return SPREAD_CORRECTION_REFUSAL.BATCH_NOT_EXECUTED;
190
+ }
191
+ /**
192
+ * P0 observability: record a spread-correction refusal on the manager's
193
+ * metrics (the only object reachable from this planner; getMetrics overlays
194
+ * these onto the bot's counters). Counter-only; never throws, never gates.
195
+ * @param {Object} manager - OrderManager instance
196
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
197
+ */
198
+ export function recordSpreadCorrectionRefusal(manager, cause) {
199
+ try {
200
+ const m = manager?._metrics;
201
+ if (!m)
202
+ return;
203
+ m.spreadCorrectionRefusedCount = (Number(m.spreadCorrectionRefusedCount) || 0) + 1;
204
+ const causes = (m.spreadCorrectionRefusalCauses && typeof m.spreadCorrectionRefusalCauses === 'object')
205
+ ? m.spreadCorrectionRefusalCauses
206
+ : (m.spreadCorrectionRefusalCauses = {});
207
+ causes[cause] = (Number(causes[cause]) || 0) + 1;
208
+ }
209
+ catch { /* metrics are best-effort */ }
210
+ }
211
+ /**
212
+ * P5 observability: count a bounded spread-correction re-plan retry. Churn
213
+ * signal — a rising retry rate means concurrent commits are repeatedly
214
+ * invalidating corrections. Counter-only; never throws.
215
+ * @param {Object} manager - OrderManager instance
216
+ */
217
+ export function recordSpreadCorrectionRetry(manager) {
218
+ try {
219
+ const m = manager?._metrics;
220
+ if (!m)
221
+ return;
222
+ m.spreadCorrectionRetryCount = (Number(m.spreadCorrectionRetryCount) || 0) + 1;
223
+ }
224
+ catch { /* metrics are best-effort */ }
225
+ }
226
+ /**
227
+ * P2 plan-time dedupe: which of a correction's planned CREATE destinations are
228
+ * now occupied by a live (ACTIVE/PARTIAL) order with a chain id?
229
+ *
230
+ * The correction is planned under _gridLock, then broadcast after the lock is
231
+ * released. A concurrent fill rebalance can commit an order onto one of the
232
+ * planned slots in that window; the COW build layer then rejects the whole
233
+ * batch (`Rejecting CREATE … existing orderId`). Detecting it here turns that
234
+ * into a cheap plan-time re-derive (see the retry loop in checkSpreadCondition)
235
+ * instead of a mid-broadcast refusal and structural resync.
236
+ *
237
+ * Pure and never throws. A missing/non-Map orders store selects the empty set.
238
+ * @param {Object} manager - OrderManager instance
239
+ * @param {Object|null} correction - Prepared spread correction
240
+ * @returns {string[]} Occupied planned slot ids
241
+ */
242
+ export function getOccupiedCorrectionSlots(manager, correction) {
243
+ const occupied = [];
244
+ try {
245
+ const orders = manager.orders;
246
+ if (!(orders instanceof Map) || !correction)
247
+ return occupied;
248
+ for (const o of correction.ordersToPlace || []) {
249
+ const cur = orders.get(o.id);
250
+ if (!cur)
251
+ continue;
252
+ const liveState = cur.state === ORDER_STATES.ACTIVE || cur.state === ORDER_STATES.PARTIAL;
253
+ if (liveState && cur.orderId)
254
+ occupied.push(o.id);
255
+ }
256
+ }
257
+ catch { /* best-effort detection */ }
258
+ return occupied;
259
+ }
260
+ /**
261
+ * P1/P3 shared re-plan: derive a spread correction from the CURRENT master
262
+ * state (side chosen from fresh on-chain book, opposite-side starvation
263
+ * fallback). Used both for the plan-time collision dedupe and the bounded
264
+ * refusal retry. Read-only against the grid; no _gridLock needed (matches the
265
+ * existing TOCTOU fund re-plan contract).
266
+ * @param {Object} manager - OrderManager instance
267
+ * @returns {Promise<Object|null>} A correction with at least one create, or null
268
+ */
269
+ export async function replanSpreadCorrectionFromFreshMaster(manager) {
270
+ const freshOnChain = _getOnChainOrders(manager);
271
+ const freshBest = getGridBestPrices(freshOnChain.onChainBuys, freshOnChain.onChainSells);
272
+ const freshPrice = (freshBest.bestBuy !== null && freshBest.bestSell !== null)
273
+ ? (freshBest.bestBuy + freshBest.bestSell) / 2
274
+ : Number(manager.config.startPrice) || 0;
275
+ const decision = determineOrderSideByFunds(manager, freshPrice);
276
+ if (!decision.side)
277
+ return null;
278
+ let c = await prepareSpreadCorrectionOrders(manager, decision.side, manager.outOfSpread);
279
+ if ((c?.ordersToPlace?.length || 0) === 0) {
280
+ const opposite = decision.side === ORDER_TYPES.BUY ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
281
+ const oc = await prepareSpreadCorrectionOrders(manager, opposite, manager.outOfSpread);
282
+ if ((oc?.ordersToPlace?.length || 0) > 0)
283
+ c = oc;
284
+ }
285
+ return c;
286
+ }
287
+ /**
288
+ * P2: resolve a planned correction whose CREATE destination(s) were taken after
289
+ * planning. Detects the collision, re-derives once from fresh master, and
290
+ * reports whether the caller should broadcast, swap in the re-plan, or refuse.
291
+ *
292
+ * Extracted from checkSpreadCondition so the branch is a real, production-called
293
+ * unit that tests can drive directly (no test-only hook in the production path).
294
+ *
295
+ * @param {Object} manager - OrderManager instance
296
+ * @param {Object|null} correction - The plan about to broadcast
297
+ * @param {number} attempt - 1-based attempt index
298
+ * @param {number} maxAttempts - Total attempts allowed
299
+ * @returns {Promise<OccupiedCorrectionResolution>}
300
+ */
301
+ export async function resolveOccupiedCorrection(manager, correction, attempt, maxAttempts) {
302
+ const occupied = getOccupiedCorrectionSlots(manager, correction);
303
+ if (!(occupied.length > 0 && attempt < maxAttempts))
304
+ return { action: 'broadcast' };
305
+ const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
306
+ if (replanned && (replanned.ordersToPlace?.length || 0) > 0) {
307
+ return { action: 'replanned', correction: replanned, occupied };
308
+ }
309
+ return { action: 'blocked', occupied };
310
+ }
112
311
  /**
113
312
  * Central resolution for the RMS structural-divergence threshold (percent).
114
313
  * Single source of truth: per-bot override wins, global GRID_COMPARISON default
@@ -129,9 +328,9 @@ function _snapshotFundState(manager) {
129
328
  sellLocked: Number(manager.accountTotals?.sellLocked || 0),
130
329
  };
131
330
  }
132
- 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';
133
- 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';
134
- import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot } from './utils/system.js';
331
+ import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
332
+ 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';
333
+ import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice } from './utils/system.js';
135
334
  import * as MathUtils from './utils/math.js';
136
335
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
137
336
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
@@ -230,13 +429,9 @@ export function clearGridBloatFlag(manager) {
230
429
  * @returns {Promise<any|null>}
231
430
  * @private
232
431
  */
233
- export async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
432
+ function _computeSizingContextSync(manager, side) {
234
433
  if (!manager || !manager.assets)
235
434
  return null;
236
- // 1. Ensure fund state is fresh before sizing
237
- if (!skipRecalc) {
238
- await manager.recalculateFunds();
239
- }
240
435
  const snap = manager.getChainFundsSnapshot ? manager.getChainFundsSnapshot() : {};
241
436
  const isBuy = side === 'buy';
242
437
  const type = isBuy ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
@@ -247,8 +442,8 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
247
442
  // BTS fees are paid for ALL order operations regardless of side, so the
248
443
  // BTS-holding side reserves fees for both buy and sell target counts.
249
444
  if (budget > 0) {
250
- const targetBuy = Math.max(0, manager.config.activeOrders?.buy ?? 1) + resolveReserveCount(manager.config, 'buy');
251
- const targetSell = Math.max(0, manager.config.activeOrders?.sell ?? 1) + resolveReserveCount(manager.config, 'sell');
445
+ const targetBuy = Math.max(0, manager.config.coreOrders?.buy ?? 1) + resolveEdgeCount(manager.config, 'buy');
446
+ const targetSell = Math.max(0, manager.config.coreOrders?.sell ?? 1) + resolveEdgeCount(manager.config, 'sell');
252
447
  const totalTarget = targetBuy + targetSell;
253
448
  const btsOrderType = getBtsSide(manager.config?.assetA, manager.config?.assetB);
254
449
  const isBtsSide = isBuy ? (btsOrderType === ORDER_TYPES.BUY) : (btsOrderType === ORDER_TYPES.SELL);
@@ -269,6 +464,19 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
269
464
  config: manager.config
270
465
  };
271
466
  }
467
+ /**
468
+ * Async sizing-context accessor. Refreshes funds unless `skipRecalc`, then
469
+ * delegates to the sync core. Both divergence legs (ratio and committed
470
+ * drift) size through the sync core so they read one fund snapshot.
471
+ */
472
+ export async function _getSizingContext(manager, side, { skipRecalc = false } = {}) {
473
+ if (!manager || !manager.assets)
474
+ return null;
475
+ if (!skipRecalc) {
476
+ await manager.recalculateFunds();
477
+ }
478
+ return _computeSizingContextSync(manager, side);
479
+ }
272
480
  /**
273
481
  * Create the initial order grid structure based on configuration.
274
482
  *
@@ -639,7 +847,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
639
847
  // band, GAP-EVAC already tracking it): keep the boundary so
640
848
  // the heal path (rotation/teeth/sweeps) can run. Nuking it
641
849
  // here would discard the evacuation state for exactly the
642
- // condition evacuation exists to fix (H-BTS 2026-09-13).
850
+ // condition evacuation exists to fix (<bot> 2026-09-13).
643
851
  manager.logger?.log?.(`[GRID-LOAD] Persisted snapshot has transient in-band placement (${check.reason}): ${check.detail}. ` +
644
852
  `Keeping boundary ${restoredBoundary}; GAP-EVAC/sync sweeps own cleanup.`, 'warn');
645
853
  }
@@ -1133,22 +1341,22 @@ export async function initializeGrid(manager) {
1133
1341
  const startPriceWasDerived = typeof mpRaw !== 'number' || Number.isNaN(Number(mpRaw));
1134
1342
  const centerIsLive = startPriceWasDerived || gpSource === 'ama';
1135
1343
  if (owedCrawls.length > 0 && !centerIsLive) {
1136
- // Reserve fills never crawl (static insurance). Classify them
1344
+ // Edge fills never crawl (static insurance). Classify them
1137
1345
  // against the OLD generation (manager.orders is replaced below)
1138
1346
  // with the same live anchors the runtime derivation uses, so the
1139
- // fold can never be driven by a reserve fill.
1347
+ // fold can never be driven by an edge fill.
1140
1348
  const oldSlots = Array.from(manager.orders.values());
1141
1349
  const edgeAnchors = {
1142
- buy: resolveLiveReserveEdgeAnchorPrice(manager, 'buy'),
1143
- sell: resolveLiveReserveEdgeAnchorPrice(manager, 'sell')
1350
+ buy: resolveLiveEdgeAnchorPrice(manager, 'buy'),
1351
+ sell: resolveLiveEdgeAnchorPrice(manager, 'sell')
1144
1352
  };
1145
- const reserveBuyIds = reserveEdgeIdSet(oldSlots, manager.config, ORDER_TYPES.BUY, edgeAnchors.buy, liveWindowIdSet(manager, ORDER_TYPES.BUY));
1146
- const reserveSellIds = reserveEdgeIdSet(oldSlots, manager.config, ORDER_TYPES.SELL, edgeAnchors.sell, liveWindowIdSet(manager, ORDER_TYPES.SELL));
1353
+ const edgeBuyIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.BUY, edgeAnchors.buy, liveWindowIdSet(manager, ORDER_TYPES.BUY));
1354
+ const edgeSellIds = edgeOrderIdSet(oldSlots, manager.config, ORDER_TYPES.SELL, edgeAnchors.sell, liveWindowIdSet(manager, ORDER_TYPES.SELL));
1147
1355
  let netShift = 0;
1148
1356
  for (const e of owedCrawls) {
1149
- if (e?.side === ORDER_TYPES.BUY && reserveBuyIds?.has(e.slotId))
1357
+ if (e?.side === ORDER_TYPES.BUY && edgeBuyIds?.has(e.slotId))
1150
1358
  continue;
1151
- if (e?.side === ORDER_TYPES.SELL && reserveSellIds?.has(e.slotId))
1359
+ if (e?.side === ORDER_TYPES.SELL && edgeSellIds?.has(e.slotId))
1152
1360
  continue;
1153
1361
  if (e?.side === ORDER_TYPES.SELL)
1154
1362
  netShift++;
@@ -1445,14 +1653,14 @@ export function checkAndUpdateGridIfNeeded(manager) {
1445
1653
  for (const s of sides) {
1446
1654
  if (s.grid <= 0)
1447
1655
  continue;
1448
- const feeActiveOrders = manager.config.activeOrders && typeof manager.config.activeOrders === 'object'
1656
+ const feeCoreOrders = manager.config.coreOrders && typeof manager.config.coreOrders === 'object'
1449
1657
  ? {
1450
- ...manager.config.activeOrders,
1451
- buy: Math.max(0, Number(manager.config.activeOrders.buy) || 0) + resolveReserveCount(manager.config, 'buy'),
1452
- sell: Math.max(0, Number(manager.config.activeOrders.sell) || 0) + resolveReserveCount(manager.config, 'sell'),
1658
+ ...manager.config.coreOrders,
1659
+ buy: Math.max(0, Number(manager.config.coreOrders.buy) || 0) + resolveEdgeCount(manager.config, 'buy'),
1660
+ sell: Math.max(0, Number(manager.config.coreOrders.sell) || 0) + resolveEdgeCount(manager.config, 'sell'),
1453
1661
  }
1454
- : manager.config.activeOrders;
1455
- 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);
1662
+ : manager.config.coreOrders;
1663
+ 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);
1456
1664
  // Denominator: side's allocated capital (or chain total fallback).
1457
1665
  const allocated = s.name === 'buy' ? chainSnap.allocatedBuy : chainSnap.allocatedSell;
1458
1666
  const denominator = (allocated > 0) ? allocated : (s.grid + availableFunds);
@@ -1464,8 +1672,11 @@ export function checkAndUpdateGridIfNeeded(manager) {
1464
1672
  // chain-total drops: a normal fill moves value across sides (pays one
1465
1673
  // asset, receives the other), so one side's total routinely drops >=3%
1466
1674
  // on ordinary fills — and the fill pipeline already re-sizes from the
1467
- // post-fill budget. External removal is caught here because the
1468
- // committed/planned grid stays put while the allocation sinks.
1675
+ // post-fill budget. External removal is caught here only while the plan
1676
+ // still carries the old budget; once the fill pipeline re-derives
1677
+ // VIRTUAL downward the overAlloc gap closes (grid == allocated), and the
1678
+ // committed-drift leg folded in below is what catches it. The two
1679
+ // together cover the pre- and post-pipeline phases.
1469
1680
  // NOTE: with an explicit 0 allocation the shared fallback denominator
1470
1681
  // yields overAlloc ≈ +100%, i.e. a 0%-funded side holding size always
1471
1682
  // triggers — which is the desired unwind (zero budget sizes everything
@@ -1491,8 +1702,174 @@ export function checkAndUpdateGridIfNeeded(manager) {
1491
1702
  }
1492
1703
  }
1493
1704
  }
1705
+ // Fold the committed-drift legs into this single entry so the trigger is
1706
+ // complete on its own. Both numerators above track `virtual` (the grow
1707
+ // denominator via `availableFunds`, the shrink base via `total.grid`), so
1708
+ // an external deposit/withdrawal already folded into the plan by the
1709
+ // fill pipeline is invisible to them. The on-chain committed delta closes
1710
+ // that gap in both directions. Callers must refresh funds first
1711
+ // (monitorDivergence does; direct callers own that responsibility).
1712
+ const driftResult = _computeCommittedSizeDriftSync(manager);
1713
+ result.buyUpdated = result.buyUpdated || driftResult.buyUpdated;
1714
+ result.sellUpdated = result.sellUpdated || driftResult.sellUpdated;
1715
+ result.buyShrink = result.buyShrink || driftResult.buyShrink;
1716
+ result.sellShrink = result.sellShrink || driftResult.sellShrink;
1494
1717
  return result;
1495
1718
  }
1719
+ /**
1720
+ * Committed-size drift check (fund trigger blind-spot closure).
1721
+ *
1722
+ * checkAndUpdateGridIfNeeded measures available funds as
1723
+ * `chainFree - virtualReservation`. The fill/rotation sizing pipeline
1724
+ * re-derives VIRTUAL slot sizes from the live budget, so a deposit (or an
1725
+ * external withdrawal) is folded into the virtual reservation on the first
1726
+ * rotation after it lands. chainFree and virtual then move together, the
1727
+ * ratio stays pinned at the unallocated remainder, and a side whose
1728
+ * on-chain (ACTIVE/PARTIAL) orders still carry the pre-deposit sizes is
1729
+ * never flagged — the full-side resize waits for an unrelated full resync
1730
+ * (RMS or AMA recenter).
1731
+ *
1732
+ * This leg closes that blind spot: it computes the geometric ideal for
1733
+ * every side slot from the current budget and measures the gap against the
1734
+ * sizes actually committed on chain, applying the resize path's own
1735
+ * free-balance growth cap so the metric equals the on-chain delta a resize
1736
+ * would really produce. A side whose committed orders would change by
1737
+ * >= GRID_REGENERATION_PERCENTAGE of the committed size is flagged for the
1738
+ * same COW resize path (applyGridDivergenceCorrections), which updates
1739
+ * every changed on-chain order — i.e. the full side.
1740
+ *
1741
+ * Only on-chain slots contribute: VIRTUAL slots are the plan (already sized
1742
+ * by the fill pipeline) and SPREAD placeholders carry no commitment.
1743
+ * Non-slot-N shelf/manual orders are excluded (never resized by the
1744
+ * geometric pass; same gate as _recalculateGridOrderSizesFromBlockchain).
1745
+ *
1746
+ * @param {import('./types').OrderManager} manager - Manager instance with order state
1747
+ * @returns {{ buyUpdated: boolean; sellUpdated: boolean; buyShrink: boolean; sellShrink: boolean }}
1748
+ */
1749
+ function _computeCommittedSizeDriftSync(manager) {
1750
+ const result = { buyUpdated: false, sellUpdated: false, buyShrink: false, sellShrink: false };
1751
+ if (!manager || !manager.assets || !manager.orders)
1752
+ return result;
1753
+ const rawThreshold = manager.config?.gridLimits?.GRID_REGENERATION_PERCENTAGE;
1754
+ // Same fallback contract as checkAndUpdateGridIfNeeded: a configured 0 or
1755
+ // non-numeric value falls back to the global default rather than disabling.
1756
+ const threshold = (Number.isFinite(Number(rawThreshold)) && Number(rawThreshold) > 0)
1757
+ ? Number(rawThreshold)
1758
+ : GRID_LIMITS.GRID_REGENERATION_PERCENTAGE;
1759
+ const sides = [
1760
+ { name: 'buy', orderType: ORDER_TYPES.BUY },
1761
+ { name: 'sell', orderType: ORDER_TYPES.SELL }
1762
+ ];
1763
+ for (const s of sides) {
1764
+ // Sync core: checkAndUpdateGridIfNeeded is sync and expects funds to
1765
+ // already be fresh (monitorDivergence / checkCommittedSizeDrift recalc).
1766
+ const ctx = _computeSizingContextSync(manager, s.name);
1767
+ if (!ctx || !(ctx.budget > 0))
1768
+ continue;
1769
+ // Must match _recalculateGridOrderSizesFromBlockchain exactly: same
1770
+ // source (manager.orders), same ASC price sort, same denominator set.
1771
+ const allSideSlots = Array.from(manager.orders.values())
1772
+ .filter((o) => o.type === s.orderType)
1773
+ .sort((a, b) => a.price - b.price);
1774
+ if (allSideSlots.length === 0)
1775
+ continue;
1776
+ let newSizes;
1777
+ try {
1778
+ newSizes = calculateRotationOrderSizes(ctx.budget, 0, allSideSlots.length, s.orderType, manager.config, 0, ctx.precision);
1779
+ }
1780
+ catch (_err) {
1781
+ continue;
1782
+ }
1783
+ // Replay the resize path's free-balance cap so `growth` is exactly the
1784
+ // committed growth the resize could apply (VIRTUAL slots do not consume
1785
+ // free balance; shrink releases it back for later slots). The cap uses
1786
+ // the float delta (matching the resize), but the reported drift is gated
1787
+ // on the same blockchain-integer change test the resize uses to decide
1788
+ // whether an on-chain UPDATE is emitted.
1789
+ const freeKey = s.name === 'buy' ? 'buyFree' : 'sellFree';
1790
+ let sideFreeAvailable = Number(manager.accountTotals?.[freeKey] || 0);
1791
+ let growth = 0;
1792
+ let shrink = 0;
1793
+ let committedTotal = 0;
1794
+ for (let i = 0; i < allSideSlots.length; i++) {
1795
+ const slot = allSideSlots[i];
1796
+ if (!isOrderOnChain(slot) || !hasOnChainId(slot))
1797
+ continue;
1798
+ if (parseSlotIndex(slot.id) === null)
1799
+ continue;
1800
+ const ideal = Number(newSizes?.[i] || 0);
1801
+ const current = Number(slot.size || 0);
1802
+ committedTotal += current;
1803
+ let newSize = ideal;
1804
+ const delta = ideal - current;
1805
+ if (delta > 0) {
1806
+ const affordableDelta = Math.min(delta, Math.max(0, sideFreeAvailable));
1807
+ if (affordableDelta < delta)
1808
+ newSize = current + affordableDelta;
1809
+ sideFreeAvailable = Math.max(0, sideFreeAvailable - affordableDelta);
1810
+ }
1811
+ else if (delta < 0) {
1812
+ sideFreeAvailable += Math.abs(delta);
1813
+ }
1814
+ // Match the resize's integer-space change gate: a slot whose size
1815
+ // rounds to the same blockchain integer emits no UPDATE and must not
1816
+ // count toward the drift metric (otherwise the leg would re-trigger
1817
+ // against a no-op resize every tick).
1818
+ const currentInt = floatToBlockchainInt(current, ctx.precision);
1819
+ const newInt = floatToBlockchainInt(newSize, ctx.precision);
1820
+ if (currentInt === newInt)
1821
+ continue;
1822
+ const applied = newSize - current;
1823
+ if (applied > 0)
1824
+ growth += applied;
1825
+ else if (applied < 0)
1826
+ shrink += Math.abs(applied);
1827
+ }
1828
+ // Baseline is the on-chain committed size, NOT the whole allocation:
1829
+ // a deposit's active-window share is a small slice of the allocation
1830
+ // (the far rail holds most of the plan), so an `allocated` denominator
1831
+ // would never reach 3% while the committed side is genuinely ~12%
1832
+ // under-sized. Relative to the committed side, a normal fill moves the
1833
+ // budget by well under the threshold, so this stays quiet in steady
1834
+ // state. No on-chain orders -> nothing to resize.
1835
+ if (!(committedTotal > 0))
1836
+ continue;
1837
+ const growthPct = (growth / committedTotal) * 100;
1838
+ const shrinkPct = (shrink / committedTotal) * 100;
1839
+ const growTrigger = growthPct >= threshold;
1840
+ const shrinkTrigger = shrinkPct >= threshold;
1841
+ 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');
1842
+ if (growTrigger || shrinkTrigger) {
1843
+ if (!(manager._gridSidesUpdated instanceof Set))
1844
+ manager._gridSidesUpdated = new Set();
1845
+ manager._gridSidesUpdated.add(s.orderType);
1846
+ if (s.name === 'buy') {
1847
+ result.buyUpdated = true;
1848
+ if (shrinkTrigger)
1849
+ result.buyShrink = true;
1850
+ }
1851
+ else {
1852
+ result.sellUpdated = true;
1853
+ if (shrinkTrigger)
1854
+ result.sellShrink = true;
1855
+ }
1856
+ }
1857
+ }
1858
+ return result;
1859
+ }
1860
+ /**
1861
+ * Async committed-drift accessor: refresh funds, then run the sync core.
1862
+ * Public for callers/tests that want the drift-only result; the complete
1863
+ * trigger is checkAndUpdateGridIfNeeded, which folds this core in.
1864
+ * Naming mirrors the sizing pair: _computeCommittedSizeDriftSync is the
1865
+ * private computation, checkCommittedSizeDrift the public accessor.
1866
+ */
1867
+ export async function checkCommittedSizeDrift(manager) {
1868
+ if (manager && typeof manager.recalculateFunds === 'function') {
1869
+ await manager.recalculateFunds();
1870
+ }
1871
+ return _computeCommittedSizeDriftSync(manager);
1872
+ }
1496
1873
  /**
1497
1874
  * Standardize grid sizes using blockchain total context.
1498
1875
  *
@@ -1581,11 +1958,11 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
1581
1958
  // geometric progression including empties, then re-type the picked slot
1582
1959
  // to BUY/SELL before placement. The COW boundary-shift path re-types
1583
1960
  // the working grid by geometry first, so crossers stay in the correct
1584
- // side's denominator. Reserve edge slots are included here like any
1961
+ // side's denominator. Edge order slots are included here like any
1585
1962
  // other slot-N side slot: this geometric curve sizes them too, and the
1586
- // activation picker (_pickEdgeReserveSlots) only ever places a reserve
1963
+ // activation picker (_pickEdgeSlots) only ever places an edge order
1587
1964
  // with the stored size the target-grid sizing pipeline already wrote
1588
- // (exact values, one sizing rule). Skipping reserves in this pass
1965
+ // (exact values, one sizing rule). Skipping edge orders in this pass
1589
1966
  // would make the divergence resize disagree with that pipeline. Only
1590
1967
  // non-slot-N shelf/manual ids are skipped below.
1591
1968
  const orderSource = collectActions ? workingGrid : manager.orders;
@@ -1608,7 +1985,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
1608
1985
  const slot = allSideSlots[i];
1609
1986
  // Shelf/manual orders (non-slot-N ids, e.g. fork-kept deep-*
1610
1987
  // below the rail) sit outside window accounting: geometric
1611
- // ideals must never resize them on-chain. Same gate as reserve
1988
+ // ideals must never resize them on-chain. Same gate as edge
1612
1989
  // classification and startup cancel candidates (issue #27
1613
1990
  // follow-up). No-op upstream (grids only mint slot-N).
1614
1991
  // NB: they stay in the denominator above (budget math
@@ -1919,24 +2296,35 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
1919
2296
  * @returns {Promise<any>}
1920
2297
  */
1921
2298
  export async function monitorDivergence(manager, calculatedGrid, persistedGrid) {
1922
- // 1. Check ratio-based divergence (available funds vs allocated)
2299
+ // Refresh once so every leg sizes from one snapshot. The trigger itself
2300
+ // is sync and already folds the committed-drift legs in (see
2301
+ // checkAndUpdateGridIfNeeded), so there is no separate drift call here.
2302
+ if (manager && typeof manager.recalculateFunds === 'function') {
2303
+ await manager.recalculateFunds();
2304
+ }
2305
+ // 1. Ratio + committed-drift divergence (available funds /
2306
+ // over-allocation / on-chain committed delta).
1923
2307
  const ratioResult = checkAndUpdateGridIfNeeded(manager);
1924
- if (ratioResult.buyUpdated || ratioResult.sellUpdated) {
2308
+ const ratioBuy = ratioResult.buyUpdated;
2309
+ const ratioSell = ratioResult.sellUpdated;
2310
+ const buyShrink = ratioResult.buyShrink === true;
2311
+ const sellShrink = ratioResult.sellShrink === true;
2312
+ if (ratioBuy || ratioSell) {
1925
2313
  return {
1926
2314
  needsUpdate: true,
1927
- buy: { updated: ratioResult.buyUpdated, ratio: ratioResult.buyUpdated, rms: false, metric: 0, shrink: ratioResult.buyShrink === true },
1928
- sell: { updated: ratioResult.sellUpdated, ratio: ratioResult.sellUpdated, rms: false, metric: 0, shrink: ratioResult.sellShrink === true },
1929
- orderType: getOrderTypeFromUpdatedFlags(ratioResult.buyUpdated, ratioResult.sellUpdated)
2315
+ buy: { updated: ratioBuy, ratio: ratioBuy, rms: false, metric: 0, shrink: buyShrink },
2316
+ sell: { updated: ratioSell, ratio: ratioSell, rms: false, metric: 0, shrink: sellShrink },
2317
+ orderType: getOrderTypeFromUpdatedFlags(ratioBuy, ratioSell)
1930
2318
  };
1931
2319
  }
1932
2320
  // 2. Check RMS-based divergence (structural deviation)
1933
2321
  const rmsResult = await compareGrids(calculatedGrid, persistedGrid, manager);
1934
- const buyUpdated = ratioResult.buyUpdated || rmsResult.buy.updated;
1935
- const sellUpdated = ratioResult.sellUpdated || rmsResult.sell.updated;
2322
+ const buyUpdated = rmsResult.buy.updated;
2323
+ const sellUpdated = rmsResult.sell.updated;
1936
2324
  return {
1937
2325
  needsUpdate: buyUpdated || sellUpdated,
1938
- buy: { updated: buyUpdated, ratio: ratioResult.buyUpdated, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: ratioResult.buyShrink === true },
1939
- sell: { updated: sellUpdated, ratio: ratioResult.sellUpdated, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: ratioResult.sellShrink === true },
2326
+ buy: { updated: buyUpdated, ratio: false, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: false },
2327
+ sell: { updated: sellUpdated, ratio: false, rms: rmsResult.sell.updated, metric: rmsResult.sell.metric, shrink: false },
1940
2328
  orderType: getOrderTypeFromUpdatedFlags(buyUpdated, sellUpdated),
1941
2329
  thresholdPct: rmsResult.thresholdPct
1942
2330
  };
@@ -1949,7 +2337,7 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
1949
2337
  */
1950
2338
  function _getOnChainOrders(manager) {
1951
2339
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
1952
- // deep-*) sit outside window accounting — same gate as reserve
2340
+ // deep-*) sit outside window accounting — same gate as edge
1953
2341
  // classification and startup cancel candidates (issue #27 follow-up).
1954
2342
  // Without this, a live shelf masks an empty window side (oneSideEmpty
1955
2343
  // stays false) and skews the spread inputs. No-op on grids that only
@@ -2021,6 +2409,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2021
2409
  const lastPrice = (bestBuy !== null && bestSell !== null)
2022
2410
  ? (bestBuy + bestSell) / 2
2023
2411
  : Number(manager.config.startPrice) || 0;
2412
+ // Keep the crossing floor current: refresh the cached live market price
2413
+ // when it is stale, paced to one read per freshness window. The planner
2414
+ // then uses current market truth instead of a possibly days-old fill,
2415
+ // which is what removes the need for a distance heuristic. Best-effort;
2416
+ // on failure the fill anchor remains the fallback.
2417
+ await maybeRefreshLiveMarketPrice(manager, _BitShares);
2024
2418
  // Lock guard is handled at function entry — if _gridLock is absent we return early.
2025
2419
  let fundSnapshot = null;
2026
2420
  // Detect empty-side condition: when one side has zero on-chain orders,
@@ -2049,6 +2443,34 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2049
2443
  manager.outOfSpread = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
2050
2444
  if (manager.outOfSpread === 0)
2051
2445
  return false;
2446
+ // P-A cold book: the orchestration short-circuit, evaluated in the
2447
+ // shared readiness gate so the planner, the crossing filter and the
2448
+ // COW bypass all reason from one verdict. This early return keeps
2449
+ // the cold classification ahead of the one-sided boundary branch.
2450
+ // The planner re-evaluates the gate per call (including the re-plan
2451
+ // path, which deliberately re-reads fresh state), so this is not a
2452
+ // duplicated verdict but the same rule at two points in the cycle.
2453
+ //
2454
+ // A cold book has no realized spread to repair — the "spread" is
2455
+ // synthetic (an empty side plus the startPrice fallback) and a
2456
+ // correction here can only guess a side and place through an unseen
2457
+ // market (issue #31). The reconcile path owns the first window;
2458
+ // 'cold-book' is a structural stall that arms the targeted sync.
2459
+ // Degraded causes (stale/unmatched) keep ok=true. A null reason is
2460
+ // a gate failure (correct-by-refusal) and stalls as 'readiness-gate'.
2461
+ const readiness = evaluateSpreadCorrectionReadiness(manager, {
2462
+ onChainOrders: { buys: onChainBuys, sells: onChainSells }
2463
+ });
2464
+ if (!readiness.ok) {
2465
+ const cold = readiness.reason === 'cold-book';
2466
+ manager.logger?.log?.((cold
2467
+ ? `[SPREAD] Book is cold (no live BUY or SELL on chain); skipping spread correction — ` +
2468
+ `the reconcile path owns the first window.`
2469
+ : `[SPREAD] Spread-correction readiness gate failed; skipping this cycle.`) +
2470
+ ` Requesting a targeted chain sync.`, 'warn');
2471
+ stall = cold ? 'cold-book' : 'readiness-gate';
2472
+ return false;
2473
+ }
2052
2474
  // Check whether the empty side is caused by boundary-at-rail-edge.
2053
2475
  // When the boundary crawl has clamped to 0 or allSlots.length-1,
2054
2476
  // fill pressure can wipe out one entire side. Spread correction
@@ -2169,12 +2591,15 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2169
2591
  // Pre-flight fund verification mitigates TOCTOU between lock release and broadcast.
2170
2592
  if (shouldApplyCorrection && updateOrdersOnChainBatch && correction && fundSnapshot) {
2171
2593
  let activeCorrection = correction;
2172
- let activeSnapshot = fundSnapshot;
2594
+ // Explicit non-null alias: fundSnapshot is assigned inside the
2595
+ // executeSpreadCheck closure, so TS control-flow cannot prove it
2596
+ // non-null here even though the guard above checked it.
2597
+ const baseFundSnapshot = fundSnapshot;
2173
2598
  const currentFunds = _snapshotFundState(manager);
2174
- const fundChanged = activeSnapshot.buyFree !== currentFunds.buyFree
2175
- || activeSnapshot.sellFree !== currentFunds.sellFree
2176
- || activeSnapshot.buyLocked !== currentFunds.buyLocked
2177
- || activeSnapshot.sellLocked !== currentFunds.sellLocked;
2599
+ const fundChanged = baseFundSnapshot.buyFree !== currentFunds.buyFree
2600
+ || baseFundSnapshot.sellFree !== currentFunds.sellFree
2601
+ || baseFundSnapshot.buyLocked !== currentFunds.buyLocked
2602
+ || baseFundSnapshot.sellLocked !== currentFunds.sellLocked;
2178
2603
  if (fundChanged) {
2179
2604
  // TOCTOU: fund state changed between lock release and broadcast.
2180
2605
  // Lock-free re-plan — no _gridLock needed because the fund read
@@ -2201,7 +2626,6 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2201
2626
  const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
2202
2627
  if (rePlanCorrection && (rePlanCorrection.ordersToPlace?.length || 0) > 0) {
2203
2628
  activeCorrection = rePlanCorrection;
2204
- activeSnapshot = currentFunds;
2205
2629
  manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
2206
2630
  `re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates`, 'info');
2207
2631
  }
@@ -2215,23 +2639,86 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2215
2639
  return { ordersPlaced: 0, partialsMoved: 0, stall };
2216
2640
  }
2217
2641
  }
2642
+ // P1: hold the broadcast/placement region across the whole attempt
2643
+ // loop (re-plan + broadcast). A defer-if-broadcasting fill rebalance
2644
+ // yields while this region is held, and a waiting one parks on
2645
+ // _awaitBroadcastIdle, so a concurrent commit is far less likely to
2646
+ // bump master between this correction's plan and its broadcast — the
2647
+ // race that made the commit guard refuse the batch. This narrows the
2648
+ // window rather than closing it absolutely (the idle wait is bounded
2649
+ // and proceeds on timeout), so the commit guard stays the backstop
2650
+ // and the retry below re-plans from fresh master. The COW batch
2651
+ // refcounts the region internally; this is the outer holder.
2652
+ const MAX_SPREAD_ATTEMPTS = Number(TIMING?.SPREAD_CORRECTION_MAX_ATTEMPTS) > 0
2653
+ ? Number(TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS)
2654
+ : 2;
2655
+ let attempts = 0;
2656
+ // Whether the most recent refusal is retryable — reported to the P4
2657
+ // watchdog so a non-transient cause (commit-refused /
2658
+ // update-target-missing) counts toward staleness instead of being
2659
+ // waved through as a retry. Defaults to transient for the P2
2660
+ // collision-blocked path, which has no batch result.
2661
+ let lastTransient = true;
2662
+ let lastResult = null;
2663
+ const canHoldRegion = typeof manager.startBroadcasting === 'function'
2664
+ && typeof manager.stopBroadcasting === 'function';
2665
+ if (canHoldRegion)
2666
+ manager.startBroadcasting();
2218
2667
  try {
2219
- const batchResult = await updateOrdersOnChainBatch(activeCorrection);
2220
- if (!batchResult || batchResult.executed !== true) {
2221
- manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.`, 'warn');
2222
- // Nothing landed: ask the caller to refresh account totals +
2223
- // open orders (stale holds/balances can make the same plan
2224
- // re-derive every cycle).
2225
- return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed' };
2668
+ while (attempts < MAX_SPREAD_ATTEMPTS) {
2669
+ attempts++;
2670
+ // P2: before broadcasting, detect a planned CREATE whose
2671
+ // destination was taken by a competing batch after planning,
2672
+ // and re-derive instead of shipping a known collision.
2673
+ const resolution = await resolveOccupiedCorrection(manager, activeCorrection, attempts, MAX_SPREAD_ATTEMPTS);
2674
+ if (resolution.action !== 'broadcast') {
2675
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Plan-time dedupe: ${resolution.occupied.length} planned slot(s) occupied since planning ` +
2676
+ `(${resolution.occupied.slice(0, 8).join(', ')}${resolution.occupied.length > 8 ? ', …' : ''}); ` +
2677
+ (resolution.action === 'replanned' ? 're-planning from fresh master' : 'no re-plan candidate — refusing this cycle'), 'warn');
2678
+ recordSpreadCorrectionRefusal(manager, SPREAD_CORRECTION_REFUSAL.CREATE_COLLISION);
2679
+ if (resolution.action === 'replanned') {
2680
+ recordSpreadCorrectionRetry(manager);
2681
+ activeCorrection = resolution.correction;
2682
+ continue;
2683
+ }
2684
+ break;
2685
+ }
2686
+ const batchResult = await updateOrdersOnChainBatch(activeCorrection);
2687
+ lastResult = batchResult ?? null;
2688
+ if (batchResult && batchResult.executed === true) {
2689
+ await manager.recalculateFunds();
2690
+ const placed = activeCorrection.ordersToPlace?.length || 0;
2691
+ return { ordersPlaced: placed, partialsMoved: 0 };
2692
+ }
2693
+ const cause = classifySpreadRefusalCause(batchResult);
2694
+ recordSpreadCorrectionRefusal(manager, cause);
2695
+ const transient = isTransientSpreadRefusal(cause);
2696
+ lastTransient = transient;
2697
+ if (!transient || attempts >= MAX_SPREAD_ATTEMPTS)
2698
+ break;
2699
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Batch refused (${cause}); re-planning from fresh master ` +
2700
+ `(attempt ${attempts + 1}/${MAX_SPREAD_ATTEMPTS})`, 'warn');
2701
+ const replanned = await replanSpreadCorrectionFromFreshMaster(manager);
2702
+ if (!replanned || (replanned.ordersToPlace?.length || 0) === 0)
2703
+ break;
2704
+ recordSpreadCorrectionRetry(manager);
2705
+ activeCorrection = replanned;
2226
2706
  }
2227
- await manager.recalculateFunds();
2228
- const placed = activeCorrection.ordersToPlace?.length || 0;
2229
- return { ordersPlaced: placed, partialsMoved: 0 };
2230
2707
  }
2231
2708
  catch (err) {
2232
2709
  manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
2233
2710
  return { ordersPlaced: 0, partialsMoved: 0, stall: 'apply-error' };
2234
2711
  }
2712
+ finally {
2713
+ if (canHoldRegion)
2714
+ manager.stopBroadcasting();
2715
+ }
2716
+ manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.` +
2717
+ (lastResult ? ` (cause=${classifySpreadRefusalCause(lastResult)})` : ''), 'warn');
2718
+ // Retryable only when the last refusal cause was transient; a
2719
+ // commit-refused / update-target-missing / unmatched / shutdown
2720
+ // refusal counts toward the persistent-stale watchdog.
2721
+ return { ordersPlaced: 0, partialsMoved: 0, stall: 'batch-not-executed', transient: lastTransient };
2235
2722
  }
2236
2723
  return { ordersPlaced: 0, partialsMoved: 0, stall };
2237
2724
  }
@@ -2298,26 +2785,24 @@ export async function checkWindowDust(manager) {
2298
2785
  const topSellOrder = allOrders
2299
2786
  .filter((o) => o.type === ORDER_TYPES.SELL && isLiveOrder(o))
2300
2787
  .sort((a, b) => a.price - b.price)[0];
2301
- // Check if an order has a duplicate slot — an active sibling with same price via integer round-trip.
2302
- const hasDuplicatePriceLevel = (order, assets) => {
2303
- const precision = order.type === ORDER_TYPES.SELL ? assets.assetA.precision : assets.assetB.precision;
2788
+ // Check if an order has a duplicate price level — an active sibling at
2789
+ // the same ladder level. If so, cancelling won't create a grid gap.
2790
+ // Only checks ACTIVE siblings. If two PARTIALs share a price with no active
2791
+ // sibling, neither qualifies and the gap is left to the rebalancer.
2792
+ // Grid-vs-grid: resolve both prices to their frozen ladder level
2793
+ // (genesis-aware), NOT priceSlotEqual at the asset precision (collapses
2794
+ // adjacent levels for a low-precision asset).
2795
+ const hasDuplicatePriceLevel = (order) => {
2304
2796
  for (const o of allOrders) {
2305
2797
  if (o.id === order.id)
2306
2798
  continue;
2307
2799
  if (o.type !== order.type || o.state !== ORDER_STATES.ACTIVE || !o.orderId || o.price == null)
2308
2800
  continue;
2309
- try {
2310
- if (priceSlotEqual(o.price, order.price, precision))
2311
- return true;
2312
- }
2313
- catch {
2314
- if (o.price === order.price)
2315
- return true;
2316
- }
2801
+ if (sameGridLevel(o.price, order.price, manager._genesis))
2802
+ return true;
2317
2803
  }
2318
2804
  return false;
2319
2805
  };
2320
- const assets = manager.assets;
2321
2806
  const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
2322
2807
  const isTopBuy = (o) => !!(topBuyOrder && o.id === topBuyOrder.id);
2323
2808
  const isTopSell = (o) => !!(topSellOrder && o.id === topSellOrder.id);
@@ -2348,8 +2833,8 @@ export async function checkWindowDust(manager) {
2348
2833
  // only cancels zero-value residuals, and an interior dust rarely has a
2349
2834
  // duplicate price level. Cancelling it frees the slot for rotation to
2350
2835
  // re-derive, so the tiny gap is closed by normal grid rebalancing.
2351
- const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o, assets) || isDustSized(o, buyThresholds)));
2352
- const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o, assets) || isDustSized(o, sellThresholds)));
2836
+ const eligibleBuyPartials = allPartials.filter((o) => o.type === ORDER_TYPES.BUY && (isTopBuy(o) || hasDuplicatePriceLevel(o) || isDustSized(o, buyThresholds)));
2837
+ const eligibleSellPartials = allPartials.filter((o) => o.type === ORDER_TYPES.SELL && (isTopSell(o) || hasDuplicatePriceLevel(o) || isDustSized(o, sellThresholds)));
2353
2838
  const buyDustOrders = await _getDustOrders(manager, eligibleBuyPartials, ORDER_TYPES.BUY, buyThresholds);
2354
2839
  const sellDustOrders = await _getDustOrders(manager, eligibleSellPartials, ORDER_TYPES.SELL, sellThresholds);
2355
2840
  return {
@@ -2540,7 +3025,7 @@ function resolveMinSpreadOrdersReserve(manager) {
2540
3025
  // DEFENSE-IN-DEPTH WALK BOUNDS: the loop itself also stops
2541
3026
  // MIN_SPREAD_ORDERS short of the opposite rail edge (idx <= sellStartIdx−1−
2542
3027
  // reserve for BUY / idx >= buyEndIdx+1+reserve for SELL), so even if the
2543
- // cap above is ever miscomputed the walk cannot consume the reserved gap.
3028
+ // cap above is ever miscomputed the walk cannot consume the edged gap.
2544
3029
  // When bandSize <= reserve the bound disables promotion entirely.
2545
3030
  function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, quota, spreadReserve, maxDepth) {
2546
3031
  const isBuy = railType === ORDER_TYPES.BUY;
@@ -2582,6 +3067,32 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2582
3067
  throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
2583
3068
  }
2584
3069
  const ordersToPlace = [];
3070
+ // SHARED READINESS GATE (P-A/P-B/P-C): one verdict for the planner, the
3071
+ // crossing filter and the COW bypass. Hard refusal (cold book) returns
3072
+ // before any planning; degraded causes (stale/unmatched) keep planning
3073
+ // but withhold the bypass and drive the collision filter below.
3074
+ const onChainView = _getOnChainOrders(manager);
3075
+ const readiness = evaluateSpreadCorrectionReadiness(manager, {
3076
+ onChainOrders: { buys: onChainView.onChainBuys, sells: onChainView.onChainSells }
3077
+ });
3078
+ if (!readiness.ok) {
3079
+ // Only 'cold-book' is a named hard-refusal premise; a null reason is
3080
+ // a gate failure and gets its own stall so triage logs are precise.
3081
+ // Either way the targeted sync arms via the stall.
3082
+ const hardRefusalStall = readiness.reason === 'cold-book'
3083
+ ? 'cold-book'
3084
+ : 'readiness-gate';
3085
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing cycle: ${readiness.reason ?? 'readiness-gate-error'} — a targeted sync will re-evaluate`, 'warn');
3086
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: hardRefusalStall, origin: COW_ORIGINS.SPREAD_CORRECTION };
3087
+ }
3088
+ // Empty-candidate stall cause: name the collision case when unmatched
3089
+ // orders are present, so the targeted-sync reason states the truth.
3090
+ // Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
3091
+ // stale > unmatched), so a stale+unmatched cycle reports 'stale-snapshot'
3092
+ // and would otherwise mask the collision cause.
3093
+ const refusalStallHint = readiness.unmatched.length > 0
3094
+ ? 'unmatched-orders'
3095
+ : 'no-candidates';
2585
3096
  const railType = preferredSide;
2586
3097
  const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
2587
3098
  const configuredMissingSlots = Number(outOfSpread || 0);
@@ -2663,7 +3174,9 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2663
3174
  // market-nearest comparator that replaced it fixed that case but sorts
2664
3175
  // the FAR end first when the empties sit BELOW the window (the normal
2665
3176
  // post-fill state), which is the same class of bug mirrored.
2666
- const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
3177
+ // Reuse the gate's view: one slot-gated scan per planner call feeds both
3178
+ // the readiness verdict and the live window edges below.
3179
+ const { onChainBuys, onChainSells } = onChainView;
2667
3180
  const railBestIsMax = railType === ORDER_TYPES.BUY;
2668
3181
  const bestLiveOnRail = railBestIsMax
2669
3182
  ? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
@@ -2723,11 +3236,54 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2723
3236
  return true;
2724
3237
  return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
2725
3238
  };
3239
+ // MARKET-CROSSING GUARD: never place a SELL at/below (or a BUY at/above)
3240
+ // the last price the account actually traded at. On a one-sided or
3241
+ // freshly-regenerated book the local anchor is absent, so without this
3242
+ // the correction happily sells under a market it cannot see (issue
3243
+ // #31). Fail-open when no real fill is known — never guess from grid
3244
+ // geometry. This complements tightensSpread (which is anchor-relative)
3245
+ // with an absolute, market-relative floor.
3246
+ // Crossing floor from the shared readiness verdict: a fresh live market
3247
+ // read when available, else the fill-derived reference. No distance
3248
+ // heuristic — the floor is kept current rather than judged stale.
3249
+ const marketRef = readiness.marketRef;
3250
+ const doesNotCrossMarket = (c) => {
3251
+ if (marketRef == null || c?.price == null || !Number.isFinite(c.price))
3252
+ return true;
3253
+ return railBestIsMax ? c.price < marketRef : c.price > marketRef;
3254
+ };
3255
+ // P-C COLLISION FILTER: when the gate saw fresh unmatched chain orders,
3256
+ // drop candidates whose price level they already occupy — placing
3257
+ // another order at the same level would duplicate a live order the
3258
+ // grid has not adopted yet. Price-level only: the unmatched row carries
3259
+ // no side, and a duplicate at a level is a duplicate regardless.
3260
+ //
3261
+ // Keyed off the DATA, not `reason`: reason is priority-ranked (cold >
3262
+ // stale > unmatched), so a stale+unmatched cycle reports
3263
+ // 'stale-snapshot' while the unmatched list is fully populated. The
3264
+ // P4 protection must not expire with snapshot staleness — those chain
3265
+ // orders only clear on the next sync.
3266
+ const unmatchedPrices = readiness.unmatched.length > 0
3267
+ ? readiness.unmatched.map((u) => Number(u?.price)).filter((p) => Number.isFinite(p) && p > 0)
3268
+ : [];
3269
+ const doesNotCollideUnmatched = (c) => {
3270
+ if (unmatchedPrices.length === 0 || c?.price == null || !Number.isFinite(c.price))
3271
+ return true;
3272
+ // The unmatched row carries only a price; use the candidate's own
3273
+ // side/size for the tolerance. Tolerance-based, NOT priceSlotEqual at
3274
+ // the asset precision (low-precision assets collapse adjacent levels).
3275
+ return !unmatchedPrices.some((p) => pricesOnSameLevel(p, c.size, railType, c.price, c.size, railType, manager.assets, manager.config?.incrementPercent));
3276
+ };
3277
+ if (unmatchedPrices.length > 0) {
3278
+ manager.logger?.log?.(`[SPREAD-CORRECTION] ${unmatchedPrices.length} known-unmatched chain price level(s) excluded from ${sideName} candidates — sync will adopt them first`, 'warn');
3279
+ }
2726
3280
  const typedSpreadCandidates = allOrders
2727
3281
  .filter((o) => o.type === ORDER_TYPES.SPREAD
2728
3282
  && isSlotAvailable(o)
2729
3283
  && getSlotCorrectType(o) === railType)
2730
3284
  .filter(tightensSpread)
3285
+ .filter(doesNotCrossMarket)
3286
+ .filter(doesNotCollideUnmatched)
2731
3287
  .sort(sortCandidates)
2732
3288
  .slice(0, missingSlots);
2733
3289
  // Secondary candidates: orphaned virtual slots that have lost their
@@ -2770,6 +3326,8 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2770
3326
  && !o.orderId
2771
3327
  && getSlotCorrectType(o) === railType)
2772
3328
  .filter(tightensSpread)
3329
+ .filter(doesNotCrossMarket)
3330
+ .filter(doesNotCollideUnmatched)
2773
3331
  .sort(sortCandidates)
2774
3332
  .slice(0, missingSlots);
2775
3333
  // If the funded rail is full, the spread itself may be stale: the
@@ -2814,6 +3372,25 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2814
3372
  if (boundaryKnown && orphanedVirtualCandidates.length + typedSpreadCandidates.length < missingSlots) {
2815
3373
  const rawQuota = missingSlots - orphanedVirtualCandidates.length - typedSpreadCandidates.length;
2816
3374
  promotedCandidates.push(..._collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, sellStartIdx, rawQuota, spreadReserve, maxPromotionDepth));
3375
+ // A boundary promotion moves the window into the spread band. If
3376
+ // any of the contiguous run would land through the last real fill,
3377
+ // the whole promotion is refused (dropping only the first slot
3378
+ // would break the run's contiguity and the boundary derivation).
3379
+ const crossingPromoted = marketRef == null
3380
+ ? []
3381
+ : promotedCandidates.filter((c) => !doesNotCrossMarket(c));
3382
+ const collidingPromoted = promotedCandidates.filter((c) => !doesNotCollideUnmatched(c));
3383
+ if (marketRef != null && crossingPromoted.length > 0) {
3384
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
3385
+ `${crossingPromoted.length} slot(s) would cross the last market fill ` +
3386
+ `${Format.formatPrice6(marketRef)}`, 'warn');
3387
+ promotedCandidates.length = 0;
3388
+ }
3389
+ else if (collidingPromoted.length > 0) {
3390
+ manager.logger?.log?.(`[SPREAD-CORRECTION] Refusing boundary promotion on ${sideName}: ` +
3391
+ `${collidingPromoted.length} slot(s) collide with known-unmatched chain orders`, 'warn');
3392
+ promotedCandidates.length = 0;
3393
+ }
2817
3394
  if (promotedCandidates.length > 0) {
2818
3395
  manager.logger?.log?.(`[SPREAD-CORRECTION] ${promotedCandidates.length} gap slot(s) available for boundary promotion on ${sideName}`, 'info');
2819
3396
  }
@@ -2872,20 +3449,17 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2872
3449
  spreadCandidates = spreadCandidates.filter((c) => {
2873
3450
  if (c.price == null)
2874
3451
  return false;
2875
- const precision = railType === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
3452
+ // Grid-vs-grid: resolve both prices to their frozen ladder
3453
+ // level (genesis-aware), NOT priceSlotEqual at the asset
3454
+ // precision and NOT the chain tolerance (both can
3455
+ // collapse/merge adjacent grid levels).
2876
3456
  for (const o of allOrders) {
2877
3457
  if (!isOrderPlaced(o) || o.price == null)
2878
3458
  continue;
2879
3459
  if (o.id === c.id)
2880
3460
  continue;
2881
- try {
2882
- if (priceSlotEqual(o.price, c.price, precision))
2883
- return false;
2884
- }
2885
- catch {
2886
- if (o.price === c.price)
2887
- return false;
2888
- }
3461
+ if (sameGridLevel(o.price, c.price, manager._genesis))
3462
+ return false;
2889
3463
  }
2890
3464
  return true;
2891
3465
  });
@@ -2901,7 +3475,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2901
3475
  manager.logger?.log?.(bestLiveOnRail == null
2902
3476
  ? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
2903
3477
  : `[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');
2904
- return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: 'no-candidates', origin: COW_ORIGINS.SPREAD_CORRECTION };
3478
+ return { ordersToPlace: [], ordersToUpdate: [], plannedCount: 0, stallHint: refusalStallHint, origin: COW_ORIGINS.SPREAD_CORRECTION };
2905
3479
  }
2906
3480
  const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));
2907
3481
  const sideSlots = allOrders
@@ -3037,7 +3611,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3037
3611
  // inside the implied band. All real constraints — the
3038
3612
  // MIN_SPREAD_ORDERS reserve and opposite-rail stranding — are
3039
3613
  // enforced UPSTREAM as walk-depth caps. This backstop only
3040
- // verifies array limits plus the reserve ceiling; any
3614
+ // verifies array limits plus the edge ceiling; any
3041
3615
  // violation signals an internal inconsistency, so promotion is
3042
3616
  // refused loudly instead of silently re-geometried.
3043
3617
  const maxIdx = allSlotsByPrice.length - 1;