dexbot 1.6.18 → 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 (146) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +117 -5
  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_dynamic_weight.js +2 -1
  9. package/dist/analysis/analyze_kalman.js +3 -2
  10. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  11. package/dist/analysis/analyze_liquidity.js +336 -0
  12. package/dist/analysis/analyze_regime.js +3 -2
  13. package/dist/analysis/analyze_regime_windows.js +3 -2
  14. package/dist/analysis/analyze_volatility.js +3 -2
  15. package/dist/analysis/bot_key_utils.d.ts +44 -1
  16. package/dist/analysis/bot_key_utils.js +76 -7
  17. package/dist/analysis/fills_cache.js +2 -1
  18. package/dist/analysis/grid_correction_check.d.ts +1 -19
  19. package/dist/analysis/grid_correction_check.js +12 -30
  20. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  21. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  22. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
  24. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
  26. package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
  27. package/dist/analysis/liquidity/liquidity_view.js +66 -0
  28. package/dist/analysis/resolve_bot_accounts.js +7 -6
  29. package/dist/analysis/trade_profitability.js +4 -2
  30. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  31. package/dist/credential-daemon.js +13 -2
  32. package/dist/dexbot.js +77 -172
  33. package/dist/modules/account_bots.d.ts +11 -1
  34. package/dist/modules/account_orders.d.ts +12 -0
  35. package/dist/modules/account_orders.js +30 -0
  36. package/dist/modules/asset_lookup.d.ts +25 -0
  37. package/dist/modules/asset_lookup.js +75 -0
  38. package/dist/modules/bitshares-native/transport.js +24 -6
  39. package/dist/modules/bitshares_client.d.ts +24 -6
  40. package/dist/modules/bitshares_client.js +44 -7
  41. package/dist/modules/bot_settings.d.ts +2 -0
  42. package/dist/modules/chain_scan.d.ts +64 -0
  43. package/dist/modules/chain_scan.js +80 -0
  44. package/dist/modules/cli_colors.d.ts +5 -0
  45. package/dist/modules/cli_colors.js +7 -0
  46. package/dist/modules/cli_progress.d.ts +51 -0
  47. package/dist/modules/cli_progress.js +113 -0
  48. package/dist/modules/constants.d.ts +26 -3
  49. package/dist/modules/constants.js +63 -8
  50. package/dist/modules/dexbot_class.d.ts +1 -6
  51. package/dist/modules/dexbot_class.js +14 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  53. package/dist/modules/dexbot_cow_runtime.js +634 -136
  54. package/dist/modules/dexbot_fill_runtime.js +132 -23
  55. package/dist/modules/dexbot_maintenance_runtime.js +242 -74
  56. package/dist/modules/dexbot_startup_runtime.js +32 -20
  57. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  58. package/dist/modules/dexbot_state_recovery.js +167 -5
  59. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  60. package/dist/modules/launcher/runtime_entry.js +36 -1
  61. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  62. package/dist/modules/liquidity_pool_ref.js +116 -0
  63. package/dist/modules/node_connect_policy.d.ts +8 -1
  64. package/dist/modules/node_connect_policy.js +18 -2
  65. package/dist/modules/node_flap_score.d.ts +87 -0
  66. package/dist/modules/node_flap_score.js +124 -0
  67. package/dist/modules/node_health_cache.d.ts +40 -3
  68. package/dist/modules/node_health_cache.js +66 -20
  69. package/dist/modules/node_manager.d.ts +101 -19
  70. package/dist/modules/node_manager.js +255 -65
  71. package/dist/modules/order/accounting.js +56 -7
  72. package/dist/modules/order/format.d.ts +24 -10
  73. package/dist/modules/order/format.js +30 -10
  74. package/dist/modules/order/grid.js +91 -13
  75. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  76. package/dist/modules/order/grid_reconcile.js +333 -189
  77. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  78. package/dist/modules/order/grid_reconcile_internal.js +298 -100
  79. package/dist/modules/order/index.d.ts +19 -1
  80. package/dist/modules/order/lifecycle.d.ts +353 -0
  81. package/dist/modules/order/lifecycle.js +1109 -0
  82. package/dist/modules/order/manager.d.ts +273 -5
  83. package/dist/modules/order/manager.js +654 -48
  84. package/dist/modules/order/placement_lock.d.ts +102 -0
  85. package/dist/modules/order/placement_lock.js +222 -0
  86. package/dist/modules/order/strategy.js +13 -1
  87. package/dist/modules/order/sync_engine.d.ts +33 -1
  88. package/dist/modules/order/sync_engine.js +241 -73
  89. package/dist/modules/order/utils/math.d.ts +39 -1
  90. package/dist/modules/order/utils/math.js +83 -1
  91. package/dist/modules/order/utils/order.d.ts +181 -5
  92. package/dist/modules/order/utils/order.js +455 -9
  93. package/dist/modules/order/utils/system.d.ts +81 -1
  94. package/dist/modules/order/utils/system.js +331 -44
  95. package/dist/modules/order/utils/validate.d.ts +7 -1
  96. package/dist/modules/order/utils/validate.js +80 -3
  97. package/dist/modules/outcome.d.ts +54 -0
  98. package/dist/modules/outcome.js +51 -0
  99. package/dist/modules/settings_merge.d.ts +4 -0
  100. package/dist/modules/settings_merge.js +9 -0
  101. package/dist/modules/timing_policy.d.ts +82 -0
  102. package/dist/modules/timing_policy.js +244 -0
  103. package/dist/modules/types.d.ts +137 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  105. package/dist/modules/utils/asset_symbols.js +21 -2
  106. package/dist/scripts/analysis_runner.d.ts +10 -0
  107. package/dist/scripts/analysis_runner.js +33 -0
  108. package/dist/scripts/analyze-credit.js +54 -17
  109. package/dist/scripts/analyze-orders.d.ts +4 -2
  110. package/dist/scripts/analyze-orders.js +115 -35
  111. package/dist/scripts/asset.d.ts +26 -0
  112. package/dist/scripts/asset.js +165 -0
  113. package/dist/scripts/bts_distribution.d.ts +1 -0
  114. package/dist/scripts/bts_distribution.js +194 -142
  115. package/dist/scripts/chart_command.d.ts +1 -1
  116. package/dist/scripts/chart_command.js +60 -86
  117. package/dist/scripts/chart_targets.d.ts +18 -0
  118. package/dist/scripts/chart_targets.js +48 -0
  119. package/dist/scripts/dw.js +1 -1
  120. package/dist/scripts/liquid.d.ts +24 -0
  121. package/dist/scripts/liquid.js +134 -0
  122. package/dist/scripts/rich_list.js +12 -16
  123. package/dist/scripts/test-credit-renewal.js +12 -5
  124. package/dist/scripts/token_distribution.d.ts +2 -0
  125. package/dist/scripts/token_distribution.js +132 -108
  126. package/dist/scripts/tv.js +1 -1
  127. package/dist/scripts/verify-browser-bundle.js +18 -0
  128. package/docs/COW_INVARIANTS.md +69 -10
  129. package/docs/DEXBOT_COMPARISON.md +6 -6
  130. package/docs/EVOLUTION.md +10 -8
  131. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  132. package/docs/GRID_PRICE_INVARIANT.md +5 -2
  133. package/docs/GRID_RECONCILE.md +36 -11
  134. package/docs/LOGGING.md +50 -4
  135. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
  136. package/docs/README.md +23 -2
  137. package/docs/WORKFLOW.md +12 -4
  138. package/docs/architecture.md +42 -5
  139. package/docs/developer_guide.md +25 -8
  140. package/modules/README.md +8 -1
  141. package/package.json +3 -1
  142. package/scripts/README.md +39 -7
  143. package/scripts/pdev.sh +14 -1
  144. package/scripts/pmain.sh +23 -8
  145. package/scripts/ptest.sh +7 -0
  146. package/tests/README.md +30 -1
