dexbot 1.6.16 → 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 (124) hide show
  1. package/CHANGELOG.md +58 -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/analysis/tradingview/README.md +2 -2
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  7. package/claw/package.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  10. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  11. package/dist/analysis/analyze_args.d.ts +2 -1
  12. package/dist/analysis/fills_source.d.ts +1 -8
  13. package/dist/analysis/fills_source.js +1 -1
  14. package/dist/analysis/grid_correction_check.d.ts +9 -6
  15. package/dist/analysis/grid_correction_check.js +56 -64
  16. package/dist/analysis/math_utils.d.ts +1 -1
  17. package/dist/analysis/trade_profitability.d.ts +1 -1
  18. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
  20. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  21. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  22. package/dist/market_adapter/cli_args.d.ts +6 -1
  23. package/dist/market_adapter/cli_args.js +16 -2
  24. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  25. package/dist/market_adapter/core/kibana_candles.js +3 -1
  26. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  27. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  28. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  29. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  30. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  31. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  32. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  33. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  34. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  35. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  36. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  37. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  38. package/dist/market_adapter/inputs/window_cache.js +14 -1
  39. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  40. package/dist/market_adapter/lp_chart_runner.js +3 -1
  41. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  42. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  43. package/dist/market_adapter/market_adapter.d.ts +10 -2
  44. package/dist/market_adapter/market_adapter.js +10 -11
  45. package/dist/market_adapter/utils/chain.d.ts +2 -3
  46. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  47. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  48. package/dist/market_adapter/utils/file_lock.js +1 -1
  49. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  50. package/dist/market_adapter/utils/native_history.js +3 -1
  51. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  52. package/dist/modules/account_bots.d.ts +3 -0
  53. package/dist/modules/bots_file_lock.d.ts +2 -2
  54. package/dist/modules/bots_file_lock.js +2 -2
  55. package/dist/modules/chain_keys.d.ts +1 -1
  56. package/dist/modules/constants.d.ts +6 -0
  57. package/dist/modules/constants.js +37 -6
  58. package/dist/modules/credit_pricing.d.ts +20 -1
  59. package/dist/modules/credit_pricing.js +23 -1
  60. package/dist/modules/credit_runtime.js +33 -16
  61. package/dist/modules/dexbot_class.d.ts +11 -1
  62. package/dist/modules/dexbot_class.js +15 -2
  63. package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
  64. package/dist/modules/dexbot_cow_runtime.js +507 -108
  65. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  66. package/dist/modules/dexbot_maintenance_runtime.js +117 -12
  67. package/dist/modules/dexbot_startup_runtime.js +7 -1
  68. package/dist/modules/graceful_shutdown.d.ts +2 -2
  69. package/dist/modules/graceful_shutdown.js +2 -2
  70. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  71. package/dist/modules/launcher/credential_daemon.js +60 -26
  72. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  73. package/dist/modules/node_manager.d.ts +1 -1
  74. package/dist/modules/node_manager.js +1 -1
  75. package/dist/modules/order/accounting.js +2 -1
  76. package/dist/modules/order/export.d.ts +2 -2
  77. package/dist/modules/order/export.js +2 -2
  78. package/dist/modules/order/grid.d.ts +26 -14
  79. package/dist/modules/order/grid.js +416 -73
  80. package/dist/modules/order/grid_reconcile.js +5 -1
  81. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  82. package/dist/modules/order/index.d.ts +22 -1
  83. package/dist/modules/order/manager.d.ts +40 -7
  84. package/dist/modules/order/manager.js +149 -23
  85. package/dist/modules/order/strategy.d.ts +5 -0
  86. package/dist/modules/order/strategy.js +44 -3
  87. package/dist/modules/order/sync_engine.d.ts +12 -1
  88. package/dist/modules/order/sync_engine.js +135 -20
  89. package/dist/modules/order/utils/math.d.ts +49 -10
  90. package/dist/modules/order/utils/math.js +71 -14
  91. package/dist/modules/order/utils/order.d.ts +65 -11
  92. package/dist/modules/order/utils/order.js +198 -28
  93. package/dist/modules/order/utils/system.d.ts +112 -2
  94. package/dist/modules/order/utils/system.js +338 -12
  95. package/dist/modules/order/utils/validate.d.ts +4 -1
  96. package/dist/modules/order/utils/validate.js +9 -2
  97. package/dist/modules/storage/index.d.ts +3 -2
  98. package/dist/modules/storage/index.js +3 -2
  99. package/dist/modules/types.d.ts +44 -2
  100. package/dist/scripts/analyze-credit.js +64 -23
  101. package/dist/scripts/bts_distribution.d.ts +66 -0
  102. package/dist/scripts/bts_distribution.js +2102 -0
  103. package/dist/scripts/token_distribution.d.ts +45 -0
  104. package/dist/scripts/token_distribution.js +1870 -0
  105. package/dist/unlock.js +42 -24
  106. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  107. package/docs/COW_INVARIANTS.md +24 -8
  108. package/docs/DEXBOT_COMPARISON.md +5 -5
  109. package/docs/EVOLUTION.md +10 -8
  110. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
  111. package/docs/GRID_PRICE_INVARIANT.md +29 -3
  112. package/docs/GRID_RECALCULATION.md +3 -3
  113. package/docs/GRID_RECONCILE.md +5 -5
  114. package/docs/LIFECYCLE.md +11 -11
  115. package/docs/LOGGING.md +22 -0
  116. package/docs/MPA_CREDIT_USAGE.md +3 -2
  117. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
  118. package/docs/README.md +1 -1
  119. package/docs/architecture.md +205 -6
  120. package/docs/developer_guide.md +12 -0
  121. package/market_adapter/README.md +11 -6
  122. package/modules/README.md +18 -14
  123. package/package.json +6 -3
  124. package/scripts/README.md +85 -148
