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
@@ -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
@@ -1039,6 +1058,17 @@ declare function buildDelta(masterGrid: Map<string, ManagedOrder>, workingGrid:
1039
1058
  priceRelativeTolerance?: number;
1040
1059
  };
1041
1060
  }): DeltaAction[];
1061
+ /**
1062
+ * A pending-crawl ledger entry as consumed by a derivation.
1063
+ * `ts` is carried so the commit clears exactly the records the derivation
1064
+ * folded — never a newer record for the same slot (recording happens at fill
1065
+ * intake, so a slot can be re-recorded between derivation and commit).
1066
+ */
1067
+ type CrawlEntry = {
1068
+ slotId: string;
1069
+ side: string;
1070
+ ts?: number;
1071
+ };
1042
1072
  /**
1043
1073
  * Check whether a fill is eligible to drive boundary shift / rotation.
1044
1074
  * Partials only count when they are delayed-rotation triggers.
@@ -1075,6 +1105,7 @@ declare function deriveTargetBoundary(fills: Array<{
1075
1105
  } | null): {
1076
1106
  boundaryIdx: number | null;
1077
1107
  remainingBudget: number;
1108
+ consumedCrawlIds: CrawlEntry[];
1078
1109
  };
1079
1110
  /**
1080
1111
  * Apply recorded-but-uncommitted fill crawls to the committed boundary.
@@ -1152,6 +1183,28 @@ declare function resolveEdgeOrders(config: OrderConfigView | null | undefined):
1152
1183
  * @returns {Set<string>|null} Edge slot ids, or null when side disabled
1153
1184
  */
