dexbot 1.6.16 → 1.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/analysis/README.md +10 -9
  3. package/analysis/ama_fitting/README.md +2 -2
  4. package/analysis/bot_fitting/README.md +3 -3
  5. package/analysis/tradingview/README.md +2 -2
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  7. package/claw/package.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  10. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  11. package/dist/analysis/analyze_args.d.ts +2 -1
  12. package/dist/analysis/fills_source.d.ts +1 -8
  13. package/dist/analysis/fills_source.js +1 -1
  14. package/dist/analysis/grid_correction_check.d.ts +9 -6
  15. package/dist/analysis/grid_correction_check.js +56 -64
  16. package/dist/analysis/math_utils.d.ts +1 -1
  17. package/dist/analysis/trade_profitability.d.ts +1 -1
  18. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
  20. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  21. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  22. package/dist/market_adapter/cli_args.d.ts +6 -1
  23. package/dist/market_adapter/cli_args.js +16 -2
  24. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  25. package/dist/market_adapter/core/kibana_candles.js +3 -1
  26. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  27. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  28. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  29. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  30. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  31. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  32. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  33. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  34. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  35. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  36. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  37. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  38. package/dist/market_adapter/inputs/window_cache.js +14 -1
  39. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  40. package/dist/market_adapter/lp_chart_runner.js +3 -1
  41. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  42. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  43. package/dist/market_adapter/market_adapter.d.ts +10 -2
  44. package/dist/market_adapter/market_adapter.js +10 -11
  45. package/dist/market_adapter/utils/chain.d.ts +2 -3
  46. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  47. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  48. package/dist/market_adapter/utils/file_lock.js +1 -1
  49. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  50. package/dist/market_adapter/utils/native_history.js +3 -1
  51. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  52. package/dist/modules/account_bots.d.ts +3 -0
  53. package/dist/modules/bots_file_lock.d.ts +2 -2
  54. package/dist/modules/bots_file_lock.js +2 -2
  55. package/dist/modules/chain_keys.d.ts +1 -1
  56. package/dist/modules/constants.d.ts +6 -0
  57. package/dist/modules/constants.js +37 -6
  58. package/dist/modules/credit_pricing.d.ts +20 -1
  59. package/dist/modules/credit_pricing.js +23 -1
  60. package/dist/modules/credit_runtime.js +33 -16
  61. package/dist/modules/dexbot_class.d.ts +11 -1
  62. package/dist/modules/dexbot_class.js +15 -2
  63. package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
  64. package/dist/modules/dexbot_cow_runtime.js +507 -108
  65. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  66. package/dist/modules/dexbot_maintenance_runtime.js +117 -12
  67. package/dist/modules/dexbot_startup_runtime.js +7 -1
  68. package/dist/modules/graceful_shutdown.d.ts +2 -2
  69. package/dist/modules/graceful_shutdown.js +2 -2
  70. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  71. package/dist/modules/launcher/credential_daemon.js +60 -26
  72. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  73. package/dist/modules/node_manager.d.ts +1 -1
  74. package/dist/modules/node_manager.js +1 -1
  75. package/dist/modules/order/accounting.js +2 -1
  76. package/dist/modules/order/export.d.ts +2 -2
  77. package/dist/modules/order/export.js +2 -2
  78. package/dist/modules/order/grid.d.ts +26 -14
  79. package/dist/modules/order/grid.js +416 -73
  80. package/dist/modules/order/grid_reconcile.js +5 -1
  81. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  82. package/dist/modules/order/index.d.ts +22 -1
  83. package/dist/modules/order/manager.d.ts +40 -7
  84. package/dist/modules/order/manager.js +149 -23
  85. package/dist/modules/order/strategy.d.ts +5 -0
  86. package/dist/modules/order/strategy.js +44 -3
  87. package/dist/modules/order/sync_engine.d.ts +12 -1
  88. package/dist/modules/order/sync_engine.js +135 -20
  89. package/dist/modules/order/utils/math.d.ts +49 -10
  90. package/dist/modules/order/utils/math.js +71 -14
  91. package/dist/modules/order/utils/order.d.ts +65 -11
  92. package/dist/modules/order/utils/order.js +198 -28
  93. package/dist/modules/order/utils/system.d.ts +112 -2
  94. package/dist/modules/order/utils/system.js +338 -12
  95. package/dist/modules/order/utils/validate.d.ts +4 -1
  96. package/dist/modules/order/utils/validate.js +9 -2
  97. package/dist/modules/storage/index.d.ts +3 -2
  98. package/dist/modules/storage/index.js +3 -2
  99. package/dist/modules/types.d.ts +44 -2
  100. package/dist/scripts/analyze-credit.js +64 -23
  101. package/dist/scripts/bts_distribution.d.ts +66 -0
  102. package/dist/scripts/bts_distribution.js +2102 -0
  103. package/dist/scripts/token_distribution.d.ts +45 -0
  104. package/dist/scripts/token_distribution.js +1870 -0
  105. package/dist/unlock.js +42 -24
  106. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  107. package/docs/COW_INVARIANTS.md +24 -8
  108. package/docs/DEXBOT_COMPARISON.md +5 -5
  109. package/docs/EVOLUTION.md +10 -8
  110. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
  111. package/docs/GRID_PRICE_INVARIANT.md +29 -3
  112. package/docs/GRID_RECALCULATION.md +3 -3
  113. package/docs/GRID_RECONCILE.md +5 -5
  114. package/docs/LIFECYCLE.md +11 -11
  115. package/docs/LOGGING.md +22 -0
  116. package/docs/MPA_CREDIT_USAGE.md +3 -2
  117. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
  118. package/docs/README.md +1 -1
  119. package/docs/architecture.md +205 -6
  120. package/docs/developer_guide.md +12 -0
  121. package/market_adapter/README.md +11 -6
  122. package/modules/README.md +18 -14
  123. package/package.json +6 -3
  124. package/scripts/README.md +85 -148
