dexbot 1.7.1 → 1.7.3

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 (66) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +7 -0
  11. package/dist/modules/account_bots.js +7 -5
  12. package/dist/modules/bot_defaults.js +6 -1
  13. package/dist/modules/constants.d.ts +14 -0
  14. package/dist/modules/constants.js +82 -2
  15. package/dist/modules/dexbot_class.d.ts +39 -0
  16. package/dist/modules/dexbot_class.js +86 -1
  17. package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_cow_runtime.js +299 -75
  19. package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
  20. package/dist/modules/dexbot_maintenance_runtime.js +196 -16
  21. package/dist/modules/dexbot_state_recovery.js +15 -1
  22. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  23. package/dist/modules/launcher/instance_lock.js +131 -0
  24. package/dist/modules/node_flap_score.d.ts +6 -6
  25. package/dist/modules/node_flap_score.js +6 -6
  26. package/dist/modules/order/accounting.d.ts +9 -4
  27. package/dist/modules/order/accounting.js +89 -26
  28. package/dist/modules/order/async_lock.d.ts +7 -1
  29. package/dist/modules/order/async_lock.js +7 -1
  30. package/dist/modules/order/export.js +25 -18
  31. package/dist/modules/order/fill_ledger.d.ts +99 -0
  32. package/dist/modules/order/fill_ledger.js +103 -0
  33. package/dist/modules/order/grid.d.ts +94 -18
  34. package/dist/modules/order/grid.js +247 -75
  35. package/dist/modules/order/grid_reconcile_internal.js +16 -4
  36. package/dist/modules/order/index.d.ts +29 -6
  37. package/dist/modules/order/index.js +5 -5
  38. package/dist/modules/order/lifecycle.js +3 -3
  39. package/dist/modules/order/manager.d.ts +36 -24
  40. package/dist/modules/order/manager.js +159 -39
  41. package/dist/modules/order/placement_lock.d.ts +30 -0
  42. package/dist/modules/order/placement_lock.js +48 -0
  43. package/dist/modules/order/sync_engine.d.ts +66 -118
  44. package/dist/modules/order/sync_engine.js +118 -162
  45. package/dist/modules/order/utils/math.d.ts +7 -3
  46. package/dist/modules/order/utils/math.js +7 -3
  47. package/dist/modules/order/utils/order.d.ts +79 -42
  48. package/dist/modules/order/utils/order.js +183 -86
  49. package/dist/modules/order/utils/system.d.ts +192 -8
  50. package/dist/modules/order/utils/system.js +534 -34
  51. package/dist/modules/paths.d.ts +1 -0
  52. package/dist/modules/paths.js +1 -0
  53. package/dist/modules/timing_policy.js +4 -2
  54. package/dist/modules/types.d.ts +49 -27
  55. package/dist/pm2.js +126 -0
  56. package/dist/unlock.js +26 -1
  57. package/docs/COW_INVARIANTS.md +5 -1
  58. package/docs/DEXBOT_COMPARISON.md +5 -5
  59. package/docs/EVOLUTION.md +10 -8
  60. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  61. package/docs/GRID_RECONCILE.md +3 -3
  62. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
  63. package/docs/README.md +1 -1
  64. package/docs/architecture.md +26 -8
  65. package/modules/README.md +4 -0
  66. package/package.json +4 -3
@@ -14,13 +14,15 @@ import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dex
14
14
  const BroadcastUncertainError = BroadcastUncertainErrorBinding;
15
15
  import * as orderUtils from './order/utils/order.js';
16
16
  import { lazyShim } from './lazy_shim.js';
17
- import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference, resolveSpreadCrossingFloor, isLastFillGuardBlocked } from './order/utils/system.js';
18
- const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
17
+ import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference, resolveSpreadCrossingFloor, isLastFillGuardBlocked, evaluateLastFillGuard } from './order/utils/system.js';
18
+ const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, describeMarketCrossingActions, collectKnownOnChainOrderIds, } = orderUtils;
19
19
  import * as validate from './order/utils/validate.js';
20
20
  const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
21
21
  import * as math from './order/utils/math.js';
22
22
  const { validateOrderSize, findCrossedOrder, sameGridLevel, isEvacuationRotationAllowed, isEvacuationSizeStillValid, getSellStartIdx, getPrecisionByOrderType, isSlotIndexInGapBand, getAssetFeesSafe, blockchainToFloat, floatToBlockchainInt, quantizeFloat } = math;
23
23
  import { parseSlotIndex } from './order/utils/slot.js';
24
+ import { resolveTradedSide } from './order/fill_ledger.js';
25
+ import { takePlanLease } from './order/placement_lock.js';
24
26
  /**
25
27
  * Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
26
28
  * geometry (boundaryIdx/_gapSlots at execution time). The stamp freezes
@@ -236,6 +238,12 @@ import { unknownCowOutcome } from './outcome.js';
236
238
  * never heals on a quiet market.
237
239
  */
238
240
  const scheduleGapEvacRepair = lazyShim('./dexbot_state_recovery', 'scheduleGapEvacRepair');