1154
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>;
1155
1208
  /**
1156
1209
  * Window member ids for one side from the live manager (see
1157
1210
  * windowIdSetFromSlots). Delegates so the manager and explicit-geometry
@@ -1402,6 +1455,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1402
1455
  createIds: string[];
1403
1456
  all: string[];
1404
1457
  };
1405
- 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 };
1459
+ export type { CrawlEntry };
1406
1460
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1407
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);
@@ -2367,9 +2438,14 @@ function buildDelta(masterGrid, workingGrid, options = {}) {
2367
2438
  }
2368
2439
  return actions;
2369
2440
  }
2370
- // ================================================================================
2371
- // SECTION 10: STRATEGY CALCULATIONS
2372
- // ================================================================================
2441
+ /** Normalise a ledger record into the identity the commit clears by. */
2442
+ function toCrawlEntry(e) {
2443
+ return {
2444
+ slotId: String(e?.slotId ?? ''),
2445
+ side: String(e?.side ?? ''),
2446
+ ts: Number.isFinite(Number(e?.ts)) ? Number(e?.ts) : undefined,
2447
+ };
2448
+ }
2373
2449
  /**
2374
2450
  * Check whether a fill is eligible to drive boundary shift / rotation.
2375
2451
  * Partials only count when they are delayed-rotation triggers.
@@ -2470,7 +2546,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2470
2546
  if (referencePrice === null) {
2471
2547
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2472
2548
  const effectiveBudget = crossChunkBudget ?? fallbackCap;
2473
- return { boundaryIdx: null, remainingBudget: effectiveBudget };
2549
+ return { boundaryIdx: null, remainingBudget: effectiveBudget, consumedCrawlIds: [] };
2474
2550
  }
2475
2551
  newBoundaryIdx = calculateIdealBoundary(allSlots, referencePrice, gapSlots);
2476
2552
  if (!Number.isFinite(newBoundaryIdx) || newBoundaryIdx < 0) {
@@ -2478,7 +2554,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2478
2554
  // exists (calculateIdealBoundary returns -1). Stay null rather
2479
2555
  // than letting the clamp below fabricate a slot-0 boundary.
2480
2556
  const fallbackCap = Math.max(Math.floor((config?.coreOrders?.sell ?? 1) / 2), Math.floor((config?.coreOrders?.buy ?? 1) / 2), 1);
2481
- return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap };
2557
+ return { boundaryIdx: null, remainingBudget: crossChunkBudget ?? fallbackCap, consumedCrawlIds: [] };
2482
2558
  }
2483
2559
  recovered = true;
2484
2560
  }
@@ -2510,12 +2586,50 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2510
2586
  // anything older is still owed and shifts here. Edge-slot entries
2511
2587
  // never crawl (static insurance), same as live fills.
2512
2588
  const currentSlotIds = new Set((fills ?? []).map((f) => f?.id).filter((id) => typeof id === 'string' && id.length > 0));
2513
- const owedPending = (pendingCrawls ?? []).filter((e) => e
2514
- && typeof e.slotId === 'string' && e.slotId.length > 0
2589
+ const allPending = (pendingCrawls ?? [])
2590
+ .filter((e) => !!e
2591
+ && typeof e.slotId === 'string' && e.slotId.length > 0);
2592
+ const owedPending = allPending.filter((e) => e
2515
2593
  && !currentSlotIds.has(e.slotId)
2516
2594
  && (e.side === ORDER_TYPES.BUY || e.side === ORDER_TYPES.SELL)
2517
2595
  && !(e.side === ORDER_TYPES.BUY && edgeBuyIds && edgeBuyIds.has(e.slotId))
2518
2596
  && !(e.side === ORDER_TYPES.SELL && edgeSellIds && edgeSellIds.has(e.slotId)));
2597
+ /**
2598
+ * Ledger records this derivation CONSUMED:
2599
+ * - everything it deliberately never counts (current-batch slots whose
2600
+ * shift comes from `fills`, edge-classified slots which never crawl,
2601
+ * malformed records), and
2602
+ * - the owed entries whose shift it actually APPLIED.
2603
+ *
2604
+ * `applied` is the (possibly capped) net shift. A capped fold applies only
2605
+ * part of the owed net, so only that part may be consumed — the remainder
2606
+ * stays owed, or the next derivation would either lose it (clear-all) or
2607
+ * apply it twice (keep-all).
2608
+ */
2609
+ const consumedFor = (applied) => {
2610
+ const never = allPending.filter((e) => !owedPending.includes(e));
2611
+ let appliedEntries = [];
2612
+ if (cap <= 0) {
2613
+ // No cross-chunk budget left: NOTHING was applied, so every owed
2614
+ // record stays owed (a net-zero reading here is not a cancellation).
2615
+ appliedEntries = [];
2616
+ }
2617
+ else if (applied === 0) {
2618
+ // A net-zero mix was fully accounted for by cancelling out.
2619
+ appliedEntries = owedPending;
2620
+ }
2621
+ else {
2622
+ // Consume same-side entries up to the applied magnitude; the mixed
2623
+ // remainder still nets out to (net - applied) for the next run.
2624
+ const dirSide = applied > 0 ? ORDER_TYPES.SELL : ORDER_TYPES.BUY;
2625
+ appliedEntries = owedPending
2626
+ .filter((e) => e.side === dirSide)
2627
+ .slice(0, Math.abs(applied));
2628
+ }
2629
+ return [...never, ...appliedEntries].map(toCrawlEntry);
2630
+ };
2631
+ /** Every owed record is subsumed (absolute anchor / generation discard). */
2632
+ const consumedAll = () => allPending.map(toCrawlEntry);
2519
2633
  for (const fill of fills ?? []) {
2520
2634
  if (!isShiftEligibleFill(fill))
2521
2635
  continue;
@@ -2556,8 +2670,18 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2556
2670
  return {
2557
2671
  boundaryIdx: Math.max(0, Math.min((allSlots.length - gapSlots - 1) >= 0 ? (allSlots.length - gapSlots - 1) : (allSlots.length - 1), newBoundaryIdx)),
2558
2672
  remainingBudget: effectiveBudget,
2673
+ // The absolute fill anchor positions from live prices, which already
2674
+ // reflect every owed delta. The remaining delta is NOT added on top
2675
+ // (double-count guard), so every record is subsumed regardless of
2676
+ // what the cap would have admitted.
2677
+ consumedCrawlIds: consumedAll(),
2559
2678
  };
2560
2679
  }
2680
+ // A truncated shift (or an exhausted cross-chunk budget) applies only part
2681
+ // of the owed net, so the consumed set below is scoped to WHAT WAS APPLIED:
2682
+ // the commit must neither lose the remainder (the 2026-10-25 leak: 7 fills,
2683
+ // boundary +3 planned, all 7 records dropped) nor leave an applied entry
2684
+ // owed for a second pass.
2561
2685
  if (Math.abs(netShift) > cap) {
2562
2686
  netShift = Math.sign(netShift) * cap;
2563
2687
  }
@@ -2575,6 +2699,7 @@ function deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, config, gapSl
2575
2699
  return {
2576
2700
  boundaryIdx: Math.max(0, Math.min(ceiling, newBoundaryIdx)),
2577
2701
  remainingBudget,
2702
+ consumedCrawlIds: consumedFor(netShift),
2578
2703
  };
2579
2704
  }
