dexbot 1.7.0 → 1.7.2

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 (115) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +12 -1
  24. package/dist/modules/account_bots.js +7 -5
  25. package/dist/modules/account_orders.d.ts +12 -0
  26. package/dist/modules/account_orders.js +30 -0
  27. package/dist/modules/bitshares-native/transport.js +24 -6
  28. package/dist/modules/bitshares_client.d.ts +24 -6
  29. package/dist/modules/bitshares_client.js +44 -7
  30. package/dist/modules/bot_settings.d.ts +2 -0
  31. package/dist/modules/constants.d.ts +28 -3
  32. package/dist/modules/constants.js +79 -10
  33. package/dist/modules/dexbot_class.d.ts +23 -6
  34. package/dist/modules/dexbot_class.js +44 -0
  35. package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
  36. package/dist/modules/dexbot_cow_runtime.js +688 -188
  37. package/dist/modules/dexbot_fill_runtime.js +124 -35
  38. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  39. package/dist/modules/dexbot_maintenance_runtime.js +259 -79
  40. package/dist/modules/dexbot_startup_runtime.js +32 -20
  41. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  42. package/dist/modules/dexbot_state_recovery.js +167 -5
  43. package/dist/modules/node_connect_policy.d.ts +8 -1
  44. package/dist/modules/node_connect_policy.js +18 -2
  45. package/dist/modules/node_flap_score.d.ts +87 -0
  46. package/dist/modules/node_flap_score.js +124 -0
  47. package/dist/modules/node_health_cache.d.ts +40 -3
  48. package/dist/modules/node_health_cache.js +66 -20
  49. package/dist/modules/node_manager.d.ts +101 -19
  50. package/dist/modules/node_manager.js +255 -65
  51. package/dist/modules/order/accounting.d.ts +9 -4
  52. package/dist/modules/order/accounting.js +131 -19
  53. package/dist/modules/order/async_lock.d.ts +7 -1
  54. package/dist/modules/order/async_lock.js +7 -1
  55. package/dist/modules/order/export.js +25 -18
  56. package/dist/modules/order/fill_ledger.d.ts +99 -0
  57. package/dist/modules/order/fill_ledger.js +103 -0
  58. package/dist/modules/order/format.d.ts +24 -10
  59. package/dist/modules/order/format.js +30 -10
  60. package/dist/modules/order/grid.d.ts +75 -18
  61. package/dist/modules/order/grid.js +289 -72
  62. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  63. package/dist/modules/order/grid_reconcile.js +333 -210
  64. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  65. package/dist/modules/order/grid_reconcile_internal.js +223 -91
  66. package/dist/modules/order/index.d.ts +18 -5
  67. package/dist/modules/order/index.js +5 -5
  68. package/dist/modules/order/lifecycle.d.ts +353 -0
  69. package/dist/modules/order/lifecycle.js +1109 -0
  70. package/dist/modules/order/manager.d.ts +277 -20
  71. package/dist/modules/order/manager.js +680 -64
  72. package/dist/modules/order/placement_lock.d.ts +102 -0
  73. package/dist/modules/order/placement_lock.js +222 -0
  74. package/dist/modules/order/strategy.js +13 -1
  75. package/dist/modules/order/sync_engine.d.ts +74 -114
  76. package/dist/modules/order/sync_engine.js +254 -198
  77. package/dist/modules/order/utils/math.d.ts +29 -4
  78. package/dist/modules/order/utils/math.js +61 -4
  79. package/dist/modules/order/utils/order.d.ts +106 -37
  80. package/dist/modules/order/utils/order.js +256 -81
  81. package/dist/modules/order/utils/system.d.ts +99 -6
  82. package/dist/modules/order/utils/system.js +249 -35
  83. package/dist/modules/order/utils/validate.d.ts +7 -1
  84. package/dist/modules/order/utils/validate.js +48 -2
  85. package/dist/modules/outcome.d.ts +54 -0
  86. package/dist/modules/outcome.js +51 -0
  87. package/dist/modules/settings_merge.d.ts +4 -0
  88. package/dist/modules/settings_merge.js +9 -0
  89. package/dist/modules/timing_policy.d.ts +82 -0
  90. package/dist/modules/timing_policy.js +244 -0
  91. package/dist/modules/types.d.ts +149 -22
  92. package/dist/scripts/analyze-credit.js +54 -17
  93. package/dist/scripts/analyze-orders.d.ts +4 -2
  94. package/dist/scripts/analyze-orders.js +113 -34
  95. package/dist/scripts/chart_targets.js +11 -15
  96. package/dist/scripts/test-credit-renewal.js +12 -5
  97. package/docs/COW_INVARIANTS.md +71 -8
  98. package/docs/DEXBOT_COMPARISON.md +6 -6
  99. package/docs/EVOLUTION.md +10 -8
  100. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  101. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  102. package/docs/GRID_RECONCILE.md +18 -13
  103. package/docs/LOGGING.md +25 -1
  104. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
  105. package/docs/README.md +23 -2
  106. package/docs/WORKFLOW.md +9 -3
  107. package/docs/architecture.md +68 -13
  108. package/docs/developer_guide.md +25 -8
  109. package/modules/README.md +6 -0
  110. package/package.json +3 -3
  111. package/scripts/README.md +16 -0
  112. package/scripts/pdev.sh +14 -1
  113. package/scripts/pmain.sh +23 -8
  114. package/scripts/ptest.sh +7 -0
  115. package/tests/README.md +30 -1
@@ -13,6 +13,7 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
13
13
  import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
14
14
  const BroadcastUncertainError = BroadcastUncertainErrorBinding;
15
15
  import * as orderUtils from './order/utils/order.js';
16
+ import { lazyShim } from './lazy_shim.js';
16
17
  import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference, resolveSpreadCrossingFloor, isLastFillGuardBlocked } from './order/utils/system.js';
17
18
  const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
18
19
  import * as validate from './order/utils/validate.js';
@@ -20,6 +21,7 @@ const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGa
20
21
  import * as math from './order/utils/math.js';
21
22
  const { validateOrderSize, findCrossedOrder, sameGridLevel, isEvacuationRotationAllowed, isEvacuationSizeStillValid, getSellStartIdx, getPrecisionByOrderType, isSlotIndexInGapBand, getAssetFeesSafe, blockchainToFloat, floatToBlockchainInt, quantizeFloat } = math;
22
23
  import { parseSlotIndex } from './order/utils/slot.js';
