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
@@ -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>}
@@ -1012,20 +1020,14 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1012
1020
  catch { /* load continues boundary-less either way */ }
1013
1021
  }
1014
1022
  }
1015
- // Restore boundary index for StrategyEngine
1016
- if (restoredBoundary !== null) {
1017
- manager._restoreBoundary(restoredBoundary);
1018
- manager.logger?.log?.(`Restored boundary index: ${restoredBoundary}`, 'info');
1019
- }
1020
1023
  // Restart resilience: restore the persisted LAST-FILL-GUARD pivot
1021
- // WITH the boundary — after the persisted genesis is applied and
1022
- // the grid re-typed, before the first reconcile/broadcast — so a
1023
- // restart cannot re-open the cold window where the guard is
1024
- // disabled and evacuation stamps get applied against a boundary
1025
- // that is still being rebuilt. restoreLastFillPivot validates the
1026
- // row against the manager's live genesis (refuses on mismatch —
1027
- // a regenerated grid drops it) and onto the price ladder with the
1028
- // 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.
1029
1031
  if (restoredBoundary !== null) {
1030
1032
  try {
1031
1033
  restoreLastFillPivot(manager, manager.accountOrders?.loadLastFillPivot?.() ?? null);
@@ -1034,6 +1036,27 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
1034
1036
  manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot restore failed (${getErrorMessage(pivotErr)}); book seed takes over`, 'warn');
1035
1037
  }
1036
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
+ }
1037
1060
  // Reassign slot types based on current boundary.
1038
1061
  // Every slot's type must match its price-slot index (parseSlotIndex)
1039
1062
  // relative to the boundary + gapSlots, not array position. After
@@ -1206,6 +1229,108 @@ function resolveMinScaleSlots(primary, secondary) {
1206
1229
  return Math.max(0, Math.floor(s));
1207
1230
  return MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MIN_SCALE_SLOTS;
1208
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
+ }
1209
1334
  /**
1210
1335
  * Initialize and orchestrate the order grid.
1211
1336
  *
@@ -1514,12 +1639,16 @@ export async function initializeGrid(manager) {
1514
1639
  // Continuing would create grid with 0 fund allocation, rendering it non-functional
1515
1640
  throw new Error(`Cannot initialize grid without account totals: ${getErrorMessage(e)}`);
1516
1641
  }
1517
- const { orders, boundaryIdx, initialSpreadCount, gapSlots, genesis } = createOrderGrid({
1642
+ const { orders: derivedOrders, boundaryIdx, initialSpreadCount, gapSlots, genesis } = createOrderGrid({
1518
1643
  ...manager.config,
1519
1644
  startPrice: gridStartPrice,
1520
1645
  minPrice: resolvedMinP,
1521
1646
  maxPrice: resolvedMaxP,
1522
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;
1523
1652
  manager._gapSlots = gapSlots;
1524
1653
  if (genesis) {
1525
1654
  manager._genesis = genesis;
@@ -1555,14 +1684,27 @@ export async function initializeGrid(manager) {
1555
1684
  rearmLastFillPivotFromMarketFill(manager);
1556
1685
  }
1557
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;
1558
1700
  // RC-8: Update boundary with notification to dependent systems
1559
1701
  // Persist master boundary for StrategyEngine
1560
- if (manager.boundaryIdx !== boundaryIdx) {
1561
- manager._restoreBoundary(boundaryIdx);
1702
+ if (manager.boundaryIdx !== anchoredBoundary) {
1703
+ manager._restoreBoundary(anchoredBoundary);
1562
1704
  // RC-8: Notify StrategyEngine of boundary change (if method exists)
1563
1705
  if (typeof manager.notifyBoundaryUpdate === 'function') {
1564
1706
  try {
1565
- manager.notifyBoundaryUpdate(boundaryIdx);
1707
+ manager.notifyBoundaryUpdate(anchoredBoundary);
1566
1708
  }
1567
1709
  catch (err) {
1568
1710
  manager.logger?.log?.(`Error notifying boundary update: ${getErrorMessage(err)}`, 'warn');
@@ -1632,7 +1774,7 @@ export async function initializeGrid(manager) {
1632
1774
  }
1633
1775
  /**
1634
1776
  * Full grid resynchronization from blockchain state.
1635
- * @param {import('./types').OrderManager} manager - The manager instance.
1777
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
1636
1778
  * @param {Object} opts - Options for resynchronization.
1637
1779
  * @param {Function} opts.readOpenOrdersFn - Function to read open orders.
1638
1780
  * @param {Object} opts.chainOrders - Chain orders module.
@@ -1767,7 +1909,7 @@ export async function recalculateGrid(manager, opts) {
1767
1909
  /**
1768
1910
  * Check for grid divergence and trigger update if threshold is met.
1769
1911
  *
1770
- * @param {import('./types').OrderManager} manager - Manager instance with order state
1912
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance with order state
1771
1913
  * @returns {unknown}
1772
1914
  */
1773
1915
  export function checkAndUpdateGridIfNeeded(manager) {
@@ -1879,7 +2021,7 @@ export function checkAndUpdateGridIfNeeded(manager) {
1879
2021
  * Non-slot-N shelf/manual orders are excluded (never resized by the
1880
2022
  * geometric pass; same gate as _recalculateGridOrderSizesFromBlockchain).
1881
2023
  *
1882
- * @param {import('./types').OrderManager} manager - Manager instance with order state
2024
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance with order state
1883
2025
  * @returns {{ buyUpdated: boolean; sellUpdated: boolean; buyShrink: boolean; sellShrink: boolean }}
1884
2026
  */
1885
2027
  function _computeCommittedSizeDriftSync(manager) {
@@ -2054,7 +2196,7 @@ export async function checkCommittedSizeDrift(manager) {
2054
2196
  * - Apply: size=500 (no cap check)
2055
2197
  * - Result: slot[1] ready for placement, will consume from sideFree when placed
2056
2198
  *
2057
- * @param {import('./types').OrderManager} manager - OrderManager instance
2199
+ * @param {import('../types.js').OrderManagerLike} manager - OrderManager instance
2058
2200
  * @param {string} orderType - ORDER_TYPES.BUY or ORDER_TYPES.SELL
2059
2201
  * @param {Object} [options] - Options object
2060
2202
  * @param {import('./working_grid.js')} [options.workingGrid] - Working grid for COW pattern
@@ -2207,7 +2349,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
2207
2349
  * Creates working grid, calculates new sizes, generates UPDATE actions.
2208
2350
  * Master grid is only updated after successful blockchain confirmation.
2209
2351
  *
2210
- * @param {import('./types').OrderManager} manager - Manager instance
2352
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2211
2353
  * @param {string} orderType - 'buy', 'sell', or 'both' - which sides to update
2212
2354
  * @param {boolean} [fromBlockchainTimer=false] - If true, skip refetch of account totals (already current)
2213
2355
  * @param {number|null} [overrideBoundaryIdx=null] - Optional override for boundary index
@@ -2304,7 +2446,7 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
2304
2446
  *
2305
2447
  * @param {Array<any>} calculatedGrid - Ideal calculated grid
2306
2448
  * @param {Array<any>} persistedGrid - Persisted grid state
2307
- * @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)
2308
2450
  * @returns {Promise<any>}
2309
2451
  */
2310
2452
  export async function compareGrids(calculatedGrid, persistedGrid, manager = null) {
@@ -2426,7 +2568,7 @@ export async function compareGrids(calculatedGrid, persistedGrid, manager = null
2426
2568
  * Unified divergence monitoring.
2427
2569
  * Performs both Ratio-based and RMS-based divergence checks.
2428
2570
  *
2429
- * @param {import('./types').OrderManager} manager - Manager instance
2571
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2430
2572
  * @param {Array<any>} calculatedGrid - Ideal/calculated grid
2431
2573
  * @param {Array<any>} persistedGrid - Current/persisted grid
2432
2574
  * @returns {Promise<any>}
@@ -2468,8 +2610,8 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
2468
2610
  /**
2469
2611
  * Collect on-chain buy and sell orders from the manager.
2470
2612
  * Filters to orders with valid orderId and positive size.
2471
- * @param {import('./types').OrderManager} manager - The manager instance.
2472
- * @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[]}}
2473
2615
  */
2474
2616
  function _getOnChainOrders(manager) {
2475
2617
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
@@ -2491,13 +2633,36 @@ function _getOnChainOrders(manager) {
2491
2633
  }
2492
2634
  /**
2493
2635
  * Calculate current market spread using on-chain orders.
2494
- * @param {import('./types').OrderManager} manager - The manager instance.
2636
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2495
2637
  * @returns {number} The calculated spread percentage.
2496
2638
  */
2497
2639
  export function calculateCurrentSpread(manager) {
2498
2640
  const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2499
2641
  return calculateSpreadFromOrders(onChainBuys, onChainSells);
2500
2642
  }
2643
+ /**
2644
+ * Measure the current out-of-spread violation in grid steps, from the live
2645
+ * on-chain window only. ONE implementation for the entry reading and the
2646
+ * post-placement reading, so "did the repair reduce the violation?" is the
2647
+ * same arithmetic as "is the spread wide?" (retrospective §9.11.3: a repair
2648
+ * must reduce the violation; the watchdog otherwise counted any placement
2649
+ * as progress).
2650
+ *
2651
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2652
+ * @returns {{ currentSpread: number, nominalSpread: number, excess: number, buyCount: number, sellCount: number }}
2653
+ */
2654
+ export function measureSpreadExcess(manager) {
2655
+ const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2656
+ const currentSpread = calculateSpreadFromOrders(onChainBuys, onChainSells);
2657
+ const nominalSpread = manager.config.targetSpreadPercent ?? DEFAULT_CONFIG.targetSpreadPercent;
2658
+ // Fixed tolerance: 0.5 steps = half increment (tighter spread check).
2659
+ const toleranceSteps = 0.5;
2660
+ // `_getOnChainOrders` already slot-N/size-gated the window.
2661
+ const buyCount = onChainBuys.length;
2662
+ const sellCount = onChainSells.length;
2663
+ const excess = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
2664
+ return { currentSpread, nominalSpread, excess, buyCount, sellCount };
2665
+ }
2501
2666
  /**
2502
2667
  * Proactive spread correction check.
2503
2668
  *
@@ -2514,8 +2679,8 @@ export function calculateCurrentSpread(manager) {
2514
2679
  * - RACE CONDITION WINDOW: Between lock release and blockchain submission
2515
2680
  * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
2516
2681
  *
2517
- * @param {import('./types').OrderManager} manager - Manager instance
2518
- * @param {Object} BitShares - BitShares API client
2682
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
2683
+ * @param {unknown} _BitShares - BitShares client, forwarded to the live-market-price refresh.
2519
2684
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
2520
2685
  * @returns {Promise<any>}
2521
2686
  */
@@ -2560,21 +2725,12 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2560
2725
  // activating SPREAD slots at suboptimal prices.
2561
2726
  const oneSideEmpty = onChainBuys.length === 0 || onChainSells.length === 0;
2562
2727
  const executeSpreadCheck = async () => {
2563
- const currentSpread = calculateCurrentSpread(manager);
2564
- // Nominal spread is the configured target spread percentage.
2565
- // Keep this fixed: doubled-side flags are fill/replacement mechanics only.
2566
- const nominalSpread = manager.config.targetSpreadPercent ?? DEFAULT_CONFIG.targetSpreadPercent;
2728
+ const measured = measureSpreadExcess(manager);
2729
+ const currentSpread = measured.currentSpread;
2730
+ const nominalSpread = measured.nominalSpread;
2567
2731
  // Fixed tolerance: 0.5 steps = half increment (tighter spread check).
2568
2732
  const toleranceSteps = 0.5;
2569
- const buyCount = manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.ACTIVE)
2570
- .concat(manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.PARTIAL))
2571
- .filter((o) => o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null)
2572
- .length;
2573
- const sellCount = manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.ACTIVE)
2574
- .concat(manager.getOrdersByTypeAndState(ORDER_TYPES.SELL, ORDER_STATES.PARTIAL))
2575
- .filter((o) => o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null)
2576
- .length;
2577
- manager.outOfSpread = shouldFlagOutOfSpread(currentSpread, nominalSpread, toleranceSteps, buyCount, sellCount, manager.config.incrementPercent);
2733
+ manager.outOfSpread = measured.excess;
2578
2734
  if (manager.outOfSpread === 0)
2579
2735
  return false;
2580
2736
  // P-A cold book: the orchestration short-circuit, evaluated in the
@@ -2658,7 +2814,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2658
2814
  let chosenSide = decision.side;
2659
2815
  if (!chosenSide) {
2660
2816
  // Exact-zero free funds still allow a no-new-commitment repair:
2661
- // rotate a resting order into the promoted gap slot.
2817
+ // rotate a resting order into an unfunded tightening slot.
2662
2818
  if (decision.code === 'no-free-funds') {
2663
2819
  const fallback = await prepareZeroFreeRotationFallback(manager);
2664
2820
  if (fallback) {
@@ -2843,7 +2999,19 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2843
2999
  if (batchResult && batchResult.executed === true) {
2844
3000
  await manager.recalculateFunds();
2845
3001
  const placed = getSpreadCorrectionActionCount(activeCorrection);
2846
- return { ordersPlaced: placed, partialsMoved: 0 };
3002
+ // Post-placement measurement: the watchdog needs to know
3003
+ // whether this placement REDUCED the violation or merely
3004
+ // moved orders (§9.11.3). Measured from the committed
3005
+ // window, so a placement that only touched the side that
3006
+ // was not blocking reports the same excess.
3007
+ let excessAfter;
3008
+ try {
3009
+ excessAfter = measureSpreadExcess(manager).excess;
3010
+ }
3011
+ catch {
3012
+ excessAfter = undefined;
3013
+ }
3014
+ return { ordersPlaced: placed, partialsMoved: 0, ...(excessAfter === undefined ? {} : { excessAfter }) };
2847
3015
  }
2848
3016
  const cause = classifySpreadRefusalCause(batchResult);
2849
3017
  recordSpreadCorrectionRefusal(manager, cause);
@@ -2886,7 +3054,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2886
3054
  * flagged as violations. The "Edge-First" placement strategy intentionally
2887
3055
  * creates these gaps to maximize grid coverage during fund expansion.
2888
3056
  *
2889
- * @param {import('./types').OrderManager} manager - The manager instance.
3057
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2890
3058
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
2891
3059
  * @returns {Promise<any>}
2892
3060
  */
@@ -2922,7 +3090,7 @@ export async function checkGridHealth(manager, _updateOrdersOnChainBatch = null)
2922
3090
  * Returns boolean flags plus the actual dust order objects so callers can act
2923
3091
  * on individual orders (dust is cancelled immediately on detection).
2924
3092
  *
2925
- * @param {import('./types').OrderManager} manager
3093
+ * @param {import('../types.js').OrderManagerLike} manager
2926
3094
  * @returns {Promise<any>}
2927
3095
  */
2928
3096
  export async function checkWindowDust(manager) {
@@ -3004,7 +3172,7 @@ export async function checkWindowDust(manager) {
3004
3172
  * Returns a Map<orderId, threshold> using the same sizing context as
3005
3173
  * _getDustOrders so eligibility and dust classification stay consistent.
3006
3174
  * @private
3007
- * @param {import('./types').OrderManager} manager
3175
+ * @param {import('../types.js').OrderManagerLike} manager
3008
3176
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3009
3177
  * @returns {Promise<Map<string, number>>}
3010
3178
  */
@@ -3032,7 +3200,7 @@ async function _computeDustThresholdMap(manager, type) {
3032
3200
  * Shares the same sizing context as _hasAnyDust but returns the actual order
3033
3201
  * objects so callers can act on them (e.g. auto-cancel).
3034
3202
  * @private
3035
- * @param {import('./types').OrderManager} manager
3203
+ * @param {import('../types.js').OrderManagerLike} manager
3036
3204
  * @param {Array<any>} partials - Candidate partial orders to test.
3037
3205
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3038
3206
  * @param {Map<string, number>} [thresholdMap=null] - Optional precomputed per-slot dust thresholds.
@@ -3053,7 +3221,7 @@ async function _getDustOrders(manager, partials, type, thresholdMap = null) {
3053
3221
  }
3054
3222
  /**
3055
3223
  * Check if any partial orders on a side represent "dust" that should be cleaned.
3056
- * @param {import('./types').OrderManager} manager - Manager instance
3224
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
3057
3225
  * @param {Array<any>} partials - Partial orders to check
3058
3226
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3059
3227
  * @returns {Promise<boolean>} true if dust partials exist
@@ -3064,7 +3232,7 @@ async function _hasAnyDust(manager, partials, type) {
3064
3232
  }
3065
3233
  /**
3066
3234
  * Public dust helper shared by StrategyEngine and Grid health checks.
3067
- * @param {import('./types').OrderManager} manager
3235
+ * @param {import('../types.js').OrderManagerLike} manager
3068
3236
  * @param {Array<any>} partials
3069
3237
  * @param {'buy'|'sell'} side
3070
3238
  * @returns {Promise<boolean>}
@@ -3078,7 +3246,7 @@ export async function hasAnyDust(manager, partials, side) {
3078
3246
  /**
3079
3247
  * Public dust helper that returns the subset of candidate partials currently below
3080
3248
  * the configured dust threshold for the requested side.
3081
- * @param {import('./types').OrderManager} manager
3249
+ * @param {import('../types.js').OrderManagerLike} manager
3082
3250
  * @param {Array<any>} partials
3083
3251
  * @param {'buy'|'sell'} side
3084
3252
  * @returns {Promise<Array<any>>}
@@ -3091,10 +3259,10 @@ export async function getDustOrders(manager, partials, side) {
3091
3259
  }
3092
3260
  /**
3093
3261
  * Determine which side has more available funds for spread correction.
3094
- * @param {import('./types').OrderManager} manager - The manager instance.
3262
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
3095
3263
  * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
3096
3264
  * normalize sell-side funds into buy-side units for a fair cross-asset comparison.
3097
- * @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.
3265
+ * @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.
3098
3266
  */
3099
3267
  export function determineOrderSideByFunds(manager, currentMarketPrice) {
3100
3268
  const buyAvailable = Math.min(Number(manager.funds?.available?.buy || 0), Number(manager.accountTotals?.buyFree || 0));
@@ -3242,7 +3410,7 @@ function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, s
3242
3410
  }
3243
3411
  /**
3244
3412
  * Prepares one or more orders to correct a wide spread.
3245
- * @param {import('./types').OrderManager} manager - The OrderManager instance.
3413
+ * @param {import('../types.js').OrderManagerLike} manager - The OrderManager instance.
3246
3414
  * @param {string} preferredSide - The side to place the correction on (ORDER_TYPES.BUY/SELL).
3247
3415
  * @returns {Promise<any>}
3248
3416
  * @throws {Error} If preferredSide is invalid.
@@ -3908,13 +4076,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3908
4076
  });
3909
4077
  remainingBudget -= createSize;
3910
4078
  }
3911
- // FUND-CONSTRAINED PROMOTION: free funds could not fund every
3912
- // tightening slot. A fully allocated rail (botFunds 100%, every slot
3913
- // resting) has ~0 free forever, so create-only repair can never close
3914
- // the spread (live 2026-10-30: "planned 4, placing 1"). Rotate a
3915
- // resting same-side order into each unfunded promoted slot instead.
3916
- // The move commits NO new funds (size is the source's booked size) and
3917
- // is bounded by the same promotion/geometry guards as a create.
4079
+ // FUND-CONSTRAINED REPAIR: free funds could not fund every tightening
4080
+ // slot. A fully allocated rail (botFunds 100%, every slot resting) has
4081
+ // ~0 free forever, so create-only repair can never close the spread
4082
+ // (live 2026-10-30: "planned 4, placing 1"). Rotate a resting same-side
4083
+ // order into each unfunded tightening slot instead — whether that slot
4084
+ // is a boundary-promoted gap slot or an orphaned rail slot left by the
4085
+ // anchored boundary. The move commits NO new funds (size is the source's
4086
+ // booked size) and is bounded by the same geometry guards as a create.
3918
4087
  const ordersToRotate = [];
3919
4088
  {
3920
4089
  const fundedCreateIds = new Set(ordersToPlace.map((o) => String(o.id)));
@@ -3923,13 +4092,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3923
4092
  // placed-price collision filter (a promoted slot whose price is
3924
4093
  // already occupied from another slot must not become a rotation
3925
4094
  // destination). Re-derive the subset instead of bypassing those
3926
- // guards.
3927
- const promotedIds = new Set(promotedCandidates.map((c) => String(c.id)));
3928
- const unfundedPromotions = spreadCandidates
3929
- .filter((c) => promotedIds.has(String(c.id)))
4095
+ // guards. Orphaned rail slots are tightening candidates too; the
4096
+ // old promoted-only filter left them unfunded forever when the
4097
+ // virtual tail reserved the whole free balance (availableFund=0,
4098
+ // virtual=free), even though a resting tail order could move.
4099
+ const unfundedCandidates = spreadCandidates
3930
4100
  .filter((c) => !fundedCreateIds.has(String(c.id)))
3931
4101
  .filter((c) => isSlotAvailable(c));
3932
- if (unfundedPromotions.length > 0) {
4102
+ if (unfundedCandidates.length > 0) {
3933
4103
  const windowIds = liveWindowIdSet(manager, railType);
3934
4104
  const edgeIds = edgeOrderIdSet(allSlotsByPrice, manager.config, railType, resolveLiveEdgeAnchorPrice(manager, sideName), windowIds);
3935
4105
  const sourcePool = allOrders
@@ -3950,7 +4120,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3950
4120
  ? Number(a.price) - Number(b.price)
3951
4121
  : Number(b.price) - Number(a.price));
3952
4122
  const usedSourceIds = new Set();
3953
- for (const dest of unfundedPromotions) {
4123
+ for (const dest of unfundedCandidates) {
3954
4124
  const source = sourcePool.find((s) => !usedSourceIds.has(String(s.id)));
3955
4125
  if (!source)
3956
4126
  break;
@@ -3979,7 +4149,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3979
4149
  }
3980
4150
  if (ordersToRotate.length > 0) {
3981
4151
  manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained promotion on ${sideName}: rotating ` +
3982
- `${ordersToRotate.length} resting order(s) into the gap ` +
4152
+ `${ordersToRotate.length} resting order(s) into unfunded slot(s) ` +
3983
4153
  `(${ordersToRotate.map((r) => `${r.id}->${r.newGridId}`).join(', ')}) — ` +
3984
4154
  `no new funds required`, 'warn');
3985
4155
  }
