dexbot 1.7.2 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +6 -0
  11. package/dist/modules/bot_defaults.js +6 -1
  12. package/dist/modules/constants.d.ts +12 -0
  13. package/dist/modules/constants.js +66 -0
  14. package/dist/modules/dexbot_class.d.ts +17 -0
  15. package/dist/modules/dexbot_class.js +56 -1
  16. package/dist/modules/dexbot_cow_runtime.js +231 -19
  17. package/dist/modules/dexbot_maintenance_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_maintenance_runtime.js +164 -11
  19. package/dist/modules/dexbot_state_recovery.js +15 -1
  20. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  21. package/dist/modules/launcher/instance_lock.js +131 -0
  22. package/dist/modules/order/grid.d.ts +19 -0
  23. package/dist/modules/order/grid.js +40 -14
  24. package/dist/modules/order/index.d.ts +15 -1
  25. package/dist/modules/order/manager.d.ts +21 -0
  26. package/dist/modules/order/manager.js +119 -12
  27. package/dist/modules/order/placement_lock.d.ts +30 -0
  28. package/dist/modules/order/placement_lock.js +48 -0
  29. package/dist/modules/order/utils/order.d.ts +39 -1
  30. package/dist/modules/order/utils/order.js +73 -2
  31. package/dist/modules/order/utils/system.d.ts +112 -3
  32. package/dist/modules/order/utils/system.js +368 -6
  33. package/dist/modules/paths.d.ts +1 -0
  34. package/dist/modules/paths.js +1 -0
  35. package/dist/modules/timing_policy.js +2 -0
  36. package/dist/modules/types.d.ts +27 -0
  37. package/dist/pm2.js +126 -0
  38. package/dist/unlock.js +26 -1
  39. package/docs/DEXBOT_COMPARISON.md +5 -5
  40. package/docs/EVOLUTION.md +10 -9
  41. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  42. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +155 -2
  43. package/docs/README.md +1 -1
  44. package/modules/README.md +1 -0
  45. package/package.json +2 -1
@@ -53,7 +53,9 @@
53
53
  * SECTION 7: FILL PIPELINE & LAST-FILL GUARD (9 functions)
54
54
  * - reanchorBoundaryFromLastFill(manager, ...) - Re-anchor a rebuilt boundary to the last fill
55
55
  * - rearmLastFillPivotFromMarketFill(manager) - Re-arm the pivot from the last market fill
56
- * - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD predicate
56
+ * - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD direction predicate
57
+ * - isLastFillBandSellExempt(manager, price) - Geometry territory for a SELL counter-order
58
+ * - evaluateLastFillGuard(manager, price, type, pivot, pivotType) - Shared placement verdict
57
59
  * - isLastFillPlacementBlocked(manager, price, type) - Placement-side LAST-FILL-GUARD wrapper
58
60
  * - readFillPipelineState(source) - Projection of the fill-pipeline state
59
61
  * - resolveGridUpdateBlockers(source, options) - Blockers that forbid a grid update right now
@@ -608,6 +610,94 @@ export declare function isLastFillGuardBlocked(price: number, type: unknown, las
608
610
  pivot: number | null;
609
611
  threshold?: number | null;
610
612
  };
