dexbot 1.6.17 → 1.6.18

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 (101) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/analysis/README.md +10 -9
  3. package/analysis/ama_fitting/README.md +2 -2
  4. package/analysis/bot_fitting/README.md +3 -3
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/analyze_args.d.ts +2 -1
  9. package/dist/analysis/fills_source.d.ts +1 -8
  10. package/dist/analysis/fills_source.js +1 -1
  11. package/dist/analysis/grid_correction_check.d.ts +9 -6
  12. package/dist/analysis/grid_correction_check.js +56 -64
  13. package/dist/analysis/math_utils.d.ts +1 -1
  14. package/dist/analysis/trade_profitability.d.ts +1 -1
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  16. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  17. package/dist/market_adapter/cli_args.d.ts +6 -1
  18. package/dist/market_adapter/cli_args.js +16 -2
  19. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  20. package/dist/market_adapter/core/kibana_candles.js +3 -1
  21. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  22. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  23. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  24. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  25. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  26. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  27. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  30. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  31. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  32. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  33. package/dist/market_adapter/inputs/window_cache.js +14 -1
  34. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  35. package/dist/market_adapter/lp_chart_runner.js +3 -1
  36. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  37. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  38. package/dist/market_adapter/market_adapter.d.ts +10 -2
  39. package/dist/market_adapter/market_adapter.js +10 -11
  40. package/dist/market_adapter/utils/chain.d.ts +2 -3
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  42. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  43. package/dist/market_adapter/utils/file_lock.js +1 -1
  44. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  45. package/dist/market_adapter/utils/native_history.js +3 -1
  46. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  47. package/dist/modules/bots_file_lock.d.ts +2 -2
  48. package/dist/modules/bots_file_lock.js +2 -2
  49. package/dist/modules/constants.js +6 -3
  50. package/dist/modules/dexbot_class.d.ts +8 -0
  51. package/dist/modules/dexbot_class.js +10 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  53. package/dist/modules/dexbot_cow_runtime.js +461 -43
  54. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  55. package/dist/modules/dexbot_maintenance_runtime.js +56 -9
  56. package/dist/modules/dexbot_startup_runtime.js +7 -1
  57. package/dist/modules/graceful_shutdown.d.ts +2 -2
  58. package/dist/modules/graceful_shutdown.js +2 -2
  59. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  60. package/dist/modules/node_manager.d.ts +1 -1
  61. package/dist/modules/node_manager.js +1 -1
  62. package/dist/modules/order/accounting.js +2 -1
  63. package/dist/modules/order/export.d.ts +2 -2
  64. package/dist/modules/order/export.js +2 -2
  65. package/dist/modules/order/grid.d.ts +19 -14
  66. package/dist/modules/order/grid.js +262 -61
  67. package/dist/modules/order/grid_reconcile.js +5 -1
  68. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  69. package/dist/modules/order/index.d.ts +9 -3
  70. package/dist/modules/order/manager.d.ts +10 -0
  71. package/dist/modules/order/manager.js +41 -11
  72. package/dist/modules/order/strategy.js +22 -2
  73. package/dist/modules/order/sync_engine.d.ts +12 -1
  74. package/dist/modules/order/sync_engine.js +135 -20
  75. package/dist/modules/order/utils/math.d.ts +8 -9
  76. package/dist/modules/order/utils/math.js +24 -13
  77. package/dist/modules/order/utils/order.d.ts +52 -11
  78. package/dist/modules/order/utils/order.js +137 -21
  79. package/dist/modules/order/utils/system.d.ts +73 -29
  80. package/dist/modules/order/utils/system.js +239 -48
  81. package/dist/modules/order/utils/validate.d.ts +1 -0
  82. package/dist/modules/order/utils/validate.js +4 -1
  83. package/dist/modules/storage/index.d.ts +3 -2
  84. package/dist/modules/storage/index.js +3 -2
  85. package/dist/modules/types.d.ts +9 -0
  86. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  87. package/docs/COW_INVARIANTS.md +20 -10
  88. package/docs/DEXBOT_COMPARISON.md +5 -5
  89. package/docs/EVOLUTION.md +9 -8
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  91. package/docs/GRID_PRICE_INVARIANT.md +24 -4
  92. package/docs/GRID_RECONCILE.md +5 -5
  93. package/docs/LIFECYCLE.md +11 -11
  94. package/docs/LOGGING.md +15 -2
  95. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +123 -36
  96. package/docs/README.md +1 -1
  97. package/docs/architecture.md +115 -13
  98. package/docs/developer_guide.md +12 -0
  99. package/market_adapter/README.md +9 -4
  100. package/modules/README.md +18 -14
  101. package/package.json +4 -3
@@ -80,11 +80,12 @@ const require = createRequire(import.meta.url);
80
80
  import { path } from '../../path_api.js';
81
81
  import { getStorage } from '../../storage/index.js';
82
82
  const storage = getStorage();
