dexbot 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +12 -1
  24. package/dist/modules/account_bots.js +7 -5
  25. package/dist/modules/account_orders.d.ts +12 -0
  26. package/dist/modules/account_orders.js +30 -0
  27. package/dist/modules/bitshares-native/transport.js +24 -6
  28. package/dist/modules/bitshares_client.d.ts +24 -6
  29. package/dist/modules/bitshares_client.js +44 -7
  30. package/dist/modules/bot_settings.d.ts +2 -0
  31. package/dist/modules/constants.d.ts +28 -3
  32. package/dist/modules/constants.js +79 -10
  33. package/dist/modules/dexbot_class.d.ts +23 -6
  34. package/dist/modules/dexbot_class.js +44 -0
  35. package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
  36. package/dist/modules/dexbot_cow_runtime.js +688 -188
  37. package/dist/modules/dexbot_fill_runtime.js +124 -35
  38. package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
  39. package/dist/modules/dexbot_maintenance_runtime.js +259 -79
  40. package/dist/modules/dexbot_startup_runtime.js +32 -20
  41. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  42. package/dist/modules/dexbot_state_recovery.js +167 -5
  43. package/dist/modules/node_connect_policy.d.ts +8 -1
  44. package/dist/modules/node_connect_policy.js +18 -2
  45. package/dist/modules/node_flap_score.d.ts +87 -0
  46. package/dist/modules/node_flap_score.js +124 -0
  47. package/dist/modules/node_health_cache.d.ts +40 -3
  48. package/dist/modules/node_health_cache.js +66 -20
  49. package/dist/modules/node_manager.d.ts +101 -19
  50. package/dist/modules/node_manager.js +255 -65
  51. package/dist/modules/order/accounting.d.ts +9 -4
  52. package/dist/modules/order/accounting.js +131 -19
  53. package/dist/modules/order/async_lock.d.ts +7 -1
  54. package/dist/modules/order/async_lock.js +7 -1
  55. package/dist/modules/order/export.js +25 -18
  56. package/dist/modules/order/fill_ledger.d.ts +99 -0
  57. package/dist/modules/order/fill_ledger.js +103 -0
  58. package/dist/modules/order/format.d.ts +24 -10
  59. package/dist/modules/order/format.js +30 -10
  60. package/dist/modules/order/grid.d.ts +75 -18
  61. package/dist/modules/order/grid.js +289 -72
  62. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  63. package/dist/modules/order/grid_reconcile.js +333 -210
  64. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  65. package/dist/modules/order/grid_reconcile_internal.js +223 -91
  66. package/dist/modules/order/index.d.ts +18 -5
  67. package/dist/modules/order/index.js +5 -5
  68. package/dist/modules/order/lifecycle.d.ts +353 -0
  69. package/dist/modules/order/lifecycle.js +1109 -0
  70. package/dist/modules/order/manager.d.ts +277 -20
  71. package/dist/modules/order/manager.js +680 -64
  72. package/dist/modules/order/placement_lock.d.ts +102 -0
  73. package/dist/modules/order/placement_lock.js +222 -0
  74. package/dist/modules/order/strategy.js +13 -1
  75. package/dist/modules/order/sync_engine.d.ts +74 -114
  76. package/dist/modules/order/sync_engine.js +254 -198
  77. package/dist/modules/order/utils/math.d.ts +29 -4
  78. package/dist/modules/order/utils/math.js +61 -4
  79. package/dist/modules/order/utils/order.d.ts +106 -37
  80. package/dist/modules/order/utils/order.js +256 -81
  81. package/dist/modules/order/utils/system.d.ts +99 -6
  82. package/dist/modules/order/utils/system.js +249 -35
  83. package/dist/modules/order/utils/validate.d.ts +7 -1
  84. package/dist/modules/order/utils/validate.js +48 -2
  85. package/dist/modules/outcome.d.ts +54 -0
  86. package/dist/modules/outcome.js +51 -0
  87. package/dist/modules/settings_merge.d.ts +4 -0
  88. package/dist/modules/settings_merge.js +9 -0
  89. package/dist/modules/timing_policy.d.ts +82 -0
  90. package/dist/modules/timing_policy.js +244 -0
  91. package/dist/modules/types.d.ts +149 -22
  92. package/dist/scripts/analyze-credit.js +54 -17
  93. package/dist/scripts/analyze-orders.d.ts +4 -2
  94. package/dist/scripts/analyze-orders.js +113 -34
  95. package/dist/scripts/chart_targets.js +11 -15
  96. package/dist/scripts/test-credit-renewal.js +12 -5
  97. package/docs/COW_INVARIANTS.md +71 -8
  98. package/docs/DEXBOT_COMPARISON.md +6 -6
  99. package/docs/EVOLUTION.md +10 -8
  100. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  101. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  102. package/docs/GRID_RECONCILE.md +18 -13
  103. package/docs/LOGGING.md +25 -1
  104. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
  105. package/docs/README.md +23 -2
  106. package/docs/WORKFLOW.md +9 -3
  107. package/docs/architecture.md +68 -13
  108. package/docs/developer_guide.md +25 -8
  109. package/modules/README.md +6 -0
  110. package/package.json +3 -3
  111. package/scripts/README.md +16 -0
  112. package/scripts/pdev.sh +14 -1
  113. package/scripts/pmain.sh +23 -8
  114. package/scripts/ptest.sh +7 -0
  115. package/tests/README.md +30 -1
@@ -86,8 +86,11 @@
86
86
  * DEFAULT_NODES: List of BitShares nodes for redundancy
87
87
  * HEALTH_CHECK_INTERVAL_MS, HEALTH_CHECK_TIMEOUT_MS, MAX_PING_MS
88
88
  * BLACKLIST_THRESHOLD: Failures before node is blacklisted
89
+ * FAILURE_STRIKE_DECAY_MS: How long a live-transport strike lasts
90
+ * FLAP_WINDOW_MS / FLAP_HALF_LIFE_MS / FLAP_PENALTY_MS_PER_DROP /
91
+ * FLAP_PENALTY_MAX_MS: time-decayed connection-churn penalty
89
92
  * EXPECTED_CHAIN_ID: BitShares mainnet chain ID validation
90
- * SELECTION_STRATEGY: Node selection algorithm (latency-based)
93
+ * SELECTION_STRATEGY: Node selection algorithm (latency + churn penalty)
91
94
  *
92
95
  * 13. UPDATER - Version checking and update notification
93
96
  * ACTIVE, REPOSITORY_URL, BRANCH, SCHEDULE
@@ -139,6 +142,7 @@ import { BUILD_DIR } from './utils/build_dir.js';
139
142
  import { readGeneralSettings } from './general_settings.js';
140
143
  import { mergeSettings, buildNodesView } from './settings_merge.js';
141
144
  import { getErrorMessage } from './utils/errors.js';