613
+ /**
614
+ * REFUSED-LEVEL SAME-LEVEL RE-FILL BLOCK (§9.12/P2 amended, 2026-11-16).
615
+ *
616
+ * A fill the pivot-arming policy refused (wrong-side / too-far premium sweep)
617
+ * does not arm the direction pivot — deliberately, so the guard keeps trading
618
+ * around the live market instead of deadlocking the side for the pivot TTL.
619
+ * But the same-level re-fill refusal (§9.12/P2: "the exact pivot level remains
620
+ * blocked as a same-level re-fill") keys off the ARMED pivot, so the P1
621
+ * refusal silently suspended it: a spread-correction slot could be re-armed at
622
+ * the identical level and refill immediately, in a loop, for as long as a
623
+ * taker kept lifting it.
624
+ *
625
+ * This predicate closes that gap with a SEPARATE, minimal role: the refused
626
+ * fill's own level, same side only, within half a grid step (the same
627
+ * pricesWithinHalfStep test isLastFillPlacementBlocked uses), for a short
628
+ * in-memory TTL (GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS). It vetoes exactly
629
+ * one price level — the just-filled one — and nothing else: the counter-side
630
+ * stays governed by the (older) direction pivot and spread correction can
631
+ * still trade around the live market, so the unquoted-side deadlock P1 was
632
+ * written against cannot re-open through it. Fail-open on anything unreadable.
633
+ *
634
+ * @param {Object} manager - OrderManager instance
635
+ * @param {number} price - Candidate placement price
636
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
637
+ * @returns {{blocked: boolean, level: number|null}} Verdict + the refused level
638
+ */
639
+ export declare function isRefusedLevelRefillBlocked(manager: OrderManagerLike | null | undefined, price: unknown, type: unknown): {
640
+ blocked: boolean;
641
+ level: number | null;
642
+ };
643
+ /**
644
+ * The direction rule PLUS the geometry-territory exemption — the verdict
645
+ * every COW-path guard shares (probe and final gate), so no site re-implements
646
+ * "may this op be placed against the last fill?".
647
+ *
648
+ * Also applies the REFUSED-LEVEL same-level re-fill block (§9.12/P2 amended):
649
+ * a placement on the same side within half a grid step of a fill whose
650
+ * pivot-arm was refused stays blocked even though the direction pivot itself
651
+ * stayed behind that fill. See isRefusedLevelRefillBlocked.
652
+ *
653
+ * @param {Object} manager - OrderManager instance (geometry for the exemption)
654
+ * @param {number} price - Target price
655
+ * @param {string} type - ORDER_TYPES.BUY/SELL
656
+ * @param {number|null} pivotPrice - Resolved pivot (already ladder-snapped by the caller)
657
+ * @param {string|null} pivotType - Pivot side; null keeps the guard cold
658
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null, bandExempt?: boolean, refusedLevel?: boolean}}
659
+ */
660
+ export declare function evaluateLastFillGuard(manager: OrderManagerLike | null | undefined, price: number, type: unknown, pivotPrice: number | null, pivotType: string | null): {
661
+ blocked: boolean;
662
+ pivot: number | null;
663
+ threshold?: number | null;
664
+ bandExempt?: boolean;
665
+ refusedLevel?: boolean;
666
+ };
667
+ /**
668
+ *
669
+ * The direction rule (isLastFillGuardBlocked) says "never sell at/below the last
670
+ * sale". That is right when the veto is evidence of a fault — retrospective
671
+ * §9.7/§9.9: "a sell slot below the last sale is evidence that the boundary/
672
+ * crawl is behind the fill". It is WRONG when the geometry is exactly where the
673
+ * fill re-anchor puts it: after a SELL fill at slot f the re-anchor rule is
674
+ * `boundary >= f - gapSlots`, so the gap band (boundary, boundary+gap] tops out
675
+ * AT the filled level and every band slot is `<= pivot` by construction. The
676
+ * pivot then vetoes 100% of the counter-order rungs it just derived.
677
+ *
678
+ * Live (2026-11-15): a sweep armed the pivot at the band's own top level; every
679
+ * sell slot in the band was refused as "at/through the last fill", no sell
680
+ * could be re-placed, and the spread stayed 3.0% (limit 1.65%) for 86 minutes
681
+ * until an operator-visible watchdog ran out of options.
682
+ *
683
+ * The exemption is a GEOMETRY fact, not a second direction rule: it applies
684
+ * - SELL only. The BUY mirror is deliberately absent — after a BUY fill the
685
+ * band sits ABOVE the fill, and buys above the last buy are the chase class
686
+ * the guard was introduced for (§9.7 "buying later at higher prices").
687
+ * - inside the band only (boundary < idx <= boundary + gap),
688
+ * - strictly below the pivot's own ladder level (the pivot level itself is
689
+ * always refused as a same-level re-fill),
690
+ * - only when the boundary already satisfies the fill anchor
691
+ * (`boundary >= pivotIdx - gapSlots`), i.e. the geometry is NOT behind the
692
+ * fill — the precise precondition §9.7 names for the refusal.
693
+ * Fail-closed on anything unprovable (no genesis, off-ladder price, unknown
694
+ * boundary/gap).
695
+ *
696
+ * @param {Object} manager - OrderManager instance (pivot + boundary + gap + genesis)
697
+ * @param {number} price - SELL placement price
698
+ * @returns {boolean} True when the pivot must NOT veto this placement
699
+ */
700
+ export declare function isLastFillBandSellExempt(manager: OrderManagerLike | null | undefined, price: unknown): boolean;
611
701
  /**
612
702
  * LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
613
703
  *
@@ -625,15 +715,19 @@ export declare function isLastFillGuardBlocked(price: number, type: unknown, las
625
715
  * prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
626
716
  * still builds.
627
717
  *
718
+ * The SELL band exemption (isLastFillBandSellExempt) is applied between the two
719
+ * rules: a re-place at the traded level stays blocked, a band counter-order is
720
+ * not.
721
+ *
628
722
  * @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
629
723
  * @param {number} price - Target placement price
630
724
  * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
631
- * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
725
+ * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'|'refused-level'}}
632
726
  */
633
727
  export declare function isLastFillPlacementBlocked(manager: OrderManagerLike | null | undefined, price: unknown, type: unknown): {
634
728
  blocked: boolean;
635
729
  pivot: number | null;
636
- reason?: 'direction' | 'same-level';
730
+ reason?: 'direction' | 'same-level' | 'refused-level';
637
731
  };
638
732
  /**
639
733
  * Why a grid update was refused this cycle.
@@ -856,6 +950,21 @@ export declare function setLastFillPivot(manager: OrderManagerLike, type: string
856
950
  * @returns {boolean} True when an armed pivot was cleared
857
951
  */
858
952
  export declare function resetLastFillPivot(manager: OrderManagerLike, reason?: string): boolean;