241
+ /**
242
+ * Post-repair re-plan (lazy, same reason as the sweep above). A targeted repair
243
+ * virtualises the dead slot but cannot complete the rotation that slot's batch
244
+ * was carrying, so the grid needs one fresh plan to re-place the rail.
245
+ */
246
+ const schedulePostRecoveryRebalance = lazyShim('./dexbot_state_recovery', 'schedulePostRecoveryRebalance');
239
247
  // Maximum number of times the pre-broadcast staleness guard may re-plan the
240
248
  // batch from a fresh master before proceeding anyway. Bounded so a master
241
249
  // grid that keeps mutating (fill bursts, sync loops) can never livelock the
@@ -1104,7 +1112,7 @@ async function resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, a
1104
1112
  * @param {import('./dexbot_class.js').DEXBot} bot
1105
1113
  * @param {BroadcastUncertainError} err
1106
1114
  * @param {Array<Object>} opContexts
1107
- * @param {Object} options
1115
+ * @param {Object} _options - Reserved; the implementation takes no options yet.
1108
1116
  * @returns {Promise<Object>}
1109
1117
  */
1110
1118
  async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _options) {
@@ -1184,7 +1192,7 @@ async function reconcileAfterUncertainBroadcastImpl(bot, err, opContexts, _optio
1184
1192
  }
1185
1193
  /**
1186
1194
  * Check whether to execute creates in outside-in pair mode.
1187
- * @param {import('./dexbot_class.js').DEXBot} bot
1195
+ * @param {unknown} _bot - Unused; the decision depends only on opContexts.
1188
1196
  * @param {Array} opContexts
1189
1197
  * @returns {boolean}
1190
1198
  */
@@ -1499,6 +1507,15 @@ async function executeChunkedWithRetryOnUncertain(bot, operations, opContexts) {
1499
1507
  // mode already stops at the first failed group; the chunked wrapper
1500
1508
  // should match — continuing would only burn rejected broadcasts.
1501
1509
  abortedChunkCount = chunks.length - idx - 1;
1510
+ if (bot._metrics && abortedChunkCount > 0) {
1511
+ // Planned operations thrown away by this abort (the remaining
1512
+ // chunks are never sent). The plan's work is lost; the metric
1513
+ // makes the cost of a single stale target visible.
1514
+ let abortedOps = 0;
1515
+ for (let k = idx + 1; k < chunks.length; k++)
1516
+ abortedOps += chunks[k].operations.length;
1517
+ bot._metrics.chunkAbortedOpCount = (bot._metrics.chunkAbortedOpCount || 0) + abortedOps;
1518
+ }
1502
1519
  bot.manager.logger.log(`[COW] Chunk ${idx + 1}/${chunks.length} broadcast failed definitively (${getErrorMessage(err)}); ` +
1503
1520
  `aborting the remaining ${abortedChunkCount} chunk(s) — the rejected chunk landed nothing.`, 'error');
1504
1521
  break;
@@ -1699,7 +1716,7 @@ function validateOperationFunds(bot, operations, assetA, assetB) {
1699
1716
  }
1700
1717
  /**
1701
1718
  * Resolve the ideal size from an order-like object with fallback.
1702
- * @param {import('./dexbot_class.js').DEXBot} bot
1719
+ * @param {unknown} _bot - Unused; the size comes from orderLike only.
1703
1720
  * @param {Object|null} orderLike
1704
1721
  * @param {number|null} [fallbackSize=null]
1705
1722
  * @returns {number|null}
@@ -2121,11 +2138,14 @@ function refreshLastFillPivotFromQueue(bot) {
2121
2138
  const recvAmt = Number(receives.amount);
2122
2139
  if (Number.isFinite(paysAmt) && paysAmt > 0 && Number.isFinite(recvAmt) && recvAmt > 0) {
2123
2140
  const paysFloat = (base, precision) => base / Math.pow(10, precision);
2124
- if (paysId === assets.assetA.id) {
2141
+ // Side from the paid asset through the shared resolver
2142
+ // (order/fill_ledger.ts); the price math stays here.
2143
+ const paysSide = resolveTradedSide(paysId, assets);
2144
+ if (paysSide === ORDER_TYPES.SELL) {
2125
2145
  type = ORDER_TYPES.SELL;
2126
2146
  price = paysFloat(recvAmt, assets.assetB.precision) / paysFloat(paysAmt, assets.assetA.precision);
2127
2147
  }
2128
- else if (paysId === assets.assetB.id) {
2148
+ else if (paysSide === ORDER_TYPES.BUY) {
2129
2149
  type = ORDER_TYPES.BUY;
2130
2150
  price = paysFloat(paysAmt, assets.assetB.precision) / paysFloat(recvAmt, assets.assetA.precision);
2131
2151
  }
@@ -2195,7 +2215,8 @@ function resolveLastFillGuardIncrement(bot) {
2195
2215
  }
2196
2216
  /**
2197
2217
  * Build COW actions array from a simple plan object.
2198
- * @param {import('./dexbot_class.js').DEXBot} bot
2218
+ * @param {import('./dexbot_class.js').DEXBot} _bot - Bot whose manager supplies the frozen
2219
+ * boundary/gap geometry the plan stamp carries (plan values win when set).
2199
2220
  * @param {Object|Array} plan
2200
2221
  * @returns {Array}
2201
2222
  */
@@ -2390,10 +2411,28 @@ function buildCowResultFromPlan(bot, plan) {
2390
2411
  });
2391
2412
  }
