dexbot 1.7.1 → 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 (51) hide show
  1. package/CHANGELOG.md +28 -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/modules/account_bots.d.ts +1 -0
  6. package/dist/modules/account_bots.js +7 -5
  7. package/dist/modules/constants.d.ts +2 -0
  8. package/dist/modules/constants.js +16 -2
  9. package/dist/modules/dexbot_class.d.ts +22 -0
  10. package/dist/modules/dexbot_class.js +30 -0
  11. package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
  12. package/dist/modules/dexbot_cow_runtime.js +68 -56
  13. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  14. package/dist/modules/dexbot_maintenance_runtime.js +33 -6
  15. package/dist/modules/node_flap_score.d.ts +6 -6
  16. package/dist/modules/node_flap_score.js +6 -6
  17. package/dist/modules/order/accounting.d.ts +9 -4
  18. package/dist/modules/order/accounting.js +89 -26
  19. package/dist/modules/order/async_lock.d.ts +7 -1
  20. package/dist/modules/order/async_lock.js +7 -1
  21. package/dist/modules/order/export.js +25 -18
  22. package/dist/modules/order/fill_ledger.d.ts +99 -0
  23. package/dist/modules/order/fill_ledger.js +103 -0
  24. package/dist/modules/order/grid.d.ts +75 -18
  25. package/dist/modules/order/grid.js +207 -61
  26. package/dist/modules/order/grid_reconcile_internal.js +16 -4
  27. package/dist/modules/order/index.d.ts +14 -5
  28. package/dist/modules/order/index.js +5 -5
  29. package/dist/modules/order/lifecycle.js +3 -3
  30. package/dist/modules/order/manager.d.ts +15 -24
  31. package/dist/modules/order/manager.js +40 -27
  32. package/dist/modules/order/sync_engine.d.ts +66 -118
  33. package/dist/modules/order/sync_engine.js +118 -162
  34. package/dist/modules/order/utils/math.d.ts +7 -3
  35. package/dist/modules/order/utils/math.js +7 -3
  36. package/dist/modules/order/utils/order.d.ts +40 -41
  37. package/dist/modules/order/utils/order.js +110 -84
  38. package/dist/modules/order/utils/system.d.ts +81 -6
  39. package/dist/modules/order/utils/system.js +167 -29
  40. package/dist/modules/timing_policy.js +2 -2
  41. package/dist/modules/types.d.ts +22 -27
  42. package/docs/COW_INVARIANTS.md +5 -1
  43. package/docs/DEXBOT_COMPARISON.md +4 -4
  44. package/docs/EVOLUTION.md +6 -5
  45. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  46. package/docs/GRID_RECONCILE.md +3 -3
  47. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +38 -30
  48. package/docs/README.md +1 -1
  49. package/docs/architecture.md +26 -8
  50. package/modules/README.md +3 -0
  51. package/package.json +3 -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,7 +2633,7 @@ 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) {
@@ -2514,8 +2656,8 @@ export function calculateCurrentSpread(manager) {
2514
2656
  * - RACE CONDITION WINDOW: Between lock release and blockchain submission
2515
2657
  * - MITIGATION: Pre-flight fund verification before submission; comprehensive error handling
2516
2658
  *
2517
- * @param {import('./types').OrderManager} manager - Manager instance
2518
- * @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.
2519
2661
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function
2520
2662
  * @returns {Promise<any>}
2521
2663
  */
@@ -2658,7 +2800,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2658
2800
  let chosenSide = decision.side;
2659
2801
  if (!chosenSide) {
2660
2802
  // Exact-zero free funds still allow a no-new-commitment repair:
2661
- // rotate a resting order into the promoted gap slot.
2803
+ // rotate a resting order into an unfunded tightening slot.
2662
2804
  if (decision.code === 'no-free-funds') {
2663
2805
  const fallback = await prepareZeroFreeRotationFallback(manager);
2664
2806
  if (fallback) {
@@ -2886,7 +3028,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
2886
3028
  * flagged as violations. The "Edge-First" placement strategy intentionally
2887
3029
  * creates these gaps to maximize grid coverage during fund expansion.
2888
3030
  *
2889
- * @param {import('./types').OrderManager} manager - The manager instance.
3031
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
2890
3032
  * @param {Function|null} [updateOrdersOnChainBatch=null] - Optional batch update function.
2891
3033
  * @returns {Promise<any>}
2892
3034
  */
@@ -2922,7 +3064,7 @@ export async function checkGridHealth(manager, _updateOrdersOnChainBatch = null)
2922
3064
  * Returns boolean flags plus the actual dust order objects so callers can act
2923
3065
  * on individual orders (dust is cancelled immediately on detection).
2924
3066
  *
2925
- * @param {import('./types').OrderManager} manager
3067
+ * @param {import('../types.js').OrderManagerLike} manager
2926
3068
  * @returns {Promise<any>}
2927
3069
  */
2928
3070
  export async function checkWindowDust(manager) {
@@ -3004,7 +3146,7 @@ export async function checkWindowDust(manager) {
3004
3146
  * Returns a Map<orderId, threshold> using the same sizing context as
3005
3147
  * _getDustOrders so eligibility and dust classification stay consistent.
3006
3148
  * @private
3007
- * @param {import('./types').OrderManager} manager
3149
+ * @param {import('../types.js').OrderManagerLike} manager
3008
3150
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3009
3151
  * @returns {Promise<Map<string, number>>}
3010
3152
  */
@@ -3032,7 +3174,7 @@ async function _computeDustThresholdMap(manager, type) {
3032
3174
  * Shares the same sizing context as _hasAnyDust but returns the actual order
3033
3175
  * objects so callers can act on them (e.g. auto-cancel).
3034
3176
  * @private
3035
- * @param {import('./types').OrderManager} manager
3177
+ * @param {import('../types.js').OrderManagerLike} manager
3036
3178
  * @param {Array<any>} partials - Candidate partial orders to test.
3037
3179
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3038
3180
  * @param {Map<string, number>} [thresholdMap=null] - Optional precomputed per-slot dust thresholds.
@@ -3053,7 +3195,7 @@ async function _getDustOrders(manager, partials, type, thresholdMap = null) {
3053
3195
  }
3054
3196
  /**
3055
3197
  * Check if any partial orders on a side represent "dust" that should be cleaned.
3056
- * @param {import('./types').OrderManager} manager - Manager instance
3198
+ * @param {import('../types.js').OrderManagerLike} manager - Manager instance
3057
3199
  * @param {Array<any>} partials - Partial orders to check
3058
3200
  * @param {string} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
3059
3201
  * @returns {Promise<boolean>} true if dust partials exist
@@ -3064,7 +3206,7 @@ async function _hasAnyDust(manager, partials, type) {
3064
3206
  }
3065
3207
  /**
3066
3208
  * Public dust helper shared by StrategyEngine and Grid health checks.
3067
- * @param {import('./types').OrderManager} manager
3209
+ * @param {import('../types.js').OrderManagerLike} manager
3068
3210
  * @param {Array<any>} partials
3069
3211
  * @param {'buy'|'sell'} side
3070
3212
  * @returns {Promise<boolean>}
@@ -3078,7 +3220,7 @@ export async function hasAnyDust(manager, partials, side) {
3078
3220
  /**
3079
3221
  * Public dust helper that returns the subset of candidate partials currently below
3080
3222
  * the configured dust threshold for the requested side.
3081
- * @param {import('./types').OrderManager} manager
3223
+ * @param {import('../types.js').OrderManagerLike} manager
3082
3224
  * @param {Array<any>} partials
3083
3225
  * @param {'buy'|'sell'} side
3084
3226
  * @returns {Promise<Array<any>>}
@@ -3091,10 +3233,10 @@ export async function getDustOrders(manager, partials, side) {
3091
3233
  }
3092
3234
  /**
3093
3235
  * Determine which side has more available funds for spread correction.
3094
- * @param {import('./types').OrderManager} manager - The manager instance.
3236
+ * @param {import('../types.js').OrderManagerLike} manager - The manager instance.
3095
3237
  * @param {number} currentMarketPrice - Last traded price in B/A format (e.g. BTS/XRP), used to
3096
3238
  * 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.
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.
3098
3240
  */
3099
3241
  export function determineOrderSideByFunds(manager, currentMarketPrice) {
3100
3242
  const buyAvailable = Math.min(Number(manager.funds?.available?.buy || 0), Number(manager.accountTotals?.buyFree || 0));
@@ -3242,7 +3384,7 @@ function _collectPromotableBoundarySlots(allSlotsByPrice, railType, buyEndIdx, s
3242
3384
  }
3243
3385
  /**
3244
3386
  * Prepares one or more orders to correct a wide spread.
3245
- * @param {import('./types').OrderManager} manager - The OrderManager instance.
3387
+ * @param {import('../types.js').OrderManagerLike} manager - The OrderManager instance.
3246
3388
  * @param {string} preferredSide - The side to place the correction on (ORDER_TYPES.BUY/SELL).
3247
3389
  * @returns {Promise<any>}
3248
3390
  * @throws {Error} If preferredSide is invalid.
@@ -3908,13 +4050,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3908
4050
  });
3909
4051
  remainingBudget -= createSize;
3910
4052
  }
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.
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.
3918
4061
  const ordersToRotate = [];
3919
4062
  {
3920
4063
  const fundedCreateIds = new Set(ordersToPlace.map((o) => String(o.id)));
@@ -3923,13 +4066,14 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3923
4066
  // placed-price collision filter (a promoted slot whose price is
3924
4067
  // already occupied from another slot must not become a rotation
3925
4068
  // 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)))
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
3930
4074
  .filter((c) => !fundedCreateIds.has(String(c.id)))
3931
4075
  .filter((c) => isSlotAvailable(c));
3932
- if (unfundedPromotions.length > 0) {
4076
+ if (unfundedCandidates.length > 0) {
3933
4077
  const windowIds = liveWindowIdSet(manager, railType);
3934
4078
  const edgeIds = edgeOrderIdSet(allSlotsByPrice, manager.config, railType, resolveLiveEdgeAnchorPrice(manager, sideName), windowIds);
3935
4079
  const sourcePool = allOrders
@@ -3950,7 +4094,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3950
4094
  ? Number(a.price) - Number(b.price)
3951
4095
  : Number(b.price) - Number(a.price));
3952
4096
  const usedSourceIds = new Set();
3953
- for (const dest of unfundedPromotions) {
4097
+ for (const dest of unfundedCandidates) {
3954
4098
  const source = sourcePool.find((s) => !usedSourceIds.has(String(s.id)));
3955
4099
  if (!source)
3956
4100
  break;
@@ -3979,7 +4123,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3979
4123
  }
3980
4124
  if (ordersToRotate.length > 0) {
3981
4125
  manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained promotion on ${sideName}: rotating ` +
3982
- `${ordersToRotate.length} resting order(s) into the gap ` +
4126
+ `${ordersToRotate.length} resting order(s) into unfunded slot(s) ` +
3983
4127
  `(${ordersToRotate.map((r) => `${r.id}->${r.newGridId}`).join(', ')}) — ` +
3984
4128
  `no new funds required`, 'warn');
3985
4129
  }
@@ -3998,11 +4142,13 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
3998
4142
  };
3999
4143
  }
4000
4144
  let boundaryIdx;
4145
+ const promotedIds = new Set(promotedCandidates.map((slot) => String(slot.id)));
4001
4146
  const placedPromotedIds = new Set([
4002
4147
  ...ordersToPlace
4003
- .filter((order) => promotedCandidates.some((slot) => slot.id === order.id))
4148
+ .filter((order) => promotedIds.has(String(order.id)))
4004
4149
  .map((order) => order.id),
4005
4150
  ...ordersToRotate
4151
+ .filter((rotation) => promotedIds.has(String(rotation.newGridId)))
4006
4152
  .map((rotation) => rotation.newGridId)
4007
4153
  ]);
4008
4154
  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): ` +
@@ -31,16 +31,16 @@
31
31
  *
32
32
  * SUBSYSTEM MODULES:
33
33
  * 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
34
- * 2. grid.ts - Grid class (grid creation, synchronization, health)
34
+ * 2. grid.ts - Grid engine (grid creation, synchronization, health)
35
35
  * 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
36
- * 4. format.ts - Numeric formatting (17 functions for consistent display)
36
+ * 4. format.ts - Numeric formatting (18 functions for consistent display)
37
37
  * 5. accounting.ts - Accountant class (fund calculations and reconciliation)
38
38
  * 6. logger.ts - Logger class (structured, color-coded output)
39
39
  * 7. async_lock.ts - AsyncLock class (race condition prevention)
40
40
  * 8. working_grid.ts - WorkingGrid class (copy-on-write grid state)
41
41
  * 9. export.ts - Trade history extraction and CSV export
42
42
  * 10. grid_reconcile.ts - Grid reconciliation against chain (startup + maintenance)
43
- * 11. strategy.ts - Strategy configuration and parsing
43
+ * 11. strategy.ts - StrategyEngine class (boundary-crawl rebalancing, target grid)
44
44
  * 12. sync_engine.ts - Real-time blockchain synchronization
45
45
  *
46
46
  * ===============================================================================
@@ -113,6 +113,16 @@ declare const utils: {
113
113
  pivot: number | null;
114
114
  reason?: "direction" | "same-level";
115
115
  };
116
+ readFillPipelineState(source: unknown): system.FillPipelineState;
117
+ resolveGridUpdateBlockers(source: unknown, options?: {
118
+ now?: number;
119
+ }): system.GridUpdateBlocker[];
120
+ noteGridUpdateBlockers(source: unknown, blockers: system.GridUpdateBlocker[] | null | undefined, options?: {
121
+ limit?: number;
122
+ }): {
123
+ cycles: number;
124
+ escalate: boolean;
125
+ };
116
126
  hasUnsettledFills(source: unknown): {
117
127
  unsettled: boolean;
118
128
  reason: string | null;
@@ -213,7 +223,7 @@ declare const utils: {
213
223
  reviveVirtualSlotFromChain: typeof order.reviveVirtualSlotFromChain;
214
224
  attributeUnmatchedFillToGrid: typeof order.attributeUnmatchedFillToGrid;
215
225
  getLivePendingBroadcasts: typeof order.getLivePendingBroadcasts;
216
- buildFillKey: typeof order.buildFillKey;
226
+ buildFillKey: typeof import("./fill_ledger.js").fillKeyOf;
217
227
  correctOrderPriceOnChain: typeof order.correctOrderPriceOnChain;
218
228
  correctAllPriceMismatches: typeof order.correctAllPriceMismatches;
219
229
  _validatePriceCorrectionEntry: typeof order._validatePriceCorrectionEntry;
@@ -284,7 +294,6 @@ declare const utils: {
284
294
  resolveLiveEdgeAnchorPrice: typeof order.resolveLiveEdgeAnchorPrice;
285
295
  compareEdge: typeof order.compareEdge;
286
296
  collectRefillSlotIds: typeof order.collectRefillSlotIds;
287
- recordOrderPlacement: typeof order.recordOrderPlacement;
288
297
  isFreshlyPlacedOrder: typeof order.isFreshlyPlacedOrder;
289
298
  _filterUnmatchedChainOrders: typeof order._filterUnmatchedChainOrders;
290
299
  getBtsSide: typeof math.getBtsSide;