dexbot 1.7.2 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +6 -0
  11. package/dist/modules/bot_defaults.js +6 -1
  12. package/dist/modules/constants.d.ts +12 -0
  13. package/dist/modules/constants.js +66 -0
  14. package/dist/modules/dexbot_class.d.ts +17 -0
  15. package/dist/modules/dexbot_class.js +56 -1
  16. package/dist/modules/dexbot_cow_runtime.js +231 -19
  17. package/dist/modules/dexbot_maintenance_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_maintenance_runtime.js +164 -11
  19. package/dist/modules/dexbot_state_recovery.js +15 -1
  20. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  21. package/dist/modules/launcher/instance_lock.js +131 -0
  22. package/dist/modules/order/grid.d.ts +19 -0
  23. package/dist/modules/order/grid.js +40 -14
  24. package/dist/modules/order/index.d.ts +15 -1
  25. package/dist/modules/order/manager.d.ts +21 -0
  26. package/dist/modules/order/manager.js +119 -12
  27. package/dist/modules/order/placement_lock.d.ts +30 -0
  28. package/dist/modules/order/placement_lock.js +48 -0
  29. package/dist/modules/order/utils/order.d.ts +39 -1
  30. package/dist/modules/order/utils/order.js +73 -2
  31. package/dist/modules/order/utils/system.d.ts +112 -3
  32. package/dist/modules/order/utils/system.js +368 -6
  33. package/dist/modules/paths.d.ts +1 -0
  34. package/dist/modules/paths.js +1 -0
  35. package/dist/modules/timing_policy.js +2 -0
  36. package/dist/modules/types.d.ts +27 -0
  37. package/dist/pm2.js +126 -0
  38. package/dist/unlock.js +26 -1
  39. package/docs/DEXBOT_COMPARISON.md +5 -5
  40. package/docs/EVOLUTION.md +10 -9
  41. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  42. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +155 -2
  43. package/docs/README.md +1 -1
  44. package/modules/README.md +1 -0
  45. package/package.json +2 -1
