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
@@ -47,8 +47,7 @@
47
47
  * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
48
  * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
49
  *
50
- * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
- * - parseSlotIndex(id) - Parse "slot-N" to its rail index
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (11 functions)
52
51
  * - filterOrdersByType(orders, orderType) - Filter orders by type
53
52
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
54
53
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
@@ -512,6 +511,25 @@ declare function toRailHolePlaceholder(order: ManagedOrder, railType: string, si
512
511
  * index, boundary, or gap width is unusable so callers fail closed.
513
512
  */
514
513
  declare function geometryTypeForSlotIndex(idx: number | string | null | undefined, boundaryIdx: number | string | null | undefined, gapSlots: number | string | null | undefined): OrderType | null;
514
+ /**
515
+ * Resolve a slot's LIVE ladder position from its on-chain price.
516
+ *
517
+ * `slot.id` is the local generation index; after a refused-commit adoption it
518
+ * can be stale (an order still keyed at slot-117 can be resting at the
519
+ * slot-138 price on chain). Evacuation geometry must therefore prefer the
520
+ * chain order's real price, mapped onto the genesis ladder, and only fall back
521
+ * to the stored slot index. The slot's identity price is NOT rewritten — this
522
+ * is a read-only geometry probe (GRID-PRICE-INVARIANT stays intact).
523
+ *
524
+ * @param slot - Grid slot (needs id/orderId/rawOnChain)
525
+ * @param assets - Asset pair (precision + ids) for parseChainOrder
526
+ * @param genesis - Genesis ladder for price -> slot index
527
+ * @returns {idx, price}: ladder index (null when unknown) and live price
528
+ */
529
+ declare function resolveLiveOrderLadderPosition(slot: ManagedOrder | null | undefined, assets: AssetPair | null | undefined, genesis: unknown): {
530
+ idx: number | null;
531
+ price: number | null;
532
+ };
515
533
  /**
516
534
  * Detect gap-evacuation candidates by GEOMETRY ONLY: live on-chain orders
517
535
  * whose parsed slot index sits strictly inside the gap band
@@ -519,12 +537,20 @@ declare function geometryTypeForSlotIndex(idx: number | string | null | undefine
519
537
  * Phase 2 retypes in-band actives to rail types, so type-based detection
520
538
  * would go blind exactly when evacuation matters.
521
539
  *
540
+ * The ladder index prefers the order's LIVE chain price (see
541
+ * resolveLiveOrderLadderPosition): a refused-commit adoption can leave the
542
+ * local slot id in-rail while the order actually rests inside the band.
543
+ *
522
544
  * @param {Map} masterGrid - Master grid (slotId -> order)
523
545
  * @param {number} boundaryIdx - Last BUY slot index (frozen at plan-build)
524
546
  * @param {number} gapSlots - Spread gap slot count (frozen at plan-build)
547
+ * @param {Object} [options] - assets/genesis for the live-price probe
525
548
  * @returns {Array} Candidates [{id, idx, type, price, size, orderId}]
526
549
  */
527
- declare function detectGapEvacuationCandidates(masterGrid: Map<string, ManagedOrder>, boundaryIdx: number | string | null, gapSlots: number | string | null): Array<{
550
+ declare function detectGapEvacuationCandidates(masterGrid: Map<string, ManagedOrder>, boundaryIdx: number | string | null, gapSlots: number | string | null, options?: {
551
+ assets?: AssetPair | null;
552
+ genesis?: unknown;
553
+ }): Array<{
528
554
  id: string;
529
555
  idx: number;
530
556
  type: OrderType;
@@ -562,13 +588,6 @@ declare function updateGapEvacuationStreaks(streakMap: Map<string, number>, cand
562
588
  * @returns {string} ORDER_TYPES.BUY or ORDER_TYPES.SELL
563
589
  */
564
590
  declare function resolveSpreadOrderSide(price: number | string, startPrice: number | string | null | undefined): OrderType;
565
- /**
566
- * Parse a grid slot id ("slot-123") to its rail index. Delegates to
567
- * shared slot.ts single source (GRID_PRICE_SLOT_DETERMINISM_PLAN §2.1).
568
- * @param {unknown} id - grid slot id string
569
- * @returns {number|null}
570
- */
571
- declare function parseSlotIndex(id: string | null | undefined): number | null;
572
591
  /**
573
592
  * Whether a parsed chain order matches a grid slot exactly:
574
593
  * type-compatible (slot may be SPREAD), price strictly equal via integer
@@ -1164,6 +1183,28 @@ declare function resolveEdgeOrders(config: OrderConfigView | null | undefined):
1164
1183
  * @returns {Set<string>|null} Edge slot ids, or null when side disabled
1165
1184
  */
1166
1185
  declare function edgeOrderIdSet(allSlots: SlotLike[], config: OrderConfigView | null | undefined, orderType: OrderType, anchorPrice?: unknown, excludeIds?: Set<string> | null): Set<string> | null;
1186
+ /**
1187
+ * Collect the fill ids that belong to EDGE-pinned insurance orders.
1188
+ *
1189
+ * Edge orders (grid floor / ceiling) are static fat-finger insurance, not
1190
+ * market movement: the boundary crawl already excludes their fills
1191
+ * (`deriveTargetBoundary`), and the same exclusion must apply to the fill
1192
+ * reference the LAST-FILL-GUARD pivots on and the boundary re-anchor uses.
1193
+ * Without it, one wick that triggers a far-out insurance order would arm the
1194
+ * guard at that price AND re-anchor the window to the grid edge — the exact
1195
+ * "teleport" class the geometry guards exist to prevent.
1196
+ *
1197
+ * Uses the SAME classification the placement pickers use (live window ids
1198
+ * excluded, live edge anchor) so "edge" cannot mean two things.
1199
+ *
1200
+ * @param {Object} manager - OrderManager (orders Map, config, boundary)
1201
+ * @param {Array<Object>} fills - Fill batch
1202
+ * @returns {Set<string>} Slot ids of edge-pinned fills (empty when none/unknown)
1203
+ */
1204
+ declare function collectEdgePinnedFillIds(manager: OrderManagerLike, fills: Array<{
1205
+ id?: string;
1206
+ type?: string;
1207
+ }> | null | undefined): Set<string>;
1167
1208
  /**
1168
1209
  * Window member ids for one side from the live manager (see
1169
1210
  * windowIdSetFromSlots). Delegates so the manager and explicit-geometry
@@ -1414,7 +1455,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1414
1455
  createIds: string[];
1415
1456
  all: string[];
1416
1457
  };
1417
- export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1458
+ export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1418
1459
  export type { CrawlEntry };
1419
1460
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1420
1461
  //# sourceMappingURL=order.d.ts.map
@@ -47,8 +47,7 @@
47
47
  * - updateGapEvacuationStreaks(...) - Tick per-slot gap-evacuation streak counter
48
48
  * - collectRefillSlotIds(...) - Refill-slot wire for the COW boundary hold
49
49
  *
50
- * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (12 functions)
51
- * - parseSlotIndex(id) - Parse "slot-N" to its rail index
50
+ * SECTION 6: FILTERING & DRIFT DIAGNOSTICS (11 functions)
52
51
  * - filterOrdersByType(orders, orderType) - Filter orders by type
53
52
  * - buildOutsideInPairGroups(items, accessors) - Outside->center pair grouping
54
53
  * - extractBatchOperationResults(result) - Extract operation_results from chain batch result
@@ -121,7 +120,7 @@ import Logger from '../../order/logger.js';
121
120
  import { sleep } from './system.js';
122
121
  import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
123
122
  import { hasGenesisLadder } from '../genesis_policy.js';
124
- import { parseSlotIndex as parseSlotIndexShared } from './slot.js';
123
+ import { parseSlotIndex } from './slot.js';
125
124
  const { isValidNumber, toFiniteNumber } = Format;
126
125
  const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
127
126
  const orderLogger = new Logger('Order');
@@ -413,8 +412,10 @@ function _validatePriceCorrectionEntry(manager, entry) {
413
412
  if (!slot) {
414
413
  return { valid: false, reason: `gap-evacuation target ${slotId || '?'} no longer owns ${entry.chainOrderId}` };
415
414
  }
416
- const idx = parseSlotIndex(slot.id);
417
- const geometry = geometryTypeForSlotIndex(idx, manager?.boundaryIdx, manager?._gapSlots);
415
+ // Live chain price first: a refused-commit adoption can leave the local
416
+ // slot id in-rail while the order actually rests inside the band.
417
+ const live = resolveLiveOrderLadderPosition(slot, manager?.assets, manager?._genesis);
418
+ const geometry = geometryTypeForSlotIndex(live.idx, manager?.boundaryIdx, manager?._gapSlots);
418
419
  if (geometry !== ORDER_TYPES.SPREAD) {
419
420
  return { valid: false, reason: `gap-evacuation target ${slotId} is no longer in the current gap band` };
420
421
  }
@@ -1350,6 +1351,54 @@ function geometryTypeForSlotIndex(idx, boundaryIdx, gapSlots) {
1350
1351
  return ORDER_TYPES.SELL;
1351
1352
  return ORDER_TYPES.SPREAD;
1352
1353
  }
1354
+ /**
1355
+ * Resolve a slot's LIVE ladder position from its on-chain price.
1356
+ *
1357
+ * `slot.id` is the local generation index; after a refused-commit adoption it
1358
+ * can be stale (an order still keyed at slot-117 can be resting at the
1359
+ * slot-138 price on chain). Evacuation geometry must therefore prefer the
1360
+ * chain order's real price, mapped onto the genesis ladder, and only fall back
1361
+ * to the stored slot index. The slot's identity price is NOT rewritten — this
1362
+ * is a read-only geometry probe (GRID-PRICE-INVARIANT stays intact).
1363
+ *
1364
+ * @param slot - Grid slot (needs id/orderId/rawOnChain)
1365
+ * @param assets - Asset pair (precision + ids) for parseChainOrder
1366
+ * @param genesis - Genesis ladder for price -> slot index
1367
+ * @returns {idx, price}: ladder index (null when unknown) and live price
1368
+ */
1369
+ function resolveLiveOrderLadderPosition(slot, assets, genesis) {
1370
+ const fallbackIdx = parseSlotIndex(slot?.id);
1371
+ const fallbackPrice = Number(slot?.price);
1372
+ const raw = slot?.rawOnChain;
1373
+ if (!raw || !assets || !genesis) {
1374
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1375
+ }
1376
+ try {
1377
+ const parsed = parseChainOrder(raw, assets);
1378
+ if (!parsed)
1379
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1380
+ if (slot?.orderId && parsed.orderId !== slot.orderId) {
1381
+ // The raw snapshot belongs to a different chain order: not evidence
1382
+ // for this slot.
1383
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1384
+ }
1385
+ const livePrice = Number(parsed.price);
1386
+ if (!Number.isFinite(livePrice) || livePrice <= 0) {
1387
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1388
+ }
1389
+ let idx = fallbackIdx;
1390
+ try {
1391
+ const resolved = Number(MathUtils.slotIndexForPrice(livePrice, genesis));
1392
+ if (Number.isFinite(resolved) && resolved >= 0)
1393
+ idx = resolved;
1394
+ }
1395
+ catch { /* keep the stored index */ }
1396
+ return { idx, price: livePrice };
1397
+ }
1398
+ catch {
1399
+ return { idx: fallbackIdx, price: Number.isFinite(fallbackPrice) && fallbackPrice > 0 ? fallbackPrice : null };
1400
+ }
1401
+ }
1353
1402
  /**
1354
1403
  * Detect gap-evacuation candidates by GEOMETRY ONLY: live on-chain orders
1355
1404
  * whose parsed slot index sits strictly inside the gap band
@@ -1357,12 +1406,17 @@ function geometryTypeForSlotIndex(idx, boundaryIdx, gapSlots) {
1357
1406
  * Phase 2 retypes in-band actives to rail types, so type-based detection
1358
1407
  * would go blind exactly when evacuation matters.
1359
1408
  *
1409
+ * The ladder index prefers the order's LIVE chain price (see
1410
+ * resolveLiveOrderLadderPosition): a refused-commit adoption can leave the
1411
+ * local slot id in-rail while the order actually rests inside the band.
1412
+ *
1360
1413
  * @param {Map} masterGrid - Master grid (slotId -> order)
1361
1414
  * @param {number} boundaryIdx - Last BUY slot index (frozen at plan-build)
1362
1415
  * @param {number} gapSlots - Spread gap slot count (frozen at plan-build)
1416
+ * @param {Object} [options] - assets/genesis for the live-price probe
1363
1417
  * @returns {Array} Candidates [{id, idx, type, price, size, orderId}]
1364
1418
  */
1365
- function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots) {
1419
+ function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots, options = {}) {
1366
1420
  const out = [];
1367
1421
  if (!masterGrid || typeof masterGrid.values !== 'function')
1368
1422
  return out;
@@ -1384,11 +1438,19 @@ function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots) {
1384
1438
  for (const slot of masterGrid.values()) {
1385
1439
  if (!slot || !isOrderOnChain(slot) || !slot.orderId)
1386
1440
  continue;
1387
- const idx = parseSlotIndex(slot.id);
1441
+ const live = resolveLiveOrderLadderPosition(slot, options.assets, options.genesis);
1442
+ const idx = live.idx;
1388
1443
  if (idx === null || idx === undefined)
1389
1444
  continue;
1390
1445
  if (Number(idx) > b && Number(idx) < sellStartIdx) {
1391
- out.push({ id: slot.id, idx: Number(idx), type: slot.type, price: slot.price, size: slot.size, orderId: slot.orderId });
1446
+ out.push({
1447
+ id: slot.id,
1448
+ idx: Number(idx),
1449
+ type: slot.type,
1450
+ price: live.price != null ? live.price : slot.price,
1451
+ size: slot.size,
1452
+ orderId: slot.orderId
1453
+ });
1392
1454
  }
1393
1455
  }
1394
1456
  return out;
@@ -1450,15 +1512,6 @@ function updateGapEvacuationStreaks(streakMap, candidates, threshold = null) {
1450
1512
  function resolveSpreadOrderSide(price, startPrice) {
1451
1513
  return Number(price) < Number(startPrice) ? ORDER_TYPES.BUY : ORDER_TYPES.SELL;
1452
1514
  }
1453
- /**
1454
- * Parse a grid slot id ("slot-123") to its rail index. Delegates to
1455
- * shared slot.ts single source (GRID_PRICE_SLOT_DETERMINISM_PLAN §2.1).
1456
- * @param {unknown} id - grid slot id string
1457
- * @returns {number|null}
1458
- */
1459
- function parseSlotIndex(id) {
1460
- return parseSlotIndexShared(id);
1461
- }
1462
1515
  /**
1463
1516
  * Precision governing both price and size comparison for a parsed chain
1464
1517
  * order: base (assetA) for sells, quote (assetB) for buys.
@@ -1607,14 +1660,32 @@ function isCrossingCheckCandidate(o, excludeChainOrderId = null, cancelOpIndexBy
1607
1660
  function buildCrossingCheckCandidates(manager) {
1608
1661
  if (!manager)
1609
1662
  return [];
1610
- const candidates = manager.orders instanceof Map ? [...manager.orders.values()] : [];
1663
+ // LIVE PRICE: a refused-commit adoption can leave a master slot keyed at an
1664
+ // old generation level while its chain order actually rests at another
1665
+ // price (live incident: the grid still said slot-117 @1263 while the buy
1666
+ // was live at 1345.7). Using the stored price let a sell be emitted at the
1667
+ // same 1345.728664, self-crossing the live buy. Parse the chain snapshot
1668
+ // for the crossing probe only — the slot's identity price is unchanged.
1669
+ const withLivePrice = (o) => {
1670
+ const candidate = o;
1671
+ if (!candidate || typeof candidate !== 'object')
1672
+ return o;
1673
+ const live = resolveLiveOrderLadderPosition(candidate, manager.assets, manager._genesis);
1674
+ if (live.price == null || !Number.isFinite(Number(live.price)) || Number(live.price) <= 0)
1675
+ return o;
1676
+ return { ...o, price: Number(live.price) };
1677
+ };
1678
+ const candidates = manager.orders instanceof Map
1679
+ ? [...manager.orders.values()].map(withLivePrice)
1680
+ : [];
1611
1681
  if (manager._pendingBroadcasts instanceof Map) {
1612
1682
  for (const entry of manager._pendingBroadcasts.values()) {
1613
1683
  if (entry && entry.slotId && entry.order)
1614
- candidates.push(entry);
1684
+ candidates.push(withLivePrice(entry));
1615
1685
  }
1616
1686
  }
1617
1687
  if (Array.isArray(manager._lastUnmatchedChainOrders)) {
1688
+ // Unmatched chain orders already carry the chain price; keep as-is.
1618
1689
  for (const o of manager._lastUnmatchedChainOrders) {
1619
1690
  if (o && o.type != null && o.price != null)
1620
1691
  candidates.push(o);
@@ -2893,6 +2964,51 @@ function windowIdSetFromSlots(allSlots, config, orderType, boundaryIdx, gapSlots
2893
2964
  return null;
2894
2965
  }
2895
2966
  }
2967
+ /**
2968
+ * Collect the fill ids that belong to EDGE-pinned insurance orders.
2969
+ *
2970
+ * Edge orders (grid floor / ceiling) are static fat-finger insurance, not
2971
+ * market movement: the boundary crawl already excludes their fills
2972
+ * (`deriveTargetBoundary`), and the same exclusion must apply to the fill
2973
+ * reference the LAST-FILL-GUARD pivots on and the boundary re-anchor uses.
2974
+ * Without it, one wick that triggers a far-out insurance order would arm the
2975
+ * guard at that price AND re-anchor the window to the grid edge — the exact
2976
+ * "teleport" class the geometry guards exist to prevent.
2977
+ *
2978
+ * Uses the SAME classification the placement pickers use (live window ids
2979
+ * excluded, live edge anchor) so "edge" cannot mean two things.
2980
+ *
2981
+ * @param {Object} manager - OrderManager (orders Map, config, boundary)
2982
+ * @param {Array<Object>} fills - Fill batch
2983
+ * @returns {Set<string>} Slot ids of edge-pinned fills (empty when none/unknown)
2984
+ */
2985
+ function collectEdgePinnedFillIds(manager, fills) {
2986
+ const out = new Set();
2987
+ if (!manager || !Array.isArray(fills) || fills.length === 0)
2988
+ return out;
2989
+ try {
2990
+ const slots = manager.orders && typeof manager.orders.values === 'function'
2991
+ ? Array.from(manager.orders.values())
2992
+ : [];
2993
+ if (slots.length === 0)
2994
+ return out;
2995
+ for (const side of [ORDER_TYPES.BUY, ORDER_TYPES.SELL]) {
2996
+ const windowIds = liveWindowIdSet(manager, side);
2997
+ const edgeIds = edgeOrderIdSet(slots, manager?.config, side, resolveLiveEdgeAnchorPrice(manager, side), windowIds);
2998
+ if (!edgeIds || edgeIds.size === 0)
2999
+ continue;
3000
+ for (const f of fills) {
3001
+ if (!f || f.type !== side)
3002
+ continue;
3003
+ const id = String(f.id ?? '');
3004
+ if (id && edgeIds.has(id))
3005
+ out.add(id);
3006
+ }
3007
+ }
3008
+ }
3009
+ catch { /* classification is best-effort: never block fill intake */ }
3010
+ return out;
3011
+ }
2896
3012
  /**
2897
3013
  * Window member ids for one side from the live manager (see
2898
3014
  * windowIdSetFromSlots). Delegates so the manager and explicit-geometry
@@ -3197,7 +3313,7 @@ function calculateBudgetedSizes(slots, side, budget, weightDist, incrementPercen
3197
3313
  }
3198
3314
  const incrementFactor = Number(incrementPercent) / 100;
3199
3315
  return MathUtils.allocateFundsByWeights(budget, slots.length, weightDist, incrementFactor, isBuy, // Reverse for BUY (Market-Close is last in array)
3200
- 0, precision);
3316
+ precision);
3201
3317
  }
3202
3318
  // ================================================================================
3203
3319
  // SECTION: COW batch-shared pure helpers (moved from dexbot_cow_runtime.ts —
@@ -3395,6 +3511,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3395
3511
  const all = new Set([...masterIds, ...createIds]);
3396
3512
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3397
3513
  }
3398
- export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3514
+ export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3399
3515
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3400
3516
  //# sourceMappingURL=order.js.map
@@ -346,7 +346,7 @@ export declare function persistGridSnapshot(manager: OrderManagerLike, accountOr
346
346
  */
347
347
  export declare function restoreGapEvacStreaks(manager: OrderManagerLike, persisted: unknown): number;
348
348
  /** Why spread correction is degraded or refused for a cycle. */
349
- export type SpreadCorrectionRefusalReason = 'cold-book' | 'stale-snapshot' | 'unmatched-orders';
349
+ type SpreadCorrectionRefusalReason = 'cold-book' | 'stale-snapshot' | 'unmatched-orders';
350
350
  export interface SpreadCorrectionReadiness {
351
351
  /** False => hard refusal (cold book): the planner must not act this cycle. */
352
352
  ok: boolean;
@@ -366,7 +366,7 @@ export interface SpreadCorrectionReadiness {
366
366
  unmatched: UnmatchedChainOrderLike[];
367
367
  }
368
368
  /** Narrowed read-only view of an unmatched chain order used by the readiness gate. */
369
- export interface UnmatchedChainOrderLike extends Record<string, unknown> {
369
+ interface UnmatchedChainOrderLike extends Record<string, unknown> {
370
370
  price?: number;
371
371
  orderId?: string;
372
372
  chainOrderId?: string;
@@ -479,25 +479,6 @@ export declare function evaluateSpreadCorrectionReadiness(manager: OrderManagerL
479
479
  * @returns {number|null} Reference price or null
480
480
  */
481
481
  export declare function resolveSpreadMarketReference(manager: OrderManagerLike): number | null;
482
- /**
483
- * Resolve the reference the generic LAST-FILL-GUARD judges against.
484
- *
485
- * Prefers the live armed pivot. When that is cold (a grid regeneration
486
- * cleared it, or a rejected-snapshot reset ran) it falls back to the
487
- * bot-scoped last-market-fill row — the same market truth spread correction
488
- * already uses. This is what stops a rebuild from silently un-arming the
489
- * guard until the next fill: the price the account last traded at is known,
490
- * so a CREATE/rotation must still not cross it.
491
- *
492
- * Read-time fallback only: it does NOT mutate the pivot or persist an
493
- * old-generation value, so the genesis-bound pivot/persist contract is
494
- * unchanged. The guard still validates the value onto the CURRENT ladder via
495
- * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
496
- * regenerated geometry stays the authority on which placements are off-grid.
497
- *
498
- * @param {Object} manager - OrderManager instance
499
- * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
500
- */
501
482
  /**
502
483
  * Re-anchor the boundary so the newest REAL fill sits outside its own window.
503
484
  *
@@ -515,16 +496,33 @@ export declare function resolveSpreadMarketReference(manager: OrderManagerLike):
515
496
  *
516
497
  * Only a genuine on-ladder fill price is accepted (same one-increment drift
517
498
  * bound as `resolveOnGridPivot`), and the candidate must pass the same
518
- * placed-order-aware validation the boundary commit gate uses, so a re-anchor
519
- * can never strand a live order inside the re-typed band.
499
+ * placed-order-aware validation the boundary commit gate uses
500
+ * (`validatePersistedBoundary` — the SAME gate the restore and commit paths
501
+ * use), so a re-anchor can never strand a live order inside the re-typed band.
502
+ *
503
+ * ELIGIBILITY (same rule as the crawl, see deriveTargetBoundary):
504
+ * - EDGE-pinned insurance fills never anchor. An edge fill is by definition
505
+ * outside the window it would move, and it is a book event (a fat-finger
506
+ * wick), not market movement — the crawl already excludes it, and an
507
+ * absolute anchor from a grid-edge price would teleport the window to that
508
+ * edge. Such fills also never arm the pivot (recordLastFilledPrices skips
509
+ * them), so the reference can only be a window fill.
510
+ * - PARTIAL fills DO anchor: a partial at the far slot is still a real trade
511
+ * at a real price, and the residual it leaves at the anchor slot is
512
+ * explicitly allow-listed below (otherwise the geometry deadlocks).
520
513
  *
521
514
  * @param {Object} manager - OrderManager (pivot + genesis)
522
515
  * @param {number|null} boundaryIdx - Boundary the derivation would commit
523
516
  * @param {Array<Object>} slots - Grid slots (current generation)
524
517
  * @param {number} gapSlots - Gap band width
518
+ * @param {Array<Object>} [fills] - Current fill batch (extremum resolution)
525
519
  * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
526
520
  */
527
- export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike, boundaryIdx: number | null | undefined, slots: ManagedOrder[] | null | undefined, gapSlots: number): {
521
+ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike, boundaryIdx: number | null | undefined, slots: ManagedOrder[] | null | undefined, gapSlots: number, fills?: Array<{
522
+ id?: string;
523
+ type?: string;
524
+ price?: unknown;
525
+ }> | null | undefined): {
528
526
  boundaryIdx: number | null;
529
527
  reanchored: boolean;
530
528
  from?: number | null;
@@ -533,6 +531,29 @@ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike,
533
531
  fillSlot?: number;
534
532
  reason?: string;
535
533
  };
534
+ /**
535
+ * Resolve the reference the generic LAST-FILL-GUARD judges against.
536
+ *
537
+ * Prefers the live armed pivot. When that is cold (a grid regeneration
538
+ * cleared it, or a rejected-snapshot reset ran) it falls back to the
539
+ * bot-scoped last-market-fill row — the same market truth spread correction
540
+ * already uses. This is what stops a rebuild from silently un-arming the
541
+ * guard until the next fill: the price the account last traded at is known,
542
+ * so a CREATE/rotation must still not cross it.
543
+ *
544
+ * Read-time fallback only: it does NOT mutate the pivot or persist an
545
+ * old-generation value, so the genesis-bound pivot/persist contract is
546
+ * unchanged. The guard still validates the value onto the CURRENT ladder via
547
+ * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
548
+ * regenerated geometry stays the authority on which placements are off-grid.
549
+ *
550
+ * The rebuild path re-arms the pivot explicitly (rearmLastFillPivotFromMarketFill)
551
+ * so this fallback covers only the window before that write, not the whole
552
+ * post-rebuild lifetime.
553
+ *
554
+ * @param {Object} manager - OrderManager instance
555
+ * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
556
+ */
536
557
  export declare function resolveLastFillGuardReference(manager: OrderManagerLike): {
537
558
  price: number | null;
538
559
  type: string | null;
@@ -552,18 +573,21 @@ export declare function resolveLastFillGuardReference(manager: OrderManagerLike)
552
573
  * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
553
574
  * price counts as blocked — that is a re-place at the just-filled level, the
554
575
  * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
555
- * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
556
- * increment takes no part (kept in the signature for call-site stability).
576
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled.
577
+ *
578
+ * Signature note: the old band rule also consumed order size and the grid
579
+ * increment (it judged against `pivot ± increment/2`). Both are gone on
580
+ * purpose — re-adding an increment term re-opens retrospective §9.7 (a BUY
581
+ * below a SELL fill was blocked, a SELL one tick above our cost was blocked,
582
+ * and spread tightening became structurally impossible after any fill).
557
583
  *
558
584
  * @param {number} price - Target order price
559
- * @param {number} _size - Order size (unused, kept for compat)
560
585
  * @param {string} type - ORDER_TYPES.BUY/SELL
561
586
  * @param {number|null} lastPrice - Most recent fill price
562
587
  * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
563
- * @param {number|any} _incrementPercent - Unused (kept for signature compat)
564
588
  * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
565
589
  */
566
- export declare function isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, _incrementPercent?: number): {
590
+ export declare function isLastFillGuardBlocked(price: number, type: unknown, lastPrice: number | null, lastType: string | null): {
567
591
  blocked: boolean;
568
592
  pivot: number | null;
569
593
  threshold?: number | null;
@@ -585,6 +609,26 @@ export declare function isLastFillGuardBlocked(price: number, _size: number, typ
585
609
  export declare function restoreLastMarketFill(manager: OrderManagerLike, persisted: unknown, options?: {
586
610
  now?: number;
587
611
  }): boolean;
612
+ /**
613
+ * Re-arm the LAST-FILL-GUARD pivot from the bot-scoped market-fill row.
614
+ *
615
+ * The grid-rebuild path deliberately clears the armed pivot (a new generation).
616
+ * The guard must NOT stay cold afterwards: the price the account last traded at
617
+ * is still market truth, so the pivot is re-armed on the NEW generation
618
+ * explicitly, through the single shared writer, at the original fill timestamp.
619
+ * That makes the documented contract real ("the guard re-arms against the new
620
+ * ladder") instead of relying on the read-time fallback in
621
+ * `resolveLastFillGuardReference` for the whole post-rebuild lifetime — a
622
+ * fallback that cannot be re-validated, persisted or logged.
623
+ *
624
+ * Provenance stays 'fill' (a book seed never qualifies). The price is not
625
+ * rewritten: an off-new-ladder value is handled by the same one-increment
626
+ * `resolveOnGridPivot` rule every other probe uses.
627
+ *
628
+ * @param {Object} manager - OrderManager instance
629
+ * @returns {boolean} True when a pivot was re-armed
630
+ */
631
+ export declare function rearmLastFillPivotFromMarketFill(manager: OrderManagerLike): boolean;
588
632
  /**
589
633
  * Normalize a persisted LAST-FILL-GUARD pivot row (shared by the
590
634
  * AccountOrders sanitizer/loader and the payload builder's row contract).