dexbot 1.7.2 → 1.7.3

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 (45) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +6 -0
  11. package/dist/modules/bot_defaults.js +6 -1
  12. package/dist/modules/constants.d.ts +12 -0
  13. package/dist/modules/constants.js +66 -0
  14. package/dist/modules/dexbot_class.d.ts +17 -0
  15. package/dist/modules/dexbot_class.js +56 -1
  16. package/dist/modules/dexbot_cow_runtime.js +231 -19
  17. package/dist/modules/dexbot_maintenance_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_maintenance_runtime.js +164 -11
  19. package/dist/modules/dexbot_state_recovery.js +15 -1
  20. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  21. package/dist/modules/launcher/instance_lock.js +131 -0
  22. package/dist/modules/order/grid.d.ts +19 -0
  23. package/dist/modules/order/grid.js +40 -14
  24. package/dist/modules/order/index.d.ts +15 -1
  25. package/dist/modules/order/manager.d.ts +21 -0
  26. package/dist/modules/order/manager.js +119 -12
  27. package/dist/modules/order/placement_lock.d.ts +30 -0
  28. package/dist/modules/order/placement_lock.js +48 -0
  29. package/dist/modules/order/utils/order.d.ts +39 -1
  30. package/dist/modules/order/utils/order.js +73 -2
  31. package/dist/modules/order/utils/system.d.ts +112 -3
  32. package/dist/modules/order/utils/system.js +368 -6
  33. package/dist/modules/paths.d.ts +1 -0
  34. package/dist/modules/paths.js +1 -0
  35. package/dist/modules/timing_policy.js +2 -0
  36. package/dist/modules/types.d.ts +27 -0
  37. package/dist/pm2.js +126 -0
  38. package/dist/unlock.js +26 -1
  39. package/docs/DEXBOT_COMPARISON.md +5 -5
  40. package/docs/EVOLUTION.md +10 -9
  41. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  42. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +155 -2
  43. package/docs/README.md +1 -1
  44. package/modules/README.md +1 -0
  45. package/package.json +2 -1
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * RUNTIME PIVOT TIMELINE — mirror of the runtime's own LAST-FILL-GUARD state,
5
+ * reconstructed from a bot log (profiles/logs/<bot>.log).
6
+ *
7
+ * Why this exists (2026-11-16 incident, retrospective §9.12 addendum): since
8
+ * `66667052`/`bc7b5232` the pivot only arms on WINDOW fills — wrong-side,
9
+ * too-far (premium sweep) and gap-band fills are refused. A sweep of the bot's
10
+ * own premium rail therefore leaves the pivot several grid steps BELOW the true
11
+ * last fill, and the runtime's gate legitimately passes re-quotes that the
12
+ * strict all-fills checker (which feeds true consecutive fills into the same
13
+ * predicate) flags as violations. The fix is not to change the runtime — the
14
+ * refusal policy is deliberate and protects the rail from the 24h unquoted-side
15
+ * deadlock — but to make the checker audit the gate the runtime ACTUALLY ran.
16
+ *
17
+ * This module parses the log's own pivot bookkeeping into a timeline:
18
+ *
19
+ * observations pivot values with timestamps, from (INFO unless noted):
20
+ * [FILL-PIVOT] pivot=P(type) ... (INFO)
21
+ * [LAST-FILL-GUARD] mode=... pivot=P(type) ... (INFO)
22
+ * [LAST-FILL-GUARD] Final gate: queue .. pivot A(type)->B(type) (DEBUG, post value)
23
+ * [LAST-FILL-GUARD] Re-armed on the new generation: P(type)
24
+ * ("Pivot refreshed from N pending queued fill(s)" is NOT an
25
+ * observation: it logs the queue content, which may be a fill
26
+ * the arming policy just refused; the effective pivot is in
27
+ * the adjacent Final-gate / mode= lines.)
28
+ * refusals [LAST-FILL-GUARD] Refusing to arm pivot P(type): ...
29
+ * placements order-id -> (timestamp, price) gate-judgement anchors, from:
30
+ * Placed buy order slot-X @P xS -> 1.7.x (INFO)
31
+ * [COW] Plan action: update slot-X -> slot-Y (orderId=1.7.x, size=.., price=P)
32
+ * allowances guard bypasses that keep a below-pivot placement:
33
+ * [LAST-FILL-GUARD] Allowing SELL P against pivot ...
34
+ * [LAST-FILL-GUARD] Allowing buy evacuation UPDATE ... at P
35
+ *
36
+ * and classifies a strict-mode candidate transition against the pivot the
37
+ * runtime held when the filled order was last priced:
38
+ *
39
+ * policy-divergence the runtime pivot would NOT have blocked the placement —
40
+ * the pivot lagged the strict last fill because the strict
41
+ * fill was refused from arming (sweep/edge/gap-band policy)
42
+ * or the placement ran under a guard allowance.
43
+ * violation the runtime's OWN pivot would have blocked the
44
+ * placement — a real gate failure.
45
+ * unverifiable no placement event or no pivot observation near the
46
+ * gate — the caller keeps the strict violation (fail
47
+ * toward reporting, never toward silence).
48
+ *
49
+ * Approximations (documented, offline-inherent):
50
+ * - The pivot for a placement is the FIRST observation at/after the
51
+ * placement event within PIVOT_LOOKAHEAD_MS — the gate runs between the
52
+ * plan build and the broadcast, and the batch's own mode=/Final-gate line
53
+ * is that gate's effective pivot. A dropped plan re-planned into a later
54
+ * batch resolves to the later batch's pivot (same orderId+action shape).
55
+ * The placement anchor is the order's event whose PRICE matches the
56
+ * filled price (a rotation to another level belongs to a different
57
+ * epoch); without a price match the latest event in the window is used.
58
+ * - Band-exempt allowances are logged at DEBUG; without debug logs such a
59
+ * transition stays a violation (conservative: fail toward reporting).
60
+ * - Spread-correction placements go through the same Plan/Placed lines, so
61
+ * they are covered; a correction order whose placement event is missing
62
+ * resolves to 'unverifiable' (kept as a strict violation).
63
+ */
64
+ import { isLastFillGuardBlocked } from '../modules/order/utils/system.js';
65
+ /** How far after a placement event the judging gate may log its pivot. */
66
+ export const PIVOT_LOOKAHEAD_MS = 120_000;
67
+ /** How wide an allowance match may drift around the gate pivot. */
68
+ export const ALLOWANCE_WINDOW_MS = 120_000;
69
+ /**
70
+ * Kibana truncates fill timestamps to the second while the runtime logs the
71
+ * order's Placed/Plan-action line a few hundred ms later, so a naive
72
+ * `placement.t <= fill.t` test can miss the anchor. An order cannot fill
73
+ * before it exists, so placements slightly AFTER the (truncated) fill
74
+ * timestamp are still valid anchors.
75
+ */
76
+ export const PLACEMENT_AFTER_FILL_MS = 5_000;
77
+ /** Relative price tolerance when matching an allowance to a fill price. */
78
+ const ALLOWANCE_PRICE_TOL = 5e-5;
79
+ /**
80
+ * Relative price tolerance when picking the placement anchor for a fill:
81
+ * maker fills average slightly off the quote price, so the anchor is the
82
+ * placement whose price is within 0.1% of the filled price. A rotation to a
83
+ * different grid level is far outside this band and never matches.
84
+ */
85
+ const PLACEMENT_PRICE_TOL = 1e-3;
86
+ // ─── Line parsing ─────────────────────────────────────────────────────────────
87
+ const TS_RE = /^\[(\d{4}-\d{2}-\d{2}T[\d:.]+Z)\]/;
88
+ function lineTs(line) {
89
+ const m = TS_RE.exec(line);
90
+ if (!m)
91
+ return null;
92
+ const t = Date.parse(m[1]);
93
+ return Number.isFinite(t) ? t : null;
94
+ }
95
+ /** "1,538.559125" | "1538.559125" | "1.3534" -> number | null */
96
+ function num(raw) {
97
+ if (!raw)
98
+ return null;
99
+ const v = Number(raw.replace(/,/g, ''));
100
+ return Number.isFinite(v) ? v : null;
101
+ }
102
+ const FILL_PIVOT_RE = /\[FILL-PIVOT\] pivot=([\d.,eE+-]+)\((buy|sell)\)/;
103
+ const MODE_RE = /\[LAST-FILL-GUARD\] mode=\S+ pivot=([\d.,eE+-]+)\((buy|sell)\)/;
104
+ const FINAL_GATE_RE = /\[LAST-FILL-GUARD\] Final gate: queue \S+ pivot [\d.,eE+-]+\((?:buy|sell)\)->([\d.,eE+-]+)\((buy|sell)\)/;
105
+ const REARM_RE = /\[LAST-FILL-GUARD\] Re-armed on the new generation: ([\d.,eE+-]+)\((buy|sell)\)/;
106
+ const REFUSAL_RE = /\[LAST-FILL-GUARD\] Refusing to arm pivot ([\d.,eE+-]+)\((buy|sell)\)/;
107
+ const PLACED_RE = /\[DEXBot\] Placed (buy|sell) order slot-[\w-]+ @([\d.,eE+-]+) x[\d.,eE+-]+ -> (1\.7\.\d+)/;
108
+ const PLAN_ACTION_RE = /\[COW\] Plan action: (?:update|create) \S+(?: -> \S+)? \(orderId=(1\.7\.\d+)[^)]*?price=([\d.,eE+-]+)/;
109
+ // "Allowing buy evacuation UPDATE for slot-X -> slot-Y at P: ..." (price after "at")
110
+ // "Allowing SELL P against pivot Q: ..." (placement price right after the direction word)
111
+ const ALLOW_AT_RE = /\s+at\s+([\d.,eE+-]+)/;
112
+ const ALLOW_AGAINST_RE = /\b(?:BUY|SELL) ([\d.,eE+-]+) against/;
113
+ const ALLOW_DIR_RE = /\b(buy|sell|BUY|SELL)\b/;
114
+ /**
115
+ * Parse a bot log into the runtime pivot index. Unknown lines are skipped;
116
+ * the parser is deliberately tolerant of level/tag variation because it must
117
+ * work on rotated and filtered logs too.
118
+ */
119
+ export function parseRuntimeLog(text) {
120
+ const observations = [];
121
+ const refusals = [];
122
+ const placements = new Map();
123
+ const allowances = [];
124
+ for (const line of text.split('\n')) {
125
+ const t = lineTs(line);
126
+ if (t == null)
127
+ continue;
128
+ let m = FILL_PIVOT_RE.exec(line);
129
+ if (m) {
130
+ const price = num(m[1]);
131
+ if (price != null && price > 0)
132
+ observations.push({ t, price, type: m[2], src: 'fill-pivot' });
133
+ continue;
134
+ }
135
+ m = MODE_RE.exec(line);
136
+ if (m) {
137
+ const price = num(m[1]);
138
+ if (price != null && price > 0)
139
+ observations.push({ t, price, type: m[2], src: 'mode' });
140
+ continue;
141
+ }
142
+ m = FINAL_GATE_RE.exec(line);
143
+ if (m) {
144
+ const price = num(m[1]);
145
+ if (price != null && price > 0)
146
+ observations.push({ t, price, type: m[2], src: 'final-gate' });
147
+ continue;
148
+ }
149
+ m = REARM_RE.exec(line);
150
+ if (m) {
151
+ const price = num(m[1]);
152
+ if (price != null && price > 0)
153
+ observations.push({ t, price, type: m[2], src: 'rearm' });
154
+ continue;
155
+ }
156
+ m = REFUSAL_RE.exec(line);
157
+ if (m) {
158
+ const price = num(m[1]);
159
+ if (price != null && price > 0)
160
+ refusals.push({ t, price, type: m[2] });
161
+ continue;
162
+ }
163
+ m = PLACED_RE.exec(line);
164
+ if (m) {
165
+ const price = num(m[2]);
166
+ if (price != null)
167
+ pushPlacement(placements, { t, orderId: m[3], price, kind: 'placed' });
168
+ continue;
169
+ }
170
+ m = PLAN_ACTION_RE.exec(line);
171
+ if (m) {
172
+ const price = num(m[2]);
173
+ if (price != null)
174
+ pushPlacement(placements, { t, orderId: m[1], price, kind: 'plan-action' });
175
+ continue;
176
+ }
177
+ if (line.includes('[LAST-FILL-GUARD] Allowing')) {
178
+ const dm = ALLOW_DIR_RE.exec(line.slice(line.indexOf('Allowing')));
179
+ const am = ALLOW_AT_RE.exec(line) ?? ALLOW_AGAINST_RE.exec(line);
180
+ if (dm && am) {
181
+ const price = num(am[1]);
182
+ if (price != null)
183
+ allowances.push({ t, direction: dm[1].toLowerCase(), price });
184
+ }
185
+ continue;
186
+ }
187
+ }
188
+ observations.sort((a, b) => a.t - b.t);
189
+ refusals.sort((a, b) => a.t - b.t);
190
+ allowances.sort((a, b) => a.t - b.t);
191
+ for (const list of placements.values())
192
+ list.sort((a, b) => a.t - b.t);
193
+ return { observations, refusals, placements, allowances };
194
+ }
195
+ /**
196
+ * Kibana fills carry an operation suffix on the order id (e.g. `1.7.x:se`),
197
+ * while the runtime log's Plan/Placed lines use the plain `1.7.x`. Normalize
198
+ * to the plain id on both sides so the join works.
199
+ */
200
+ function normalizeOrderId(orderId) {
201
+ const colon = orderId.indexOf(':');
202
+ return colon === -1 ? orderId : orderId.slice(0, colon);
203
+ }
204
+ function pushPlacement(map, ev) {
205
+ ev.orderId = normalizeOrderId(ev.orderId);
206
+ const list = map.get(ev.orderId);
207
+ if (list)
208
+ list.push(ev);
209
+ else
210
+ map.set(ev.orderId, [ev]);
211
+ }
212
+ /** Latest pivot observation at or before `t` (binary search), or null. */
213
+ export function pivotAtOrBefore(observations, t) {
214
+ let lo = 0;
215
+ let hi = observations.length - 1;
216
+ let best = null;
217
+ while (lo <= hi) {
218
+ const mid = (lo + hi) >> 1;
219
+ if (observations[mid].t <= t) {
220
+ best = observations[mid];
221
+ lo = mid + 1;
222
+ }
223
+ else {
224
+ hi = mid - 1;
225
+ }
226
+ }
227
+ return best;
228
+ }
229
+ /** First pivot observation at or after `t`, or null when none within the window. */
230
+ export function pivotAtOrAfter(observations, t, windowMs = PIVOT_LOOKAHEAD_MS) {
231
+ let lo = 0;
232
+ let hi = observations.length;
233
+ while (lo < hi) {
234
+ const mid = (lo + hi) >> 1;
235
+ if (observations[mid].t < t)
236
+ lo = mid + 1;
237
+ else
238
+ hi = mid;
239
+ }
240
+ if (lo < observations.length && observations[lo].t - t <= windowMs)
241
+ return observations[lo];
242
+ return null;
243
+ }
244
+ function lastPlacementBefore(map, orderId, t, fillPrice) {
245
+ const limit = t + PLACEMENT_AFTER_FILL_MS;
246
+ const list = map.get(orderId);
247
+ if (!list || list.length === 0)
248
+ return null;
249
+ let latest = null;
250
+ let priced = null;
251
+ for (const ev of list) {
252
+ if (ev.t > limit)
253
+ break;
254
+ latest = ev;
255
+ if (fillPrice != null) {
256
+ const denom = Math.max(Math.abs(fillPrice), 1e-12);
257
+ if (Math.abs(ev.price - fillPrice) / denom <= PLACEMENT_PRICE_TOL)
258
+ priced = ev;
259
+ }
260
+ }
261
+ // Prefer the epoch the fill actually belongs to (price-matched re-quote);
262
+ // the latest event is only a fallback when no quote matches the fill.
263
+ return priced ?? latest;
264
+ }
265
+ function countRefusalsBetween(refusals, from, to) {
266
+ let n = 0;
267
+ for (const r of refusals) {
268
+ if (r.t > from && r.t <= to)
269
+ n++;
270
+ if (r.t > to)
271
+ break;
272
+ }
273
+ return n;
274
+ }
275
+ function findAllowance(allowances, direction, price, from, to) {
276
+ for (const a of allowances) {
277
+ if (a.t < from)
278
+ continue;
279
+ if (a.t > to)
280
+ break;
281
+ if (a.direction !== direction)
282
+ continue;
283
+ const denom = Math.max(Math.abs(price), 1e-12);
284
+ if (Math.abs(a.price - price) / denom <= ALLOWANCE_PRICE_TOL)
285
+ return a;
286
+ }
287
+ return null;
288
+ }
289
+ /**
290
+ * Parse an ISO timestamp. Kibana fill times are UTC but written naive
291
+ * (`2026-11-16T14:08:18`, no offset); Date.parse would read those as LOCAL
292
+ * time and shift the timeline by the host's UTC offset. Treat any timestamp
293
+ * without an explicit offset as UTC — the log lines and Kibana agree on UTC.
294
+ */
295
+ function parseIso(t) {
296
+ if (!/[Zz]|[+-]\d{2}:?\d{2}$/.test(t))
297
+ return Date.parse(t + 'Z');
298
+ return Date.parse(t);
299
+ }
300
+ /**
301
+ * Classify one strict-mode candidate transition against the pivot the runtime
302
+ * held when `currOrderId` was last priced. Verdicts and the fail direction are
303
+ * documented in the module header: anything unprovable stays a violation.
304
+ */
305
+ export function classifyTransition(cand, index) {
306
+ const currT = parseIso(cand.currTime);
307
+ const prevT = parseIso(cand.prevTime);
308
+ const unverifiable = (reason) => ({
309
+ verdict: 'unverifiable',
310
+ reason,
311
+ pivot: null,
312
+ refusalsInRange: Number.isFinite(prevT) && Number.isFinite(currT)
313
+ ? countRefusalsBetween(index.refusals, prevT, currT)
314
+ : 0,
315
+ });
316
+ if (!Number.isFinite(currT))
317
+ return unverifiable('unparseable curr fill timestamp');
318
+ const placement = lastPlacementBefore(index.placements, normalizeOrderId(cand.currOrderId), currT, cand.currPrice);
319
+ if (!placement) {
320
+ return unverifiable(`no placement event for order ${cand.currOrderId} before the fill`);
321
+ }
322
+ // The gate runs between plan build and broadcast; its effective pivot is
323
+ // the batch's own mode=/Final-gate line. Look FORWARD from the event, not
324
+ // backward — the previous batch's pivot would understate the gate.
325
+ const obs = pivotAtOrAfter(index.observations, placement.t);
326
+ if (!obs) {
327
+ return unverifiable(`no pivot observation within ${PIVOT_LOOKAHEAD_MS / 1000}s of the placement event`);
328
+ }
329
+ const refusalsInRange = Number.isFinite(prevT)
330
+ ? countRefusalsBetween(index.refusals, prevT, currT)
331
+ : 0;
332
+ const pivot = { price: obs.price, type: obs.type, t: obs.t };
333
+ const check = isLastFillGuardBlocked(cand.currPrice, cand.direction, obs.price, obs.type);
334
+ if (!check.blocked) {
335
+ return {
336
+ verdict: 'policy-divergence',
337
+ reason: refusalsInRange > 0
338
+ ? `runtime pivot ${obs.price}(${obs.type}) at the gate excluded the strict last fill from arming (window-trade policy, ${refusalsInRange} refusal(s) between the fills)`
339
+ : `runtime pivot ${obs.price}(${obs.type}) at the gate was older than the strict last fill`,
340
+ pivot,
341
+ refusalsInRange,
342
+ };
343
+ }
344
+ const allowed = findAllowance(index.allowances, cand.direction, cand.currPrice, pivot.t - ALLOWANCE_WINDOW_MS, pivot.t + 5000);
345
+ if (allowed) {
346
+ return {
347
+ verdict: 'policy-divergence',
348
+ reason: `guard allowance logged at the gate (band-exempt / stamped evacuation; pivot ${obs.price}(${obs.type}))`,
349
+ pivot,
350
+ refusalsInRange,
351
+ };
352
+ }
353
+ return {
354
+ verdict: 'violation',
355
+ reason: `the runtime's own pivot ${obs.price}(${obs.type}) would have blocked this placement`,
356
+ pivot,
357
+ refusalsInRange,
358
+ };
359
+ }
360
+ //# sourceMappingURL=pivot_timeline.js.map
@@ -249,21 +249,33 @@ async function _acquireLockCoreAsync(lockPath, opts = {}) {
249
249
  */
250
250
  function acquireFileLockSync(lockPath, opts = {}) {
251
251
  const staleMs = typeof opts.staleMs === 'number' && Number.isFinite(opts.staleMs) && opts.staleMs > 0 ? opts.staleMs : (6 * 3600 * 1000);
252
+ // Explicit opts override the market-adapter defaults (default payload,
253
+ // liveness heuristic, and message). Callers that pass none — the market
254
+ // adapter lifecycle lock — keep the exact behavior above; generic callers
255
+ // (e.g. the per-account bot instance lock) parameterize their own payload,
256
+ // holder liveness, and contention message.
257
+ const buildPayload = typeof opts.buildPayload === 'function'
258
+ ? opts.buildPayload
259
+ : () => ({ pid: runtime.pid, createdAt: new Date().toISOString() });
260
+ const aliveCheck = typeof opts.aliveCheck === 'function' ? opts.aliveCheck : isLikelyMarketAdapterProcess;
261
+ const resolveRunningMsg = typeof opts.alreadyRunningMsg === 'function'
262
+ ? opts.alreadyRunningMsg
263
+ : () => `market adapter already running (lock: ${lockPath}, pid: ${loadLockInfo(lockPath).pid ?? 'unknown'})`;
252
264
  return _acquireLockCore(lockPath, {
253
265
  staleMs,
254
266
  maxAttempts: 2,
255
267
  retryMs: 0,
256
268
  contention: 'throw',
257
- aliveCheck: isLikelyMarketAdapterProcess,
269
+ aliveCheck,
258
270
  // The payload's `pid` is display metadata for this message; the
259
271
  // release-time identity token is the core-injected `ownerId` (always a
260
272
  // fresh unique id, never reused across acquires).
261
- buildPayload: () => ({ pid: runtime.pid, createdAt: new Date().toISOString() }),
273
+ buildPayload,
262
274
  // Evaluated lazily at throw time so the reported pid reflects the lock
263
275
  // holder at the moment contention is detected, not the state when this
264
276
  // function was first called (loadLockInfo tolerates a missing lock file).
265
- alreadyRunningMsg: () => `market adapter already running (lock: ${lockPath}, pid: ${loadLockInfo(lockPath).pid ?? 'unknown'})`,
266
- timeoutMsg: `cannot acquire lock: ${lockPath}`,
277
+ alreadyRunningMsg: resolveRunningMsg,
278
+ timeoutMsg: opts.timeoutMsg || `cannot acquire lock: ${lockPath}`,
267
279
  });
268
280
  }
269
281
  function releaseFileLockSync(lock) {
@@ -119,6 +119,10 @@ declare function loadGeneralSettings(): {
119
119
  GAP_EVACUATION_STREAK_THRESHOLD: number;
120
120
  GAP_EVACUATION_CANCEL_THRESHOLD: number;
121
121
  LAST_FILL_PIVOT_TTL_MS: number;
122
+ LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
123
+ LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
124
+ LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
125
+ LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
122
126
  RELATIVE_ORDER_UPDATE_THRESHOLD_PERCENT: number;
123
127
  };
124
128
  TIMING: {
@@ -166,10 +170,12 @@ declare function loadGeneralSettings(): {
166
170
  SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
167
171
  SPREAD_STALE_FUND_ESCALATE_MS: number;
168
172
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
173
+ SPREAD_STALE_PIVOT_EXPIRE_MS: number;
169
174
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
170
175
  SPREAD_STALE_TRANSIENT_GRACE: number;
171
176
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
172
177
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
178
+ SPREAD_STALE_RECHECK_MS: number;
173
179
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
174
180
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
175
181
  GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
@@ -214,7 +214,12 @@ export function createDefaultBotMetrics() {
214
214
  gapBandPlacementShadowCount: 0,
215
215
  spreadCorrectionRefusedCount: 0,
216
216
  spreadCorrectionRefusalCauses: {},
217
- spreadCorrectionRetryCount: 0
217
+ spreadCorrectionRetryCount: 0,
218
+ stalePlanDroppedCount: 0,
219
+ stalePlanProceedCount: 0,
220
+ clampedNoopUpdateCount: 0,
221
+ chunkAbortedOpCount: 0,
222
+ reloadReplacedRailCount: 0
218
223
  };
219
224
  }
220
225
  //# sourceMappingURL=bot_defaults.js.map
@@ -242,10 +242,12 @@ declare let TIMING: {
242
242
  SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
243
243
  SPREAD_STALE_FUND_ESCALATE_MS: number;
244
244
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
245
+ SPREAD_STALE_PIVOT_EXPIRE_MS: number;
245
246
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
246
247
  SPREAD_STALE_TRANSIENT_GRACE: number;
247
248
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
248
249
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
250
+ SPREAD_STALE_RECHECK_MS: number;
249
251
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
250
252
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
251
253
  GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
@@ -301,6 +303,10 @@ declare let GRID_LIMITS: {
301
303
  GAP_EVACUATION_STREAK_THRESHOLD: number;
302
304
  GAP_EVACUATION_CANCEL_THRESHOLD: number;
303
305
  LAST_FILL_PIVOT_TTL_MS: number;
306
+ LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
307
+ LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
308
+ LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
309
+ LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
304
310
  GRID_COMPARISON: {
305
311
  RMS_PERCENTAGE: number;
306
312
  };
@@ -752,6 +758,10 @@ declare function buildDefaultGeneralSettings(): {
752
758
  GAP_EVACUATION_STREAK_THRESHOLD: number;
753
759
  GAP_EVACUATION_CANCEL_THRESHOLD: number;
754
760
  LAST_FILL_PIVOT_TTL_MS: number;
761
+ LAST_FILL_REFUSED_LEVEL_TTL_MS: number;
762
+ LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: number;
763
+ LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: number;
764
+ LAST_FILL_PIVOT_MARKET_FRESH_MS: number;
755
765
  RELATIVE_ORDER_UPDATE_THRESHOLD_PERCENT: number;
756
766
  };
757
767
  TIMING: {
@@ -799,10 +809,12 @@ declare function buildDefaultGeneralSettings(): {
799
809
  SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
800
810
  SPREAD_STALE_FUND_ESCALATE_MS: number;
801
811
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
812
+ SPREAD_STALE_PIVOT_EXPIRE_MS: number;
802
813
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
803
814
  SPREAD_STALE_TRANSIENT_GRACE: number;
804
815
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
805
816
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
817
+ SPREAD_STALE_RECHECK_MS: number;
806
818
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
807
819
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
808
820
  GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: number;
@@ -405,6 +405,16 @@ let TIMING = {
405
405
  // (`_lastGeometryResyncPivotKey`): the pivot does not move with the grid, so
406
406
  // a second attempt re-derives the identical veto.
407
407
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: 10 * 60 * 1000, // 10 minutes
408
+ // SPREAD_STALE_PIVOT_EXPIRE_MS: how long after the ONE geometry re-center
409
+ // per pivot the out-of-spread watchdog waits before clearing the
410
+ // LAST-FILL-GUARD pivot (and the bot-scoped last-market-fill reference)
411
+ // outright. Previously that state escalated to NOTHING ("a fill or the
412
+ // pivot TTL is the only heal") — live, a single off-market pivot buy
413
+ // stranded the grid out of spread for the full 24h TTL because every
414
+ // rebuild re-armed the same pivot. Clearing both references lets spread
415
+ // correction trade around the live market again; both re-arm on the next
416
+ // real fill. 0 disables the expiry (legacy behavior).
417
+ SPREAD_STALE_PIVOT_EXPIRE_MS: 20 * 60 * 1000, // 20 minutes
408
418
  // SPREAD_CORRECTION_MAX_ATTEMPTS: bounded attempts for one spread-correction
409
419
  // cycle (initial broadcast + fresh-master re-plan retries). Kept next to the
410
420
  // other SPREAD_* tunables so the retry budget is centralized; a value < 1
@@ -430,6 +440,17 @@ let TIMING = {
430
440
  // separate from BOUNDARY_HOLD_RESYNC_COOLDOWN_MS so tuning boundary-hold
431
441
  // behavior never silently changes the spread watchdog cadence.
432
442
  SPREAD_STALE_RESYNC_COOLDOWN_MS: 5 * 60 * 1000, // 5 minutes
443
+ // SPREAD_STALE_RECHECK_MS: level-triggered retry cadence for the spread
444
+ // watchdog. Every clock above (5/10/20/30 min) assumes the spread check is
445
+ // EVALUATED, but with OPEN_ORDERS_SYNC_LOOP_ENABLED=false the only driver
446
+ // is the post-fill path plus the BLOCKCHAIN_FETCH_INTERVAL_MIN (240 min)
447
+ // tick — so an out-of-tolerance grid was re-checked once per 4h and every
448
+ // window above was dead code (live: 86 minutes with no check at all, a
449
+ // second identical batch accepted only when the mid finally moved). While
450
+ // the spread is out of tolerance the watchdog now arms a one-shot recheck
451
+ // at this cadence, so the documented clocks are reachable at any base
452
+ // cadence. 0 disables the retry (legacy cadence-only behavior).
453
+ SPREAD_STALE_RECHECK_MS: 60 * 1000, // 1 minute
433
454
  // BOUNDARY_HOLD_RESYNC_THRESHOLD / COOLDOWN: consecutive boundary-hold
434
455
  // batches (each carrying fresh fills) after which the COW executor asks
435
456
  // for a guard-aware structural re-center. A hold is correct maker
@@ -778,6 +799,51 @@ let GRID_LIMITS = {
778
799
  // runtime are NOT expired — the guard has no clock there and the pivot
779
800
  // is refreshed by every fresh fill.
780
801
  LAST_FILL_PIVOT_TTL_MS: 24 * 60 * 60 * 1000, // 24 hours
802
+ // LAST_FILL_REFUSED_LEVEL_TTL_MS: how long a fill REFUSED from arming the
803
+ // pivot (wrong-side / too-far premium sweep, §9.12/P1) still marks its own
804
+ // level as a same-level re-fill block. The direction pivot deliberately
805
+ // stays behind such a fill — but the §9.12/P2 same-level refusal keys off
806
+ // the ARMED pivot, so the P1 refusal silently suspended it: a spread-
807
+ // correction slot re-placed at the just-filled level ("rises" of sub-sat
808
+ // rounding dust) refilled 5 times in 2.5 minutes on a live market-pair bot
809
+ // (2026-11-16). The marker vetoes exactly ONE level — the just-filled one —
810
+ // and nothing else, so spread correction keeps trading around the live
811
+ // market and the unquoted-side deadlock P1 was written against cannot
812
+ // re-open through it. In-memory only and short-lived: it must stop the
813
+ // immediate re-fill loop, not ratchet for the pivot's 24h TTL.
814
+ LAST_FILL_REFUSED_LEVEL_TTL_MS: 30 * 60 * 1000, // 30 minutes
815
+ // LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: a real FILL may only arm the
816
+ // LAST-FILL-GUARD pivot when it priced on the market's own side of the
817
+ // live reference: BUY at/below mid, SELL at/above mid (within this
818
+ // tolerance in grid increments). A fill on the WRONG side (a BUY above
819
+ // mid, a SELL below mid) is a crossed-book artifact — usually a misplaced
820
+ // order that got swept — and arming it vetoed every near-market SELL for
821
+ // the full 24h TTL in a live incident. The pivot AND the bot-scoped
822
+ // last-market-fill row are both skipped with the refusal (an off-mid row
823
+ // as a crossing floor freezes correction the same way), so the last
824
+ // honest fill stays the reference. Fail-open when no fresh live price
825
+ // exists.
826
+ LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS: 1,
827
+ // LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: a real FILL may also only arm the
828
+ // LAST-FILL-GUARD pivot when it priced within this many grid increments of
829
+ // the live reference, on EITHER side. The wrong-side tolerance below catches
830
+ // the direction; this catches a premium SWEEP of our own rail — a taker
831
+ // paying through several of our levels is on the "honest" side by direction
832
+ // but is not a window trade. Live: a sell 14.5 steps (4.4%) above the mid
833
+ // armed the pivot at the top of the gap band the geometry had just derived,
834
+ // so every band sell was vetoed and the spread stayed 3x wide for 86 min.
835
+ // One full target spread is ~5 steps at the default increment/spread, so 6
836
+ // keeps every interior window fill and refuses a fill a full spread away.
837
+ // 0 disables the distance leg (direction bound only).
838
+ LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS: 6,
839
+ // LAST_FILL_PIVOT_MARKET_FRESH_MS: how old the cached live market price
840
+ // (manager._liveMarketPrice) may be for the pivot market bound above to
841
+ // trust it. Older than this, the check fails open — an ancient mid must
842
+ // never veto a fresh fill after a fast market move. (The crossing FLOOR
843
+ // does not use this window: resolveSpreadCrossingFloor already picks the
844
+ // newer of the live read and the fill, and the pre-broadcast crossing
845
+ // check is an observation, not a veto — see retrospective §9.10/P4.)
846
+ LAST_FILL_PIVOT_MARKET_FRESH_MS: 15 * 60 * 1000, // 15 minutes
781
847
  // Grid comparison metrics
782
848
  // Detects significant divergence between calculated (in-memory) and persisted grid state
783
849
  // after order fills and rotations
@@ -70,6 +70,7 @@ import cowRuntime from './dexbot_cow_runtime.js';
70
70
  import type { ChainOrderLike, CowResult, OpPhase } from './dexbot_cow_runtime.js';
71
71
  import { normalizeBotEntry } from './bot_settings.js';
72
72
  import type { FillOpLike, FillLike, ReplaySafeFillAccountingOptions } from './dexbot_fill_runtime.js';
73
+ import { type BotInstanceLock } from './launcher/instance_lock.js';
73
74
  import type { BotLike, AssetPair, IncomingFill, UnknownRecord, GridConfig, OrderManagerLike, AccountOrdersLike, BotMetrics, ProcessedFillStoreLike, CreditRuntimeLike, FillBatchResult, SigningToken, SpreadCorrectionStall } from './types.js';
74
75
  /**
75
76
  * Resolve the COALESCE_BACKLOG_REPLAY opt-in.
@@ -196,9 +197,20 @@ declare class DEXBot implements BotLike {
196
197
  _marketAdapterWatchdogInFlight: boolean;
197
198
  _outOfSpreadSince: number;
198
199
  _outOfSpreadStaleWarned: boolean;
200
+ /** Held single-controller lock for this bot's account (null when not started). */
201
+ _instanceLock: BotInstanceLock | null;
199
202
  _outOfSpreadTransientCount: number;
200
203
  /** When the spread first read within tolerance; cleared on any out-of-tolerance cycle. */
201
204
  _outOfSpreadToleranceSince: number;
205
+ /**
206
+ * Level-triggered spread recheck (see TIMING.SPREAD_STALE_RECHECK_MS).
207
+ * Armed by the out-of-spread watchdog while the grid is out of tolerance,
208
+ * since the base maintenance cadence can be hours.
209
+ */
210
+ _spreadRecheckTimer: ReturnType<typeof setTimeout> | null;
211
+ _spreadRecheckInFlight: boolean;
212
+ /** "placed but did not reduce the violation" was already reported for this run. */
213
+ _outOfSpreadNoProgressWarned: boolean;
202
214
  _postRecoveryRebalanceDefers: number;
203
215
  _skipEmptyReadConfirmDelay: boolean;
204
216
  _spreadStallArmed: boolean;
@@ -1053,6 +1065,11 @@ declare class DEXBot implements BotLike {
1053
1065
  spreadCorrectionRefusedCount: number;
1054
1066
  spreadCorrectionRefusalCauses: Record<string, number>;
1055
1067
  spreadCorrectionRetryCount: number;
1068
+ stalePlanDroppedCount: number;
1069
+ stalePlanProceedCount: number;
1070
+ clampedNoopUpdateCount: number;
1071
+ chunkAbortedOpCount: number;
1072
+ reloadReplacedRailCount: number;
1056
1073
  };
1057
1074
  /**
1058
1075
  * Execute grid maintenance checks in strict order with pipeline consensus.