953
+ /**
954
+ * Drop the ENTIRE last-fill guard state — the pivot scalar family AND the
955
+ * bot-scoped last-market-fill reference, live and persisted — after the
956
+ * spread watchdog concluded the pivot can never heal the grid (geometry
957
+ * re-center already tried and failed; SPREAD_STALE_PIVOT_EXPIRE_MS elapsed).
958
+ *
959
+ * Mirrors restoreLastMarketFill's dead-row contract: persisted rows are
960
+ * erased too, so a restart/rebuild cannot re-arm the same veto via
961
+ * rearmLastFillPivotFromMarketFill. Both references re-arm on the next real
962
+ * fill.
963
+ *
964
+ * @param {Object} manager - OrderManager instance
965
+ * @param {string} reason - Log/debug label for the expiry
966
+ */
967
+ export declare function expireLastFillGuardReferences(manager: OrderManagerLike, reason?: string): void;
859
968
  /**
860
969
  * Restore the persisted LAST-FILL-GUARD pivot into the manager.
861
970
  *
@@ -53,7 +53,9 @@
53
53
  * SECTION 7: FILL PIPELINE & LAST-FILL GUARD (9 functions)
54
54
  * - reanchorBoundaryFromLastFill(manager, ...) - Re-anchor a rebuilt boundary to the last fill
55
55
  * - rearmLastFillPivotFromMarketFill(manager) - Re-arm the pivot from the last market fill
56
- * - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD predicate
56
+ * - isLastFillGuardBlocked(price, type, lastPrice, lastType) - LAST-FILL-GUARD direction predicate
57
+ * - isLastFillBandSellExempt(manager, price) - Geometry territory for a SELL counter-order
58
+ * - evaluateLastFillGuard(manager, price, type, pivot, pivotType) - Shared placement verdict
57
59
  * - isLastFillPlacementBlocked(manager, price, type) - Placement-side LAST-FILL-GUARD wrapper
58
60
  * - readFillPipelineState(source) - Projection of the fill-pipeline state
59
61
  * - resolveGridUpdateBlockers(source, options) - Blockers that forbid a grid update right now
@@ -1733,6 +1735,185 @@ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
1733
1735
  return { blocked: true, pivot, threshold: pivot };
1734
1736
  return { blocked: false, pivot: null, threshold: null };
1735
1737
  }
1738
+ /**
1739
+ * REFUSED-LEVEL SAME-LEVEL RE-FILL BLOCK (§9.12/P2 amended, 2026-11-16).
1740
+ *
1741
+ * A fill the pivot-arming policy refused (wrong-side / too-far premium sweep)
1742
+ * does not arm the direction pivot — deliberately, so the guard keeps trading
1743
+ * around the live market instead of deadlocking the side for the pivot TTL.
1744
+ * But the same-level re-fill refusal (§9.12/P2: "the exact pivot level remains
1745
+ * blocked as a same-level re-fill") keys off the ARMED pivot, so the P1
1746
+ * refusal silently suspended it: a spread-correction slot could be re-armed at
1747
+ * the identical level and refill immediately, in a loop, for as long as a
1748
+ * taker kept lifting it.
1749
+ *
1750
+ * This predicate closes that gap with a SEPARATE, minimal role: the refused
1751
+ * fill's own level, same side only, within half a grid step (the same
1752
+ * pricesWithinHalfStep test isLastFillPlacementBlocked uses), for a short
1753
+ * in-memory TTL (GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS). It vetoes exactly
1754
+ * one price level — the just-filled one — and nothing else: the counter-side
1755
+ * stays governed by the (older) direction pivot and spread correction can
1756
+ * still trade around the live market, so the unquoted-side deadlock P1 was
1757
+ * written against cannot re-open through it. Fail-open on anything unreadable.
1758
+ *
1759
+ * @param {Object} manager - OrderManager instance
1760
+ * @param {number} price - Candidate placement price
1761
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
1762
+ * @returns {{blocked: boolean, level: number|null}} Verdict + the refused level
1763
+ */
1764
+ export function isRefusedLevelRefillBlocked(manager, price, type) {
1765
+ const p = Number(price);
1766
+ const level = Number(manager?._lastRefusedFillPrice);
1767
+ const at = Number(manager?._lastRefusedFillAt);
1768
+ const refType = manager?._lastRefusedFillType;
1769
+ if (!Number.isFinite(p) || !Number.isFinite(level) || level <= 0)
1770
+ return { blocked: false, level: null };
1771
+ if (refType !== ORDER_TYPES.BUY && refType !== ORDER_TYPES.SELL)
1772
+ return { blocked: false, level: null };
1773
+ if (type !== refType)
1774
+ return { blocked: false, level };
1775
+ const ttl = Number(GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS);
1776
+ if (!(ttl > 0) || !Number.isFinite(at) || at <= 0 || (Date.now() - at) > ttl)
1777
+ return { blocked: false, level };
1778
+ let sameLevel = false;
1779
+ try {
1780
+ sameLevel = MathUtils.pricesWithinHalfStep(p, level, Number(manager?.config?.incrementPercent));
1781
+ }
1782
+ catch {
1783
+ sameLevel = p === level;
1784
+ }
1785
+ return { blocked: sameLevel, level };
1786
+ }
1787
+ /**
1788
+ * The direction rule PLUS the geometry-territory exemption — the verdict
1789
+ * every COW-path guard shares (probe and final gate), so no site re-implements
1790
+ * "may this op be placed against the last fill?".
1791
+ *
1792
+ * Also applies the REFUSED-LEVEL same-level re-fill block (§9.12/P2 amended):
1793
+ * a placement on the same side within half a grid step of a fill whose
1794
+ * pivot-arm was refused stays blocked even though the direction pivot itself
1795
+ * stayed behind that fill. See isRefusedLevelRefillBlocked.
1796
+ *
1797
+ * @param {Object} manager - OrderManager instance (geometry for the exemption)
1798
+ * @param {number} price - Target price
1799
+ * @param {string} type - ORDER_TYPES.BUY/SELL
1800
+ * @param {number|null} pivotPrice - Resolved pivot (already ladder-snapped by the caller)
1801
+ * @param {string|null} pivotType - Pivot side; null keeps the guard cold
1802
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null, bandExempt?: boolean, refusedLevel?: boolean}}
1803
+ */
1804
+ export function evaluateLastFillGuard(manager, price, type, pivotPrice, pivotType) {
1805
+ const check = isLastFillGuardBlocked(price, type, pivotPrice, pivotType);
1806
+ let verdict;
1807
+ if (!check.blocked)
1808
+ verdict = check;
1809
+ else if (type === ORDER_TYPES.SELL && isLastFillBandSellExempt(manager, price)) {
1810
+ verdict = { blocked: false, pivot: check.pivot, bandExempt: true };
1811
+ }
1812
+ else
1813
+ verdict = check;
1814
+ if (!verdict.blocked) {
1815
+ const refused = isRefusedLevelRefillBlocked(manager, price, type);
1816
+ if (refused.blocked) {
1817
+ return { blocked: true, pivot: refused.level, threshold: refused.level, refusedLevel: true };
1818
+ }
1819
+ }
1820
+ return verdict;
1821
+ }
1822
+ /**
1823
+ *
1824
+ * The direction rule (isLastFillGuardBlocked) says "never sell at/below the last
1825
+ * sale". That is right when the veto is evidence of a fault — retrospective
1826
+ * §9.7/§9.9: "a sell slot below the last sale is evidence that the boundary/
1827
+ * crawl is behind the fill". It is WRONG when the geometry is exactly where the
1828
+ * fill re-anchor puts it: after a SELL fill at slot f the re-anchor rule is
1829
+ * `boundary >= f - gapSlots`, so the gap band (boundary, boundary+gap] tops out
1830
+ * AT the filled level and every band slot is `<= pivot` by construction. The
1831
+ * pivot then vetoes 100% of the counter-order rungs it just derived.
1832
+ *
1833
+ * Live (2026-11-15): a sweep armed the pivot at the band's own top level; every
1834
+ * sell slot in the band was refused as "at/through the last fill", no sell
1835
+ * could be re-placed, and the spread stayed 3.0% (limit 1.65%) for 86 minutes
1836
+ * until an operator-visible watchdog ran out of options.
1837
+ *
1838
+ * The exemption is a GEOMETRY fact, not a second direction rule: it applies
1839
+ * - SELL only. The BUY mirror is deliberately absent — after a BUY fill the
1840
+ * band sits ABOVE the fill, and buys above the last buy are the chase class
1841
+ * the guard was introduced for (§9.7 "buying later at higher prices").
1842
+ * - inside the band only (boundary < idx <= boundary + gap),
1843
+ * - strictly below the pivot's own ladder level (the pivot level itself is
1844
+ * always refused as a same-level re-fill),
1845
+ * - only when the boundary already satisfies the fill anchor
1846
+ * (`boundary >= pivotIdx - gapSlots`), i.e. the geometry is NOT behind the
1847
+ * fill — the precise precondition §9.7 names for the refusal.
1848
+ * Fail-closed on anything unprovable (no genesis, off-ladder price, unknown
1849
+ * boundary/gap).
1850
+ *
1851
+ * @param {Object} manager - OrderManager instance (pivot + boundary + gap + genesis)
1852
+ * @param {number} price - SELL placement price
1853
+ * @returns {boolean} True when the pivot must NOT veto this placement
1854
+ */
1855
+ export function isLastFillBandSellExempt(manager, price) {
1856
+ if (!manager)
1857
+ return false;
1858
+ const p = Number(price);
1859
+ if (!Number.isFinite(p) || p <= 0)
1860
+ return false;
1861
+ let ref = { price: null, type: null };
1862
+ try {
1863
+ ref = resolveFillProvenancedReference(manager);
1864
+ }
1865
+ catch {
1866
+ return false;
1867
+ }
1868
+ if (ref.type !== ORDER_TYPES.SELL || ref.price == null || !Number.isFinite(Number(ref.price)))
1869
+ return false;
1870
+ const genesis = manager._genesis;
1871
+ const levels = genesis?.priceLevels;
1872
+ if (!Array.isArray(levels) || levels.length === 0)
1873
+ return false;
1874
+ const gapRaw = manager._gapSlots;
1875
+ const gap = Number(gapRaw);
1876
+ const boundary = Number(manager.boundaryIdx);
1877
+ if (!Number.isFinite(gap) || gap < 0 || !Number.isFinite(boundary))
1878
+ return false;
1879
+ const lo = Number(levels[0]);
1880
+ const hi = Number(levels[levels.length - 1]);
1881
+ const inRail = (v) => Number.isFinite(v) && v >= lo && v <= hi;
1882
+ if (!inRail(p) || !inRail(Number(ref.price)))
1883
+ return false;
1884
+ let pivotIdx;
1885
+ let candIdx;
1886
+ try {
1887
+ const g = genesis;
1888
+ pivotIdx = Number(MathUtils.slotIndexForPrice(Number(ref.price), g));
1889
+ candIdx = Number(MathUtils.slotIndexForPrice(p, g));
1890
+ }
1891
+ catch {
1892
+ return false;
1893
+ }
1894
+ if (!Number.isFinite(pivotIdx) || !Number.isFinite(candIdx))
1895
+ return false;
1896
+ // Only a genuine ladder level: same one-increment drift bound the re-anchor
1897
+ // uses, so an adopted/orphan price cannot invent an exemption.
1898
+ const incRaw = Number(manager.config?.incrementPercent);
1899
+ const maxDrift = Number.isFinite(incRaw) && incRaw > 0 ? incRaw / 100 : 0.005;
1900
+ let levelPrice;
1901
+ try {
1902
+ levelPrice = Number(MathUtils.priceForSlot(candIdx, genesis));
1903
+ }
1904
+ catch {
1905
+ return false;
1906
+ }
1907
+ if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - p) / p > maxDrift)
1908
+ return false;
1909
+ if (candIdx <= boundary)
1910
+ return false;
1911
+ if (candIdx > boundary + Math.floor(gap))
1912
+ return false;
1913
+ if (candIdx >= pivotIdx)
1914
+ return false;
1915
+ return boundary >= pivotIdx - Math.floor(gap);
1916
+ }
1736
1917
  /**
1737
1918
  * LAST-FILL PLACEMENT GUARD — the direction rule applied to a PLACEMENT.
1738
1919
  *
@@ -1750,10 +1931,14 @@ export function isLastFillGuardBlocked(price, type, lastPrice, lastType) {
1750
1931
  * prices" incident). Fail-open on a cold pivot (no fill yet) so a fresh grid
1751
1932
  * still builds.
1752
1933
  *
1934
+ * The SELL band exemption (isLastFillBandSellExempt) is applied between the two
1935
+ * rules: a re-place at the traded level stays blocked, a band counter-order is
1936
+ * not.
1937
+ *
1753
1938
  * @param {Object} manager - OrderManager instance (pivot + config.incrementPercent)
1754
1939
  * @param {number} price - Target placement price
1755
1940
  * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
1756
- * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'}}
1941
+ * @returns {{blocked: boolean, pivot: number|null, reason?: 'direction'|'same-level'|'refused-level'}}
1757
1942
  */