83
- import { API_LIMITS, ORDER_TYPES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
83
+ import { API_LIMITS, ORDER_TYPES, ORDER_STATES, COW_ACTIONS, FEE_PARAMETERS, BTS_PRECISION, PIPELINE_TIMING, NATIVE_CLIENT, GRID_LIMITS, TIMING } from '../../constants.js';
84
84
  import { PATHS } from '../../paths.js';
85
85
  import { toFiniteNumber, isValidNumber, toKnownNumber } from '../format.js';
86
86
  import * as MathUtils from './math.js';
87
87
  import * as OrderUtils from './order.js';
88
+ import { parseSlotIndex } from './slot.js';
88
89
  import Logger from '../../order/logger.js';
89
90
  import { runtime } from '../../runtime.js';
90
91
  import { getErrorMessage, sleepMs } from '../../utils/errors.js';
@@ -1245,37 +1246,10 @@ export function evaluateSpreadCorrectionReadiness(manager, options = {}) {
1245
1246
  * @returns {number|null} Reference price or null
1246
1247
  */
1247
1248
  export function resolveSpreadMarketReference(manager) {
1248
- const live = Number(manager?._lastFilledPrice);
1249
- const liveType = manager?._lastFilledType;
1250
- if (manager?.lastFillPivotSource === 'fill' && Number.isFinite(live) && live > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1251
- return live;
1252
- }
1253
- const market = Number(manager?._lastMarketFillPrice);
1254
- const marketType = manager?._lastMarketFillType;
1255
- if (Number.isFinite(market) && market > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1256
- return market;
1257
- }
1258
- return null;
1249
+ // ONE predicate: the price-only reader and the price+side reader must never
1250
+ // disagree about what counts as a fill-provenanced market reference.
1251
+ return resolveFillProvenancedReference(manager).price;
1259
1252
  }
1260
- /**
1261
- * Resolve the reference the generic LAST-FILL-GUARD judges against.
1262
- *
1263
- * Prefers the live armed pivot. When that is cold (a grid regeneration
1264
- * cleared it, or a rejected-snapshot reset ran) it falls back to the
1265
- * bot-scoped last-market-fill row — the same market truth spread correction
1266
- * already uses. This is what stops a rebuild from silently un-arming the
1267
- * guard until the next fill: the price the account last traded at is known,
1268
- * so a CREATE/rotation must still not cross it.
1269
- *
1270
- * Read-time fallback only: it does NOT mutate the pivot or persist an
1271
- * old-generation value, so the genesis-bound pivot/persist contract is
1272
- * unchanged. The guard still validates the value onto the CURRENT ladder via
1273
- * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
1274
- * regenerated geometry stays the authority on which placements are off-grid.
1275
- *
1276
- * @param {Object} manager - OrderManager instance
1277
- * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1278
- */
1279
1253
  /**
1280
1254
  * Re-anchor the boundary so the newest REAL fill sits outside its own window.
1281
1255
  *
@@ -1293,16 +1267,29 @@ export function resolveSpreadMarketReference(manager) {
1293
1267
  *
1294
1268
  * Only a genuine on-ladder fill price is accepted (same one-increment drift
1295
1269
  * bound as `resolveOnGridPivot`), and the candidate must pass the same
1296
- * placed-order-aware validation the boundary commit gate uses, so a re-anchor
1297
- * can never strand a live order inside the re-typed band.
1270
+ * placed-order-aware validation the boundary commit gate uses
1271
+ * (`validatePersistedBoundary` — the SAME gate the restore and commit paths
1272
+ * use), so a re-anchor can never strand a live order inside the re-typed band.
1273
+ *
1274
+ * ELIGIBILITY (same rule as the crawl, see deriveTargetBoundary):
1275
+ * - EDGE-pinned insurance fills never anchor. An edge fill is by definition
1276
+ * outside the window it would move, and it is a book event (a fat-finger
1277
+ * wick), not market movement — the crawl already excludes it, and an
1278
+ * absolute anchor from a grid-edge price would teleport the window to that
1279
+ * edge. Such fills also never arm the pivot (recordLastFilledPrices skips
1280
+ * them), so the reference can only be a window fill.
1281
+ * - PARTIAL fills DO anchor: a partial at the far slot is still a real trade
1282
+ * at a real price, and the residual it leaves at the anchor slot is
1283
+ * explicitly allow-listed below (otherwise the geometry deadlocks).
1298
1284
  *
1299
1285
  * @param {Object} manager - OrderManager (pivot + genesis)
1300
1286
  * @param {number|null} boundaryIdx - Boundary the derivation would commit
1301
1287
  * @param {Array<Object>} slots - Grid slots (current generation)
1302
1288
  * @param {number} gapSlots - Gap band width
1289
+ * @param {Array<Object>} [fills] - Current fill batch (extremum resolution)
1303
1290
  * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
1304
1291
  */
1305
- export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots) {
1292
+ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots, fills = null) {
1306
1293
  // NB: Number(null) === 0 and Number('') === 0 — a boundary-less manager must
1307
1294
  // not be re-anchored onto slot 0 (same absent-value trap as
1308
1295
  // consumePendingFillCrawls).
@@ -1312,7 +1299,13 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
1312
1299
  const boundary = Number(boundaryIdx);
1313
1300
  if (!Number.isFinite(boundary))
1314
1301
  return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1315
- const ref = resolveLastFillGuardReference(manager);
1302
+ // An absolute re-anchor must be a FILL fact, never a book seed. The
1303
+ // generic guard deliberately accepts a one-sided book seed as a pricing
1304
+ // hint, but using that heuristic as the geometry anchor would move the
1305
+ // boundary off our own resting order price. Prefer the live pivot only
1306
+ // when its provenance is 'fill'; otherwise fall back to the bot-scoped
1307
+ // last-market-fill row (a real trade that survives grid regeneration).
1308
+ const ref = resolveFillProvenancedReference(manager);
1316
1309
  const price = Number(ref?.price);
1317
1310
  if (!Number.isFinite(price) || price <= 0)
1318
1311
  return { boundaryIdx: boundary, reanchored: false, reason: 'cold-pivot' };
@@ -1342,21 +1335,67 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
1342
1335
  if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - price) / price > maxDrift) {
1343
1336
  return { boundaryIdx: boundary, reanchored: false, reason: 'off-ladder-fill' };
1344
1337
  }
1338
+ // BATCH EXTREMUM: the pivot is the LAST-processed fill, but a sweep is
1339
+ // processed in chunks and the pivot is overwritten per chunk (live
1340
+ // incident: one sweep's pivot bounced 1366 -> 1349 -> 1361). Anchoring on
1341
+ // the last chunk under-advances the window and leaves the furthest fill's
1342
+ // counter-order in-band. The rail must clear the FURTHEST fill of the side:
1343
+ // max slot for SELL fills, min slot for BUY fills.
1344
+ let anchorIdx = idx;
1345
+ let anchorPrice = price;
1346
+ const batchExtremum = resolveFillAnchorIndex(fills, side, genesis, maxDrift);
1347
+ if (batchExtremum) {
1348
+ anchorIdx = batchExtremum.idx;
1349
+ if (batchExtremum.price != null && Number.isFinite(batchExtremum.price) && batchExtremum.price > 0) {
1350
+ anchorPrice = batchExtremum.price;
1351
+ }
1352
+ }
1345
1353
  const gap = Number.isFinite(Number(gapSlots)) && Number(gapSlots) >= 0 ? Math.floor(Number(gapSlots)) : 0;
1346
1354
  const slotCount = Array.isArray(slots) ? slots.length : 0;
1347
1355
  if (slotCount === 0)
1348
1356
  return { boundaryIdx: boundary, reanchored: false, reason: 'no-slots' };
1349
1357
  const ceiling = (slotCount - gap - 1) >= 0 ? (slotCount - gap - 1) : (slotCount - 1);
1350
- const required = side === ORDER_TYPES.SELL ? idx - gap : idx - 1;
1358
+ const required = side === ORDER_TYPES.SELL ? anchorIdx - gap : anchorIdx - 1;
1351
1359
  if (side === ORDER_TYPES.SELL ? boundary >= required : boundary <= required) {
1352
1360
  return { boundaryIdx: boundary, reanchored: false, reason: 'already-outside' };
1353
1361
  }
1354
1362
  const candidate = Math.max(0, Math.min(ceiling, required));
1355
1363
  if (candidate === boundary)
1356
1364
  return { boundaryIdx: boundary, reanchored: false, reason: 'no-op' };