@@ -170,9 +170,10 @@ C_i = C_total * weight_i / sum(all weights)
170
170
  ```
171
171
 
172
172
  - **MPA**: `feedPrice_i` is the current settlement feed price (collateral per debt asset), discovered from the chain and cached per position.
173
- - **Credit**: `conversionRate_i` is the offer's `acceptable_collateral` price (debt asset per collateral unit), discovered from existing deals or `allowedOfferIds`.
174
- - **Fallback chain** (every pair resolves a rate, so every CR is calculable): offer map → LP pool valuation (`pool-derived`) → universal DEX price (`market-direct`, else `market-bridge:<asset>` via bridge hops, default BTS). Only when all three fail does the group keep its existing budget with a warning and `weight = outputWeight * targetCR`.
173
+ - **Credit**: `conversionRate_i` is the live pool value for LP-share collateral (`pool-derived`); other collateral uses the offer's `acceptable_collateral` price (debt asset per collateral unit), discovered from existing deals or `allowedOfferIds`.
174
+ - **Fallback chain** (every pair resolves a rate, so every CR is calculable): LP-share collateral tries pool valuation (`pool-derived`) → offer map → universal DEX price; other collateral tries offer map → LP pool valuation → universal DEX price (`market-direct`, else `market-bridge:<asset>` via bridge hops, default BTS). Only when all three fail does the group keep its existing budget with a warning and `weight = outputWeight * targetCR`.
175
175
  - All offer-price orientation, conversion-rate, and CR math lives in `modules/credit_pricing.ts`, shared by the runtime and `dexbot credit`.
176
+ - LP-share collateral is valued at the pure pool market value: reserves/supply, with no slippage, taker fee, or withdrawal-fee deduction, matching the runtime borrow gate.
176
177
  - `outputWeight` is the user's output proportion. Equal weights produce **equal economic debt value** across all lending items, regardless of price or CR differences.
177
178
 
178
179
  ### Examples
@@ -43,7 +43,8 @@
43
43
  - 6. Consolidated invariants
44
44
  - 7. Consolidated verification — grid-correction check as regression gate
45
45
  - 8. Provenance & supersession record
46
- - 9. COW Broadcast, Resync & Geometry Safety (v1.6.4 → v1.6.14) — addendum
46
+ - 9. COW Broadcast, Resync & Geometry Safety (v1.6.4 → v1.6.17) — addendum
47
+ - 9.10 Review pass over v1.6.12 → v1.6.17 (findings P1–P5)
47
48
  - A. Grid-Price Invariant — former failure trace (appendix)
48
49
 
49
50
  ---
@@ -67,7 +68,7 @@ local state.
67
68
  |---|---|---|
68
69
  | **Orphan orders** | Live chain orders absent from local state; locked funds, accidental cancels, re-placement | Adoption, committed-order protection, durable orphan gates — fixed/re-broken repeatedly |
69
70
  | **Ghost / phantom orders** | Local slot with no real order, or a live order no slot owns; `size > 0` with no `orderId` | Virtualization guards, ghost-order cleanup, dust cancel |
70
- | **Self-trading / crossing** | Re-pricing a BUY above own SELLs (or vice versa) | `LAST-FILL-GUARD` (pivot formula revised twice) + final pre-broadcast pivot gate |
71
+ | **Self-trading / crossing** | Re-pricing a BUY above own SELLs (or vice versa) | `LAST-FILL-GUARD` (pivot formula revised **three** times — the third removed the band entirely, §9.7/§9.10) + final pre-broadcast pivot gate + an offline mirror that must BE the same predicate, not a copy of it |
71
72
  | **Grid-price invariant** | Two sources of truth for a slot price (genesis ladder vs mutable `slot.price`); orphan adoption corrupted the ladder | Enforce ladder price at every emission site; escalate persistent violations to resync |
72
73
  | **Boundary drift / gap band** | Buy/sell split index moved without matching fills, stranding live orders in the band | Prevention plans P1–P6 landed, then largely reverted; replaced by fill-driven boundary + last-fill guard |
73
74
  | **Fund-accounting races** | Stale totals, optimistic deductions, "orphan-fill death spiral" | Lag guards, tolerance widening, rebuild-from-chain, invariant escalation |
@@ -95,6 +96,11 @@ notes; the grid-price invariant has its own doc — [GRID_PRICE_INVARIANT.md](GR
95
96
  socket leaks, shutdown races, node failover. The demons were *policy* for uncertain
96
97
  state; you can restart a daemon, you can only *model* an ambiguous broadcast, and the
97
98
  model kept being wrong.
99
+ 5. **One rule, several implementations.** "A fill must not be traded through" is decided in
100
+ the runtime guard, the spread-correction planner, the rail clamp and the offline checker.
101
+ Every copy drifted on its own schedule: the planner used the crossing floor, the checker
102
+ kept the old band, the rail clamp kept the old slot ids (§9.7, §9.10). The fix that
103
+ sticks is one exported predicate and callers that re-implement nothing.
98
104
 
99
105
  ### R4. What actually fixed it
100
106
 
@@ -110,6 +116,17 @@ notes; the grid-price invariant has its own doc — [GRID_PRICE_INVARIANT.md](GR
110
116
  ambiguity — see §9.1.
111
117
  - **Fail-closed geometry (v1.6.14+):** an unknown boundary/gap is no longer coerced to a
112
118
  valid-looking `0` — see §9.1.
119
+ - **One eligibility rule (§9.10):** what may become the pivot — and therefore the absolute
120
+ geometry anchor — is decided by the same classifier the crawl uses
121
+ (`collectEdgePinnedFillIds`), so a static edge fill can never drive the geometry.
122
+ - **One validator (§9.10):** the fill re-anchor and the rail clamp both end in
123
+ `validatePersistedBoundary`, the gate the restore and commit paths already used, instead of
124
+ each path carrying its own idea of "stranded".
125
+ - **Live identity over local keys (§9.10, `531edeb4`):** every rail/geometry decision maps the
126
+ order's LIVE chain price onto the ladder; a slot id is a hint, never the fact.
127
+ - **Observability instead of a veto (§9.10/P4):** where a hard guard would re-create a
128
+ deadlock (a counter order crossing the floor by construction), log it once and let the
129
+ chain price it as a taker fill.
113
130
 
114
131
  The winning strategy was **removing writers and sources of truth**, not adding handlers.
115
132
 
@@ -124,7 +141,22 @@ The winning strategy was **removing writers and sources of truth**, not adding h
124
141
  5. Make deferred work **level-triggered** — never let a retry depend on a future event.
125
142
  6. If a fix class keeps returning, the model is wrong, not the fix.
126
143
  7. Treat **ambiguity as deferral, not destruction** — a reset that clears guard state is
127
- another writer, and `Number(null) === 0` is how "unknown" becomes a confident `0`.
144
+ another writer, and `Number(null) === 0` is how "unknown" becomes a confident `0`. The
145
+ mirror case is the same bug from the other side: if clearing guard state is a writer,
146
+ *restoring* it is one too — a pivot that a rebuild silently re-arms (or silently keeps)
147
+ is a guard whose lifetime nobody decided (§9.10/P2).
148
+ 8. **A guard needs a lifetime, not just a predicate.** Which price is the reference, how
149
+ long it stays valid, who re-arms it after a rebuild, and what happens when the grid it was
150
+ armed against no longer exists are all part of the rule. A predicate that is correct and
151
+ an arming policy that is accidental is still a broken guard.
152
+ 9. **Eligibility must be defined once.** "What counts as a real fill" (edge insurance?
153
+ partial? off-ladder price?) cannot be answered separately by the crawl, the pivot and the
154
+ anchor; the first divergence is a window teleport (§9.10/P1).
155
+ 10. **Bound a repair by the evidence that justifies it.** The rail clamp may move the boundary
156
+ only inside the window the batch itself placed into — strays do not vote (§9.10/P3). A
157
+ repair that can cite one stray order is not a repair.
158
+ 11. **When a veto would deadlock, ship the observation.** A taker-fee risk earns a log line,
159
+ not a rule that re-creates the deadlock the previous fix removed (§9.10/P4).
128
160
 
129
161
  ---
130
162
 
@@ -149,9 +181,9 @@ plans, `LANDED`/`REVERTED`/`SUPERSEDED` statuses, commit hashes, and verificatio
149
181
 
150
182
  **Naming:** instance/order IDs are genericized (`bot-A` = grid bot, `bot-B`/`bot-C` = credit bots, `bot-D/D2` = grid bots; `<order-N>` = `1.7.x`). Same token = same order within a section. Market pairs are genericized as `<pair>`; account names `1.2.x` placeholders.
151
183
 
152
- **Grid terms:** `boundary` = discrete sell/buy split index; `gap band` = `SPREAD/virtual` slots around boundary; `sellStartIdx = splitIdx - floor(gap/2) - 1`; center-priced ladder `createOrderGrid` = `startPrice × step^(k+½)` (`modules/order/grid.ts:441,449`); `MarketAnchor` = fill-derived `lastFillPrice/maxFilledSellPrice/minFilledBuyPrice/lastFillSide`; tolerance helpers `calculatePriceTolerance = (1/satsA+1/satsB)×price` (`modules/order/utils/math.ts:820-824`), `PRICE_TOLERANCE_MAX_PERCENT 0.01` (`constants.ts:461`).
184
+ **Grid terms:** `boundary` = discrete sell/buy split index; `gap band` = `SPREAD/virtual` slots around boundary; `sellStartIdx = splitIdx - floor(gap/2) - 1`; center-priced ladder `createOrderGrid` = `startPrice × step^(k+½)` (`modules/order/grid.ts`); `MarketAnchor` = fill-derived `lastFillPrice/maxFilledSellPrice/minFilledBuyPrice/lastFillSide`; tolerance helpers `calculatePriceTolerance = (1/satsA+1/satsB)×price` (`modules/order/utils/math.ts`), `GRID_LIMITS.PRICE_TOLERANCE_MAX_PERCENT 0.01` (`modules/constants.ts`).
153
185
 
154
- **Validation tool:** `analysis/grid_correction_check.ts` (test-only, mirrors `analysis/trade_profitability.ts` Kibana path `https://kibana.bitshares.dev`, `bitshares-*`, `operation_type:4` `fill_order` only; `buildFillQuery`, paginated `search_after`, `_source` `block_data` fields). **Invariants:** `sell→sell` with no `buy` between must rise (`curr > prev`, equal OK), `buy→buy` must fall (`curr < prev`); `per-order` aggregated default (weighted avg collapses multi-fill `1.7.x`), `--per-fill` raw. Resolution via `bot_key_utils.ts` `loadBotMeta/computeBotKey`. Reports violations, `%`, daily histogram, time/range, table with price/Δ%/times/orderIds; `--json/--csv` export; exit `0` pass / `2` fail. Strict sat-level is ground truth (`--tolerance P` allows `b < a*(1-P/100)` sell / `b > a*(1+P/100)` buy). Used as regression gate below; pre-fix per-account baselines are intentionally omitted here — §7 states the targets (`0` violations).
186
+ **Validation tool:** `analysis/grid_correction_check.ts` (test-only, mirrors `analysis/trade_profitability.ts` Kibana path `https://kibana.bitshares.dev`, `bitshares-*`, `operation_type:4` `fill_order` only; `buildFillQuery`, paginated `search_after`, `_source` `block_data` fields). **Invariants:** `sell→sell` with no `buy` between must rise (`curr > prev`, **equal is a violation** — a re-place at the just-filled level), `buy→buy` must fall (`curr < prev`); `per-order` aggregated default (weighted avg collapses multi-fill `1.7.x`), `--per-fill` raw. Resolution via `bot_key_utils.ts` `loadBotMeta/computeBotKey`. Reports violations, `%`, daily histogram, time/range, table with price/Δ%/times/orderIds; `--json/--csv` export; exit `0` pass / `2` fail. Strict sat-level is ground truth — the verdict is **direction only** (equal price is a violation); `--increment` is **informational only** (the band the removed `--tolerance` flag used to express is gone, §9.10/P5). Used as regression gate below; pre-fix per-account baselines are intentionally omitted here — §7 states the targets (`0` violations).
155
187
 
156
188
  ---
157
189
 
@@ -162,9 +194,9 @@ plans, `LANDED`/`REVERTED`/`SUPERSEDED` statuses, commit hashes, and verificatio
162
194
  **Landing map (corrected 2026-08-31):**
163
195
  - **P1** — landed `f94d6ec4` (same-batch CANCEL injection in `COWRebalanceEngine.execute` + `_assertGapBandIntactPostCommit` cancelOnly). **REVERTED `e2898e51`** ("remove placement guards that interfered with normal operation") — both sites removed; stranding is now handled by `calculateIdealBoundary` + `LAST-FILL-GUARD` + adoption path (P3 gate removed `e7231534`).
164
196
  - **P2** — landed `f94d6ec4`; **REVERTED `3713c496`** after a live-bot incident (the sweep cancelled two legitimate boundary buys under a stale boundary). In-gap chain orders are now *adopted* by the normal reconcile path once the boundary is re-derived via `calculateIdealBoundary`; cancellation is never used as a self-healing net.