24
+ import { resolveTradedSide } from './order/fill_ledger.js';
23
25
  /**
24
26
  * Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
25
27
  * geometry (boundaryIdx/_gapSlots at execution time). The stamp freezes
@@ -59,6 +61,147 @@ export function isEvacuationStampStillValid(liveBoundary, liveGapSlots, sourceId
59
61
  const dstInRail = orderType === ORDER_TYPES.SELL ? Number(dstIdx) >= sellStartIdx : Number(dstIdx) <= b;
60
62
  return dstInRail;
61
63
  }
64
+ /**
65
+ * Detect a live-rail conflict: the resting BUY/SELL rails cannot coexist with
66
+ * a `gapSlots`-wide spread band, i.e. no boundary value satisfies
67
+ * `maxBuy <= boundary` and `minSell >= boundary + gapSlots + 1` at once.
68
+ *
69
+ * Why this matters for gap evacuation: the stale-stamp check below refuses an
70
+ * evacuation whose source is no longer in-band under the LIVE (pre-commit)
71
+ * boundary. That is correct when the live geometry is itself consistent (the
72
+ * 2026-10-30 incident: plan boundary 124 wanted buys 125-128 evacuated, live
73
+ * 128 kept them on the rail, the bid edge survived). It is WRONG when the live
74
+ * rails already overlap: then the batch's boundary retreat is FORCED — some
75
+ * order has to move — and refusing the evacuation leaves the stranded order
76
+ * inside the band permanently (observed class: a buy fill inside the band
77
+ * crawls the boundary down, the retreat strands the two buys above it, the
78
+ * guard skips their rotation as stale, the rail clamp cannot move the boundary
79
+ * back because the sell rail caps it, and the 4-slot spread band keeps two
80
+ * live buys forever → real spread 1.2% against a 2.0% target).
81
+ *
82
+ * The test is boundary-independent (a crossing is a crossing at any boundary),
83
+ * so it cannot be satisfied by simply moving the boundary: only an evacuation
84
+ * resolves it. Ladder positions use the same live-price resolution as
85
+ * deriveRailBoundary, so a stale slot id cannot fake a rail member.
86
+ *
87
+ * @param manager - Manager exposing orders/assets/_genesis
88
+ * @param gapSlots - Gap-band width (slots)
89
+ * @returns `{ crossed, maxBuyIdx, minSellIdx, upper }`; `crossed` is false when
90
+ * either rail is empty (one-sided book proves nothing) or geometry is
91
+ * unknown (fail closed: keep the stale-stamp refusal).
92
+ */
93
+ export function liveRailsConflictWithGap(manager, gapSlots) {
94
+ const result = { crossed: false, maxBuyIdx: null, minSellIdx: null, upper: null };
95
+ const rawGap = Format.toKnownNumber(gapSlots);
96
+ if (!Number.isFinite(rawGap) || rawGap < 0)
97
+ return result;
98
+ const gap = Math.floor(rawGap);
99
+ const master = manager?.orders;
100
+ if (!(master instanceof Map))
101
+ return result;
102
+ const assets = manager?.assets;
103
+ const genesis = manager?._genesis;
104
+ let maxBuyIdx = null;
105
+ let minSellIdx = null;
106
+ for (const raw of master.values()) {
107
+ const o = raw;
108
+ if (!o || !o.id || !o.orderId)
109
+ continue;
110
+ if (o.state !== ORDER_STATES.ACTIVE && o.state !== ORDER_STATES.PARTIAL)
111
+ continue;
112
+ if (o.type !== ORDER_TYPES.BUY && o.type !== ORDER_TYPES.SELL)
113
+ continue;
114
+ const live = orderUtils.resolveLiveOrderLadderPosition(o, assets, genesis);
115
+ const idx = live.idx !== null && Number.isFinite(Number(live.idx)) ? Number(live.idx) : null;
116
+ if (idx === null)
117
+ continue;
118
+ if (o.type === ORDER_TYPES.BUY)
119
+ maxBuyIdx = maxBuyIdx === null ? idx : Math.max(maxBuyIdx, idx);
120
+ else
121
+ minSellIdx = minSellIdx === null ? idx : Math.min(minSellIdx, idx);
122
+ }
123
+ result.maxBuyIdx = maxBuyIdx;
124
+ result.minSellIdx = minSellIdx;
125
+ if (maxBuyIdx === null || minSellIdx === null)
126
+ return result;
127
+ const upper = minSellIdx - gap - 1;
128
+ result.upper = upper;
129
+ result.crossed = maxBuyIdx > upper;
130
+ return result;
131
+ }
132
+ /**
133
+ * Decide whether a stale-stamp refusal of a gap-evacuation rotation must yield
134
+ * to the forced-retreat allowance. Single authority for the three call sites
135
+ * (stamped build branch, unstamped build branch, final pivot gate) so the
136
+ * conditions can never drift apart.
137
+ *
138
+ * Two conditions, both required:
139
+ * 1. The stamp could actually be EVALUATED: an unparseable source/dest id is
140
+ * not a geometry disagreement — `isEvacuationStampStillValid` refuses those
141
+ * too, and overriding that would ship a rotation whose geometry nobody
142
+ * proved. Never override an unprovable stamp.
143
+ * 2. The live rails already conflict (see liveRailsConflictWithGap): some
144
+ * order must move at ANY boundary, so the plan's retreat is the only
145
+ * consistent geometry and the pre-commit "still on the rail" reading is not
146
+ * authoritative.
147
+ *
148
+ * @param manager - Manager exposing orders/assets/_genesis
149
+ * @param gapSlots - LIVE gap-band width (slots)
150
+ * @param sourceId - Evacuation source slot id
151
+ * @param destId - Evacuation destination slot id
152
+ * @returns The conflict record when the allowance applies, otherwise null.
153
+ */
154
+ export function forcedRetreatJustifiesEvacuation(manager, gapSlots, sourceId, destId) {
155
+ if (parseSlotIndex(sourceId) == null || parseSlotIndex(destId) == null)
156
+ return null;
157
+ const conflict = liveRailsConflictWithGap(manager, gapSlots);
158
+ return conflict.crossed ? conflict : null;
159
+ }
160
+ /**
161
+ * Split pending price corrections into "drain now" and "held back because this
162
+ * batch supersedes them".
163
+ *
164
+ * A cancel-only gap-evacuation whose chain order the batch ROTATES is
165
+ * superseded by the plan: the rotation moves that order onto its rail in place,
166
+ * and cancelling it first destroys the batch's own source. Observed live on a
167
+ * stranded 4-slot band: the teeth queued cancels for the two rotation sources,
168
+ * the pre-batch drain executed them, and the UPDATE batch was rejected
169
+ * pre-broadcast ("2 target(s) missing on chain") → structural resync + full grid
170
+ * reload + two CREATEs, instead of two in-place price updates.
171
+ *
172
+ * Held entries are put back after the drain: if the rotation is dropped or the
173
+ * batch aborts they stay queued (their own staleness check drops them once the
174
+ * slot no longer owns the order).
175
+ *
176
+ * @param entries - `manager.ordersNeedingPriceCorrection`
177
+ * @param actions - The batch's planned actions
178
+ * @returns `{ kept, held }` (both empty-safe)
179
+ */
180
+ export function splitEvacuationCancelsSupersededByRotations(entries, actions) {
181
+ const list = Array.isArray(entries) ? entries : [];
182
+ const kept = [];
183
+ const held = [];
184
+ const rotatedOrderIds = new Set();
185
+ if (Array.isArray(actions)) {
186
+ for (const action of actions) {
187
+ if (action?.type !== COW_ACTIONS.UPDATE || !action?.orderId)
188
+ continue;
189
+ rotatedOrderIds.add(String(action.orderId));
190
+ }
191
+ }
192
+ if (rotatedOrderIds.size === 0)
193
+ return { kept: list, held };
194
+ for (const entry of list) {
195
+ const superseded = entry?.gapEvacuation === true
196
+ && entry?.chainOrderId != null
197
+ && rotatedOrderIds.has(String(entry.chainOrderId));
198
+ if (superseded)
199
+ held.push(entry);
200
+ else
201
+ kept.push(entry);
202
+ }
203
+ return { kept, held };
204
+ }
62
205
  function hasSlotPriceCollision(items, targetPrice, genesis, excludeId, predicate) {
63
206
  for (const it of items) {
64
207
  if (predicate && !predicate(it))
@@ -84,6 +227,16 @@ const Format = FormatModule;
84
227
  import * as workingGridModule from './order/working_grid.js';
85
228
  const { WorkingGrid } = workingGridModule;
86
229
  import { getErrorMessage, resolveSeamMs, resolveSeamMsOrNull, getErrorField } from './utils/errors.js';
230
+ import { unknownCowOutcome } from './outcome.js';
231
+ /**
232
+ * Post-commit gap-evacuation sweep (lazy: dexbot_state_recovery pulls the
233
+ * bitshares client into the graph, which this runtime deliberately avoids).
234
+ * Detects live orders left inside the committed band and schedules a fill-less
235
+ * re-plan to evacuate them — the in-batch rotation is refused as stale when the
236
+ * plan's own crawl created the stranding, and without this the spread collapse
237
+ * never heals on a quiet market.
238
+ */
239
+ const scheduleGapEvacRepair = lazyShim('./dexbot_state_recovery', 'scheduleGapEvacRepair');
87
240
  // Maximum number of times the pre-broadcast staleness guard may re-plan the
88
241
  // batch from a fresh master before proceeding anyway. Bounded so a master
89
242
  // grid that keeps mutating (fill bursts, sync loops) can never livelock the
@@ -152,16 +305,16 @@ function createOpFingerprintForSlot(bot, order, finalInts, slotId) {
152
305
  });
153
306
  }
154
307
  /**
155
- * Read the pending-broadcast entries as an array. The manager map is
156
- * created lazily by recordPendingBroadcast, so every reader must guard
157
- * on `instanceof Map` — this helper is the single spelling of that guard.
308
+ * Read the pending-broadcast entries as an array.
309
+ *
310
+ * Thin wrapper over the single liveness authority (`getLivePendingBroadcasts`
311
+ * in `order/utils/order.ts`): TTL + caught-up-sync + 2× hard cap, with expired
312
+ * entries pruned. Do not re-implement the policy here.
158
313
  * @param {import('./dexbot_class.js').DEXBot} bot
159
314
  * @returns {Array}
160
315
  */
161
316
  function getPendingBroadcasts(bot) {
162
- return (bot.manager && bot.manager._pendingBroadcasts instanceof Map)
163
- ? Array.from(bot.manager._pendingBroadcasts.values())
164
- : [];
317
+ return orderUtils.getLivePendingBroadcasts(bot?.manager);
165
318
  }
166
319
  /**
167
320
  * Probe the chain snapshot for a pending-broadcast entry's slot.
@@ -332,6 +485,8 @@ function recordPendingBroadcast(bot, entry) {
332
485
  if (!bot.manager._pendingBroadcasts || !(bot.manager._pendingBroadcasts instanceof Map)) {
333
486
  bot.manager._pendingBroadcasts = new Map();
334
487
  }
488
+ // Prune expired entries before recording a new one (bounded map).
489
+ getPendingBroadcasts(bot);
335
490
  const fingerprint = createOpFingerprintForSlot(bot, entry.order, entry.finalInts, entry.order.id);
336
491
  if (!fingerprint) {
337
492
  bot.manager.logger.log?.(`[COW] Skipped pending-broadcast record: could not build fingerprint for ${entry.order?.id || 'unknown'}`, 'warn');
@@ -472,7 +627,7 @@ async function deferUncertainBroadcastRead(bot, detail, suffix, resyncReason, re
472
627
  bot.manager.logger.log(`[COW][UNCERTAIN] Structural resync escalation suppressed (cooldown ${cooldownMs}ms) — ` +
473
628
  `pending-broadcast protection retained; next clean read adopts landed orders.`, 'debug');
474
629
  }
475
- return { executed: false, hadRotation: false, uncertain: true, ambiguousRead: true };
630
+ return unknownCowOutcome('ambiguous-read');
476
631
  }
477
632
  /**
478
633
  * Build a fingerprint for an on-chain order so it can be matched against
@@ -950,7 +1105,7 @@ async function resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, a
950
1105
  * @param {import('./dexbot_class.js').DEXBot} bot
951
1106
  * @param {BroadcastUncertainError} err
952
1107
  * @param {Array<Object>} opContexts
953
- * @param {Object} options
1108
+ * @param {Object} _options - Reserved; the implementation takes no options yet.
954
1109
  * @returns {Promise<Object>}
955
1110
  */
956
1111
  async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _options) {
@@ -965,7 +1120,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
965
1120
  bot.manager.logger.log('[COW][UNCERTAIN] readOpenOrdersWithMeta unavailable; falling back to structural resync only.', 'error');
966
1121
  await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders unavailable', { batchId: err?.batchId || null });
967
1122
  clearPendingBroadcasts(bot.manager?._pendingBroadcasts);
968
- return { executed: false, hadRotation: false, uncertain: true };
1123
+ return unknownCowOutcome('unavailable', { detail: 'readOpenOrdersWithMeta unavailable' });
969
1124
  }
970
1125
  // 1. Read the chain
971
1126
  const accountRef = bot.accountId || bot.account?.id || bot.account;
@@ -981,7 +1136,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
981
1136
  `Falling back to structural resync.`, 'error');
982
1137
  await requestStructuralResync(bot, 'broadcast uncertain — readOpenOrders failed', { batchId: err?.batchId || null, error: getErrorMessage(readErr) || String(readErr) });
983
1138
  clearPendingBroadcasts(bot.manager?._pendingBroadcasts);
984
- return { executed: false, hadRotation: false, uncertain: true };
1139
+ return unknownCowOutcome('unavailable', { detail: 'readOpenOrders failed' });
985
1140
  }
986
1141
  // 1.5. Empty/truncated-read guard: an empty snapshot is ambiguous — the
987
1142
  // account is either genuinely empty or the node is lagging behind the
@@ -1026,11 +1181,11 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
1026
1181
  // after the reconciliation, ensuring the next cycle re-plans from a clean
1027
1182
  // chain snapshot.
1028
1183
  await resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, adoptedCount, discardedCount);
1029
- return { executed: false, hadRotation: false, uncertain: true, adoptedCount, discardedCount };
1184
+ return unknownCowOutcome('lost-receipt', { adoptedCount, discardedCount });
1030
1185
  }