1365
+ // Clamping can defeat the anchor: a fill near the grid ceiling needs
1366
+ // `required > ceiling`, so the clamped candidate still leaves the fill
1367
+ // inside its own window. Fail closed instead of reporting a re-anchor that
1368
+ // did not move the fill outside.
1369
+ const outsideWindow = side === ORDER_TYPES.SELL ? candidate >= required : candidate <= required;
1370
+ if (!outsideWindow) {
1371
+ return { boundaryIdx: boundary, reanchored: false, reason: 'ceiling-clamped' };
1372
+ }
1373
+ // The fill's OWN residual is not a stranding placement: a partial fill
1374
+ // leaves the remainder at the fill slot, and any boundary that puts the
1375
+ // fill outside its window necessarily puts that slot inside the implied
1376
+ // band. Allow exactly that residual (PARTIAL, same side, same ladder
1377
+ // level); every other in-band order still refuses the re-anchor.
1378
+ const allowedInBandSlotIds = [];
1379
+ const fillSlotOrder = Array.isArray(slots) ? slots[anchorIdx] : null;
1380
+ if (fillSlotOrder && fillSlotOrder.orderId
1381
+ && fillSlotOrder.state === ORDER_STATES.PARTIAL
1382
+ && fillSlotOrder.type === side) {
1383
+ let orderIdx = null;
1384
+ try {
1385
+ orderIdx = Number(MathUtils.slotIndexForPrice(Number(fillSlotOrder.price), genesis));
1386
+ }
1387
+ catch {
1388
+ orderIdx = null;
1389
+ }
1390
+ const orderPrice = Number(fillSlotOrder.price);
1391
+ if (orderIdx === idx && Number.isFinite(orderPrice) && orderPrice > 0
1392
+ && Math.abs(orderPrice - price) / price <= maxDrift) {
1393
+ allowedInBandSlotIds.push(String(fillSlotOrder.id));
1394
+ }
1395
+ }
1357
1396
  let check = { ok: true };
1358
1397
  try {
1359
- check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap);
1398
+ check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap, allowedInBandSlotIds.length > 0 ? { allowInBandSlotIds: allowedInBandSlotIds } : undefined);
1360
1399
  }
1361
1400
  catch (err) {
1362
1401
  check = { ok: false, reason: getErrorMessage(err) };
@@ -1365,13 +1404,130 @@ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlo
1365
1404
  return { boundaryIdx: boundary, reanchored: false, reason: `unsafe: ${check?.reason ?? 'unknown'}` };
1366
1405
  }
1367
1406
  try {
1368
- manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${idx} ` +
1369
- `(${price.toFixed(6)}); boundary ${boundary} -> ${candidate} so the fill sits outside ` +
1407
+ manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${anchorIdx} ` +
1408
+ `(${anchorPrice.toFixed(6)}); boundary ${boundary} -> ${candidate} so the fill sits outside ` +
1370
1409
  `its own window (crawl alone cannot recover a window behind the fill)`, 'warn');
1371
1410
  }
1372
1411
  catch { /* logging is best-effort */ }
1373
- return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot: idx };
1412
+ return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot: anchorIdx };
1413
+ }
1414
+ /**
1415
+ * Resolve the EXTREMUM fill of one side in a fill batch, mapped onto the
1416
+ * genesis ladder.
1417
+ *
1418
+ * The pivot is the LAST-processed fill, which a chunked sweep overwrites per
1419
+ * chunk, so the geometry anchor must be the batch's furthest fill of that side
1420
+ * (max slot for SELL, min slot for BUY) — otherwise the furthest fill's
1421
+ * counter-order lands inside the implied band. Prices are the real execution
1422
+ * prices (sync_engine stamps them from the chain), with the slot id as a
1423
+ * legacy fallback for fill records that carry no price.
1424
+ *
1425
+ * Pure: reads the batch only, no manager state.
1426
+ *
1427
+ * @param {Array<Object>} fills - Fill batch
1428
+ * @param {string} side - ORDER_TYPES.BUY / SELL (entries of the other side are ignored)
1429
+ * @param {Object} genesis - Genesis ladder
1430
+ * @param {number} maxDrift - One-increment drift bound for a price to count as on-ladder
1431
+ * @returns {{idx: number, price: number|null}|null} Extremum, or null when the batch has no usable entry for the side
1432
+ */
1433
+ function resolveFillAnchorIndex(fills, side, genesis, maxDrift) {
1434
+ if (!Array.isArray(fills) || fills.length === 0)
1435
+ return null;
1436
+ let best = null;
1437
+ for (const f of fills) {
1438
+ if (!f || f.type !== side)
1439
+ continue;
1440
+ let fIdx = null;
1441
+ let fPrice = null;
1442
+ const rawPrice = Number(f.price);
1443
+ if (Number.isFinite(rawPrice) && rawPrice > 0) {
1444
+ try {
1445
+ const candidateIdx = Number(MathUtils.slotIndexForPrice(rawPrice, genesis));
1446
+ const candidateLevel = Number(MathUtils.priceForSlot(candidateIdx, genesis));
1447
+ if (Number.isFinite(candidateIdx) && candidateIdx >= 0
1448
+ && Number.isFinite(candidateLevel) && candidateLevel > 0
1449
+ && Math.abs(candidateLevel - rawPrice) / rawPrice <= maxDrift) {
1450
+ fIdx = candidateIdx;
1451
+ fPrice = rawPrice;
1452
+ }
1453
+ }
1454
+ catch { /* fall back to the slot id */ }
1455
+ }
1456
+ if (fIdx === null) {
1457
+ const idIdx = parseSlotIndex(f.id);
1458
+ if (idIdx !== null && idIdx !== undefined && Number.isFinite(Number(idIdx)) && Number(idIdx) >= 0) {
1459
+ fIdx = Number(idIdx);
1460
+ try {
1461
+ fPrice = Number(MathUtils.priceForSlot(fIdx, genesis));
1462
+ }
1463
+ catch {
1464
+ fPrice = null;
1465
+ }
1466
+ }
1467
+ }
1468
+ if (fIdx === null)
1469
+ continue;
1470
+ if (best === null
1471
+ || (side === ORDER_TYPES.SELL && fIdx > best.idx)
1472
+ || (side === ORDER_TYPES.BUY && fIdx < best.idx)) {
1473
+ best = {
1474
+ idx: fIdx,
1475
+ price: Number.isFinite(Number(fPrice)) && Number(fPrice) > 0 ? Number(fPrice) : null
1476
+ };
1477
+ }
1478
+ }
1479
+ return best;
1480
+ }
1481
+ /**
1482
+ * Resolve a FILL-PROVENANCED reference for absolute geometry repairs.
1483
+ *
1484
+ * `resolveLastFillGuardReference` intentionally accepts a one-sided book seed
1485
+ * as a guard hint. A re-anchor is different: it moves the boundary, so a
1486
+ * heuristic max-bid/min-ask price must never be treated as a trade. Accept the
1487
+ * live pivot only when `lastFillPivotSource === 'fill'`; otherwise fall back to
1488
+ * the bot-scoped last-market-fill row, which is written only by real fills and
1489
+ * survives grid regeneration.
1490
+ * @param {Object} manager - OrderManager instance
1491
+ * @returns {{price: number|null, type: string|null}}
1492
+ */
1493
+ function resolveFillProvenancedReference(manager) {
1494
+ if (manager?.lastFillPivotSource === 'fill') {
1495
+ const livePrice = Number(manager?._lastFilledPrice);
1496
+ const liveType = manager?._lastFilledType;
1497
+ if (Number.isFinite(livePrice) && livePrice > 0 && (liveType === ORDER_TYPES.BUY || liveType === ORDER_TYPES.SELL)) {
1498
+ return { price: livePrice, type: liveType };
1499
+ }
1500
+ }
1501
+ const marketPrice = Number(manager?._lastMarketFillPrice);
1502
+ const marketType = manager?._lastMarketFillType;
1503
+ if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1504
+ return { price: marketPrice, type: marketType };
1505
+ }
1506
+ return { price: null, type: null };
1374
1507
  }