1758
1943
  export function isLastFillPlacementBlocked(manager, price, type) {
1759
1944
  const numPrice = Number(price);
@@ -1768,8 +1953,17 @@ export function isLastFillPlacementBlocked(manager, price, type) {
1768
1953
  }
1769
1954
  const pivot = reference.price;
1770
1955
  const pivotType = reference.type;
1771
- if (pivot == null || pivotType == null)
1956
+ if (pivot == null || pivotType == null) {
1957
+ // Cold direction pivot: a refused (off-market) fill marker can still be
1958
+ // live and must keep blocking the same-level re-fill (§9.12/P2 amended).
1959
+ try {
1960
+ const refused = isRefusedLevelRefillBlocked(manager, numPrice, type);
1961
+ if (refused.blocked)
1962
+ return { blocked: true, pivot: refused.level, reason: 'refused-level' };
1963
+ }
1964
+ catch { /* fail-open */ }
1772
1965
  return { blocked: false, pivot: null };
1966
+ }
1773
1967
  if (type !== ORDER_TYPES.BUY && type !== ORDER_TYPES.SELL)
1774
1968
  return { blocked: false, pivot };
1775
1969
  try {
@@ -1778,9 +1972,9 @@ export function isLastFillPlacementBlocked(manager, price, type) {
1778
1972
  }
1779
1973
  }
1780
1974
  catch { /* fall through to the direction rule */ }
1781
- const guard = isLastFillGuardBlocked(numPrice, type, pivot, pivotType);
1975
+ const guard = evaluateLastFillGuard(manager, numPrice, type, pivot, pivotType);
1782
1976
  if (guard.blocked)
1783
- return { blocked: true, pivot, reason: 'direction' };
1977
+ return { blocked: true, pivot: guard.pivot, reason: guard.refusedLevel ? 'refused-level' : 'direction' };
1784
1978
  return { blocked: false, pivot };
1785
1979
  }