@@ -121,6 +121,7 @@ import { sleep } from './system.js';
121
121
  import { getErrorMessage, getErrorCode, getErrorName } from '../../utils/errors.js';
122
122
  import { hasGenesisLadder } from '../genesis_policy.js';
123
123
  import { parseSlotIndex } from './slot.js';
124
+ import { pendingBroadcastTtlMs } from '../lifecycle.js';
124
125
  const { isValidNumber, toFiniteNumber } = Format;
125
126
  const { blockchainToFloat, floatToBlockchainInt, quantizeFloat, slotIndexForPrice, priceSlotEqual } = MathUtils;
126
127
  const orderLogger = new Logger('Order');
@@ -162,6 +163,28 @@ function isOrderGoneErrorMessage(message, orderId) {
162
163
  return true;
163
164
  return false;
164
165
  }
166
+ /**
167
+ * Classify a working-grid staleness reason as a STRUCTURAL rebuild.
168
+ *
169
+ * `_syncWorkingGridFromMasterMutation` stamps reasons such as
170
+ * `master mutation during broadcasting (grid-init)` (a full grid rebuild) or
171
+ * `(fill-place)` (a fill landing during the plan). The two are NOT
172
+ * interchangeable: after a rebuild the fresh master no longer carries the live
173
+ * chain order IDs, so re-planning from it emits CREATEs for price levels the
174
+ * startup reconcile is concurrently re-pricing via UPDATE — both generations
175
+ * land and the loser becomes a duplicate-price orphan backlog.
176
+ *
177
+ * Single source of truth for every planner/guard that must treat a rebuild
178
+ * differently from a fill. Keep the pattern anchored to the context tokens
179
+ * emitted by manager._syncWorkingGridFromMasterMutation / structural paths.
180
+ * @param {unknown} reason - evaluateCommit refusal reason or staleness label.
181
+ * @returns {boolean} True when the master was structurally rebuilt.
182
+ */
183
+ function isStructuralRebuildStaleReason(reason) {
184
+ if (typeof reason !== 'string' || reason.length === 0)
185
+ return false;
186
+ return /\bgrid-init\b|\brebuild\b|\bresync\b|\bregenerated grid\b|\bstructural rebuild\b/i.test(reason);
187
+ }
165
188
  // ---------------------------------------------------------------------------
166
189
  // Persistent duplicate-orphan detection escalation. A duplicate-price-level
167
190
  // orphan is expected self-healing (fully filled order leaves a sub-dust
@@ -243,8 +266,15 @@ function _filterUnmatchedChainOrders(manager, chainOrderId) {
243
266
  }
244
267
  /**
245
268
  * Record a fresh on-chain placement timestamp for surplus-cancel grace.
246
- * Called when a slot gains a chain orderId it did not have before (create,
247
- * adopt, rotation target). Powers isFreshlyPlacedOrder below.
269
+ * Powers isFreshlyPlacedOrder below.
270
+ *
271
+ * NOTE: in production the placement stamp is written by the lifecycle write
272
+ * funnel (`OrderManager._syncLifecycleFromMutation` -> `markPlaced`) for every
273
+ * mutation, including the COW whole-map commit. This helper remains for callers
274
+ * that hold only a manager-shaped object (tests, fixtures) and for the `_placedAt`
275
+ * retention bound; it writes through the same facade, so there is still one copy
276
+ * of the stamp.
277
+ *
248
278
  * @param {unknown} manager - OrderManager instance (owns `_placedAt`)
249
279
  * @param {string} chainOrderId - Chain order id that was just placed
250
280
  */