165
- - **P3** — landed `f94d6ec4` (`validateBoundaryAgainstChainEvidence` + reconcile phase-1 gate + `placementsAllowed` adoption-only mode); amended `3713c496` (anchor demoted to non-authoritative hint, can never veto); extended `a54863ca` (NO_FEASIBLE escalates a straddle-cancel ladder instead of freezing). **REVERTED `e7231534`** — `validateBoundaryAgainstChainEvidence` (`grid_reconcile.ts:359`) and `placementsAllowed` (`grid_reconcile_internal.ts:1601`) removed; **current** boundary derives from `calculateIdealBoundary` (`order/utils/order.ts:1216` via `grid.ts:160`) + `LAST-FILL-GUARD` (`manager.ts:1679`/`dexbot_cow_runtime.ts:1624`), not a P3 chain-evidence gate.
166
- - **P4** — landed `f94d6ec4` (`dexbot_state_recovery.ts:581 rejectCorruptedGridSnapshot` clears in-memory + persisted boundary on reject). Live.
167
- - **P5** — landed `f94d6ec4` (skip/defer logging + `STRUCTURAL_RESYNC_MAX_DEFER_MS` force, `dexbot_maintenance_runtime.ts:2242-2266`). Live.
197
+ - **P3** — landed `f94d6ec4` (`validateBoundaryAgainstChainEvidence` + reconcile phase-1 gate + `placementsAllowed` adoption-only mode); amended `3713c496` (anchor demoted to non-authoritative hint, can never veto); extended `a54863ca` (NO_FEASIBLE escalates a straddle-cancel ladder instead of freezing). **REVERTED `e7231534`** — `validateBoundaryAgainstChainEvidence` (`grid_reconcile.ts`) and `placementsAllowed` (`grid_reconcile_internal.ts`) removed; **current** boundary derives from `calculateIdealBoundary` (`order/utils/order.ts` via `grid.ts`) + `LAST-FILL-GUARD` (`manager.ts`/`dexbot_cow_runtime.ts`), not a P3 chain-evidence gate.
198
+ - **P4** — landed `f94d6ec4` (`dexbot_state_recovery.ts` `rejectCorruptedGridSnapshot` clears in-memory + persisted boundary on reject). Live.
199
+ - **P5** — landed `f94d6ec4` (skip/defer logging + `STRUCTURAL_RESYNC_MAX_DEFER_MS` force, `dexbot_maintenance_runtime.ts`). Live.
168
200
  - **P6** — landed `f94d6ec4` (2026-08-29) as boundary chain-evidence regression coverage, since superseded by the boundary-geometry suite (`tests/test_boundary_anchor_recovery.ts`, `tests/test_boundary_restore_validation.ts`) and the slot-invariant guard tests.
169
201
 
170
202
  #### 1.1 Incident summary
@@ -255,7 +287,7 @@ Falling market Aug 28 after ~17:00 UTC: bot **placed new SELLs below own live se
255
287
 
256
288
  **Mode C — COW commit geometry (separate).** Attribution corrected: `Batch transaction failed: Execution error: Order does not exist … cannot update` confirmed post-commit on bot-B: `<order-4>` `00:28:51 chunk1/3`, `<order-5>` `06:43:09 chunk5/9`, `<order-6>` `00:29:30` (`limit_order_update delta=-2341206 targets missing`). Broadcast refs missing orderId, aborts partial grid. `GAP-BAND VIOLATION after commit` = 0 in post-commit bot-A/B/C logs (evidence is bot-D `4` + D2 `11` dated Aug 26/28/29). Need: (a) COW rejects placement inside gap pre-broadcast; (b) pre-broadcast existence check off slot→orderId map. Gap case hardening independent. **Status: (b) LANDED `552b3ed7` (v1.6.14) as `UPDATE_TARGET_MISSING`; (a) deliberately shipped as a non-gating shadow (`gapBandPlacementShadowCount`) — see §9.2.**
257
289
 
258
- **Mode D — boundary-evidence re-derivation not persisted (freeze).** `grid_reconcile.ts:359-502` re-derives corrected boundary via `manager._restoreBoundary (:380)` but didn't survive next resync; bot-A re-derived at *every* hourly resync: `117→118 (00:28:48)`, `118→119 (01:00)`, `118→115 (02:00)`, `118→114 (03:00,04:00)`, `118→115 (04:30,05:00)`, `122→119 (07:00)` — 8× identical `ERROR` in ~7h. Bot-C `NO_FEASIBLE_BOUNDARY` → adoption-only at `00:27:17, 00:31:12, 04:27:48`; after `04:27:48` placed **zero orders 04:27:48→07:15:27 (~2h48m)** — only fills + `[ORPHAN-FILL]`. Earlier freeze `00:31→00:54`. Resumed only via fill-driven rotation `07:15`. → Fix #5 (LANDED).
290
+ **Mode D — boundary-evidence re-derivation not persisted (freeze).** `grid_reconcile.ts` re-derives corrected boundary via `manager._restoreBoundary` but didn't survive next resync; bot-A re-derived at *every* hourly resync: `117→118 (00:28:48)`, `118→119 (01:00)`, `118→115 (02:00)`, `118→114 (03:00,04:00)`, `118→115 (04:30,05:00)`, `122→119 (07:00)` — 8× identical `ERROR` in ~7h. Bot-C `NO_FEASIBLE_BOUNDARY` → adoption-only at `00:27:17, 00:31:12, 04:27:48`; after `04:27:48` placed **zero orders 04:27:48→07:15:27 (~2h48m)** — only fills + `[ORPHAN-FILL]`. Earlier freeze `00:31→00:54`. Resumed only via fill-driven rotation `07:15`. → Fix #5 (LANDED).
259
291
 
260
292
  **Post-commit hardening (§2.3 sub):** (1) lagging-node read-back thrash bot-B `06:43:09–06:47:09` after chunk5/9 fail — fresh CREATEs absent (`<order-7> likely lagging node`), protection piled to 14, all CREATEs rejected, 30s cap forced resync mid-broadcast ~4 min/24 events; (2) sync lock `timed out after 20000ms` + `[SYNC] abandoned force-released 69355ms` (~70s lost), bot-C ~110 `Structural resync defer` warnings at 250 ms/30s; (3) `[MAINT] n/m price correction(s) failed` ratios `2/3,2/2,1/8,2/25,1/23,1/14` — stale slot maps.
261
293
 
@@ -280,12 +312,12 @@ Falling market Aug 28 after ~17:00 UTC: bot **placed new SELLs below own live se
280
312
 
281
313
  #### 2.5 Root-cause chain (code refs)
282
314
 
