dexbot 1.6.14 → 1.6.16

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 (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -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;
@@ -11,7 +11,7 @@
11
11
  * - Detailed shutdown logging
12
12
  *
13
13
  * ===============================================================================
14
- * EXPORTS (3 functions)
14
+ * EXPORTS (4 functions)
15
15
  * ===============================================================================
16
16
  *
17
17
  * 1. registerCleanup(name, cleanupFn) - Register cleanup function
@@ -21,7 +21,11 @@
21
21
  *
22
22
  * 2. unregisterCleanup(name) - Unregister a previously registered cleanup
23
23
  *
24
- * 3. setupGracefulShutdown() - Install signal and exception handlers
24
+ * 3. registerExitWipe(name, wipeFn) - Register a synchronous wipe callback
25
+ * that runs AFTER all LIFO cleanups, right before process exit (e.g. a
26
+ * best-effort disk wipe); returns an unregister function
27
+ *
28
+ * 4. setupGracefulShutdown() - Install signal and exception handlers
25
29
  * Registers SIGTERM, SIGINT, uncaughtException, unhandledRejection handlers
26
30
  * Should be called once at process startup
27
31
  *
@@ -11,7 +11,7 @@
11
11
  * - Detailed shutdown logging
12
12
  *
13
13
  * ===============================================================================
14
- * EXPORTS (3 functions)
14
+ * EXPORTS (4 functions)
15
15
  * ===============================================================================
16
16
  *
17
17
  * 1. registerCleanup(name, cleanupFn) - Register cleanup function
@@ -21,7 +21,11 @@
21
21
  *
22
22
  * 2. unregisterCleanup(name) - Unregister a previously registered cleanup
23
23
  *
24
- * 3. setupGracefulShutdown() - Install signal and exception handlers
24
+ * 3. registerExitWipe(name, wipeFn) - Register a synchronous wipe callback
25
+ * that runs AFTER all LIFO cleanups, right before process exit (e.g. a
26
+ * best-effort disk wipe); returns an unregister function
27
+ *
28
+ * 4. setupGracefulShutdown() - Install signal and exception handlers
25
29
  * Registers SIGTERM, SIGINT, uncaughtException, unhandledRejection handlers
26
30
  * Should be called once at process startup
27
31
  *
@@ -681,6 +681,10 @@ function createBotSupervisor({ bots = null, buildEnv = buildScopedChildEnv, spaw
681
681
  await restartAll({ logAction: 'reload-all' });
682
682
  return { ok: true };
683
683
  case 'delete':
684
+ // delete tears the supervisor down as a whole; a bot target
685
+ // would silently kill every bot, so refuse it explicitly.
686
+ if (cmd.bot)
687
+ return { error: `'delete' is whole-runtime; use 'stop ${cmd.bot}' to stop one bot` };
684
688
  await shutdown({ preserveSockets: cmd.preserveSockets || [] });
685
689
  return { ok: true };
686
690
  default:
@@ -52,10 +52,13 @@ function parseUnlockArgs(argv = process.argv) {
52
52
  let cmd = positionalArgs[0];
53
53
  const target = positionalArgs[1] || null;
54
54
  // Normalize whole-runtime controls: restart/reload/stop (no target or 'all') → *-all
55
- // reload mirrors restart but skips the credential daemon re-unlock.
56
- const consumedAll = (cmd === 'restart' || cmd === 'reload' || cmd === 'stop') && (!target || target === 'all');
55
+ // and delete (no target or 'all') → delete. reload mirrors restart but
56
+ // skips the credential daemon re-unlock.
57
+ const wholeRuntime = cmd === 'restart' || cmd === 'reload' || cmd === 'stop' || cmd === 'delete';
58
+ const consumedAll = wholeRuntime && (!target || target === 'all');
57
59
  if (consumedAll) {
58
- cmd += '-all';
60
+ if (cmd !== 'delete')
61
+ cmd += '-all';
59
62
  }
60
63
  return {
61
64
  botName: null,
@@ -51,7 +51,45 @@ declare function listConfiguredBots(botsFile?: string): Array<{
51
51
  declare function getActiveAmaBotFingerprint(botsFile?: string): string;
52
52
  declare function getControlBotNames(target: string | null | undefined, wholeRuntime?: boolean): string[];
53
53
  declare function getControlActionLabel(cmd: string): "shutting down" | "restarting" | "reloading" | "stopping";
54
+ /**
55
+ * Decide the effective `(cmd, target)` for a runtime control request.
56
+ *
57
+ * `all` always selects the whole runtime. A per-bot target exists only under
58
+ * the isolated supervisor: a live monolithic runtime runs every active bot in
59
+ * one worker, so a target cannot select a single bot and the request degrades
60
+ * to the whole-runtime command. `delete` is whole-runtime on every surface and
61
+ * rejects a bot target; `status` is whole-runtime and ignores one.
62
+ *
63
+ * Pure, so the routing contract is unit-testable without a live runtime.
64
+ */
65
+ interface ControlRouting {
66
+ /** Canonical command to dispatch. */
67
+ cmd: string;
68
+ /** Target to act on (null for a whole-runtime action). */
69
+ target: string | null;
70
+ /** The normalized target the user asked for, before any fold (for validation). */
71
+ requestedTarget: string | null;
72
+ /** True when a requested target was dropped into a whole-runtime action. */
73
+ folded: boolean;
74
+ /** Informational message to print when a target was folded. */
75
+ notice: string | null;
76
+ /** Error message when the request must be refused. */
77
+ reject: string | null;
78
+ }
79
+ /**
80
+ * Normalize a target selector: `all` (and empty) select the whole runtime;
81
+ * anything else is treated as a bot name. Single source of the alias rule.
82
+ */
83
+ declare function normalizeControlTarget(target?: string | null): string | null;
84
+ declare function botNotFoundMessage(name: string): string;
85
+ declare function statusIgnoresTargetMessage(name: string): string;
86
+ declare function resolveControlRouting({ cmd, target, monolithicLive }: {
87
+ cmd: string;
88
+ target?: string | null;
89
+ monolithicLive: boolean;
90
+ }): ControlRouting;
54
91
  declare function getControlServiceNames(cmd: string, botNames: string[]): string[];
55
92
  declare function printControlActionSummary(action: string, botNames: string[], serviceNames?: string[]): void;
56
- export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, printControlActionSummary, formatBotCount };
93
+ export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, normalizeControlTarget, botNotFoundMessage, statusIgnoresTargetMessage, printControlActionSummary, formatBotCount };
94
+ export type { ControlRouting };
57
95
  //# sourceMappingURL=monolithic_runtime.d.ts.map
@@ -350,6 +350,65 @@ function getControlActionLabel(cmd) {
350
350
  return 'shutting down';
351
351
  return 'stopping';
352
352
  }
353
+ /**
354
+ * Normalize a target selector: `all` (and empty) select the whole runtime;
355
+ * anything else is treated as a bot name. Single source of the alias rule.
356
+ */
357
+ function normalizeControlTarget(target) {
358
+ return target === 'all' ? null : (target || null);
359
+ }
360
+ // Shared control/status text, built here so the same message cannot drift
361
+ // between the control router, the status validator and the status branch.
362
+ function botNotFoundMessage(name) {
363
+ return `Bot '${name}' not found in bots.json`;
364
+ }
365
+ function statusIgnoresTargetMessage(name) {
366
+ return `'status' is whole-runtime; ignoring target '${name}'.`;
367
+ }
368
+ function resolveControlRouting({ cmd, target, monolithicLive }) {
369
+ const baseCmd = cmd === 'shutdown' ? 'delete' : cmd === 'stat' ? 'status' : cmd;
370
+ const requestedTarget = normalizeControlTarget(target);
371
+ if (!requestedTarget) {
372
+ // Canonicalize the whole-runtime form so a caller that passes a bare
373
+ // `stop`/`restart`/`reload` still gets the `*-all` command the
374
+ // monolithic dispatch expects (the parser usually does this earlier).
375
+ const wholeCmd = (baseCmd === 'stop' || baseCmd === 'restart' || baseCmd === 'reload')
376
+ ? `${baseCmd}-all`
377
+ : baseCmd;
378
+ return { cmd: wholeCmd, target: null, requestedTarget: null, folded: false, notice: null, reject: null };
379
+ }
380
+ if (baseCmd === 'delete') {
381
+ return {
382
+ cmd: baseCmd,
383
+ target: null,
384
+ requestedTarget,
385
+ folded: true,
386
+ notice: null,
387
+ reject: `'delete' is a whole-runtime control and does not accept a bot name; use 'dexbot delete' or 'dexbot stop ${requestedTarget}'.`,
388
+ };
389
+ }
390
+ if (baseCmd === 'status') {
391
+ return {
392
+ cmd: baseCmd,
393
+ target: null,
394
+ requestedTarget,
395
+ folded: true,
396
+ notice: statusIgnoresTargetMessage(requestedTarget),
397
+ reject: null,
398
+ };
399
+ }
400
+ if (monolithicLive) {
401
+ return {
402
+ cmd: `${baseCmd}-all`,
403
+ target: null,
404
+ requestedTarget,
405
+ folded: true,
406
+ notice: `Monolithic runtime runs all active bots in one worker; '${baseCmd} ${requestedTarget}' applies to the whole runtime.`,
407
+ reject: null,
408
+ };
409
+ }
410
+ return { cmd: baseCmd, target: requestedTarget, requestedTarget, folded: false, notice: null, reject: null };
411
+ }
353
412
  function getControlServiceNames(cmd, botNames) {
354
413
  if (!['stop-all', 'restart-all', 'reload-all', 'delete', 'shutdown'].includes(cmd))
355
414
  return [];
@@ -378,5 +437,5 @@ function printControlActionSummary(action, botNames, serviceNames = []) {
378
437
  console.log('='.repeat(50));
379
438
  console.log();
380
439
  }
381
- export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, printControlActionSummary, formatBotCount };
440
+ export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, normalizeControlTarget, botNotFoundMessage, statusIgnoresTargetMessage, printControlActionSummary, formatBotCount };
382
441
  //# sourceMappingURL=monolithic_runtime.js.map
@@ -0,0 +1,79 @@
1
+ export type RuntimeMode = 'monolithic' | 'isolated' | 'pm2' | 'none';
2
+ export interface Pm2Proc {
3
+ pid?: number | string;
4
+ name?: string;
5
+ pm2_env?: {
6
+ pm_uptime?: unknown;
7
+ status?: string;
8
+ };
9
+ monit?: {
10
+ memory?: number;
11
+ };
12
+ [key: string]: unknown;
13
+ }
14
+ export interface RuntimeInfo {
15
+ mode: RuntimeMode;
16
+ /** Live monolithic wrapper PID, or 0. */
17
+ monolithicPid: number;
18
+ /** A supervised (isolated) supervisor socket is present. */
19
+ supervisorSocket: boolean;
20
+ /** The credential daemon is still alive (e.g. after a `stop`). */
21
+ credentialDaemonAlive: boolean;
22
+ /** Live credential-daemon PID (unlock mode), or 0. */
23
+ credentialDaemonPid: number;
24
+ /** Any unlock-mode process is up (monolithic, isolated, or cred daemon). */
25
+ unlockRunning: boolean;
26
+ /** DexBot PM2 processes; empty unless the unlock runtime is down. */
27
+ pm2Processes: Pm2Proc[];
28
+ }
29
+ /** True when `name` matches a configured bot (case-insensitive). */
30
+ export declare function isConfiguredBotName(name: string): boolean;
31
+ export interface StatusTargetCheck {
32
+ error: string | null;
33
+ notice: string | null;
34
+ }
35
+ /**
36
+ * Validate the optional bot name on `dexbot status`. status is whole-runtime
37
+ * on every surface, so a real name is announced-then-ignored and an unknown
38
+ * one is rejected — the same contract the unlock control path applies.
39
+ */
40
+ export declare function checkStatusTarget(target?: string | null): StatusTargetCheck;
41
+ export type StatusRoute = 'unlock' | 'pm2' | 'empty';
42
+ /**
43
+ * Which branch `dexbot status` takes. PM2 wins when PM2 bots are running (even
44
+ * if a stray credential daemon lingers) so the report and the help banner name
45
+ * the same runtime; otherwise a live unlock process is shown by delegating to
46
+ * `unlock status`. The cred-daemon-only case stays on the unlock route so the
47
+ * daemon is still reported.
48
+ */
49
+ export declare function resolveStatusRoute(info: RuntimeInfo): StatusRoute;
50
+ /**
51
+ * Parse `pm2 jlist` and keep only DEXBot2's own processes. Returns `[]` on any
52
+ * failure (pm2 missing, daemon down, malformed output) so callers can treat
53
+ * "no PM2" and "pm2 unavailable" the same way.
54
+ */
55
+ export declare function listDexbotPm2Processes(): Pm2Proc[];
56
+ /**
57
+ * Detect the active runtime and the supporting state the callers need.
58
+ * Monolithic wins over isolated if both markers linger; PM2 is probed last.
59
+ */
60
+ export declare function detectRuntimeMode(): RuntimeInfo;
61
+ /** Human label for the active-runtime banner. */
62
+ export declare const RUNTIME_MODE_LABELS: Record<RuntimeMode, string>;
63
+ /**
64
+ * Banner label for a detection result. `none` with a live credential daemon
65
+ * is called out so the banner agrees with `dexbot status` (which reports the
66
+ * daemon that outlived a `stop`).
67
+ */
68
+ export declare function runtimeModeLabel(info: RuntimeInfo): string;
69
+ export interface RuntimeHelpEntry {
70
+ command: string;
71
+ description: string;
72
+ }
73
+ /**
74
+ * The Runtime command group, phrased for the runtime that is actually up.
75
+ * `none` shows the standard monolithic runtime (the `dexbot start` default)
76
+ * so the reference is always complete before anything is running.
77
+ */
78
+ export declare function runtimeControlHelp(mode: RuntimeMode): RuntimeHelpEntry[];
79
+ //# sourceMappingURL=runtime_mode.d.ts.map