@@ -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,17 +1246,264 @@ 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;
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;
1252
+ }
1253
+ /**
1254
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
1255
+ *
1256
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
1257
+ * behind the fill (a sweep filled several slots while the commit dropped the
1258
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
1259
+ * tightening slot on that side is then at/through the last fill and the
1260
+ * last-fill guard refuses all of them, while the funds sit in the resting
1261
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
1262
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
1263
+ *
1264
+ * The fill itself is the anchor, so place it outside its window:
1265
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
1266
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
1267
+ *
1268
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
1269
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
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).
1284
+ *
1285
+ * @param {Object} manager - OrderManager (pivot + genesis)
1286
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
1287
+ * @param {Array<Object>} slots - Grid slots (current generation)
1288
+ * @param {number} gapSlots - Gap band width
1289
+ * @param {Array<Object>} [fills] - Current fill batch (extremum resolution)
1290
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
1291
+ */
1292
+ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots, fills = null) {
1293
+ // NB: Number(null) === 0 and Number('') === 0 — a boundary-less manager must
1294
+ // not be re-anchored onto slot 0 (same absent-value trap as
1295
+ // consumePendingFillCrawls).
1296
+ if (boundaryIdx === null || boundaryIdx === undefined || boundaryIdx === '') {
1297
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1298
+ }
1299
+ const boundary = Number(boundaryIdx);
1300
+ if (!Number.isFinite(boundary))
1301
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
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);
1309
+ const price = Number(ref?.price);
1310
+ if (!Number.isFinite(price) || price <= 0)
1311
+ return { boundaryIdx: boundary, reanchored: false, reason: 'cold-pivot' };
1312
+ const side = ref.type === ORDER_TYPES.SELL ? ORDER_TYPES.SELL : ref.type === ORDER_TYPES.BUY ? ORDER_TYPES.BUY : null;
1313
+ if (!side)
1314
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-fill-side' };
1315
+ const genesis = manager?._genesis;
1316
+ const levels = genesis?.priceLevels;
1317
+ if (!genesis || !Array.isArray(levels) || levels.length === 0) {
1318
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-genesis' };
1319
+ }
1320
+ let idx;
1321
+ try {
1322
+ idx = Number(MathUtils.slotIndexForPrice(price, genesis));
1323
+ }
1324
+ catch {
1325
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1326
+ }
1327
+ if (!Number.isFinite(idx) || idx < 0)
1328
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1329
+ // Only a genuine ladder level: an off-ladder (orphan/adopted) fill price
1330
+ // must not be snapped into geometry. One increment is the caller's drift
1331
+ // bound everywhere else (resolveOnGridPivot), so reuse it here.
1332
+ const levelPrice = Number(MathUtils.priceForSlot(idx, genesis));
1333
+ const incrementPct = Math.abs(Number(manager?.config?.incrementPercent));
1334
+ const maxDrift = Number.isFinite(incrementPct) && incrementPct > 0 ? incrementPct / 100 : 0.005;
1335
+ if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - price) / price > maxDrift) {
1336
+ return { boundaryIdx: boundary, reanchored: false, reason: 'off-ladder-fill' };
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
+ }
1353
+ const gap = Number.isFinite(Number(gapSlots)) && Number(gapSlots) >= 0 ? Math.floor(Number(gapSlots)) : 0;
1354
+ const slotCount = Array.isArray(slots) ? slots.length : 0;
1355
+ if (slotCount === 0)
1356
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-slots' };
1357
+ const ceiling = (slotCount - gap - 1) >= 0 ? (slotCount - gap - 1) : (slotCount - 1);
1358
+ const required = side === ORDER_TYPES.SELL ? anchorIdx - gap : anchorIdx - 1;
1359
+ if (side === ORDER_TYPES.SELL ? boundary >= required : boundary <= required) {
1360
+ return { boundaryIdx: boundary, reanchored: false, reason: 'already-outside' };
1361
+ }
1362
+ const candidate = Math.max(0, Math.min(ceiling, required));
1363
+ if (candidate === boundary)
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
+ }
1396
+ let check = { ok: true };
1397
+ try {
1398
+ check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap, allowedInBandSlotIds.length > 0 ? { allowInBandSlotIds: allowedInBandSlotIds } : undefined);
1252
1399
  }