1508
+ /**
1509
+ * Resolve the reference the generic LAST-FILL-GUARD judges against.
1510
+ *
1511
+ * Prefers the live armed pivot. When that is cold (a grid regeneration
1512
+ * cleared it, or a rejected-snapshot reset ran) it falls back to the
1513
+ * bot-scoped last-market-fill row — the same market truth spread correction
1514
+ * already uses. This is what stops a rebuild from silently un-arming the
1515
+ * guard until the next fill: the price the account last traded at is known,
1516
+ * so a CREATE/rotation must still not cross it.
1517
+ *
1518
+ * Read-time fallback only: it does NOT mutate the pivot or persist an
1519
+ * old-generation value, so the genesis-bound pivot/persist contract is
1520
+ * unchanged. The guard still validates the value onto the CURRENT ladder via
1521
+ * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
1522
+ * regenerated geometry stays the authority on which placements are off-grid.
1523
+ *
1524
+ * The rebuild path re-arms the pivot explicitly (rearmLastFillPivotFromMarketFill)
1525
+ * so this fallback covers only the window before that write, not the whole
1526
+ * post-rebuild lifetime.
1527
+ *
1528
+ * @param {Object} manager - OrderManager instance
1529
+ * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1530
+ */
1375
1531
  export function resolveLastFillGuardReference(manager) {
1376
1532
  const livePrice = Number(manager?._lastFilledPrice);
1377
1533
  const liveType = manager?._lastFilledType;
@@ -1400,18 +1556,21 @@ export function resolveLastFillGuardReference(manager) {
1400
1556
  * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
1401
1557
  * price counts as blocked — that is a re-place at the just-filled level, the
1402
1558
  * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
1403
- * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
1404
- * increment takes no part (kept in the signature for call-site stability).
1559
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled.
1560
+ *
1561
+ * Signature note: the old band rule also consumed order size and the grid
1562
+ * increment (it judged against `pivot ± increment/2`). Both are gone on
1563
+ * purpose — re-adding an increment term re-opens retrospective §9.7 (a BUY
1564
+ * below a SELL fill was blocked, a SELL one tick above our cost was blocked,
1565
+ * and spread tightening became structurally impossible after any fill).
1405
1566
  *
1406
1567
  * @param {number} price - Target order price
1407
- * @param {number} _size - Order size (unused, kept for compat)
1408
1568
  * @param {string} type - ORDER_TYPES.BUY/SELL
1409
1569
  * @param {number|null} lastPrice - Most recent fill price
1410
1570
  * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
1411
- * @param {number|any} _incrementPercent - Unused (kept for signature compat)
1412
1571
  * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
1413
1572
  */
1414
- export function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, _incrementPercent) {
1573
+ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
1415
1574
  const numPrice = Number(price);
1416
1575
  if (!Number.isFinite(numPrice))
1417
1576
  return { blocked: false, pivot: null };
@@ -1468,6 +1627,40 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
1468
1627
  manager.logger?.log?.(`[SPREAD-CORRECTION] Restored last-market-fill ${row.price}(${row.type}) age=${Math.round((now - row.fillsAt) / 1000)}s — spread correction will not trade through it`, 'info');
1469
1628
  return true;
1470
1629
  }
1630
+ /**
1631
+ * Re-arm the LAST-FILL-GUARD pivot from the bot-scoped market-fill row.
1632
+ *
1633
+ * The grid-rebuild path deliberately clears the armed pivot (a new generation).
1634
+ * The guard must NOT stay cold afterwards: the price the account last traded at
1635
+ * is still market truth, so the pivot is re-armed on the NEW generation
1636
+ * explicitly, through the single shared writer, at the original fill timestamp.
1637
+ * That makes the documented contract real ("the guard re-arms against the new
1638
+ * ladder") instead of relying on the read-time fallback in
1639
+ * `resolveLastFillGuardReference` for the whole post-rebuild lifetime — a
1640
+ * fallback that cannot be re-validated, persisted or logged.
1641
+ *
1642
+ * Provenance stays 'fill' (a book seed never qualifies). The price is not
1643
+ * rewritten: an off-new-ladder value is handled by the same one-increment
1644
+ * `resolveOnGridPivot` rule every other probe uses.
1645
+ *
1646
+ * @param {Object} manager - OrderManager instance
1647
+ * @returns {boolean} True when a pivot was re-armed
1648
+ */
1649
+ export function rearmLastFillPivotFromMarketFill(manager) {
1650
+ if (!manager)
1651
+ return false;
1652
+ const ref = resolveFillProvenancedReference(manager);
1653
+ const price = Number(ref?.price);
1654
+ const type = ref?.type;
1655
+ if (!Number.isFinite(price) || price <= 0 || (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL))
1656
+ return false;
1657
+ const at = Number(manager?._lastFilledAt) || Number(manager?._lastMarketFillAt) || Date.now();
1658
+ if (!setLastFillPivot(manager, type, price, 'fill', at))
1659
+ return false;
1660
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Re-armed on the new generation: ${price}(${type}) from the last real fill ` +
1661
+ `(age ${Math.max(0, Math.round((Date.now() - at) / 1000))}s) — the guard survives a rebuild by design`, 'info');
1662
+ return true;
1663
+ }
1471
1664
  /**
1472
1665
  * Shared field gate for a persisted fill-derived row: finite price > 0,
1473
1666
  * BUY/SELL side, finite positive timestamp. One shape contract for the
@@ -1893,9 +2086,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1893
2086
  // stays a rail-typed VIRTUAL hole (size preserved for the
1894
2087
  // rotation pairing downstream); only true gap-band slots
1895
2088
  // become side-neutral SPREAD.
1896
- const holeGeoType = OrderUtils.geometryTypeForSlotIndex(OrderUtils.parseSlotIndex
1897
- ? OrderUtils.parseSlotIndex(current?.id)
1898
- : null, workingBoundaryIdx, gapSlots);
2089
+ const holeGeoType = OrderUtils.geometryTypeForSlotIndex(parseSlotIndex(current?.id), workingBoundaryIdx, gapSlots);
1899
2090
  workingGrid.set(onChainOrder.id, (holeGeoType === ORDER_TYPES.BUY || holeGeoType === ORDER_TYPES.SELL)
1900
2091
  ? OrderUtils.toRailHolePlaceholder(current, holeGeoType)
1901
2092
  : OrderUtils.convertToSpreadPlaceholder(current));
@@ -40,6 +40,7 @@ interface ReconcileGridOptions {
40
40
  dustThresholdPercent?: number;
41
41
  gapSlots?: number;
42
42
  assets?: AssetPair | null;
43
+ genesis?: unknown;
43
44
  evacStreaks?: Map<string, number>;
44
45
  [key: string]: unknown;
45
46
  }
@@ -573,7 +573,10 @@ function reconcileGrid(masterGrid, targetGrid, targetBoundary, options = {}) {
573
573
  let evacReady = [];
574
574
  try {
575
575
  if (options?.evacStreaks instanceof Map && hasPlanGeometry) {
576
- const candidates = detectGapEvacuationCandidates(masterGrid, validatedBoundary, planGapSlots);
576
+ const candidates = detectGapEvacuationCandidates(masterGrid, validatedBoundary, planGapSlots, {
577
+ assets: evacAssets,
578
+ genesis: options?.genesis ?? null
579
+ });
577
580
  const tick = updateGapEvacuationStreaks(options.evacStreaks, candidates);
578
581
  evacReady = tick.ready;
579
582
  if (evacReady.length > 0 && logger) {
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * Provides a unified IStorageAdapter interface for all filesystem operations.
5
5
  *
6
- * Usage:
7
- * const storage = require('./modules/storage').getStorage();
6
+ * Usage (from the repo root):
7
+ * import { getStorage } from './modules/storage/index.js';
8
+ * const storage = getStorage();
8
9
  * const data = storage.readJSON('/path/to/file.json');
9
10
  * storage.writeJSON('/path/to/file.json', { hello: 'world' });
10
11
  * if (storage.exists('/path/to/file.json')) { ... }
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * Provides a unified IStorageAdapter interface for all filesystem operations.
5
5
  *
6
- * Usage:
7
- * const storage = require('./modules/storage').getStorage();
6
+ * Usage (from the repo root):
7
+ * import { getStorage } from './modules/storage/index.js';
8
+ * const storage = getStorage();
8
9
  * const data = storage.readJSON('/path/to/file.json');
9
10
  * storage.writeJSON('/path/to/file.json', { hello: 'world' });
10
11
  * if (storage.exists('/path/to/file.json')) { ... }
@@ -227,6 +227,15 @@ export interface BotLike {
227
227
  _lastDeferredHoldResyncAt: number;
228
228
  _lastGridPriceInvariantResyncAt: number;
229
229
  _lastSpreadStaleResyncAt: number;
230
+ /**
231
+ * Fill pivot (`price|type`) the geometry-bind (`last-fill-blocked`) escalation
232
+ * already re-centered for. A re-center does not move the pivot, so a second
233
+ * request on the same fill only churns the new generation; cleared whenever
234
+ * the spread heals.
235
+ */
236
+ _lastGeometryResyncPivotKey: string;
237
+ /** Pivot key the "re-center cannot clear this pivot" warning was logged for. */
238
+ _geometryResyncWarnedPivotKey: string;
230
239
  _gridLockHoldWarnAt: number;
231
240
  _outOfSpreadSince: number;
232
241
  _outOfSpreadStaleWarned: boolean;
@@ -229,7 +229,7 @@ syncFromMaster(masterGrid, orderId, masterVersion?) {
229
229
  |--------|-------------|
230
230
  | `performSafeRebalance(fills, excludeIds)` | Entry point — delegates to COW |
231
231
  | `_applySafeRebalanceCOW(fills, excludeIds)` | Creates working grid, runs planning |
232
- | `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:205`, delegating to `utils/order.ts`) |
232
+ | `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts`, delegating to `utils/order.ts`) |
233
233
  | `_commitWorkingGrid(workingGrid, indexes, boundary, options = {})` | Atomic swap to master |
234
234
  | `_setRebalanceState(state)` | Track rebalance state |
235
235
  | `_currentWorkingGridStack` | Stack of active working-grid references during rebalance for fill sync; peek the innermost via `_peekWorkingGrid()`, managed with `_pushWorkingGridRef`/`_popWorkingGridRef`/`_releaseWorkingGridRef`/`_clearWorkingGridRef` |
@@ -57,12 +57,14 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
57
57
  - `_clearOrderCachesLogic` must bump `_gridVersion` so an in-flight COW plan (baseVersion from the pre-swap grid) is refused at commit instead of committing over a regenerated zero-slot grid.
58
58
 
59
59
  - `INV-COW-006` Boundary moves only on fills and same-batch spread promotion
60
- - Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`) and spread promotion move it, and promotion shifts it only onto orders placed in the same atomic batch (`prepareSpreadCorrectionOrders`).
60
+ - Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`), spread promotion, and the fill-driven rail clamp move it, and promotion shifts it only onto orders placed in the same atomic batch (`prepareSpreadCorrectionOrders`).
61
61
  - Funds drive order sizing/budget allocation only; `syncBoundaryToFunds`/`calculateFundDrivenBoundary` are deleted (1.5.3).
62
+ - `deriveRailBoundary` (`dexbot_cow_runtime.ts`, pre-broadcast) clamps the committed boundary to the batch's resulting rails: `maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1`. A fill's counter order is the rail fact, so it decides the boundary; an empty refill hole never outvotes it. Rail membership = the batch's own op destinations + master rail orders on their own side of the planned boundary (BUY at/below, SELL at/above the implied sellStart); a master order parked on the wrong side is a STRAY (refused-commit adoption, SPREAD-GUARD straggler, stranded hold) and is skipped, because clamping onto it would self-legalize the corrupt state (live: one stray sell clamped 138 → 115). Rail indices are the orders' LIVE chain price (`resolveLiveOrderLadderPosition`), not stale slot ids. A crossed/over-ceiling rail fails closed (`rail-crossed` / `rail-exceeds-grid`) and keeps the previous value instead of legalizing it; the result then passes the shared `validatePersistedBoundary` gate (with cancel/rotation sources allow-listed), so the rail clamp and the fill re-anchor end in one validator.
62
63
 
63
64
  - `INV-COW-007` Boundary hold on guard-skipped refills
64
65
  - When a slot on the plan's refill wire (`collectRefillSlotIds`: the plan's CREATE ids minus edge-ladder edge ids) was guard-skipped at broadcast (`skippedUpdateSlotIds` ∪ `clampedUpdateSlotIds` ∪ `skippedCreateSlotIds`), `resolveRefillBoundaryHold` keeps the COMMITTED boundary instead of committing the plan's shifted one over the stranded rail hole; the grid still commits.
65
66
  - Edge-ladder CREATEs are excluded because reserves are static edge insurance whose fills never crawl — a skipped reserve must not pin geometry.
67
+ - The hold is intersected with `deriveRailBoundary`: when the batch actually placed a counter order above the committed boundary, the rail clamp advances the boundary (the hold becomes a no-op and the counter stays live). The hold still applies when nothing was placed on the promoted rail. `boundaryHeld` is `effectiveBoundary !== workingBoundary`, so crawl consumption follows the value actually committed.
66
68
  - The hold rides to the commit as `options.boundaryHeld`, which suppresses the pending-crawl clear.
67
69
  - `trackBoundaryHold` counts consecutive hold batches (`manager._consecutiveBoundaryHolds`, cleared on the first clean batch) with a last-hold snapshot (`manager._lastBoundaryHoldInfo`); runs of 3+ escalate visibly. It also records a hold signature (`manager._lastHeldPlanSignature`: committed boundary + guard pivot + `_lastFilledAt` + held wire) so a fill-less re-plan of an unchanged state defers instead of re-broadcasting the identical vetoed plan.
68
70
  - Fill-driven rebalances never sleep on `_broadcastingFlag` inside `_fillProcessingLock`: `performSafeRebalance({deferIfBroadcasting:true})` returns a `deferred` result and the region-end hook schedules one no-fill rebalance (`schedulePostRecoveryRebalance`). This prevents the 20s lock-acquisition-timeout cascade when a broadcast region outlives the 30s `_awaitBroadcastIdle` wait. The stale-flag watchdog (`_clearStaleBroadcastFlag`, 120s) fires the same region-end hook when it hard-clears a leaked flag, so deferred fills are woken even when the region never ends through `stopBroadcasting()`.
@@ -71,7 +73,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
71
73
  - `INV-COW-008` Owed fill crawls survive unapplied commits
72
74
  - `order/strategy.ts` records a crawl per shift-eligible fill at intake (slot-level dedupe, capped at 500); `deriveTargetBoundary` folds still-owed `_pendingFillCrawls` into the next derivation, excluding the current batch's slots, edge slots, and window members — a window that reaches the grid edge is not an edge order, using the same window exclusion every placement picker and `countLiveEdgeOrders` apply.
73
75
  - `_commitWorkingGrid` clears them only when the plan's boundary was actually applied — a held boundary (`boundaryHeld`), a gate-rejected boundary, and a null boundary all leave them owed.
74
- - A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. Fail-closed preconditions: fill-provenanced pivot with a recorded side, on-ladder price within one increment, and `validatePersistedBoundary` (a strand refuses the re-anchor). This is what unblocks a sweep whose crawls were lost, without a rebuild.
76
+ - A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. The anchor index is the current fill batch's EXTREMUM for the fill side (max slot for SELL, min slot for BUY), not the mutable last-processed pivot: a sweep processed in chunks overwrites the pivot per chunk (live: 1366 → 1349 → 1361), and anchoring on a non-extremum leaves the furthest fill's counter order in-band. Prices come from the fill record (the real execution price, `INV-COW-011`) with the slot id as a legacy fallback. Fail-closed preconditions: a pivot whose `lastFillPivotSource` is `fill` (a book seed never anchors; the bot-scoped last-market-fill row is the fallback), on-ladder price within one increment, a post-clamp target that actually puts the fill outside the window, and `validatePersistedBoundary` (a strand refuses the re-anchor). ELIGIBILITY matches the crawl: EDGE-pinned insurance fills never arm the pivot (`recordLastFilledPrices` skips them, shared classifier `collectEdgePinnedFillIds`) and so can never anchor — an edge order is static insurance, not market movement, and an absolute anchor at a rail-edge price would teleport the window there; PARTIAL fills still anchor (real trade) because the fill's OWN PARTIAL residual at the anchor slot is explicitly allow-listed (it is inside the band by construction). Startup/recovery load paths tolerate that pure in-band state (`tolerateTransientStranding`) so a restart does not rebuild the boundary before GAP-EVAC clears the residual. A successful re-anchor is absolute: it consumes the whole pending-crawl snapshot taken at plan time, so no older delta can be applied on top.
75
77
  - Consumption is SCOPED to what the derivation applied: `deriveTargetBoundary` returns `consumedCrawlIds` (the owed records whose shift it folded, plus the records it deliberately never counts — current-batch slots, edge-classified slots, malformed records), the plan carries it (`buildSuccessResult` → `CowResult` → `_commitWorkingGrid` options), and `_consumePendingFillCrawls` drops exactly those, logging `Dropped N … kept=M`. A capped fold consumes only the entries it actually applied (same-side prefix up to the applied magnitude), so the remainder stays owed exactly once. `_clearPendingFillCrawls` remains the explicit allowed-loss path (rebuild, rejected snapshot, restart replay) and drops everything.
76
78
  - A commit **without** the wire consumes nothing (a create-only plan never derived a boundary): clearing it would be the old silent-loss bug (2026-10-25: 7 slots 147–153 swept, every record dropped, boundary ending 7 levels behind).
77
79
  - `consumePendingFillCrawls` applies them onto a restored finite boundary; `applyPersistedPendingCrawls` is the shared startup/recovery wrapper used before sync/reconcile; `_clearPendingFillCrawls` drops them when the boundary is re-anchored (grid rebuild via `initializeGrid`, rejected snapshot via `rejectCorruptedGridSnapshot`, persisted snapshot wipe via `AccountOrders.clearGrid`).
@@ -82,7 +84,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
82
84
  - The row carries `{price, type, fillsAt, genesisHash}` validated by one shared gate (`normalizeLastFillPivot`) used by BOTH the `storeMasterGrid` sanitizer and the loader — the two shape checks cannot drift. `null` from the payload builder always clears the stored row (consumed pivot / cold manager / no live genesis), `undefined` stays a legacy no-op for old callers, and a malformed shape also clears.
83
85
  - Restore ordering: `grid.loadGrid` restores the pivot right after `_restoreBoundary` — with the persisted genesis applied and the grid re-typed, BEFORE the first reconcile/broadcast — so a restart cannot re-open the cold window where evacuation stamps get applied against a boundary still being rebuilt. All `loadGrid` callers (startup resume, price-match resume, recovery reload) inherit it; there is no second restore call site to drift.
84
86
  - Validation chain (`restoreLastFillPivot`): TTL expiry (`GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS`, 24h; the pivot is a "latest fill" fact, not a permanent ratchet; expired pivots hand over to the startup book seed) and genesis binding (mismatched hash = dead generation) erase the row through one shared drop path (`clearPersistedLastFillPivot` under the bot's persistence lock, best-effort). Off-grid refusal (`resolveOnGridPivot` — the runtime's own ladder validator, imported lazily from the restore site so ONE implementation serves both the per-probe live guard and the restore; the restorer can never accept a value the runtime would refuse per probe) is a no-op that falls back to the book seed and leaves the row for the next snapshot flush to clear (the cold in-memory pivot makes the payload builder return null). The snapped ladder level is restored, never the raw float, and the ORIGINAL `fillsAt` is preserved through `setLastFillPivot`'s `atMs` param so the TTL keeps meaning "age of the last fill", not "time since this restart".
85
- - Generation invalidation mirrors the pending-crawl ledger: `initializeGrid` and `rejectCorruptedGridSnapshot` clear the in-memory pivot via `resetLastFillPivot` (exposed as `OrderManager._resetLastFillPivot`), which clears the FULL scalar family — per-side mirrors included — so `seedLastFilledPricesFromBook`'s cold gate cannot be silently suppressed by stale per-side values after a grid rebuild, and `AccountOrders.clearGrid` wipes the persisted row with the snapshot. The guard re-arms on the first real fill of the new generation.
87
+ - Generation invalidation mirrors the pending-crawl ledger: `initializeGrid` and `rejectCorruptedGridSnapshot` clear the in-memory pivot via `resetLastFillPivot` (exposed as `OrderManager._resetLastFillPivot`), which clears the FULL scalar family — per-side mirrors included — so `seedLastFilledPricesFromBook`'s cold gate cannot be silently suppressed by stale per-side values after a grid rebuild, and `AccountOrders.clearGrid` wipes the persisted row with the snapshot.
88
+ - A rebuild then RE-ARMS explicitly (`rearmLastFillPivotFromMarketFill`) from the bot-scoped last-market-fill row, through the same writer, at the original timestamp and with provenance `'fill'`. The guard must not go cold while the account's last trade price is known (pre-1.6.14 behaviour: a rebuild let a fresh grid sell below the last sale), and the re-arm must be a logged, persisted write rather than an accident of the read-time fallback — the rebuild site's comment and the runtime behaviour were allowed to differ before this. Consequence, pinned by test: the pivot SURVIVES a rebuild (bounded by the same 24h TTL). If the market has moved away from that price, the same-side rail reads `last-fill-blocked` and only a fill (or TTL expiry) restores it; the geometry-bind watchdog therefore re-centers at most ONCE per pivot (`_lastGeometryResyncPivotKey`) — a re-center cannot move the pivot, so a second attempt would only churn the new generation — and then reports that fact instead of escalating.
89
+ - EDGE-PINNED fills never arm the pivot: `recordLastFilledPrices` skips the ids returned by `collectEdgePinnedFillIds` (the same window/edge classifier the placement pickers use). An edge order is static fat-finger insurance, not market movement; letting a wick on one arm the pivot at a rail-edge price would veto that whole side of the book AND, because the pivot doubles as the re-anchor's absolute geometry anchor, teleport the window to the edge.
86
90
 
87
91
  - `INV-COW-010` Grid-layer spread-correction cycle is atomic and bounded
88
92
  - `checkSpreadCondition` holds the refcounted broadcast region (`startBroadcasting` / `stopBroadcasting`, released in `finally`) across its whole attempt loop, so a fill-driven rebalance defers rather than committing a master-version bump between the initial plan and its broadcast. This narrows the race; the COW commit guard remains the backstop.
@@ -90,20 +94,26 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
90
94
  - A transient refusal re-plans ONCE from fresh master (`replanSpreadCorrectionFromFreshMaster`, bounded by `TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`); a non-transient refusal (`commit-refused` / `update-target-missing` / `unmatched-chain-orders` / `shutdown`) is not retried and counts toward the out-of-spread stale clock.
91
95
  - Candidates are tightening-edge-only on real grid slots (`tightensSpread` + distance-to-edge ordering + `doesNotCrossMarket`) AND last-fill consistent: the planner applies the guard's own direction rule (`passesLastFill`, same pivot, same predicate) before the quota slice, so a batch is never built from ops the broadcast guard would drop. An unplaceable side reports the geometry bind `last-fill-blocked` instead of a wasted "prepared but not executed" cycle.
92
96
  - The budget spent by the loop is chain-truth for a known candidate set: `available = chainFree − virtualReservation` is circular when the reservation describes the very slots being funded, so an over-sized projection (rail sized from a larger balance or from inventory locked in resting orders) would read 0 forever (`planned 3, placing 0`, 84 minutes live). `deriveChainTruthFundBudget` re-derives it as `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available` is 0 **and** the reservation exceeds chain free (a zero caused by fees or an empty balance is a real constraint and is honoured); the chain stays the final arbiter.
93
- - Terminal stalls are named and escalated on their own windows rather than the structural 30 minutes: rail oversubscription (`availableFund = chainFree − virtual` reads 0 while the side still holds inventory) on `SPREAD_STALE_FUND_ESCALATE_MS`, the `last-fill-blocked` geometry bind on `SPREAD_STALE_GEOMETRY_ESCALATE_MS`, and the persistence clock clears only after sustained tolerance (`SPREAD_STALE_IN_TOLERANCE_RESET_MS`) or a placement.
97
+ - Terminal stalls are named and escalated on their own windows rather than the structural 30 minutes: rail oversubscription (`availableFund = chainFree − virtual` reads 0 while the side still holds inventory) on `SPREAD_STALE_FUND_ESCALATE_MS`, the `last-fill-blocked` geometry bind on `SPREAD_STALE_GEOMETRY_ESCALATE_MS` (capped at ONE re-center per fill pivot — `_lastGeometryResyncPivotKey` — because a re-center cannot move the pivot, and the skip is explained once instead of rebuilt every cooldown), and the persistence clock clears only after sustained tolerance (`SPREAD_STALE_IN_TOLERANCE_RESET_MS`) or a placement.
94
98
  - This is the grid layer's counterpart to `INV-COW-003` (COW-layer pre-broadcast re-plan) and to `INV-COW-007`'s broadcast-flag deferral contract.
95
99
 
100
+ - `INV-COW-011` Live-price provenance for fill, gap and crossing decisions
101
+ - A fill record carries the chain execution price (`sync_engine._computeFillTransitionResult` / pass-1 full-fill / pass-2 adoption), computed from paid/received amounts when only the history is available; the slot's generation price is a fallback, never the first choice. The queued-fill pivot refresh (`refreshLastFillPivotFromQueue`) likewise prefers fill economics over the slot price. The slot's identity price is NOT rewritten (`GRID-PRICE-INVARIANT`); only the transient fill/pivot fact uses the chain price.
102
+ - Gap-evacuation geometry maps an on-chain order's LIVE price onto the genesis ladder (`resolveLiveOrderLadderPosition`) before falling back to `parseSlotIndex(slot.id)`. Detection (`detectGapEvacuationCandidates`), the drain-time validation (`_validatePriceCorrectionEntry`), and the teeth (`_processGapEvacuationTeeth`) all use it, so a refused-commit adoption that leaves an order keyed at an in-rail slot cannot hide an in-band order.
103
+ - A price mismatch whose live chain price maps inside the gap band queues a cancel-only `gapEvacuation` correction and drops any opposite-kind (plain re-price) entry for the same chain order. Evacuation takes precedence over correcting the order back to a stale slot price.
104
+ - The crossing guard's candidate set (`buildCrossingCheckCandidates`) uses the live chain price for master and pending orders, so an emission cannot print onto a live opposite-side order that was adopted at a stale slot price.
105
+
96
106
  - `INV-PROJ-001` New projected orders remain virtual
97
107
  - Orders projected into empty slots must be `VIRTUAL` with no `orderId` until chain confirmation.
98
108
 
99
109
  - `INV-PROJ-002` Preserve on-chain PARTIAL size in projection
100
110
  - If identity is retained (`keepOrderId=true`) and current state is `PARTIAL`, projected size must preserve current on-chain remaining size.
101
111
  - It must not be overwritten by ideal geometric `targetSize`.
102
- - Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path at `modules/order/utils/validate.ts:1187`).
112
+ - Exception: a `PARTIAL` with a rotation/size-update action targeting its `orderId` does use `targetSize` (the explicit-UPDATE path in `projectTargetToWorkingGrid`, `modules/order/utils/validate.ts`).
103
113
  - Preserve-path size must be normalized to finite, non-negative value.
104
114
 
105
115
  - `INV-PROJ-003` ACTIVE on-chain projection preserves current size (same as PARTIAL)
106
- - If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts:1187`).
116
+ - If identity is retained and state is `ACTIVE`, projection preserves current on-chain size via the same `shouldPreserveSize` path as `PARTIAL` (`validate.ts`, `projectTargetToWorkingGrid`).
107
117
  - An explicit UPDATE action targeting the `orderId` is required to apply `targetSize`.
