dexbot 1.6.14 → 1.6.15

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 (70) hide show
  1. package/CHANGELOG.md +34 -4
  2. package/analysis/README.md +6 -6
  3. package/analysis/tradingview/README.md +2 -1
  4. package/claw/README.md +7 -7
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +80 -6
  9. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  10. package/dist/dexbot.js +23 -3
  11. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  12. package/dist/modules/account_bots.d.ts +3 -0
  13. package/dist/modules/account_bots.js +3 -0
  14. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  15. package/dist/modules/bot_defaults.d.ts +13 -2
  16. package/dist/modules/bot_defaults.js +31 -2
  17. package/dist/modules/bot_settings.js +3 -0
  18. package/dist/modules/constants.d.ts +6 -0
  19. package/dist/modules/constants.js +24 -0
  20. package/dist/modules/credit_runtime.d.ts +35 -5
  21. package/dist/modules/credit_runtime.js +219 -38
  22. package/dist/modules/dexbot_class.d.ts +19 -1
  23. package/dist/modules/dexbot_class.js +58 -20
  24. package/dist/modules/dexbot_cow_runtime.js +19 -18
  25. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  26. package/dist/modules/dexbot_fill_runtime.js +4 -7
  27. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  28. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  29. package/dist/modules/dexbot_startup_runtime.js +3 -2
  30. package/dist/modules/dexbot_state_recovery.js +1 -1
  31. package/dist/modules/order/export.js +2 -2
  32. package/dist/modules/order/grid.d.ts +118 -1
  33. package/dist/modules/order/grid.js +292 -50
  34. package/dist/modules/order/grid_reconcile.js +4 -3
  35. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  36. package/dist/modules/order/index.d.ts +3 -1
  37. package/dist/modules/order/manager.d.ts +1 -0
  38. package/dist/modules/order/manager.js +5 -14
  39. package/dist/modules/order/sync_engine.js +18 -9
  40. package/dist/modules/order/utils/math.d.ts +98 -26
  41. package/dist/modules/order/utils/math.js +177 -57
  42. package/dist/modules/order/utils/order.js +16 -4
  43. package/dist/modules/order/utils/system.js +2 -2
  44. package/dist/modules/order/utils/validate.d.ts +1 -1
  45. package/dist/modules/order/utils/validate.js +48 -58
  46. package/dist/modules/types.d.ts +7 -0
  47. package/dist/scripts/analyze-credit.js +44 -27
  48. package/dist/scripts/diagnose-pool-history.js +35 -30
  49. package/dist/scripts/pnl.js +1 -1
  50. package/dist/scripts/rich_list.d.ts +18 -0
  51. package/dist/scripts/rich_list.js +461 -0
  52. package/dist/scripts/run-tests.js +80 -4
  53. package/dist/unlock.d.ts +2 -1
  54. package/dist/unlock.js +4 -3
  55. package/docs/COW_INVARIANTS.md +6 -0
  56. package/docs/DEXBOT_COMPARISON.md +6 -6
  57. package/docs/EVOLUTION.md +10 -9
  58. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  59. package/docs/LOGGING.md +16 -1
  60. package/docs/MPA_CREDIT_USAGE.md +10 -5
  61. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +159 -9
  62. package/docs/README.md +1 -1
  63. package/docs/WORKFLOW.md +1 -0
  64. package/docs/architecture.md +56 -2
  65. package/docs/developer_guide.md +5 -1
  66. package/market_adapter/README.md +4 -4
  67. package/modules/README.md +1 -1
  68. package/package.json +2 -1
  69. package/scripts/README.md +59 -32
  70. package/tests/README.md +11 -2
@@ -18,7 +18,7 @@ const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationRes
18
18
  import * as validate from './order/utils/validate.js';
19
19
  const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
20
20
  import * as math from './order/utils/math.js';
21
- const { validateOrderSize, findCrossedOrder, priceSlotEqual, isEvacuationRotationAllowed, isEvacuationSizeStillValid, getSellStartIdx, getPrecisionByOrderType, isSlotIndexInGapBand, getAssetFeesSafe, blockchainToFloat, floatToBlockchainInt, quantizeFloat } = math;
21
+ const { validateOrderSize, findCrossedOrder, sameGridLevel, isEvacuationRotationAllowed, isEvacuationSizeStillValid, getSellStartIdx, getPrecisionByOrderType, isSlotIndexInGapBand, getAssetFeesSafe, blockchainToFloat, floatToBlockchainInt, quantizeFloat } = math;
22
22
  import { parseSlotIndex } from './order/utils/slot.js';