@@ -261,6 +261,9 @@ declare class OrderManager implements OrderManagerLike {
261
261
  _lastFilledPrice: number | null;
262
262
  _lastFilledType: string | null;
263
263
  _lastFilledAt: number;
264
+ _lastRefusedFillPrice: number | null;
265
+ _lastRefusedFillType: string | null;
266
+ _lastRefusedFillAt: number;
264
267
  /** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
265
268
  _lastFillPivotExpiryLoggedAt: number;
266
269
  lastFillPivotSource: 'fill' | 'book' | null;
@@ -1028,6 +1031,17 @@ declare class OrderManager implements OrderManagerLike {
1028
1031
  * edge. Skipping keeps the reference on the last WINDOW trade, matching
1029
1032
  * the crawl's classification (collectEdgePinnedFillIds is the shared
1030
1033
  * definition).
1034
+ *
1035
+ * IN-BAND FILLS ARE SKIPPED TOO (same rule, completed). A slot the CURRENT
1036
+ * geometry classifies as gap-band holds a stranded residual — an order the
1037
+ * engine has already declared out of place ("placed_order_in_band") — not a
1038
+ * window trade. Live: a sweep crawled the boundary over a resting sell,
1039
+ * that stranded sell then partially filled 11s later, and the fill armed the
1040
+ * pivot at the top of the band the geometry had just derived. Every SELL in
1041
+ * the band was then `<= pivot`, so the counter-orders the sweep owed could
1042
+ * never be placed. The eligibility rule (§9.6 "Only a window trade may
1043
+ * become the pivot") is applied at this single writer: edge-pinned here,
1044
+ * in-band here, off-market distance in setLastFillPivot.
1031
1045
  * @param {Array} fills
1032
1046
  */
1033
1047
  recordLastFilledPrices(fills: COWFillLike[]): void;
@@ -1061,6 +1075,7 @@ declare class OrderManager implements OrderManagerLike {
1061
1075
  partialsMoved: number;
1062
1076
  stall?: import("../types.js").SpreadCorrectionStall;
1063
1077
  transient?: boolean;
1078
+ excessAfter?: number;
1064
1079
  }>;
1065
1080
  /**
1066
1081
  * @param {Function} batchCb - Batch callback
@@ -1184,11 +1199,17 @@ declare class OrderManager implements OrderManagerLike {
1184
1199
  * @param {boolean} [options.skipBroadcastWait] - Set by the COW re-plan path,
1185
1200
  * which runs INSIDE its own startBroadcasting() region and must not wait
1186
1201
  * on the flag it holds itself.
1202
+ * @param {boolean} [options.holdPlanRegion] - Claim the exclusive placement
1203
+ * region before planning and ride it on the result, so the plan→broadcast
1204
+ * window is serialized against other planners. Set by the callers that are
1205
+ * guaranteed to execute the result (fill path, post-recovery rebalance).
1206
+ * Planner-only callers (unit fixtures) leave it off and stay lease-free.
1187
1207
  * @returns {Promise<any>}
1188
1208
  */
1189
1209
  performSafeRebalance(fills?: COWFillLike[], excludeIds?: Set<string>, options?: {
1190
1210
  skipBroadcastWait?: boolean;
1191
1211
  deferIfBroadcasting?: boolean;
1212
+ holdPlanRegion?: boolean;
1192
1213
  [key: string]: unknown;
1193
1214
  }): Promise<RebalanceResult>;
1194
1215
  _applySafeRebalanceCOW(fills?: COWFillLike[], excludeIds?: Set<string>): Promise<RebalanceResult>;
@@ -33,7 +33,7 @@ import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolve
33
33
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
34
34
  import { resolveSpreadOrderSide, resolveLiveOrderLadderPosition, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, collectEdgePinnedFillIds, isStructuralRebuildStaleReason } from './utils/order.js';
35
35
  import { parseSlotIndex } from './utils/slot.js';
36
- import PlacementLock, { withPlacement as runWithPlacement } from './placement_lock.js';
36
+ import PlacementLock, { withPlacement as runWithPlacement, attachPlanLease } from './placement_lock.js';
37
37
  import { getErrorMessage, getErrorCode } from '../utils/errors.js';
38
38
  const { toFiniteNumber } = Format;
39
39
  function stalePlacementDropReason(action, planBoundary) {
@@ -520,6 +520,12 @@ class OrderManager {
520
520
  _lastFilledPrice;
521
521
  _lastFilledType;
522
522
  _lastFilledAt;
523
+ // Refused (off-market) fill level: the pivot-arming refusal (§9.12/P1)
524
+ // still marks its level as a same-level re-fill block (§9.12/P2 amended).
525
+ // In-memory only — never persisted, cleared by resetLastFillPivot.
526
+ _lastRefusedFillPrice;
527
+ _lastRefusedFillType;
528
+ _lastRefusedFillAt;
523
529
  /** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
524
530
  _lastFillPivotExpiryLoggedAt;
525
531
  lastFillPivotSource;
@@ -693,6 +699,9 @@ class OrderManager {
693
699
  this._lastFilledPrice = null;
694
700
  this._lastFilledType = null;
695
701
  this._lastFilledAt = 0;
702
+ this._lastRefusedFillPrice = null;
703
+ this._lastRefusedFillType = null;
704
+ this._lastRefusedFillAt = 0;
696
705
  this._lastFillPivotExpiryLoggedAt = 0;
697
706
  // Pivot provenance for the LAST-FILL-GUARD persist/restore contract:
698
707
  // 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
@@ -1892,11 +1901,22 @@ class OrderManager {
1892
1901
  return;
1893
1902
  }
1894
1903
  if (nextId !== prevId) {
1904
+ const isLoadContext = context === 'grid-load' || context === 'grid-init';
1895
1905
  // A freshly assigned chain id (create/adopt broadcast in flight, or
1896
1906
  // not yet visible to a lagging read) must not read as "absent from
1897
1907
  // chain": absence decisions defer while it is younger than
1898
1908
  // SYNC_LOCK_TIMEOUT_MS (isRecentlyAssigned).
1899
- this._lifecycle.markAssigned(slotId, nextId);
1909
+ //
1910
+ // Snapshot/grid load paths are excluded for ids this process
1911
+ // already knows: a reload re-adopts OLD ids, so re-stamping them
1912
+ // would hand the same (possibly dead) order a brand-new defer
1913
+ // window on every reload. The reload that follows a refused
1914
+ // UPDATE re-armed it indefinitely, so a genuinely absent orderId
1915
+ // could never be cleaned up and kept blocking the gap band. First
1916
+ // sight of an id (fresh process) still gets the grace.
1917
+ const isKnownId = this._lifecycle.assignedAt.has(nextId);
1918
+ if (!isLoadContext || !isKnownId)
1919
+ this._lifecycle.markAssigned(slotId, nextId);
1900
1920
  // Fresh-placement timestamp for the surplus-cancel grace window: a
1901
1921
  // slot gaining an orderId it did not have is a new placement
1902
1922
  // (create, adopt, rotation target), and surplus sweeps must not
@@ -1905,7 +1925,6 @@ class OrderManager {
1905
1925
  // Snapshot/grid load paths are excluded: reloaded orders are old by
1906
1926
  // definition, and stamping them would neuter surplus sweeps for 15
1907
1927
  // minutes after every restart.
1908
- const isLoadContext = context === 'grid-load' || context === 'grid-init';
1909
1928
  if (!isLoadContext)
1910
1929
  this._lifecycle.markPlaced(nextId, undefined, slotId);
1911
1930
  }
@@ -2088,7 +2107,10 @@ class OrderManager {
2088
2107
  const reanchorBudgetBefore = Number(this._boundaryReanchorBudget);
2089
2108
  const rebalanceResult = await this.performSafeRebalance(orders, excl, {
2090
2109
  ...(options || {}),
2091
- deferIfBroadcasting: true
2110
+ deferIfBroadcasting: true,
2111
+ // This result is always fed to the executor by
2112
+ // _processFillsWithBatching, so the region can span plan→commit.
2113
+ holdPlanRegion: true
2092
2114
  });
2093
2115
  // Carry the fill set + exclusions on the result so the COW batch
2094
2116
  // executor can re-plan once from fresh master if the plan goes
@@ -2476,6 +2498,17 @@ class OrderManager {
2476
2498
  * edge. Skipping keeps the reference on the last WINDOW trade, matching
2477
2499
  * the crawl's classification (collectEdgePinnedFillIds is the shared
2478
2500
  * definition).
2501
+ *
2502
+ * IN-BAND FILLS ARE SKIPPED TOO (same rule, completed). A slot the CURRENT
2503
+ * geometry classifies as gap-band holds a stranded residual — an order the
2504
+ * engine has already declared out of place ("placed_order_in_band") — not a
2505
+ * window trade. Live: a sweep crawled the boundary over a resting sell,
2506
+ * that stranded sell then partially filled 11s later, and the fill armed the
2507
+ * pivot at the top of the band the geometry had just derived. Every SELL in
2508
+ * the band was then `<= pivot`, so the counter-orders the sweep owed could
2509
+ * never be placed. The eligibility rule (§9.6 "Only a window trade may
2510
+ * become the pivot") is applied at this single writer: edge-pinned here,
2511
+ * in-band here, off-market distance in setLastFillPivot.
2479
2512
  * @param {Array} fills
2480
2513
  */
2481
2514
  recordLastFilledPrices(fills) {
@@ -2484,6 +2517,7 @@ class OrderManager {
2484
2517
  const edgeFillIds = collectEdgePinnedFillIds(this, fills);
2485
2518
  let recorded = 0;
2486
2519
  let skippedEdge = 0;
2520
+ let skippedInBand = 0;
2487
2521
  let lastKind = 'unknown';
2488
2522
  let lastPriceSrc = 'direct';
2489
2523
  for (const f of fills) {
@@ -2493,6 +2527,20 @@ class OrderManager {
2493
2527
  skippedEdge++;
2494
2528
  continue;
2495
2529
  }
2530
+ // Geometry eligibility: an in-band slot is not a window trade. Fails
2531
+ // OPEN when the geometry is unreadable (no boundary/gap yet), because
2532
+ // a cold grid must still arm on its first real fill.
2533
+ if (f.id != null) {
2534
+ try {
2535
+ const idx = parseSlotIndex(String(f.id));
2536
+ const geom = geometryTypeForSlotIndex(idx, this.boundaryIdx, this._gapSlots);
2537
+ if (geom === ORDER_TYPES.SPREAD) {
2538
+ skippedInBand++;
2539
+ continue;
2540
+ }
2541
+ }
2542
+ catch { /* unreadable geometry — treat as eligible */ }
2543
+ }
2496
2544
  let price = Number(f.price ?? f.order?.price);
2497
2545
  let priceSrc = 'direct';
2498
2546
  if (!Number.isFinite(price) || price <= 0) {
@@ -2523,13 +2571,19 @@ class OrderManager {
2523
2571
  this.logger?.log?.(`[FILL-PIVOT] pivot=${fmt(this._lastFilledPrice)}(${this._lastFilledType}) ` +
2524
2572
  `buy=${fmt(this._lastFilledBuyPrice)} sell=${fmt(this._lastFilledSellPrice)} ` +
2525
2573
  `n=${recorded} src=${lastKind}/${lastPriceSrc}` +
2526
- `${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}`, 'info');
2574
+ `${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}` +
2575
+ `${skippedInBand > 0 ? ` band-skipped=${skippedInBand}` : ''}`, 'info');
2527
2576
  }
2528
2577
  catch { /* logging is best-effort */ }
2529
2578
  }
2530
- else if (skippedEdge > 0) {
2579
+ else if (skippedEdge > 0 || skippedInBand > 0) {
2531
2580
  try {
2532
- this.logger?.log?.(`[FILL-PIVOT] ${skippedEdge} edge-pinned fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade`, 'info');
2581
+ const parts = [];
2582
+ if (skippedEdge > 0)
2583
+ parts.push(`${skippedEdge} edge-pinned`);
2584
+ if (skippedInBand > 0)
2585
+ parts.push(`${skippedInBand} gap-band (stranded residual)`);
2586
+ this.logger?.log?.(`[FILL-PIVOT] ${parts.join(' + ')} fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade`, 'info');
2533
2587
  }
2534
2588
  catch { /* logging is best-effort */ }
2535
2589
  }
@@ -2880,6 +2934,11 @@ class OrderManager {
2880
2934
  * @param {boolean} [options.skipBroadcastWait] - Set by the COW re-plan path,
2881
2935
  * which runs INSIDE its own startBroadcasting() region and must not wait
2882
2936
  * on the flag it holds itself.
2937
+ * @param {boolean} [options.holdPlanRegion] - Claim the exclusive placement
2938
+ * region before planning and ride it on the result, so the plan→broadcast
2939
+ * window is serialized against other planners. Set by the callers that are
2940
+ * guaranteed to execute the result (fill path, post-recovery rebalance).
2941
+ * Planner-only callers (unit fixtures) leave it off and stay lease-free.
2883
2942
  * @returns {Promise<any>}
2884
2943
  */
2885
2944
  async performSafeRebalance(fills = [], excludeIds = new Set(), options = {}) {
@@ -2971,9 +3030,57 @@ class OrderManager {
2971
3030
  }
2972
3031
  }
2973
3032
  }
2974
- return await this._gridLock.acquire(async () => {
2975
- return await this._applySafeRebalanceCOW(fills, excludeIds);
2976
- });
3033
+ // PLAN REGION (plan → broadcast → commit), opted in by holdPlanRegion.
3034
+ // For the callers that are guaranteed to execute the result (the fill
3035
+ // path and the post-recovery rebalance), the region is claimed BEFORE
3036
+ // planning, not by the executor afterwards. The old split left a window
3037
+ // between "plan finished" and "executor claimed placement" in which a
3038
+ // second planner passed every pre-check (`isPlacementActive()` was still
3039
+ // false), built from the same master, and both batches broadcast — the
3040
+ // duplicate-order window (two plans 595 ms apart, observed 2026-11-13).
3041
+ // Holding the lease across the plan makes the next planner defer on the
3042
+ // existing `isPlacementActive()` check; the lease rides on the result
3043
+ // and the executor adopts it (placement_lock.ts PLAN_LEASE_RESULT_KEY).
3044
+ // Planner-only callers leave the flag off: they never execute, so a
3045
+ // lease would only strand the region.
3046
+ //
3047
+ // `skipBroadcastWait` is the COW re-plan recursion: this frame is
3048
+ // already inside the executor's region and hands its own lease to the
3049
+ // inline re-broadcast, so acquiring again would self-deadlock (the
3050
+ // lock is not reentrant).
3051
+ let planLease = null;
3052
+ if (options?.holdPlanRegion === true && !options?.skipBroadcastWait
3053
+ && typeof this.tryAcquirePlacement === 'function') {
3054
+ // Non-blocking by design: a planner that cannot get the region
3055
+ // DEFERS (the same level-triggered contract as the
3056
+ // isPlacementActive() pre-check just above) instead of parking the
3057
+ // fill lock for a full acquisition timeout. The pre-check makes
3058
+ // this a narrow race, not the normal path.
3059
+ planLease = this.tryAcquirePlacement('cow-plan');
3060
+ if (!planLease) {
3061
+ this.logger.log('[SAFE-REBALANCE] Deferred: exclusive placement region became unavailable; rebalance retries after it ends', 'info');
3062
+ this._deferredRebalanceAt = Date.now();
3063
+ return { ...buildAbortedResult('placement-active-deferred'), deferred: true };
3064
+ }
3065
+ }
3066
+ let result;
3067
+ try {
3068
+ result = await this._gridLock.acquire(async () => {
3069
+ return await this._applySafeRebalanceCOW(fills, excludeIds);
3070
+ });
3071
+ }
3072
+ catch (err) {
3073
+ // A plan that throws must not park the region (the COW body's own
3074
+ // claim path has the same contract).
3075
+ planLease?.release();
3076
+ throw err;
3077
+ }
3078
+ if (!result || result.aborted) {
3079
+ planLease?.release();
3080
+ return result;
3081
+ }
3082
+ attachPlanLease(result, planLease);
3083
+ return result;
2977
3084
  }
2978
3085
  async _applySafeRebalanceCOW(fills = [], excludeIds = new Set()) {
2979
3086
  const cowEngine = this._getCOWEngine();
@@ -3096,7 +3203,7 @@ class OrderManager {
3096
3203
  comparePrecisions
3097
3204
  });
3098
3205
  if (!preCommitGuard.canCommit) {
3099
- this.logger.log(`[COW] ${preCommitGuard.reason}`, preCommitGuard.level || 'warn');
3206
+ this.logger.log(`[COW] ${preCommitGuard.reason}`, preCommitGuard?.level || 'warn');
3100
3207
  releaseStackEntry();
3101
3208
  return false;
3102
3209
  }
@@ -3108,7 +3215,7 @@ class OrderManager {
3108
3215
  comparePrecisions
3109
3216
  });
3110
3217
  if (!lockCommitGuard.canCommit) {
3111
- this.logger.log(`[COW] ${lockCommitGuard.reason}`, lockCommitGuard.level || 'warn');
3218
+ this.logger.log(`[COW] ${lockCommitGuard.reason}`, lockCommitGuard?.level || 'warn');
3112
3219
  // Working grid ref is cleared exactly once below via the
3113
3220
  // !committed path (the callback returns without committing).
3114
3221
  return;
@@ -44,6 +44,36 @@ export interface PlacementCapableManager {
44
44
  isPlacementLeaseCurrent?(lease: PlacementLease | null | undefined): boolean;
45
45
  placementKind?(): string | null;
46
46
  }
47
+ /**
48
+ * Result-carried plan lease (the plan → broadcast → commit region).
49
+ *
50
+ * `performSafeRebalance` acquires the placement region BEFORE it plans, so a
51
+ * second planner cannot build from the master this plan is about to mutate
52
+ * (the gap between "plan finished" and "executor claimed placement" was the
53
+ * duplicate-order window: two plans 595 ms apart both passed the
54
+ * `isPlacementActive()` pre-check, then both broadcast). The lease rides on
55
+ * the rebalance result until the executor adopts it; every consumer either
56
+ * takes it (the COW body, which releases it in its own finally) or releases
57
+ * it (no-action / discarded results).
58
+ *
59
+ * Keep the property name in one place: producer (manager), consumer
60
+ * (dexbot_class / dexbot_cow_runtime / dexbot_state_recovery) and tests must
61
+ * agree on it.
62
+ */
63
+ export declare const PLAN_LEASE_RESULT_KEY = "_planPlacementLease";
64
+ export declare function attachPlanLease(result: unknown, lease: PlacementLease | null | undefined): void;
65
+ /**
66
+ * Remove and return the plan lease carried by a rebalance result.
67
+ * The caller becomes the owner and MUST release it (directly or through the
68
+ * COW body's finally). Taking is idempotent: a second call returns null.
69
+ */
70
+ export declare function takePlanLease(result: unknown): PlacementLease | null;
71
+ /**
72
+ * Release (and drop) a plan lease a caller will not execute. Safe on results
73
+ * that never carried one, and safe to call twice (lease release is
74
+ * token-guarded/idempotent).
75
+ */
76
+ export declare function releasePlanLease(result: unknown): void;
47
77
  /**
48
78
  * Run `fn` inside the exclusive placement region.
49
79
  *
@@ -34,6 +34,54 @@
34
34
  * still the lease that owns the region?".
35
35
  */
36
36
  const leaseTokens = new WeakMap();
37
+ /**
38
+ * Result-carried plan lease (the plan → broadcast → commit region).
39
+ *
40
+ * `performSafeRebalance` acquires the placement region BEFORE it plans, so a
41
+ * second planner cannot build from the master this plan is about to mutate
42
+ * (the gap between "plan finished" and "executor claimed placement" was the
43
+ * duplicate-order window: two plans 595 ms apart both passed the
44
+ * `isPlacementActive()` pre-check, then both broadcast). The lease rides on
45
+ * the rebalance result until the executor adopts it; every consumer either
46
+ * takes it (the COW body, which releases it in its own finally) or releases
47
+ * it (no-action / discarded results).
48
+ *
49
+ * Keep the property name in one place: producer (manager), consumer
50
+ * (dexbot_class / dexbot_cow_runtime / dexbot_state_recovery) and tests must
51
+ * agree on it.
52
+ */
53
+ export const PLAN_LEASE_RESULT_KEY = '_planPlacementLease';
54
+ export function attachPlanLease(result, lease) {
55
+ if (!result || typeof result !== 'object' || !lease)
56
+ return;
57
+ result[PLAN_LEASE_RESULT_KEY] = lease;
58
+ }
59
+ /**
60
+ * Remove and return the plan lease carried by a rebalance result.
61
+ * The caller becomes the owner and MUST release it (directly or through the
62
+ * COW body's finally). Taking is idempotent: a second call returns null.
63
+ */
64
+ export function takePlanLease(result) {
65
+ if (!result || typeof result !== 'object')
66
+ return null;
67
+ const carrier = result;
68
+ const lease = carrier[PLAN_LEASE_RESULT_KEY] ?? null;
69
+ if (lease)
70
+ delete carrier[PLAN_LEASE_RESULT_KEY];
71
+ return lease;
72
+ }
73
+ /**
74
+ * Release (and drop) a plan lease a caller will not execute. Safe on results
75
+ * that never carried one, and safe to call twice (lease release is
76
+ * token-guarded/idempotent).
77
+ */
78
+ export function releasePlanLease(result) {
79
+ const lease = takePlanLease(result);
80
+ try {
81
+ lease?.release();
82
+ }
83
+ catch { /* a release must never escape into the settle path */ }
84
+ }
37
85
  /** Used when the caller has no lock (dry-run mocks / browser shims). */
38
86
  const NOOP_PLACEMENT_LEASE = { kind: 'noop', release: () => { } };
39
87
  /**
@@ -29,6 +29,7 @@
29
29
  * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
30
30
  * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
31
31
  * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
32
+ * - describeMarketCrossingActions(...) - Observe actions priced across the market floor
32
33
  * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
33
34
  *
34
35
  * SECTION 3: ORDER CONSTRUCTION (5 functions)
@@ -1591,6 +1592,43 @@ declare function chainOrderUnchangedFromCache(chainOrder: ChainOrder | null | un
1591
1592
  * Detector only: any internal failure returns null (never blocks a broadcast).
1592
1593
  */
1593
1594
  declare function detectCrossedBookPlan(manager: OrderManagerLike, actions: CowAction[]): string | null;
1595
+ /**
1596
+ * Describe batch actions whose result price sits on the WRONG side of the
1597
+ * market floor — the EVIDENCE for the crossing OBSERVATION.
1598
+ *
1599
+ * Retrospective §9.10/P4 is explicit that this class must not be a hard veto:
1600
+ * "a hard veto re-opens the counter-order deadlock: after a gap the counter
1601
+ * sits across the floor by construction and executes at the best available
1602
+ * price. Made visible instead." A pre-broadcast version that dropped the
1603
+ * actions (and refused the batch when nothing remained) re-created exactly
1604
+ * that deadlock live on 2026-11-15: the only repair for an out-of-spread rail
1605
+ * was priced above a cached mid, the batch was refused, and the grid stayed
1606
+ * 3.0% wide (limit 1.65%) until the mid happened to move 86 minutes later.
1607
+ *
1608
+ * Evidence: the SHARED recency-aware floor (resolveSpreadCrossingFloor — an
1609
+ * executed trade is fresher truth than an older book read). The rejected
1610
+ * implementation re-derived its own reference from manager._liveMarketPrice
1611
+ * behind a 15-minute window, i.e. a second answer to "where is the market?":
1612
+ * live, that mid was 8 minutes old, had itself been the midpoint of the bot's
1613
+ * own book, and the five fills in hand (all newer than the mid, the last one
1614
+ * 4.4% above it) had already falsified it. The same batch, at identical
1615
+ * prices, was accepted at the next tick once a fresher read existed.
1616
+ *
1617
+ * CANCELs are never reported: a cancel cannot cross anything. Fail-open on
1618
+ * every unprovable case (no floor, malformed action).
1619
+ *
1620
+ * @param {Object} manager - OrderManager instance
1621
+ * @param {Array} actions - COW batch actions (never mutated)
1622
+ * @returns {{ floor: number|null, dropped: Array<{ index: number, action: Object, reason: string }> }}
1623
+ */
1624
+ declare function describeMarketCrossingActions(manager: OrderManagerLike, actions: CowAction[]): {
1625
+ floor: number | null;
1626
+ dropped: Array<{
1627
+ index: number;
1628
+ action: CowAction;
1629
+ reason: string;
1630
+ }>;
1631
+ };
1594
1632
  /**
1595
1633
  * Collect every on-chain order id master currently needs to converge against,
1596
1634
  * so adoption can re-read them by id (immune to the get_full_accounts window
@@ -1630,7 +1668,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1630
1668
  createIds: string[];
1631
1669
  all: string[];
1632
1670
  };
1633
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1671
+ export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, describeMarketCrossingActions, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1634
1672
  export type { CrawlEntry };
1635
1673
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1636
1674
  //# sourceMappingURL=order.d.ts.map
@@ -29,6 +29,7 @@
29
29
  * - buildCrossingCheckCandidates(...) - Candidate set for crossing-placement checks
30
30
  * - chainOrderUnchangedFromCache(...) - Chain order still matches cached pre-update state
31
31
  * - detectCrossedBookPlan(...) - Pre-broadcast crossed-book assert
32
+ * - describeMarketCrossingActions(...) - Observe actions priced across the market floor
32
33
  * - collectKnownOnChainOrderIds(...) - On-chain ids master must converge against
33
34
  *
34
35
  * SECTION 3: ORDER CONSTRUCTION (5 functions)
@@ -127,7 +128,7 @@ import { ORDER_TYPES, ORDER_STATES, TIMING, FEE_PARAMETERS, GRID_LIMITS, NATIVE_
127
128
  import * as Format from '../format.js';
128
129
  import * as MathUtils from './math.js';
129
130
  import Logger from '../../order/logger.js';
130
- import { sleep } from './system.js';
131
+ import { sleep, resolveSpreadCrossingFloor } from './system.js';
131
132
  import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
132
133
  import { hasGenesisLadder } from '../genesis_policy.js';
133
134
  import { parseSlotIndex } from './slot.js';
@@ -3897,6 +3898,76 @@ function detectCrossedBookPlan(manager, actions) {
3897
3898
  return null;
3898
3899
  }
3899
3900
  }
3901
+ /**
3902
+ * Describe batch actions whose result price sits on the WRONG side of the
3903
+ * market floor — the EVIDENCE for the crossing OBSERVATION.
3904
+ *
3905
+ * Retrospective §9.10/P4 is explicit that this class must not be a hard veto:
3906
+ * "a hard veto re-opens the counter-order deadlock: after a gap the counter
3907
+ * sits across the floor by construction and executes at the best available
3908
+ * price. Made visible instead." A pre-broadcast version that dropped the
3909
+ * actions (and refused the batch when nothing remained) re-created exactly
3910
+ * that deadlock live on 2026-11-15: the only repair for an out-of-spread rail
3911
+ * was priced above a cached mid, the batch was refused, and the grid stayed
3912
+ * 3.0% wide (limit 1.65%) until the mid happened to move 86 minutes later.
3913
+ *
3914
+ * Evidence: the SHARED recency-aware floor (resolveSpreadCrossingFloor — an
3915
+ * executed trade is fresher truth than an older book read). The rejected
3916
+ * implementation re-derived its own reference from manager._liveMarketPrice
3917
+ * behind a 15-minute window, i.e. a second answer to "where is the market?":
3918
+ * live, that mid was 8 minutes old, had itself been the midpoint of the bot's
3919
+ * own book, and the five fills in hand (all newer than the mid, the last one
3920
+ * 4.4% above it) had already falsified it. The same batch, at identical
3921
+ * prices, was accepted at the next tick once a fresher read existed.
3922
+ *
3923
+ * CANCELs are never reported: a cancel cannot cross anything. Fail-open on
3924
+ * every unprovable case (no floor, malformed action).
3925
+ *
3926
+ * @param {Object} manager - OrderManager instance
3927
+ * @param {Array} actions - COW batch actions (never mutated)
3928
+ * @returns {{ floor: number|null, dropped: Array<{ index: number, action: Object, reason: string }> }}
3929
+ */
3930
+ function describeMarketCrossingActions(manager, actions) {
3931
+ const list = Array.isArray(actions) ? actions : [];
3932
+ let floor = null;
3933
+ try {
3934
+ floor = resolveSpreadCrossingFloor(manager);
3935
+ }
3936
+ catch {
3937
+ floor = null;
3938
+ }
3939
+ const usable = floor != null && Number.isFinite(Number(floor)) && Number(floor) > 0;
3940
+ if (!usable)
3941
+ return { floor: null, dropped: [] };
3942
+ const ref = Number(floor);
3943
+ const dropped = [];
3944
+ list.forEach((a, index) => {
3945
+ try {
3946
+ if (!a || a.type === COW_ACTIONS.CANCEL)
3947
+ return;
3948
+ const price = Number(a.type === COW_ACTIONS.UPDATE
3949
+ ? (a.newPrice ?? a.order?.price)
3950
+ : a.order?.price);
3951
+ let type = a.order?.type;
3952
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL) {
3953
+ // Same legacy convention as detectCrossedBookPlan: derive the
3954
+ // side from the existing book entry / order being updated.
3955
+ const entry = manager?.orders?.get?.(String(a.orderId ?? a.id ?? ''));
3956
+ type = entry?.type;
3957
+ }
3958
+ if (!Number.isFinite(price) || (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL))
3959
+ return;
3960
+ if (type === ORDER_TYPES.BUY && price > ref) {
3961
+ dropped.push({ index, action: a, reason: `BUY ${price} above the market floor ${ref}` });
3962
+ }
3963
+ else if (type === ORDER_TYPES.SELL && price < ref) {
3964
+ dropped.push({ index, action: a, reason: `SELL ${price} below the market floor ${ref}` });
3965
+ }
3966
+ }
3967
+ catch { /* fail-open per action */ }
3968
+ });
3969
+ return { floor: ref, dropped };
3970
+ }
3900
3971
  /**
3901
3972
  * Collect every on-chain order id master currently needs to converge against,
3902
3973
  * so adoption can re-read them by id (immune to the get_full_accounts window
@@ -3983,6 +4054,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3983
4054
  const all = new Set([...masterIds, ...createIds]);
3984
4055
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3985
4056
  }
3986
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
4057
+ export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, getLivePendingBroadcasts, 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, isStructuralRebuildStaleReason, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, describeMarketCrossingActions, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3987
4058
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3988
4059
  //# sourceMappingURL=order.js.map