dexbot 1.7.0 → 1.7.1

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 (105) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +11 -1
  24. package/dist/modules/account_orders.d.ts +12 -0
  25. package/dist/modules/account_orders.js +30 -0
  26. package/dist/modules/bitshares-native/transport.js +24 -6
  27. package/dist/modules/bitshares_client.d.ts +24 -6
  28. package/dist/modules/bitshares_client.js +44 -7
  29. package/dist/modules/bot_settings.d.ts +2 -0
  30. package/dist/modules/constants.d.ts +26 -3
  31. package/dist/modules/constants.js +63 -8
  32. package/dist/modules/dexbot_class.d.ts +1 -6
  33. package/dist/modules/dexbot_class.js +14 -0
  34. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  35. package/dist/modules/dexbot_cow_runtime.js +620 -132
  36. package/dist/modules/dexbot_fill_runtime.js +124 -35
  37. package/dist/modules/dexbot_maintenance_runtime.js +226 -73
  38. package/dist/modules/dexbot_startup_runtime.js +32 -20
  39. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  40. package/dist/modules/dexbot_state_recovery.js +167 -5
  41. package/dist/modules/node_connect_policy.d.ts +8 -1
  42. package/dist/modules/node_connect_policy.js +18 -2
  43. package/dist/modules/node_flap_score.d.ts +87 -0
  44. package/dist/modules/node_flap_score.js +124 -0
  45. package/dist/modules/node_health_cache.d.ts +40 -3
  46. package/dist/modules/node_health_cache.js +66 -20
  47. package/dist/modules/node_manager.d.ts +101 -19
  48. package/dist/modules/node_manager.js +255 -65
  49. package/dist/modules/order/accounting.js +56 -7
  50. package/dist/modules/order/format.d.ts +24 -10
  51. package/dist/modules/order/format.js +30 -10
  52. package/dist/modules/order/grid.js +82 -11
  53. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  54. package/dist/modules/order/grid_reconcile.js +333 -210
  55. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  56. package/dist/modules/order/grid_reconcile_internal.js +207 -87
  57. package/dist/modules/order/index.d.ts +4 -0
  58. package/dist/modules/order/lifecycle.d.ts +353 -0
  59. package/dist/modules/order/lifecycle.js +1109 -0
  60. package/dist/modules/order/manager.d.ts +271 -5
  61. package/dist/modules/order/manager.js +651 -48
  62. package/dist/modules/order/placement_lock.d.ts +102 -0
  63. package/dist/modules/order/placement_lock.js +222 -0
  64. package/dist/modules/order/strategy.js +13 -1
  65. package/dist/modules/order/sync_engine.d.ts +13 -1
  66. package/dist/modules/order/sync_engine.js +153 -53
  67. package/dist/modules/order/utils/math.d.ts +22 -1
  68. package/dist/modules/order/utils/math.js +54 -1
  69. package/dist/modules/order/utils/order.d.ts +75 -5
  70. package/dist/modules/order/utils/order.js +158 -9
  71. package/dist/modules/order/utils/system.d.ts +18 -0
  72. package/dist/modules/order/utils/system.js +84 -8
  73. package/dist/modules/order/utils/validate.d.ts +7 -1
  74. package/dist/modules/order/utils/validate.js +48 -2
  75. package/dist/modules/outcome.d.ts +54 -0
  76. package/dist/modules/outcome.js +51 -0
  77. package/dist/modules/settings_merge.d.ts +4 -0
  78. package/dist/modules/settings_merge.js +9 -0
  79. package/dist/modules/timing_policy.d.ts +82 -0
  80. package/dist/modules/timing_policy.js +244 -0
  81. package/dist/modules/types.d.ts +132 -0
  82. package/dist/scripts/analyze-credit.js +54 -17
  83. package/dist/scripts/analyze-orders.d.ts +4 -2
  84. package/dist/scripts/analyze-orders.js +113 -34
  85. package/dist/scripts/chart_targets.js +11 -15
  86. package/dist/scripts/test-credit-renewal.js +12 -5
  87. package/docs/COW_INVARIANTS.md +67 -8
  88. package/docs/DEXBOT_COMPARISON.md +6 -6
  89. package/docs/EVOLUTION.md +9 -8
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  91. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  92. package/docs/GRID_RECONCILE.md +17 -12
  93. package/docs/LOGGING.md +25 -1
  94. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +175 -26
  95. package/docs/README.md +23 -2
  96. package/docs/WORKFLOW.md +9 -3
  97. package/docs/architecture.md +42 -5
  98. package/docs/developer_guide.md +25 -8
  99. package/modules/README.md +3 -0
  100. package/package.json +1 -1
  101. package/scripts/README.md +16 -0
  102. package/scripts/pdev.sh +14 -1
  103. package/scripts/pmain.sh +23 -8
  104. package/scripts/ptest.sh +7 -0
  105. package/tests/README.md +30 -1
@@ -138,9 +138,10 @@ function batchReadOrdersSeam(mgr, orderIds, timeoutMs) {
138
138
  const { BitShares } = client;
139
139
  import { NATIVE_CLIENT } from '../constants.js';
140
140
  const { toFiniteNumber } = Format;
141
- import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
141
+ import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, resolveGapSlots, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
142
142
  import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders, attributeUnmatchedFillToGrid, reviveVirtualSlotFromChain, resolveExecutionPrice } from './utils/order.js';
143
143
  import { parseSlotIndex } from './utils/slot.js';
144
+ import { readSlotLifecycle } from './lifecycle.js';
144
145
  import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