283
- 1. Ladder quantized to center. 2. Recovery resyncs re-anchor via two config points (see Fix #1). 3. Tolerance rounding-scale `≈0.036` at 1110 vs AMA shift `0.045%` → `~0.5` shift = 15× tolerance → pass-1 + pass-2 adoption (`sync_engine.ts:146-156,:1040-1060`) reject. 4. `PRICE_DRIFT_TOLERANCE_MULTIPLIER 4` (`constants.ts:557`) → budget 0.144 < 0.43 diff → no `price-drift-orphan` → only logged (`dexbot_maintenance_runtime.ts:1311-1317`). 5. Regenerated ladder sell rail below orphans → self-undercut; `maxFilledSellPrice/minFilledBuyPrice` built from grid-tracked fills only → guard unenforceable once orphans unmanaged; orphans later fill outside accounting.
315
+ 1. Ladder quantized to center. 2. Recovery resyncs re-anchor via two config points (see Fix #1). 3. Tolerance rounding-scale `≈0.036` at 1110 vs AMA shift `0.045%` → `~0.5` shift = 15× tolerance → pass-1 + pass-2 adoption (`sync_engine.ts`) reject. 4. `PRICE_DRIFT_TOLERANCE_MULTIPLIER 4` (`constants.ts`) → budget 0.144 < 0.43 diff → no `price-drift-orphan` → only logged (`dexbot_maintenance_runtime.ts`). 5. Regenerated ladder sell rail below orphans → self-undercut; `maxFilledSellPrice/minFilledBuyPrice` built from grid-tracked fills only → guard unenforceable once orphans unmanaged; orphans later fill outside accounting.
284
316
 
285
317
  #### 2.6 Ranked fixes (with 2026-08-30 landed status)
286
318
 
287
319
  **#1 Stop re-anchoring on recovery resyncs (two config points, highest leverage) — LANDED 2026-08-30 (`4838bcb0`).**
288
- `rms_structural_grid_resync` → both flipped: (`dexbot_maintenance_runtime.ts:2327` `requestGridReset` call, hardcoded `refreshCenterPrice:false`) + (`:102` `GRID_RESYNC_REASONS.rms_structural_grid_resync.shouldRefreshCenterPrice: false`, covers the `buildGridResyncOptions('rms_structural_grid_resync')` call sites at `:1710-1712`). Structural resync keeps geometry; re-anchor only on manual/trigger-file and `GRID_RESYNC_REASONS` market-adapter delta/slope/bootstrap — intentionally stay `true`. `requestGridReset` default `TRUE` (`:2194`) so manual resets still re-anchor. Risk if center moved: geometry briefly mispriced but managed vs orphaning.
320
+ `rms_structural_grid_resync` → both flipped: (`dexbot_maintenance_runtime.ts` `requestGridReset` call, hardcoded `refreshCenterPrice:false`) + (`GRID_RESYNC_REASONS.rms_structural_grid_resync.shouldRefreshCenterPrice: false`, covers the `buildGridResyncOptions('rms_structural_grid_resync')` call sites). Structural resync keeps geometry; re-anchor only on manual/trigger-file and `GRID_RESYNC_REASONS` market-adapter delta/slope/bootstrap — intentionally stay `true`. `requestGridReset` default `TRUE` (its `refreshCenterPrice` default) so manual resets still re-anchor. Risk if center moved: geometry briefly mispriced but managed vs orphaning.
289
321
 
290
322
  **#2 Regeneration must preserve order identity (defense-in-depth) — LANDED bounded 4×.**
291
323
  `recalculateGrid` after `initializeGrid` adopts `chainOpenOrders` into nearest slots at chain price before reconcile; alt widen pass-2 fallback to ~0.25 step for VIRTUAL only. `ORPHAN_ADOPTION_TOLERANCE_MULTIPLIER 4` (`constants.ts` GRID_LIMITS) → 0.144 at 1110 (~¼ step); bot-D diffs 0.43–0.57 beyond band — coherent layering: #1 removes large diffs, residual → #3 surplus cancel. Also pre-empts `price-drift-orphan` on empty slots. Invariant: resync (incl. startup reconcile) never leaves live order unmanaged. Also covers startup reconcile (bot-A `<order-8>` 06:42→07:00 adopted to slot-140 still `Unmatched`; `<order-9>` re-adopted 6× 01:00–05:00 then `06:42:15 ORPHAN-FILL`).
@@ -297,10 +329,10 @@ Original force-cancel regressed reset path (fresh grid no ACTIVE bindings → ca
297
329
  Debug line: `[BOUNDARY] boundary=123 sellStart=128 spread=4 anchorProjected=138 maxFilledSell=1044.79` on role/placement — makes Mode B diagnosable.
298
330
 
299
331
  **#5 Persist boundary-evidence + define NO_FEASIBLE recovery (Mode D, high impact) — LANDED 2026-08-30 (`4838bcb0`), extended `a54863ca`.**
300
- (a) Persistence: `recalculateGrid` persists the reconciled grid after reconcile, so the `manager._restoreBoundary` re-derivation (`grid_reconcile.ts:380`) survives to the next cycle. After fix: `[BOUNDARY-EVIDENCE]` contradiction fires at most once per stale boundary. (b) NO_FEASIBLE: bounded periodic re-validation (5min cooldown, 20 attempts) landed with `4838bcb0`; `a54863ca` went further — the validator enumerates straddling orders (`conflictingBuyIds/conflictingSellIds`) and the reconcile escalates a cancel ladder (smaller single side → other side → both, `grid_reconcile.ts:417-444`), re-derives the boundary and proceeds with placements; the adoption-only freeze remains only as a defensive fallback.
332
+ (a) Persistence: `recalculateGrid` persists the reconciled grid after reconcile, so the `manager._restoreBoundary` re-derivation (`grid_reconcile.ts`) survives to the next cycle. After fix: `[BOUNDARY-EVIDENCE]` contradiction fires at most once per stale boundary. (b) NO_FEASIBLE: bounded periodic re-validation (5min cooldown, 20 attempts) landed with `4838bcb0`; `a54863ca` went further — the validator enumerates straddling orders (`conflictingBuyIds/conflictingSellIds`) and the reconcile escalates a cancel ladder (smaller single side → other side → both, `grid_reconcile.ts`), re-derives the boundary and proceeds with placements; the adoption-only freeze remains only as a defensive fallback.
301
333
 
302
334
  **#6 Retry/backoff post-broadcast adoption read-back — LANDED (cooldown `4838bcb0` + retry `d808c052`).**
303
- `deferUncertainBroadcastRead` (`dexbot_cow_runtime.ts:301`) 30s escalation cooldown bounds thrash; `adoptPlacedBatchFromChain` retries lagging/failed by-id reads (3 attempts, 2s/4s backoff) before deferring with pending-broadcast protection kept. Cross-node failover remains open.
335
+ `deferUncertainBroadcastRead` (`dexbot_cow_runtime.ts`) 30s escalation cooldown bounds thrash; `adoptPlacedBatchFromChain` retries lagging/failed by-id reads (3 attempts, 2s/4s backoff) before deferring with pending-broadcast protection kept. Cross-node failover remains open.
304
336
 
305
337
  **#7 Sync-lock/maintenance observability — LANDED.**
306
338
  Throttle `Structural resync defer` to first/last per cap window (was 120/30s); log/retry `[MAINT] n/m failed` with orderId/reason.
@@ -328,27 +360,27 @@ Slot-90 loop is *proximate* form; rotation suppression is mechanism, cascade is
328
360
 
329
361
  #### 3.2 Full picture
330
362
 
331
- **Step 1 — Race:** ~`17:40:39–51` market moved fast, buys filled, boundary crawled down, sells `<order-1>…<order-4>`, `<order-5>`, `<order-6>…<order-10>`. `_batchInFlight` serializes fill consumer but planning+broadcast not atomic with master commit: Batch A broadcasts `<order-1>…<order-4>,<order-5>` at `17:40:39`; Batch B plans stale, places `<order-6>/<order-7>` at same prices (`17:40:42 a COW broadcast is already in flight; deferring`), commit refused `17:40:51.237 [COW] Refusing stale working grid commit: master mutation during rebalancing` (now `utils/validate.ts:1102`), adoption `Orphaned chain order … duplicates price level of active slot-88` (`sync_engine.ts:906`).
363
+ **Step 1 — Race:** ~`17:40:39–51` market moved fast, buys filled, boundary crawled down, sells `<order-1>…<order-4>`, `<order-5>`, `<order-6>…<order-10>`. `_batchInFlight` serializes fill consumer but planning+broadcast not atomic with master commit: Batch A broadcasts `<order-1>…<order-4>,<order-5>` at `17:40:39`; Batch B plans stale, places `<order-6>/<order-7>` at same prices (`17:40:42 a COW broadcast is already in flight; deferring`), commit refused `17:40:51.237 [COW] Refusing stale working grid commit: master mutation during rebalancing` (now `utils/validate.ts`), adoption `Orphaned chain order … duplicates price level of active slot-88` (`sync_engine.ts`).
332
364
 
333
- **Step 2 — Refused → invariant:** Fresh sells not recorded, adoption `adoptPlacedBatchFromChain` (`dexbot_cow_runtime.ts:3364`) capped window drops freshest (`chain_orders.ts:573-638`), adoption lossy `<order-6> NOT adopted / <order-9>→slot-106 / <order-10>→slot-107`, collides with re-plan `Rejecting CREATE for slot-105/106 existing orderId=<order-8>/<order-9>` (`17:40:51.335`). Fund recalc `CRITICAL: Fund invariant violation (SELL): blockchainTotal (474877) != trackedTotal (473173) diff:1703.62 allowed:474.87`.
365
+ **Step 2 — Refused → invariant:** Fresh sells not recorded, adoption `adoptPlacedBatchFromChain` (`dexbot_cow_runtime.ts`) capped window drops freshest (`chain_orders.ts`), adoption lossy `<order-6> NOT adopted / <order-9>→slot-106 / <order-10>→slot-107`, collides with re-plan `Rejecting CREATE for slot-105/106 existing orderId=<order-8>/<order-9>` (`17:40:51.335`). Fund recalc `CRITICAL: Fund invariant violation (SELL): blockchainTotal (474877) != trackedTotal (473173) diff:1703.62 allowed:474.87`.
334
366
 
335
367
  **Step 3 — Recovery:** `Fund invariant → state recovery (1/5)` → `Restored boundary 82` → `[SNAPSHOT-REJECT] drift sell=1703.62 — Deleting snapshot` → `Synchronization from 40 blockchain orders — TRUNCATED: 42 live, 40 read` → regeneration matches `165→91,167→108,168→110` but `169,174` never matched (dropped).
336
368
 
337
369
  **Step 4 — ORPHAN-FILL:** `17:57:18 WARN [ORPHAN-FILL] Processing funds for unknown order <order-10>/<order-9> (not in grid but crediting proceeds)` — no slot virtualized → more violations → Aug 29 stale boundary `90` (`Restored boundary index: 90`).
338
370
 
339
- **Step 5 — Rotation same-slot:** `15:19:06` partial fill `<order-11>` slot-90 dust `2.92`, dust detection cancelled the residual, synthesizing a fill with `skipBoundaryShift:true` (removed `1b27f6eb`; defensive check removed this commit — `order/utils/order.ts` and `manager.ts` no longer inspect `skipBoundaryShift`; reintroduction would silently restore the same-slot fill loop) → `isShiftEligibleFill` false → boundary crawl suppressed. `processFilledOrders` only rebalances non-partial (`manager.ts:1460`) but synthetic `isDelayedRotationTrigger` forces rebalance with boundary frozen → slot-90 stays `BUY` → `Placed buy slot-90 -> <order-12>` `15:19:15` → `FILL DETECTED slot-90` `15:19:39`. Boundary detached (`projected=72 drift -18`, `PROJECTION_ENABLED false` `constants.ts:729`; the projection override itself was removed `3713c496`) → buy above market re-fills. Root fix: filled buy should rotate (SELL or bottom BUY), not re-stamp same price — LANDED `1b27f6eb`.
371
+ **Step 5 — Rotation same-slot:** `15:19:06` partial fill `<order-11>` slot-90 dust `2.92`, dust detection cancelled the residual, synthesizing a fill with `skipBoundaryShift:true` (removed `1b27f6eb`; defensive check removed this commit — `order/utils/order.ts` and `manager.ts` no longer inspect `skipBoundaryShift`; reintroduction would silently restore the same-slot fill loop) → `isShiftEligibleFill` false → boundary crawl suppressed. `processFilledOrders` only rebalances non-partial (`manager.ts`) but synthetic `isDelayedRotationTrigger` forces rebalance with boundary frozen → slot-90 stays `BUY` → `Placed buy slot-90 -> <order-12>` `15:19:15` → `FILL DETECTED slot-90` `15:19:39`. Boundary detached (`projected=72 drift -18`, `PROJECTION_ENABLED false`; the projection override itself was removed `3713c496`, and the constant was deleted with the anchor in `e7231534`) → buy above market re-fills. Root fix: filled buy should rotate (SELL or bottom BUY), not re-stamp same price — LANDED `1b27f6eb`.
340
372
 
341
373
  #### 3.3 Fix plan (layered; statuses corrected against HEAD — see §3 header)
342
374
 
343
- **P0 Reliable ID-based adoption after refused commit — LANDED `1b27f6eb` (hardened `d808c052`).** Kills orphan/invariant at source: `adoptPlacedBatchFromChain` builds `collectKnownOnChainOrderIds(mgr, placedResults, placedContexts)` (`dexbot_cow_runtime.ts:3281,3364`) = `mgr.grid[*].orderId ∪ fresh CREATE ids from `extractBatchOperationResults(result)[i][1]`↔`executedContexts[i]` (`:3293`); re-read by ID `chainOrders.batchReadOrders (chain_orders.ts:530)` → `syncFromOpenOrders(fullChain, {skipAccounting:false})`; lagging-node deferral: if ANY fresh CREATE id `null` → defer (`return false`) keep protection (later read adopts), by-id error → defer (no fallback to window); absent master ids = expected. `d808c052` added a retry (3 attempts, 2s/4s backoff) before deferring. Window read remains fallback only and defers on `truncated`.
375
+ **P0 Reliable ID-based adoption after refused commit — LANDED `1b27f6eb` (hardened `d808c052`).** Kills orphan/invariant at source: `adoptPlacedBatchFromChain` builds `collectKnownOnChainOrderIds(mgr, placedResults, placedContexts)` (`dexbot_cow_runtime.ts`) = `mgr.grid[*].orderId ∪ fresh CREATE ids from `extractBatchOperationResults(result)[i][1]`↔`executedContexts[i]`); re-read by ID `chainOrders.batchReadOrders (chain_orders.ts)` → `syncFromOpenOrders(fullChain, {skipAccounting:false})`; lagging-node deferral: if ANY fresh CREATE id `null` → defer (`return false`) keep protection (later read adopts), by-id error → defer (no fallback to window); absent master ids = expected. `d808c052` added a retry (3 attempts, 2s/4s backoff) before deferring. Window read remains fallback only and defers on `truncated`.
344
376
 
345
- **P0 Recovery must not lose orders when snapshot deleted — LANDED `1b27f6eb`.** `recoverFromPersistedGrid` (`dexbot_state_recovery.ts:314`) on truncated window falls back to `batchReadOrders` over `persistedGrid[*].orderId` (recovers bot's own incl. ID-adopted creates now persisted), without virtualizing ACTIVE; cannot discover brand-new orphans (prevented above); with no known ids still defers. Intentionally lossy for unenumeratable = reconcile virtualize-as-filled acceptable here; adoption path hard-defers.
377
+ **P0 Recovery must not lose orders when snapshot deleted — LANDED `1b27f6eb`.** `recoverFromPersistedGrid` (`dexbot_state_recovery.ts`) on truncated window falls back to `batchReadOrders` over `persistedGrid[*].orderId` (recovers bot's own incl. ID-adopted creates now persisted), without virtualizing ACTIVE; cannot discover brand-new orphans (prevented above); with no known ids still defers. Intentionally lossy for unenumeratable = reconcile virtualize-as-filled acceptable here; adoption path hard-defers.
346
378
 
347
- **P1 Atomic plan→broadcast→commit — PARTIAL.** Landed pieces: `restoreBoundaryAfterAdoption` re-applies the batch's shifted boundary immediately after by-id adoption (`1b27f6eb`); Phase-2 reconcile wrapped in a refcounted broadcast flag with `_awaitBroadcastIdle` deferral (`d808c052`); stale-commit refusal lives at `utils/validate.ts:1102`. Still open: full re-plan from fresh master after winning `waitForCowBroadcastSingleFlight` + a COW-plan mutex covering the entire plan→broadcast→commit; dust-cancel `checkGridHealth` waits.
379
+ **P1 Atomic plan→broadcast→commit — PARTIAL.** Landed pieces: `restoreBoundaryAfterAdoption` re-applies the batch's shifted boundary immediately after by-id adoption (`1b27f6eb`); Phase-2 reconcile wrapped in a refcounted broadcast flag with `_awaitBroadcastIdle` deferral (`d808c052`); stale-commit refusal lives at `utils/validate.ts`. Still open: full re-plan from fresh master after winning `waitForCowBroadcastSingleFlight` + a COW-plan mutex covering the entire plan→broadcast→commit; dust-cancel `checkGridHealth` waits.
348
380
 
349
- **P1 Rotation same-slot — LANDED core (`1b27f6eb`); sub-fixes superseded.** (1) `skipBoundaryShift:true` removed from both dust synthetic fills (was `dexbot_maintenance_runtime.ts:1821/:1826`) — dust fills are shift-eligible again; regression guard `tests/test_rotation_no_same_slot.ts` now 4 cases (ROT-4 same-slot loop case removed this commit, guard deleted); no defensive `skipBoundaryShift` check remains (`order/utils/order.ts` + `manager.ts` removed). Reintroduction of the flag would silently restore the same-slot fill loop. (2) moot — dust fills now trigger the crawl naturally. (3) SUPERSEDED — the Phase-2 projection override was removed entirely (`3713c496`); `ANCHOR.PROJECTION_ENABLED` (`constants.ts:729`) is an unused constant. (4) SUPERSEDED — the `d808c052` anchor-refill/price-sanity guard extensions were removed `e2898e51`; the original `calculateTargetGrid` fill-range rotation (`strategy.ts:345-369`) remains.
381
+ **P1 Rotation same-slot — LANDED core (`1b27f6eb`); sub-fixes superseded.** (1) `skipBoundaryShift:true` removed from both dust synthetic fills (was `dexbot_maintenance_runtime.ts`) — dust fills are shift-eligible again; regression guard `tests/test_rotation_no_same_slot.ts` now 4 cases (ROT-4 same-slot loop case removed this commit, guard deleted); no defensive `skipBoundaryShift` check remains (`order/utils/order.ts` + `manager.ts` removed). Reintroduction of the flag would silently restore the same-slot fill loop. (2) moot — dust fills now trigger the crawl naturally. (3) SUPERSEDED — the Phase-2 projection override was removed entirely (`3713c496`); `ANCHOR.PROJECTION_ENABLED` no longer exists at all — it was deleted with the anchor in `e7231534`, so it is not merely an unused constant. (4) SUPERSEDED — the `d808c052` anchor-refill/price-sanity guard extensions were removed `e2898e51`; the original `calculateTargetGrid` fill-range rotation (`strategy.ts`) remains.
350
382
 
351
- **P1 Duplicate-orphan cancellation reliable — OPEN (partially mitigated).** Verify `queueCorrection` cancelOnly (`sync_engine.ts:913`) executes, not blocked by in-flight; hard error if cannot cancel. `d808c052` mitigates the consequences (unknown-fill adoption-before-credit + empty-read guard) but the explicit verify/hard-error behavior is still open.
383
+ **P1 Duplicate-orphan cancellation reliable — OPEN (partially mitigated).** Verify `queueCorrection` cancelOnly (`sync_engine.ts`) executes, not blocked by in-flight; hard error if cannot cancel. `d808c052` mitigates the consequences (unknown-fill adoption-before-credit + empty-read guard) but the explicit verify/hard-error behavior is still open.
352
384
 
353
385
  **P2 Observability — PARTIAL (counters landed 2026-09-13).** `d808c052` added anchor price-outlier rejection with rate-limited warns (that warn surface was later removed `e2898e51`). Since then the GRID-PRICE-INVARIANT guard added per-batch/per-site emitted-price counters and **blocks** an off-grid emission (`[GRID-PRICE-INVARIANT] site=<site> checked=N violated=M unchecked=K`, six emission sites) and a `pivotSlot=`/`pivotOffGrid=true` marker plus a numeric `pivotOffGrid=<n>` per-action count on the LAST-FILL-GUARD batch summary (the count says how many guarded probes used an unsnapped pivot) — see `docs/GRID_PRICE_INVARIANT.md`. Two self-healing escalations now sit on top of those counters: a slot rejected off-grid for
354
386
  `GRID_PRICE_INVARIANT_RESYNC_THRESHOLD` (3) **consecutive** batches escalates to the structural resync
@@ -382,7 +414,7 @@ All eight surface through `getMetrics()`; the five baseline counters via the exi
382
414
 
383
415
  #### 3.4 Key code references (from source table)
384
416
 
385
- `dexbot_cow_runtime.ts:3281,3364` by-id adoption (`collectKnownOnChainOrderIds`/`adoptPlacedBatchFromChain`); `:3293` placed IDs from broadcast result; stale-commit refusal `utils/validate.ts:1102`; `sync_engine.ts:906-913` duplicate skip + `queueCorrection`; `chain_orders.ts:573-638` truncation cap; `:503 readSingleOrder, :530 batchReadOrders` immune; `dexbot_state_recovery.ts:314,581` recovery/reject; `dexbot_maintenance_runtime.ts:806 performGridResync`; `order/utils/order.ts:1560-1561` `isShiftEligibleFill`; `strategy.ts:345-369` fill-range rotation guard; `constants.ts:729` `PROJECTION_ENABLED` (unused since `3713c496`); `<bot>.log 15:19:06→39` slot-90 loop.
417
+ `dexbot_cow_runtime.ts` by-id adoption (`collectKnownOnChainOrderIds`/`adoptPlacedBatchFromChain`); placed IDs from broadcast result (`extractBatchOperationResults` ↔ `executedContexts`); stale-commit refusal `utils/validate.ts` (`evaluateCommit`); `sync_engine.ts` duplicate skip + `queueCorrection`; `chain_orders.ts` truncation cap (`readOpenOrdersGuarded`); `readSingleOrder` / `batchReadOrders` immune (by-id reads); `dexbot_state_recovery.ts` recovery/reject; `dexbot_maintenance_runtime.ts` (`performGridResync`); `order/utils/order.ts` (`isShiftEligibleFill`); `strategy.ts` fill-range rotation guard; `PROJECTION_ENABLED` (unused since `3713c496`, deleted `e7231534`); `<bot>.log 15:19:06→39` slot-90 loop.
386
418
 
387
419
  ---
388
420
 
@@ -423,7 +455,7 @@ In-memory `marketAnchor` on manager (`dexbot_fill_runtime.ts`) `lastFillPrice/ma
423
455
 
424
456
  *Status: SUPERSEDED — landed `1bbf1a23` (flag on), REMOVED `3713c496`.*
425
457
  Pure `projectAnchorToGrid(anchor, allSlots, gapSlots)` via `computePriceAnchoredBoundaryTarget` (`order/utils/order.ts`), gap centered on traded range + I4 ceiling; `calculateTargetGrid` (`strategy.ts`): `boundaryIdx = anchorFresh ? project(...) : legacyDeriveTargetBoundary(...)` gated `projectionEnabled` (D3); fund floor D1 at most ½ window (`syncBoundaryToFunds/calculateFundDrivenBoundary` `utils/system.ts`); placement guard unchanged as enforcement I1; stale-anchor continues from last range decayed to AMA center (not fall back to crawl). Gate: suite green flag on/off + property harness random bursts/re-plans/replays/empty-book all I1–I6; flip per-bot start smaller, 48h soak watcher `ANCHOR-DIVERGENCE`/`PLACEMENT-GUARD`/fund friction. **Done = incident class closed, rollback = flag flip.**
426
- **Post-mortem (`3713c496`):** the projection override plus the anchor's veto role let a fresh fill-anchor override chain evidence under a stale boundary, and the gap-band sweep then cancelled legitimate orders. Removed: the `projectionEnabled` gating, the `projectAnchorToGrid` boundary override, and the fund-floor pull in `calculateTargetGrid`. `strategy.ts:232-236` records the decision — the anchor is shadow telemetry only (`[ANCHOR-DIVERGENCE]`/`[ANCHOR-STALE]`). The original fill-range rotation guard remains at `strategy.ts:345-369`; the `d808c052` price-sanity/anchor-refill guard extensions were removed `e2898e51`.
458
+ **Post-mortem (`3713c496`):** the projection override plus the anchor's veto role let a fresh fill-anchor override chain evidence under a stale boundary, and the gap-band sweep then cancelled legitimate orders. Removed: the `projectionEnabled` gating, the `projectAnchorToGrid` boundary override, and the fund-floor pull in `calculateTargetGrid`. `strategy.ts` records the decision — the anchor is shadow telemetry only (`[ANCHOR-DIVERGENCE]`/`[ANCHOR-STALE]`). The original fill-range rotation guard remains at `strategy.ts`; the `d808c052` price-sanity/anchor-refill guard extensions were removed `e2898e51`.
427
459
 
428
460
  #### 4.7 Phase 3 — Conditional deletion
429
461
 
@@ -468,7 +500,7 @@ Goal (Phase 2): I1–I6 property pass, full suite green, harness random, 48h per
468
500
 
469
501
  - **Gap-band (amended `3713c496`/`e2898e51`; **P3 reverted `e7231534`**):** in-gap chain orders are never cancelled as a self-healing net; they are adopted by the normal reconcile path once the boundary is re-derived via `calculateIdealBoundary` (P3 `validateBoundaryAgainstChainEvidence` gate removed `e7231534`). Placement into the band is prevented by `LAST-FILL-GUARD` / `findCrossedOrder`, not by P3 cancellation sweeps.
470
502
  - **Identity:** every resync (incl. startup reconcile) leaves no live order unmanaged (adopted-or-cancelled-as-surplus, surplus = `chainCount-targetCount` farthest-first).
471
- - **Monotonicity (grid-check):** adjacent same-direction fills monotonic rising sell / falling buy (equal OK).
503
+ - **Monotonicity (grid-check):** adjacent same-direction fills monotonic rising sell / falling buy. Equal price is **not** OK — the guard blocks a re-place at the just-filled level, and the checker mirrors that verdict. **Failure = place `sell→sell` lower-or-equal / `buy→buy` higher-or-equal.**
472
504
  - **I1–I6 PRICE_FIRST** plus COW-commit-only boundary writes and price-less degrades conservatively.
473
505
 
474
506
  ---
@@ -480,7 +512,7 @@ Goal (Phase 2): I1–I6 property pass, full suite green, harness random, 48h per
480
512
  npm run analysis:grid-check -- --bot-key <bot-key> --account 1.2.xxxxx --hours 168
481
513
  npm run analysis:grid-check -- --bot-key <bot-key> --account 1.2.xxxxx --hours 720
482
514
  npm run analysis:grid-check -- --bot-key <bot-key> --account 1.2.xxxxx --hours 168 --json out.json --csv out.csv
483
- # cross-pair opt: --include-cross-pair ; per-fill opt: --per-fill ; tolerance opt: --tolerance 0.1
515
+ # cross-pair opt: --include-cross-pair ; per-fill opt: --per-fill ; --increment is informational (direction-only verdict)
484
516
  ```
485
517
  Pairs-checked base excludes cross-pair unless flagged; strict sat-level detection (`detectViolations`, `aggregateByOrder`).
486
518
 
@@ -492,8 +524,9 @@ Pairs-checked base excludes cross-pair unless flagged; strict sat-level detectio
492
524
  - Post-broadcast read-back retry: bot-B `06:43` no `14` piled / forced resync mid-broadcast. *(Addressed v1.6.13–1.6.14 by the resync-cascade break (`7eb65c8e`) and the fresh-placement cancel grace (`85a7e7f0`); see §9.)*
493
525
  - COW commit never places inside gap; pre-broadcast existence check: bot-B `<order-4/5>` + bot-D/D2 `GAP-BAND` fixtures → `0`. *(Amended: the commit-time in-gap cancel sweep was reverted `e2898e51` — current expectation is adoption-after-chain-evidence-correction; `0` unmanaged in-gap orders remains the target.)*
494
526
  - Aug 28 burst `17:09–17:16` (3 regs/6m, sells 1110–1176) → `0` orphans, `0` sells below asks.
527
+ - *(Direction rule, post-`8e5e1a3c`):* the checker reports `sell→sell` at/below the previous sell and `buy→buy` at/above the previous buy. A run that only passed because equal prices were tolerated is a **regression signal**, not a baseline.
495
528
  - **Orphan regression over ~7h post-`cd690000` on bot-A/B/C:** distinct `Unmatched` `58/60/91 → ~0` (full `229/107/172 → ~0`), `Fund invariant violation` `0` (was `3077.07→3184.93` etc.), `ORPHAN-FILL` `0` (was `7/33/22`), repeated `[BOUNDARY-EVIDENCE]` `0`, deferred minutes `0`, `[MAINT] n/m failed` `0`.
496
- - **Grid-correction soak (external, strict):** pre-fix baselines on the affected markets showed double-digit `%` same-direction inversion rates over 7d/30d windows → `0` sustained. Sustain 48h per-bot (Phase 2) and 14-day zero-guard/divergence (Phase 3). *(Phase 2/3 soak gates moot since `3713c496` — projection removed; the divergence telemetry remains as a monitoring signal.)* **Failure = place `sell→sell` lower / `buy→buy` higher.**
529
+ - **Grid-correction soak (external, strict):** pre-fix baselines on the affected markets showed double-digit `%` same-direction inversion rates over 7d/30d windows → `0` sustained. Sustain 48h per-bot (Phase 2) and 14-day zero-guard/divergence (Phase 3). *(Phase 2/3 soak gates moot since `3713c496` — projection removed; the divergence telemetry remains as a monitoring signal.)* **Failure = place `sell→sell` lower-or-equal / `buy→buy` higher-or-equal.**
497
530
 
498
531
  Original doc regression excerpts preserved: GAP P6 A/B/C; LADDER §2.8 checks (10 bullets); ORPHAN §3 guardrails; PRICE §4.7/4.10 kill-switch. The randomized chaos/property harness was the PRICE_FIRST Phase 2 gate (§4.6), not part of LADDER §2.8.
499
532
 
@@ -505,14 +538,15 @@ Original doc regression excerpts preserved: GAP P6 A/B/C; LADDER §2.8 checks (1
505
538
  - [x] No other doc/index lists the four (verified 2026-08-31); `analysis/README.md` documents the `grid_correction_check` tool.
506
539
  - [x] Stale `*.md` filename references in code comments/tests updated to the consolidated doc (9 module files, 6 test files), then re-pointed to this hub when it absorbed the summary.
507
540
 
508
- *Generated 2026-08-31 from the 4 test-only docs at their HEAD contents; statuses corrected against `test` HEAD `a54863ca` the same day, then refreshed against `1382f267` (2026-09-13) and extended through v1.6.14 at `f6c0df32` (2026-10-12; see §9). Landed/reverted/superseded annotations carry commit hashes where known; **line references in §§1-4 were re-verified at `a54863ca` and are subject to drift** — treat them as pointers, not assertions. The GRID-PRICE-INVARIANT guard is **BLOCKING** at all six emission sites (CREATE / UPDATE / CREATE-FALLBACK in `modules/dexbot_cow_runtime.ts`, RECONCILE-CREATE / RECONCILE-UPDATE / STARTUP-CREATE in `modules/order/grid_reconcile_internal.ts`): an off-grid emission is skipped, not merely counted, so a `violated>0` line means an emission was *prevented* rather than a writer merely *pinned*. Counters are still reported (`site=`, `checked=`, `violated=`, `unchecked=`) for observability — see `docs/GRID_PRICE_INVARIANT.md`.*
541
+ *Generated 2026-08-31 from the 4 test-only docs at their HEAD contents; statuses corrected against `test` HEAD `a54863ca` the same day, then refreshed against `1382f267` (2026-09-13), extended through v1.6.14 at `f6c0df32` (2026-10-12), through v1.6.17 at `78ccbb8e`, and then through the post-1.6.17 review pass (`§9.10`: `f4d6da8c`, `a2bf6ba5`, `56481b16`, `3d16f9e4`). Landed/reverted/superseded annotations carry commit hashes where known; **line references in §§1-4 were re-verified at `a54863ca` and are subject to drift** — treat them as pointers, not assertions. The GRID-PRICE-INVARIANT guard is **BLOCKING** at all six emission sites (CREATE / UPDATE / CREATE-FALLBACK in `modules/dexbot_cow_runtime.ts`, RECONCILE-CREATE / RECONCILE-UPDATE / STARTUP-CREATE in `modules/order/grid_reconcile_internal.ts`): an off-grid emission is skipped, not merely counted, so a `violated>0` line means an emission was *prevented* rather than a writer merely *pinned*. Counters are still reported (`site=`, `checked=`, `violated=`, `unchecked=`) for observability — see `docs/GRID_PRICE_INVARIANT.md`.*
509
542
 
510
543
  ---
511
544
 
512
- ### 9. COW Broadcast, Resync & Geometry Safety (v1.6.4 → v1.6.14)
545
+ ### 9. COW Broadcast, Resync & Geometry Safety (v1.6.4 → v1.6.17)
513
546
 
514
- > **Source:** `CHANGELOG.md` v1.6.4 → v1.6.14 · **Snapshot:** `f6c0df32` (2026-10-12).
547
+ > **Source:** `CHANGELOG.md` v1.6.4 → v1.6.17 · **Snapshot:** `78ccbb8e` (v1.6.17 tag).
515
548
  > Extends the §§1–8 ledger; the `§0`–`§8` numbers are unchanged (code and tests cite them).
549
+ > `§9.10` and the last two ledger rows cover the **post-1.6.17** work, which is unreleased.
516
550
 
517
551
  Sections 1–4 end with the prevention sweeps reverted: a cancel sweep on ambiguous evidence
518
552
  proved worse than the orphan it targets. The post-1.6.3 arc is the constructive inverse —
@@ -522,8 +556,10 @@ proved worse than the orphan it targets. The post-1.6.3 arc is the constructive
522
556
 
523
557
  R4's fixes (genesis determinism, one writer, the last-fill guard) closed the *orphan* family.
524
558
  The remaining harm was self-inflicted: **structural resyncs fired on evidence that did not
525
- justify them**, and each reset clears the LAST-FILL-GUARD pivot and any gap-evacuation streak.
526
- The engine now treats uncertainty as *defer, never rebuild*:
559
+ justify them**, and each reset clears the LAST-FILL-GUARD pivot and any gap-evacuation streak
560
+ (since §9.10/P2 the pivot is then re-armed explicitly from the last real fill, so a rebuild no
561
+ longer silently un-arms the guard). The engine now treats uncertainty as *defer, never
562
+ rebuild*:
527
563
 
528
564
  - **Uncertain-broadcast reconciliation is master-aware** (`7eb65c8e`, v1.6.13):
529
565
  `resyncIfUnreconciled` treats a chain order as reconciled if master already tracks it
@@ -600,7 +636,7 @@ fail-closed behind `_assertGenesisInvariant`. This is R4's "removing writers and
600
636
  truth" carried to its end: the no-ladder state that Appendix A's `slot.price` corruption
601
637
  required is no longer reachable at runtime.
602
638
 
603
- #### 9.5 Ledger (order-engine commits, v1.6.4 → v1.6.14)
639
+ #### 9.5 Ledger (order-engine commits, v1.6.4 → v1.6.17 + unreleased)
604
640
 
605
641
  | Commit | Release | Change |
606
642
  |---|---|---|
@@ -631,6 +667,16 @@ required is no longer reachable at runtime.
631
667
  | `750386ac` | 1.6.14 | Guard unknown boundary in the gap-band shadow |
632
668
  | `dc87ce01` | 1.6.14 | Close missed 1.6.13 regressions in absent geometry and the rebuild guard |
633
669
  | `249016e4` | 1.6.14 | Keep `validateBoundaryCommit` fail-closed for garbage boundaries |
670
+ | `6c86d505` | 1.6.15 | Level identity is the price, not the asset amount (adoption/compare) |
671
+ | `8e5e1a3c` | 1.6.17 | Last-fill guard blocks only higher buys and lower sells (band removed, §9.7) |
672
+ | `62312e60` | 1.6.17 | Plan only placeable tightening slots; name the stall causes |
673
+ | `276cd504` | 1.6.17 | Fund from chain truth and re-anchor the boundary from the fill (§9.9) |
674
+ | `2e618197` | 1.6.17 | Consume only the owed fill crawls a derivation applied (§9.8) |
675
+ | `d99b8685` | post-1.6.17 | Harden partial-fill re-anchor and recovery (residual allow-list, tolerant load) |
676
+ | `531edeb4` | post-1.6.17 | Keep the boundary on the placed rails; use live fill prices for geometry |
677
+ | `f4d6da8c` | post-1.6.17 | Edge-pinned fills never arm the pivot or the anchor (§9.10/P1) |
678
+ | `a2bf6ba5` | post-1.6.17 | Guard arity, explicit pivot re-arm, stray-aware rail clamp, crossing observation (§9.10/P2-P4) |
679
+ | `56481b16` | post-1.6.17 | Offline checker judges by the same direction-only predicate (§9.10/P5) |
634
680
 
635
681
  #### 9.6 Invariants added
636
682
 
@@ -641,6 +687,164 @@ required is no longer reachable at runtime.
641
687
  wire; no `limit_order_update` may abort a chunk.
642
688
  - **Placed is not surplus:** an order inside `SURPLUS_CANCEL_GRACE_MS` is never cancelled by a
643
689
  sweep running on a stale snapshot.
690
+ - **Only a window trade may become the pivot:** edge-pinned insurance fills are skipped at the
691
+ single pivot writer, so they can neither veto a side nor anchor the geometry (§9.10/P1).
692
+ - **One boundary validator:** a boundary write that can strand a live order in the implied
693
+ band is refused by `validatePersistedBoundary`, whoever computed it — re-anchor, rail clamp,
694
+ restore, commit (§9.10/P2/P3).
695
+ - **A rail clamp only cites its own evidence:** the batch's op destinations and the master
696
+ orders on their own side of the planned boundary; strays are ignored and named (§9.10/P3).
697
+ - **The pivot has a lifetime:** re-armed explicitly after a rebuild from the last real fill,
698
+ bounded by the same 24h TTL, and a re-center is requested at most once per pivot because a
699
+ re-center cannot move it (§9.10/P2).
700
+
701
+ #### 9.7 The guard was a band, not an economic rule (`c86b4b0e`)
702
+
703
+ **Observed (2026-10-24/25, a live market-pair bot).** A dump swept the grid and the
704
+ market then held. Spread correction planned, the broadcast guard dropped the creates,
705
+ `SPREAD-STALE` reported **84 minutes with no correction placed**, and only a structural
706
+ re-center (grid rebuild) restored the spread. Two distinct guard defects, both from one
707
+ predicate:
708
+
709
+ 1. **The pivot band ignored the fill's side.** `isLastFillGuardBlocked` judged against
710
+ `pivot ± increment/2`:
711
+ ```ts
712
+ BUY blocked if price > pivot * (1 - inc/2/100)
713
+ SELL blocked if price < pivot * (1 + inc/2/100)
714
+ ```
715
+ The `lastType` argument was passed and never read. Consequences: a BUY **below** a SELL
716
+ fill was blocked (the doc claimed "buy-below-sell is never gated"; the code gated it),
717
+ and a SELL 0.2% **above** our cost was blocked after a BUY fill — exactly the spread
718
+ edge, which correction places tighter than a full increment by design. Repair therefore
719
+ depended on the `SPREAD_CORRECTION` bypass, which `09dbaad7` denies whenever a real fill
720
+ reference exists — so after any fill, tightening was structurally impossible.
721
+ 2. **Planner and guard disagreed.** `09dbaad7` intended a planner-side filter against the
722
+ fill reference, but the implementation used the readiness *crossing floor*, which
723
+ prefers a **fresh live market read** over the fill anchor. With a fresh read the planner
724
+ admitted what the guard would drop, producing the live sequence
725
+ `planned 2, placing 1 → Skipping sell CREATE … below last filled → Transient refusal 1/3
726
+ → batch was prepared but not executed` — a whole cycle spent on a guaranteed refusal.
727
+
728
+ **Fix.** Direction only, one predicate shared by both sides:
729
+
730
+ ```ts
731
+ BUY blocked if price >= pivot // never place a higher BUY
732
+ SELL blocked if price <= pivot // never place a lower SELL
733
+ ```
734
+
735
+ Equal price stays blocked (re-place at the filled level). The predicate lives in
736
+ `order/utils/system.ts` next to `resolveLastFillGuardReference`; `dexbot_cow_runtime`
737
+ re-exports it. Its signature is now `(price, type, lastPrice, lastType)`: the dead `size`
738
+ and `increment` parameters were removed in §9.10, so an increment term can no longer reach
739
+ the predicate at all (LFG-5 pins the arity). The planner now filters every candidate pool
740
+ (and boundary promotion) with the **same** predicate before the quota slice, so a batch is
741
+ never built out of ops the guard will drop, and an unplaceable side reports it honestly.
742
+
743
+ **Deliberately not relaxed.** A lower SELL is still refused **when the last fill was a
744
+ SELL**: after a fill the sell window must move *up*, so a sell slot below the last sale is
745
+ evidence that the boundary/crawl is behind the fill — a geometry fault, not a placement
746
+ opportunity. The log confirms it: seven slots (147–153) filled in one sync, the boundary
747
+ then **moved down** to 146 (two commits each dropping owed crawls), leaving slots 151/152
748
+ as sell-zone holes below the last sale. A cost-basis rule (sell only above the last BUY)
749
+ would have *placed into* that corrupted geometry.
750
+
751
+ #### 9.8 Stalls that placement cannot repair get their own clocks
752
+
753
+ Three states were previously indistinguishable from patience and all waited for the
754
+ 30-minute structural window:
755
+
756
+ - **Rail oversubscribed** — `availableFund = chainFree − virtual` reads 0 when the empty
757
+ rail already reserves more than the account holds (live: free 454560.80 vs virtual
758
+ 456046.21, `planned 3, placing 0` for 84 minutes). Named in the log, flagged on the
759
+ manager, escalated on `SPREAD_STALE_FUND_ESCALATE_MS` (5 min).
760
+ - **Geometry bind (`last-fill-blocked`)** — every tightening slot is at/through the last
761
+ fill, i.e. the window is behind the fill. A distinct stall value, preserved through the
762
+ starvation-fallback merge (`mergeSpreadStalls`), escalated on
763
+ `SPREAD_STALE_GEOMETRY_ESCALATE_MS` (10 min).
764
+ - **Oscillating measurement** — one in-tolerance reading no longer clears the persistence
765
+ clock; tolerance must hold for `SPREAD_STALE_IN_TOLERANCE_RESET_MS` (10 min), and a
766
+ placed correction still clears it immediately. A single good glance between refusals was
767
+ what let 84 minutes pass.
768
+
769
+ **RESOLVED (crawl consumption is now scoped).** The clear was ledger-wide while
770
+ the derivation folded a subset. `deriveTargetBoundary` now returns
771
+ `consumedCrawlIds`, the plan carries it to the commit (`_consumePendingFillCrawls`),
772
+ and only the applied records are dropped — a capped fold consumes a same-side
773
+ prefix up to the applied magnitude, so the remainder stays owed exactly once.
774
+ A commit without the wire consumes nothing. The instrumentation below remains
775
+ (and now reports `kept=M`), and the historical leak record is kept for context:
776
+
777
+ **Original finding (leak #6): the crawl ledger dropped records it never applied.** A commit clears
778
+ **all** owed fill crawls whenever the plan's boundary is accepted and not held
779
+ (`_clearPendingFillCrawls('boundary commit')`), while the derivation folds only the subset
780
+ that passes its batch-dedupe, edge classification and `fallbackCap`. Any excluded entry is
781
+ lost — the same class `77e763f6` fixed for the held boundary, still open for the rest, and
782
+ the mechanism behind a multi-slot sweep leaving the boundary *behind* the fills.
783
+
784
+ #### 9.9 Two deadlocks that were bookkeeping, not market (`430dee6a` follow-up)
785
+
786
+ Both incidents in §9.7/§9.8 ended in a rebuild. Neither was a fund shortage and
787
+ neither needed a new guard — each was a self-referential calculation that could
788
+ only be broken from outside.
789
+
790
+ **The budget that vetoed its own placement.** `available = chainFree −
791
+ virtualReservation` is the right question for "how much room is left beyond the
792
+ projected rail", but the correction then spends it on *that same projection*:
793
+ when the rail was sized from a larger balance (or from inventory locked in
794
+ resting orders), the reservation exceeds chain free, `available` reads 0, no
795
+ placement can consume the reservation, and it can never shrink. Live: free
796
+ 454560.80 vs virtual 456046.21 — `planned 3, placing 0` every cycle for 84
797
+ minutes. The fix is arithmetic, not policy: for a known candidate set the budget
798
+ is `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available`
799
+ is 0 (`deriveChainTruthFundBudget`). Bound on both sides, and the chain rejects
800
+ an over-commit anyway.
801
+
802
+ **The crawl that could not catch up.** A boundary crawl is ±1 slot per committed
803
+ fill, so once a sweep leaves the window *behind* the fill, crawling is
804
+ arithmetically unable to recover: every tightening slot is then at/through the
805
+ fill, `passesLastFill` refuses all of them, and the funds sit in the stranded
806
+ resting inventory. The cheapest repair (rotate the stranded orders down) is
807
+ itself a lower sell, which the same guard forbids — three locks, no key. The fill
808
+ is the anchor: `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f =>
809
+ boundary ≤ f − 1` (`reanchorBoundaryFromLastFill`), subject to a real
810
+ fill-provenanced pivot, an on-ladder price and `validatePersistedBoundary` — and, since
811
+ §9.10, subject to the fill being a **window** trade: edge-pinned insurance fills never arm
812
+ the pivot, so they can never anchor the geometry.
813
+
814
+ **Deliberately rejected: the pair ledger.** Making each fill mint its counter
815
+ order (reserve the exact proceeds) would prove per-trade funding and delete the
816
+ `fund-constrained prefix` logic — but it also turns the ladder into a set of
817
+ independent round trips, so sizes stop following the side budget. Spread repair
818
+ must stay fund-driven from the side pool: a SELL fill returns quote while the
819
+ same-side repair needs base, so no fill can ever fund its own side, and pairing
820
+ would hide that asymmetry instead of resolving it.
821
+
822
+ #### 9.10 Review pass over v1.6.12 → v1.6.17 (unreleased)
823
+
824
+ A code review of the whole 1.6.12→1.6.17 order-engine arc (90 commits) against
825
+ the three stated goals — buy-low/sell-high counter orders, never trading through
826
+ the last real fill, and repairing a stale/out-of-spread book from free funds —
827
+ found the arc sound and identified five gaps. All five are fixed here.
828
+
829
+ | # | Finding | Fix |
830
+ |---|---|---|
831
+ | P1 | The re-anchor ignored the crawl's EDGE-fill exclusion: `recordLastFilledPrices` armed the pivot on every fill, and the re-anchor is absolute, so one wick on a floor insurance BUY teleported the window to the grid floor (repro: boundary 29 → 0 on a 60-slot ladder; mirror at the ceiling). | Eligibility now lives at the single pivot writer: `collectEdgePinnedFillIds` (the placement pickers' own classifier) is applied in `recordLastFilledPrices`, so an edge fill can neither arm the guard nor anchor the geometry. Partials still anchor (a real trade; residual allow-listed). Pinned by `tests/test_edge_fill_pivot.ts`. |
832
+ | P2 | The rebuild site claimed "the guard re-arms on the first real fill of the new generation" while the read-time fallback silently kept the old-generation pivot — so after a re-center in a market that had moved away, one whole side read `last-fill-blocked` forever AND the 10-minute geometry clock rebuilt the new generation again every cooldown, with no way to succeed. | Re-arm is explicit and logged (`rearmLastFillPivotFromMarketFill`, provenance `fill`, original timestamp) so code and docs agree; the geometry escalation is capped at ONE re-center per pivot (`_lastGeometryResyncPivotKey`) and then reports that only a fill or the pivot TTL restores the side. The pivot's survival is the decision, not an accident. Pinned by `tests/test_last_fill_pivot_rearm.ts` and SLF-11. |
833
+ | P3 | `deriveRailBoundary` clamped the boundary to EVERY live rail order: one stray order 18 slots off clamped 138 → 115 and re-typed the whole window (self-legalizing the corrupt state), and it classified rails by slot id while the rest of the engine had moved to live chain prices. | Rail membership = the batch's own op destinations + master orders on their own side of the planned boundary; strays are skipped and named in the log; rail indices come from `resolveLiveOrderLadderPosition`; the result passes the shared `validatePersistedBoundary` gate (cancel/rotation sources allow-listed, sparse ladders excluded because that gate's ceiling is array-derived). Pinned by RAIL-10..14. |
834
+ | P4 | The crossing floor (`doesNotCrossMarket`) exists only in the spread-correction planner, so a generic reconcile/re-fill CREATE can execute as a taker fill where the planner would refuse. | Deliberately NOT blocked (a hard veto re-opens the counter-order deadlock: after a gap the counter sits across the floor by construction and executes at the best available price). Made visible instead: `warnCrossingCreate`, once per batch, from cached evidence only. Pinned by SLF-12. |
835
+ | P5 | `analysis/grid_correction_check.ts` still implemented the OLD `pivot ± increment/2` band and claimed to mirror the guard 1:1, so it reported the tightening placements the direction-only guard allows as violations. | Predicate reduced to the live direction rule (arity-pinned in LFG-5), report/help text updated, `--increment` documented as informational, edge-fill false-positive class documented. |
836
+
837
+ Simplifications landed with the fixes: one pivot resolver (two identical copies
838
+ merged), one boundary validator for the re-anchor and the rail clamp, one
839
+ eligibility rule for the crawl, the pivot and the anchor, the dead
840
+ `size`/`increment` parameters of `isLastFillGuardBlocked` removed (an increment
841
+ term is no longer reachable through it — LFG-5 pins the arity), and the batch
842
+ extremum extracted as `resolveFillAnchorIndex` (pure, batch-only).
843
+
844
+ **Commits:** `f4d6da8c` (P1) · `a2bf6ba5` (P2–P4 plus the arity and the anchor
845
+ extraction) · `56481b16` (P5) · `3d16f9e4` (this document, the doc-level invariants
846
+ and the log rows it cites). **Unreleased:** no version bump and no `CHANGELOG.md`
847
+ entry — both belong to the release step, not to this pass.
644
848
 
645
849
  ---
646
850
 
package/docs/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  This directory contains the comprehensive technical documentation for the DEXBot2 trading bot. It is designed to guide developers from high-level architecture down to the nuances of fund accounting and state management.
4
4
 
5
- **Version context:** v1.6.16 (released).
5
+ **Version context:** v1.6.18 (released).
6
6
 
7
7
  ---
8
8