2392
2413
  else if (action.type === COW_ACTIONS.UPDATE) {
2414
+ // A ROTATION is TWO effects in one op: the SOURCE becomes a hole at
2415
+ // ITS OWN ladder level and the DESTINATION takes the order at the
2416
+ // destination level. The source is not part of the UPDATE payload —
2417
+ // falling through to the in-place branch below copied `action.order`
2418
+ // (the DESTINATION's price and size) onto the vacated slot, so two
2419
+ // slots ended up on one level. Live: 6 duplicated levels in a
2420
+ // persisted grid, a non-monotonic ladder, a shifted boundary index
2421
+ // and ~32k of double-reserved virtual intent. Apply and leave; the
2422
+ // in-place branch is for a partial-fill size update (same slot).
2393
2423
  if (action.newGridId && action.newGridId !== action.id) {
2394
2424
  const current = workingGrid.get(action.id);
2395
2425
  if (current) {
2396
- workingGrid.set(action.id, toWorkingHole(current));
2426
+ // GRID-PRICE-INVARIANT at the writer: a hole keeps the
2427
+ // level of the slot it vacated. Asserted (not assumed) so a
2428
+ // future placeholder change cannot re-open the class — the
2429
+ // emission-site checks never see this slot because no op
2430
+ // targets it.
2431
+ const sourceLevel = Number(current.price);
2432
+ const hole = toWorkingHole(current);
2433
+ workingGrid.set(action.id, Number.isFinite(sourceLevel) && sourceLevel > 0
2434
+ ? { ...hole, price: sourceLevel }
2435
+ : hole);
2397
2436
  }
2398
2437
  const targetId = action.newGridId;
2399
2438
  const targetCurrent = workingGrid.get(targetId) || { id: targetId };
@@ -2412,6 +2451,7 @@ function buildCowResultFromPlan(bot, plan) {
2412
2451
  state: ORDER_STATES.VIRTUAL,
2413
2452
  orderId: null,
2414
2453
  });
2454
+ continue;
2415
2455
  }
2416
2456
  const current = workingGrid.get(action.id);
2417
2457
  if (!current)
@@ -3137,13 +3177,52 @@ async function replanStaleBatch(bot, cowResult, replanDepth, preBroadcastGuard,
3137
3177
  result: { executed: false, aborted: true, reason: 'STRUCTURAL_REBUILD_DEFERRED', hadRotation: false }
3138
3178
  };
3139
3179
  }
3140
- const canReplan = replanDepth < STALE_PLAN_REPLAN_LIMIT
3141
- && Array.isArray(cowResult.fills) && cowResult.fills.length > 0;
3180
+ const hasFillContext = Array.isArray(cowResult.fills) && cowResult.fills.length > 0;
3181
+ const canReplan = replanDepth < STALE_PLAN_REPLAN_LIMIT && hasFillContext;
3142
3182
  if (!canReplan) {
3183
+ if (!hasFillContext) {
3184
+ // NO FILL CONTEXT → DROP, DON'T SHIP. The master mutated while this
3185
+ // batch was being planned (dominant cause: a snapshot `grid-load`,
3186
+ // also surplus cancels / handle-fill batches) and there is no fill
3187
+ // set to re-plan from. The bounded "proceed anyway" policy exists
3188
+ // because an abort would drop a fill set — that rationale does not
3189
+ // apply here. Shipping it broadcast UPDATE/CREATE ops computed from
3190
+ // the pre-mutation slot/orderId map: observed as missing UPDATE
3191
+ // targets (repair), duplicate creates at the same level, refused
3192
+ // commits, fund drift → snapshot reject → another reload.
3193
+ // Dropping is level-triggered: `_deferredRebalanceAt` makes the
3194
+ // region-end hook (placement release below) schedule the no-fill
3195
+ // rebalance that re-derives from the fresh master.
3196
+ if (bot._metrics) {
3197
+ bot._metrics.stalePlanDroppedCount = (bot._metrics.stalePlanDroppedCount || 0) + 1;
3198
+ }
3199
+ bot.manager.logger.log(`[COW] Plan stale pre-broadcast (${preBroadcastGuard.reason}); no fill context to re-plan ` +
3200
+ `— dropping the batch instead of broadcasting stale slot state`, 'warn');
3201
+ popPushedWorkingGrid(bot, cowResult);
3202
+ clearPendingBroadcastsForSlots(bot, cowResult.actions);
3203
+ if (bot.manager && typeof bot.manager === 'object') {
3204
+ bot.manager._deferredRebalanceAt = Date.now();
3205
+ }
3206
+ return {
3207
+ handled: true,
3208
+ result: {
3209
+ executed: false,
3210
+ aborted: true,
3211
+ deferred: true,
3212
+ droppedStalePlan: true,
3213
+ reason: 'STALE_PLAN_NO_FILL_CONTEXT',
3214
+ hadRotation: false
3215
+ }
3216
+ };
3217
+ }
3218
+ // Fill batch that is still stale at the re-plan limit: keep the
3219
+ // documented bounded policy (proceed + resync) — the fill set is real
3220
+ // and the post-broadcast commit guard + chain adoption close divergence.
3221
+ if (bot._metrics) {
3222
+ bot._metrics.stalePlanProceedCount = (bot._metrics.stalePlanProceedCount || 0) + 1;
3223
+ }
3143
3224
  bot.manager.logger.log(`[COW] Plan stale pre-broadcast (${preBroadcastGuard.reason}); ` +
3144
- (replanDepth >= STALE_PLAN_REPLAN_LIMIT
3145
- ? 'still stale after re-plan — proceeding with plan (commit guard + chain adoption close divergence)'
3146
- : 'no fill context for re-plan — proceeding with plan (commit guard + chain adoption close divergence)'), 'warn');
3225
+ 'still stale after re-plan — proceeding with plan (commit guard + chain adoption close divergence)', 'warn');
3147
3226
  await requestStructuralResync(bot, 'plan stale pre-broadcast (proceeding with plan)', { reason: preBroadcastGuard.reason });
3148
3227
  return { handled: false };
3149
3228
  }
@@ -3290,13 +3369,6 @@ async function waitForCowBroadcastSingleFlight(bot, label) {
3290
3369
  }
3291
3370
  return false;
3292
3371
  }
3293
- /**
3294
- * COW broadcast: Execute blockchain operations and commit working grid on success.
3295
- * @param {import('./dexbot_class.js').DEXBot} bot
3296
- * @param {Object} cowResult
3297
- * @param {Object} [options={}] - Internal execution options (replanDepth)
3298
- * @returns {Promise<Object>}
3299
- */
3300
3372
  /**
3301
3373
  * Derive an update action's planned target size (shared by the rotation and
3302
3374
  * plain size-update op builders).
@@ -3627,8 +3699,69 @@ async function runPreBroadcastGuards(bot, cowResult) {
3627
3699
  if (missing.length > 0) {
3628
3700
  bot.manager.logger.log(`[COW] Rejecting UPDATE batch pre-broadcast: ${missing.length} target(s) missing on chain ` +
3629
3701
  `(${missing.slice(0, 8).join(', ')}${missing.length > 8 ? ', …' : ''}); ` +
3630
- `grid/chain existence divergence — structural resync required`, 'error');
3702
+ `grid/chain existence divergence`, 'error');
3631
3703
  popPushedWorkingGrid(bot, cowResult);
3704
+ // REPAIR THE SLOT, NOT THE WHOLE GRID. Both reads above agreed
3705
+ // these ids are absent, so each one is a slot whose chain order
3706
+ // is gone (a missed fill or a phantom left by an earlier
3707
+ // reload). The old response — a structural resync, which
3708
+ // reloads the on-disk snapshot — could only re-read the same
3709
+ // stale slot from disk and plan the same UPDATE again: the
3710
+ // refused batch re-armed itself forever, and while that slot
3711
+ // sat "placed" inside the gap band every boundary slide
3712
+ // (hence every sell-side promotion) stayed refused, so the
3713
+ // spread never closed. `_targetedOrderRepair` is the existing
3714
+ // single-slot repair (chain read -> placeholder when absent),
3715
+ // already used by the size-drift path; it releases the dead
3716
+ // commitment and leaves the level as a plain hole.
3717
+ let repaired = false;
3718
+ if (typeof bot._targetedOrderRepair === 'function') {
3719
+ try {
3720
+ repaired = (await bot._targetedOrderRepair(missing)) === true;
3721
+ }
3722
+ catch (repairErr) {
3723
+ bot.manager.logger.log(`[COW] Targeted repair of missing UPDATE target(s) failed (${getErrorMessage(repairErr)}); ` +
3724
+ `falling back to structural resync`, 'warn');
3725
+ repaired = false;
3726
+ }
3727
+ }
3728
+ if (repaired) {
3729
+ // A repair that leaves an id tracked did nothing (e.g. the
3730
+ // id belongs to no grid slot): that must escalate, not
3731
+ // silently drop a batch per cycle.
3732
+ const stillTracked = new Set();
3733
+ for (const order of bot.manager.orders.values()) {
3734
+ const trackedId = order?.orderId ? String(order.orderId) : '';
3735
+ if (trackedId && missing.includes(trackedId))
3736
+ stillTracked.add(trackedId);
3737
+ }
3738
+ if (stillTracked.size > 0) {
3739
+ bot.manager.logger.log(`[COW] Targeted repair left ${stillTracked.size} missing target(s) tracked ` +
3740
+ `(${[...stillTracked].slice(0, 8).join(', ')}); falling back to structural resync`, 'warn');
3741
+ repaired = false;
3742
+ }
3743
+ }
3744
+ if (repaired) {
3745
+ bot.manager.logger.log(`[COW] Repaired ${missing.length} missing UPDATE target(s) locally ` +
3746
+ `(${missing.slice(0, 8).join(', ')}${missing.length > 8 ? ', …' : ''}); ` +
3747
+ `batch dropped and a fresh plan scheduled — no snapshot reload`, 'warn');
3748
+ schedulePostRecoveryRebalance(bot, `missing update target repair (${missing.join(', ')})`);
3749
+ return {
3750
+ proceed: false,
3751
+ result: {
3752
+ executed: false,
3753
+ aborted: true,
3754
+ // Reason stays UPDATE_TARGET_MISSING so every
3755
+ // existing classifier/metric keeps its meaning;
3756
+ // `repairedMissingTargets` tells the re-plan path
3757
+ // that the grid was repaired rather than reloaded.
3758
+ reason: 'UPDATE_TARGET_MISSING',
3759
+ missingUpdateOrderIds: missing,
3760
+ repairedMissingTargets: true,
3761
+ hadRotation: false
3762
+ }
3763
+ };
3764
+ }
3632
3765
  await requestStructuralResync(bot, 'pre-broadcast update target missing on chain', { missingUpdateOrderIds: missing });
3633
3766
  return {
3634
3767
  proceed: false,
@@ -3708,6 +3841,25 @@ async function runPreBroadcastGuards(bot, cowResult) {
3708
3841
  }
3709
3842
  };
3710
3843
  }
3844
+ // MARKET-CROSSING OBSERVATION (retrospective §9.10/P4): actions priced on
3845
+ // the wrong side of the market floor are REPORTED, never dropped. A hard
3846
+ // veto here re-opens the counter-order deadlock P4 rejected — after a gap
3847
+ // the counter sits across the floor by construction, and the live cost of
3848
+ // the veto was a batch refused at identical prices that the next tick
3849
+ // accepted once the reference moved (86 minutes out of spread). The
3850
+ // crossed-book gate above still protects the batch internally (buy >= our
3851
+ // own sell), and the market prices a genuinely crossing op as a taker fill.
3852
+ try {
3853
+ const { floor, dropped } = describeMarketCrossingActions(bot.manager, actions);
3854
+ if (dropped.length > 0) {
3855
+ bot.manager.logger.log(`[COW-CROSS-GUARD] ${dropped.length}/${actions.length} action(s) priced across the market floor `
3856
+ + `${floor != null ? Format.formatPrice6(floor) : 'n/a'} `
3857
+ + `(${dropped.map((d) => d.reason).slice(0, 4).join('; ')}`
3858
+ + `${dropped.length > 4 ? '; …' : ''}) — observation only, batch broadcast unchanged `
3859
+ + `(a hard veto re-opens the counter-order deadlock; retrospective §9.10/P4)`, 'warn');
3860
+ }
3861
+ }
3862
+ catch { /* the observation must never break a batch */ }
3711
3863
  return { proceed: true, crossingCandidates, intraBatchCandidates };