145
146
  import { hasGenesisLadder } from './genesis_policy.js';
146
147
  import { getErrorMessage } from '../utils/errors.js';
@@ -497,6 +498,20 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
497
498
  matchedGridOrderIds.delete(bestMatch.id);
498
499
  return false;
499
500
  }
501
+ // ADOPTION IS CHAIN EVIDENCE: a chain order was matched into this slot by
502
+ // this very snapshot, so record it as such. The write funnel can only speak
503
+ // for the LOCAL slot state ('local'); without this the registry would claim a
504
+ // purely local basis for the strongest thing we know about the order, and
505
+ // `observedAt` ("when did the chain last tell us anything") would never
506
+ // advance for adoptions.
507
+ try {
508
+ mgr._lifecycle?.markLanded?.(chainOrderId, {
509
+ slotId: String(bestMatch.id),
510
+ evidence: 'adoption',
511
+ phase: bestMatch.state === ORDER_STATES.PARTIAL ? 'filling' : 'landed',
512
+ });
513
+ }
514
+ catch { /* lifecycle bookkeeping must never break adoption */ }
500
515
  updatedOrders.push(bestMatch);
501
516
  chainOrderIdsOnGrid.add(chainOrderId);
502
517
  // Adopted means matched: drop any deferred-orphan record so fund counting