1253
- const market = Number(manager?._lastMarketFillPrice);
1400
+ catch (err) {
1401
+ check = { ok: false, reason: getErrorMessage(err) };
1402
+ }
1403
+ if (!check || check.ok !== true) {
1404
+ return { boundaryIdx: boundary, reanchored: false, reason: `unsafe: ${check?.reason ?? 'unknown'}` };
1405
+ }
1406
+ try {
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 ` +
1409
+ `its own window (crawl alone cannot recover a window behind the fill)`, 'warn');
1410
+ }
1411
+ catch { /* logging is best-effort */ }
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);
1254
1502
  const marketType = manager?._lastMarketFillType;
1255
- if (Number.isFinite(market) && market > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1256
- return market;
1503
+ if (Number.isFinite(marketPrice) && marketPrice > 0 && (marketType === ORDER_TYPES.BUY || marketType === ORDER_TYPES.SELL)) {
1504
+ return { price: marketPrice, type: marketType };
1257
1505
  }
1258
- return null;
1506
+ return { price: null, type: null };
1259
1507
  }
1260
1508
  /**
1261
1509
  * Resolve the reference the generic LAST-FILL-GUARD judges against.
@@ -1273,6 +1521,10 @@ export function resolveSpreadMarketReference(manager) {
1273
1521
  * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
1274
1522
  * regenerated geometry stays the authority on which placements are off-grid.
1275
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
+ *
1276
1528
  * @param {Object} manager - OrderManager instance
1277
1529
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1278
1530
  */
@@ -1289,6 +1541,48 @@ export function resolveLastFillGuardReference(manager) {
1289
1541
  }
1290
1542
  return { price: null, type: null };
1291
1543
  }
1544
+ /**
1545
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
1546
+ *
1547
+ * BUY blocked if price >= pivot (never place a higher BUY)
1548
+ * SELL blocked if price <= pivot (never place a lower SELL)
1549
+ *
1550
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
1551
+ * broadcast guard judge candidates with literally the same predicate: a batch
1552
+ * must never be built from a create the guard will drop, and a dropped batch
1553
+ * must never be reported as an unexplained "prepared but not executed".
1554
+ *
1555
+ * A placement on the permitted side is always profitable against the last trade
1556
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
1557
+ * price counts as blocked — that is a re-place at the just-filled level, the
1558
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
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).
1566
+ *
1567
+ * @param {number} price - Target order price
1568
+ * @param {string} type - ORDER_TYPES.BUY/SELL
1569
+ * @param {number|null} lastPrice - Most recent fill price
1570
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
1571
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
1572
+ */
1573
+ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
1574
+ const numPrice = Number(price);
1575
+ if (!Number.isFinite(numPrice))
1576
+ return { blocked: false, pivot: null };
1577
+ if (lastPrice == null || !Number.isFinite(Number(lastPrice)) || lastType == null)
1578
+ return { blocked: false, pivot: null };
1579
+ const pivot = Number(lastPrice);
1580
+ if (type === ORDER_TYPES.BUY && numPrice >= pivot)
1581
+ return { blocked: true, pivot, threshold: pivot };
1582
+ if (type === ORDER_TYPES.SELL && numPrice <= pivot)
1583
+ return { blocked: true, pivot, threshold: pivot };
1584
+ return { blocked: false, pivot: null, threshold: null };
1585
+ }
1292
1586
  /**
1293
1587
  * Restore the persisted bot-scoped last-market-fill reference into the
1294
1588
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -1333,6 +1627,40 @@ export function restoreLastMarketFill(manager, persisted, options = {}) {
1333
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');
1334
1628
  return true;
1335
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
+ }
1336
1664
  /**
1337
1665
  * Shared field gate for a persisted fill-derived row: finite price > 0,
1338
1666
  * BUY/SELL side, finite positive timestamp. One shape contract for the
@@ -1758,9 +2086,7 @@ export async function applyGridDivergenceCorrections(manager, accountOrders, _bo
1758
2086
  // stays a rail-typed VIRTUAL hole (size preserved for the
1759
2087
  // rotation pairing downstream); only true gap-band slots
1760
2088
  // become side-neutral SPREAD.
1761
- const holeGeoType = OrderUtils.geometryTypeForSlotIndex(OrderUtils.parseSlotIndex
1762
- ? OrderUtils.parseSlotIndex(current?.id)
1763
- : null, workingBoundaryIdx, gapSlots);
2089
+ const holeGeoType = OrderUtils.geometryTypeForSlotIndex(parseSlotIndex(current?.id), workingBoundaryIdx, gapSlots);
1764
2090
  workingGrid.set(onChainOrder.id, (holeGeoType === ORDER_TYPES.BUY || holeGeoType === ORDER_TYPES.SELL)
1765
2091
  ? OrderUtils.toRailHolePlaceholder(current, holeGeoType)
1766
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
  }
@@ -289,15 +290,17 @@ declare function buildAbortedResult(reason: string | null | undefined): {
289
290
  * @param {Object} params - Result parameters
290
291
  * @returns {Object} Success result object
291
292
  */
292
- declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }: {
293
+ declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }: {
293
294
  actions: CowAction[];
294
295
  stateUpdates: ManagedOrder[];
295
296
  workingGrid: WorkingGrid;
296
297
  workingBoundary: number | null;
297
298
  planningDuration: number;
298
299
  refillSlotIds?: unknown;
300
+ consumedCrawlIds?: unknown;
299
301
  }): {
300
302
  aborted: boolean;
303
+ consumedCrawlIds?: {} | null | undefined;
301
304
  refillSlotIds?: {} | null | undefined;
302
305
  actions: CowAction[];
303
306
  stateUpdates: ManagedOrder[];
@@ -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) {
@@ -1137,7 +1140,7 @@ function buildAbortedResult(reason) {
1137
1140
  * @param {Object} params - Result parameters
1138
1141
  * @returns {Object} Success result object
1139
1142
  */
1140
- function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }) {
1143
+ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }) {
1141
1144
  return {
1142
1145
  actions,
1143
1146
  stateUpdates,
@@ -1150,6 +1153,10 @@ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundar
1150
1153
  // planned boundary shift. May be absent/empty => executor treats as
1151
1154
  // empty (guarded default, never fail-open).
1152
1155
  ...(refillSlotIds !== undefined ? { refillSlotIds } : {}),
1156
+ // Crawl-ledger wire: the owed fill-crawl records this plan's derivation
1157
+ // actually folded. The commit clears only these; anything it could not
1158
+ // apply stays owed for the next derivation.
1159
+ ...(consumedCrawlIds !== undefined ? { consumedCrawlIds } : {}),
1153
1160
  aborted: false
1154
1161
  };
1155
1162
  }
@@ -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')) { ... }
@@ -38,7 +38,15 @@ export type OrderState = 'virtual' | 'active' | 'partial';
38
38
  * ('stale-snapshot' is degraded-ok, not a stall: the planner still acts, it
39
39
  * only withholds the LAST-FILL-GUARD bypass.)
40
40
  */
41
- export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | 'batch-not-executed' | 'apply-error';
41
+ export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | 'batch-not-executed' | 'apply-error'
42
+ /**
43
+ * Every tightening slot on the corrected side is at/through the last fill
44
+ * (SELL at/below it, BUY at/above it), so placement cannot repair the side:
45
+ * the bind is the grid WINDOW (a sell slot below the last sale means the
46
+ * boundary/crawl is behind the fill), not a missing candidate. Escalates on
47
+ * the short geometry window instead of the structural one.
48
+ */
49
+ | 'last-fill-blocked';
42
50
  /**
43
51
  * Dict with unknown values. The canonical replacement for
44
52
  * `Record<string, any>`; callers must narrow a value before using it.
@@ -219,10 +227,25 @@ export interface BotLike {
219
227
  _lastDeferredHoldResyncAt: number;
220
228
  _lastGridPriceInvariantResyncAt: number;
221
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;
222
239
  _gridLockHoldWarnAt: number;
223
240
  _outOfSpreadSince: number;
224
241
  _outOfSpreadStaleWarned: boolean;
225
242
  _outOfSpreadTransientCount: number;
243
+ /**
244
+ * Timestamp when the spread first read within tolerance. Cleared on any
245
+ * out-of-tolerance cycle. A single good reading no longer clears the
246
+ * persistence clock — it must hold for SPREAD_STALE_IN_TOLERANCE_RESET_MS.
247
+ */
248
+ _outOfSpreadToleranceSince: number;
226
249
  _strandedHoldSince: Map<string, number>;
227
250
  _recoverySyncInFlight: number;
228
251
  _batchInFlight: number;
@@ -235,7 +258,14 @@ export interface BotLike {
235
258
  _marketAdapterWatchdogInFlight: boolean;
236
259
  _blockchainFetchInFlight: number;
237
260
  _blockchainFetchIntervalMin: number;
238
- _spreadFundsExhausted: boolean;
261
+ /**
262
+ * A spread-correction stall was mirrored this cycle. ANY cause arms the
263
+ * targeted chain refresh (a missed fill can hide the tightening slot, a stale
264
+ * hold can zero the funds), so the flag is cause-agnostic — the cause itself
265
+ * is carried in `_spreadCorrectionStall`. Formerly `_spreadFundsExhausted`,
266
+ * which mislabelled geometry stalls as fund stalls.
267
+ */
268
+ _spreadStallArmed: boolean;
239
269
  _spreadCorrectionStall: SpreadCorrectionStall | null;
240
270
  _skipEmptyReadConfirmDelay: boolean;
241
271
  _testPollIntervalMs?: number;
@@ -950,6 +980,18 @@ export interface CreditRuntimeLike {
950
980
  }
951
981
  export interface OrderManagerLike {
952
982
  _consecutiveBoundaryHolds?: number;
983
+ /**
984
+ * Set by the spread-correction planner when the corrected side's rail reserves
985
+ * more than the chain free balance (virtual > free). Cleared when a correction
986
+ * becomes fundable again. The out-of-spread watchdog escalates on its short
987
+ * fund window when this is fresh.
988
+ */
989
+ _spreadRailOversubscribed?: {
990
+ side: string;
991
+ virtual: number;
992
+ free: number;
993
+ at: number;
994
+ } | null;
953
995
  _boundaryShiftBudgetBase?: number;
954
996
  _lastBoundaryHoldInfo?: unknown;
955
997
  _lastHeldPlanSignature?: {