dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -13,7 +13,7 @@ const { readOpenOrdersWithMetaSafe } = chainOrdersModule;
13
13
  import { BroadcastUncertainError as BroadcastUncertainErrorBinding } from './dexbot_credential_client.js';
14
14
  const BroadcastUncertainError = BroadcastUncertainErrorBinding;
15
15
  import * as orderUtils from './order/utils/order.js';
16
- import { sleep, setLastFillPivot } from './order/utils/system.js';
16
+ import { sleep, setLastFillPivot, fireStructuralResync, evaluateSpreadCorrectionReadiness, resolveLastFillGuardReference } from './order/utils/system.js';
17
17
  const { buildCreateOrderArgs, buildCreateOpFingerprint, extractBatchOperationResults, formatUnmatchedChainOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, buildOutsideInPairGroups, isOrderPlaced, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, } = orderUtils;
18
18
  import * as validate from './order/utils/validate.js';
19
19
  const { validateCreateTargetSlots, evaluateCommit, hasExecutableActions, stampGapEvacuationRotation } = validate;
@@ -31,10 +31,20 @@ import { parseSlotIndex } from './order/utils/slot.js';
31
31
  * keeps the plan-build authority (fail-open to the stamp, never to the guard).
32
32
  */
33
33
  export function isEvacuationStampStillValid(liveBoundary, liveGapSlots, sourceId, destId, orderType) {
34
- const b = Number(liveBoundary);
35
- const g = Number(liveGapSlots);
36
34
  if (orderType !== ORDER_TYPES.BUY && orderType !== ORDER_TYPES.SELL)
37
35
  return false;
36
+ // Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0 and
37
+ // Number('') === 0 are finite and would read an unknown live geometry as
38
+ // boundary 0, falsely DISPROVING the stamp and downgrading the rotation to
39
+ // the live guard — the opposite of the documented "non-finite geometry
40
+ // keeps plan-build authority" contract (undefined already fails open via
41
+ // NaN). Same Number(null)===0 trap guarded elsewhere in the COW runtime.
42
+ if (liveBoundary === null || liveBoundary === undefined || liveBoundary === '')
43
+ return true;
44
+ if (liveGapSlots === null || liveGapSlots === undefined || liveGapSlots === '')
45
+ return true;
46
+ const b = Number(liveBoundary);
47
+ const g = Number(liveGapSlots);
38
48
  if (!Number.isFinite(b) || !Number.isFinite(g) || g < 0)
39
49
  return true;
40
50
  const srcIdx = parseSlotIndex(sourceId);
@@ -70,7 +80,7 @@ function hasSlotPriceCollision(items, targetPrice, precision, excludeId, predica
70
80
  return null;
71
81
  }
72
82
  import * as constantsModule from './constants.js';
73
- const { COW_ACTIONS, COW_PERFORMANCE, ORDER_STATES, ORDER_TYPES, REBALANCE_STATES, } = constantsModule;
83
+ const { COW_ACTIONS, COW_ORIGINS, COW_PERFORMANCE, ORDER_STATES, ORDER_TYPES, REBALANCE_STATES, } = constantsModule;
74
84
  import { acquireIfNotHeld } from './order/async_lock.js';
75
85
  import * as FormatModule from './order/format.js';
76
86
  const Format = FormatModule;
@@ -912,11 +922,22 @@ async function resyncIfUnreconciled(bot, err, pending, chainSnapshot, adopted, a
912
922
  // chain snapshot.
913
923
  const alreadyScheduled = bot._structuralGridResyncRunning || bot._structuralGridResyncTimer;
914
924
  if (!alreadyScheduled && chainSnapshot.length > 0) {
925
+ // "Unreconciled" must mean chain orders absent from MASTER, not merely
926
+ // absent from this batch's adopted set. Every resting order master
927
+ // already tracks is reconciled by definition; counting those as
928
+ // unreconciled forced a structural resync (grid rebuild + LAST-FILL
929
+ // pivot clear) after every uncertain broadcast on a populated grid.
915
930
  const reconciledOrderIds = new Set(adopted.map((a) => a.match?.id).filter(Boolean));
931
+ try {
932
+ const known = collectKnownOnChainOrderIds(bot.manager, null, null).masterIds;
933
+ for (const id of known)
934
+ reconciledOrderIds.add(id);
935
+ }
936
+ catch { /* best-effort: fall back to the adopted-only set */ }
916
937
  const unreconciledCount = chainSnapshot.filter((o) => !reconciledOrderIds.has(o.id)).length;
917
938
  if (unreconciledCount > 0) {
918
- bot.manager.logger.log(`[COW][UNCERTAIN] ${unreconciledCount} chain order(s) remain unreconciled after uncertain broadcast recovery. ` +
919
- `These may be legitimate pre-existing orders or leftovers from a prior cycle. Requesting structural resync.`, 'warn');
939
+ bot.manager.logger.log(`[COW][UNCERTAIN] ${unreconciledCount} chain order(s) unknown to master remain after uncertain ` +
940
+ `broadcast recovery (neither adopted nor tracked). Requesting structural resync.`, 'warn');
920
941
  await requestStructuralResync(bot, 'unreconciled orders after uncertain broadcast', {
921
942
  batchId: err?.batchId || null,
922
943
  pendingCount: pending.length,
@@ -1714,21 +1735,13 @@ function considerGridPriceInvariantEscalation(bot, slotId, price, inv, site) {
1714
1735
  `${Number.isFinite(actual) ? Format.formatPrice6(actual) : 'n/a'} ` +
1715
1736
  `(genesis ${Number.isFinite(expected) ? Format.formatPrice6(expected) : 'n/a'}); ` +
1716
1737
  `requesting structural resync to repair the slot`, 'error');
1717
- try {
1718
- const res = bot.manager.requestStructuralGridResync('grid-price-invariant-violation', {
1719
- slotId: String(slotId),
1720
- expected: Number.isFinite(expected) ? expected : null,
1721
- actual: Number.isFinite(actual) ? actual : null,
1722
- site,
1723
- streak,
1724
- });
1725
- res?.catch?.((err) => {
1726
- bot.manager?.logger?.log?.(`[GRID-PRICE-INVARIANT] Structural resync request failed: ${getErrorMessage(err)}`, 'error');
1727
- });
1728
- }
1729
- catch (err) {
1730
- bot.manager?.logger?.log?.(`[GRID-PRICE-INVARIANT] Structural resync request failed: ${getErrorMessage(err)}`, 'error');
1731
- }
1738
+ fireStructuralResync(bot, 'grid-price-invariant-violation', {
1739
+ slotId: String(slotId),
1740
+ expected: Number.isFinite(expected) ? expected : null,
1741
+ actual: Number.isFinite(actual) ? actual : null,
1742
+ site,
1743
+ streak,
1744
+ }, '[GRID-PRICE-INVARIANT] Structural resync request failed');
1732
1745
  return streak;
1733
1746
  }
1734
1747
  /**
@@ -1747,10 +1760,115 @@ function logGridPriceInvariantSummary(bot, stats, site) {
1747
1760
  }
1748
1761
  catch { /* summary is best-effort */ }
1749
1762
  }
1763
+ /**
1764
+ * P2 observability (advisory, never blocks): count a BUY emitted at or above
1765
+ * the last filled BUY pivot.
1766
+ *
1767
+ * This is the "re-stamp a just-filled BUY above the anchor" shape the
1768
+ * LAST-FILL-GUARD exists to block (`BUY > pivot*(1-half)`), so a counted
1769
+ * emission means the guard was bypassed (spread correction / stamped gap
1770
+ * evacuation) or the pivot was unjudgeable and the probe failed open. The
1771
+ * counter makes a bypass leak visible without changing placement policy —
1772
+ * the guard already owns enforcement, and turning this into a second gate
1773
+ * would re-introduce the reverted placement-guard class.
1774
+ *
1775
+ * Warns at most once per batch (keyed on `_currentCycleId`). Never throws.
1776
+ *
1777
+ * @returns {boolean} true when the emission was counted
1778
+ */
1779
+ function recordRestampBuyAboveAnchor(bot, price, type) {
1780
+ try {
1781
+ if (type !== ORDER_TYPES.BUY)
1782
+ return false;
1783
+ if (bot?.manager?._lastFilledType !== ORDER_TYPES.BUY)
1784
+ return false;
1785
+ const pivot = Number(bot?.manager?._lastFilledPrice);
1786
+ const p = Number(price);
1787
+ if (!Number.isFinite(pivot) || pivot <= 0 || !Number.isFinite(p) || p <= 0)
1788
+ return false;
1789
+ // At or above the pivot is the re-stamp shape; a lower BUY is the
1790
+ // legitimate rotation target (I3) and is not counted.
1791
+ if (p < pivot)
1792
+ return false;
1793
+ if (bot._metrics)
1794
+ bot._metrics.restampBuyAboveAnchorCount = (bot._metrics.restampBuyAboveAnchorCount || 0) + 1;
1795
+ // Warn at most once per batch. Stored as a single scalar (not a
1796
+ // per-cycle map key) so the flag cannot accumulate unbounded keys on
1797
+ // the bot across cycles.
1798
+ const cycleId = bot?._currentCycleId ?? 'na';
1799
+ const botRecord = bot;
1800
+ if (botRecord._lastRestampWarnCycleId !== cycleId) {
1801
+ botRecord._lastRestampWarnCycleId = cycleId;
1802
+ bot?.manager?.logger?.log?.(`[RESTAMP-BUY] BUY emitted at ${Format.formatPrice6(p)} at/above the last filled BUY ` +
1803
+ `${Format.formatPrice6(pivot)} (guard bypass or unjudgeable pivot); counted, not blocked. ` +
1804
+ `(reported once per batch)`, 'warn');
1805
+ }
1806
+ return true;
1807
+ }
1808
+ catch {
1809
+ return false;
1810
+ }
1811
+ }
1812
+ /**
1813
+ * Collect non-spread-correction CREATE/UPDATE destinations that sit inside
1814
+ * the plan's gap band.
1815
+ *
1816
+ * Mode C(a) SHADOW: the gap band is not unconditionally illegal — spread
1817
+ * correction legitimately places INTO it (the LAST-FILL-GUARD bypass exists
1818
+ * for exactly that) and gap evacuation moves an order OUT of it. Excluding
1819
+ * those origins leaves the genuinely suspicious set: a rail placement whose
1820
+ * destination geometry IS the spread. The result is counted/warned, never
1821
+ * blocked (see the guard call site for the revert-history rationale).
1822
+ *
1823
+ * Pure and never throws. A non-finite boundary/gap selects the empty set.
1824
+ *
1825
+ * @param {Array<Object>|null} actions - COW actions
1826
+ * @param {unknown} boundary - The PLAN's boundary (workingBoundary), not the committed one
1827
+ * @param {unknown} gapSlots - Gap slot count
1828
+ * @returns {string[]} destinations inside the gap band
1829
+ */
1830
+ function collectGapBandPlacementShadowSlots(actions, boundary, gapSlots) {
1831
+ try {
1832
+ // Explicit null/empty guard BEFORE Number(): Number(null) === 0 and
1833
+ // Number('') === 0 would otherwise read an unknown boundary as slot 0
1834
+ // and select a real gap band around it (same trap that
1835
+ // buildCowResultFromPlan guards for workingBoundary).
1836
+ if (boundary === null || boundary === undefined || boundary === '')
1837
+ return [];
1838
+ if (gapSlots === null || gapSlots === undefined || gapSlots === '')
1839
+ return [];
1840
+ const b = Number(boundary);
1841
+ const g = Number(gapSlots);
1842
+ if (!Number.isFinite(b) || !Number.isFinite(g) || !Array.isArray(actions))
1843
+ return [];
1844
+ const out = [];
1845
+ for (const action of actions) {
1846
+ if (action?.type !== COW_ACTIONS.CREATE && action?.type !== COW_ACTIONS.UPDATE)
1847
+ continue;
1848
+ const origin = action?.origin;
1849
+ if (origin === COW_ORIGINS.SPREAD_CORRECTION || origin === COW_ORIGINS.GAP_EVACUATION)
1850
+ continue;
1851
+ const destId = String(action?.newGridId || action?.id || action?.order?.id || '');
1852
+ if (!destId)
1853
+ continue;
1854
+ const idx = parseSlotIndex(destId);
1855
+ if (idx === null || idx === undefined)
1856
+ continue;
1857
+ if (!isSlotIndexInGapBand(idx, b, g))
1858
+ continue;
1859
+ out.push(destId);
1860
+ }
1861
+ return out;
1862
+ }
1863
+ catch {
1864
+ return [];
1865
+ }
1866
+ }
1750
1867
  /**
1751
1868
  * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
1752
- * last fill @x with increment i: BUY < x*(1 - i/2/100), SELL > x*(1 + i/2/100)
1753
- * e.g. x=1000, i=0.5% => BUY < 997.5, SELL > 1002.5
1869
+ * last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
1870
+ * SELL < x*(1 + i/2/100)
1871
+ * e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
1754
1872
  * Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
1755
1873
  * bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
1756
1874
  * bypass only via the violation-reducing allowance (origin='gap-evacuation',
@@ -1791,6 +1909,44 @@ function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, increme
1791
1909
  return { blocked: true, pivot, halfInc, threshold: sellThreshold };
1792
1910
  return { blocked: false, pivot: null, halfInc, threshold: null };
1793
1911
  }
1912
+ /**
1913
+ * Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
1914
+ *
1915
+ * The bypass exists so gap repair can close even after a recent fill (the
1916
+ * correction is tightening the spread, not chasing it). It must not become a
1917
+ * licence to place THROUGH the market the bot last traded at:
1918
+ *
1919
+ * 1. A real fill pivot (`lastFillPivotSource === 'fill'`) is always honored —
1920
+ * no bypass. A sell below the last fill (or a buy above it) is the
1921
+ * issue-#31 adverse fill.
1922
+ * 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
1923
+ * fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
1924
+ * A stale snapshot (known-unmatched chain orders, or an old sync) can hide
1925
+ * the real window edge, so the bypass is withheld and the guard applies.
1926
+ *
1927
+ * Exported for tests.
1928
+ * @param {Object} bot
1929
+ * @returns {boolean} True when the bypass may be used
1930
+ */
1931
+ function isSpreadCorrectionBypassAllowed(bot) {
1932
+ const mgr = bot?.manager;
1933
+ if (!mgr)
1934
+ return true; // no manager state ⇒ nothing for the guard to protect
1935
+ // ONE verdict with the planner (evaluateSpreadCorrectionReadiness): the
1936
+ // bypass is licensed only when the snapshot is trusted AND no real FILL
1937
+ // reference exists. The LAST-FILL-GUARD is fill-based, so a live market
1938
+ // price (which only strengthens the planner's crossing floor) must not
1939
+ // change this decision. A real fill denies it; a stale or known-unmatched
1940
+ // snapshot denies it too (the guard applies instead). Fail-closed (deny
1941
+ // bypass) if the gate throws — never less safe than applying the guard.
1942
+ try {
1943
+ const readiness = evaluateSpreadCorrectionReadiness(mgr);
1944
+ return readiness.snapshotTrusted && readiness.fillMarketRef == null;
1945
+ }
1946
+ catch {
1947
+ return false;
1948
+ }
1949
+ }
1794
1950
  /**
1795
1951
  * Refresh the LAST-FILL guard pivot from fills that arrived while the current
1796
1952
  * batch was being planned or broadcast but have not been ingested yet.
@@ -1952,9 +2108,9 @@ function buildActionsFromPlan(_bot, plan) {
1952
2108
  // per-action origin there is safe. Other plan origins keep riding
1953
2109
  // non-UPDATE actions unchanged.
1954
2110
  if (action?.type !== COW_ACTIONS.UPDATE) {
1955
- return planOrigin === 'gap-evacuation' ? { ...action } : { ...action, origin: planOrigin };
2111
+ return planOrigin === COW_ORIGINS.GAP_EVACUATION ? { ...action } : { ...action, origin: planOrigin };
1956
2112
  }
1957
- if (planOrigin !== 'gap-evacuation')
2113
+ if (planOrigin !== COW_ORIGINS.GAP_EVACUATION)
1958
2114
  return { ...action, origin: planOrigin };
1959
2115
  if (!hasFrozenGeometry)
1960
2116
  return { ...action, origin: planOrigin };
@@ -2059,7 +2215,8 @@ function buildCowResultFromPlan(bot, plan) {
2059
2215
  // Guard null/undefined explicitly: Number(null) === 0 would be treated as a
2060
2216
  // valid finite boundary (index 0), silently biasing role classification.
2061
2217
  const rawBoundary = plan?.boundaryIdx;
2062
- const requestedBoundary = rawBoundary != null ? Number(rawBoundary) : NaN;
2218
+ // Absent-aware: null/undefined/'' are unknown (NaN), never boundary 0.
2219
+ const requestedBoundary = Format.toKnownNumber(rawBoundary);
2063
2220
  const workingBoundary = Number.isFinite(requestedBoundary)
2064
2221
  ? requestedBoundary
2065
2222
  : bot.manager.boundaryIdx;
@@ -2071,8 +2228,16 @@ function buildCowResultFromPlan(bot, plan) {
2071
2228
  const toWorkingHole = (slot) => {
2072
2229
  try {
2073
2230
  const idx = parseSlotIndex(slot?.id);
2074
- const b = Number(workingBoundary);
2075
- const gapSlots = Number(bot?.manager?._gapSlots);
2231
+ // Explicit null/'' guard: the workingBoundary fallback (manager.boundaryIdx)
2232
+ // can be null, and Number(null) === 0 would misclassify slot 0 as a BUY
2233
+ // rail hole (same trap guarded for plan.boundaryIdx above).
2234
+ const b = (workingBoundary === null || workingBoundary === undefined || workingBoundary === '')
2235
+ ? NaN
2236
+ : Number(workingBoundary);
2237
+ const rawGapSlots = bot?.manager?._gapSlots;
2238
+ const gapSlots = (rawGapSlots === null || rawGapSlots === undefined || rawGapSlots === '')
2239
+ ? NaN
2240
+ : Number(rawGapSlots);
2076
2241
  if (idx !== null && idx !== undefined && Number.isFinite(b) && Number.isFinite(gapSlots) && gapSlots >= 0) {
2077
2242
  if (Number(idx) <= b)
2078
2243
  return toRailHolePlaceholder(slot, ORDER_TYPES.BUY);
@@ -2857,6 +3022,112 @@ async function runPreBroadcastGuards(bot, cowResult) {
2857
3022
  }
2858
3023
  };
2859
3024
  }
3025
+ // MODE C(b) — pre-broadcast UPDATE-target existence check off the
3026
+ // slot->orderId map. A tracked order that is already gone on chain makes a
3027
+ // limit_order_update abort the broadcast chunk ("Order does not exist …
3028
+ // cannot update") and leaves a partially-applied grid. Re-reading the
3029
+ // referenced ids right before broadcast turns that into a clean
3030
+ // pre-broadcast refusal + structural resync, so nothing is half-applied.
3031
+ const updateTargetIds = new Set();
3032
+ for (const action of actions) {
3033
+ if (action?.type === COW_ACTIONS.UPDATE && action.orderId)
3034
+ updateTargetIds.add(String(action.orderId));
3035
+ }
3036
+ if (updateTargetIds.size > 0 && typeof chainOrders.batchReadOrders === 'function') {
3037
+ try {
3038
+ const readResult = await chainOrders.batchReadOrders([...updateTargetIds], 3000);
3039
+ const readMap = readResult;
3040
+ // Fail OPEN on a non-Map result (tests/other accessors): only an
3041
+ // authoritative map can prove an order gone.
3042
+ if (readMap && typeof readMap.get === 'function') {
3043
+ const missing = [];
3044
+ for (const id of updateTargetIds) {
3045
+ if (!readMap.get(id))
3046
+ missing.push(id);
3047
+ }
3048
+ if (missing.length > 0 && typeof chainOrders.readSingleOrder === 'function') {
3049
+ // Second, independent read before an absence decision: a
3050
+ // node that has not yet seen a freshly created order can
3051
+ // return null from the batch read. Re-reading each candidate
3052
+ // individually cancels the absence when the order is found;
3053
+ // a failed re-read must not manufacture an absence (fail
3054
+ // open), so only a read that returns an explicit null is
3055
+ // treated as confirming the gap.
3056
+ const stillMissing = [];
3057
+ for (const id of missing) {
3058
+ let present = true;
3059
+ try {
3060
+ present = Boolean(await chainOrders.readSingleOrder(id, 3000));
3061
+ }
3062
+ catch { /* failed re-verify must not manufacture an absence */ }
3063
+ if (!present)
3064
+ stillMissing.push(id);
3065
+ }
3066
+ missing.length = 0;
3067
+ missing.push(...stillMissing);
3068
+ }
3069
+ if (missing.length > 0) {
3070
+ bot.manager.logger.log(`[COW] Rejecting UPDATE batch pre-broadcast: ${missing.length} target(s) missing on chain ` +
3071
+ `(${missing.slice(0, 8).join(', ')}${missing.length > 8 ? ', …' : ''}); ` +
3072
+ `grid/chain existence divergence — structural resync required`, 'error');
3073
+ popPushedWorkingGrid(bot, cowResult);
3074
+ await requestStructuralResync(bot, 'pre-broadcast update target missing on chain', { missingUpdateOrderIds: missing });
3075
+ return {
3076
+ proceed: false,
3077
+ result: {
3078
+ executed: false,
3079
+ aborted: true,
3080
+ reason: 'UPDATE_TARGET_MISSING',
3081
+ missingUpdateOrderIds: missing,
3082
+ hadRotation: false
3083
+ }
3084
+ };
3085
+ }
3086
+ }
3087
+ }
3088
+ catch (existenceErr) {
3089
+ // A failed/foreign read must never block a legitimate broadcast;
3090
+ // the chain's own rejection remains the backstop.
3091
+ bot.manager.logger.log(`[COW] Pre-broadcast UPDATE existence check failed (${getErrorMessage(existenceErr)}); ` +
3092
+ `proceeding (chain rejection remains the backstop)`, 'debug');
3093
+ }
3094
+ }
3095
+ // MODE C(a) — gap-band placement SHADOW check (observability + summary,
3096
+ // no placement change). A non-spread-correction CREATE/UPDATE whose
3097
+ // destination sits inside the plan's gap band is the Mode-C geometry that
3098
+ // the reverted P1/P2 cancellation nets used to mop up; enforcement is
3099
+ // deliberately NOT done here because spread correction legitimately places
3100
+ // INTO the band (the LAST-FILL-GUARD bypass exists for exactly that) and a
3101
+ // hard reject would re-open the P1-e2898e51 regression class. Count + warn
3102
+ // so the leak is measurable before any policy change.
3103
+ try {
3104
+ const planBoundaryValue = cowResult?.workingBoundary;
3105
+ const planBoundaryRaw = (planBoundaryValue === null || planBoundaryValue === undefined || planBoundaryValue === '')
3106
+ ? NaN
3107
+ : Number(planBoundaryValue);
3108
+ // Fall back to the committed boundary only when it is itself known:
3109
+ // Number(null) === 0 and Number('') === 0 must not silently become
3110
+ // slot 0 (same trap the helper guards).
3111
+ const managerBoundaryRaw = bot.manager?.boundaryIdx;
3112
+ const shadowBoundary = Number.isFinite(planBoundaryRaw)
3113
+ ? planBoundaryRaw
3114
+ : (managerBoundaryRaw != null && managerBoundaryRaw !== '' ? Number(managerBoundaryRaw) : NaN);
3115
+ // Absent-aware gap: Number(null) === 0 would defeat the helper's own
3116
+ // null guard by passing a collapsed 0 band before the helper sees it.
3117
+ const shadowGapSlots = Format.toKnownNumber(bot.manager?._gapSlots);
3118
+ const shadowSlots = collectGapBandPlacementShadowSlots(actions, shadowBoundary, shadowGapSlots);
3119
+ if (shadowSlots.length > 0) {
3120
+ if (bot._metrics) {
3121
+ bot._metrics.gapBandPlacementShadowCount =
3122
+ (bot._metrics.gapBandPlacementShadowCount || 0) + shadowSlots.length;
3123
+ }
3124
+ bot.manager.logger.log(`[COW-GAP-BAND] shadow: ${shadowSlots.length} non-spread-correction placement(s) ` +
3125
+ `inside the plan's gap band (boundary ${shadowBoundary}, gap ${shadowGapSlots}): ` +
3126
+ `${shadowSlots.slice(0, 8).join(', ')}${shadowSlots.length > 8 ? ', …' : ''} ` +
3127
+ `— counted for observability, NOT blocked`, 'warn');
3128
+ }
3129
+ }
3130
+ catch { /* shadow check must never break a batch */ }
2860
3131
  // Crossing-check candidate set (master + pending-broadcast + unmatched