108
118
 
109
119
  - `INV-ID-001` Order identity retention rule
@@ -122,7 +132,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
122
132
  - `INV-ACC-003` Cross-bot fund registry invariant (INVARIANT 3)
123
133
  - Shared-account per-bot commitment must not exceed the bot's proportional share of chain balance.
124
134
  - Checked with widened tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
125
- - Registry failure logs an error (`order/accounting.ts:636-685`), not a silent skip.
135
+ - Registry failure logs an error (`order/accounting.ts`, cross-bot registry invariant block), not a silent skip.
126
136
 
127
137
  ---
128
138
 
@@ -263,7 +273,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
263
273
 
264
274
  - `INV-BATCH-001` Illegal state batch abort
265
275
  - `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
266
- - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:533`) is a test-only dead branch — production never emits that code; only a test stub uses it.
276
+ - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts`) is a test-only dead branch — production never emits that code; only a test stub uses it.
267
277
  - In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
268
278
  - Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
269
279
 
@@ -282,7 +292,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
282
292
  - NOT virtualize the slot.
283
293
  - Preserve `orderId` until sync reconciles it.
284
294
  - NOT mark the order as stale-cleaned.
285
- - Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts:273`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
295
+ - Fast path: if the batch result indicates `ORDER_SIZE_DRIFT_TARGETED` (`dexbot_state_recovery.ts`), a targeted repair applies the correction directly and skips `_triggerStateRecoverySync`.
286
296
 