145
+ import { DEFAULT_FLAP_HALF_LIFE_MS, DEFAULT_FLAP_PENALTY_MAX_MS, DEFAULT_FLAP_PENALTY_MS_PER_DROP, DEFAULT_FLAP_WINDOW_MS, } from './node_flap_score.js';
142
146
  const ORDER_TYPES = Object.freeze({
143
147
  SELL: 'sell',
144
148
  BUY: 'buy',
@@ -231,7 +235,12 @@ let TIMING = {
231
235
  // BTS acquisition for non-BTS pairs: min cooldown between acquisition attempts (minutes)
232
236
  BTS_ACQUIRE_COOLDOWN_MIN: 60,
233
237
  // Fill processing timing
234
- FILL_DEDUPE_WINDOW_MS: 5000, // 5 seconds - window for deduplicating same fill events
238
+ // Claim LEASE for a fill accepted into the queue but not yet booked
239
+ // (deferral, crash). It is NOT the dedupe authority: the processed-fill
240
+ // store refuses a booked key while it is retained, regardless of age;
241
+ // FILL_RECORD_RETENTION_MS bounds that retention, it is not an expiry
242
+ // (docs/FILL_PIPELINE.md stage 2).
243
+ FILL_DEDUPE_WINDOW_MS: 5000,
235
244
  FILL_RECORD_RETENTION_MS: 7 * 24 * 60 * 60 * 1000, // 7 days - how long to keep persisted fill records (was 1h, increased to close double-credit window on restarts >1h apart)
236
245
  PROCESSED_FILL_PERSIST_BATCH_MS: 250, // 250ms - coalesce processed-fill persistence writes under burst load
237
246
  PROCESSED_FILL_PERSIST_BATCH_SIZE: 25, // Flush immediately once this many processed fills are queued
@@ -300,6 +309,42 @@ let TIMING = {
300
309
  // bound (FILL_BROADCAST_DEFER_MAX_MS, derived below) are expressed in
301
310
  // terms of it, so they cannot be tuned out of agreement.
302
311
  BROADCAST_STALE_CLEAR_MS: 120000, // 120 seconds
312
+ // PENDING_BROADCAST_TTL_MS: a CREATE recorded as pending (uncertain
313
+ // broadcast) protects its slot/price from a duplicate CREATE. The entry is
314
+ // normally cleared when the batch resolves; if that resolution is lost
315
+ // (crash, hung poll) a stale entry must not block creates forever. After
316
+ // this TTL it is dropped and the next caught-up read re-verifies the level
317
+ // against the chain instead.
318
+ PENDING_BROADCAST_TTL_MS: 30 * 60 * 1000, // 30 minutes
319
+ // BATCH_INFLIGHT_STALE_MS / RECOVERY_INFLIGHT_STALE_MS: leak watchdogs for
320
+ // the bot-level pipeline counters. A parked fill queue for minutes with no
321
+ // progress (2026-11-03: _batchInFlight stuck ~2.5 min, queue depth 10) must
322
+ // be surfaced and, when nothing actually holds placement, cleared so the
323
+ // pipeline can recover. Generous: a legitimate create-group reconcile can
324
+ // take minutes. Never force-clear while placement is still held (a live
325
+ // batch owns it).
326
+ BATCH_INFLIGHT_STALE_MS: 10 * 60 * 1000,
327
+ RECOVERY_INFLIGHT_STALE_MS: 10 * 60 * 1000,
328
+ // PLACEMENT_STALE_CLEAR_MS: a placement lease (COW / reconcile / drain)
329
+ // has no natural deadline — a hung chain call or a missed release can hold
330
+ // the exclusive region forever. Fills and rebalances defer while it is
331
+ // held, so the watchdog force-releases a region held far longer than any
332
+ // legitimate path. Sized above the longest observed reconcile (~8 min) and
333
+ // the COW batch ceiling; unlike the broadcast refcount there is no
334
+ // "re-arm on progress" signal, so err generous.
335
+ PLACEMENT_STALE_CLEAR_MS: 15 * 60 * 1000,
336
+ // CHAIN_SIZE_APPLIED_MARKER_TTL_MS: a sync-pass-1 "size already applied"
337
+ // marker is only meaningful until the matching fill history arrives. Stale
338
+ // markers are ignored/dropped so they cannot suppress an unrelated later
339
+ // fill of the same order.
340
+ CHAIN_SIZE_APPLIED_MARKER_TTL_MS: 5 * 60 * 1000,
341
+ // STRUCTURAL_REBUILD_DEFER_MAX_MS: fill-driven rebalances defer while a
342
+ // structural rebuild runs. A hung rebuild (e.g. a 10-minute reconcile) must
343
+ // not defer them silently for its whole duration: after this bound, log at
344
+ // warn every tick so the stall is visible to operators. The deferral
345
+ // itself is kept (correctness beats availability: planning mid-rebuild is
346
+ // exactly the duplicate class), but it is no longer silent.
347
+ STRUCTURAL_REBUILD_DEFER_MAX_MS: 3 * 60 * 1000,
303
348
  // BROADCAST_DEFER_SAFETY_MARGIN_MS: headroom added to
304
349
  // BROADCAST_STALE_CLEAR_MS when deriving FILL_BROADCAST_DEFER_MAX_MS, so a
305
350
  // region that is still considered live by the stale-clear watchdog cannot
@@ -915,8 +960,17 @@ let FILL_PROCESSING = {
915
960
  // into gapSlots+1-op transactions, so this only removes the intermediate
916
961
  // plan/broadcast cycles (Stale-Restart #5). Default OFF: opt-in rollout
917
962
  // for the live boundary engine, overridable per bot via
918
- // `fillProcessing.COALESCE_BACKLOG_REPLAY` in general settings.
963
+ // `fillProcessing.COALESCE_BACKLOG_REPLAY` in bots.json (or globally via
964
+ // FILL_PROCESSING in general.settings.json).
919
965
  COALESCE_BACKLOG_REPLAY: false,
966
+ // GRID_BLOCKED_ESCALATE_CYCLES: how many consecutive attempts a grid update
967
+ // may be refused with an UNREADABLE pipeline state before the blocker
968
+ // escalation fires a structural resync. A cycle count, not a timing window:
969
+ // it is deliberately not a TIMING entry (see modules/timing_policy.ts) and
970
+ // must not be turned into one. Only `unknown-blocker` escalates — a busy
971
+ // pipeline (fills in flight, an unresolved broadcast, a held placement
972
+ // region) is normal work and is bounded by its own watchdog.
973
+ GRID_BLOCKED_ESCALATE_CYCLES: 12,
920
974
  // MAX_CONSECUTIVE_CONSUMER_FAILURES: Threshold for the _consumeFillQueue
921
975
  // watchdog. Below this count, the consumer re-schedules on every failure
922
976
  // via setImmediate. At or above this count, the consumer switches to
@@ -1010,15 +1064,30 @@ let NODE_MANAGEMENT = {
1010
1064
  BLACKLIST_THRESHOLD: 3, // Failures before blacklist
1011
1065
  BLACKLIST_COOLDOWN_MS: 24 * 60 * 60 * 1000, // 24 hours before retrying blacklisted nodes
1012
1066
  FAILURE_REPORT_COOLDOWN_MS: 1000, // Min ms between failure count increments (prevents rapid-fire blacklisting)
1013
- // Consecutive successful health probes required before a node whose last
1014
- // failure came from the live transport (not a health check) gets its
1015
- // failure ledger reset. Prevents a single "is it up?" probe from erasing
1016
- // live-transport strikes, so flapping nodes still reach BLACKLIST_THRESHOLD.
1017
- LIVE_FAILURE_HEALTH_SUCCESS_STREAK: 2,
1067
+ // Strike decay: a live-transport failure counts as a strike, and strikes
1068
+ // fade out over this window instead of being erased by a successful health
1069
+ // probe. With a 4h probe interval and a once-a-day flapper, the old
1070
+ // success-streak reset wiped every strike before it could reach
1071
+ // BLACKLIST_THRESHOLD (every failure logged "attempt 1/3"), so a node that
1072
+ // drops its socket daily was selected forever. A strike is fully forgiven
1073
+ // only after this long without a new failure.
1074
+ FAILURE_STRIKE_DECAY_MS: 24 * 60 * 60 * 1000, // 24 hours
1075
+ // Flapping (connection-churn) scoring used by node selection: a node ranks
1076
+ // on `latency + penalty`, where the penalty is the time-decayed weight of
1077
+ // its recent transport drops. Zero recent drops means ping alone decides.
1078
+ // Values come from modules/node_flap_score.ts so the ranking maths and the
1079
+ // defaults here can never drift apart.
1080
+ FLAP_WINDOW_MS: DEFAULT_FLAP_WINDOW_MS, // only the trailing day counts
1081
+ FLAP_HALF_LIFE_MS: DEFAULT_FLAP_HALF_LIFE_MS, // a drop's weight halves every 12h
1082
+ FLAP_PENALTY_MS_PER_DROP: DEFAULT_FLAP_PENALTY_MS_PER_DROP, // +5s effective latency per fresh drop
1083
+ FLAP_PENALTY_MAX_MS: DEFAULT_FLAP_PENALTY_MAX_MS, // cap so a degraded node stays a last resort
1018
1084
  // Expected chain ID (BitShares mainnet)
1019
1085
  EXPECTED_CHAIN_ID: '4018d7844c78f6a6c41c6a552b898022310fc5dec06da467ee7905a8dad512c8',
1020
- // Selection strategy
1021
- SELECTION_STRATEGY: 'latency' // latency-based selection
1086
+ // Selection strategy. 'latency' means latency + the time-decayed flap
1087
+ // penalty (see FLAP_* above): the fastest node wins only while it is also
1088
+ // stable, which is what stops a cheap Cloudflare endpoint that drops every
1089
+ // few hours from outranking a slightly slower endpoint that never drops.
1090
+ SELECTION_STRATEGY: 'latency'
1022
1091
  };
1023
1092
  // Pipeline timeout configuration
1024
1093
  let PIPELINE_TIMING = {
@@ -421,6 +421,28 @@ declare class DEXBot implements BotLike {
421
421
  * @returns {string|null} Fallback key or null
422
422
  */
423
423
  _buildOrphanFillFallbackKey(fill: FillLike): string | null;
424
+ /**
425
+ * Claim a fill key for this cycle, or report that it was already handled.
426
+ *
427
+ * Two authorities, in this order:
428
+ * 1. **The processed-fill store** — booked keys. Checked first and without
429
+ * any clock, because "already credited" does not expire. Before P2 a
430
+ * booked key older than the lease window was accepted again here and
431
+ * only refused later by accounting, so the replay still paid for queue
432
+ * churn and a FILL DETECTED log.
433
+ * 2. **The claim lease** — fills accepted but not yet booked (deferral,
434
+ * crash). Its TTL (`FILL_DEDUPE_WINDOW_MS`) is a lease, not the dedupe
435
+ * authority; the store refuses a booked key while retained, at any age.
436
+ *
437
+ * Claims are released on every path that does not book (requeue, orphan
438
+ * adoption, stale-totals deferral), so a held claim means "in flight".
439
+ *
440
+ * @param {string} fillKey - Chain fill identity (`orderId:blockNum:historyId`)
441
+ * @param {Set<string>} processedFillKeys - Per-cycle key set
442
+ * @param {string} [label] - Log prefix
443
+ * @param {string} [orderId] - Chain order id, for the log only
444
+ * @returns {boolean} true when this cycle may process the fill
445
+ */
424
446
  _isNewFillKey(fillKey: string, processedFillKeys: Set<string>, label?: string, orderId?: string): boolean;
425
447
  /**
426
448
  * Apply replay-safe fill accounting for tracked fills (those with a valid grid order).
@@ -728,12 +750,7 @@ declare class DEXBot implements BotLike {
728
750
  * @param {Array<Object>} opContexts - Original opContexts from the failed batch
729
751
  * @returns {Promise<Object>} Result object compatible with batch return shape
730
752
  */
731
- _reconcileAfterUncertainBroadcast(err: unknown, opContexts: OpPhase[], options?: UnknownRecord): Promise<UnknownRecord | {
732
- executed: boolean;
733
- hadRotation: boolean;
734
- uncertain: boolean;
735
- ambiguousRead: boolean;
736
- }>;
753
+ _reconcileAfterUncertainBroadcast(err: unknown, opContexts: OpPhase[], options?: UnknownRecord): Promise<UnknownRecord>;
737
754
  /**
738
755
  * Execute operations with retry on BroadcastUncertainError.
739
756
  * The daemon already retries internally against a 25s deadline. If it
@@ -83,6 +83,7 @@ import { path } from './path_api.js';
83
83
  import * as Format from './order/format.js';
84
84
  import cowRuntime from './dexbot_cow_runtime.js';
85
85
  import { ProcessedFillStore } from './order/processed_fill_store.js';
86
+ import { isFillBooked } from './order/fill_ledger.js';
86
87
  import { TIMING, DAEMON_CODES, FILL_PROCESSING, } from './constants.js';
87
88
  import { normalizeBotEntry } from './bot_settings.js';
88
89
  import { createDefaultBotMetrics } from './bot_defaults.js';
@@ -610,7 +611,36 @@ class DEXBot {
610
611
  _buildOrphanFillFallbackKey(fill) {
611
612
  return DexbotFillRuntime.buildOrphanFillFallbackKey(this, fill);
612
613
  }
614
+ /**
615
+ * Claim a fill key for this cycle, or report that it was already handled.
616
+ *
617
+ * Two authorities, in this order:
618
+ * 1. **The processed-fill store** — booked keys. Checked first and without
619
+ * any clock, because "already credited" does not expire. Before P2 a
620
+ * booked key older than the lease window was accepted again here and
621
+ * only refused later by accounting, so the replay still paid for queue
622
+ * churn and a FILL DETECTED log.
623
+ * 2. **The claim lease** — fills accepted but not yet booked (deferral,
624
+ * crash). Its TTL (`FILL_DEDUPE_WINDOW_MS`) is a lease, not the dedupe
625
+ * authority; the store refuses a booked key while retained, at any age.
626
+ *
627
+ * Claims are released on every path that does not book (requeue, orphan
628
+ * adoption, stale-totals deferral), so a held claim means "in flight".
629
+ *
630
+ * @param {string} fillKey - Chain fill identity (`orderId:blockNum:historyId`)
631
+ * @param {Set<string>} processedFillKeys - Per-cycle key set
632
+ * @param {string} [label] - Log prefix
633
+ * @param {string} [orderId] - Chain order id, for the log only
634
+ * @returns {boolean} true when this cycle may process the fill
635
+ */
613
636
  _isNewFillKey(fillKey, processedFillKeys, label = '', orderId = '') {
637
+ if (isFillBooked(this._processedFillStore, fillKey)) {
638
+ if (label) {
639
+ const idSuffix = orderId ? ` for ${orderId}` : '';
640
+ this.manager?.logger?.log?.(`${label} Skipping fill${idSuffix}: ${fillKey} is already booked`, 'debug');
641
+ }
642
+ return false;
643
+ }
614
644
  const now = Date.now();
615
645
  if (this._recentlyQueuedFills.has(fillKey)) {
616
646
  const lastProcessed = this._recentlyQueuedFills.get(fillKey) ?? 0;
@@ -1115,6 +1145,14 @@ class DEXBot {
1115
1145
  if (typeof this.manager?.pauseFundRecalc === 'function') {
1116
1146
  this.manager.pauseFundRecalc();
1117
1147
  }
1148
+ // One absolute boundary re-anchor per drained fill batch: each fill
1149
+ // event re-anchoring + a fresh COW plan amplified churn (6 re-anchors
1150
+ // in ~1 min). The crawl still runs per chunk; the absolute anchor is
1151
+ // the expensive geometry jump. A BUDGET (not a boolean) is nest-safe:
1152
+ // a nested/overlapping fill cycle restores the outer budget instead of
1153
+ // silently re-enabling multiple anchors.
1154
+ const prevReanchorBudget = this.manager._boundaryReanchorBudget;
1155
+ this.manager._boundaryReanchorBudget = 1;
1118
1156
  let anyDeferred = false;
1119
1157
  try {
1120
1158
  const activeSell = this.manager?.config?.coreOrders?.sell ?? 1;
@@ -1183,6 +1221,12 @@ class DEXBot {
1183
1221
  if (this.manager) {
1184
1222
  delete this.manager._boundaryShiftBudget;
1185
1223
  delete this.manager._boundaryShiftBudgetBase;
1224
+ if (prevReanchorBudget === undefined) {
1225
+ delete this.manager._boundaryReanchorBudget;
1226
+ }
1227
+ else {
1228
+ this.manager._boundaryReanchorBudget = prevReanchorBudget;
1229
+ }
1186
1230
  }
1187
1231
  if (typeof this.manager?.resumeFundRecalc === 'function') {
1188
1232
  await this.manager.resumeFundRecalc();
@@ -20,6 +20,97 @@ import { isLastFillGuardBlocked } from './order/utils/system.js';
20
20
  * keeps the plan-build authority (fail-open to the stamp, never to the guard).
21
21
  */
22
22
  export declare function isEvacuationStampStillValid(liveBoundary: unknown, liveGapSlots: unknown, sourceId: unknown, destId: unknown, orderType: unknown): boolean;
23
+ /**
24
+ * Detect a live-rail conflict: the resting BUY/SELL rails cannot coexist with
25
+ * a `gapSlots`-wide spread band, i.e. no boundary value satisfies
26
+ * `maxBuy <= boundary` and `minSell >= boundary + gapSlots + 1` at once.
27
+ *
28
+ * Why this matters for gap evacuation: the stale-stamp check below refuses an
29
+ * evacuation whose source is no longer in-band under the LIVE (pre-commit)
30
+ * boundary. That is correct when the live geometry is itself consistent (the
31
+ * 2026-10-30 incident: plan boundary 124 wanted buys 125-128 evacuated, live
32
+ * 128 kept them on the rail, the bid edge survived). It is WRONG when the live
33
+ * rails already overlap: then the batch's boundary retreat is FORCED — some
34
+ * order has to move — and refusing the evacuation leaves the stranded order
35
+ * inside the band permanently (observed class: a buy fill inside the band
36
+ * crawls the boundary down, the retreat strands the two buys above it, the
37
+ * guard skips their rotation as stale, the rail clamp cannot move the boundary
38
+ * back because the sell rail caps it, and the 4-slot spread band keeps two
39
+ * live buys forever → real spread 1.2% against a 2.0% target).
40
+ *
41
+ * The test is boundary-independent (a crossing is a crossing at any boundary),
42
+ * so it cannot be satisfied by simply moving the boundary: only an evacuation
43
+ * resolves it. Ladder positions use the same live-price resolution as
44
+ * deriveRailBoundary, so a stale slot id cannot fake a rail member.
45
+ *
46
+ * @param manager - Manager exposing orders/assets/_genesis
47
+ * @param gapSlots - Gap-band width (slots)
48
+ * @returns `{ crossed, maxBuyIdx, minSellIdx, upper }`; `crossed` is false when
49
+ * either rail is empty (one-sided book proves nothing) or geometry is
50
+ * unknown (fail closed: keep the stale-stamp refusal).
51
+ */
52
+ export declare function liveRailsConflictWithGap(manager: unknown, gapSlots: unknown): {
53
+ crossed: boolean;
54
+ maxBuyIdx: number | null;
55
+ minSellIdx: number | null;
56
+ upper: number | null;
57
+ };
58
+ /**
59
+ * Decide whether a stale-stamp refusal of a gap-evacuation rotation must yield
60
+ * to the forced-retreat allowance. Single authority for the three call sites
61
+ * (stamped build branch, unstamped build branch, final pivot gate) so the
62
+ * conditions can never drift apart.
63
+ *
64
+ * Two conditions, both required:
65
+ * 1. The stamp could actually be EVALUATED: an unparseable source/dest id is
66
+ * not a geometry disagreement — `isEvacuationStampStillValid` refuses those
67
+ * too, and overriding that would ship a rotation whose geometry nobody
68
+ * proved. Never override an unprovable stamp.
69
+ * 2. The live rails already conflict (see liveRailsConflictWithGap): some
70
+ * order must move at ANY boundary, so the plan's retreat is the only
71
+ * consistent geometry and the pre-commit "still on the rail" reading is not
72
+ * authoritative.
73
+ *
74
+ * @param manager - Manager exposing orders/assets/_genesis
75
+ * @param gapSlots - LIVE gap-band width (slots)
76
+ * @param sourceId - Evacuation source slot id
77
+ * @param destId - Evacuation destination slot id
78
+ * @returns The conflict record when the allowance applies, otherwise null.
79
+ */
80
+ export declare function forcedRetreatJustifiesEvacuation(manager: unknown, gapSlots: unknown, sourceId: unknown, destId: unknown): {
81
+ crossed: boolean;
82
+ maxBuyIdx: number | null;
83
+ minSellIdx: number | null;
84
+ upper: number | null;
85
+ } | null;
86
+ /**
87
+ * Split pending price corrections into "drain now" and "held back because this
88
+ * batch supersedes them".
89
+ *
90
+ * A cancel-only gap-evacuation whose chain order the batch ROTATES is
91
+ * superseded by the plan: the rotation moves that order onto its rail in place,
92
+ * and cancelling it first destroys the batch's own source. Observed live on a
93
+ * stranded 4-slot band: the teeth queued cancels for the two rotation sources,
94
+ * the pre-batch drain executed them, and the UPDATE batch was rejected
95
+ * pre-broadcast ("2 target(s) missing on chain") → structural resync + full grid
96
+ * reload + two CREATEs, instead of two in-place price updates.
97
+ *
98
+ * Held entries are put back after the drain: if the rotation is dropped or the
99
+ * batch aborts they stay queued (their own staleness check drops them once the
100
+ * slot no longer owns the order).
101
+ *
102
+ * @param entries - `manager.ordersNeedingPriceCorrection`
103
+ * @param actions - The batch's planned actions
104
+ * @returns `{ kept, held }` (both empty-safe)
105
+ */
106
+ export declare function splitEvacuationCancelsSupersededByRotations(entries: unknown, actions: unknown): {
107
+ kept: Array<{
108
+ [key: string]: unknown;
109
+ }>;
110
+ held: Array<{
111
+ [key: string]: unknown;
112
+ }>;
113
+ };
23
114
  import * as workingGridModule from './order/working_grid.js';
24
115
  declare const WorkingGrid: typeof workingGridModule.WorkingGrid;
25
116
  import type { BotLike, OrderManagerLike, ManagedOrder, ChainOrder, UnknownRecord, CowAction } from './types.js';
@@ -176,12 +267,7 @@ declare function findChainOrderForSlot(bot: BotLike, chainOrders: ChainOrderLike
176
267
  * @param {Object} [options]
177
268
  * @returns {Promise<Object>}
178
269
  */
179
- declare function reconcileAfterUncertainBroadcast(bot: BotLike, err: unknown, opContexts: OpPhase[], options?: JsonObj): Promise<UnknownRecord | {
180
- executed: boolean;
181
- hadRotation: boolean;
182
- uncertain: boolean;
183
- ambiguousRead: boolean;
184
- }>;
270
+ declare function reconcileAfterUncertainBroadcast(bot: BotLike, err: unknown, opContexts: OpPhase[], options?: JsonObj): Promise<UnknownRecord>;
185
271
  /**
186
272
  * Restore discarded CREATE slots to creation-uncertain state and clear
187
273
  * their pending entries; residual pending entries that survive the
@@ -360,7 +446,8 @@ declare function isSpreadCorrectionBypassAllowed(bot: BotLike): boolean;
360
446
  declare function refreshLastFillPivotFromQueue(bot: BotLike): boolean;
361
447
  /**
362
448
  * Build COW actions array from a simple plan object.
363
- * @param {import('./dexbot_class.js').DEXBot} bot
449
+ * @param {import('./dexbot_class.js').DEXBot} _bot - Bot whose manager supplies the frozen
450
+ * boundary/gap geometry the plan stamp carries (plan values win when set).
364
451
  * @param {Object|Array} plan
365
452
  * @returns {Array}
366
453
  */
@@ -398,8 +485,12 @@ declare function toRefillSlotIdSet(refillSlotIds: unknown): Set<string>;
398
485
  * Unrelated vetoes (skip ids outside the refill set) never pin geometry.
399
486
  * The grid still commits; only the boundary value is held (same discipline
400
487
  * as the overrun-hold in validateBoundaryCommit).
488
+ *
489
+ * `refillSide` (BUY/SELL) scopes the hold to the boundary's PROMOTION
490
+ * direction; a fill-driven retreat, or a wire whose side cannot be resolved
491
+ * (null), keeps the legacy hold.
401
492
  */
402
- declare function resolveRefillBoundaryHold(workingBoundary: unknown, committedBoundary: unknown, skippedUpdateSlotIds: Iterable<string> | null | undefined, clampedUpdateSlotIds: Iterable<string> | null | undefined, refillSlotIds: unknown, skippedCreateSlotIds?: Iterable<string> | null | undefined): {
493
+ declare function resolveRefillBoundaryHold(workingBoundary: unknown, committedBoundary: unknown, skippedUpdateSlotIds: Iterable<string> | null | undefined, clampedUpdateSlotIds: Iterable<string> | null | undefined, refillSlotIds: unknown, skippedCreateSlotIds?: Iterable<string> | null | undefined, refillSide?: unknown): {
403
494
  effectiveBoundary: unknown;
404
495
  heldRefillSlotIds: string[];
405
496
  };
@@ -464,6 +555,35 @@ export declare function deriveRailBoundary(manager: OrderManagerLike, opContexts
464
555
  */
465
556
  declare function trackBoundaryHold(manager: OrderManagerLike, held: boolean, keptBoundary: unknown, plannedBoundary: unknown, heldSlotIds: string[]): number;
466
557
  declare function updateOrdersOnChainBatchCOW(bot: BotLike, cowResult: CowResult, options?: JsonObj): Promise<JsonObj>;
558
+ /**
559
+ * Converge master with the chain after a COW commit was refused (master moved
560
+ * during broadcast) or an uncertain broadcast was poll-confirmed.
561
+ *
562
+ * Preferred path (when the broadcast result is available): re-read the exact
563
+ * on-chain orders BY ID — every id master already tracks plus the batch's
564
+ * fresh CREATE ids. get_objects returns the complete, authoritative set
565
+ * regardless of account size, so syncFromOpenOrders converges master instead
566
+ * of dropping the freshest creates (which previously left permanent orphans
567
+ * and tripped the fund invariant). This is fully immune to the
568
+ * get_full_accounts window truncation that broke the old window-read path.
569
+ *
570
+ * Fallback (no broadcast result, e.g. uncertain paths, or by-id read
571
+ * unavailable): window read. A truncated read is ambiguous — only the
572
+ * freshest orders are dropped — so it MUST NOT drive adoption; we return false
573
+ * and let the caller keep pending-broadcast protection + structural resync.
574
+ *
575
+ * @param {unknown} bot
576
+ * @param {unknown} chainOrders - chain_orders module (has readOpenOrdersWithMetaSafe + batchReadOrders)
577
+ * @param {string} logPrefix
578
+ * @param {Object} [opts]
579
+ * @param {unknown} [opts.placedResults] - broadcast result carrying operation_results
580
+ * @param {unknown[]} [opts.placedContexts] - opContexts aligned with operation_results
581
+ * @param {string[]} [opts.polledCreateIds] - fresh CREATE chain ids confirmed by
582
+ * the uncertain-broadcast poll (no broadcast result exists on that path);
583
+ * routes the poll call sites through the by-id path with its lagging-create
584
+ * retry instead of the unguarded window fallback
585
+ * @returns {Promise<boolean>} true if master was adopted from the chain
586
+ */
467
587
  declare function adoptPlacedBatchFromChain(bot: BotLike, chainOrders: typeof chainOrdersModule, logPrefix: string, opts?: JsonObj): Promise<boolean>;
468
588
  /**
469
589
  * Resolve the LAST-FILL guard pivot to an ON-GRID price.