@@ -3998,11 +4168,13 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3998
4168
  };
3999
4169
  }
4000
4170
  let boundaryIdx;
4171
+ const promotedIds = new Set(promotedCandidates.map((slot) => String(slot.id)));
4001
4172
  const placedPromotedIds = new Set([
4002
4173
  ...ordersToPlace
4003
- .filter((order) => promotedCandidates.some((slot) => slot.id === order.id))
4174
+ .filter((order) => promotedIds.has(String(order.id)))
4004
4175
  .map((order) => order.id),
4005
4176
  ...ordersToRotate
4177
+ .filter((rotation) => promotedIds.has(String(rotation.newGridId)))
4006
4178
  .map((rotation) => rotation.newGridId)
4007
4179
  ]);
4008
4180
  if (placedPromotedIds.size > 0) {
@@ -1802,13 +1802,25 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1802
1802
  chainCount = Math.max(0, chainCount - dustCancelledCount);
1803
1803
  const createCount = Math.max(0, targetCount - chainCount);
1804
1804
  const remainingSlots = desiredSlots.slice(updateCount);
1805
- // UNSETTLED-FILL GATE: while fills are queued, draining, in flight, or
1806
- // owed a crawl, the master still treats filled slots as ACTIVE and the
1807
- // boundary has not crawled for them. Any window top-up derived from that
1808
- // geometry refills the EXPENSIVE end of the rail — the live incident
1805
+ // UNSETTLED-FILL GATE: while fills are draining, in flight, or owed a
1806
+ // crawl, the master still treats filled slots as ACTIVE and the boundary
1807
+ // has not crawled for them. Any window top-up derived from that geometry
1808
+ // refills the EXPENSIVE end of the rail — the live incident
1809
1809
  // (12s of buys at 1282.78 -> 1310.04 while the market was ~1280). Defer
1810
1810
  // the top-up to the cycle after the fills (and their crawl) are committed;
1811
1811
  // 1:1 repairs (cancelled-slot replacement, vacated-rail refill) still run.
1812
+ //
1813
+ // SCOPE: a bare manager exposes only MANAGER-level state here
1814
+ // (`_pendingFillCrawls`, `_fillBatchInFlight`). The bot-level queue
1815
+ // (`_incomingFillQueue`) and the deferred-drain flag
1816
+ // (`_deferredFillsPending`) are invisible from this source, so "queued" is
1817
+ // covered by the CALLER's gate, not by this one. The startup and
1818
+ // targeted-sync callers drain fills before they reconcile (the bootstrap
1819
+ // consumer / _syncOpenOrdersAndProcessFills); the rebuild caller
1820
+ // (recalculateGrid) has no bot and relies on the structural-rebuild
1821
+ // bracket. That leaves only a fill arriving during this reconcile's chain
1822
+ // read. Widening it belongs at a caller that owns the bot
1823
+ // (docs/FILL_PIPELINE.md B2) — not a second counter here.
1812
1824
  const unsettled = hasUnsettledFills(manager);
1813
1825
  if (unsettled.unsettled && createCount > 0) {
1814
1826
  logger?.log?.(`Startup: Deferring ${Math.min(createCount, remainingSlots.length)} ${sideUpper} window top-up create(s): ` +