2580
2705
  /**
@@ -2839,6 +2964,51 @@ function windowIdSetFromSlots(allSlots, config, orderType, boundaryIdx, gapSlots
2839
2964
  return null;
2840
2965
  }
2841
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
+ }
2842
3012
  /**
2843
3013
  * Window member ids for one side from the live manager (see
2844
3014
  * windowIdSetFromSlots). Delegates so the manager and explicit-geometry
@@ -3143,7 +3313,7 @@ function calculateBudgetedSizes(slots, side, budget, weightDist, incrementPercen
3143
3313
  }
3144
3314
  const incrementFactor = Number(incrementPercent) / 100;
3145
3315
  return MathUtils.allocateFundsByWeights(budget, slots.length, weightDist, incrementFactor, isBuy, // Reverse for BUY (Market-Close is last in array)
3146
- 0, precision);
3316
+ precision);
3147
3317
  }
3148
3318
  // ================================================================================
3149
3319
  // SECTION: COW batch-shared pure helpers (moved from dexbot_cow_runtime.ts —
@@ -3341,6 +3511,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3341
3511
  const all = new Set([...masterIds, ...createIds]);
3342
3512
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3343
3513
  }
3344
- 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 };
3345
3515
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3346
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,6 +479,58 @@ 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
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
484
+ *
485
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
486
+ * behind the fill (a sweep filled several slots while the commit dropped the
487
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
488
+ * tightening slot on that side is then at/through the last fill and the
489
+ * last-fill guard refuses all of them, while the funds sit in the resting
490
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
491
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
492
+ *
493
+ * The fill itself is the anchor, so place it outside its window:
494
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
495
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
496
+ *
497
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
498
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
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).
513
+ *
514
+ * @param {Object} manager - OrderManager (pivot + genesis)
515
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
516
+ * @param {Array<Object>} slots - Grid slots (current generation)
517
+ * @param {number} gapSlots - Gap band width
518
+ * @param {Array<Object>} [fills] - Current fill batch (extremum resolution)
519
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
520
+ */
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): {
526
+ boundaryIdx: number | null;
527
+ reanchored: boolean;
528
+ from?: number | null;
529
+ to?: number;
530
+ side?: string;
531
+ fillSlot?: number;
532
+ reason?: string;
533
+ };
482
534
  /**
483
535
  * Resolve the reference the generic LAST-FILL-GUARD judges against.
484
536
  *
@@ -495,6 +547,10 @@ export declare function resolveSpreadMarketReference(manager: OrderManagerLike):
495
547
  * resolveOnGridPivot at the call site (off-ladder → raw value + warn), so a
496
548
  * regenerated geometry stays the authority on which placements are off-grid.
497
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
+ *
498
554
  * @param {Object} manager - OrderManager instance
499
555
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
500
556
  */
@@ -502,6 +558,40 @@ export declare function resolveLastFillGuardReference(manager: OrderManagerLike)
502
558
  price: number | null;
503
559
  type: string | null;
504
560
  };
561
+ /**
562
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
563
+ *
564
+ * BUY blocked if price >= pivot (never place a higher BUY)
565
+ * SELL blocked if price <= pivot (never place a lower SELL)
566
+ *
567
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
568
+ * broadcast guard judge candidates with literally the same predicate: a batch
569
+ * must never be built from a create the guard will drop, and a dropped batch
570
+ * must never be reported as an unexplained "prepared but not executed".
571
+ *
572
+ * A placement on the permitted side is always profitable against the last trade
573
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
574
+ * price counts as blocked — that is a re-place at the just-filled level, the
575
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
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).
583
+ *
584
+ * @param {number} price - Target order price
585
+ * @param {string} type - ORDER_TYPES.BUY/SELL
586
+ * @param {number|null} lastPrice - Most recent fill price
587
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
588
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
589
+ */
590
+ export declare function isLastFillGuardBlocked(price: number, type: unknown, lastPrice: number | null, lastType: string | null): {
591
+ blocked: boolean;
592
+ pivot: number | null;
593
+ threshold?: number | null;
594
+ };
505
595
  /**
506
596
  * Restore the persisted bot-scoped last-market-fill reference into the
507
597
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -519,6 +609,26 @@ export declare function resolveLastFillGuardReference(manager: OrderManagerLike)
519
609
  export declare function restoreLastMarketFill(manager: OrderManagerLike, persisted: unknown, options?: {
520
610
  now?: number;
521
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;
522
632
  /**
523
633
  * Normalize a persisted LAST-FILL-GUARD pivot row (shared by the
524
634
  * AccountOrders sanitizer/loader and the payload builder's row contract).