@@ -252,6 +282,8 @@ function recordOrderPlacement(manager, chainOrderId) {
252
282
  try {
253
283
  if (!manager || chainOrderId == null || String(chainOrderId).length === 0)
254
284
  return;
285
+ // Writing through the facade records `placedAt` on the lifecycle record
286
+ // (one clock, one owner) — no separate grace bookkeeping to keep in sync.
255
287
  if (!(manager._placedAt instanceof Map))
256
288
  manager._placedAt = new Map();
257
289
  manager._placedAt.set(String(chainOrderId), Date.now());
@@ -280,6 +312,11 @@ function isFreshlyPlacedOrder(manager, chainOrderId, graceMs) {
280
312
  try {
281
313
  if (chainOrderId == null || String(chainOrderId).length === 0)
282
314
  return false;
315
+ // Single definition of the grace window lives on the lifecycle view.
316
+ const lifecycle = manager?.getLifecycle;
317
+ if (typeof lifecycle === 'function') {
318
+ return lifecycle.call(manager, String(chainOrderId)).isFreshlyPlaced(graceMs);
319
+ }
283
320
  const placedAt = manager?._placedAt instanceof Map
284
321
  ? manager._placedAt.get(String(chainOrderId))
285
322
  : null;
@@ -326,6 +363,303 @@ function _stampCorrectionProvenance(entry, source) {
326
363
  }
327
364
  return entry;
328
365
  }
366
+ /**
367
+ * Resolve the EXECUTION price of a fill from its paid/received raw amounts
368
+ * (quote per base). This is the fill FACT the LAST-FILL-GUARD pivot and the
369
+ * boundary re-anchor need — the slot price is only a grid identity and may be
370
+ * stale after a refused-commit chain adoption or an off-ladder maker fill.
371
+ *
372
+ * Returns null when either side of the amounts is missing/unusable, so callers
373
+ * can fall back (a fill we cannot price must not move the pivot).
374
+ *
375
+ * @param {Object} assets - {assetA (base), assetB (quote)} with precisions
376
+ * @param {string|null} paysAssetId - Asset the account paid
377
+ * @param {number} paysAmountRaw - Raw (integer) amount paid
378
+ * @param {string|null} receivesAssetId - Asset the account received
379
+ * @param {number} receivesAmountRaw - Raw (integer) amount received
380
+ * @returns {number|null} Quote-per-base price, or null when unresolvable
381
+ */
382
+ function resolveExecutionPrice(assets, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw) {
383
+ if (!assets?.assetA || !assets?.assetB)
384
+ return null;
385
+ const pays = Number(paysAmountRaw);
386
+ const receives = Number(receivesAmountRaw);
387
+ if (!Number.isFinite(pays) || pays <= 0)
388
+ return null;
389
+ if (!Number.isFinite(receives) || receives <= 0)
390
+ return null;
391
+ const A = assets.assetA;
392
+ const B = assets.assetB;
393
+ let baseRaw = null;
394
+ let quoteRaw = null;
395
+ if (paysAssetId === A.id && receivesAssetId === B.id) {
396
+ baseRaw = pays;
397
+ quoteRaw = receives;
398
+ }
399
+ else if (paysAssetId === B.id && receivesAssetId === A.id) {
400
+ baseRaw = receives;
401
+ quoteRaw = pays;
402
+ }
403
+ if (baseRaw === null || quoteRaw === null)
404
+ return null;
405
+ const base = MathUtils.blockchainToFloat(baseRaw, A.precision);
406
+ const quote = MathUtils.blockchainToFloat(quoteRaw, B.precision);
407
+ if (!(base > 0) || !(quote > 0))
408
+ return null;
409
+ const price = quote / base;
410
+ return Number.isFinite(price) && price > 0 ? price : null;
411
+ }
412
+ /**
413
+ * Resolve the grid SLOT a fill belongs to when its chain order id no longer
414
+ * identifies one.
415
+ *
416
+ * Every virtualisation path (`virtualizeOrder` -> `convertToSpreadPlaceholder`
417
+ * / `toRailHolePlaceholder`) NULLS `orderId`, so after a phantom cleanup or a
418
+ * refused-commit adoption the master holds no slot keyed by the filled order:
419
+ * the id lookup misses exactly when the fill matters most. The genesis ladder
420
+ * is the authority for "which slot does this price belong to" (same rule pass 2
421
+ * uses for adoption), so the fill's own execution price identifies the level.
422
+ *
423
+ * Returns null for a price outside the frozen rail: a shelf/manual order or an
424
+ * off-ladder wick must never be mapped onto an edge slot (that would arm the
425
+ * pivot with a price the grid never traded at).
426
+ *
427
+ * @param {Object} manager - OrderManager instance (genesis ladder + assets)
428
+ * @param {number} price - Fill execution price
429
+ * @param {Object} [hints] - Optional {size, type} of the fill for edge-dust tolerance
430
+ * @returns {string|null} `slot-N` id, or null when unresolvable/out-of-grid
431
+ */
432
+ function resolveSlotIdForFillPrice(manager, price, hints = {}) {
433
+ try {
434
+ const genesis = manager._genesis;
435
+ if (!hasGenesisLadder(genesis) || !Number.isFinite(price))
436
+ return null;
437
+ const ladder = genesis;
438
+ if (MathUtils.isChainPriceOutOfGrid(price, ladder, Number(hints.size) || 0, hints.type === ORDER_TYPES.BUY || hints.type === ORDER_TYPES.SELL ? hints.type : null, manager?.assets ?? null))
439
+ return null;
440
+ const idx = MathUtils.slotIndexForPrice(price, ladder);
441
+ if (!Number.isFinite(idx) || idx < 0)
442
+ return null;
443
+ const levels = ladder.priceLevels;
444
+ if (Array.isArray(levels) && levels.length > 0 && idx >= levels.length)
445
+ return null;
446
+ return `slot-${idx}`;
447
+ }
448
+ catch {
449
+ return null;
450
+ }
451
+ }
452
+ /**
453
+ * REVIVE a virtualised slot whose chain order is still LIVE on chain.
454
+ *
455
+ * The state hole this closes: a slot can be virtualised (phantom cleanup on a
456
+ * truncated read, refused-commit adoption, rotation cleanup) while its order
457
+ * still rests on the chain. In that state the slot is invisible to window
458
+ * accounting (`_countActiveOnGrid` needs ACTIVE/PARTIAL) but its order is still
459
+ * counted in `chainCount`, so the reconcile reads a shortfall it can never
460
+ * repair — and the planner sees a free level, which is how a second order can be
461
+ * created at a price that already holds one.
462
+ *
463
+ * The revive is broadcast-free (master-only): the order is already on chain, so
464
+ * this only re-materialises the slot at its chain size/state. It refuses when
465
+ * the chain order does NOT rest at this slot's level: the slot then merely
466
+ * aliases the id (a rotation source whose cancel has not landed, a re-slotted
467
+ * order) and reviving it would resurrect a level the planner emptied on purpose.
468
+ *
469
+ * @param {Object} manager - OrderManager instance
470
+ * @param {Object} slot - Master slot (must NOT be placed)
471
+ * @param {Object} chainOrder - Parsed chain order (price/size/type/orderId)
472
+ * @param {unknown} rawOnChain - Raw chain object for the slot snapshot
473
+ * @param {string} context - Update context tag for logging/accounting
474
+ * @param {Object} [options] - {skipAccounting}
475
+ * @returns {Promise<Object|null>} The revived slot when applied, else null
476
+ */
477
+ async function reviveVirtualSlotFromChain(manager, slot, chainOrder, rawOnChain, context, options = {}) {
478
+ try {
479
+ if (!manager || !slot || !slot.id || !chainOrder)
480
+ return null;
481
+ // Only a NON-placed slot can be revived; a placed one is already live.
482
+ if (isOrderPlaced(slot))
483
+ return null;
484
+ const chainId = chainOrder.orderId ?? slot.orderId ?? null;
485
+ if (!chainId)
486
+ return null;
487
+ if (slot.orderId && String(slot.orderId) !== String(chainId))
488
+ return null;
489
+ const type = chainOrder.type;
490
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
491
+ return null;
492
+ const chainPrice = Number(chainOrder.price);
493
+ const chainSize = Number(chainOrder.size);
494
+ if (!Number.isFinite(chainPrice) || chainPrice <= 0)
495
+ return null;
496
+ if (!Number.isFinite(chainSize) || chainSize <= 0)
497
+ return null;
498
+ if (!MathUtils.sameGridLevel(chainPrice, Number(slot.price), manager._genesis))
499
+ return null;
500
+ const booked = toFiniteNumber(slot.size, 0);
501
+ const state = booked > chainSize ? ORDER_STATES.PARTIAL : ORDER_STATES.ACTIVE;
502
+ const { createUncertain: _staleMarker, ...rest } = slot;
503
+ const revived = {
504
+ ...rest,
505
+ type,
506
+ state,
507
+ size: chainSize,
508
+ orderId: String(chainId),
509
+ rawOnChain: (rawOnChain && typeof rawOnChain === 'object'
510
+ ? { ...rawOnChain, fetchedAt: Date.now() }
511
+ : (slot.rawOnChain ?? null)),
512
+ };
513
+ const applied = await manager._applyOrderUpdate(revived, context, {
514
+ skipAccounting: options.skipAccounting === true,
515
+ fee: 0
516
+ });
517
+ if (applied === false) {
518
+ manager.logger?.log?.(`[SYNC] Revive of virtualised slot ${slot.id} rejected — slot keeps its VIRTUAL state`, 'warn');
519
+ return null;
520
+ }
521
+ manager.logger?.log?.(`[SYNC] Revived virtualised slot ${slot.id}: its chain order ${chainId} is still live ` +
522
+ `(${type} @ ${Format.formatPrice6(chainPrice)}, size ${chainSize}) while the slot was ` +
523
+ `${ORDER_STATES.VIRTUAL} — re-materialised in place (no broadcast), so window accounting ` +
524
+ `counts it again`, 'warn');
525
+ return revived;
526
+ }
527
+ catch {
528
+ return null;
529
+ }
530
+ }
531
+ /**
532
+ * ATTRIBUTE a fill to the grid when its chain order id identifies no live slot
533
+ * ("order not found in active grid").
534
+ *
535
+ * The failure this closes (live incident): a 120s stale broadcast region
536
+ * deferred the fill queue, a phantom cleanup then virtualised the filled slots
537
+ * (which NULLS their `orderId`), and the re-delivered fills were dropped AFTER
538
+ * their accounting had been booked. Neither the LAST-FILL-GUARD pivot nor the
539
+ * owed boundary crawl learned the execution price, so the pivot stayed on a
540
+ * stale, HIGHER value and the direction rule then allowed re-buys ABOVE the
541
+ * market (9 buy-lower violations, 23.5% of the window's BTS).
542
+ *
543
+ * Two identities, in order:
544
+ * 1. the slot that still owns the chain order id (any state — a virtualised
545
+ * slot can keep its id), or
546
+ * 2. the genesis ladder level the fill's own execution price maps to (the
547
+ * common case, because virtualisation clears the id).
548
+ *
549
+ * Only what the fill PROVES is recorded: the pivot, and — when the resolved
550
+ * slot is a hole — an owed boundary crawl. The slot and the already-booked
551
+ * accounting are never touched: the funds are the accountant's business, this
552
+ * only keeps the geometry honest. A price outside the frozen rail is refused,
553
+ * so a shelf/manual order can never arm the pivot at a level the grid does not
554
+ * trade.
555
+ *
556
+ * @param {Object} manager - OrderManager instance
557
+ * @param {Object} params - fill identity {orderId, pays/receives amount+asset, isPartial}
558
+ * @returns {boolean} true when the fill was attributed to the grid
559
+ */
560
+ function attributeUnmatchedFillToGrid(manager, params) {
561
+ const mgr = manager;
562
+ if (!mgr || !(mgr.orders instanceof Map))
563
+ return false;
564
+ const input = params ?? {};
565
+ const assets = mgr.assets;
566
+ if (!assets?.assetA || !assets?.assetB)
567
+ return false;
568
+ // Identity 1: the slot that still owns this chain order id, in ANY state.
569
+ const chainOrderId = input.orderId != null && String(input.orderId).length > 0 ? String(input.orderId) : null;
570
+ let slot = null;
571
+ if (chainOrderId) {
572
+ for (const candidate of mgr.orders.values()) {
573
+ if (candidate && String(candidate.orderId ?? '') === chainOrderId) {
574
+ slot = candidate;
575
+ break;
576
+ }
577
+ }
578
+ }
579
+ // Side from the asset that was PAID: paying the quote (assetB) buys the
580
+ // base, paying the base sells it. Independent of any slot type. When the
581
+ // fill event carries no pays asset (malformed/degraded), fall back to the
582
+ // matched slot's rail type — the side must never be guessed from the price.
583
+ let type = null;
584
+ if (input.paysAssetId === assets.assetB.id)
585
+ type = ORDER_TYPES.BUY;
586
+ else if (input.paysAssetId === assets.assetA.id)
587
+ type = ORDER_TYPES.SELL;
588
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL && slot
589
+ && (slot.type === ORDER_TYPES.BUY || slot.type === ORDER_TYPES.SELL)) {
590
+ type = slot.type;
591
+ }
592
+ if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
593
+ return false;
594
+ const execPrice = resolveExecutionPrice(assets, input.paysAssetId, input.paysAmountRaw, input.receivesAssetId, input.receivesAmountRaw);
595
+ let identity = slot && slot.id ? 'chain-id' : null;
596
+ let slotId = slot && slot.id ? String(slot.id) : null;
597
+ let price = execPrice;
598
+ if (identity === 'chain-id' && (price == null || !(price > 0))) {
599
+ // Unpriced fill on a known slot: its stored level is the best evidence.
600
+ const slotPrice = Number(slot?.price);
601
+ price = Number.isFinite(slotPrice) && slotPrice > 0 ? slotPrice : null;
602
+ }
603
+ // Identity 2: the ladder level the execution price maps to. Only for a
604
+ // price that is genuinely inside the frozen rail (never a shelf order).
605
+ if (identity == null) {
606
+ if (price == null || !(price > 0))
607
+ return false;
608
+ const derived = resolveSlotIdForFillPrice(mgr, price, { type });
609
+ if (!derived)
610
+ return false;
611
+ identity = 'ladder';
612
+ slotId = derived;
613
+ slot = mgr.orders.get(derived) ?? null;
614
+ }
615
+ if (price == null || !Number.isFinite(price) || price <= 0)
616
+ return false;
617
+ if (!slotId)
618
+ return false;
619
+ // 1. Pivot: the LAST-FILL-GUARD reference must track the real trade.
620
+ // recordLastFilledPrices owns the scalar family + the edge-pinned
621
+ // exclusion (a wick on an edge order must not arm it).
622
+ let pivotRecorded = false;
623
+ try {
624
+ mgr.recordLastFilledPrices?.([{ id: slotId, type, price, isPartial: input.isPartial === true }]);
625
+ // Honest reporting: the writer deliberately SKIPS edge-pinned fills (a
626
+ // wick on the static floor/ceiling must not arm the pivot), so "did the
627
+ // pivot move to this price" is the only truthful signal.
628
+ pivotRecorded = Number(mgr._lastFilledPrice) === price;
629
+ }
630
+ catch (err) {
631
+ mgr.logger?.log?.(`[SYNC] Fill-pivot record failed for unattributed fill ${chainOrderId ?? 'unknown'}: ${getErrorMessage(err)}`, 'warn');
632
+ }
633
+ // 2. Owed crawl: the same ledger the strategy maintains, and only for a
634
+ // slot that is actually a HOLE the grid owns — a crawl is owed because
635
+ // the level must be re-placed, which cannot happen while an order still
636
+ // occupies it (and cannot be consumed for a slot that does not exist).
637
+ // Same eligibility as strategy.processFillsOnly: the edge classification
638
+ // that decides whether a crawl is APPLIED lives in the boundary
639
+ // derivation. Re-delivery replaces, never stacks; dry runs never commit a
640
+ // boundary, so they must not grow the ledger.
641
+ const slotIsHole = !!slot && !isOrderPlaced(slot);
642
+ try {
643
+ if (slotIsHole && mgr.config?.dryRun !== true && Array.isArray(mgr._pendingFillCrawls)) {
644
+ const pending = mgr._pendingFillCrawls;
645
+ const at = pending.findIndex((e) => e && e.slotId === slotId);
646
+ if (at >= 0)
647
+ pending.splice(at, 1);
648
+ pending.push({ slotId, side: type, ts: Date.now() });
649
+ while (pending.length > 500)
650
+ pending.shift();
651
+ if (typeof mgr._markGridDirty === 'function')
652
+ mgr._markGridDirty();
653
+ }
654
+ }
655
+ catch { /* best-effort: the pivot above is the fail-safe */ }
656
+ mgr.logger?.log?.(`[SYNC] Fill for order ${chainOrderId ?? 'unknown'} attributed to ${slotId} via ${identity} ` +
657
+ `(${type} @ ${Format.formatPrice6(price)}): ` +
658
+ `${pivotRecorded ? 'pivot recorded' : 'pivot NOT armed (edge-pinned fill or no writer)'}` +
659
+ `${slotIsHole ? ' + owed boundary crawl' : ' (slot still holds a live order: no crawl)'}` +
660
+ `; accounting already booked`, 'warn');
661
+ return true;
662
+ }
329
663
  /**
330
664
  * Find the live grid slot that currently owns a chain order.
331
665
  * When slotId is supplied, only that exact slot is considered; otherwise all
@@ -993,13 +1327,56 @@ function resolveCorrectionWarnRateLimitMs(manager) {
993
1327
  * Cancel-type corrections (duplicate orphans, surplus) are batched into
994
1328
  * chunked multi-op transactions; price updates run sequentially.
995
1329
  *
1330
+ * Runs inside the exclusive placement region: every correction broadcasts a
1331
+ * chain mutation, so it must never interleave with a COW batch, startup
1332
+ * reconcile Phase 2 or a dust/residual cancel. A caller already holding the
1333
+ * region (COW pre-batch drain) passes its lease so the nested call does not
1334
+ * deadlock.
1335
+ *
996
1336
  * @param {Object} manager - OrderManager instance
997
1337
  * @param {string} accountName - Account name for blockchain transactions
998
1338
  * @param {string} privateKey - Private key for signing
999
1339
  * @param {Object} accountOrders - AccountOrders accessor for blockchain ops
1340
+ * @param {Object} [options] - placementLease (reuse) + timeoutMs (bounded wait)
1000
1341
  * @returns {Promise<Object>} Summary {corrected, failed, results}
1001
1342
  */
1002
- async function correctAllPriceMismatches(manager, accountName, privateKey, accountOrders) {
1343
+ async function correctAllPriceMismatches(manager, accountName, privateKey, accountOrders, options = {}) {
1344
+ if (!manager || !manager._gridLock)
1345
+ return { corrected: 0, failed: 0, results: [] };
1346
+ const run = () => _correctAllPriceMismatchesLocked(manager, accountName, privateKey, accountOrders);
1347
+ // NESTED CALLER (COW pre-batch drain): the caller already owns the region.
1348
+ // Reuse the inherited lease only while it STILL owns it — `isPlacementActive()`
1349
+ // would also be true for a different holder (e.g. the watchdog force-released
1350
+ // this lease and another path took the region), which would run the drain
1351
+ // unprotected and re-open the duplicate window.
1352
+ if (options.placementLease) {
1353
+ const inherited = options.placementLease;
1354
+ const stillCurrent = typeof manager.isPlacementLeaseCurrent === 'function'
1355
+ ? manager.isPlacementLeaseCurrent(inherited)
1356
+ : true;
1357
+ if (stillCurrent)
1358
+ return await run();
1359
+ }
1360
+ const timeoutMs = Math.max(1, Number.isFinite(Number(options.timeoutMs)) ? Number(options.timeoutMs) : 5000);
1361
+ const deferredResult = { corrected: 0, failed: 0, results: [], staleDropped: 0, deferred: true, reason: 'placement-active' };
1362
+ // Single acquire/release contract (placement_lock.withPlacement).
1363
+ if (typeof manager.withPlacement === 'function') {
1364
+ const placed = await manager.withPlacement('correction-drain', async () => run(), { timeoutMs });
1365
+ return placed ?? deferredResult;
1366
+ }
1367
+ if (typeof manager.acquirePlacement !== 'function')
1368
+ return await run();
1369
+ const lease = await manager.acquirePlacement('correction-drain', { timeoutMs });
1370
+ if (!lease)
1371
+ return deferredResult;
1372
+ try {
1373
+ return await run();
1374
+ }
1375
+ finally {
1376
+ lease.release();
1377
+ }
1378
+ }
1379
+ async function _correctAllPriceMismatchesLocked(manager, accountName, privateKey, accountOrders) {
1003
1380
  if (!manager || !manager._gridLock)
1004
1381
  return { corrected: 0, failed: 0, results: [] };
1005
1382
  // 6b: backlog alarm (rate-limited). Emitted even when the drain defers
@@ -1464,9 +1841,15 @@ function detectGapEvacuationCandidates(masterGrid, boundaryIdx, gapSlots, option
1464
1841
  * @param {Map} streakMap - Mutable Map slotId -> consecutive-cycle count
1465
1842
  * @param {Array} candidates - detectGapEvacuationCandidates output
1466
1843
  * @param {number} [threshold] - GRID_LIMITS.GAP_EVACUATION_STREAK_THRESHOLD default
1844
+ * @param {Object} [options] - `increment: false` re-derives the ledger (prune
1845
+ * resolved ids + report readiness) WITHOUT counting a new observation. The
1846
+ * committed-geometry sweep uses it because the plan ticks the same ledger in
1847
+ * the same cycle; counting twice would arm the cancel-only teeth in the very
1848
+ * cycle whose rotation is about to evacuate the order.
1467
1849
  * @returns {{streaks: Object, ready: Array}}
1468
1850
  */
1469
- function updateGapEvacuationStreaks(streakMap, candidates, threshold = null) {
1851
+ function updateGapEvacuationStreaks(streakMap, candidates, threshold = null, options = {}) {
1852
+ const increment = options?.increment !== false;
1470
1853
  const thrRaw = threshold !== null && threshold !== undefined ? Number(threshold) : Number(GRID_LIMITS?.GAP_EVACUATION_STREAK_THRESHOLD);
1471
1854
  const thr = Number.isFinite(thrRaw) && thrRaw > 0 ? Math.floor(thrRaw) : 2;
1472
1855
  const seen = new Set();
@@ -1476,7 +1859,7 @@ function updateGapEvacuationStreaks(streakMap, candidates, threshold = null) {
1476
1859
  continue;
1477
1860
  seen.add(c.id);
1478
1861
  if (streakMap instanceof Map) {
1479
- streakMap.set(c.id, Number(streakMap.get(c.id) || 0) + 1);
1862
+ streakMap.set(c.id, increment ? Number(streakMap.get(c.id) || 0) + 1 : Number(streakMap.get(c.id) || 0));
1480
1863
  }
1481
1864
  }
1482
1865
  if (streakMap instanceof Map) {
@@ -1644,6 +2027,68 @@ function isCrossingCheckCandidate(o, excludeChainOrderId = null, cancelOpIndexBy
1644
2027
  return false;
1645
2028
  return true;
1646
2029
  }
2030
+ /**
2031
+ * LIVE (unexpired) pending-broadcast entries — the SINGLE liveness authority.
2032
+ *
2033
+ * A pending entry protects a slot/price whose uncertain CREATE may already be
2034
+ * live on chain but is not adopted yet. Three readers need that set (the COW
2035
+ * pre-broadcast guard, the reconcile CREATE path, and the reconcile surplus
2036
+ * sweep) and they used to disagree: two re-implemented the TTL by hand with
2037
+ * different rules and one read the raw map with no TTL at all, so a reconcile
2038
+ * could stay blocked by an entry the COW guard already considered dead.
2039
+ *
2040
+ * Liveness rule (unchanged from the COW guard, now the only one):
2041
+ * - younger than `PENDING_BROADCAST_TTL_MS` → live;
2042
+ * - older than the TTL but a successful open-orders sync completed AFTER it was
2043
+ * recorded → expired (a caught-up read re-verifies the level);
2044
+ * - older than 2× the TTL → expired regardless (a permanently lagging node must
2045
+ * not park CREATEs forever);
2046
+ * - no usable `recordedAt` → live (fail closed, never a silent unblock).
2047
+ *
2048
+ * Expired entries are DELETED here; callers get the live list.
2049
+ *
2050
+ * @param {Object} manager - OrderManager (`_pendingBroadcasts`, `_lastSyncAt`)
2051
+ * @param {Object} [options] - `now` clock override (tests)
2052
+ * @returns {Array} Live pending-broadcast entries
2053
+ */
2054
+ function getLivePendingBroadcasts(manager, options = {}) {
2055
+ const map = manager?._pendingBroadcasts;
2056
+ if (!(map instanceof Map))
2057
+ return [];
2058
+ // Single definition of the TTL and its fixture fallback (lifecycle.ts).
2059
+ const ttl = pendingBroadcastTtlMs();
2060
+ const now = Number.isFinite(Number(options?.now)) ? Number(options.now) : Date.now();
2061
+ const lastSyncAt = Number(manager?._lastSyncAt) || 0;
2062
+ const log = manager?.logger?.log;
2063
+ for (const [fingerprint, rawEntry] of map) {
2064
+ const entry = rawEntry;
2065
+ const recordedAt = Number(entry?.recordedAt) || 0;
2066
+ if (!(recordedAt > 0))
2067
+ continue;
2068
+ const age = now - recordedAt;
2069
+ if (age <= ttl)
2070
+ continue;
2071
+ const syncedSinceRecord = lastSyncAt > recordedAt;
2072
+ if (!syncedSinceRecord && age <= ttl * 2) {
2073
+ log?.(`[COW] Pending-broadcast entry ${String(fingerprint)} is ${Math.round(age / 1000)}s old but no sync has completed since it was recorded; keeping it (fail-closed) until a caught-up read`, 'debug');
2074
+ continue;
2075
+ }
2076
+ map.delete(fingerprint);
2077
+ // Abandoned, not resolved: the order may be live. Route through the
2078
+ // lifecycle so the slot records `unknown` instead of becoming a clean
2079
+ // hole the next cycle re-CREATEs.
2080
+ try {
2081
+ const expire = manager
2082
+ ?._expirePendingBroadcast;
2083
+ if (typeof expire === 'function')
2084
+ expire.call(manager, String(fingerprint), entry);
2085
+ }
2086
+ catch { /* bookkeeping only */ }
2087
+ log?.(`[COW] Dropped expired pending-broadcast entry ${String(fingerprint)} (slot ${entry?.slotId ?? '?'}, age ${Math.round(age / 1000)}s, ` +
2088
+ `${syncedSinceRecord ? 'sync completed since record' : 'hard TTL cap'})`, 'warn');
2089
+ }
2090
+ return Array.from(map.values());
2091
+ }
1647
2092
  /**
1648
2093
  * Shared candidate set for crossing-placement checks: master orders plus
1649
2094
  * chain-side orders that may exist on chain but are not (yet) adopted into
@@ -1679,9 +2124,10 @@ function buildCrossingCheckCandidates(manager) {
1679
2124
  ? [...manager.orders.values()].map(withLivePrice)
1680
2125
  : [];
1681
2126
  if (manager._pendingBroadcasts instanceof Map) {
1682
- for (const entry of manager._pendingBroadcasts.values()) {
1683
- if (entry && entry.slotId && entry.order)
1684
- candidates.push(withLivePrice(entry));
2127
+ for (const entry of getLivePendingBroadcasts(manager)) {
2128
+ const wrapper = entry;
2129
+ if (wrapper && wrapper.slotId && wrapper.order)
2130
+ candidates.push(withLivePrice(wrapper));
1685
2131
  }
1686
2132
  }
1687
2133
  if (Array.isArray(manager._lastUnmatchedChainOrders)) {
@@ -3511,6 +3957,6 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3511
3957
  const all = new Set([...masterIds, ...createIds]);
3512
3958
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3513
3959
  }
3514
- export { parseChainOrder, resolveLiveOrderLadderPosition, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveEdgeCount, resolveEdgeOrders, selectEdgeSlots, getCoreOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, collectEdgePinnedFillIds, edgeOrderIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3960
+ 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 };
3515
3961
  export { resolveEdgeAnchorPrice, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3516
3962
  //# sourceMappingURL=order.js.map
@@ -551,10 +551,15 @@ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike,
551
551
  * so this fallback covers only the window before that write, not the whole
552
552
  * post-rebuild lifetime.
553
553
  *
554
+ * LIFETIME: a fill reference older than GRID_LIMITS.LAST_FILL_PIVOT_TTL_MS is
555
+ * ignored (read-time expiry, same bound the restore path applies), so a stale
556
+ * pivot cannot veto one side forever in a long-lived process. Unknown ages
557
+ * (missing timestamp) never expire.
558
+ *
554
559
  * @param {Object} manager - OrderManager instance
555
560
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
556
561
  */
557
- export declare function resolveLastFillGuardReference(manager: OrderManagerLike): {
562
+ export declare function resolveLastFillGuardReference(manager: OrderManagerLike | null | undefined): {
558
563
  price: number | null;
559
564
  type: string | null;
560
565
  };
@@ -592,6 +597,71 @@ export declare function isLastFillGuardBlocked(price: number, type: unknown, las
592
597
  pivot: number | null;
593
598
  threshold?: number | null;
594
599
  };
600
+ /**
601
+ * LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
602
+ *
603
+ * Wraps isLastFillGuardBlocked with the same pivot resolution the runtime uses
604
+ * (live fill pivot, then the bot-scoped market-fill row) and adds the
605
+ * SAME-LEVEL refusal: a placement within half a grid step of the pivot is a
606
+ * re-place at the level that just traded, which the raw `>=`/`<=` comparison
607
+ * lets through because a slot price and its execution price differ by
608
+ * rounding (live: slot 1310.046339 filled at 1310.060435).
609
+ *
610
+ * Unlike the COW-path guard this is meant for the reconcile/startup placement
611
+ * paths (create + relocation), which previously had no last-fill check at all:
612
+ * a startup-style top-up could therefore re-create a BUY at the price the bot
613
+ * had just bought at, or place a BUY above it (the "buying later at higher
614
+ * prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
615
+ * still builds.
616
+ *
617
+ * @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
618
+ * @param {number} price - Target placement price
619
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
620
+ * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
621
+ */
622
+ export declare function isLastFillPlacementBlocked(manager: OrderManagerLike | null | undefined, price: unknown, type: unknown): {
623
+ blocked: boolean;
624
+ pivot: number | null;
625
+ reason?: 'direction' | 'same-level';
626
+ };
627
+ /**
628
+ * Are fills still UNSETTLED (arrived but not yet absorbed by the grid)?
629
+ *
630
+ * While this returns true the master grid still holds filled slots as ACTIVE
631
+ * and the boundary has not crawled for them, so any geometry-derived plan
632
+ * (window top-up, startup-style reconcile) is built on the PREVIOUS book. The
633
+ * live incident: a 120s stale broadcast region deferred 12 fills, the
634
+ * post-fill reconcile saw "buy 12/20" on that stale master and re-created 8
635
+ * BUYs at the TOP of the un-crawled rail (1282.78 -> 1310.04), which filled
636
+ * within seconds (9 buy-lower violations, 23.5% of the window's BTS).
637
+ *
638
+ * Accepts a bot (its `manager` is inspected) or a bare manager.
639
+ *
640
+ * @param {Object} source - DEXBot-like or OrderManager-like instance
641
+ * @returns {{unsettled: boolean, reason: string|null}}
642
+ */
643
+ export declare function hasUnsettledFills(source: unknown): {
644
+ unsettled: boolean;
645
+ reason: string | null;
646
+ };
647
+ /**
648
+ * Age of the most recent bot-level pipeline raise.
649
+ *
650
+ * The two counters (`_batchInFlight`, `_recoverySyncInFlight`) each carry a
651
+ * `*StartedAt` stamp maintained by their raise site; a nested raise (a COW
652
+ * re-plan, a second recovery frame) refreshes it, so this reports how long ago
653
+ * the pipeline LAST showed activity, not how long the oldest frame has been
654
+ * open. That is the question a stale-region watchdog needs: a recent raise is
655
+ * evidence of progress. Lives here (next to
656
+ * `hasUnsettledFills`, the same bot/manager field-peeking contract) so the
657
+ * maintenance tick and the fill consumer cannot disagree about it.
658
+ *
659
+ * @param {Object} source - DEXBot-like (or OrderManager-like) instance
660
+ * @param {number} [nowMs] - Clock override (tests)
661
+ * @returns {number} Milliseconds since the most recent raise, 0 when nothing
662
+ * is in flight or the stamp is missing
663
+ */
664
+ export declare function getPipelineInFlightAgeMs(source: unknown, nowMs?: number): number;
595
665
  /**
596
666
  * Restore the persisted bot-scoped last-market-fill reference into the
597
667
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -625,6 +695,16 @@ export declare function restoreLastMarketFill(manager: OrderManagerLike, persist
625
695
  * rewritten: an off-new-ladder value is handled by the same one-increment
626
696
  * `resolveOnGridPivot` rule every other probe uses.
627
697
  *
698
+ * The timestamp comes from the SAME row as the price (see
699
+ * resolveFillProvenancedRow). Reading `_lastFilledAt` unconditionally paired a
700
+ * market-row price with a book-seed clock: a book seed writes `_lastFilledAt`
701
+ * but never the market row, and `setLastFillPivot(..., 'fill')` then re-stamps
702
+ * `_lastMarketFillAt` with that newer time — refreshing the 24h lifetime on
703
+ * every rebuild until the row never expires.
704
+ *
705
+ * EXPIRED ROWS DO NOT RE-ARM (resolveFillProvenancedRow drops them), so the
706
+ * documented pivot lifetime holds with or without a restart.
707
+ *
628
708
  * @param {Object} manager - OrderManager instance
629
709
  * @returns {boolean} True when a pivot was re-armed
630
710
  */