287
297
  ---
288
298
 
@@ -306,7 +316,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
306
316
  - `INV-REG-001` Cross-bot allocation ≤ proportional share
307
317
  - Per-bot committed amounts (sum of on-chain orders) must not exceed `totalChainBalance × allocatedPercent`.
308
318
  - Violation triggers an error-level log entry (not silent), with tolerance `max(PERCENT_TOLERANCE * 3, 0.15)`.
309
- - Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts:617` filters `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
319
+ - Registry registration is pre-flight + atomic; only shared-account bots register (`dexbot.ts` derives `sharedAccounts` where `accountGroups[a].length > 1`), and registration completes before any shared-account bot starts.
310
320
  - Release happens in `DEXBot.shutdown`.
311
321
 
312
322
  - `INV-REG-002` Async-locked registry writes
@@ -1,7 +1,7 @@
1
1
  # DEXBot vs DEXBot2 — Detailed Comparison Report
2
2
 
3
3
  > **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
4
- > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.17).
4
+ > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.18).
5
5
  > **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
6
6
 
7
7
  ---
@@ -36,7 +36,7 @@
36
36
 
37
37
  | Attribute | DEXBot (original) | DEXBot2 |
38
38
  |---|---|---|
39
- | **Release Track** | 1.0.0 | v1.6.17 |
39
+ | **Release Track** | 1.0.0 | v1.6.18 |
40
40
  | **Language** | Python 3.6+ | TypeScript 5.x |
41
41
  | **Status** | Released 1.0.0, unmaintained | Active development |
42
42
  | **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
@@ -776,10 +776,10 @@ Where:
776
776
 
777
777
  | Metric | DEXBot | DEXBot2 |
778
778
  |---|---|---|
779
- | **Release Track** | 1.0.0 | v1.6.17 |
779
+ | **Release Track** | 1.0.0 | v1.6.18 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
- | **Last Commit** | May 23, 2020 | 2026-10-30 |
782
- | **Total Commits** | 2281 | 2,438 (current HEAD, v1.6.17 line) |
781
+ | **Last Commit** | May 23, 2020 | 2026-11-01 |
782
+ | **Total Commits** | 2281 | 2,457 (current HEAD, v1.6.18 line) |
783
783
  | **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
784
784
  | **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
785
785
  | **Test Files** | 16 Python test files | 327 `test_*.ts` files (310 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |