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
@@ -12,7 +12,7 @@
12
12
  * - Detects and flags out-of-spread conditions
13
13
  *
14
14
  * ===============================================================================
15
- * TABLE OF CONTENTS - Grid Functions (34 exports)
15
+ * TABLE OF CONTENTS - Grid Functions (34 exports + internal helpers)
16
16
  * ===============================================================================
17
17
  *
18
18
  * CONFIGURATION & CALCULATION (2 functions)
@@ -81,6 +81,13 @@
81
81
  * 33. isGridBloatGraceActive(manager) - Check the bloat grace state
82
82
  * 34. clearGridBloatFlag(manager) - Clear the bloat state
83
83
  *
84
+ * SPREAD STALL MERGING (1 function)
85
+ * 35. mergeSpreadStalls(...) - Merge two side stalls so starvation cannot mask a cause
86
+ *
87
+ * REBUILD FILL ANCHOR (2 functions)
88
+ * 36. anchorRebuildBoundaryToLastFill(...) - Anchor a rebuilt boundary to the last fill
89
+ * 37. applyRebuildFillAnchor(...) - Apply the anchor and re-type the rails for it
90
+ *
84
91
  * ===============================================================================
85
92
  *
86
93
  * GRID STRUCTURE:
@@ -325,7 +332,8 @@ function getSpreadCorrectionActionCount(correction) {
325
332
  * `determineOrderSideByFunds` is still pure-fund-driven, so a rail with
326
333
  * exactly zero free on both sides returns null. Rotations, however, need no
327
334
  * new commitment: a fully allocated rail can still be repaired by moving a
328
- * resting order into a promoted gap slot. Try both sides and accept the first
335
+ * resting order into an unfunded tightening slot (promoted gap or orphaned
336
+ * rail slot). Try both sides and accept the first
329
337
  * executable plan (create or rotation). Callers must only use this when the
330
338
  * side decision failed for INSUFFICIENT FREE FUNDS, not for an unavailable
331
339
  * market price where cross-asset side comparison is unsafe.
@@ -420,7 +428,7 @@ function _snapshotFundState(manager) {
420
428
  import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, pricesOnSameLevel, sameGridLevel, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
421
429
  import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveEdgeCount, edgeOrderIdSet, resolveLiveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
422
430
  import { parseSlotIndex } from './utils/slot.js';
423
- import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillPlacementBlocked } from './utils/system.js';
431
+ import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot, rearmLastFillPivotFromMarketFill, reanchorBoundaryFromLastFill, evaluateSpreadCorrectionReadiness, maybeRefreshLiveMarketPrice, resolveLastFillGuardReference, isLastFillPlacementBlocked } from './utils/system.js';
424
432
  import * as MathUtils from './utils/math.js';
425
433
  import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
426
434
  import { getWhitelistFlags } from '../market_adapter_whitelist.js';
@@ -514,7 +522,7 @@ export function clearGridBloatFlag(manager) {
514
522
  * Unifies budget calculation and fee deduction for all grid sizing scenarios.
515
523
  * Ensures consistent fund context (Allocated vs Total) across the bot.
516
524
  *
517
- * @param {import('./types').OrderManager} manager - OrderManager instance
525
+ * @param {import('../types.js').OrderManagerLike} manager - OrderManager instance
518
526
  * @param {string} side - 'buy' or 'sell'
519
527
  * @returns {Promise<any|null>}
520
528
  * @private
@@ -706,7 +714,7 @@ export function createOrderGrid(config) {
706
714
  * Note: Uses explicit assignment instead of .clear() to enforce COW semantics:
707
715
  * - Replace the master grid atomically with a fresh Map instance
708
716
  * - Avoid mutating any previously referenced Map object
709
- * @param {import('./types').OrderManager} manager - OrderManager instance
717
+ * @param {import('../types.js').OrderManagerLike} manager - OrderManager instance
710
718
  * @private
711
719
  */
712
720
  function _clearOrderCachesLogic(manager) {
@@ -731,7 +739,7 @@ function _clearOrderCachesLogic(manager) {
731
739
  * the creation-time value instead of recomputing from live config
732
740
  * - Sanitizes phantom orders (ACTIVE/PARTIAL without orderId → VIRTUAL)
733
741
  *
734
- * @param {import('./types').OrderManager} manager - The manager instance.
742
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
735
743
  * @param {Array<any>} grid - The persisted grid array.
736
744
  * @param {number|null} [boundaryIdx=null] - The master boundary index.
737
745
  * @returns {Promise<void>}
@@ -908,6 +916,21 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
908
916
  }
909
917
  // RC-2: Use logic helper
910
918
  _clearOrderCachesLogic(manager);
919
+ // Restart durability: merge the pass-1 "size already applied"
920
+ // markers persisted with this snapshot (live markers win on
921
+ // conflict), so a fill replayed after a crash is not subtracted a
922
+ // second time.
923
+ try {
924
+ const restoreMarkers = manager.restoreChainSizeAppliedFills;
925
+ const acct = manager.accountOrders;
926
+ const persistedMarkers = typeof acct?.loadChainSizeAppliedFills === 'function'
927
+ ? acct.loadChainSizeAppliedFills()
928
+ : null;
929
+ if (typeof restoreMarkers === 'function' && persistedMarkers) {
930
+ restoreMarkers.call(manager, persistedMarkers);
931
+ }
932
+ }
933
+ catch { /* marker restore is best-effort; normal accounting still applies */ }
911
934
  // resetFunds under _fundLock only — no persistGrid needed (grid already
912
935
  // on disk). For the resync variant see recalculateGrid (grid.ts:~1037)
913
936
  // which snapshots fund values under lock and persists outside.
@@ -929,6 +952,14 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
929
952
  // center boundary from slot prices, falling back to "no boundary"
930
953
  // (callers sync against chain right after load either way).
931
954
  const loadGapSlots = calculateGapSlots(manager.config?.incrementPercent, manager.config?.targetSpreadPercent, manager.config?.gridLimits);
955
+ // Publish the geometry BEFORE restoring the boundary. The restore
956
+ // path (and anything it calls: last-fill pivot snapping, the
957
+ // [BOUNDARY] restore debug line) reads manager._gapSlots, and
958
+ // leaving it unset until the re-type pass below made every restart
959
+ // report `gapSlots=0 sellStart=boundary+1` — i.e. "the spread band
960
+ // is gone" on a perfectly healthy 4-slot band. Same value as the
961
+ // assignment in the re-type block, which now only reads it.
962
+ manager._gapSlots = loadGapSlots;
932
963
  let restoredBoundary = typeof boundaryIdx === 'number' ? boundaryIdx : null;
933
964
  if (restoredBoundary !== null) {
934
965
  const check = validatePersistedBoundary(restoredBoundary, grid, loadGapSlots);
@@ -989,20 +1020,14 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
989
1020
  catch { /* load continues boundary-less either way */ }
990
1021
  }
991
1022
  }
992
- // Restore boundary index for StrategyEngine
993
- if (restoredBoundary !== null) {
994
- manager._restoreBoundary(restoredBoundary);
995
- manager.logger?.log?.(`Restored boundary index: ${restoredBoundary}`, 'info');
996
- }
997
1023
  // Restart resilience: restore the persisted LAST-FILL-GUARD pivot
998
- // WITH the boundary — after the persisted genesis is applied and
999
- // the grid re-typed, before the first reconcile/broadcast — so a
1000
- // restart cannot re-open the cold window where the guard is
1001
- // disabled and evacuation stamps get applied against a boundary
1002
- // that is still being rebuilt. restoreLastFillPivot validates the
1003
- // row against the manager's live genesis (refuses on mismatch —
1004
- // a regenerated grid drops it) and onto the price ladder with the
1005
- // same one-increment drift rule the runtime guard applies.
1024
+ // from the persisted genesis (refuses on mismatch — a regenerated
1025
+ // grid drops it) onto the price ladder with the same one-increment
1026
+ // drift rule the runtime guard applies. The boundary is restored
1027
+ // AFTER the pivot because the fill anchor below needs it: the
1028
+ // persisted boundary is disk state, while the fill is the geometry
1029
+ // fact. This also closes the cold window where the guard is
1030
+ // disabled during the restart.
1006
1031
  if (restoredBoundary !== null) {
1007
1032
  try {
1008
1033
  restoreLastFillPivot(manager, manager.accountOrders?.loadLastFillPivot?.() ?? null);
@@ -1011,6 +1036,27 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1011
1036
  manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot restore failed (${getErrorMessage(pivotErr)}); book seed takes over`, 'warn');
1012
1037
  }
1013
1038
  }
1039
+ // FILL-DERIVED GEOMETRY ON LOAD: a persisted boundary is still
1040
+ // disk state. When the last real fill sits inside the implied band
1041
+ // (a rebuild centered the band on the market while the pivot fell
1042
+ // behind it), the startup picker will skip the levels at/through
1043
+ // the fill and the realized spread stays two steps wide. Re-anchor
1044
+ // the restored boundary to the fill BEFORE re-typing, using the
1045
+ // same predicate the fill cycle uses. Cold/unsafe/anchor-less
1046
+ // states keep the persisted value.
1047
+ if (restoredBoundary !== null) {
1048
+ const anchoredBoundary = anchorRebuildBoundaryToLastFill(manager, restoredBoundary, grid, loadGapSlots);
1049
+ if (anchoredBoundary !== restoredBoundary) {
1050
+ restoredBoundary = anchoredBoundary;
1051
+ }
1052
+ }
1053
+ // Restore boundary index for StrategyEngine AFTER the fill anchor:
1054
+ // the re-type pass below and every runtime consumer must see the
1055
+ // anchored value, not the persisted one the anchor just corrected.
1056
+ if (restoredBoundary !== null) {
1057
+ manager._restoreBoundary(restoredBoundary);
1058
+ manager.logger?.log?.(`Restored boundary index: ${restoredBoundary}`, 'info');
1059
+ }
1014
1060
  // Reassign slot types based on current boundary.
1015
1061
  // Every slot's type must match its price-slot index (parseSlotIndex)
1016
1062
  // relative to the boundary + gapSlots, not array position. After
@@ -1018,7 +1064,6 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1018
1064
  // slot-N is the canonical identity.
1019
1065
  if (restoredBoundary !== null) {
1020
1066
  const gapSlots = loadGapSlots;
1021
- manager._gapSlots = gapSlots;
1022
1067
  const buyEndIdx = restoredBoundary;
1023
1068
  const sellStartIdx = getSellStartIdx(restoredBoundary, gapSlots);
1024
1069
  let reassignCount = 0;
@@ -1166,6 +1211,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1166
1211
  });
1167
1212
  manager.initialSpreadCount = spreadCount;
1168
1213
  manager.currentSpreadCount = spreadCount;
1214
+ manager._spreadCountKnown = true;
1169
1215
  }
1170
1216
  finally {
1171
1217
  await manager.resumeFundRecalc();
@@ -1183,6 +1229,108 @@ function resolveMinScaleSlots(primary, secondary) {
1183
1229
  return Math.max(0, Math.floor(s));
1184
1230
  return MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MIN_SCALE_SLOTS;
1185
1231
  }
1232
+ /**
1233
+ * Anchor a rebuilt or reloaded boundary to the last real fill.
1234
+ *
1235
+ * A fresh grid generation derives its band from the current market center, but
1236
+ * the last execution is the geometry fact the fill cycle already honors:
1237
+ *
1238
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below the fill)
1239
+ * SELL fill at slot f -> boundary >= f - gapSlots (sell window starts above it)
1240
+ *
1241
+ * Without this clamp, a generation centered ABOVE the pivot leaves the top
1242
+ * buy levels at/through the fill. The startup picker then correctly skips them
1243
+ * (the LAST-FILL-GUARD refuses the re-placement), fills the buy window lower,
1244
+ * and the first ask stays at the old sellStart — a realized spread two grid
1245
+ * steps wider than target with no order-fill reason for the extra width.
1246
+ *
1247
+ * The decision is delegated to `reanchorBoundaryFromLastFill` (single source:
1248
+ * fill-provenanced pivot, on-ladder price, TTL, shared boundary validator), so
1249
+ * this helper only fixes the array indexing (price-sorted ladder) and keeps a
1250
+ * refusal fail-closed. Returns the original boundary when no safe anchor
1251
+ * applies (cold pivot, already outside, off-ladder, unsafe geometry).
1252
+ *
1253
+ * @param manager - OrderManager holding the new generation + re-armed pivot
1254
+ * @param boundaryIdx - Derived/restored boundary for that generation
1255
+ * @param slots - Generation slots (any order; sorted by price here)
1256
+ * @param gapSlots - Generation gap width
1257
+ * @returns The fill-anchored boundary, or the original when no safe move exists
1258
+ */
1259
+ export function anchorRebuildBoundaryToLastFill(manager, boundaryIdx, slots, gapSlots) {
1260
+ if (boundaryIdx === null || boundaryIdx === '' || boundaryIdx === undefined)
1261
+ return boundaryIdx;
1262
+ const boundary = Number(boundaryIdx);
1263
+ if (!Number.isFinite(boundary))
1264
+ return boundaryIdx;
1265
+ const gap = Number(gapSlots);
1266
+ if (!Number.isFinite(gap) || gap < 0)
1267
+ return boundaryIdx;
1268
+ const ladder = Array.from(slots ?? [])
1269
+ .filter((slot) => !!slot && Number.isFinite(Number(slot.price)))
1270
+ .sort((a, b) => Number(a.price) - Number(b.price));
1271
+ if (ladder.length === 0)
1272
+ return boundaryIdx;
1273
+ let anchor;
1274
+ try {
1275
+ anchor = reanchorBoundaryFromLastFill(manager, boundary, ladder, gap, null);
1276
+ }
1277
+ catch (err) {
1278
+ manager.logger?.log?.(`[BOUNDARY] Last-fill anchor failed during rebuild/load: ${getErrorMessage(err)}; keeping ${boundary}`, 'warn');
1279
+ return boundaryIdx;
1280
+ }
1281
+ if (!anchor?.reanchored) {
1282
+ // Only the actionable refusals are worth a line: a cold/already-outside
1283
+ // state is the normal case on every boot.
1284
+ if (anchor?.reason && anchor.reason !== 'already-outside' && anchor.reason !== 'cold-pivot'
1285
+ && anchor.reason !== 'no-fill-side' && anchor.reason !== 'no-genesis') {
1286
+ manager.logger?.log?.(`[BOUNDARY] Last-fill anchor not applied (${anchor.reason}); keeping ${boundary}`, 'debug');
1287
+ }
1288
+ return boundaryIdx;
1289
+ }
1290
+ const next = Number(anchor.boundaryIdx);
1291
+ if (!Number.isFinite(next) || !Number.isInteger(next) || next < 0) {
1292
+ manager.logger?.log?.(`[BOUNDARY] Last-fill anchor returned an invalid index (${String(anchor.boundaryIdx)}); keeping ${boundary}`, 'warn');
1293
+ return boundaryIdx;
1294
+ }
1295
+ return next;
1296
+ }
1297
+ /**
1298
+ * Apply the rebuild fill anchor AND re-type the rails for the anchored
1299
+ * boundary.
1300
+ *
1301
+ * The split matters: `anchorRebuildBoundaryToLastFill` moves the band, but the
1302
+ * slot roles still belong to createOrderGrid's structural boundary. Persisting
1303
+ * those roles with the anchored boundary would leave the two counter levels
1304
+ * typed as the old side (slot-158/159 BUY and 162/163 SPREAD for the incident)
1305
+ * while every geometry consumer reads boundary 157. This helper keeps the
1306
+ * boundary and the role assignment atomic, using the same `assignGridRoles`
1307
+ * pass as a fresh build.
1308
+ *
1309
+ * @param manager - OrderManager holding the new generation + re-armed pivot
1310
+ * @param boundaryIdx - Structural boundary from createOrderGrid
1311
+ * @param slots - Slots from createOrderGrid
1312
+ * @param gapSlots - Generation gap width
1313
+ * @returns Anchored boundary and slots re-typed for it
1314
+ */
1315
+ export function applyRebuildFillAnchor(manager, boundaryIdx, slots, gapSlots) {
1316
+ // assignGridRoles classifies by array position for non-empty slots, so the
1317
+ // returned array must be the price-sorted ladder the boundary indexes.
1318
+ const list = Array.from(slots ?? [])
1319
+ .filter((slot) => !!slot && Number.isFinite(Number(slot.price)))
1320
+ .sort((a, b) => Number(a.price) - Number(b.price));
1321
+ const anchoredBoundary = anchorRebuildBoundaryToLastFill(manager, boundaryIdx, list, gapSlots);
1322
+ const gap = Number(gapSlots);
1323
+ if (anchoredBoundary === null
1324
+ || !Number.isFinite(Number(anchoredBoundary))
1325
+ || !Number.isFinite(gap)
1326
+ || Number(anchoredBoundary) === Number(boundaryIdx)) {
1327
+ return { boundaryIdx: anchoredBoundary, slots: list };
1328
+ }
1329
+ return {
1330
+ boundaryIdx: anchoredBoundary,
1331
+ slots: assignGridRoles(list, Number(anchoredBoundary), gap, ORDER_TYPES, ORDER_STATES),
1332
+ };
1333
+ }
1186
1334
  /**
1187
1335
  * Initialize and orchestrate the order grid.
1188
1336
  *
@@ -1491,12 +1639,16 @@ export async function initializeGrid(manager) {
1491
1639
  // Continuing would create grid with 0 fund allocation, rendering it non-functional
1492
1640
  throw new Error(`Cannot initialize grid without account totals: ${getErrorMessage(e)}`);
1493
1641
  }
1494
- const { orders, boundaryIdx, initialSpreadCount, gapSlots, genesis } = createOrderGrid({
1642
+ const { orders: derivedOrders, boundaryIdx, initialSpreadCount, gapSlots, genesis } = createOrderGrid({
1495
1643
  ...manager.config,
1496
1644
  startPrice: gridStartPrice,
1497
1645
  minPrice: resolvedMinP,
1498
1646
  maxPrice: resolvedMaxP,
1499
1647
  });
1648
+ // Re-typed below if the fill anchor moves the boundary off the
1649
+ // structural center; the derived array's roles are only valid for
1650
+ // `boundaryIdx`.
1651
+ let orders = derivedOrders;
1500
1652
  manager._gapSlots = gapSlots;
1501
1653
  if (genesis) {
1502
1654
  manager._genesis = genesis;
@@ -1532,14 +1684,27 @@ export async function initializeGrid(manager) {
1532
1684
  rearmLastFillPivotFromMarketFill(manager);
1533
1685
  }
1534
1686
  catch { }
1687
+ // FILL-DERIVED GEOMETRY ON REBUILD: a fresh generation centers the
1688
+ // band on the current market, but the last real fill is still the
1689
+ // geometry fact. If the derived boundary sits ahead of that fill, the
1690
+ // startup picker will skip the levels at/through the fill (the
1691
+ // LAST-FILL-GUARD correctly refuses same-side re-placement) and the
1692
+ // realized spread ends up two steps wider than target. Anchor the
1693
+ // boundary to the fill BEFORE the reconcile builds its windows:
1694
+ // BUY fill at f => boundary <= f-1, SELL fill at f => boundary >= f-gap.
1695
+ // This is a no-op for a cold pivot and for a fill already outside the
1696
+ // window; unsafe candidates are refused by the shared validator.
1697
+ const anchoredGeometry = applyRebuildFillAnchor(manager, boundaryIdx, orders, gapSlots);
1698
+ const anchoredBoundary = anchoredGeometry.boundaryIdx;
1699
+ orders = anchoredGeometry.slots;
1535
1700
  // RC-8: Update boundary with notification to dependent systems
1536
1701
  // Persist master boundary for StrategyEngine
1537
- if (manager.boundaryIdx !== boundaryIdx) {
1538
- manager._restoreBoundary(boundaryIdx);
1702
+ if (manager.boundaryIdx !== anchoredBoundary) {
1703
+ manager._restoreBoundary(anchoredBoundary);
1539
1704
  // RC-8: Notify StrategyEngine of boundary change (if method exists)
1540
1705
  if (typeof manager.notifyBoundaryUpdate === 'function') {
1541
1706
  try {
1542
- manager.notifyBoundaryUpdate(boundaryIdx);
1707
+ manager.notifyBoundaryUpdate(anchoredBoundary);
1543
1708
  }
1544
1709
  catch (err) {
1545
1710
  manager.logger?.log?.(`Error notifying boundary update: ${getErrorMessage(err)}`, 'warn');
@@ -1573,6 +1738,10 @@ export async function initializeGrid(manager) {
1573
1738
  // RC-2: Wrap atomic changes in grid lock
1574
1739
  await manager._gridLock.acquire(async () => {
1575
1740
  _clearOrderCachesLogic(manager);
1741
+ // Regeneration replaces every chain order id: pass-1 size markers
1742
+ // keyed by the old ids are no longer evidence (unlike a snapshot
1743
+ // RELOAD, which restores/merges the persisted markers).
1744
+ manager._chainSizeAppliedFills = new Map();
1576
1745
  await manager._fundLock.acquire(async () => {
1577
1746
  await manager.resetFunds();
1578
1747
  });
@@ -1596,6 +1765,7 @@ export async function initializeGrid(manager) {
1596
1765
  // should not assume the two paths agree.
1597
1766
  manager.initialSpreadCount = initialSpreadCount.buy + initialSpreadCount.sell;
1598
1767
  manager.currentSpreadCount = manager.initialSpreadCount;
1768
+ manager._spreadCountKnown = true;
1599
1769
  });
1600
1770
  // FIX: Use consistent optional chaining pattern for all logger calls
1601
1771
  manager.logger?.log?.(`Initialized grid with ${orders.length} orders.`, 'info');
@@ -1604,7 +1774,7 @@ export async function initializeGrid(manager) {
1604
1774
  }
1605
1775
  /**
1606
1776
  * Full grid resynchronization from blockchain state.
1607
- * @param {import('./types').OrderManager} manager - The manager instance.
1777
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
1608
1778
  * @param {Object} opts - Options for resynchronization.
1609
1779
  * @param {Function} opts.readOpenOrdersFn - Function to read open orders.
1610
1780
  * @param {Object} opts.chainOrders - Chain orders module.
@@ -1616,6 +1786,9 @@ export async function recalculateGrid(manager, opts) {
1616
1786
  const { readOpenOrdersFn, chainOrders, account, privateKey } = opts;
1617
1787
  // Suppress invariant warnings during full resync
1618
1788
  manager.startBootstrap();
1789
+ // A rebuild owns placement until the reconcile completes: fill-driven
1790
+ // COW rebalances defer instead of re-planning against the fresh master.
1791
+ manager.beginStructuralRebuild?.('recalculateGrid');
1619
1792
  // Total timeout across all steps — prevents indefinite hang even if
1620
1793
  // an individual withBlockchainRetry step pins the event loop.
1621
1794
  const totalTimeoutMs = PIPELINE_TIMING.TIMEOUT_MS * 2; // 10 min
@@ -1668,6 +1841,16 @@ export async function recalculateGrid(manager, opts) {
1668
1841
  if (_resyncAborted)
1669
1842
  return;
1670
1843
  const { reconcileGridOrders } = require('./grid_reconcile');
1844
+ // NOTE: do NOT re-adopt the chain snapshot by ladder index here.
1845
+ // After a rebuild every slot price moved, so a price-agnostic
1846
+ // ladder adoption would park each old order on a slot whose new
1847
+ // price differs from the order's actual chain price. The
1848
+ // reconcile marks that slot as matched and would leave the stale
1849
+ // price in place for a later correction cycle. The rebuild is
1850
+ // bracketed by beginStructuralRebuild(), so no concurrent COW
1851
+ // can create against the fresh master; reconcileGridOrders owns
1852
+ // update-first placement and re-prices the live orders onto the
1853
+ // new slots from the chain snapshot directly.
1671
1854
  // #5: Reconcile grid orders.
1672
1855
  // No per-attempt wall-clock race around the whole reconcile.
1673
1856
  // Phase 2 performs many sequential broadcasts (creates ~3s each)
@@ -1681,7 +1864,7 @@ export async function recalculateGrid(manager, opts) {
1681
1864
  // failover standard via withBlockchainRetry, and the 10-min
1682
1865
  // totalTimeoutMs safety net below bounds the whole resync.
1683
1866
  try {
1684
- await reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders });
1867
+ await reconcileGridOrders({ manager, config: manager.config, account, privateKey, chainOrders, chainOpenOrders, options: { allowDuringRebuild: true } });
1685
1868
  }
1686
1869
  catch (err) {
1687
1870
  manager.logger?.log?.(`Error during startup order reconciliation: ${getErrorMessage(err)}`, 'error');
@@ -1705,6 +1888,7 @@ export async function recalculateGrid(manager, opts) {
1705
1888
  }
1706
1889
  finally {
1707
1890
  manager.finishBootstrap();
1891
+ manager.endStructuralRebuild?.();
1708
1892
  }
1709
1893
  })();
1710
1894
  // Swallow late rejection if timeout wins the race
@@ -1725,7 +1909,7 @@ export async function recalculateGrid(manager, opts) {
1725
1909
  /**
1726
1910
  * Check for grid divergence and trigger update if threshold is met.
1727
1911
  *
1728
- * @param {import('./types').OrderManager} manager - Manager instance with order state
1912
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance with order state
1729
1913
  * @returns {unknown}
1730
1914
  */
1731
1915
  export function checkAndUpdateGridIfNeeded(manager) {
@@ -1837,7 +2021,7 @@ export function checkAndUpdateGridIfNeeded(manager) {
1837
2021
  * Non-slot-N shelf/manual orders are excluded (never resized by the
1838
2022
  * geometric pass; same gate as _recalculateGridOrderSizesFromBlockchain).
1839
2023
  *
1840
- * @param {import('./types').OrderManager} manager - Manager instance with order state
2024
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance with order state
1841
2025
  * @returns {{ buyUpdated: boolean; sellUpdated: boolean; buyShrink: boolean; sellShrink: boolean }}
1842
2026
  */
1843
2027
  function _computeCommittedSizeDriftSync(manager) {
@@ -2012,7 +2196,7 @@ export async function checkCommittedSizeDrift(manager) {
2012
2196
  * - Apply: size=500 (no cap check)
2013
2197
  * - Result: slot[1] ready for placement, will consume from sideFree when placed
2014
2198
  *
2015
- * @param {import('./types').OrderManager} manager - OrderManager instance
2199
+ * @param {import('../types.js').OrderManagerLike} manager - OrderManager instance
2016
2200
  * @param {string} orderType - ORDER_TYPES.BUY or ORDER_TYPES.SELL
2017
2201
  * @param {Object} [options] - Options object
2018
2202
  * @param {import('./working_grid.js')} [options.workingGrid] - Working grid for COW pattern
@@ -2165,7 +2349,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
2165
2349
  * Creates working grid, calculates new sizes, generates UPDATE actions.
2166
2350
  * Master grid is only updated after successful blockchain confirmation.
2167
2351
  *
2168
- * @param {import('./types').OrderManager} manager - Manager instance
2352
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2169
2353
  * @param {string} orderType - 'buy', 'sell', or 'both' - which sides to update
2170
2354
  * @param {boolean} [fromBlockchainTimer=false] - If true, skip refetch of account totals (already current)
2171
2355
  * @param {number|null} [overrideBoundaryIdx=null] - Optional override for boundary index
@@ -2262,7 +2446,7 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
2262
2446
  *
2263
2447
  * @param {Array<any>} calculatedGrid - Ideal calculated grid
2264
2448
  * @param {Array<any>} persistedGrid - Persisted grid state
2265
- * @param {import('./types').OrderManager|null} [manager=null] - Manager instance (for grid lock access)
2449
+ * @param {import('../types.js').OrderManagerLike|null} [manager=null] - Manager instance (for grid lock access)
2266
2450
  * @returns {Promise<any>}
2267
2451
  */
2268
2452
  export async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
@@ -2384,7 +2568,7 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
2384
2568
  * Unified divergence monitoring.
2385
2569
  * Performs both Ratio-based and RMS-based divergence checks.
2386
2570
  *
2387
- * @param {import('./types').OrderManager} manager - Manager instance
2571
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2388
2572
  * @param {Array<any>} calculatedGrid - Ideal/calculated grid
2389
2573
  * @param {Array<any>} persistedGrid - Current/persisted grid
2390
2574
  * @returns {Promise<any>}
@@ -2426,8 +2610,8 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
2426
2610
  /**
2427
2611
  * Collect on-chain buy and sell orders from the manager.
2428
2612
  * Filters to orders with valid orderId and positive size.
2429
- * @param {import('./types').OrderManager} manager - The manager instance.
2430
- * @returns {{onChainBuys: Array<import('./types').Order>, onChainSells: Array<import('./types').Order>}}
2613
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2614
+ * @returns {{onChainBuys: ManagedOrder[], onChainSells: ManagedOrder[]}}
2431
2615
  */
2432
2616
  function _getOnChainOrders(manager) {
2433
2617
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
@@ -2449,7 +2633,7 @@ function _getOnChainOrders(manager) {
2449
2633
  }
2450
2634
  /**
2451
2635
  * Calculate current market spread using on-chain orders.
2452
- * @param {import('./types').OrderManager} manager - The manager instance.
2636
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2453
2637
  * @returns {number} The calculated spread percentage.
2454
2638
  */
2455
2639
  export function calculateCurrentSpread(manager) {
@@ -2472,8 +2656,8 @@ export function calculateCurrentSpread(manager) {
2472
2656
  * - RACE CONDITION WINDOW: Between lock release and blockchain submission
2473
2657
  * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
2474
2658
  *
2475
- * @param {import('./types').OrderManager} manager - Manager instance
2476
- * @param {Object} BitShares - BitShares API client
2659
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2660
+ * @param {unknown} _BitShares - BitShares client, forwarded to the live-market-price refresh.
2477
2661
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
2478
2662
  * @returns {Promise<any>}
2479
2663
  */
@@ -2616,7 +2800,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2616
2800
  let chosenSide = decision.side;
2617
2801
  if (!chosenSide) {
2618
2802
  // Exact-zero free funds still allow a no-new-commitment repair:
2619
- // rotate a resting order into the promoted gap slot.
2803
+ // rotate a resting order into an unfunded tightening slot.
2620
2804
  if (decision.code === 'no-free-funds') {
2621
2805
  const fallback = await prepareZeroFreeRotationFallback(manager);
2622
2806
  if (fallback) {
@@ -2844,7 +3028,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2844
3028
  * flagged as violations. The "Edge-First" placement strategy intentionally
2845
3029
  * creates these gaps to maximize grid coverage during fund expansion.
2846
3030
  *
2847
- * @param {import('./types').OrderManager} manager - The manager instance.
3031
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2848
3032
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
2849
3033
  * @returns {Promise<any>}
2850
3034
  */
@@ -2880,7 +3064,7 @@ export async function checkGridHealth(manager, _updateOrdersOnChainBatch = null)
2880
3064
  * Returns boolean flags plus the actual dust order objects so callers can act
2881
3065
  * on individual orders (dust is cancelled immediately on detection).
2882
3066
  *
2883
- * @param {import('./types').OrderManager} manager
3067
+ * @param {import('../types.js').OrderManagerLike} manager
2884
3068
  * @returns {Promise<any>}
2885
3069
  */
2886
3070
  export async function checkWindowDust(manager) {
@@ -2962,7 +3146,7 @@ export async function checkWindowDust(manager) {
2962
3146
  * Returns a Map<orderId, threshold> using the same sizing context as
2963
3147
  * _getDustOrders so eligibility and dust classification stay consistent.
2964
3148
  * @private
2965
- * @param {import('./types').OrderManager} manager
3149
+ * @param {import('../types.js').OrderManagerLike} manager
2966
3150
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
2967
3151
  * @returns {Promise<Map<string, number>>}
2968
3152
  */
@@ -2990,7 +3174,7 @@ async function _computeDustThresholdMap(manager, type) {
2990
3174
  * Shares the same sizing context as _hasAnyDust but returns the actual order
2991
3175
  * objects so callers can act on them (e.g. auto-cancel).
2992
3176
  * @private
2993
- * @param {import('./types').OrderManager} manager
3177
+ * @param {import('../types.js').OrderManagerLike} manager
2994
3178
  * @param {Array<any>} partials - Candidate partial orders to test.
2995
3179
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
2996
3180
  * @param {Map<string, number>} [thresholdMap=null] - Optional precomputed per-slot dust thresholds.
@@ -3011,7 +3195,7 @@ async function _getDustOrders(manager, partials, type, thresholdMap = null) {
3011
3195
  }
3012
3196
  /**
3013
3197
  * Check if any partial orders on a side represent "dust" that should be cleaned.
3014
- * @param {import('./types').OrderManager} manager - Manager instance
3198
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
3015
3199
  * @param {Array<any>} partials - Partial orders to check
3016
3200
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3017
3201
  * @returns {Promise<boolean>} true if dust partials exist
@@ -3022,7 +3206,7 @@ async function _hasAnyDust(manager, partials, type) {
3022
3206
  }
3023
3207
  /**
3024
3208
  * Public dust helper shared by StrategyEngine and Grid health checks.
3025
- * @param {import('./types').OrderManager} manager
3209
+ * @param {import('../types.js').OrderManagerLike} manager
3026
3210
  * @param {Array<any>} partials
3027
3211
  * @param {'buy'|'sell'} side
3028
3212
  * @returns {Promise<boolean>}
@@ -3036,7 +3220,7 @@ export async function hasAnyDust(manager, partials, side) {
3036
3220
  /**
3037
3221
  * Public dust helper that returns the subset of candidate partials currently below
3038
3222
  * the configured dust threshold for the requested side.
3039
- * @param {import('./types').OrderManager} manager
3223
+ * @param {import('../types.js').OrderManagerLike} manager
3040
3224
  * @param {Array<any>} partials
3041
3225
  * @param {'buy'|'sell'} side
3042
3226
  * @returns {Promise<Array<any>>}
@@ -3049,10 +3233,10 @@ export async function getDustOrders(manager, partials, side) {
3049
3233
  }
3050
3234
  /**
3051
3235
  * Determine which side has more available funds for spread correction.
3052
- * @param {import('./types').OrderManager} manager - The manager instance.
3236
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
3053
3237
  * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
3054
3238
  * normalize sell-side funds into buy-side units for a fair cross-asset comparison.
3055
- * @returns {{ side: import('./types').OrderType|null, reason: string, code?: 'market-price-unavailable'|'no-free-funds' }} The side to correct on, or null with a structured cause.
3239
+ * @returns {{ side: import('../types.js').OrderType|null, reason: string, code?: 'market-price-unavailable'|'no-free-funds' }} The side to correct on, or null with a structured cause.
3056
3240
  */
3057
3241
  export function determineOrderSideByFunds(manager, currentMarketPrice) {
3058
3242
  const buyAvailable = Math.min(Number(manager.funds?.available?.buy || 0), Number(manager.accountTotals?.buyFree || 0));
@@ -3126,10 +3310,16 @@ function resolveMinSpreadOrdersReserve(manager) {
3126
3310
  const raw = Number(manager?.config?.gridLimits?.MIN_SPREAD_ORDERS ?? GRID_LIMITS.MIN_SPREAD_ORDERS);
3127
3311
  return (Number.isFinite(raw) && raw >= 0) ? Math.floor(raw) : GRID_LIMITS.MIN_SPREAD_ORDERS;
3128
3312
  }
3129
- // Collect contiguous empty gap-band slots adjacent to a rail edge for boundary
3130
- // promotion. BUY walks upward from the boundary into the gap, SELL walks
3131
- // downward from the sell start; both stop at the first unavailable slot.
3132
- // Mirrors are collapsed into one directional walk (step +/- 1).
3313
+ // Collect gap-band slots adjacent to a rail edge for boundary promotion.
3314
+ // BUY walks upward from the boundary into the gap, SELL walks downward from
3315
+ // the sell start. An EMPTY available slot is promoted; a same-side order
3316
+ // already PLACED inside the band is ABSORBED (it becomes a legal rail member
3317
+ // once the boundary slides past it) and only advances the depth; anything
3318
+ // else (opposite-side placement, phantom, unavailable slot) stops the walk.
3319
+ // "Same-side" is the slot's stored rail type by construction: a placed
3320
+ // SPREAD slot is an ILLEGAL_SPREAD_STATE (validateOrder), so there is no
3321
+ // side-neutral placement to resolve here. Mirrors are collapsed into one
3322
+ // directional walk (step +/- 1).
3133
3323
  //
3134
3324
  // PROMOTION CAP (gap-band geometry): promotion may consume at most
3135
3325
  // bandSize − MIN_SPREAD_ORDERS slots, where bandSize = sellStartIdx −
@@ -3160,20 +3350,41 @@ function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, s
3160
3350
  const promotionQuota = Math.min(quota, maxPromotable, Math.max(0, maxDepth));
3161
3351
  const promoted = [];
3162
3352
  const step = isBuy ? 1 : -1;
3163
- for (let idx = isBuy ? buyEndIdx + 1 : sellStartIdx - 1; promoted.length < promotionQuota
3353
+ // Depth counts EVERY band slot the boundary slide consumes, not only the
3354
+ // new placements: a same-side order already PLACED inside the band is
3355
+ // absorbed by the slide (it becomes a legal rail member once the
3356
+ // boundary moves past it) and is not a placement target. Only empty
3357
+ // available slots are returned. Absorbing is what repairs the
3358
+ // post-crawl shape (boundary 169, sell 173 in-band, 170-172 empty):
3359
+ // step over 173, promote 172, boundary 167. Pushing the placed slot
3360
+ // would plan a CREATE over a live order (duplicate/occupied slot) and
3361
+ // abort the batch, so it only advances `depth`.
3362
+ let depth = 0;
3363
+ for (let idx = isBuy ? buyEndIdx + 1 : sellStartIdx - 1; promotionQuota > 0
3364
+ && depth < maxDepth
3365
+ && depth < maxPromotable
3164
3366
  && (isBuy
3165
3367
  ? idx <= sellStartIdx - 1 - spreadReserve
3166
3368
  : idx >= buyEndIdx + 1 + spreadReserve); idx += step) {
3167
3369
  const slot = allSlotsByPrice[idx];
3168
- if (!slot || !isSlotAvailable(slot))
3370
+ if (!slot)
3371
+ break;
3372
+ if (isOrderPlaced(slot) && slot.type === railType) {
3373
+ depth++;
3374
+ continue;
3375
+ }
3376
+ if (!isSlotAvailable(slot))
3169
3377
  break;
3170
3378
  promoted.push(slot);
3379
+ depth++;
3380
+ if (promoted.length >= promotionQuota)
3381
+ break;
3171
3382
  }
3172
3383
  return promoted;
3173
3384
  }
3174
3385
  /**
3175
3386
  * Prepares one or more orders to correct a wide spread.
3176
- * @param {import('./types').OrderManager} manager - The OrderManager instance.
3387
+ * @param {import('../types.js').OrderManagerLike} manager - The OrderManager instance.
3177
3388
  * @param {string} preferredSide - The side to place the correction on (ORDER_TYPES.BUY/SELL).
3178
3389
  * @returns {Promise<any>}
3179
3390
  * @throws {Error} If preferredSide is invalid.
@@ -3507,9 +3718,11 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3507
3718
  .sort(sortCandidates)
3508
3719
  .slice(0, missingSlots);
3509
3720
  // If the funded rail is full, the spread itself may be stale: the
3510
- // nearest empty slots are still in the gap band. Promote contiguous
3511
- // empty gap slots from that rail edge so correction can repair the
3512
- // boundary and place orders in one atomic COW commit.
3721
+ // nearest empty slots are still in the gap band. Promote from that rail
3722
+ // edge so correction can repair the boundary and place orders in one
3723
+ // atomic COW commit. The walk may ABSORB a same-side order already
3724
+ // placed inside the band (it becomes a rail member once the boundary
3725
+ // slides past it); only empty slots become CREATE targets.
3513
3726
  //
3514
3727
  // Requires a KNOWN committed boundary: with a null/unknown boundary the
3515
3728
  // rail edges are fabricated (buyEndIdx=0), so promotion would place
@@ -3837,13 +4050,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3837
4050
  });
3838
4051
  remainingBudget -= createSize;
3839
4052
  }
3840
- // FUND-CONSTRAINED PROMOTION: free funds could not fund every
3841
- // tightening slot. A fully allocated rail (botFunds 100%, every slot
3842
- // resting) has ~0 free forever, so create-only repair can never close
3843
- // the spread (live 2026-10-30: "planned 4, placing 1"). Rotate a
3844
- // resting same-side order into each unfunded promoted slot instead.
3845
- // The move commits NO new funds (size is the source's booked size) and
3846
- // is bounded by the same promotion/geometry guards as a create.
4053
+ // FUND-CONSTRAINED REPAIR: free funds could not fund every tightening
4054
+ // slot. A fully allocated rail (botFunds 100%, every slot resting) has
4055
+ // ~0 free forever, so create-only repair can never close the spread
4056
+ // (live 2026-10-30: "planned 4, placing 1"). Rotate a resting same-side
4057
+ // order into each unfunded tightening slot instead — whether that slot
4058
+ // is a boundary-promoted gap slot or an orphaned rail slot left by the
4059
+ // anchored boundary. The move commits NO new funds (size is the source's
4060
+ // booked size) and is bounded by the same geometry guards as a create.
3847
4061
  const ordersToRotate = [];
3848
4062
  {
3849
4063
  const fundedCreateIds = new Set(ordersToPlace.map((o) => String(o.id)));
@@ -3852,13 +4066,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3852
4066
  // placed-price collision filter (a promoted slot whose price is
3853
4067
  // already occupied from another slot must not become a rotation
3854
4068
  // destination). Re-derive the subset instead of bypassing those
3855
- // guards.
3856
- const promotedIds = new Set(promotedCandidates.map((c) => String(c.id)));
3857
- const unfundedPromotions = spreadCandidates
3858
- .filter((c) => promotedIds.has(String(c.id)))
4069
+ // guards. Orphaned rail slots are tightening candidates too; the
4070
+ // old promoted-only filter left them unfunded forever when the
4071
+ // virtual tail reserved the whole free balance (availableFund=0,
4072
+ // virtual=free), even though a resting tail order could move.
4073
+ const unfundedCandidates = spreadCandidates
3859
4074
  .filter((c) => !fundedCreateIds.has(String(c.id)))
3860
4075
  .filter((c) => isSlotAvailable(c));
3861
- if (unfundedPromotions.length > 0) {
4076
+ if (unfundedCandidates.length > 0) {
3862
4077
  const windowIds = liveWindowIdSet(manager, railType);
3863
4078
  const edgeIds = edgeOrderIdSet(allSlotsByPrice, manager.config, railType, resolveLiveEdgeAnchorPrice(manager, sideName), windowIds);
3864
4079
  const sourcePool = allOrders
@@ -3879,7 +4094,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3879
4094
  ? Number(a.price) - Number(b.price)
3880
4095
  : Number(b.price) - Number(a.price));
3881
4096
  const usedSourceIds = new Set();
3882
- for (const dest of unfundedPromotions) {
4097
+ for (const dest of unfundedCandidates) {
3883
4098
  const source = sourcePool.find((s) => !usedSourceIds.has(String(s.id)));
3884
4099
  if (!source)
3885
4100
  break;
@@ -3908,7 +4123,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3908
4123
  }
3909
4124
  if (ordersToRotate.length > 0) {
3910
4125
  manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained promotion on ${sideName}: rotating ` +
3911
- `${ordersToRotate.length} resting order(s) into the gap ` +
4126
+ `${ordersToRotate.length} resting order(s) into unfunded slot(s) ` +
3912
4127
  `(${ordersToRotate.map((r) => `${r.id}->${r.newGridId}`).join(', ')}) — ` +
3913
4128
  `no new funds required`, 'warn');
3914
4129
  }
@@ -3927,11 +4142,13 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3927
4142
  };
3928
4143
  }
3929
4144
  let boundaryIdx;
4145
+ const promotedIds = new Set(promotedCandidates.map((slot) => String(slot.id)));
3930
4146
  const placedPromotedIds = new Set([
3931
4147
  ...ordersToPlace
3932
- .filter((order) => promotedCandidates.some((slot) => slot.id === order.id))
4148
+ .filter((order) => promotedIds.has(String(order.id)))
3933
4149
  .map((order) => order.id),
3934
4150
  ...ordersToRotate
4151
+ .filter((rotation) => promotedIds.has(String(rotation.newGridId)))
3935
4152
  .map((rotation) => rotation.newGridId)
3936
4153
  ]);
3937
4154
  if (placedPromotedIds.size > 0) {