2861
3132
  // chain orders). Built after the batch-level pending/unmatched guards so
2862
3133
  // it reflects any sync they triggered.
@@ -3109,8 +3380,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3109
3380
  // whose freeze picked up a pre-freeze queued fill look "moved" at the
3110
3381
  // gate — a spurious warn plus a redundant full re-check against the
3111
3382
  // identical pivot.
3112
- const frozenPivotAtBatchStart = bot.manager?._lastFilledPrice;
3113
- const frozenTypeAtBatchStart = bot.manager?._lastFilledType;
3383
+ // Same effective reference the per-action guard judges against (live
3384
+ // pivot, else the bot-scoped market fill) so the freeze cannot run cold
3385
+ // while the guard still blocks.
3386
+ const frozenRef = resolveLastFillGuardReference(bot.manager);
3387
+ const frozenPivotAtBatchStart = frozenRef.price;
3388
+ const frozenTypeAtBatchStart = frozenRef.type;
3114
3389
  for (const action of actions) {
3115
3390
  if (action.type === COW_ACTIONS.CANCEL) {
3116
3391
  try {
@@ -3203,8 +3478,9 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3203
3478
  try {
3204
3479
  const actionOrigin = action?.origin;
3205
3480
  const batchOrigin = cowResult?.origin;
3206
- const isCorrectionCreate = actionOrigin === 'spread-correction'
3207
- || (actionOrigin == null && batchOrigin === 'spread-correction');
3481
+ const isCorrectionCreate = (actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
3482
+ || (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
3483
+ && isSpreadCorrectionBypassAllowed(bot);
3208
3484
  if (!isCorrectionCreate) {
3209
3485
  const { check, refreshed } = runLastFillGuardCheck(bot, createPrice, order.size, order.type, lastFillGuardStats, true);
3210
3486
  if (refreshed)
@@ -3235,6 +3511,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3235
3511
  skippedCreateSlotIds.add(order.id);
3236
3512
  continue;
3237
3513
  }
3514
+ recordRestampBuyAboveAnchor(bot, createPrice, order.type);
3238
3515
  const buildResult = await chainOrders.buildCreateOrderOp(bot.account, args.amountToSell, args.sellAssetId, args.minToReceive, args.receiveAssetId, null);
3239
3516
  if (!buildResult) {
3240
3517
  bot.manager.logger.log(`Skipping create op for ${action.id}: amounts would round to 0 on blockchain`, 'warn');
@@ -3375,9 +3652,11 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3375
3652
  try {
3376
3653
  let bypassedEvacuation = false;
3377
3654
  const rotationOrigin = action?.origin;
3378
- if (rotationOrigin === 'gap-evacuation') {
3379
- const frozenB = Number(action?.evacBoundary);
3380
- const frozenG = Number(action?.evacGapSlots);
3655
+ if (rotationOrigin === COW_ORIGINS.GAP_EVACUATION) {
3656
+ // Absent-aware: a legacy stamp carrying null/''
3657
+ // geometry must not read as boundary 0 / gap 0.
3658
+ const frozenB = Format.toKnownNumber(action?.evacBoundary);
3659
+ const frozenG = Format.toKnownNumber(action?.evacGapSlots);
3381
3660
  let stampUsable = Number.isFinite(frozenB) && Number.isFinite(frozenG);
3382
3661
  if (stampUsable) {
3383
3662
  // Stale-stamp check: the stamp froze PLAN-BUILD
@@ -3506,6 +3785,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3506
3785
  skippedUpdateSlotIds.add(action.newGridId);
3507
3786
  continue;
3508
3787
  }
3788
+ recordRestampBuyAboveAnchor(bot, newPrice, orderType);
3509
3789
  const buildResult = await chainOrders.buildUpdateOrderOp(bot.account, action.orderId, { amountToSell, minToReceive, newPrice, orderType }, masterOrder.rawOnChain || null);
3510
3790
  if (!buildResult) {
3511
3791
  skippedUpdateCount++;
@@ -3641,6 +3921,7 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3641
3921
  if (!recordGridPriceInvariantCheck(bot, targetSlotId, fbPrice, gridPriceInvariantStats, 'CREATE-FALLBACK')) {
3642
3922
  continue;
3643
3923
  }
3924
+ recordRestampBuyAboveAnchor(bot, fbPrice, fbType);
3644
3925
  const fbResult = await chainOrders.buildCreateOrderOp(bot.account, fbArgs.amountToSell, fbArgs.sellAssetId, fbArgs.minToReceive, fbArgs.receiveAssetId, null);
3645
3926
  if (fbResult) {
3646
3927
  operations.push(fbResult.op);
@@ -3761,8 +4042,12 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
3761
4042
  const gateGuarded = finalGateStats.checked + finalGateStats.bypassed;
3762
4043
  const totalGuarded = lastFillGuardStats.checked + lastFillGuardStats.bypassed + gateGuarded;
3763
4044
  if (totalGuarded > 0) {
3764
- const sumPivotRaw = bot.manager?._lastFilledPrice;
3765
- const sumType = bot.manager?._lastFilledType;
4045
+ // Same effective reference the guard judged against (live pivot
4046
+ // else the bot-scoped market fill) so the summary cannot report
4047
+ // disabled(cold) while placements were actually blocked.
4048
+ const sumRef = resolveLastFillGuardReference(bot.manager);
4049
+ const sumPivotRaw = sumRef.price;
4050
+ const sumType = sumRef.type;
3766
4051
  const sumInc = resolveLastFillGuardIncrement(bot);
3767
4052
  const cold = sumPivotRaw == null || !Number.isFinite(Number(sumPivotRaw)) || sumType == null;
3768
4053
  const batchOrigin = cowResult?.origin;
@@ -4054,6 +4339,15 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4054
4339
  });
4055
4340
  }
4056
4341
  const batchResult = await processBatchResults(bot, result, executedContexts);
4342
+ // A `suspended` persist result is a deliberate, temporary gate
4343
+ // (credential-daemon outage), NOT a corrupt/ahead state: the
4344
+ // in-memory master stays authoritative and the dirty-flush
4345
+ // pipeline persists it once suspension lifts. Treat it as a
4346
+ // deferral — never as a structural-resync trigger.
4347
+ const isSuspendedPersist = (r) => {
4348
+ const v = r;
4349
+ return Boolean(v && v.skipped && v.suspended === true);
4350
+ };
4057
4351
  const persistResult = await bot.manager.persistGrid();
4058
4352
  if (persistResult && (persistResult.skipped || persistResult.isValid === false)) {
4059
4353
  bot.manager.logger.log(`[COW][PERSIST-GUARD] First persist attempt was ` +
@@ -4062,7 +4356,21 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4062
4356
  `clearing working grid reference.`, 'warn');
4063
4357
  bot.manager._persistenceWarning = persistResult;
4064
4358
  const retryResult = await bot.manager.persistGrid();
4065
- if (retryResult && (retryResult.skipped || retryResult.isValid === false)) {
4359
+ if (isSuspendedPersist(retryResult)) {
4360
+ bot.manager.logger.log(`[COW][PERSIST-GUARD] Grid persistence is suspended ` +
4361
+ `(${retryResult.reason || 'no reason'}); deferring disk flush until it resumes.`, 'warn');
4362
+ // The committed grid is not on disk yet. Mark it dirty so
4363
+ // the end-of-tick flushGridDirty safety net retries it at
4364
+ // the next end-of-tick flush after the suspension lifts,
4365
+ // instead of relying on the next COW/recovery persist to
4366
+ // converge disk.
4367
+ try {
4368
+ bot.manager._markGridDirty?.();
4369
+ }
4370
+ catch { /* best-effort */ }
4371
+ delete bot.manager._persistenceWarning;
4372
+ }
4373
+ else if (retryResult && (retryResult.skipped || retryResult.isValid === false)) {
4066
4374
  bot.manager.logger.log(`[COW][PERSIST-GUARD] Retry also skipped/invalid ` +
4067
4375
  `(${retryResult.reason || 'no reason'}). Master grid in memory ` +
4068
4376
  `is ahead of disk snapshot; structural resync requested.`, 'error');
@@ -4157,6 +4465,10 @@ async function updateOrdersOnChainBatchCOWBody(bot, cowResult, replanDepth, seam
4157
4465
  // balance reflects the on-chain cost (shared with the
4158
4466
  // refused-commit paths via recoverRefusedCommit).
4159
4467
  return await recoverRefusedCommit(bot, chainOrders, '[COW][UNCERTAIN]', { placedContexts: opContexts, polledCreateIds: confirmation.confirmedChainIds }, opContexts, effectiveBoundary, {
4468
+ // Poll-confirmed SUCCESS: the commit was accepted;
4469
+ // this funnel is only reused for chain adoption +
4470
+ // fee deduction, so it must not count as a refusal.
4471
+ refusedCommit: false,
4160
4472
  extraReturn: { commitRefused: false },
4161
4473
  successReturn: { executed: true, hadRotation: false, uncertainResolved: true },
4162
4474
  failureResyncReason: 'poll-confirmed commit (chain adoption unavailable)',
@@ -4449,6 +4761,18 @@ async function persistGridAndClearPendingBroadcasts(bot, logPrefix) {
4449
4761
  * @returns {Promise<Object>} The commit-refused return object
4450
4762
  */
4451
4763
  async function recoverRefusedCommit(bot, chainOrders, logPrefix, adoptOpts, contexts, workingBoundary, opts = {}) {
4764
+ // P2 observability: count genuine commit refusals at this single funnel (so
4765
+ // the three call sites cannot double-count). This function is ALSO the
4766
+ // shared funnel for the poll-confirmed SUCCESS path (chain adoption + fee
4767
+ // deduction), which passes `refusedCommit: false` because the commit was
4768
+ // accepted — counting it would overstate the refusal signal. Never gates
4769
+ // behavior.
4770
+ try {
4771
+ if (opts.refusedCommit !== false && bot._metrics) {
4772
+ bot._metrics.refusedCommitCount = (bot._metrics.refusedCommitCount || 0) + 1;
4773
+ }
4774
+ }
4775
+ catch { /* metrics are best-effort */ }
4452
4776
  const extraReturn = (opts.extraReturn ?? {});
4453
4777
  const successReturn = opts.successReturn;
4454
4778
  const failureResyncReason = (opts.failureResyncReason ?? 'commit refused after broadcast (chain adoption unavailable)');
@@ -4564,8 +4888,12 @@ function runLastFillGuardCheck(bot, price, size, type, stats, skipRefresh = fals
4564
4888
  }
4565
4889
  catch { /* best-effort */ }
4566
4890
  }
4567
- const lastPrice = bot.manager?._lastFilledPrice;
4568
- const lastType = bot.manager?._lastFilledType;
4891
+ // Effective reference: the live pivot when armed, else the bot-scoped
4892
+ // market fill that survives a grid regeneration. Without the fallback a
4893
+ // rebuild un-arms the guard until the next fill.
4894
+ const lastRef = resolveLastFillGuardReference(bot.manager);
4895
+ const lastPrice = lastRef.price;
4896
+ const lastType = lastRef.type;
4569
4897
  const inc = resolveLastFillGuardIncrement(bot);
4570
4898
  // Validate the pivot onto the ladder before use (see resolveOnGridPivot).
4571
4899
  // Reported once per probe at warn when the raw pivot was NOT a grid level:
@@ -4692,8 +5020,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4692
5020
  const queueDepthAfter = Array.isArray(bot?._incomingFillQueue)
4693
5021
  ? bot._incomingFillQueue.length
4694
5022
  : null;
4695
- const livePivot = Number(bot.manager?._lastFilledPrice);
4696
- const liveType = bot.manager?._lastFilledType;
5023
+ const liveRef = resolveLastFillGuardReference(bot.manager);
5024
+ const livePivot = Number(liveRef.price);
5025
+ const liveType = liveRef.type;
4697
5026
  const liveCold = !Number.isFinite(livePivot) || liveType == null;
4698
5027
  // No-op fast path: pivot unchanged (or uncomparable) since the freeze.
4699
5028
  // frozenCold + liveCold: guard stayed disabled — nothing to re-check.
@@ -4734,7 +5063,7 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4734
5063
  const dropIdx = new Set();
4735
5064
  const dropped = [];
4736
5065
  const inc = resolveLastFillGuardIncrement(bot);
4737
- const onGrid = resolveOnGridPivot(bot.manager, bot.manager?._lastFilledPrice);
5066
+ const onGrid = resolveOnGridPivot(bot.manager, liveRef.price);
4738
5067
  for (let i = 0; i < opContexts.length; i++) {
4739
5068
  const ctx = opContexts[i];
4740
5069
  if (!ctx || ctx.kind === 'cancel' || ctx.kind === 'size-update')
@@ -4753,8 +5082,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4753
5082
  // Spread-correction CREATE bypass (mirrors the build loop:
4754
5083
  // per-action origin, batch origin as back-compat fallback).
4755
5084
  const actionOrigin = action?.origin;
4756
- if (actionOrigin === 'spread-correction'
4757
- || (actionOrigin == null && batchOrigin === 'spread-correction')) {
5085
+ if ((actionOrigin === COW_ORIGINS.SPREAD_CORRECTION
5086
+ || (actionOrigin == null && batchOrigin === COW_ORIGINS.SPREAD_CORRECTION))
5087
+ && isSpreadCorrectionBypassAllowed(bot)) {
4758
5088
  if (stats)
4759
5089
  stats.bypassed = (Number(stats.bypassed) || 0) + 1;
4760
5090
  continue;
@@ -4806,9 +5136,9 @@ function runFinalPivotGate(bot, operations, opContexts, opts = {}) {
4806
5136
  // The gate must not invent a block it cannot prove —
4807
5137
  // especially not on an op the build loop already allowed.
4808
5138
  const rotOrigin = action?.origin;
4809
- if (rotOrigin === 'gap-evacuation'
4810
- && Number.isFinite(Number(action?.evacBoundary))
4811
- && Number.isFinite(Number(action?.evacGapSlots))) {
5139
+ if (rotOrigin === COW_ORIGINS.GAP_EVACUATION
5140
+ && Number.isFinite(Format.toKnownNumber(action?.evacBoundary))
5141
+ && Number.isFinite(Format.toKnownNumber(action?.evacGapSlots))) {
4812
5142
  if (stats)
4813
5143
  stats.bypassed = (Number(stats.bypassed) || 0) + 1;
4814
5144
  continue;
@@ -5196,43 +5526,24 @@ async function processBatchResults(bot, result, opContexts) {
5196
5526
  updateOperationCount
5197
5527
  };
5198
5528
  }
5199
- export { isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, reconcileAfterUncertainBroadcastImpl, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, pollChainForConfirmation, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5529
+ export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
5200
5530
  // Exported for regression tests (issue #23 sibling): the uncertain-broadcast
5201
5531
  // discard path must never drop a placement silently when master lost the slot.
5202
5532
  export { restoreDiscardedCreates };
5203
5533
  export default {
5204
5534
  buildOutsideInPairGroupsForOrders,
5205
5535
  buildOutsideInPairGroupsForCreateEntries,
5206
- extractOperationResults,
5207
- findMissingCreateResultContexts,
5208
5536
  markMissingCreateResultsAsStructuralBlocker,
5209
5537
  formatUnmatchedChainOrderForLog,
5210
5538
  recordPendingBroadcast,
5211
5539
  clearPendingBroadcasts,
5212
- clearPendingBroadcastsForSlots,
5213
- popPushedWorkingGrid,
5214
- buildChainOrderFingerprint,
5215
- normalizeChainOrderForPendingMatch,
5216
5540
  findChainOrderForSlot,
5217
5541
  reconcileAfterUncertainBroadcast,
5218
- reconcileAfterUncertainBroadcastImpl,
5219
- shouldExecuteCreatePairMode,
5220
5542
  executeWithRetryOnUncertain,
5221
5543
  executeChunkedWithRetryOnUncertain,
5222
- formatPartialBroadcastSummary,
5223
- validateOperationFunds,
5224
- resolveIdealSizeForValidation,
5225
- validateOrderSizeForExecution,
5226
- buildActionsFromPlan,
5544
+ popPushedWorkingGrid,
5227
5545
  buildCowResultFromPlan,
5228
- restoreSkippedUpdateSlotsInWorkingGrid,
5229
- resolveRefillBoundaryHold,
5230
- toRefillSlotIdSet,
5231
- trackBoundaryHold,
5232
- applyRotationTransitionsToWorkingGrid,
5233
- pollChainForConfirmation,
5234
5546
  updateOrdersOnChainBatchCOW,
5235
5547
  processBatchResults,
5236
- runFinalPivotGate,
5237
5548
  };
5238
5549
  //# sourceMappingURL=dexbot_cow_runtime.js.map