3712
3864
  }
3713
3865
  function restoreTestPollIntervalSeam(bot, prev) {
@@ -3728,6 +3880,7 @@ async function updateOrdersOnChainBatchCOW(bot, cowResult, options = {}) {
3728
3880
  // branch and any re-plan recursion pick it up without changing the
3729
3881
  // production call signature used by the runtime.
3730
3882
  const seamPollIntervalMs = resolveSeamMsOrNull(options?.pollIntervalMs);
3883
+ let resultPlanLease = null;
3731
3884
  const prevSeamPollIntervalMs = bot?._testPollIntervalMs;
3732
3885
  if (seamPollIntervalMs != null) {
3733
3886
  bot._testPollIntervalMs = seamPollIntervalMs;
@@ -3744,9 +3897,18 @@ async function updateOrdersOnChainBatchCOW(bot, cowResult, options = {}) {
3744
3897
  // recursion, throws) funnels through the body() finally below, so no exit
3745
3898
  // can leak bot._testPollIntervalMs onto the bot.
3746
3899
  try {
3747
- return await updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs ?? undefined, options?.placementLease ?? null);
3900
+ // Plan region carried by the result (manager.performSafeRebalance
3901
+ // acquires it before planning). Direct callers of this function (tests,
3902
+ // the re-plan shim) may hand it over here instead of as an option.
3903
+ resultPlanLease = takePlanLease(cowResult);
3904
+ return await updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seamPollIntervalMs ?? undefined, resultPlanLease ?? options?.placementLease ?? null);
3748
3905
  }
3749
3906
  finally {
3907
+ // Idempotent safety release: the body releases the inherited lease on
3908
+ // every one of its own exits; this covers a throw before the body's
3909
+ // try/finally takes ownership, so a direct caller cannot strand the
3910
+ // region on the result path.
3911
+ resultPlanLease?.release();
3750
3912
  // Restore only when this frame actually wrote a seam. The entry
3751
3913
  // single-flight await (inside body()) lets a second, seam-less batch
3752
3914
  // run concurrently: an unguarded restore would delete the seam owned
@@ -3856,6 +4018,27 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3856
4018
  let heldBroadcastSlot = false;
3857
4019
  let batchInFlightRaised = false;
3858
4020
  let ordersLocked = false;
4021
+ // Broadcast-region ownership for THIS frame. startBroadcasting() runs
4022
+ // before the action loop (fills must stay deferred while ops are built),
4023
+ // but the inner broadcast try/finally only covers the broadcast section.
4024
+ // Every early return in between — all CREATEs skipped by the last-fill /
4025
+ // crossing / size guards (operations.length === 0), fund-validation
4026
+ // refusal, stale-plan re-plan, single-flight/placement aborts — used to
4027
+ // return with the refcount still held. The leaked flag then froze the
4028
+ // fill consumer until the 120s stale-flag watchdog (2026-11-04 incident:
4029
+ // three such returns parked 26 fills, the backlog was replayed against a
4030
+ // stale boundary and the bot sold below levels it had already sold).
4031
+ // One flag + one releaser: the inner finally, the catch and the outer
4032
+ // finally all call it, and only the first call decrements — a second raw
4033
+ // stopBroadcasting() in the outer finally would underflow another
4034
+ // holder's region (grid reconcile / spread correction).
4035
+ let broadcastRegionHeld = false;
4036
+ const releaseBroadcastRegion = () => {
4037
+ if (!broadcastRegionHeld)
4038
+ return;
4039
+ broadcastRegionHeld = false;
4040
+ bot.manager.stopBroadcasting();
4041
+ };
3859
4042
  try {
3860
4043
  // Single-flight COW broadcast guard (entry check): never broadcast two
3861
4044
  // batches concurrently. Overlapping broadcasts plan from the same base
@@ -4003,6 +4186,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4003
4186
  bot._markGridActivity('batch start');
4004
4187
  bot.manager._setRebalanceState(REBALANCE_STATES.BROADCASTING);
4005
4188
  bot.manager.startBroadcasting();
4189
+ broadcastRegionHeld = true;
4006
4190
  // P3 — freeze the guard pivot once per batch: per-action refreshes
4007
4191
  // mutated the pivot mid-batch (02:03 pivots drifted 0.001523→0.001529
4008
4192
  // across 20 checks), so early actions were judged against a different
@@ -4138,8 +4322,9 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4138
4322
  lastFillGuardPivotRefreshed = true;
4139
4323
  if (check.blocked) {
4140
4324
  lastFillGuardStats.skipped++;
4141
- const dir = order.type === ORDER_TYPES.BUY ? 'above' : 'below';
4142
- bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'debug');
4325
+ bot.manager.logger.log(check.refusedLevel
4326
+ ? `[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: same-level re-fill of the just-filled level ${Format.formatPrice6(Number(check.pivot))} (its pivot-arm was refused; the level stays blocked for the marker TTL, §9.12/P2 amended); re-planned after market moves`
4327
+ : `[LAST-FILL-GUARD] Skipping ${order.type} CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ${order.type === ORDER_TYPES.BUY ? 'above' : 'below'} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'debug');
4143
4328
  if (order.id)
4144
4329
  skippedCreateSlotIds.add(order.id);
4145
4330
  continue;
@@ -4483,8 +4668,9 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4483
4668
  skippedUpdateSlotIds.add(action.id);
4484
4669
  if (action.newGridId)
4485
4670
  skippedUpdateSlotIds.add(action.newGridId);
4486
- const dir = orderType === ORDER_TYPES.BUY ? 'above' : 'below';
4487
- bot.manager.logger.log(`[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${dir} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill)`, 'debug');
4671
+ bot.manager.logger.log(check.refusedLevel
4672
+ ? `[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: same-level re-fill of the just-filled level ${Format.formatPrice6(Number(check.pivot))} (its pivot-arm was refused; the level stays blocked for the marker TTL, §9.12/P2 amended)`
4673
+ : `[LAST-FILL-GUARD] Skipping ${orderType} UPDATE for ${action.id} -> ${action.newGridId} at ${Format.formatPrice6(newPrice)}: ${orderType === ORDER_TYPES.BUY ? 'above' : 'below'} last filled ${Format.formatPrice6(Number(check.pivot))} (direction rule: BUY must be below / SELL above the last fill)`, 'debug');
4488
4674
  continue;
4489
4675
  }
4490
4676
  lastFillGuardStats.passed++;
@@ -4536,7 +4722,29 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4536
4722
  const plannedNewSize = plannedUpdateSize(action);
4537
4723
  const newSize = clampPostFillUpdateSize(bot, masterOrder, plannedNewSize, action);
4538
4724
  if (newSize !== plannedNewSize) {
4725
+ // The clamp only fires when the plan wanted to GROW a
4726
+ // PARTIAL slot; the target is the booked remainder,
4727
+ // i.e. the size already on chain. Building the op would
4728
+ // re-read the order from chain and return null (observed:
4729
+ // 1 136/1 137 "no blockchain delta" skips were this
4730
+ // clamp), so skip it here like the rotation path does
4731
+ // (see the POST-FILL GROWTH GUARD above) — same rule, one
4732
+ // predicate, no wasted chain read. The slot still joins
4733
+ // clampedUpdateSlotIds so the commit re-syncs it from
4734
+ // master (the working grid holds the refused larger size).
4539
4735
  clampedUpdateSlotIds.add(action.id);
4736
+ skippedUpdateCount++;
4737
+ if (action.id)
4738
+ skippedUpdateSlotIds.add(action.id);
4739
+ if (action.newGridId)
4740
+ skippedUpdateSlotIds.add(action.newGridId);
4741
+ if (bot._metrics) {
4742
+ bot._metrics.clampedNoopUpdateCount = (bot._metrics.clampedNoopUpdateCount || 0) + 1;
4743
+ }
4744
+ bot.manager.logger.log(`[COW] Skipping size update ${action.id} (${action.orderId}): ` +
4745
+ `PARTIAL slot at its booked remaining ${Format.formatAmount(newSize)} — ` +
4746
+ `growth in place refused, no chain change`, 'debug');
4747
+ continue;
4540
4748
  }
4541
4749
  const orderType = action.order?.type || masterOrder?.type;
4542
4750
  const cachedRawOnChain = masterOrder?.rawOnChain || action.order?.rawOnChain || null;
@@ -5171,7 +5379,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
5171
5379
  finally {
5172
5380
  bot.manager._throwOnIllegalState = false;
5173
5381
  await bot.manager.resumeFundRecalc();
5174
- bot.manager.stopBroadcasting();
5382
+ releaseBroadcastRegion();
5175
5383
  const createCount = actions.filter((a) => a.type === COW_ACTIONS.CREATE).length;
5176
5384
  const cancelCount = actions.filter((a) => a.type === COW_ACTIONS.CANCEL).length;
5177
5385
  bot.manager.logger.logFundsStatus(bot.manager, `AFTER COW batch (created=${createCount}, cancelled=${cancelCount})`);
@@ -5182,7 +5390,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
5182
5390
  if (getErrorField(err, 'partialOnChainState')) {
5183
5391
  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');
5184
5392
  }
5185
- bot.manager.stopBroadcasting();
5393
+ releaseBroadcastRegion();
5186
5394
  // Chain polling: for uncertain broadcasts (not partial), try to confirm
5187
5395
  // CREATE operations on chain before clearing the working grid. If all
5188
5396
  // planned CREATEs are confirmed, the entire batch was accepted atomically
@@ -5296,6 +5504,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
5296
5504
  if (heldBroadcastSlot)
5297
5505
  bot._cowBroadcastInFlight = false;
5298
5506
  releasePlacement();
5507
+ // Release the region as early as the frame contract allows: after
5508
+ // _batchInFlight-- and placement release (so region-end listeners see
5509
+ // a torn-down frame), but BEFORE the remaining best-effort cleanup.
5510
+ // A throw from _markGridActivity / unlockOrders / the fill-consumer
5511
+ // restart must not strand the refcount for the next 120s watchdog.
5512
+ releaseBroadcastRegion();
5299
5513
  if (batchInFlightRaised)
5300
5514
  bot._markGridActivity('batch end');
5301
5515
  if (ordersLocked)
@@ -5324,19 +5538,34 @@ async function requestStructuralResync(bot, reason, details = {}) {
5324
5538
  await bot.manager.requestStructuralGridResync(reason, details);
5325
5539
  }
5326
5540
  /**
5327
- * Adopt a batch's placed orders from the chain after the commit was refused
5328
- * or after a poll-confirmed uncertain commit. The batch ops are already on
5329
- * chain but never reached master, so a full chain sync with accounting
5330
- * enabled locks the placed orders' capital and releases any cancelled ones.
5331
- * Returns true when the adoption sync ran; false when the chain state could
5332
- * not be read (empty/lagging read, truncated read, or sync failure) — the
5333
- * caller then keeps the pending-broadcast protection and defers adoption to
5334
- * a structural resync.
5335
- * @param {import('./dexbot_class.js').DEXBot} bot
5336
- * @param {Object} chainOrders - Chain orders module
5337
- * @param {string} logPrefix - Log prefix for sync failure messages
5338
- * @returns {Promise<boolean>}
5541
+ * P1-atomic: after a refused/uncertain COW commit is recovered by adopting the
5542
+ * placed orders from the chain, re-apply the rotational boundary this batch had
5543
+ * already computed (workingBoundary) to master. The refused commit discarded
5544
+ * the working grid, so without this the next rebalance would re-derive the
5545
+ * boundary from a master that still reflects the pre-fill layout and could
5546
+ * re-stamp the just-filled slot x. Applying workingBoundary commits the
5547
+ * post-fill rotation immediately (no re-broadcast), so the next placement lands
5548
+ * at the shifted slot, never at x.
5549
+ *
5550
+ * @param {unknown} bot
5551
+ * @param {number} workingBoundary - boundary index the refused batch targeted
5339
5552
  */
5553
+ async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
5554
+ try {
5555
+ if (workingBoundary === undefined || workingBoundary === null)
5556
+ return;
5557
+ if (typeof bot.manager._restoreBoundary === 'function') {
5558
+ bot.manager._restoreBoundary(workingBoundary);
5559
+ }
5560
+ else {
5561
+ bot.manager.boundaryIdx = workingBoundary;
5562
+ }
5563
+ bot.manager.logger.log(`[COW] Restored rotational boundary ${workingBoundary} after refused/uncertain commit + chain adoption (atomic re-plan)`, 'info');
5564
+ }
5565
+ catch (e) {
5566
+ bot.manager.logger.log(`[COW] Post-adoption boundary restore failed: ${getErrorMessage(e)}`, 'warn');
5567
+ }
5568
+ }
5340
5569
  /**
5341
5570
  * Converge master with the chain after a COW commit was refused (master moved
5342
5571
  * during broadcast) or an uncertain broadcast was poll-confirmed.
@@ -5366,35 +5595,6 @@ async function requestStructuralResync(bot, reason, details = {}) {
5366
5595
  * retry instead of the unguarded window fallback
5367
5596
  * @returns {Promise<boolean>} true if master was adopted from the chain
5368
5597
  */
5369
- /**
5370
- * P1-atomic: after a refused/uncertain COW commit is recovered by adopting the
5371
- * placed orders from the chain, re-apply the rotational boundary this batch had
5372
- * already computed (workingBoundary) to master. The refused commit discarded
5373
- * the working grid, so without this the next rebalance would re-derive the
5374
- * boundary from a master that still reflects the pre-fill layout and could
5375
- * re-stamp the just-filled slot x. Applying workingBoundary commits the
5376
- * post-fill rotation immediately (no re-broadcast), so the next placement lands
5377
- * at the shifted slot, never at x.
5378
- *
5379
- * @param {unknown} bot
5380
- * @param {number} workingBoundary - boundary index the refused batch targeted
5381
- */
5382
- async function restoreBoundaryAfterAdoption(bot, workingBoundary) {
5383
- try {
5384
- if (workingBoundary === undefined || workingBoundary === null)
5385
- return;
5386
- if (typeof bot.manager._restoreBoundary === 'function') {
5387
- bot.manager._restoreBoundary(workingBoundary);
5388
- }
5389
- else {
5390
- bot.manager.boundaryIdx = workingBoundary;
5391
- }
5392
- bot.manager.logger.log(`[COW] Restored rotational boundary ${workingBoundary} after refused/uncertain commit + chain adoption (atomic re-plan)`, 'info');
5393
- }
5394
- catch (e) {
5395
- bot.manager.logger.log(`[COW] Post-adoption boundary restore failed: ${getErrorMessage(e)}`, 'warn');
5396
- }
5397
- }
5398
5598
  async function adoptPlacedBatchFromChain(bot, chainOrders, logPrefix, opts = {}) {
5399
5599
  const { placedResults = null, placedContexts = null, polledCreateIds = null } = opts || {};
5400
5600
  try {
@@ -5758,7 +5958,18 @@ function runLastFillGuardCheck(bot, price, type, stats, skipRefresh = false) {
5758
5958
  catch { /* logging is best-effort */ }
5759
5959
  stats.pivotOffGrid = (stats.pivotOffGrid || 0) + 1;
5760
5960
  }
5761
- const check = isLastFillGuardBlocked(price, type, onGrid.price, lastType);
5961
+ const check = evaluateLastFillGuard(bot.manager, price, type, onGrid.price, lastType);
5962
+ // Geometry-territory exemption (see isLastFillBandSellExempt): a SELL that
5963
+ // closes a band the fill anchor itself derived is not a "lower sell" the
5964
+ // guard is meant to refuse — refusing it vetoes 100% of the counter-orders.
5965
+ if (check.bandExempt) {
5966
+ try {
5967
+ bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Allowing SELL ${Format.formatPrice6(price)} against pivot `
5968
+ + `${Format.formatPrice6(Number(onGrid.price))}: inside the gap band the fill anchor derives `
5969
+ + `(boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots}) — geometry is not behind the fill`, 'debug');
5970
+ }
5971
+ catch { /* logging is best-effort */ }
5972
+ }
5762
5973
  stats.checked++;
5763
5974
  return { check, refreshed };
5764
5975
  }
@@ -6041,12 +6252,20 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
6041
6252
  continue;
6042
6253
  if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
6043
6254
  continue;
6044
- const check = isLastFillGuardBlocked(price, type, onGrid.price, liveType);
6255
+ const check = evaluateLastFillGuard(bot.manager, price, type, onGrid.price, liveType);
6045
6256
  if (stats)
6046
6257
  stats.checked = (Number(stats.checked) || 0) + 1;
6047
6258
  if (!check.blocked) {
6048
6259
  if (stats)
6049
6260
  stats.passed = (Number(stats.passed) || 0) + 1;
6261
+ if (check.bandExempt) {
6262
+ try {
6263
+ bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate keeping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at `
6264
+ + `${Format.formatPrice6(price)}: inside the gap band the fill anchor derives `
6265
+ + `(boundary ${bot.manager?.boundaryIdx}/gap ${bot.manager?._gapSlots})`, 'debug');
6266
+ }
6267
+ catch { /* logging is best-effort */ }
6268
+ }
6050
6269
  continue;
6051
6270
  }
6052
6271
  // Blocked: drop the op + context, restore the slot below.
@@ -6056,9 +6275,14 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
6056
6275
  const dir = type === ORDER_TYPES.BUY ? 'above' : 'below';
6057
6276
  dropped.push({ index: i, kind: ctx.kind, slotId, price, type });
6058
6277
  try {
6059
- bot.manager?.logger?.log?.(`[LAST-FILL-GUARD] Final gate dropping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at ` +
6060
- `${Format.formatPrice6(price)}: ${dir} last filled ${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
6061
- `(direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'warn');
6278
+ bot.manager?.logger?.log?.(check.refusedLevel
6279
+ ? `[LAST-FILL-GUARD] Final gate dropping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at ` +
6280
+ `${Format.formatPrice6(price)}: same-level re-fill of the just-filled level ` +
6281
+ `${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
6282
+ `(its pivot-arm was refused; the level stays blocked for the marker TTL, §9.12/P2 amended)`
6283
+ : `[LAST-FILL-GUARD] Final gate dropping ${type} ${ctx.kind} for ${slotId ?? 'unknown'} at ` +
6284
+ `${Format.formatPrice6(price)}: ${dir} last filled ${check.pivot != null ? Format.formatPrice6(Number(check.pivot)) : 'n/a'} ` +
6285
+ `(direction rule: BUY must be below / SELL above the last fill); re-planned after market moves`, 'warn');
6062
6286
  }
6063
6287
  catch { /* logging is best-effort */ }
6064
6288
  }