1786
1980
  /**
@@ -2135,6 +2329,78 @@ export function normalizeLastFillPivot(row) {
2135
2329
  export function normalizeLastMarketFill(row) {
2136
2330
  return normalizeFillRow(row);
2137
2331
  }
2332
+ /**
2333
+ * LAST-FILL-PIVOT MARKET BOUND — is this fill evidence of the CURRENT window,
2334
+ * or of something else? Two legs, one reference:
2335
+ *
2336
+ * wrong-side BUY above mid / SELL below mid (past the one-step tolerance).
2337
+ * Fills at/through the opposite side of the book cannot happen on
2338
+ * an honest market — a crossed-book artifact (typically the
2339
+ * bot's own misplaced order swept by an external taker).
2340
+ * too-far Either side, further than
2341
+ * GRID_LIMITS.LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS increments
2342
+ * from the mid. Live: a taker swept our rail up to a level 14.5
2343
+ * steps (4.4%) ABOVE the mid and EVERY one of those fills is on
2344
+ * the honest side by direction, so the wrong-side leg let them
2345
+ * through; the top one armed the pivot at the band's own top,
2346
+ * vetoing every sell the geometry had just derived and freeing
2347
+ * nothing for 86 minutes. A premium sweep is not a window trade.
2348
+ *
2349
+ * Both legs judge against the cached live market price, and only while it is
2350
+ * fresh (GRID_LIMITS.LAST_FILL_PIVOT_MARKET_FRESH_MS) — fail-open otherwise.
2351
+ * The reference is deliberately the BOOK read, not the fill-derived one: a
2352
+ * trade must be judged against the quotes it traded through, never against
2353
+ * itself (which would make the bound self-satisfying).
2354
+ *
2355
+ * @param {Object} manager - OrderManager instance
2356
+ * @param {string} type - ORDER_TYPES.BUY / ORDER_TYPES.SELL
2357
+ * @param {number} price - Fill price
2358
+ * @returns {{ steps: number, mid: number, kind?: 'wrong-side'|'too-far' } | null}
2359
+ * Off-market detail, or null when the fill is window evidence / unknowable
2360
+ */
2361
+ function offMarketFill(manager, type, price) {
2362
+ const mid = Number(manager?._liveMarketPrice);
2363
+ const midAt = Number(manager?._liveMarketPriceAt);
2364
+ if (!Number.isFinite(mid) || mid <= 0)
2365
+ return null;
2366
+ if (!Number.isFinite(midAt) || midAt <= 0)
2367
+ return null;
2368
+ const freshMs = Number(GRID_LIMITS.LAST_FILL_PIVOT_MARKET_FRESH_MS);
2369
+ if (!(freshMs > 0) || (Date.now() - midAt) > freshMs)
2370
+ return null;
2371
+ const incRaw = Number(manager?.config?.incrementPercent);
2372
+ const stepPct = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 0.5;
2373
+ const step = 1 + (stepPct / 100);
2374
+ const tolerance = Number(GRID_LIMITS.LAST_FILL_PIVOT_WRONG_SIDE_TOLERANCE_STEPS);
2375
+ const tol = Number.isFinite(tolerance) && tolerance >= 0 ? tolerance : 1;
2376
+ // Relative epsilon so "exactly N steps above mid" is not refused by
2377
+ // floating-point drift in Math.pow (1000 * 1.005 === 1004.9999999999999).
2378
+ const eps = mid * 1e-9;
2379
+ if (type === ORDER_TYPES.BUY) {
2380
+ const limit = mid * Math.pow(step, tol);
2381
+ if (price > limit + eps) {
2382
+ return { steps: Math.max(1, Math.round(Math.log(price / mid) / Math.log(step))), mid, kind: 'wrong-side' };
2383
+ }
2384
+ }
2385
+ else {
2386
+ const limit = mid / Math.pow(step, tol);
2387
+ if (price < limit - eps) {
2388
+ return { steps: Math.max(1, Math.round(Math.log(mid / price) / Math.log(step))), mid, kind: 'wrong-side' };
2389
+ }
2390
+ }
2391
+ // Second leg: a fill inside the direction tolerance can still be a premium
2392
+ // sweep (a taker paying through several of our levels). Distance is judged
2393
+ // symmetrically — both sides are equally far from the market.
2394
+ const maxStepsRaw = Number(GRID_LIMITS.LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS);
2395
+ const maxSteps = Number.isFinite(maxStepsRaw) && maxStepsRaw > 0 ? maxStepsRaw : 0;
2396
+ if (maxSteps > 0) {
2397
+ const dist = Math.abs(Math.log(price / mid) / Math.log(step));
2398
+ if (dist > maxSteps + 1e-9) {
2399
+ return { steps: Math.max(1, Math.round(dist)), mid, kind: 'too-far' };
2400
+ }
2401
+ }
2402
+ return null;
2403
+ }
2138
2404
  /**
2139
2405
  * Write the LAST-FILL-GUARD pivot scalar family in one place (free
2140
2406
  * implementation shared by the manager method, cow_runtime's queued-fill
@@ -2162,6 +2428,48 @@ export function setLastFillPivot(manager, type, price, provenance, atMs) {
2162
2428
  const p = Number(price);
2163
2429
  if (!Number.isFinite(p) || p <= 0)
2164
2430
  return false;
2431
+ // LAST-FILL-PIVOT MARKET BOUND (fill provenance only): a real fill may arm
2432
+ // the guard only when it is evidence of the CURRENT window — on the
2433
+ // market's own side of the live reference AND within a full spread of it.
2434
+ // A wrong-side fill is a crossed-book artifact; a fill many steps away on
2435
+ // the honest side is a premium sweep of our own rail. Both are cases where
2436
+ // arming the pivot vetoes the very band the geometry derives, for the full
2437
+ // 24h TTL. Fail-open when no fresh live price exists: an ancient mid must
2438
+ // never veto a fresh fill after a fast move.
2439
+ // Deliberately applied to EVERY fill-provenance write (direct fills,
2440
+ // queued-fill refresh, rebuild re-arm) so no path can re-arm an
2441
+ // off-market row. The market-fill reference is skipped with it — an
2442
+ // off-market row as the crossing floor would freeze correction the same
2443
+ // way.
2444
+ if (provenance === 'fill') {
2445
+ const offMarket = offMarketFill(manager, type, p);
2446
+ if (offMarket) {
2447
+ const why = offMarket.kind === 'too-far'
2448
+ ? `it priced ${offMarket.steps} grid step(s) away from the live market `
2449
+ + `${offMarket.mid} — a premium sweep of our own rail, not a window trade`
2450
+ : `it priced ${offMarket.steps} grid step(s) on the wrong side of the live market `
2451
+ + `${offMarket.mid} — a crossed-book artifact, not market truth`;
2452
+ // REFUSED-LEVEL MARKER (§9.12/P2 amended): the fill does not arm the
2453
+ // direction pivot, but its LEVEL must still refuse the immediate
2454
+ // re-place at the just-filled price. Without this the P1 refusal
2455
+ // silently suspended the P2 same-level block (which keys off the
2456
+ // ARMED pivot): a spread-correction slot re-armed at the identical
2457
+ // level and refilled in a loop for as long as a taker kept lifting
2458
+ // it (live 2026-11-16: 5 full fills at one premium level in 2.5
2459
+ // minutes). In-memory, TTL-bounded (LAST_FILL_REFUSED_LEVEL_TTL_MS).
2460
+ try {
2461
+ manager._lastRefusedFillPrice = p;
2462
+ manager._lastRefusedFillType = type;
2463
+ manager._lastRefusedFillAt = Date.now();
2464
+ }
2465
+ catch { /* marker is best-effort */ }
2466
+ const ttlMin = Math.round(Number(GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS) / 60000);
2467
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Refusing to arm pivot ${p}(${type}): ${why}; the guard `
2468
+ + `stays as-is and spread correction keeps trading around the live market; `
2469
+ + `the just-filled level stays blocked as a same-level re-fill for ${ttlMin}m`, 'warn');
2470
+ return false;
2471
+ }
2472
+ }
2165
2473
  const now = Number.isFinite(Number(atMs)) && Number(atMs) > 0 ? Number(atMs) : Date.now();
2166
2474
  manager._lastFilledPrice = p;
2167
2475
  manager._lastFilledType = type;
@@ -2210,6 +2518,11 @@ export function resetLastFillPivot(manager, reason = 'unspecified') {
2210
2518
  manager.lastFillPivotSource = null;
2211
2519
  manager._lastFilledBuyPrice = null;
2212
2520
  manager._lastFilledSellPrice = null;
2521
+ // The refused-level marker belongs to the same guard generation: a grid
2522
+ // rebuild invalidates the geometry (and any marker read against it).
2523
+ manager._lastRefusedFillPrice = null;
2524
+ manager._lastRefusedFillType = null;
2525
+ manager._lastRefusedFillAt = 0;
2213
2526
  if (wasArmed) {
2214
2527
  try {
2215
2528
  manager.logger?.log?.(`[LAST-FILL-GUARD] Pivot cleared (${reason}); guard re-arms on the next fill`, 'info');
@@ -2218,6 +2531,48 @@ export function resetLastFillPivot(manager, reason = 'unspecified') {
2218
2531
  }
2219
2532
  return wasArmed;
2220
2533
  }
2534
+ /**
2535
+ * Drop the ENTIRE last-fill guard state — the pivot scalar family AND the
2536
+ * bot-scoped last-market-fill reference, live and persisted — after the
2537
+ * spread watchdog concluded the pivot can never heal the grid (geometry
2538
+ * re-center already tried and failed; SPREAD_STALE_PIVOT_EXPIRE_MS elapsed).
2539
+ *
2540
+ * Mirrors restoreLastMarketFill's dead-row contract: persisted rows are
2541
+ * erased too, so a restart/rebuild cannot re-arm the same veto via
2542
+ * rearmLastFillPivotFromMarketFill. Both references re-arm on the next real
2543
+ * fill.
2544
+ *
2545
+ * @param {Object} manager - OrderManager instance
2546
+ * @param {string} reason - Log/debug label for the expiry
2547
+ */
2548
+ export function expireLastFillGuardReferences(manager, reason = 'unspecified') {
2549
+ if (!manager)
2550
+ return;
2551
+ const pivotArmed = manager._lastFilledPrice != null && manager._lastFilledType != null;
2552
+ const fillRefArmed = manager._lastMarketFillPrice != null;
2553
+ resetLastFillPivot(manager, reason);
2554
+ manager._lastMarketFillPrice = null;
2555
+ manager._lastMarketFillType = null;
2556
+ manager._lastMarketFillAt = 0;
2557
+ try {
2558
+ const acct = manager.accountOrders;
2559
+ if (acct && typeof acct.clearPersistedLastMarketFill === 'function') {
2560
+ void acct.clearPersistedLastMarketFill();
2561
+ }
2562
+ if (acct && typeof acct.clearPersistedLastFillPivot === 'function') {
2563
+ void acct.clearPersistedLastFillPivot();
2564
+ }
2565
+ }
2566
+ catch { /* best-effort */ }
2567
+ if (pivotArmed || fillRefArmed) {
2568
+ try {
2569
+ manager.logger?.log?.(`[LAST-FILL-GUARD] Expired guard references (${reason}): pivot and last-market-fill ` +
2570
+ `cleared live and persisted — spread correction trades around the live market ` +
2571
+ `again; both re-arm on the next real fill`, 'warn');
2572
+ }
2573
+ catch { /* logging is best-effort */ }
2574
+ }
2575
+ }
2221
2576
  /**
2222
2577
  * Restore the persisted LAST-FILL-GUARD pivot into the manager.
2223
2578
  *
@@ -2301,7 +2656,14 @@ export function restoreLastFillPivot(manager, persisted, options = {}) {
2301
2656
  if (!validated)
2302
2657
  return false;
2303
2658
  // Arm through the shared writer, preserving the persisted timestamp.
2304
- setLastFillPivot(manager, row.type, validated.price, 'fill', row.fillsAt);
2659
+ // The writer's wrong-side market bound can refuse (fresh live mid on
2660
+ // the other side of the row) — treat that like any other dead row:
2661
+ // erase the persisted value so a restart cannot re-arm the same veto.
2662
+ const armed = setLastFillPivot(manager, row.type, validated.price, 'fill', row.fillsAt);
2663
+ if (!armed) {
2664
+ dropPersistedRow();
2665
+ return false;
2666
+ }
2305
2667
  manager.logger?.log?.(`[LAST-FILL-GUARD] Restored persisted pivot ${validated.price}(${row.type})` +
2306
2668
  `${validated.slotIdx != null ? ` slot=${validated.slotIdx}` : ''}` +
2307
2669
  `${validated.snapped ? ' (snapped)' : ''} age=${Math.round((now - row.fillsAt) / 1000)}s from snapshot`, 'info');
@@ -112,6 +112,7 @@ declare const PATHS: {
112
112
  ECOSYSTEM_CONFIG_JS: string;
113
113
  SUPERVISOR_SOCK: string;
114
114
  MONOLITHIC_PID: string;
115
+ INSTANCE_LOCKS_DIR: string;
115
116
  MONOLITHIC_BOT_PID: string;
116
117
  MONOLITHIC_BOT_INFO: string;
117
118
  MONOLITHIC_CRED_PID: string;
@@ -308,6 +308,7 @@ const PATHS = {
308
308
  ECOSYSTEM_CONFIG_JS: path.join(PROFILES_DIR, 'ecosystem.config.cjs'),
309
309
  SUPERVISOR_SOCK: path.join(PROFILES_DIR, 'supervisor.sock'),
310
310
  MONOLITHIC_PID: path.join(PROFILES_DIR, 'monolithic.pid'),
311
+ INSTANCE_LOCKS_DIR: path.join(PROFILES_DIR, 'instance-locks'),
311
312
  MONOLITHIC_BOT_PID: path.join(PROFILES_DIR, 'monolithic-bot.pid'),
312
313
  MONOLITHIC_BOT_INFO: path.join(PROFILES_DIR, 'monolithic-bot.json'),
313
314
  MONOLITHIC_CRED_PID: path.join(PROFILES_DIR, 'monolithic-cred.pid'),
@@ -107,8 +107,10 @@ export const TIMING_CLASSIFICATIONS = Object.freeze({
107
107
  SPREAD_STALE_ESCALATE_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before escalation.' },
108
108
  SPREAD_STALE_FUND_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is fundability.' },
109
109
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is geometry.' },
110
+ SPREAD_STALE_PIVOT_EXPIRE_MS: { kind: 'policy', rationale: 'Pivot lifetime after the one re-center per fill before the guard references are expired outright.' },
110
111
  SPREAD_STALE_IN_TOLERANCE_RESET_MS: { kind: 'policy', rationale: 'How long in-tolerance must hold before the watchdog resets.' },
111
112
  SPREAD_STALE_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on spread-correction resyncs.' },
113
+ SPREAD_STALE_RECHECK_MS: { kind: 'policy', rationale: 'Level-triggered recheck cadence while the spread is out of tolerance (the documented watchdog clocks assume evaluation).' },
112
114
  SPREAD_STALE_TRANSIENT_GRACE: { kind: 'policy', rationale: 'Consecutive transient corrections tolerated before escalating.' },
113
115
  SPREAD_STALE_WARN_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before a warning.' },
114
116
  TARGETED_DRIFT_SYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on targeted drift syncs.' },