23
23
  /**
24
24
  * Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
@@ -59,7 +59,7 @@ export function isEvacuationStampStillValid(liveBoundary, liveGapSlots, sourceId
59
59
  const dstInRail = orderType === ORDER_TYPES.SELL ? Number(dstIdx) >= sellStartIdx : Number(dstIdx) <= b;
60
60
  return dstInRail;
61
61
  }
62
- function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predicate) {
62
+ function hasSlotPriceCollision(items, targetPrice, genesis, excludeId, predicate) {
63
63
  for (const it of items) {
64
64
  if (predicate && !predicate(it))
65
65
  continue;
@@ -68,14 +68,11 @@ function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predica
68
68
  const p = it.order ? it.order.price : it.price;
69
69
  if (p == null)
70
70
  continue;
71
- try {
72
- if (priceSlotEqual(Number(p), targetPrice, precision))
73
- return it;
74
- }
75
- catch {
76
- if (p === targetPrice)
77
- return it;
78
- }
71
+ // Grid-vs-grid: resolve both prices to their frozen ladder level (a
72
+ // low-precision asset must not collapse adjacent levels, and a price
73
+ // rounded a quantum off its level still resolves back).
74
+ if (sameGridLevel(Number(p), targetPrice, genesis))
75
+ return it;
79
76
  }
80
77
  return null;
81
78
  }
@@ -461,7 +458,7 @@ async function deferUncertainBroadcastRead(bot, detail, suffix, resyncReason, re
461
458
  // Fix #6 (docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md §2): an ambiguous/truncated chain read is
462
459
  // node lag, not a missing order — the broadcast already succeeded. Previously every
463
460
  // such read requested a structural resync, piling pending broadcasts (up to 14) and
464
- // forcing a resync mid-broadcast (the T-BTS 06:43Z thrash). The pending-broadcast
461
+ // forcing a resync mid-broadcast (the <bot> 06:43Z thrash). The pending-broadcast
465
462
  // protection already prevents double-creates on the next cycle, so we keep it and
466
463
  // only escalate to a structural resync once per cooldown window. The next clean
467
464
  // read adopts any landed orders without the churn.
@@ -2747,10 +2744,16 @@ async function waitForCowBroadcastSingleFlight(bot, label) {
2747
2744
  return false;
2748
2745
  bot.manager.logger.log(`[COW] ${label}: a COW broadcast is already in flight; deferring this batch until it settles (prevents overlapping-broadcast commit collision).`, 'warn');
2749
2746
  const waitDeadline = Date.now() + SINGLE_FLIGHT_MAX_WAIT_MS;
2747
+ // Test seam: a caller may shorten the poll cadence via
2748
+ // bot._cowSingleFlightPollMs. Production leaves it unset and keeps the
2749
+ // 250 ms rung, but tests that release the in-flight batch immediately must
2750
+ // not pay a full poll interval after the slot clears.
2751
+ const configuredPollMs = Number(bot._cowSingleFlightPollMs);
2752
+ const pollMs = Number.isFinite(configuredPollMs) && configuredPollMs > 0 ? configuredPollMs : 250;
2750
2753
  while (bot._cowBroadcastInFlight) {
2751
2754
  if (bot._shuttingDown || Date.now() > waitDeadline)
2752
2755
  break;
2753
- await sleep(250);
2756
+ await sleep(pollMs);
2754
2757
  }
2755
2758
  if (bot._shuttingDown) {
2756
2759
  bot.manager.logger.log(`[COW] ${label}: shutdown began while waiting for the in-flight broadcast; aborting this batch.`, 'warn');
@@ -2829,7 +2832,7 @@ async function runPreBroadcastGuards(bot, cowResult) {
2829
2832
  const chainOrderCandidates = Array.isArray(bot.manager?._lastUnmatchedChainOrders)
2830
2833
  ? bot.manager._lastUnmatchedChainOrders
2831
2834
  : [];
2832
- const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates);
2835
+ const createSlotValidation = validateCreateTargetSlots(actions, bot.manager?.orders, bot.manager?.assets, chainOrderCandidates, bot.manager?.config?.incrementPercent ?? null);
2833
2836
  if (!createSlotValidation.isValid) {
2834
2837
  for (const violation of createSlotValidation.violations) {
2835
2838
  let reason;
@@ -3439,8 +3442,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3439
3442
  `emitting planned price (live slot price is derived from genesis and is not authoritative).`, 'warn');
3440
3443
  }
3441
3444
  const createPrice = effectiveOrder.price;
3442
- const precision = order.type === ORDER_TYPES.SELL ? bot.manager.assets.assetA.precision : bot.manager.assets.assetB.precision;
3443
- const batchCollision = hasSlotPriceCollision(opContexts, createPrice, precision, order.id, (ctx) => ctx.kind === 'create' && ctx.order?.price != null);
3445
+ const batchCollision = hasSlotPriceCollision(opContexts, createPrice, bot.manager._genesis, order.id, (ctx) => ctx.kind === 'create' && ctx.order?.price != null);
3444
3446
  if (batchCollision) {
3445
3447
  bot.manager.logger.log(`[COW] Skipping CREATE for ${order.id} at ${Format.formatPrice6(createPrice)}: ` +
3446
3448
  `same-batch CREATE ${batchCollision.id} already at ` +
@@ -3867,15 +3869,14 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3867
3869
  bot.manager.logger.log(`[COW] CREATE fallback for ${action.id} rejected by size validation: ${sizeCheck.reason}`, 'warn');
3868
3870
  }
3869
3871
  else if (fbType && fbSize > 0 && fbPrice > 0) {
3870
- const fbPrecision = fbType === ORDER_TYPES.SELL ? bot.manager.assets.assetA.precision : bot.manager.assets.assetB.precision;
3871
- const fbCollision = hasSlotPriceCollision([...bot.manager.orders.values()], fbPrice, fbPrecision, targetSlotId, isOrderPlaced);
3872
+ const fbCollision = hasSlotPriceCollision([...bot.manager.orders.values()], fbPrice, bot.manager._genesis, targetSlotId, isOrderPlaced);
3872
3873
  if (fbCollision) {
3873
3874
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3874
3875
  `existing placed order ${fbCollision.id} (${fbCollision.orderId}) ` +
3875
3876
  `already at price ${Format.formatPrice6(Number(fbCollision.price))}.`, 'warn');
3876
3877
  continue;
3877
3878
  }
3878
- const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice, fbPrecision, targetSlotId, (ctx) => ctx.kind === 'create');
3879
+ const fbBatchCollision = hasSlotPriceCollision(opContexts, fbPrice, bot.manager._genesis, targetSlotId, (ctx) => ctx.kind === 'create');
3879
3880
  if (fbBatchCollision) {
3880
3881
  bot.manager.logger.log(`[COW] Skipping CREATE fallback for ${targetSlotId} at ${Format.formatPrice6(fbPrice)}: ` +
3881
3882
  `same-batch CREATE ${fbBatchCollision.id} already at ` +
@@ -243,7 +243,7 @@ declare function scheduleFillConsumerRestart(bot: BotLike, chainOrders: ChainOrd
243
243
  * Level-triggered retry for fills parked by consumeFillQueue's pre-lock
244
244
  * gates (order-pipeline or broadcast deferral).
245
245
  *
246
- * Incident (2026-09-13, H-BTS slot-86): a lone fill deferred by an active
246
+ * Incident (2026-09-13, <bot> slot-86): a lone fill deferred by an active
247
247
  * broadcast never drained — the defer branches returned without
248
248
  * rescheduling, and none of the edge-triggered wake-ups came: the flag was
249
249
  * leaked (no region end would ever fire), no second fill arrived to trip
@@ -59,10 +59,7 @@ async function isUnknownFillOrderAdoptable(bot, fillOp) {
59
59
  // through to the credit path instead of deferring credit
60
60
  // to an adoption sync that must not adopt it.
61
61
  {
62
- const precision = parsed.type === ORDER_TYPES.SELL
63
- ? bot.manager?.assets?.assetA?.precision
64
- : bot.manager?.assets?.assetB?.precision;
65
- if (isChainPriceOutOfGrid(price, genesis, precision))
62
+ if (isChainPriceOutOfGrid(price, genesis, Number(parsed?.size) || 0, parsed?.type ?? null, bot.manager?.assets ?? null))
66
63
  return false;
67
64
  }
68
65
  const slotId = `slot-${idx}`;
@@ -555,7 +552,7 @@ function scheduleFillConsumerRestart(bot, chainOrders) {
555
552
  * Level-triggered retry for fills parked by consumeFillQueue's pre-lock
556
553
  * gates (order-pipeline or broadcast deferral).
557
554
  *
558
- * Incident (2026-09-13, H-BTS slot-86): a lone fill deferred by an active
555
+ * Incident (2026-09-13, <bot> slot-86): a lone fill deferred by an active
559
556
  * broadcast never drained — the defer branches returned without
560
557
  * rescheduling, and none of the edge-triggered wake-ups came: the flag was
561
558
  * leaked (no region end would ever fire), no second fill arrived to trip
@@ -917,7 +914,7 @@ async function consumeFillQueue(bot, chainOrders) {
917
914
  resetFailureWatchdogIfSet();
918
915
  // Level-triggered retry: without this, a lone fill parked here
919
916
  // waits for a region end / second fill / maintenance tick that may
920
- // never come (2026-09-13 H-BTS slot-86).
917
+ // never come (2026-09-13 <bot> slot-86).
921
918
  scheduleDeferredFillRetry(bot, chainOrders, 'order pipeline active');
922
919
  return;
923
920
  }
@@ -933,7 +930,7 @@ async function consumeFillQueue(bot, chainOrders) {
933
930
  resetFailureWatchdogIfSet();
934
931
  // Level-triggered retry: without this, a lone fill parked here
935
932
  // waits for a region end / second fill / maintenance tick that may
936
- // never come (2026-09-13 H-BTS slot-86).
933
+ // never come (2026-09-13 <bot> slot-86).
937
934
  scheduleDeferredFillRetry(bot, chainOrders, 'broadcast active');
938
935
  return;
939
936
  }
@@ -340,9 +340,11 @@ declare function executeMaintenanceLogic(bot: BotLike, context: string): Promise
340
340
  * @param {unknown} bot
341
341
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
342
342
  * @param {number} ordersPlaced - Correction orders placed this tick
343
+ * @param {boolean} [transient=false] - True when the correction was refused for
344
+ * a retryable reason (stale plan / duplicate CREATE / unclassified non-execution)
343
345
  * @returns {{staleMs: number, escalated: boolean}}
344
346
  */