@@ -781,17 +796,30 @@ class SyncEngine {
781
796
  // This eliminates type confusion - each map has a single, clear purpose
782
797
  const parsedChainOrders = new Map();
783
798
  const rawChainOrders = new Map();
799
+ // Unparseable chain orders are UNKNOWN, not absent. A live order the
800
+ // node returned but we could not decode must never make its slot look
801
+ // empty: that virtualizes a real order and re-CREATEs on top of it.
802
+ // The id set is threaded into pass 1 so the absence decision can consult
803
+ // it (mirrors the accounting recovery sweep's `malformedOrderIds`).
804
+ const malformedChainOrderIds = new Set();
784
805
  for (const order of chainOrders) {
785
806
  try {
786
807
  const parsed = parseChainOrder(order, mgr.assets);
787
- if (!parsed)
808
+ if (!parsed) {
809
+ const rawId = order.id;
810
+ if (rawId != null)
811
+ malformedChainOrderIds.add(String(rawId));
788
812
  continue;
813
+ }
789
814
  // Store parsed (converted) data in parsedChainOrders
790
815
  parsedChainOrders.set(order.id, parsed);
791
816
  // Store raw blockchain data in separate map - clean separation of concerns
792
817
  rawChainOrders.set(order.id, order);
793
818
  }
794
819
  catch (e) {
820
+ const rawId = order.id;
821
+ if (rawId != null)
822
+ malformedChainOrderIds.add(String(rawId));
795
823
  mgr.logger?.log?.(`Warning: Error parsing chain order ${order.id}: ${getErrorMessage(e)}`, 'warn');
796
824
  continue;
797
825
  }
@@ -902,7 +930,7 @@ class SyncEngine {
902
930
  const runReconciliation = async () => {
903
931
  mgr.pauseFundRecalc();
904
932
  try {
905
- await this._performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options);
933
+ await this._performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, malformedChainOrderIds, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options);
906
934
  }
907
935
  finally {
908
936
  await mgr.resumeFundRecalc();
@@ -924,6 +952,7 @@ class SyncEngine {
924
952
  * @param {number} assetBPrecision - Asset B precision
925
953
  * @param {Map<string, any>} parsedChainOrders - Parsed chain orders by ID
926
954
  * @param {Map<string, Object>} rawChainOrders - Raw blockchain order objects by ID
955
+ * @param {Set<string>} malformedChainOrderIds - Chain order IDs that were returned but could not be parsed (UNKNOWN, not absent)
927
956
  * @param {Set<string>} chainOrderIdsOnGrid - Output set: chain order IDs matched to grid
928
957
  * @param {Set<string>} matchedGridOrderIds - Output set: grid order IDs matched to chain
929
958
  * @param {Array<Object>} filledOrders - Output array: orders detected as filled
@@ -933,7 +962,7 @@ class SyncEngine {
933
962
  * @param {Object} options - Sync options (skipAccounting, etc.)
934
963
  * @returns {Promise<any>}
935
964
  */
936
- async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
965
+ async _performSyncFromOpenOrders(mgr, assetAPrecision, assetBPrecision, parsedChainOrders, rawChainOrders, malformedChainOrderIds, chainOrderIdsOnGrid, matchedGridOrderIds, filledOrders, updatedOrders, ordersNeedingCorrection, unmatchedChainOrders, options) {
937
966
  const skipAccounting = (options?.skipAccounting ?? true);
938
967
  const queueCorrection = (entry) => {
939
968
  // Provenance: classify the detector so a stale replay at drain
@@ -972,6 +1001,14 @@ class SyncEngine {
972
1001
  continue;
973
1002
  let updatedOrder = { ...gridOrder };
974
1003
  chainOrderIdsOnGrid.add(gridOrder.orderId);
1004
+ // A grid order matched against this snapshot IS a chain
1005
+ // observation: record it with the only evidence kind that
1006
+ // advances `observedAt` (when did the chain last tell us).
1007
+ mgr._lifecycle?.markLanded?.(String(gridOrder.orderId), {
1008
+ slotId: String(gridOrder.id),
1009
+ evidence: 'chain-snapshot',
1010
+ phase: gridOrder.state === ORDER_STATES.PARTIAL ? 'filling' : 'landed',
1011
+ });
975
1012
  // REVIVE BEFORE ANYTHING ELSE: this slot is not placed but its
976
1013
  // chain order is still live. Leaving it VIRTUAL is the "dark
977
1014
  // level" state — invisible to window accounting
@@ -1183,6 +1220,19 @@ class SyncEngine {
1183
1220
  // divergence re-detects on the next sync.
1184
1221
  mgr.logger?.log?.(`[SYNC] Partial-size update for ${gridOrder.id} rejected — slot keeps booked size ${gridOrder.size}`, 'warn');
1185
1222
  }
1223
+ else if (chainSizeInt < currentSizeInt && gridOrder.orderId) {
1224
+ // Mark the fill's size/fund delta as already absorbed:
1225
+ // the fill-history batch that follows must not shrink
1226
+ // (or credit) it a second time.
1227
+ mgr.noteChainSizeAppliedFill?.(String(gridOrder.orderId), currentSizeInt - chainSizeInt);
1228
+ // The marker is persisted with the grid snapshot
1229
+ // (debugInputs). Force the snapshot dirty AFTER
1230
+ // recording it: a flush already queued by
1231
+ // _applyOrderUpdate may have captured the grid
1232
+ // without the marker, and a crash in that window
1233
+ // would replay the fill as a second shrink.
1234
+ mgr._markGridDirty?.();
1235
+ }
1186
1236
  }
1187
1237
  else {
1188
1238
  const spreadOrder = convertToSpreadPlaceholder(gridOrder);
@@ -1216,59 +1266,68 @@ class SyncEngine {
1216
1266
  // genuine fill on the other side.
1217
1267
  // Don't virtualize orders placed by a successful COW commit.
1218
1268
  // The chain snapshot may lag behind confirmed transactions,
1219
- // causing correctly-placed orders to appear missing. _committedOrderIds
1220
- // is atomically rebuilt from every successful COW commit
1269
+ // causing correctly-placed orders to appear missing. The committed
1270
+ // snapshot is published by every successful COW commit
1221
1271
  // (manager.ts:_commitWorkingGrid) and is always active for all sync
1222
- // paths.
1223
- // filled/virtualized orders are absent from the next commit's
1224
- // finalMap, so their IDs drop out on the next atomic rebuild.
1225
- //
1226
- // SAFETY: _committedOrderIds is replaced atomically (reference swap)
1227
- // by _commitWorkingGrid. The sync reads has(gridOrder.orderId) against the
1228
- // current reference. If a concurrent COW commit replaces the set mid-sync,
1229
- // the new set is a superset (only adds entries for newly committed orders).
1230
- // An order in the superset was just committed, so it is genuinely on-chain
1231
- // and should not be virtualized. An order removed from the old set was
1232
- // filled/virtualized, which the sync will detect independently via the
1233
- // chain snapshot. Superset behavior is safe for this guard.
1272
+ // paths. Filled/virtualized orders are absent from the next commit's
1273
+ // finalMap, so their IDs drop out on the next atomic publish.
1234
1274
  //
1235
1275
  // ESCAPE HATCH 1 — Ghost orders (PARTIAL + size=0): These preserve the
1236
1276
  // original orderId only to block duplicate CREATEs after a full fill
1237
- // that the chain hasn't closed yet. The orderId is in _committedOrderIds
1238
- // because the original order was COW-placed, but the slot is already a
1239
- // known fill. Allow phantom detection to proceed so the ghost is cleaned
1240
- // up on the next sync cycle after the chain cancel succeeds.
1277
+ // that the chain hasn't closed yet. The orderId is in the committed
1278
+ // snapshot because the original order was COW-placed, but the slot is
1279
+ // already a known fill. Allow phantom detection to proceed so the ghost
1280
+ // is cleaned up on the next sync cycle after the chain cancel succeeds.
1241
1281
  //
1242
- // ESCAPE HATCH 2 — Time-based: If the most recent COW commit is older
1243
- // than SYNC_LOCK_TIMEOUT_MS, the committed-but-missing order is
1244
- // presumed genuinely filled. The chain should have confirmed or
1245
- // rejected the transaction within the sync timeout window (~7 blocks
1246
- // at 3s each). Prevents permanent stall when a fill event was missed
1247
- // (reconnect gap, lossy subscription) and the only detection path is
1248
- // this open-orders sync.
1249
- if (gridOrder.orderId != null && mgr._committedOrderIds?.has(gridOrder.orderId)) {
1250
- const commitAge = Date.now() - (mgr._committedOrderIdsBuiltAt || 0);
1282
+ // ESCAPE HATCH 2 — Time-based: the lifecycle in-flight window is
1283
+ // bounded (2× the pending-broadcast TTL), so a permanently lagging
1284
+ // node cannot park cleanup forever; past it the committed-but-missing
1285
+ // order is presumed genuinely filled. This is what keeps a missed fill
1286
+ // event (reconnect gap, lossy subscription) from stalling the grid.
1287
+ //
1288
+ // ONE GUARD: the absence decision asks `isInFlight()` — the single
1289
+ // definition of "absence is not trustworthy yet". This site used to
1290
+ // consult the committed window and the fresh-assignment window
1291
+ // separately, while the startup reconcile and the fund recalibration
1292
+ // sweep asked `isInFlight()`: same order, three different answers for
1293
+ // the `unknown`/`broadcasting` phases (an abandoned CREATE receipt, an
1294
+ // unreadable chain entry). Those phases are exactly what the guard is
1295
+ // for, so reading a subset here re-opened the bug class it exists to
1296
+ // close.
1297
+ if (gridOrder.orderId != null) {
1298
+ const slotLifecycle = readSlotLifecycle(mgr, gridOrder);
1251
1299
  const isGhost = gridOrder.size <= 0 && gridOrder.state === ORDER_STATES.PARTIAL;
1252
- if (!isGhost && commitAge < TIMING.SYNC_LOCK_TIMEOUT_MS) {
1300
+ // Guard 0: the order was returned but could not be decoded.
1301
+ // Absence is UNKNOWN — keep the id and let a later, readable
1302
+ // snapshot decide. Reading an unparseable entry as absent
1303
+ // virtualizes a live order and duplicates it on re-create.
1304
+ if (malformedChainOrderIds.has(String(gridOrder.orderId))) {
1305
+ mgr._lifecycle?.markUnknown?.(String(gridOrder.orderId), {
1306
+ slotId: String(gridOrder.id),
1307
+ evidence: 'chain-snapshot',
1308
+ });
1309
+ mgr.logger?.log?.(`[SYNC] ${gridOrder.id}: chain order ${gridOrder.orderId} is present but unparseable — ` +
1310
+ `absence is UNKNOWN (not virtualizing)`, 'warn');
1311
+ continue;
1312
+ }
1313
+ // Ghosts are known fills: they must pass so the cleanup runs.
1314
+ if (!isGhost && slotLifecycle.isInFlight()) {
1315
+ if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL) {
1316
+ mgr.logger?.log?.(`[SYNC] ${gridOrder.id}: chain order ${gridOrder.orderId} is absent from the snapshot but ` +
1317
+ `${slotLifecycle.isUnresolved
1318
+ ? 'its lifecycle phase is unresolved'
1319
+ : 'it was assigned/committed recently'} — absence not yet trustworthy`, 'debug');
1320
+ }
1321
+ else {
1322
+ mgr.logger?.log?.(`[SYNC] Stale-id check for ${gridOrder.id} deferred: chain id ${gridOrder.orderId} was ` +
1323
+ `assigned recently and is not in the snapshot — absence not yet trustworthy`, 'debug');
1324
+ }
1253
1325
  continue;
1254
1326
  }
1255
1327
  }
1256
1328
  const currentGridOrder = mgr.orders.get(gridOrder.id) || gridOrder;
1257
1329
  const hadOrderId = Boolean(currentGridOrder?.orderId);
1258
1330
  const wasPlaced = isOrderPlaced(currentGridOrder);
1259
- // A freshly assigned id on a NON-placed slot is not trustworthy
1260
- // evidence of absence yet (an in-flight create/cancel whose
1261
- // broadcast has not landed, or a lagging read). Mirrors the
1262
- // reconcile's _orderIdAssignedAt deferral: keep the id, re-check
1263
- // next sync. A PLACED slot keeps the existing behaviour.
1264
- if (!wasPlaced && hadOrderId) {
1265
- const assignedAt = Number(mgr._orderIdAssignedAt?.get(String(currentGridOrder.orderId)) || 0);
1266
- if (assignedAt > 0 && Date.now() - assignedAt < TIMING.SYNC_LOCK_TIMEOUT_MS) {
1267
- mgr.logger?.log?.(`[SYNC] Stale-id check for ${gridOrder.id} deferred: chain id ${currentGridOrder.orderId} was ` +
1268
- `assigned ${Date.now() - assignedAt}ms ago and is not in the snapshot — absence not yet trustworthy`, 'debug');
1269
- continue;
1270
- }
1271
- }
1272
1331
  const spreadOrder = convertToSpreadPlaceholder(currentGridOrder);
1273
1332
  const cleanupContext = wasPlaced ? 'sync-cleanup-phantom' : 'sync-clear-stale-id';
1274
1333
  const phantomApplied = await mgr._applyOrderUpdate(spreadOrder, cleanupContext, { skipAccounting: skipAccounting, fee: 0 });
@@ -1386,7 +1445,11 @@ class SyncEngine {
1386
1445
  continue;
1387
1446
  }
1388
1447
  }
1389
- const gapSlots = genesis?.gapSlots ?? mgr._gapSlots ?? 0;
1448
+ // Unknown geometry must NOT read as gap 0 (a 0-wide band turns the
1449
+ // slot just above the boundary into a SELL rail slot, so an in-band
1450
+ // orphan could be adopted onto the wrong rail). resolveGapSlots is
1451
+ // the single source of truth (_gapSlots ?? config-derived).
1452
+ const gapSlots = genesis?.gapSlots ?? resolveGapSlots(mgr);
1390
1453
  const boundaryIdx = mgr.boundaryIdx;
1391
1454
  // Pre-boundary sync: gap geometry is unknown, so adoption is
1392
1455
  // deferred entirely — touch nothing (no adopt, no cancelOnly).
@@ -1537,7 +1600,26 @@ class SyncEngine {
1537
1600
  const currentSizeInt = Number.isFinite(effectiveRawForSale)
1538
1601
  ? Math.max(0, Math.round(effectiveRawForSale))
1539
1602
  : currentSizeIntFromGrid;
1540
- const newSizeInt = Math.max(0, currentSizeInt - filledAmountInt);
1603
+ // `rawOnChain.for_sale` may already include the part of this fill that
1604
+ // sync pass 1 absorbed. Subtract only the NOT-yet-applied remainder;
1605
+ // subtracting the whole fill (or none of it) is the double-shrink /
1606
+ // growth pair from the 2026-11-03 incident. Both forms are supported:
1607
+ // the explicit applied amount (partial coverage) and the legacy boolean.
1608
+ const explicitApplied = Number.isFinite(Number(params.alreadyAppliedInt))
1609
+ ? Math.round(Number(params.alreadyAppliedInt))
1610
+ : 0;
1611
+ // The legacy boolean is a FALLBACK, never a floor: it carries no amount,
1612
+ // so it can only speak for the whole fill. It is honoured ONLY when the
1613
+ // caller supplied no explicit applied amount — otherwise a group in
1614
+ // which ONE entry was marked would skip the unapplied remainder of its
1615
+ // siblings (the aggregated batch path reads the flag off the last entry
1616
+ // only, so the explicit sum must win).
1617
+ const hasExplicitApplied = params.alreadyAppliedInt != null
1618
+ && Number.isFinite(Number(params.alreadyAppliedInt));
1619
+ const appliedFromBoolean = !hasExplicitApplied && params.alreadyAppliedChainSize ? filledAmountInt : 0;
1620
+ const appliedInt = Math.max(0, Math.min(filledAmountInt, Math.max(explicitApplied, appliedFromBoolean)));
1621
+ const remainingFillInt = Math.max(0, filledAmountInt - appliedInt);
1622
+ const newSizeInt = Math.max(0, currentSizeInt - remainingFillInt);
1541
1623
  const newSize = blockchainToFloat(newSizeInt, precision);
1542
1624
  if (Number.isFinite(effectiveRawForSale) && currentSizeInt !== currentSizeIntFromGrid) {
1543
1625
  mgr.logger.log(`[SYNC] Using rawOnChain.for_sale baseline for ${matchedGridOrder.orderId}: raw=${currentSizeInt}, grid=${currentSizeIntFromGrid}` +
@@ -1614,6 +1696,18 @@ class SyncEngine {
1614
1696
  }
1615
1697
  }
1616
1698
  }
1699
+ // ZERO-REMAINDER BRAKE: a fill that leaves nothing tradeable must never
1700
+ // produce a 0-size PARTIAL slot (invalid order state), even when the
1701
+ // quote-side rounding test above could not decide (a corrupt/zero slot
1702
+ // price makes `otherSize` non-finite, so `<= 0` is false). Deliberately
1703
+ // placed AFTER the residual verification: taking this brake earlier
1704
+ // skipped the explicit cancel of a real chain residual — the exact
1705
+ // stranding path `cancelResidualOrders` exists for.
1706
+ if (!isEffectivelyFull && newSizeInt <= 0) {
1707
+ isEffectivelyFull = true;
1708
+ mgr.logger.log(`[SYNC] Order ${matchedGridOrder.orderId} (slot ${matchedGridOrder.id}) leaves no tradeable remainder ` +
1709
+ `(filled=${filledAmountInt} baseline=${currentSizeInt} applied=${appliedInt}); treating as a full fill.`, 'debug');
1710
+ }
1617
1711
  let fullUpdate;
1618
1712
  let partialUpdate;
1619
1713
  let filledOrderResult;
@@ -1642,10 +1736,10 @@ class SyncEngine {
1642
1736
  const { btsFeeState, ...matchedWithoutDeferredFee } = matchedGridOrder;
1643
1737
  let updatedOrder = { ...matchedWithoutDeferredFee, type: orderType, state: ORDER_STATES.PARTIAL };
1644
1738
  if (updatedOrder.rawOnChain && updatedOrder.rawOnChain.for_sale !== undefined) {
1645
- const baselineForSale = (chainRefetched && Number.isFinite(effectiveRawForSale))
1646
- ? effectiveRawForSale
1647
- : toFiniteNumber(updatedOrder.rawOnChain.for_sale);
1648
- const nextForSaleInt = Math.max(0, Math.round(baselineForSale) - filledAmountInt);
1739
+ // The snapshot's for_sale is the authoritative remaining size
1740
+ // after the not-yet-applied portion was subtracted above; it is
1741
+ // never decremented a second time.
1742
+ const nextForSaleInt = newSizeInt;
1649
1743
  updatedOrder.rawOnChain = {
1650
1744
  ...updatedOrder.rawOnChain,
1651
1745
  for_sale: String(nextForSaleInt),
@@ -1784,7 +1878,9 @@ class SyncEngine {
1784
1878
  blockNum,
1785
1879
  historyId,
1786
1880
  isMaker,
1787
- fillPrice: ctx.fillPrice
1881
+ fillPrice: ctx.fillPrice,
1882
+ alreadyAppliedInt: Math.max(0, Math.round(Number(fillOp.__chainSizeAppliedInt) || 0)),
1883
+ alreadyAppliedChainSize: Boolean(fillOp.__chainSizeAlreadyApplied)
1788
1884
  });
1789
1885
  const filledOrders = [];
1790
1886
  const updatedOrders = [];
@@ -2044,8 +2140,10 @@ class SyncEngine {
2044
2140
  // Sum the integer filled amounts across this order's fills so
2045
2141
  // the single transition reflects the total consumption.
2046
2142
  let totalFilledAmountInt = 0;
2143
+ let totalAppliedInt = 0;
2047
2144
  for (const ctx of group) {
2048
2145
  totalFilledAmountInt += ctx.filledAmountInt;
2146
+ totalAppliedInt += Math.max(0, Math.round(Number(ctx.entry.fillOp.__chainSizeAppliedInt) || 0));
2049
2147
  }
2050
2148
  const totalFilledAmount = blockchainToFloat(totalFilledAmountInt, precision);
2051
2149
  if (group.length > 1) {
@@ -2069,7 +2167,9 @@ class SyncEngine {
2069
2167
  blockNum: lastCtx.entry.blockNum,
2070
2168
  historyId: lastCtx.entry.historyId,
2071
2169
  isMaker: lastCtx.entry.isMaker,
2072
- fillPrice: lastCtx.fillPrice
2170
+ fillPrice: lastCtx.fillPrice,
2171
+ alreadyAppliedInt: Math.min(totalFilledAmountInt, Math.max(0, totalAppliedInt)),
2172
+ alreadyAppliedChainSize: Boolean(lastCtx.entry.fillOp.__chainSizeAlreadyApplied)
2073
2173
  });
2074
2174
  if (result.isFull) {
2075
2175
  mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
@@ -1026,6 +1026,7 @@ declare function validateBoundaryCommit(proposedBoundary: number | null | undefi
1026
1026
  ok: boolean;
1027
1027
  reason?: string;
1028
1028
  detail?: string;
1029
+ inBandCount?: number;
1029
1030
  };
1030
1031
  /**
1031
1032
  * Validate a boundary restored from PERSISTED state (disk snapshot) before it
@@ -1061,7 +1062,27 @@ declare function validatePersistedBoundary(proposedBoundary: number | null | und
1061
1062
  ok: boolean;
1062
1063
  reason?: string;
1063
1064
  detail?: string;
1065
+ inBandCount?: number;
1064
1066
  };
1067
+ /**
1068
+ * Whether moving a boundary from `current` to `candidate` strands FEWER placed
1069
+ * orders (a violation-reducing repair). Strictly fewer — an equal count is not
1070
+ * a repair, and a structural refusal on either side is never a repair.
1071
+ *
1072
+ * This is the one rule behind the fill re-anchor and the rail clamp accepting a
1073
+ * move the strict validator would refuse only for transient stranding; both
1074
+ * bounds stay in force (fill-anchor direction at the caller, strand count here).
1075
+ *
1076
+ * @param currentBoundary - Boundary currently committed
1077
+ * @param candidateBoundary - Proposed boundary
1078
+ * @param orders - Placed-order slots
1079
+ * @param gapSlots - Gap band width
1080
+ * @param options - Optional in-band allow-list (a fill's own partial residual)
1081
+ * @returns True when the candidate strands strictly fewer placed orders
1082
+ */
1083
+ declare function boundaryMoveReducesStrands(currentBoundary: number | null | undefined, candidateBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
1084
+ allowInBandSlotIds?: Iterable<string>;
1085
+ }): boolean;
1065
1086
  /**
1066
1087
  * Whether a persisted-boundary rejection is the TRANSIENT kind that must not
1067
1088
  * trigger a rebuild: stranding (`placed_order_in_band`) with no accompanying
@@ -1272,7 +1293,7 @@ declare function derivePriceLevels(startPrice: number, minPrice: number, maxPric
1272
1293
  declare function pricesWithinHalfStep(priceA: number, priceB: number, incrementPercent: number | null | undefined): boolean;
1273
1294
  declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
1274
1295
  export type { FeeCacheEntry };
1275
- export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
1296
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, boundaryMoveReducesStrands, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
1276
1297
  /**
1277
1298
  * Round a value to a given factor.
1278
1299
  * @param {number} value - Value to round
@@ -1686,6 +1686,7 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
1686
1686
  return {
1687
1687
  ok: false,
1688
1688
  reason: BOUNDARY_REJECT_PLACED_IN_BAND,
1689
+ inBandCount,
1689
1690
  detail: `boundary=${raw} gapSlots=${gapSlots} placed count=${inBandCount} first idx=${firstInBandIdx} price=${firstInBandPrice} ` +
1690
1691
  `sits strictly inside implied band (${raw}, ${sellStart})`
1691
1692
  };
@@ -1726,6 +1727,58 @@ function validatePersistedBoundary(proposedBoundary, orders, gapSlots, options =
1726
1727
  ...(options.allowInBandSlotIds ? { allowInBandSlotIds: options.allowInBandSlotIds } : {})
1727
1728
  });
1728
1729
  }
1730
+ /**
1731
+ * Count the placed orders a boundary would strand inside its implied band.
1732
+ *
1733
+ * Returns 0 for a clean boundary, the validator's own count for a pure
1734
+ * stranding rejection, and null for a STRUCTURAL refusal (crossed book, ceiling,
1735
+ * range, non-integer) — the two are not comparable, so callers must not treat a
1736
+ * structural refusal as "zero strands". Uses the same validator (and the same
1737
+ * allow-list) as the commit/restore paths: no second stranding predicate.
1738
+ *
1739
+ * @param proposedBoundary - Boundary to judge
1740
+ * @param orders - Placed-order slots
1741
+ * @param gapSlots - Gap band width
1742
+ * @param options - Optional in-band allow-list (a fill's own partial residual)
1743
+ * @returns Strand count, or null when the refusal is structural
1744
+ */
1745
+ function countInBandPlacements(proposedBoundary, orders, gapSlots, options = {}) {
1746
+ const check = validateBoundaryCommit(proposedBoundary, orders, gapSlots, {
1747
+ rejectInBandPlacements: true,
1748
+ ...(options.allowInBandSlotIds ? { allowInBandSlotIds: options.allowInBandSlotIds } : {})
1749
+ });
1750
+ if (check.ok)
1751
+ return 0;
1752
+ if (check.reason === BOUNDARY_REJECT_PLACED_IN_BAND) {
1753
+ // Unknown is NOT zero: a validator that cannot report the count must not
1754
+ // read as "strands nothing" (the Number(null)===0 trap this stack keeps
1755
+ // guarding). Fail closed instead.
1756
+ const count = Number(check.inBandCount);
1757
+ return Number.isFinite(count) ? count : null;
1758
+ }
1759
+ return null;
1760
+ }
1761
+ /**
1762
+ * Whether moving a boundary from `current` to `candidate` strands FEWER placed
1763
+ * orders (a violation-reducing repair). Strictly fewer — an equal count is not
1764
+ * a repair, and a structural refusal on either side is never a repair.
1765
+ *
1766
+ * This is the one rule behind the fill re-anchor and the rail clamp accepting a
1767
+ * move the strict validator would refuse only for transient stranding; both
1768
+ * bounds stay in force (fill-anchor direction at the caller, strand count here).
1769
+ *
1770
+ * @param currentBoundary - Boundary currently committed
1771
+ * @param candidateBoundary - Proposed boundary
1772
+ * @param orders - Placed-order slots
1773
+ * @param gapSlots - Gap band width
1774
+ * @param options - Optional in-band allow-list (a fill's own partial residual)
1775
+ * @returns True when the candidate strands strictly fewer placed orders
1776
+ */
1777
+ function boundaryMoveReducesStrands(currentBoundary, candidateBoundary, orders, gapSlots, options = {}) {
1778
+ const current = countInBandPlacements(currentBoundary, orders, gapSlots, options);
1779
+ const candidate = countInBandPlacements(candidateBoundary, orders, gapSlots, options);
1780
+ return current !== null && candidate !== null && candidate < current;
1781
+ }
1729
1782
  /**
1730
1783
  * Whether a persisted-boundary rejection is the TRANSIENT kind that must not
1731
1784
  * trigger a rebuild: stranding (`placed_order_in_band`) with no accompanying
@@ -2188,7 +2241,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
2188
2241
  createdAt: Date.now()
2189
2242
  };
2190
2243
  }
2191
- export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2244
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, boundaryMoveReducesStrands, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2192
2245
  /**
2193
2246
  * Round a value to a given factor.
2194
2247
  * @param {number} value - Value to round
@@ -113,6 +113,7 @@
113
113
  *
114
114
  * ===============================================================================
115
115
  */
116
+ import type { PlacementLease } from '../placement_lock.js';
116
117
  import type { OrderManagerLike, PendingPriceCorrection, ChainOrder, ParsedChainOrder, AssetPair, AssetInfo, OrderType, ManagedOrder, UnmatchedChainOrder, CowAction, ProjectedFunds } from '../../types.js';
117
118
  import type { GridGenesis } from './math.js';
118
119
  interface CorrectionAccountOrdersLike {
@@ -142,6 +143,24 @@ interface CorrectionAccountOrdersLike {
142
143
  * @returns {boolean} True if the message indicates the order is gone.
143
144
  */
144
145
  declare function isOrderGoneErrorMessage(message: string | null | undefined, orderId?: string | null): boolean;
146
+ /**
147
+ * Classify a working-grid staleness reason as a STRUCTURAL rebuild.
148
+ *
149
+ * `_syncWorkingGridFromMasterMutation` stamps reasons such as
150
+ * `master mutation during broadcasting (grid-init)` (a full grid rebuild) or
151
+ * `(fill-place)` (a fill landing during the plan). The two are NOT
152
+ * interchangeable: after a rebuild the fresh master no longer carries the live
153
+ * chain order IDs, so re-planning from it emits CREATEs for price levels the
154
+ * startup reconcile is concurrently re-pricing via UPDATE — both generations
155
+ * land and the loser becomes a duplicate-price orphan backlog.
156
+ *
157
+ * Single source of truth for every planner/guard that must treat a rebuild
158
+ * differently from a fill. Keep the pattern anchored to the context tokens
159
+ * emitted by manager._syncWorkingGridFromMasterMutation / structural paths.
160
+ * @param {unknown} reason - evaluateCommit refusal reason or staleness label.
161
+ * @returns {boolean} True when the master was structurally rebuilt.
162
+ */
163
+ declare function isStructuralRebuildStaleReason(reason: unknown): boolean;
145
164
  /**
146
165
  * Record a duplicate-orphan detection for an orderId.
147
166
  * First sighting stays quiet (count 1). A repeated sighting of the same
@@ -173,8 +192,15 @@ declare function duplicateOrphanLogInfo(orderId: string | null | undefined): {
173
192
  declare function _filterUnmatchedChainOrders(manager: OrderManagerLike, chainOrderId: string): void;
174
193
  /**
175
194
  * Record a fresh on-chain placement timestamp for surplus-cancel grace.
176
- * Called when a slot gains a chain orderId it did not have before (create,
177
- * adopt, rotation target). Powers isFreshlyPlacedOrder below.
195
+ * Powers isFreshlyPlacedOrder below.
196
+ *
197
+ * NOTE: in production the placement stamp is written by the lifecycle write
198
+ * funnel (`OrderManager._syncLifecycleFromMutation` -> `markPlaced`) for every
199
+ * mutation, including the COW whole-map commit. This helper remains for callers
200
+ * that hold only a manager-shaped object (tests, fixtures) and for the `_placedAt`
201
+ * retention bound; it writes through the same facade, so there is still one copy
202
+ * of the stamp.
203
+ *
178
204
  * @param {unknown} manager - OrderManager instance (owns `_placedAt`)
179
205
  * @param {string} chainOrderId - Chain order id that was just placed
180
206
  */
@@ -449,13 +475,23 @@ declare function correctOrderPriceOnChain(manager: OrderManagerLike, correctionI
449
475
  * Cancel-type corrections (duplicate orphans, surplus) are batched into
450
476
  * chunked multi-op transactions; price updates run sequentially.
451
477
  *
478
+ * Runs inside the exclusive placement region: every correction broadcasts a
479
+ * chain mutation, so it must never interleave with a COW batch, startup
480
+ * reconcile Phase 2 or a dust/residual cancel. A caller already holding the
481
+ * region (COW pre-batch drain) passes its lease so the nested call does not
482
+ * deadlock.
483
+ *
452
484
  * @param {Object} manager - OrderManager instance
453
485
  * @param {string} accountName - Account name for blockchain transactions
454
486
  * @param {string} privateKey - Private key for signing
455
487
  * @param {Object} accountOrders - AccountOrders accessor for blockchain ops
488
+ * @param {Object} [options] - placementLease (reuse) + timeoutMs (bounded wait)
456
489
  * @returns {Promise<Object>} Summary {corrected, failed, results}
457
490
  */
458
- declare function correctAllPriceMismatches(manager: OrderManagerLike, accountName: string, privateKey: string, accountOrders: CorrectionAccountOrdersLike): Promise<{
491
+ declare function correctAllPriceMismatches(manager: OrderManagerLike, accountName: string, privateKey: string, accountOrders: CorrectionAccountOrdersLike, options?: {
492
+ placementLease?: PlacementLease | null;
493
+ timeoutMs?: number;
494
+ }): Promise<{
459
495
  corrected: number;
460
496
  failed: number;
461
497
  results: (PendingPriceCorrection & {
@@ -673,9 +709,16 @@ declare function detectGapEvacuationCandidates(masterGrid: Map<string, ManagedOr
673
709
  * @param {Map} streakMap - Mutable Map slotId -> consecutive-cycle count
674
710
  * @param {Array} candidates - detectGapEvacuationCandidates output
675
711
  * @param {number} [threshold] - GRID_LIMITS.GAP_EVACUATION_STREAK_THRESHOLD default
712
+ * @param {Object} [options] - `increment: false` re-derives the ledger (prune
713
+ * resolved ids + report readiness) WITHOUT counting a new observation. The
714
+ * committed-geometry sweep uses it because the plan ticks the same ledger in
715
+ * the same cycle; counting twice would arm the cancel-only teeth in the very
716
+ * cycle whose rotation is about to evacuate the order.
676
717
  * @returns {{streaks: Object, ready: Array}}
677
718
  */
678
- declare function updateGapEvacuationStreaks(streakMap: Map<string, number>, candidates: unknown, threshold?: number | null): {
719
+ declare function updateGapEvacuationStreaks(streakMap: Map<string, number>, candidates: unknown, threshold?: number | null, options?: {
720
+ increment?: boolean;
721
+ }): {
679
722
  streaks: Record<string, number>;
680
723
  ready: Array<{
681
724
  id: string;
@@ -752,6 +795,33 @@ declare function crossingCandidateChainId(o: CrossingCandidate | null | undefine
752
795
  * @returns {boolean} True when the candidate participates in crossing checks
753
796
  */
754
797
  declare function isCrossingCheckCandidate(o: CrossingCandidate | null | undefined, excludeChainOrderId?: string | null, cancelOpIndexByOrderId?: Map<string, unknown> | null): boolean;
798
+ /**
799
+ * LIVE (unexpired) pending-broadcast entries — the SINGLE liveness authority.
800
+ *
801
+ * A pending entry protects a slot/price whose uncertain CREATE may already be
802
+ * live on chain but is not adopted yet. Three readers need that set (the COW
803
+ * pre-broadcast guard, the reconcile CREATE path, and the reconcile surplus
804
+ * sweep) and they used to disagree: two re-implemented the TTL by hand with
805
+ * different rules and one read the raw map with no TTL at all, so a reconcile
806
+ * could stay blocked by an entry the COW guard already considered dead.
807
+ *
808
+ * Liveness rule (unchanged from the COW guard, now the only one):
809
+ * - younger than `PENDING_BROADCAST_TTL_MS` → live;
810
+ * - older than the TTL but a successful open-orders sync completed AFTER it was
811
+ * recorded → expired (a caught-up read re-verifies the level);
812
+ * - older than 2× the TTL → expired regardless (a permanently lagging node must
813
+ * not park CREATEs forever);
814
+ * - no usable `recordedAt` → live (fail closed, never a silent unblock).
815
+ *
816
+ * Expired entries are DELETED here; callers get the live list.
817
+ *
818
+ * @param {Object} manager - OrderManager (`_pendingBroadcasts`, `_lastSyncAt`)
819
+ * @param {Object} [options] - `now` clock override (tests)
820
+ * @returns {Array} Live pending-broadcast entries
821
+ */
822
+ declare function getLivePendingBroadcasts(manager: OrderManagerLike | null | undefined, options?: {
823
+ now?: number;
824
+ }): unknown[];
755
825
  /**
756
826
  * Shared candidate set for crossing-placement checks: master orders plus
757
827
  * chain-side orders that may exist on chain but are not (yet) adopted into
@@ -1561,7 +1631,7 @@ declare function collectKnownOnChainOrderIds(mgr: OrderManagerLike, placedResult
1561
1631
  createIds: string[];
1562
1632
  all: string[];
1563
1633
  };
1564
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, resolveExecutionPrice, resolveSlotIdForFillPrice, reviveVirtualSlotFromChain, attributeUnmatchedFillToGrid, 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 };
1634
+ 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 };
1565
1635
  export type { CrawlEntry };
1566
1636
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1567
1637
  //# sourceMappingURL=order.d.ts.map