1031
1186
  /**
1032
1187
  * Check whether to execute creates in outside-in pair mode.
1033
- * @param {import('./dexbot_class.js').DEXBot} bot
1188
+ * @param {unknown} _bot - Unused; the decision depends only on opContexts.
1034
1189
  * @param {Array} opContexts
1035
1190
  * @returns {boolean}
1036
1191
  */
@@ -1545,7 +1700,7 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1545
1700
  }
1546
1701
  /**
1547
1702
  * Resolve the ideal size from an order-like object with fallback.
1548
- * @param {import('./dexbot_class.js').DEXBot} bot
1703
+ * @param {unknown} _bot - Unused; the size comes from orderLike only.
1549
1704
  * @param {Object|null} orderLike
1550
1705
  * @param {number|null} [fallbackSize=null]
1551
1706
  * @returns {number|null}
@@ -1967,11 +2122,14 @@ function refreshLastFillPivotFromQueue(bot) {
1967
2122
  const recvAmt = Number(receives.amount);
1968
2123
  if (Number.isFinite(paysAmt) && paysAmt > 0 && Number.isFinite(recvAmt) && recvAmt > 0) {
1969
2124
  const paysFloat = (base, precision) => base / Math.pow(10, precision);
1970
- if (paysId === assets.assetA.id) {
2125
+ // Side from the paid asset through the shared resolver
2126
+ // (order/fill_ledger.ts); the price math stays here.
2127
+ const paysSide = resolveTradedSide(paysId, assets);
2128
+ if (paysSide === ORDER_TYPES.SELL) {
1971
2129
  type = ORDER_TYPES.SELL;
1972
2130
  price = paysFloat(recvAmt, assets.assetB.precision) / paysFloat(paysAmt, assets.assetA.precision);
1973
2131
  }
1974
- else if (paysId === assets.assetB.id) {
2132
+ else if (paysSide === ORDER_TYPES.BUY) {
1975
2133
  type = ORDER_TYPES.BUY;
1976
2134
  price = paysFloat(paysAmt, assets.assetB.precision) / paysFloat(recvAmt, assets.assetA.precision);
1977
2135
  }
@@ -2041,7 +2199,8 @@ function resolveLastFillGuardIncrement(bot) {
2041
2199
  }
2042
2200
  /**
2043
2201
  * Build COW actions array from a simple plan object.
2044
- * @param {import('./dexbot_class.js').DEXBot} bot
2202
+ * @param {import('./dexbot_class.js').DEXBot} _bot - Bot whose manager supplies the frozen
2203
+ * boundary/gap geometry the plan stamp carries (plan values win when set).
2045
2204
  * @param {Object|Array} plan
2046
2205
  * @returns {Array}
2047
2206
  */
@@ -2477,6 +2636,42 @@ function toRefillSlotIdSet(refillSlotIds) {
2477
2636
  }
2478
2637
  return set;
2479
2638
  }
2639
+ /**
2640
+ * Resolve the rail side of a plan's refill holes from the working grid (the
2641
+ * planned CREATE/rotation type) with the master grid as fallback. Used only to
2642
+ * scope the boundary hold to the promotion direction; an unknown side keeps the
2643
+ * legacy hold (fail safe).
2644
+ * @param refillSlotIds - Plan hole-CREATE/rotation destination ids
2645
+ * @param workingGrid - Plan working grid (has the planned slot types)
2646
+ * @param manager - Order manager (master fallback)
2647
+ * @returns ORDER_TYPES.BUY / SELL, or null when no refill slot carries a side
2648
+ */
2649
+ function resolveRefillSide(refillSlotIds, workingGrid, manager) {
2650
+ if (!Array.isArray(refillSlotIds))
2651
+ return null;
2652
+ let side = null;
2653
+ for (const raw of refillSlotIds) {
2654
+ if (typeof raw !== 'string' || raw.length === 0)
2655
+ continue;
2656
+ const planned = workingGrid?.get?.(raw);
2657
+ const master = manager?.orders instanceof Map ? manager.orders.get(raw) : null;
2658
+ // Prefer the planned type, but fall back to the master type when the
2659
+ // planned slot is side-neutral (SPREAD) or absent: a refill wire can
2660
+ // carry an id whose working-grid entry was normalized away.
2661
+ const plannedType = planned?.type;
2662
+ const type = (plannedType === ORDER_TYPES.BUY || plannedType === ORDER_TYPES.SELL)
2663
+ ? plannedType
2664
+ : master?.type;
2665
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
2666
+ continue;
2667
+ // A one-sided plan is the norm; a mixed wire is not a usable direction
2668
+ // signal, so report unknown and let the caller keep the legacy hold.
2669
+ if (side !== null && side !== type)
2670
+ return null;
2671
+ side = type;
2672
+ }
2673
+ return side;
2674
+ }
2480
2675
  /**
2481
2676
  * Boundary-hold decision for guard-skipped refills.
2482
2677
  * When a skipped slot is one of the plan's refill slots — a hole-CREATE that
@@ -2487,11 +2682,30 @@ function toRefillSlotIdSet(refillSlotIds) {
2487
2682
  * Unrelated vetoes (skip ids outside the refill set) never pin geometry.
2488
2683
  * The grid still commits; only the boundary value is held (same discipline
2489
2684
  * as the overrun-hold in validateBoundaryCommit).
2685
+ *
2686
+ * `refillSide` (BUY/SELL) scopes the hold to the boundary's PROMOTION
2687
+ * direction; a fill-driven retreat, or a wire whose side cannot be resolved
2688
+ * (null), keeps the legacy hold.
2490
2689
  */