345
- export declare function trackOutOfSpreadStaleness(bot: BotLike, spreadChecked: boolean, ordersPlaced: number): {
347
+ export declare function trackOutOfSpreadStaleness(bot: BotLike, spreadChecked: boolean, ordersPlaced: number, transient?: boolean): {
346
348
  staleMs: number;
347
349
  escalated: boolean;
348
350
  };
@@ -435,7 +437,6 @@ declare function markGridActivity(bot: BotLike, reason?: string): void;
435
437
  * @returns {Object}
436
438
  */
437
439
  declare function getMetrics(bot: BotLike): {
438
- boundaryDriftExceedsWindowCount: number;
439
440
  queueDepth: number;
440
441
  fillProcessingLockActive: boolean;
441
442
  divergenceLockActive: boolean;
@@ -455,7 +456,11 @@ declare function getMetrics(bot: BotLike): {
455
456
  refusedCommitCount: number;
456
457
  orphanFillCreditedCount: number;
457
458
  restampBuyAboveAnchorCount: number;
459
+ boundaryDriftExceedsWindowCount: number;
458
460
  gapBandPlacementShadowCount: number;
461
+ spreadCorrectionRefusedCount: number;
462
+ spreadCorrectionRefusalCauses: Record<string, number>;
463
+ spreadCorrectionRetryCount: number;
459
464
  };
460
465
  /**
461
466
  * Read open orders from chain, sync with local state, and process any fills found.
@@ -2501,7 +2501,7 @@ async function executeMaintenanceLogic(bot, context) {
2501
2501
  }
2502
2502
  // Persistence watchdog: a correction that keeps placing nothing
2503
2503
  // while the spread stays wide is a stale grid, not patience.
2504
- trackOutOfSpreadStaleness(bot, true, spreadPlaced);
2504
+ trackOutOfSpreadStaleness(bot, true, spreadPlaced, spreadResult?.transient === true);
2505
2505
  }
2506
2506
  }
2507
2507
  catch (err) {
@@ -2532,13 +2532,16 @@ async function executeMaintenanceLogic(bot, context) {
2532
2532
  * @param {unknown} bot
2533
2533
  * @param {boolean} spreadChecked - Whether the spread check ran this tick
2534
2534
  * @param {number} ordersPlaced - Correction orders placed this tick
2535
+ * @param {boolean} [transient=false] - True when the correction was refused for
2536
+ * a retryable reason (stale plan / duplicate CREATE / unclassified non-execution)
2535
2537
  * @returns {{staleMs: number, escalated: boolean}}
2536
2538
  */
2537
- export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2539
+ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced, transient = false) {
2538
2540
  const outOfSpread = Number(bot?.manager?.outOfSpread) || 0;
2539
2541
  if (ordersPlaced > 0 || outOfSpread === 0) {
2540
2542
  bot._outOfSpreadSince = 0;
2541
2543
  bot._outOfSpreadStaleWarned = false;
2544
+ bot._outOfSpreadTransientCount = 0;
2542
2545
  return { staleMs: 0, escalated: false };
2543
2546
  }
2544
2547
  if (!spreadChecked) {
@@ -2546,6 +2549,29 @@ export function trackOutOfSpreadStaleness(bot, spreadChecked, ordersPlaced) {
2546
2549
  return { staleMs: since > 0 ? Date.now() - since : 0, escalated: false };
2547
2550
  }
2548
2551
  const now = Date.now();
2552
+ // Transient refusals (stale plan / duplicate CREATE / unclassified
2553
+ // non-execution) are retried by checkSpreadCondition's bounded re-plan, so
2554
+ // they must not immediately count toward the persistent-stale clock — a
2555
+ // single concurrent commit would otherwise force a structural re-center.
2556
+ // Count them and restart the clock while under the grace budget; past it,
2557
+ // fall through so a genuinely deadlocked transient still heals.
2558
+ if (transient) {
2559
+ const transientCount = (Number(bot._outOfSpreadTransientCount) || 0) + 1;
2560
+ bot._outOfSpreadTransientCount = transientCount;
2561
+ const grace = Number(TIMING?.SPREAD_STALE_TRANSIENT_GRACE) > 0
2562
+ ? Number(TIMING.SPREAD_STALE_TRANSIENT_GRACE)
2563
+ : 3;
2564
+ if (transientCount <= grace) {
2565
+ bot._outOfSpreadSince = now;
2566
+ bot._outOfSpreadStaleWarned = false;
2567
+ bot._log(`[SPREAD-STALE] Transient spread-correction refusal ${transientCount}/${grace} ` +
2568
+ `(outOfSpread=${outOfSpread}); retrying before any structural re-center`, 'warn');
2569
+ return { staleMs: 0, escalated: false };
2570
+ }
2571
+ }
2572
+ else {
2573
+ bot._outOfSpreadTransientCount = 0;
2574
+ }
2549
2575
  if (!Number(bot._outOfSpreadSince))
2550
2576
  bot._outOfSpreadSince = now;
2551
2577
  const staleMs = now - Number(bot._outOfSpreadSince);
@@ -3158,6 +3184,25 @@ function markGridActivity(bot, reason = 'activity') {
3158
3184
  bot._lastGridActivityAt = Date.now();
3159
3185
  bot.manager?.logger?.log?.(`[MAINT-IDLE] Activity observed: ${reason}`, 'debug');
3160
3186
  }
3187
+ /**
3188
+ * Manager-owned counters overlaid onto the bot's metrics snapshot. The
3189
+ * grid/strategy engines write these on the MANAGER because they have no bot
3190
+ * reference. Kept in one function so wiring a new engine-owned counter does not
3191
+ * mean copying the `manager ?? bot` fallback again.
3192
+ * @param {Object} bot - DEXBot instance
3193
+ * @returns {Object} The manager-owned counters, or {} when the manager has none
3194
+ */
3195
+ function managerOwnedCounters(bot) {
3196
+ const mgr = bot.manager?._metrics;
3197
+ if (!mgr)
3198
+ return {};
3199
+ return {
3200
+ boundaryDriftExceedsWindowCount: mgr.boundaryDriftExceedsWindowCount ?? bot._metrics.boundaryDriftExceedsWindowCount,
3201
+ spreadCorrectionRefusedCount: mgr.spreadCorrectionRefusedCount ?? bot._metrics.spreadCorrectionRefusedCount,
3202
+ spreadCorrectionRefusalCauses: mgr.spreadCorrectionRefusalCauses ?? bot._metrics.spreadCorrectionRefusalCauses,
3203
+ spreadCorrectionRetryCount: mgr.spreadCorrectionRetryCount ?? bot._metrics.spreadCorrectionRetryCount
3204
+ };
3205
+ }
3161
3206
  /**
3162
3207
  * Get current metrics for monitoring and debugging.
3163
3208
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -3175,11 +3220,11 @@ function getMetrics(bot) {
3175
3220
  const heldUnmatched = unmatched.filter((u) => isNonBlockingUnmatchedOrder(u));
3176
3221
  return {
3177
3222
  ...bot._metrics,
3178
- // The boundary-drift counter is written by the strategy engine on the
3179
- // MANAGER's metrics object (calculateTargetGrid has no bot reference),
3180
- // so overlay it here — otherwise the P2 signal is counted but never
3181
- // surfaced by getMetrics().
3182
- boundaryDriftExceedsWindowCount: bot.manager?._metrics?.boundaryDriftExceedsWindowCount ?? bot._metrics.boundaryDriftExceedsWindowCount,
3223
+ // Counters written by the grid/strategy engines on the MANAGER's metrics
3224
+ // object (those engines have no bot reference). Overlay them here so
3225
+ // they are actually surfaced by getMetrics(). Single wiring point: add
3226
+ // a new engine-owned counter here, not as another inline fallback.
3227
+ ...managerOwnedCounters(bot),
3183
3228
  queueDepth: bot._incomingFillQueue.length,
3184
3229
  fillProcessingLockActive: bot.manager?._fillProcessingLock?.isLocked() || false,
3185
3230
  divergenceLockActive: bot.manager?._divergenceLock?.isLocked() || false,
@@ -4,6 +4,7 @@ import { path } from './path_api.js';
4
4
  import * as chainOrders from './chain_orders.js';
5
5
  import { readOpenOrdersGuarded } from './chain_orders.js';
6
6
  import { ORDER_STATES, TIMING } from './constants.js';
7
+ import { Config } from './config.js';
7
8
  import { PATHS } from './paths.js';
8
9
  import { getStorage } from './storage/index.js';
9
10
  import { normalizeBotEntry } from './bot_settings.js';
@@ -424,7 +425,7 @@ async function finishStartupSequence(bot, startupState) {
424
425
  else {
425
426
  bot._log('Open-orders sync loop disabled by configuration');
426
427
  }
427
- bot._log(`DEXBot started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
428
+ bot._log(`DEXBot v${Config.VERSION} started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
428
429
  return;
429
430
  }
430
431
  await bot.manager._fundLock.acquire(async () => {
@@ -731,7 +732,7 @@ async function finishStartupSequence(bot, startupState) {
731
732
  else {
732
733
  bot._log('Open-orders sync loop disabled by configuration');
733
734
  }
734
- bot._log(`DEXBot started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
735
+ bot._log(`DEXBot v${Config.VERSION} started. OrderManager running (dryRun=${!!bot.config.dryRun})`);
735
736
  }
736
737
  catch (err) {
737
738
  bot._warn(`Error during grid initialization: ${getErrorMessage(err)}`);
@@ -302,7 +302,7 @@ async function recoverFromPersistedGrid(bot) {
302
302
  // SPREAD-GUARD mid-evacuation state (live orders crawled into the band,
303
303
  // GAP-EVAC streak already tracking it; the snapshot may also be stale
304
304
  // by one crawl). Rejecting it here forces a structural resync that
305
- // wipes the in-progress evacuation — the H-BTS 2026-09-13 sabotage
305
+ // wipes the in-progress evacuation — the <bot> 2026-09-13 sabotage
306
306
  // loop. Warn + load instead; GAP-EVAC/sync sweeps own the cleanup.
307
307
  // All other reasons stay rebuild-worthy.
308
308
  let tolerateTransientStranding = false;
@@ -516,8 +516,8 @@ async function exportBotTrades(botKey, botConfig, outputDir = './exports') {
516
516
  try {
517
517
  const logFiles = storage.readdir(logsDir);
518
518
  const want = String(botKey).toLowerCase();
519
- // Case-insensitive: log files use the display name (XRP-BTS.log)
520
- // while bot keys are lowercase (xrp-bts). Prefer the exact
519
+ // Case-insensitive: log files use the display name (<bot>.log)
520
+ // while bot keys are lowercase (e.g. <botKey>). Prefer the exact
521
521
  // "<key>.log" hit, fall back to any non-error log containing the key.
522
522
  const exactLog = logFiles.find((f) => f.toLowerCase() === `${want}.log`);
523
523
  const matchingLog = exactLog || logFiles.find((f) => f.toLowerCase().includes(want) && f.endsWith('.log') && !f.toLowerCase().includes('error'));
@@ -102,6 +102,118 @@ interface SpreadCorrection {
102
102
  origin?: string;
103
103
  [key: string]: unknown;
104
104
  }
105
+ /**
106
+ * Spread-correction refusal causes — the single vocabulary shared by
107
+ * classifySpreadRefusalCause, the retry/transience decision and the
108
+ * spreadCorrectionRefusalCauses metric key. Keep every reader/writer keyed off
109
+ * this map so a new cause cannot leave classification and transience out of
110
+ * sync.
111
+ */
112
+ export declare const SPREAD_CORRECTION_REFUSAL: Readonly<{
113
+ /** Post-broadcast working-grid commit rejected (orders may already be on chain). */
114
+ readonly COMMIT_REFUSED: "commit-refused";
115
+ /** Plan went stale / skipped before broadcast (base-version mismatch). */
116
+ readonly VERSION_MISMATCH: "version-mismatch";
117
+ /** A tracked UPDATE target was gone on chain (COW pre-broadcast guard). */
118
+ readonly UPDATE_TARGET_MISSING: "update-target-missing";
119
+ /** Destination slot already held an active order (plan-time dedupe). */
120
+ readonly CREATE_COLLISION: "create-collision";
121
+ /** Unmatched chain orders blocked the CREATE batch. */
122
+ readonly UNMATCHED_CHAIN_ORDERS: "unmatched-chain-orders";
123
+ /** Shutdown began while the batch was in flight. */
124
+ readonly SHUTDOWN: "shutdown";
125
+ /** Unclassified non-execution (fallback). */
126
+ readonly BATCH_NOT_EXECUTED: "batch-not-executed";
127
+ }>;
128
+ export type SpreadCorrectionRefusalCause = (typeof SPREAD_CORRECTION_REFUSAL)[keyof typeof SPREAD_CORRECTION_REFUSAL];
129
+ /**
130
+ * Whether a refusal cause is retryable by the bounded spread-correction re-plan.
131
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
132
+ * @returns {boolean}
133
+ */
134
+ export declare function isTransientSpreadRefusal(cause: SpreadCorrectionRefusalCause): boolean;
135
+ /**
136
+ * P0 observability: classify WHY a spread-correction batch did not land
137
+ * (executed !== true) from the COW batch result. Counter-only — never gates
138
+ * placement. Returns a SPREAD_CORRECTION_REFUSAL value so the metric key, the
139
+ * retry decision and the log all share one vocabulary.
140
+ * @param {Object|null} batchResult - The COW batch result
141
+ * @returns {string} A SPREAD_CORRECTION_REFUSAL value
142
+ */
143
+ export declare function classifySpreadRefusalCause(batchResult: unknown): SpreadCorrectionRefusalCause;
144
+ /**
145
+ * P0 observability: record a spread-correction refusal on the manager's
146
+ * metrics (the only object reachable from this planner; getMetrics overlays
147
+ * these onto the bot's counters). Counter-only; never throws, never gates.
148
+ * @param {Object} manager - OrderManager instance
149
+ * @param {string} cause - A SPREAD_CORRECTION_REFUSAL value
150
+ */
151
+ export declare function recordSpreadCorrectionRefusal(manager: OrderManagerLike, cause: SpreadCorrectionRefusalCause): void;
152
+ /**
153
+ * P5 observability: count a bounded spread-correction re-plan retry. Churn
154
+ * signal — a rising retry rate means concurrent commits are repeatedly
155
+ * invalidating corrections. Counter-only; never throws.
156
+ * @param {Object} manager - OrderManager instance
157
+ */
158
+ export declare function recordSpreadCorrectionRetry(manager: OrderManagerLike): void;
159
+ /**
160
+ * P2 plan-time dedupe: which of a correction's planned CREATE destinations are
161
+ * now occupied by a live (ACTIVE/PARTIAL) order with a chain id?
162
+ *
163
+ * The correction is planned under _gridLock, then broadcast after the lock is
164
+ * released. A concurrent fill rebalance can commit an order onto one of the
165
+ * planned slots in that window; the COW build layer then rejects the whole
166
+ * batch (`Rejecting CREATE … existing orderId`). Detecting it here turns that
167
+ * into a cheap plan-time re-derive (see the retry loop in checkSpreadCondition)
168
+ * instead of a mid-broadcast refusal and structural resync.
169
+ *
170
+ * Pure and never throws. A missing/non-Map orders store selects the empty set.
171
+ * @param {Object} manager - OrderManager instance
172
+ * @param {Object|null} correction - Prepared spread correction
173
+ * @returns {string[]} Occupied planned slot ids
174
+ */
175
+ export declare function getOccupiedCorrectionSlots(manager: OrderManagerLike, correction: SpreadCorrection | null | undefined): string[];
176
+ /**
177
+ * P1/P3 shared re-plan: derive a spread correction from the CURRENT master
178
+ * state (side chosen from fresh on-chain book, opposite-side starvation
179
+ * fallback). Used both for the plan-time collision dedupe and the bounded
180
+ * refusal retry. Read-only against the grid; no _gridLock needed (matches the
181
+ * existing TOCTOU fund re-plan contract).
182
+ * @param {Object} manager - OrderManager instance
183
+ * @returns {Promise<Object|null>} A correction with at least one create, or null
184
+ */
185
+ export declare function replanSpreadCorrectionFromFreshMaster(manager: OrderManagerLike): Promise<SpreadCorrection | null>;
186
+ /**
187
+ * Outcome of the P2 plan-time collision resolution.
188
+ * - 'broadcast': no occupied destination (or the final attempt) — ship the plan.
189
+ * - 'replanned': a destination was taken and a fresh correction was derived.
190
+ * - 'blocked': a destination was taken and no fresh correction exists — refuse.
191
+ */
192
+ export type OccupiedCorrectionResolution = {
193
+ action: 'broadcast';
194
+ } | {
195
+ action: 'replanned';
196
+ correction: SpreadCorrection;
197
+ occupied: string[];
198
+ } | {
199
+ action: 'blocked';
200
+ occupied: string[];
201
+ };
202
+ /**
203
+ * P2: resolve a planned correction whose CREATE destination(s) were taken after
204
+ * planning. Detects the collision, re-derives once from fresh master, and
205
+ * reports whether the caller should broadcast, swap in the re-plan, or refuse.
206
+ *
207
+ * Extracted from checkSpreadCondition so the branch is a real, production-called
208
+ * unit that tests can drive directly (no test-only hook in the production path).
209
+ *
210
+ * @param {Object} manager - OrderManager instance
211
+ * @param {Object|null} correction - The plan about to broadcast
212
+ * @param {number} attempt - 1-based attempt index
213
+ * @param {number} maxAttempts - Total attempts allowed
214
+ * @returns {Promise<OccupiedCorrectionResolution>}
215
+ */
216
+ export declare function resolveOccupiedCorrection(manager: OrderManagerLike, correction: SpreadCorrection | null | undefined, attempt: number, maxAttempts: number): Promise<OccupiedCorrectionResolution>;
105
217
  /**
106
218
  * Central resolution for the RMS structural-divergence threshold (percent).
107
219
  * Single source of truth: per-bot override wins, global GRID_COMPARISON default
@@ -486,10 +598,15 @@ export declare function calculateCurrentSpread(manager: OrderManagerLike): numbe
486
598
  */
487
599
  export declare function checkSpreadCondition(manager: OrderManagerLike, _BitShares: unknown, updateOrdersOnChainBatch?: ((correction: SpreadCorrection) => Promise<{
488
600
  executed?: boolean;
489
- }>) | null): Promise<{
601
+ reason?: unknown;
602
+ commitRefused?: boolean;
603
+ skippedStalePlan?: boolean;
604
+ [key: string]: unknown;
605
+ } | null | undefined>) | null): Promise<{
490
606
  ordersPlaced: number;
491
607
  partialsMoved: number;
492
608
  stall?: SpreadCorrectionStall;
609
+ transient?: boolean;
493
610
  }>;
494
611
  /**
495
612
  * Grid health check for structural violations.