2491
- function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUpdateSlotIds, clampedUpdateSlotIds, refillSlotIds, skippedCreateSlotIds = undefined) {
2690
+ function resolveRefillBoundaryHold(workingBoundary, committedBoundary, skippedUpdateSlotIds, clampedUpdateSlotIds, refillSlotIds, skippedCreateSlotIds = undefined, refillSide = null) {
2492
2691
  const refills = toRefillSlotIdSet(refillSlotIds);
2493
2692
  const heldRefillSlotIds = [];
2494
- if (refills.size > 0) {
2693
+ // A refill hold is evidence for a boundary PROMOTION — the move advances
2694
+ // TOWARD the band holes the refills would fill. A fill-driven retreat moves
2695
+ // AWAY from them: the skipped holes are now band slots, so holding the old
2696
+ // boundary would discard the fill-derived geometry (live incident: a hold
2697
+ // kept 169 over a fill-derived 168 after the buy fills at 168/167). Judging
2698
+ // the direction keeps the hold's own premise instead of adding a second
2699
+ // geometry source. No side/geometry => legacy hold (fail safe, never
2700
+ // fail-open into a boundary shift).
2701
+ const working = Format.toKnownNumber(workingBoundary);
2702
+ const committed = Format.toKnownNumber(committedBoundary);
2703
+ const towardBand = refillSide === ORDER_TYPES.BUY
2704
+ ? (Number.isFinite(working) && Number.isFinite(committed) ? Number(working) > Number(committed) : true)
2705
+ : refillSide === ORDER_TYPES.SELL
2706
+ ? (Number.isFinite(working) && Number.isFinite(committed) ? Number(working) < Number(committed) : true)
2707
+ : true;
2708
+ if (refills.size > 0 && towardBand) {
2495
2709
  const seen = new Set();
2496
2710
  const skipCollections = skippedCreateSlotIds !== undefined
2497
2711
  ? [skippedUpdateSlotIds, clampedUpdateSlotIds, skippedCreateSlotIds]
@@ -2751,13 +2965,24 @@ export function deriveRailBoundary(manager, opContexts, desiredBoundary, gapSlot
2751
2965
  if (dense) {
2752
2966
  const check = math.validatePersistedBoundary(next, slotsForGate, gap, vacatedSlotIds.size > 0 ? { allowInBandSlotIds: vacatedSlotIds } : undefined);
2753
2967
  if (!check || check.ok !== true) {
2754
- return {
2755
- boundary: null,
2756
- maxBuyIdx,
2757
- minSellIdx,
2758
- clamped: false,
2759
- reason: `unsafe: ${check?.reason ?? 'unknown'}${check?.detail ? ` (${check.detail})` : ''}`
2760
- };
2968
+ // VIOLATION-REDUCING REPAIR (same rule as the fill re-anchor):
2969
+ // the clamp may accept a move the strict validator refuses for
2970
+ // transient stranding only when it strands STRICTLY FEWER placed
2971
+ // orders than the committed boundary already does. This is what
2972
+ // lets a fill-derived retreat land while GAP-EVAC is still
2973
+ // draining older strands; structural refusals stay closed.
2974
+ const committed = Format.toKnownNumber(manager?.boundaryIdx);
2975
+ const repairsStrands = check?.reason === math.BOUNDARY_REJECT_PLACED_IN_BAND
2976
+ && math.boundaryMoveReducesStrands(Number.isFinite(committed) ? Number(committed) : null, next, slotsForGate, gap, vacatedSlotIds.size > 0 ? { allowInBandSlotIds: vacatedSlotIds } : undefined);
2977
+ if (!repairsStrands) {
2978
+ return {
2979
+ boundary: null,
2980
+ maxBuyIdx,
2981
+ minSellIdx,
2982
+ clamped: false,
2983
+ reason: `unsafe: ${check?.reason ?? 'unknown'}${check?.detail ? ` (${check.detail})` : ''}`
2984
+ };
2985
+ }
2761
2986
  }
2762
2987
  }
2763
2988
  }
@@ -2866,12 +3091,57 @@ function restoreSkippedUpdateSlotsInWorkingGrid(bot, workingGrid, skippedSlotIds
2866
3091
  * @param {Object} cowResult - The stale plan result
2867
3092
  * @param {number} replanDepth - Recursion depth (0 = first attempt)
2868
3093
  * @param {Object} preBroadcastGuard - The failed evaluateCommit result
2869
- * @returns {Promise<{handled: boolean, result?: Object}>} handled=true when the
3094
+ * @returns {Promise<{handled: boolean, result?: Object, placementTransferred?: boolean}>} handled=true when the
2870
3095
  * batch was resolved by the re-plan (fresh plan executed, or stale plan
2871
3096
  * skipped as already-consistent); handled=false when the caller must proceed
2872
- * with the original plan.
3097
+ * with the original plan. `placementTransferred` means the recursion now owns
3098
+ * the placement lease and the caller must not release it.
2873
3099
  */
2874
- async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs) {
3100
+ async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs, placementLease = null) {
3101
+ const rebuildInProgress = typeof bot.manager?.isStructuralRebuildInProgress === 'function'
3102
+ && bot.manager.isStructuralRebuildInProgress() === true;
3103
+ // STRUCTURAL REBUILD GUARD. A `grid-init`/resync staleness means the master
3104
+ // was rebuilt while this plan was in flight. The fresh master has no live
3105
+ // chain order IDs, so a re-plan would emit a create-only batch for levels
3106
+ // that startup reconcile is concurrently re-pricing via UPDATE. Both
3107
+ // generations land and the loser becomes a duplicate-price orphan backlog
3108
+ // (2026-11-03: 25 duplicate orders). Abort instead and let the
3109
+ // reconcile (update-first) complete — fills stay recorded and are drained
3110
+ // by the bootstrap consumer / next reconcile.
3111
+ //
3112
+ // The progress flag is the authoritative signal, not the reason string: a
3113
+ // rebuild mutates the master with contexts like `sync-pass1-partial`
3114
+ // (those mutations are stamped `structural rebuild` by the manager), and
3115
+ // a plan can reach here after the rebuild ended but while the reason still
3116
+ // names a fill. Checking both closes the non-`grid-init` gap.
3117
+ const structuralRebuild = rebuildInProgress
3118
+ || (typeof bot.manager?.isStructuralRebuildStale === 'function'
3119
+ ? bot.manager.isStructuralRebuildStale(preBroadcastGuard?.reason)
3120
+ : orderUtils.isStructuralRebuildStaleReason(preBroadcastGuard?.reason));
3121
+ if (structuralRebuild) {
3122
+ bot.manager.logger.log(`[COW] Plan stale after a structural grid rebuild (${preBroadcastGuard.reason}); ` +
3123
+ `aborting this batch so the startup reconcile keeps update-first ownership (no create-only re-plan).`, 'warn');
3124
+ popPushedWorkingGrid(bot, cowResult);
3125
+ // The aborted plan's CREATE slots were recorded as pending broadcasts
3126
+ // during op-building but will never be sent. Drop only THEIR entries:
3127
+ // keeping them would make the reconcile's surplus sweep and the next
3128
+ // batch's pending-broadcast guard treat a phantom create as in flight.
3129
+ // Entries from an earlier unresolved batch are deliberately kept.
3130
+ clearPendingBroadcastsForSlots(bot, cowResult.actions);
3131
+ // A rebuild that is still running already owns the repair: requesting
3132
+ // another structural resync here would start a second rebuild on top of
3133
+ // it (churn loop). Only ask when the rebuild has already ended.
3134
+ if (!rebuildInProgress) {
3135
+ await requestStructuralResync(bot, 'plan stale after structural rebuild (deferred to reconcile)', { reason: preBroadcastGuard.reason });
3136
+ }
3137
+ else {
3138
+ bot.manager.logger.log('[COW] Structural rebuild still in progress; leaving the resync to the active rebuild (no churn request)', 'debug');
3139
+ }
3140
+ return {
3141
+ handled: true,
3142
+ result: { executed: false, aborted: true, reason: 'STRUCTURAL_REBUILD_DEFERRED', hadRotation: false }
3143
+ };
3144
+ }
2875
3145
  const canReplan = replanDepth < STALE_PLAN_REPLAN_LIMIT
2876
3146
  && Array.isArray(cowResult.fills) && cowResult.fills.length > 0;
2877
3147
  if (!canReplan) {
@@ -2892,6 +3162,10 @@ async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard,
2892
3162
  const hadPushedGrid = cowResult?._workingGridPushed === true;
2893
3163
  popPushedWorkingGrid(bot, cowResult);
2894
3164
  let replanned = null;
3165
+ // Pre-plan snapshot of the per-batch absolute-anchor budget (see the restore
3166
+ // above). Kept at function scope so the fresh plan can carry it on for a
3167
+ // second re-plan.
3168
+ const reanchorBudgetBefore = Number(cowResult._reanchorBudgetBeforePlan);
2895
3169
  try {
2896
3170
  // Restore the boundary-shift budget consumed by the abandoned plan:
2897
3171
  // it was built from the same fills and never shipped, so the re-plan
@@ -2901,6 +3175,14 @@ async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard,
2901
3175
  if (bot.manager?._boundaryShiftBudgetBase != null) {
2902
3176
  bot.manager._boundaryShiftBudget = bot.manager._boundaryShiftBudgetBase;
2903
3177
  }
3178
+ // The absolute fill re-anchor is a per-batch BUDGET consumed at PLAN time
3179
+ // (strategy.calculateTargetGrid). The abandoned plan's anchor was never
3180
+ // committed, so hand it back: restore the value observed by the pre-plan
3181
+ // snapshot carried on the plan. A static batch base would be wrong — an
3182
+ // earlier chunk that legitimately committed its anchor must stay spent.
3183
+ if (Number.isFinite(reanchorBudgetBefore)) {
3184
+ bot.manager._boundaryReanchorBudget = reanchorBudgetBefore;
3185
+ }
2904
3186
  if (typeof bot.manager.performSafeRebalance === 'function') {
2905
3187
  // skipBroadcastWait: this frame is itself inside the executor's
2906
3188
  // startBroadcasting() region — waiting on the flag we hold would
@@ -2924,10 +3206,17 @@ async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard,
2924
3206
  // (duplicate orders). The recursion's guard will then abort +
2925
3207
  // reconcile instead.
2926
3208
  clearPendingBroadcastsForSlots(bot, cowResult.actions);
3209
+ // Hand the same pre-plan snapshot to the fresh plan so a SECOND
3210
+ // re-plan (its plan also goes stale) can restore the anchor again:
3211
+ // the budget is per-batch, and every abandoned plan must give back
3212
+ // only what IT spent.
3213
+ replanned._reanchorBudgetBeforePlan = reanchorBudgetBefore;
2927
3214
  return {
2928
3215
  handled: true,
3216
+ placementTransferred: true,
2929
3217
  result: await updateOrdersOnChainBatchCOW(bot, replanned, {
2930
3218
  replanDepth: replanDepth + 1,
3219
+ placementLease,
2931
3220
  // Carry the seam through the recursion explicitly: the inner
2932
3221
  // frame re-sets and re-restores it, so it must not depend on
2933
3222
  // the outer frame's side-channel value surviving.
@@ -3006,13 +3295,6 @@ async function waitForCowBroadcastSingleFlight(bot, label) {
3006
3295
  }
3007
3296
  return false;
3008
3297
  }
3009
- /**
3010
- * COW broadcast: Execute blockchain operations and commit working grid on success.
3011
- * @param {import('./dexbot_class.js').DEXBot} bot
3012
- * @param {Object} cowResult
3013
- * @param {Object} [options={}] - Internal execution options (replanDepth)
3014
- * @returns {Promise<Object>}
3015
- */
3016
3298
  /**
3017
3299
  * Derive an update action's planned target size (shared by the rotation and
3018
3300
  * plain size-update op builders).
@@ -3020,9 +3302,20 @@ async function waitForCowBroadcastSingleFlight(bot, label) {
3020
3302
  * @returns {number}
3021
3303
  */
3022
3304
  function plannedUpdateSize(action) {
3023
- return Number.isFinite(Number(action.newSize))
3305
+ const planned = Number.isFinite(Number(action.newSize))
3024
3306
  ? Number(action.newSize)
3025
3307
  : Number(action.order?.size || 0);
3308
+ // A PARTIAL slot's booked size is the post-fill remainder. The plan's
3309
+ // desired size is a full-side target and must not grow the order in place:
3310
+ // target the booked remainder at plan time so the broadcast op is correct
3311
+ // by construction (the clamp below stays as a defense-in-depth invariant).
3312
+ const order = action.order;
3313
+ if (order && order.state === ORDER_STATES.PARTIAL) {
3314
+ const booked = Number(order.size);
3315
+ if (Number.isFinite(booked) && booked > 0 && planned > booked)
3316
+ return booked;
3317
+ }
3318
+ return planned;
3026
3319
  }
3027
3320
  /**
3028
3321
  * Post-fill size invariant for COW UPDATE ops: a partially-filled order
@@ -3047,10 +3340,16 @@ function clampPostFillUpdateSize(bot, masterOrder, newSize, action) {
3047
3340
  if (!Number.isFinite(target) || !Number.isFinite(booked) || booked <= 0)
3048
3341
  return target;
3049
3342
  if (target > booked) {
3343
+ const slotKey = String(action?.id || masterOrder?.id || 'unknown');
3344
+ const warned = bot._clampPostFillWarnedSlots
3345
+ || (bot._clampPostFillWarnedSlots = new Set());
3346
+ const firstHit = !warned.has(slotKey);
3347
+ if (firstHit)
3348
+ warned.add(slotKey);
3050
3349
  bot.manager.logger.log(`[COW] Post-fill size clamp for ${action?.id || masterOrder?.id}: slot is PARTIAL with ` +
3051
3350
  `booked remaining ${Format.formatAmount(booked)} but the plan targets ` +
3052
3351
  `${Format.formatAmount(target)} — clamping to booked remaining. ` +
3053
- `A partially-filled order must not be grown in place by a COW update (fill accounting divergence).`, 'warn');
3352
+ `A partially-filled order must not be grown in place by a COW update (fill accounting divergence).`, firstHit ? 'warn' : 'debug');
3054
3353
  return booked;
3055
3354
  }
3056
3355
  return target;
@@ -3074,7 +3373,13 @@ async function runPreBroadcastGuards(bot, cowResult) {
3074
3373
  const chainOrderCandidates = Array.isArray(bot.manager?._lastUnmatchedChainOrders)
3075
3374
  ? bot.manager._lastUnmatchedChainOrders
3076
3375
  : [];
3077
- const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates, bot.manager?.config?.incrementPercent ?? null);
3376
+ const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates, bot.manager?.config?.incrementPercent ?? null, getPendingBroadcasts(bot).map((entry) => ({
3377
+ slotId: entry.slotId ?? entry.order?.id,
3378
+ price: entry.order?.price,
3379
+ size: entry.order?.size,
3380
+ type: entry.orderType ?? entry.order?.type,
3381
+ fingerprint: entry.fingerprint,
3382
+ })));
3078
3383
  if (!createSlotValidation.isValid) {
3079
3384
  for (const violation of createSlotValidation.violations) {
3080
3385
  let reason;
@@ -3097,6 +3402,9 @@ async function runPreBroadcastGuards(bot, cowResult) {
3097
3402
  case 'slot_create_uncertain':
3098
3403
  reason = `an earlier CREATE here has an unknown outcome (createUncertain)`;
3099
3404
  break;
3405
+ case 'pending_broadcast_collision':
3406
+ reason = `a pending uncertain CREATE already targets this slot/price`;
3407
+ break;
3100
3408
  default:
3101
3409
  reason = `existing orderId=${violation.currentOrderId}`;
3102
3410
  }
@@ -3434,7 +3742,7 @@ async function updateOrdersOnChainBatchCOW(bot, cowResult, options = {}) {
3434
3742
  // recursion, throws) funnels through the body() finally below, so no exit
3435
3743
  // can leak bot._testPollIntervalMs onto the bot.
3436
3744
  try {
3437
- return await updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs ?? undefined);
3745
+ return await updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs ?? undefined, options?.placementLease ?? null);
3438
3746
  }
3439
3747
  finally {
3440
3748
  // Restore only when this frame actually wrote a seam. The entry
@@ -3451,7 +3759,7 @@ async function updateOrdersOnChainBatchCOW(bot, cowResult, options = {}) {
3451
3759
  }
3452
3760
  }
3453
3761
  }
3454
- async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs) {
3762
+ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs, inheritedPlacementLease = null) {
3455
3763
  bot._currentCycleId = (Number.isFinite(Number(bot._currentCycleId)) ? Number(bot._currentCycleId) : 0) + 1;
3456
3764
  const { workingGrid, workingIndexes, workingBoundary, actions } = cowResult;
3457
3765
  // Boundary-hold value: computed pre-broadcast after the skip-restore and
@@ -3484,93 +3792,49 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3484
3792
  popPushedWorkingGrid(bot, cowResult);
3485
3793
  return { executed: true, hadRotation: false };
3486
3794
  }
3487
- // Single-flight COW broadcast guard (entry check): never broadcast two
3488
- // batches concurrently. Overlapping broadcasts plan from the same base
3489
- // grid version; when the first commits it bumps _gridVersion, so the
3490
- // second's commit is refused (base-version mismatch) -> adopt-from-chain
3491
- // -> snapshot reload that can drop the adopted order and produce an
3492
- // orphan fill. This entry wait is an optimization; the authoritative
3493
- // atomic check-and-set happens right before the broadcast below.
3494
- if (await waitForCowBroadcastSingleFlight(bot, 'entry')) {
3495
- popPushedWorkingGrid(bot, cowResult);
3496
- return { executed: false, aborted: true, reason: 'SHUTDOWN_IN_PROGRESS', hadRotation: false };
3497
- }
3498
- // DRAIN PENDING CORRECTIONS before the batch is planned/broadcast.
3499
- // Cancel-only corrections (duplicate-price orphans) queued by an earlier
3500
- // sync must not sit while batches run back-to-back (startup create
3501
- // groups, fill bursts) — with the open-orders sync loop disabled they
3502
- // would otherwise linger indefinitely, keep blocking same-level CREATEs,
3503
- // and risk cancelling the wrong side of a duplicate later. Draining here
3504
- // also keeps this batch's collision checks (chain_orphan_collision)
3505
- // honest: orphaned chain orders already queued for cancellation are
3506
- // resolved before the plan validates its CREATE targets against them.
3507
- const pendingCorrectionCount = Array.isArray(bot.manager?.ordersNeedingPriceCorrection)
3508
- ? bot.manager.ordersNeedingPriceCorrection.length
3509
- : 0;
3510
- if (pendingCorrectionCount > 0 && !bot._shuttingDown) {
3511
- try {
3512
- bot.manager.logger.log(`[COW] Draining ${pendingCorrectionCount} pending correction(s) before batch`, 'info');
3513
- const drainResult = await orderUtils.correctAllPriceMismatches(bot.manager, bot.account, bot.privateKey, chainOrders);
3514
- if (drainResult?.failed > 0) {
3515
- bot.manager.logger.log(`[COW] ${drainResult.failed} correction(s) failed pre-batch` +
3516
- ((drainResult.staleDropped ?? 0) > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
3517
- `; remaining entries retry on next sync/maintenance tick`, 'warn');
3518
- }
3519
- else if ((drainResult?.staleDropped ?? 0) > 0) {
3520
- bot.manager.logger.log(`[COW] Pre-batch drain resolved, ${drainResult.staleDropped} stale correction(s) dropped`, 'info');
3521
- }
3522
- }
3523
- catch (drainErr) {
3524
- bot.manager.logger.log(`[COW] Pre-batch correction drain failed: ${getErrorMessage(drainErr)}`, 'warn');
3795
+ // Exclusive placement region (shared with startup reconcile Phase 2,
3796
+ // correction drains, dust/residual cancels and pool swaps). Claim it BEFORE
3797
+ // the pre-batch drain and before any other mutation: planning is read-only,
3798
+ // but the drain and the broadcast are not, and a competing path that slips
3799
+ // in between the drain and the old late claim is exactly the duplicate
3800
+ // window this closes. Held through commit/uncertain-catch and released in
3801
+ // the body's finally (or transferred to the re-plan recursion).
3802
+ let heldPlacementLease = inheritedPlacementLease;
3803
+ const claimPlacement = async (stage) => {
3804
+ if (heldPlacementLease)
3805
+ return true;
3806
+ if (typeof bot.manager?.acquirePlacement !== 'function')
3807
+ return true;
3808
+ const lease = await bot.manager.acquirePlacement('cow-broadcast', {
3809
+ timeoutMs: SINGLE_FLIGHT_MAX_WAIT_MS,
3810
+ isShuttingDown: () => bot._shuttingDown === true,
3811
+ });
3812
+ if (!lease) {
3813
+ bot.manager.logger.log(`[COW] ${stage}: exclusive placement region unavailable (timeout/shutdown); aborting this batch instead of overlapping another placement path.`, 'warn');
3814
+ return false;
3525
3815
  }
3816
+ heldPlacementLease = lease;
3817
+ return true;
3818
+ };
3819
+ const releasePlacement = () => {
3820
+ const lease = heldPlacementLease;
3821
+ heldPlacementLease = null;
3822
+ lease?.release();
3823
+ };
3824
+ // Claim before the entry single-flight wait: the second batch then queues
3825
+ // on placement instead of building a plan, and there is no lock-order
3826
+ // inversion (both COW frames acquire placement before the COW slot).
3827
+ if (!(await claimPlacement('entry'))) {
3828
+ popPushedWorkingGrid(bot, cowResult);
3829
+ return { executed: false, aborted: true, reason: 'PLACEMENT_REGION_UNAVAILABLE', hadRotation: false };
3526
3830
  }
3527
- // Pre-broadcast guard chain (create-slot validation, recovery-exhausted
3528
- // block, pending/unmatched guards, crossed-book gate) — see
3529
- // runPreBroadcastGuards. Refusals already popped the working grid.
3530
- const guards = await runPreBroadcastGuards(bot, cowResult);
3531
- if (!guards.proceed)
3532
- return guards.result ?? { executed: false, hadRotation: false };
3533
- const { crossingCandidates = [], intraBatchCandidates = [] } = guards;
3534
- const { assetA, assetB } = bot.manager.assets;
3831
+ // Everything after a successful claim runs INSIDE this try/finally: the
3832
+ // placement lease is released on every exit, including a throw from the
3833
+ // pre-broadcast drain/guards. An acquire outside the try leaked the lease
3834
+ // on any throw, and a leaked lease parks the fill queue (placement-aware
3835
+ // deferral) while the broadcast watchdog refuses to clear it.
3535
3836
  const operations = [];
3536
3837
  const opContexts = [];
3537
- const skippedUpdateSlotIds = new Set();
3538
- let skippedUpdateCount = 0;
3539
- // Guard-skipped CREATE slot ids (hole-refills never placed). Fed to the
3540
- // boundary-hold intersect alongside the UPDATE sets above — a skipped
3541
- // refill CREATE strands its rail hole exactly like a restored UPDATE.
3542
- const skippedCreateSlotIds = new Set();
3543
- // Per-batch LAST-FILL-GUARD disposition counters. Per-action pass lines
3544
- // would spam big batches, so the guard emits one batch summary instead
3545
- // (see the summary after the action loop below).
3546
- const lastFillGuardStats = { checked: 0, passed: 0, skipped: 0, bypassed: 0, pivotOffGrid: 0 };
3547
- // One crossing-CREATE observation per batch (see warnCrossingCreate).
3548
- let crossingCreateWarned = false;
3549
- // Fingerprints of the pending-broadcast entries recorded by THIS batch's
3550
- // op-building (both CREATE paths). The final pivot gate's compaction
3551
- // remaps these entries' stored opIndex/ctxIndex to their post-drop
3552
- // positions; entry.batchId cannot discriminate batches (always null in
3553
- // production), so the fingerprint set is the ownership marker.
3554
- const batchPendingFps = new Set();
3555
- // Per-batch GRID-PRICE-INVARIANT counters (BLOCKING). Tracks emitted prices
3556
- // that are not the genesis level for their slot — such emissions are
3557
- // rejected, not placed. One batch summary.
3558
- const gridPriceInvariantStats = { checked: 0, violated: 0, unchecked: 0 };
3559
- // Whether any guard check in this batch refreshed the pivot from
3560
- // still-queued fills — reported in the batch summary so a pivot change
3561
- // that altered a guard decision is visible at info, not just debug.
3562
- let lastFillGuardPivotRefreshed = false;
3563
- // Slots whose size-update op was broadcast with a post-fill-clamped
3564
- // target: the working grid still holds the planned (larger) size, so the
3565
- // slots are re-synced from master before commit to keep the committed
3566
- // books equal to the broadcast chain amounts.
3567
- const clampedUpdateSlotIds = new Set();
3568
- // orderId -> operations index of its cancel op. A crossing re-pricing
3569
- // update is only safe when the crossed order's cancel was already queued
3570
- // at an earlier position: ops broadcast in gap-slot-sized chunks,
3571
- // so an earlier index means the cancel confirms on chain (same or earlier
3572
- // chunk, applied sequentially) before the crossing order lands.
3573
- const cancelOpIndexByOrderId = new Map();
3574
3838
  const idsToLock = new Set();
3575
3839
  for (const action of actions) {
3576
3840
  if (action.type === COW_ACTIONS.CANCEL && action.orderId) {
@@ -3587,20 +3851,178 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3587
3851
  idsToLock.add(action.id);
3588
3852
  }
3589
3853
  }
3590
- bot.manager.lockOrders(idsToLock);
3591
- // Ownership of the single-flight broadcast slot for THIS frame. Only the
3592
- // frame that claimed the slot (set bot._cowBroadcastInFlight = true below)
3593
- // may clear it in the finally. A frame that waits at the entry check or
3594
- // early-returns after planning (fund validation, create-slot abort, op-prep
3595
- // throw) never owns the slot and MUST NOT clear it — an unconditional clear
3596
- // would wipe a concurrent batch's in-flight flag and let a third batch
3597
- // broadcast on top of it (the exact overlap this guard prevents).
3598
3854
  let heldBroadcastSlot = false;
3855
+ let batchInFlightRaised = false;
3856
+ let ordersLocked = false;
3857
+ // Broadcast-region ownership for THIS frame. startBroadcasting() runs
3858
+ // before the action loop (fills must stay deferred while ops are built),
3859
+ // but the inner broadcast try/finally only covers the broadcast section.
3860
+ // Every early return in between — all CREATEs skipped by the last-fill /
3861
+ // crossing / size guards (operations.length === 0), fund-validation
3862
+ // refusal, stale-plan re-plan, single-flight/placement aborts — used to
3863
+ // return with the refcount still held. The leaked flag then froze the
3864
+ // fill consumer until the 120s stale-flag watchdog (2026-11-04 incident:
3865
+ // three such returns parked 26 fills, the backlog was replayed against a
3866
+ // stale boundary and the bot sold below levels it had already sold).
3867
+ // One flag + one releaser: the inner finally, the catch and the outer
3868
+ // finally all call it, and only the first call decrements — a second raw
3869
+ // stopBroadcasting() in the outer finally would underflow another
3870
+ // holder's region (grid reconcile / spread correction).
3871
+ let broadcastRegionHeld = false;
3872
+ const releaseBroadcastRegion = () => {
3873
+ if (!broadcastRegionHeld)
3874
+ return;
3875
+ broadcastRegionHeld = false;
3876
+ bot.manager.stopBroadcasting();
3877
+ };
3599
3878
  try {
3879
+ // Single-flight COW broadcast guard (entry check): never broadcast two
3880
+ // batches concurrently. Overlapping broadcasts plan from the same base
3881
+ // grid version; when the first commits it bumps _gridVersion, so the
3882
+ // second's commit is refused (base-version mismatch) -> adopt-from-chain
3883
+ // -> snapshot reload that can drop the adopted order and produce an
3884
+ // orphan fill. This entry wait is an optimization; the authoritative
3885
+ // atomic check-and-set happens right before the broadcast below.
3886
+ if (await waitForCowBroadcastSingleFlight(bot, 'entry')) {
3887
+ releasePlacement();
3888
+ popPushedWorkingGrid(bot, cowResult);
3889
+ return { executed: false, aborted: true, reason: 'SHUTDOWN_IN_PROGRESS', hadRotation: false };
3890
+ }
3891
+ // DRAIN PENDING CORRECTIONS before the batch is planned/broadcast.
3892
+ // Cancel-only corrections (duplicate-price orphans) queued by an earlier
3893
+ // sync must not sit while batches run back-to-back (startup create
3894
+ // groups, fill bursts) — with the open-orders sync loop disabled they
3895
+ // would otherwise linger indefinitely, keep blocking same-level CREATEs,
3896
+ // and risk cancelling the wrong side of a duplicate later. Draining here
3897
+ // also keeps this batch's collision checks (chain_orphan_collision)
3898
+ // honest: orphaned chain orders already queued for cancellation are
3899
+ // resolved before the plan validates its CREATE targets against them.
3900
+ //
3901
+ // EXCEPTION — a cancel-only gap-evacuation whose chain order THIS batch
3902
+ // rotates is superseded by the plan: the rotation moves the order onto its
3903
+ // rail in place, and cancelling it first destroys the batch's own source
3904
+ // (observed live: "2 target(s) missing on chain" → structural resync + full
3905
+ // grid reload instead of two in-place price updates). Hold those entries out
3906
+ // of the drain and put them back afterwards — if the rotation is dropped or
3907
+ // the batch aborts, the entry stays queued for the next tick (its own
3908
+ // staleness check drops it once the slot is evacuated).
3909
+ let heldEvacuationCorrections = [];
3910
+ if (Array.isArray(bot.manager?.ordersNeedingPriceCorrection)) {
3911
+ const split = splitEvacuationCancelsSupersededByRotations(bot.manager.ordersNeedingPriceCorrection, actions);
3912
+ if (split.held.length > 0) {
3913
+ heldEvacuationCorrections = split.held;
3914
+ bot.manager.ordersNeedingPriceCorrection = split.kept;
3915
+ bot.manager.logger.log(`[COW] Holding ${split.held.length} gap-evacuation cancel(s) back from the pre-batch drain: ` +
3916
+ `this batch rotates the same chain order (the rotation IS the evacuation)`, 'debug');
3917
+ }
3918
+ }
3919
+ const pendingCorrectionCount = Array.isArray(bot.manager?.ordersNeedingPriceCorrection)
3920
+ ? bot.manager.ordersNeedingPriceCorrection.length
3921
+ : 0;
3922
+ if (pendingCorrectionCount > 0 && !bot._shuttingDown) {
3923
+ try {
3924
+ bot.manager.logger.log(`[COW] Draining ${pendingCorrectionCount} pending correction(s) before batch`, 'info');
3925
+ const drainResult = await orderUtils.correctAllPriceMismatches(bot.manager, bot.account, bot.privateKey, chainOrders, { placementLease: heldPlacementLease });
3926
+ if (drainResult?.failed > 0) {
3927
+ bot.manager.logger.log(`[COW] ${drainResult.failed} correction(s) failed pre-batch` +
3928
+ ((drainResult.staleDropped ?? 0) > 0 ? `, ${drainResult.staleDropped} stale dropped` : '') +
3929
+ `; remaining entries retry on next sync/maintenance tick`, 'warn');
3930
+ }
3931
+ else if ((drainResult?.staleDropped ?? 0) > 0) {
3932
+ bot.manager.logger.log(`[COW] Pre-batch drain resolved, ${drainResult.staleDropped} stale correction(s) dropped`, 'info');
3933
+ }
3934
+ }
3935
+ catch (drainErr) {
3936
+ bot.manager.logger.log(`[COW] Pre-batch correction drain failed: ${getErrorMessage(drainErr)}`, 'warn');
3937
+ }
3938
+ }
3939
+ if (heldEvacuationCorrections.length > 0 && Array.isArray(bot.manager?.ordersNeedingPriceCorrection)) {
3940
+ // Restore in queue order. Entries the drain already resolved are gone;
3941
+ // these were never handed to it, so they are all still pending.
3942
+ bot.manager.ordersNeedingPriceCorrection.push(...heldEvacuationCorrections);
3943
+ }
3944
+ // Pre-broadcast guard chain (create-slot validation, recovery-exhausted
3945
+ // block, pending/unmatched guards, crossed-book gate) — see
3946
+ // runPreBroadcastGuards. Refusals already popped the working grid.
3947
+ const guards = await runPreBroadcastGuards(bot, cowResult);
3948
+ if (!guards.proceed) {
3949
+ releasePlacement();
3950
+ return guards.result ?? { executed: false, hadRotation: false };
3951
+ }
3952
+ const { crossingCandidates = [], intraBatchCandidates = [] } = guards;
3953
+ const { assetA, assetB } = bot.manager.assets;
3954
+ const skippedUpdateSlotIds = new Set();
3955
+ let skippedUpdateCount = 0;
3956
+ // Guard-skipped CREATE slot ids (hole-refills never placed). Fed to the
3957
+ // boundary-hold intersect alongside the UPDATE sets above — a skipped
3958
+ // refill CREATE strands its rail hole exactly like a restored UPDATE.
3959
+ const skippedCreateSlotIds = new Set();
3960
+ // Per-batch LAST-FILL-GUARD disposition counters. Per-action pass lines
3961
+ // would spam big batches, so the guard emits one batch summary instead
3962
+ // (see the summary after the action loop below).
3963
+ const lastFillGuardStats = { checked: 0, passed: 0, skipped: 0, bypassed: 0, pivotOffGrid: 0 };
3964
+ // One crossing-CREATE observation per batch (see warnCrossingCreate).
3965
+ let crossingCreateWarned = false;
3966
+ // Fingerprints of the pending-broadcast entries recorded by THIS batch's
3967
+ // op-building (both CREATE paths). The final pivot gate's compaction
3968
+ // remaps these entries' stored opIndex/ctxIndex to their post-drop
3969
+ // positions; entry.batchId cannot discriminate batches (always null in
3970
+ // production), so the fingerprint set is the ownership marker.
3971
+ const batchPendingFps = new Set();
3972
+ // Per-batch GRID-PRICE-INVARIANT counters (BLOCKING). Tracks emitted prices
3973
+ // that are not the genesis level for their slot — such emissions are
3974
+ // rejected, not placed. One batch summary.
3975
+ const gridPriceInvariantStats = { checked: 0, violated: 0, unchecked: 0 };
3976
+ // Whether any guard check in this batch refreshed the pivot from
3977
+ // still-queued fills — reported in the batch summary so a pivot change
3978
+ // that altered a guard decision is visible at info, not just debug.
3979
+ let lastFillGuardPivotRefreshed = false;
3980
+ // Slots whose size-update op was broadcast with a post-fill-clamped
3981
+ // target: the working grid still holds the planned (larger) size, so the
3982
+ // slots are re-synced from master before commit to keep the committed
3983
+ // books equal to the broadcast chain amounts.
3984
+ const clampedUpdateSlotIds = new Set();
3985
+ // orderId -> operations index of its cancel op. A crossing re-pricing
3986
+ // update is only safe when the crossed order's cancel was already queued
3987
+ // at an earlier position: ops broadcast in gap-slot-sized chunks,
3988
+ // so an earlier index means the cancel confirms on chain (same or earlier
3989
+ // chunk, applied sequentially) before the crossing order lands.
3990
+ const cancelOpIndexByOrderId = new Map();
3991
+ bot.manager.lockOrders(idsToLock);
3992
+ ordersLocked = true;
3993
+ // Ownership of the single-flight broadcast slot for THIS frame. Only the
3994
+ // frame that claimed the slot (set bot._cowBroadcastInFlight = true below)
3995
+ // may clear it in the finally. A frame that waits at the entry check or
3996
+ // early-returns after planning (fund validation, create-slot abort, op-prep
3997
+ // throw) never owns the slot and MUST NOT clear it — an unconditional clear
3998
+ // would wipe a concurrent batch's in-flight flag and let a third batch
3999
+ // broadcast on top of it (the exact overlap this guard prevents).
4000
+ // Exclusive placement region is claimed at the top of the body (before the
4001
+ // pre-batch drain). `heldBroadcastSlot` only serializes COW batches; the
4002
+ // placement lease serializes EVERY chain-mutating path. Both are released
4003
+ // on every exit; the re-plan recursion inherits the lease.
4004
+ // LEASE-LIVENESS RE-CHECK (the mirror of the nested drain's check): the
4005
+ // stale-region watchdog may have force-released this lease while the batch
4006
+ // was parked on a slow chain read, and another path can own the region by
4007
+ // now. The OWNER has to verify before broadcasting, exactly like the drain
4008
+ // it hands the lease to — otherwise the torn-down batch wakes up and
4009
+ // broadcasts unprotected, which is the duplicate window the watchdog was
4010
+ // allowed to open only because it believed the batch was hung.
4011
+ if (heldPlacementLease
4012
+ && typeof bot.manager.isPlacementLeaseCurrent === 'function'
4013
+ && !bot.manager.isPlacementLeaseCurrent(heldPlacementLease)) {
4014
+ bot.manager.logger.log('[COW] Placement lease was force-released while this batch was in flight (stale-region watchdog); ' +
4015
+ 'aborting this batch instead of broadcasting without the region.', 'warn');
4016
+ popPushedWorkingGrid(bot, cowResult);
4017
+ return { executed: false, aborted: true, reason: 'PLACEMENT_LEASE_LOST', hadRotation: false };
4018
+ }
3600
4019
  bot._batchInFlight++;
4020
+ batchInFlightRaised = true;
4021
+ bot._batchInFlightStartedAt = Date.now();
3601
4022
  bot._markGridActivity('batch start');
3602
4023
  bot.manager._setRebalanceState(REBALANCE_STATES.BROADCASTING);
3603
4024
  bot.manager.startBroadcasting();
4025
+ broadcastRegionHeld = true;
3604
4026
  // P3 — freeze the guard pivot once per batch: per-action refreshes
3605
4027
  // mutated the pivot mid-batch (02:03 pivots drifted 0.001523→0.001529
3606
4028
  // across 20 checks), so early actions were judged against a different
@@ -3930,9 +4352,27 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3930
4352
  // live probe below instead of bypassing outright.
3931
4353
  const stampValid = isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, action.id, action.newGridId, orderType);
3932
4354
  if (!stampValid) {
3933
- stampUsable = false;
3934
- bot.manager.logger.log(`[LAST-FILL-GUARD] Stamped evacuation for ${action.id} -> ${action.newGridId} is stale under live ` +
3935
- `boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} — refusing the stale plan`, 'warn');
4355
+ // FORCED-RETREAT ALLOWANCE: the pre-commit
4356
+ // geometry says the source is still a rail
4357
+ // member, but if the live rails cannot host
4358
+ // the gap band at ANY boundary then the
4359
+ // batch's retreat is forced and refusing
4360
+ // this evacuation is what permanently
4361
+ // strands the order inside the band (the
4362
+ // spread-collapse class this check is meant
4363
+ // to protect against, inverted).
4364
+ const conflict = forcedRetreatJustifiesEvacuation(bot.manager, bot.manager?._gapSlots, action.id, action.newGridId);
4365
+ if (conflict) {
4366
+ bot.manager.logger.log(`[LAST-FILL-GUARD] Stamped evacuation for ${action.id} -> ${action.newGridId} is stale under live ` +
4367
+ `boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}, but the live rails already conflict ` +
4368
+ `(maxBuy=${conflict.maxBuyIdx} > minSell-gap-1=${conflict.upper}) — the retreat this batch commits is ` +
4369
+ `forced, so the evacuation proceeds (plan-build authority kept)`, 'warn');
4370
+ }
4371
+ else {
4372
+ stampUsable = false;
4373
+ bot.manager.logger.log(`[LAST-FILL-GUARD] Stamped evacuation for ${action.id} -> ${action.newGridId} is stale under live ` +
4374
+ `boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots} — refusing the stale plan`, 'warn');
4375
+ }
3936
4376
  }
3937
4377
  }
3938
4378
  if (stampUsable) {
@@ -4005,10 +4445,26 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4005
4445
  // Non-finite live geometry keeps plan-build authority
4006
4446
  // (isEvacuationStampStillValid returns true there).
4007
4447
  let staleSkipReason = null;
4008
- if (!isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, action.id, action.newGridId, orderType)) {
4009
- staleSkipReason = `source/dest no longer evacuation geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`;
4448
+ const stampStillValid = isEvacuationStampStillValid(bot.manager?.boundaryIdx, bot.manager?._gapSlots, action.id, action.newGridId, orderType);
4449
+ if (!stampStillValid) {
4450
+ // Same forced-retreat allowance as the
4451
+ // stamped branch: a live rail conflict means
4452
+ // only an evacuation can resolve the
4453
+ // geometry, so the pre-commit "still on the
4454
+ // rail" reading is not authoritative. The
4455
+ // live probe below still proves direction
4456
+ // and size (this is not a blind bypass).
4457
+ const conflict = forcedRetreatJustifiesEvacuation(bot.manager, bot.manager?._gapSlots, action.id, action.newGridId);
4458
+ if (conflict) {
4459
+ bot.manager.logger.log(`[LAST-FILL-GUARD] ${action.id} -> ${action.newGridId} is stale under live boundary ` +
4460
+ `${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}, but the live rails already conflict ` +
4461
+ `(maxBuy=${conflict.maxBuyIdx} > minSell-gap-1=${conflict.upper}) — re-proving the evacuation live`, 'warn');
4462
+ }
4463
+ else {
4464
+ staleSkipReason = `source/dest no longer evacuation geometry under live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}`;
4465
+ }
4010
4466
  }
4011
- else {
4467
+ if (staleSkipReason === null) {
4012
4468
  const evacCheck = isEvacuationRotationAllowed(oldPrice, oldSize, newPrice, newSize, orderType, sidePrecision);
4013
4469
  if (evacCheck.allowed) {
4014
4470
  bypassedEvacuation = true;
@@ -4390,8 +4846,11 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4390
4846
  }
4391
4847
  // BOUNDARY HOLD: skipped refill slots strand empty rail holes past the
4392
4848
  // planned boundary (commit gate skips empties, self-legalizing) — hold
4393
- // the committed boundary; intersect-only, grid still commits.
4394
- const refillHold = resolveRefillBoundaryHold(workingBoundary, bot.manager.boundaryIdx, skippedUpdateSlotIds, clampedUpdateSlotIds, cowResult?.refillSlotIds, skippedCreateSlotIds);
4849
+ // the committed boundary; intersect-only, grid still commits. The hold
4850
+ // is scoped to the boundary's PROMOTION direction: a fill-driven retreat
4851
+ // moves away from the holes and must not be pinned (see
4852
+ // resolveRefillBoundaryHold).
4853
+ const refillHold = resolveRefillBoundaryHold(workingBoundary, bot.manager.boundaryIdx, skippedUpdateSlotIds, clampedUpdateSlotIds, cowResult?.refillSlotIds, skippedCreateSlotIds, resolveRefillSide(cowResult?.refillSlotIds, workingGrid, bot.manager));
4395
4854
  effectiveBoundary = refillHold.effectiveBoundary;
4396
4855
  boundaryHeld = refillHold.heldRefillSlotIds.length > 0;
4397
4856
  if (refillHold.heldRefillSlotIds.length > 0) {
@@ -4484,8 +4943,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4484
4943
  });
4485
4944
  if (!preBroadcastGuard.canCommit) {
4486
4945
  // Bounded re-plan + proceed — policy documented on replanStaleBatch.
4487
- const replan = await replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs);
4946
+ const replan = await replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard, seamPollIntervalMs, heldPlacementLease);
4488
4947
  if (replan.handled) {
4948
+ if (replan.placementTransferred)
4949
+ heldPlacementLease = null;
4489
4950
  return replan.result ?? { executed: false, hadRotation: false };
4490
4951
  }
4491
4952
  // Fall through: proceed with the current plan (bounded policy).
@@ -4507,6 +4968,8 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4507
4968
  popPushedWorkingGrid(bot, cowResult);
4508
4969
  return { executed: false, aborted: true, reason: 'SHUTDOWN_IN_PROGRESS', hadRotation: false };
4509
4970
  }
4971
+ // Placement was claimed at the top of the body, before the pre-batch
4972
+ // drain, and is held through this broadcast and the commit.
4510
4973
  bot._cowBroadcastInFlight = true;
4511
4974
  heldBroadcastSlot = true;
4512
4975
  // Re-validate the plan AFTER winning the broadcast slot, but only when
@@ -4530,8 +4993,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4530
4993
  `(${postWaitGuard.reason}); releasing the broadcast slot and re-planning from fresh master`, 'warn');
4531
4994
  bot._cowBroadcastInFlight = false;
4532
4995
  heldBroadcastSlot = false;
4533
- const replan = await replanStaleBatch(bot, cowResult, replanDepth, postWaitGuard, seamPollIntervalMs);
4996
+ const replan = await replanStaleBatch(bot, cowResult, replanDepth, postWaitGuard, seamPollIntervalMs, heldPlacementLease);
4534
4997
  if (replan.handled) {
4998
+ if (replan.placementTransferred)
4999
+ heldPlacementLease = null;
4535
5000
  return replan.result ?? { executed: false, hadRotation: false };
4536
5001
  }
4537
5002
  // No fill context for a re-plan (or the re-plan limit was
@@ -4541,6 +5006,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4541
5006
  popPushedWorkingGrid(bot, cowResult);
4542
5007
  return { executed: false, aborted: true, reason: 'SHUTDOWN_IN_PROGRESS', hadRotation: false };
4543
5008
  }
5009
+ if (!(await claimPlacement('post-stale-replan'))) {
5010
+ popPushedWorkingGrid(bot, cowResult);
5011
+ return { executed: false, aborted: true, reason: 'PLACEMENT_REGION_UNAVAILABLE', hadRotation: false };
5012
+ }
4544
5013
  bot._cowBroadcastInFlight = true;
4545
5014
  heldBroadcastSlot = true;
4546
5015
  }
@@ -4699,6 +5168,17 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4699
5168
  }
4700
5169
  bot._metrics.batchesExecuted++;
4701
5170
  clearPendingBroadcasts(bot.manager?._pendingBroadcasts);
5171
+ // Post-commit stranding sweep: a boundary move that left a live
5172
+ // order inside the band is a violation this batch created, and
5173
+ // the in-batch evacuation was refused as stale (see
5174
+ // forcedRetreatJustifiesEvacuation for the allowance).
5175
+ // Re-plan now that the committed geometry IS the live geometry:
5176
+ // the evacuation stamp validates and the rotation executes as a
5177
+ // single price update. No-op when the band is clean.
5178
+ try {
5179
+ scheduleGapEvacRepair(bot, 'post-commit');
5180
+ }
5181
+ catch { /* heal path is best-effort; never fail a committed batch */ }
4702
5182
  return { ...batchResult, executed: true, hadRotation: true };
4703
5183
  }
4704
5184
  else {
@@ -4711,7 +5191,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4711
5191
  finally {
4712
5192
  bot.manager._throwOnIllegalState = false;
4713
5193
  await bot.manager.resumeFundRecalc();
4714
- bot.manager.stopBroadcasting();
5194
+ releaseBroadcastRegion();
4715
5195
  const createCount = actions.filter((a) => a.type === COW_ACTIONS.CREATE).length;
4716
5196
  const cancelCount = actions.filter((a) => a.type === COW_ACTIONS.CANCEL).length;
4717
5197
  bot.manager.logger.logFundsStatus(bot.manager, `AFTER COW batch (created=${createCount}, cancelled=${cancelCount})`);
@@ -4722,14 +5202,14 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4722
5202
  if (getErrorField(err, 'partialOnChainState')) {
4723
5203
  bot.manager.logger.log(`[COW] Non-atomic grouped execution detected (${formatPartialBroadcastSummary(err)}). Local rollback cannot undo confirmed on-chain operations; next sync/reconcile will converge state.`, 'warn');
4724
5204
  }
4725
- bot.manager.stopBroadcasting();
5205
+ releaseBroadcastRegion();
4726
5206
  // Chain polling: for uncertain broadcasts (not partial), try to confirm
4727
5207
  // CREATE operations on chain before clearing the working grid. If all
4728
5208
  // planned CREATEs are confirmed, the entire batch was accepted atomically
4729
5209
  // and we can commit the working grid directly, bypassing the expensive
4730
5210
  // reconciliation state machine. This handles the ~90% case where the
4731
5211
  // chain accepted the transaction but the response was lost.
4732
- if (err instanceof BroadcastUncertainError && getErrorField(err, 'partialOnChainState') !== true) {
5212
+ if (err instanceof BroadcastUncertainError && heldBroadcastSlot && getErrorField(err, 'partialOnChainState') !== true) {
4733
5213
  try {
4734
5214
  const confirmation = await pollChainForConfirmation(bot, opContexts);
4735
5215
  if (confirmation.allConfirmed) {
@@ -4827,11 +5307,25 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4827
5307
  throw err;
4828
5308
  }
4829
5309
  finally {
4830
- bot._batchInFlight--;
5310
+ if (batchInFlightRaised) {
5311
+ bot._batchInFlight = Math.max(0, bot._batchInFlight - 1);
5312
+ if (bot._batchInFlight === 0) {
5313
+ bot._batchInFlightStartedAt = 0;
5314
+ }
5315
+ }
4831
5316
  if (heldBroadcastSlot)
4832
5317
  bot._cowBroadcastInFlight = false;
4833
- bot._markGridActivity('batch end');
4834
- bot.manager.unlockOrders(idsToLock);
5318
+ releasePlacement();
5319
+ // Release the region as early as the frame contract allows: after
5320
+ // _batchInFlight-- and placement release (so region-end listeners see
5321
+ // a torn-down frame), but BEFORE the remaining best-effort cleanup.
5322
+ // A throw from _markGridActivity / unlockOrders / the fill-consumer
5323
+ // restart must not strand the refcount for the next 120s watchdog.
5324
+ releaseBroadcastRegion();
5325
+ if (batchInFlightRaised)
5326
+ bot._markGridActivity('batch end');
5327
+ if (ordersLocked)
5328
+ bot.manager.unlockOrders(idsToLock);
4835
5329
  if (!bot._shuttingDown && bot._incomingFillQueue.length > 0) {
4836
5330
  bot._scheduleFillConsumerRestart(chainOrders);
4837
5331
  }
@@ -4856,19 +5350,34 @@ async function requestStructuralResync(bot, reason, details = {}) {
4856
5350
  await bot.manager.requestStructuralGridResync(reason, details);
4857
5351
  }
4858
5352
  /**
4859
- * Adopt a batch's placed orders from the chain after the commit was refused
4860
- * or after a poll-confirmed uncertain commit. The batch ops are already on
4861
- * chain but never reached master, so a full chain sync with accounting
4862
- * enabled locks the placed orders' capital and releases any cancelled ones.
4863
- * Returns true when the adoption sync ran; false when the chain state could
4864
- * not be read (empty/lagging read, truncated read, or sync failure) — the
4865
- * caller then keeps the pending-broadcast protection and defers adoption to
4866
- * a structural resync.
4867
- * @param {import('./dexbot_class.js').DEXBot} bot
4868
- * @param {Object} chainOrders - Chain orders module
4869
- * @param {string} logPrefix - Log prefix for sync failure messages
4870
- * @returns {Promise<boolean>}
5353
+ * P1-atomic: after a refused/uncertain COW commit is recovered by adopting the
5354
+ * placed orders from the chain, re-apply the rotational boundary this batch had
5355
+ * already computed (workingBoundary) to master. The refused commit discarded
5356
+ * the working grid, so without this the next rebalance would re-derive the
5357
+ * boundary from a master that still reflects the pre-fill layout and could
5358
+ * re-stamp the just-filled slot x. Applying workingBoundary commits the
5359
+ * post-fill rotation immediately (no re-broadcast), so the next placement lands
5360
+ * at the shifted slot, never at x.
5361
+ *
5362
+ * @param {unknown} bot
5363
+ * @param {number} workingBoundary - boundary index the refused batch targeted
4871
5364
  */
5365
+ async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
5366
+ try {
5367
+ if (workingBoundary === undefined || workingBoundary === null)
5368
+ return;
5369
+ if (typeof bot.manager._restoreBoundary === 'function') {
5370
+ bot.manager._restoreBoundary(workingBoundary);
5371
+ }
5372
+ else {
5373
+ bot.manager.boundaryIdx = workingBoundary;
5374
+ }
5375
+ bot.manager.logger.log(`[COW] Restored rotational boundary ${workingBoundary} after refused/uncertain commit + chain adoption (atomic re-plan)`, 'info');
5376
+ }
5377
+ catch (e) {
5378
+ bot.manager.logger.log(`[COW] Post-adoption boundary restore failed: ${getErrorMessage(e)}`, 'warn');
5379
+ }
5380
+ }
4872
5381
  /**
4873
5382
  * Converge master with the chain after a COW commit was refused (master moved
4874
5383
  * during broadcast) or an uncertain broadcast was poll-confirmed.
@@ -4898,35 +5407,6 @@ async function requestStructuralResync(bot, reason, details = {}) {
4898
5407
  * retry instead of the unguarded window fallback
4899
5408
  * @returns {Promise<boolean>} true if master was adopted from the chain
4900
5409
  */
4901
- /**
4902
- * P1-atomic: after a refused/uncertain COW commit is recovered by adopting the
4903
- * placed orders from the chain, re-apply the rotational boundary this batch had
4904
- * already computed (workingBoundary) to master. The refused commit discarded
4905
- * the working grid, so without this the next rebalance would re-derive the
4906
- * boundary from a master that still reflects the pre-fill layout and could
4907
- * re-stamp the just-filled slot x. Applying workingBoundary commits the
4908
- * post-fill rotation immediately (no re-broadcast), so the next placement lands
4909
- * at the shifted slot, never at x.
4910
- *
4911
- * @param {unknown} bot
4912
- * @param {number} workingBoundary - boundary index the refused batch targeted
4913
- */
4914
- async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
4915
- try {
4916
- if (workingBoundary === undefined || workingBoundary === null)
4917
- return;
4918
- if (typeof bot.manager._restoreBoundary === 'function') {
4919
- bot.manager._restoreBoundary(workingBoundary);
4920
- }
4921
- else {
4922
- bot.manager.boundaryIdx = workingBoundary;
4923
- }
4924
- bot.manager.logger.log(`[COW] Restored rotational boundary ${workingBoundary} after refused/uncertain commit + chain adoption (atomic re-plan)`, 'info');
4925
- }
4926
- catch (e) {
4927
- bot.manager.logger.log(`[COW] Post-adoption boundary restore failed: ${getErrorMessage(e)}`, 'warn');
4928
- }
4929
- }
4930
5410
  async function adoptPlacedBatchFromChain(bot, chainOrders, logPrefix, opts = {}) {
4931
5411
  const { placedResults = null, placedContexts = null, polledCreateIds = null } = opts || {};
4932
5412
  try {
@@ -5527,6 +6007,26 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
5527
6007
  stats.bypassed = (Number(stats.bypassed) || 0) + 1;
5528
6008
  continue;
5529
6009
  }
6010
+ // FORCED-RETREAT ALLOWANCE (mirrors the build loop): when the
6011
+ // live rails cannot host the gap band at ANY boundary, the
6012
+ // boundary move this batch commits is forced and only an
6013
+ // evacuation can resolve the geometry — keeping the op is the
6014
+ // violation-reducing choice, not a bypass of the guard's
6015
+ // intent. Without this the gate would drop exactly the
6016
+ // rotation the retreat needs and strand the order in the band.
6017
+ const gateConflict = forcedRetreatJustifiesEvacuation(bot.manager, bot.manager?._gapSlots, evacSrcId, evacDestId);
6018
+ if (gateConflict) {
6019
+ if (stats)
6020
+ stats.bypassed = (Number(stats.bypassed) || 0) + 1;
6021
+ try {
6022
+ bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate keeping gap-evacuation ${ctx.kind} ${slotId ?? 'unknown'} ` +
6023
+ `despite live boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}: the live rails ` +
6024
+ `already conflict (maxBuy=${gateConflict.maxBuyIdx} > minSell-gap-1=${gateConflict.upper}), so the ` +
6025
+ `retreat is forced`, 'warn');
6026
+ }
6027
+ catch { /* logging is best-effort */ }
6028
+ continue;
6029
+ }
5530
6030
  // Geometry went stale after op-building (e.g. a boundary
5531
6031
  // commit landed mid-batch). Dropping is the only fail-closed
5532
6032
  // option: the normal guard below only checks the fill price,