dexbot 1.6.16 → 1.6.17

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 (60) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/analysis/tradingview/README.md +2 -2
  3. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  8. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  9. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +4 -4
  10. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  11. package/dist/modules/account_bots.d.ts +3 -0
  12. package/dist/modules/chain_keys.d.ts +1 -1
  13. package/dist/modules/constants.d.ts +6 -0
  14. package/dist/modules/constants.js +34 -6
  15. package/dist/modules/credit_pricing.d.ts +20 -1
  16. package/dist/modules/credit_pricing.js +23 -1
  17. package/dist/modules/credit_runtime.js +33 -16
  18. package/dist/modules/dexbot_class.d.ts +3 -1
  19. package/dist/modules/dexbot_class.js +5 -2
  20. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  21. package/dist/modules/dexbot_cow_runtime.js +47 -66
  22. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  23. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  24. package/dist/modules/launcher/credential_daemon.js +60 -26
  25. package/dist/modules/order/grid.d.ts +7 -0
  26. package/dist/modules/order/grid.js +157 -15
  27. package/dist/modules/order/index.d.ts +15 -0
  28. package/dist/modules/order/manager.d.ts +30 -7
  29. package/dist/modules/order/manager.js +108 -12
  30. package/dist/modules/order/strategy.d.ts +5 -0
  31. package/dist/modules/order/strategy.js +23 -2
  32. package/dist/modules/order/utils/math.d.ts +41 -1
  33. package/dist/modules/order/utils/math.js +47 -1
  34. package/dist/modules/order/utils/order.d.ts +13 -0
  35. package/dist/modules/order/utils/order.js +61 -7
  36. package/dist/modules/order/utils/system.d.ts +66 -0
  37. package/dist/modules/order/utils/system.js +135 -0
  38. package/dist/modules/order/utils/validate.d.ts +3 -1
  39. package/dist/modules/order/utils/validate.js +5 -1
  40. package/dist/modules/types.d.ts +35 -2
  41. package/dist/scripts/analyze-credit.js +64 -23
  42. package/dist/scripts/bts_distribution.d.ts +66 -0
  43. package/dist/scripts/bts_distribution.js +2102 -0
  44. package/dist/scripts/token_distribution.d.ts +45 -0
  45. package/dist/scripts/token_distribution.js +1870 -0
  46. package/dist/unlock.js +42 -24
  47. package/docs/COW_INVARIANTS.md +6 -0
  48. package/docs/DEXBOT_COMPARISON.md +5 -5
  49. package/docs/EVOLUTION.md +9 -8
  50. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -1
  51. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  52. package/docs/GRID_RECALCULATION.md +3 -3
  53. package/docs/LOGGING.md +9 -0
  54. package/docs/MPA_CREDIT_USAGE.md +3 -2
  55. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +117 -0
  56. package/docs/README.md +1 -1
  57. package/docs/architecture.md +98 -1
  58. package/market_adapter/README.md +2 -2
  59. package/package.json +3 -1
  60. package/scripts/README.md +85 -148
package/CHANGELOG.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.17] - 2026-10-30 - Last-Fill Direction Guard, Spread-Correction Stall Naming & Chain-Truth Funding, Owed-Crawl Consumption, Restart Auth-Before-Stop, Pool-Priced LP Collateral, Supply Distribution Analyzers
6
+
7
+ ### 2026-10-30
8
+
9
+ - **Feat(scripts)**: add a BTS supply distribution analyzer — `scripts/bts_distribution.ts` (`npm run distribution`) is a read-only live-chain report that buckets the core asset into call-order collateral, global and individual settlement funds (with individual debt and force-settlement parameters), governance tickets, vesting and legacy balances, liquidity pools, SameT/credit funds, HTLC escrow and asset fee pools, then reports the leftover as a derived liquid residual compared against total supply and a derived circulating float (optional external reference). It also pulls the liquid rich list from `asset_api::get_asset_holders` (retrying on a node without that API), tags exchange-like account names as a heuristic, and can page the full holder list to split the residual into account balances, blinded balances and order books with concentration and balance bands. Output is a colorized terminal report plus a self-contained HTML donut report under the gitignored `analysis/charts/`. Documented in `scripts/README.md`; verified with a clean build, `check:any`, and live runs in default and full-rich-list modes.
10
+
11
+ - **Feat(scripts)**: add a per-token companion analyzer — `scripts/token_distribution.ts` (`npm run token-distribution`) buckets a single asset into free balances, limit orders, liquidity pools, vesting balances, P2P credit offers and deal collateral, SameT funds, HTLC escrow, accumulated market fees and blinded supply, reconciling every bucket against `current_supply`. Liquidity is grouped by counterpart asset and reported as a separate donut, and a 3% price-change table combines orderbook and constant-product pool depth per market (token sellable at −3%, buyable at +3%, each as a share of total supply), with pool depth net of the taker fee and capped orderbook rows marked. Read-only, with `--json` and `--no-orders` modes; documented in `scripts/README.md`.
12
+
13
+ - **Tune(ama)**: make the slowPeriod ladder exact −9% response steps — AMA2–AMA4 are now derived from AMA1 (62.1) so each preset lowers the effective smoothing coefficient by ~9% at the typical ER (`AMA_CONVERGENCE_ER_AVG` 0.151), where the old fixed +16% period ladder shrank the response difference toward the slow end (−9.4/−8.7/−7.8%). AMA2 72.0 → 71.5, AMA3 83.6 → 83.5, AMA4 96.9 → 99.3 (unrounded 62.10/71.48/83.46/99.27); AMA4 is the only material change (~4.7% lower ER→0 noise floor, ~1.25% less responsive at ER 0.151, ~16 extra warmup bars), AMA1–AMA3 are effectively unchanged. Docs, chart preset annotations and the Huber backtest default (now derived from `MARKET_ADAPTER.AMAS` instead of hardcoded) are aligned. Covered by `test_bot_defaults_parity`, `test_market_adapter_logic` and `test_lp_chart`.
14
+
15
+ - **Tune(ama)**: raise the AMA slope ceiling default from 0.09 to 0.1 — `DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT` now needs a stronger per-bar trend before reaching full influence, de-sensitizing range asymmetry, grid price offset and buy/sell weight tilt to the same slope magnitude; the AMA-slope grid-reset trigger threshold scales with the ceiling, so it rises proportionally. TradingView/grid-reset simulator fallbacks and the research-doc default follow the canonical constant; per-bot `amaSlope.maxSlopePct` overrides still win. Behavioral default change for bots without an explicit override. Covered by `test_grid_reset_sim`, `test_ama_slope_model` and `test_market_adapter_logic`.
16
+
17
+ - **Fix(guard)**: last-fill guard blocks only higher buys and lower sells — the guard judged placements against a price band around the last fill and never read the fill's side, so it blocked profitable placements within half an increment of the fill (exactly where spread correction places) and blocked buy-backs *below* a SELL fill. It is replaced by the direction rule `BUY blocked at/above the pivot`, `SELL blocked at/below the pivot` in `modules/order/utils/system.ts` (equal price stays blocked to prevent the immediate re-fill loop; a cold pivot or unrecorded fill side still disables the guard). The increment no longer participates but stays in the signature so call sites and logs are unchanged, and `LastFillGuardResult` drops `halfInc`. Live impact: a sweep no longer freezes spread repair for the rest of the band. Covered by a rewritten `tests/test_last_fill_guard.ts` plus re-solved invariants in `tests/test_grid_price_invariant_wiring.ts`.
18
+
19
+ - **Fix(spread)**: plan only placeable tightening slots and name the stalls — the correction planned candidates the broadcast guard was guaranteed to drop, because its crossing floor preferred a fresh live read over the fill anchor and had no planner-side last-fill filter. `passesLastFill` (exported next to `resolveLastFillGuardReference` and reused by the COW runtime, so planner and guard cannot resolve different pivots) is now applied to every candidate pool and boundary promotion before the quota slice; an empty side is reported as the `last-fill-blocked` stall and survives the starvation-fallback merge instead of collapsing to no-candidates; a rail reservation above the chain free balance is named and flagged `OVERSUBSCRIBED`; and the out-of-spread clock is cleared only after sustained tolerance or a placement, with the fund and geometry escalations on their own windows. The crawl-ledger drop log now carries side split, net, age and boundary delta. Files: `order/utils/system.ts`, `order/grid.ts`, `dexbot_cow_runtime.ts`, `dexbot_maintenance_runtime.ts`, `order/manager.ts`, `constants.ts`, `types.ts`, `dexbot_class.ts`; covered by new `tests/test_spread_last_fill_planning.ts` and updated `test_spread_market_reference`, `test_stale_grid_hardening`, `test_dexbot_maintenance_runtime_dynamic_weights`, `test_targeted_drift_reconcile`.
20
+
21
+ - **Fix(spread)**: fund from chain truth and re-anchor the boundary from the fill — two self-referential calculations could only be broken from outside. (1) The budget vetoed its own placement: `available = chainFree − virtual` then spends it on that same projection, so a rail sized from a larger balance (or from resting inventory) can leave `available` at 0 forever; `deriveChainTruthFundBudget` (`order/utils/math.ts`) re-derives the budget for a known candidate set as `min(chainFree, min(virtual, Σ candidate ideals))`, bounded on both sides and still rejected at broadcast if over-committed, while a zero caused by fees or an empty balance is honoured unchanged. (2) A boundary crawl is ±1 slot per committed fill, so once a sweep leaves the window behind the fill no tightening slot can be placed and the stranded orders cannot rotate down either; `reanchorBoundaryFromLastFill` (`order/utils/system.ts`, applied from `calculateTargetGrid`) anchors the fill (`SELL` fill at slot f → boundary ≥ f − gapSlots; `BUY` fill at slot f → boundary ≤ f − 1), fail-closed on fill provenance, on-ladder price and `validatePersistedBoundary`. A per-fill pair ledger was rejected on purpose: sizes must follow the side budget, and a SELL fill returns quote while the same-side repair needs base. Covered by `tests/test_chain_truth_funding.ts` and `tests/test_boundary_fill_reanchor.ts`; documented in the architecture, COW invariant and fund-movement docs plus retrospective §9.9.
22
+
23
+ - **Fix(crawls)**: consume only the owed fill crawls a derivation applied — the pending-crawl ledger records one relative boundary delta per shift-eligible fill because the batch that sees a fill may not commit a boundary, but the derivation folds only a subset (own-batch slots are deduped, edge slots never crawl, the cross-chunk cap bounds one plan) while the commit cleared *all* of it, so an owed record the derivation could not apply vanished. Live signature: seven fills swept slots and two commits each dropped owed crawls, leaving the boundary seven levels behind and the sell window below the last sale. `deriveTargetBoundary` now returns `consumedCrawlIds` (applied records plus the ones deliberately never counted; a capped fold consumes a same-side prefix so the remainder stays owed exactly once), the plan carries it through `buildSuccessResult` → `CowResult` → both `_commitWorkingGrid` call sites, and `_consumePendingFillCrawls` drops exactly those records (matched by `slotId` + `ts`) while logging `Dropped N … kept=M`. A commit without the wire consumes nothing; `_clearPendingFillCrawls` keeps its explicit allowed-loss meaning. The recorder still dedupes per slot and caps the ledger at 500, so no age cap is needed. Covered by new `tests/test_crawl_ledger_consumption.ts` plus updated pending-fill and market-scenario tests.
24
+
25
+ - **Fix(restart)**: verify the master password before stopping the credential daemon — a failed `dexbot restart` used to stop the live daemon first and then abort on a wrong or cancelled password, leaving every bot without key access until a later successful start. Both restart-all paths (monolithic and isolated supervisor) now authenticate first and only stop the existing daemon once the secret is verified, handing the verified secret to `ensureCredentialDaemon` so it does not prompt twice; a failed authentication exits non-zero without touching the daemon or signalling the runtime. Files: `unlock.ts`, `modules/launcher/credential_daemon.ts` (`authenticateCredential`, optional pre-verified `vaultSecret`); covered by `tests/test_restart_password_gate.ts`.
26
+
27
+ - **Refactor(restart)**: type the vault secret and clear it after daemon handoff — the pre-verified secret was typed `unknown` and the launcher-side reference stayed live until the restart block ended. `VaultSecret` is now exported from `chain_keys` and used by the restart/daemon-start APIs, and `clearVaultSecret` is called in a `finally` covering every startup path (successful bootstrap handoff, spawn/startup failure, bootstrap server creation failure, bootstrap path-file write failure), with both restart paths clearing the caller's reference even if daemon startup throws. A caller-supplied `vaultSecret` is documented as consumed and must not be reused. Nothing is persisted: the secret stays in process memory, is never logged or written to disk, and hex strings cannot be zeroed in place in V8, so the helper nulls the fields and lets GC reclaim them. Covered by `test_restart_password_gate` and `test_credential_daemon_controller_output`.
28
+
29
+ - **Fix(credit)**: value LP-share collateral at the pool market price — `dexbot credit` and the runtime's conversion-rate resolver used the offer's fixed `acceptable_collateral` price for liquidity-pool share collateral, which is a contract haircut and can go stale, so the reported CR was false for LP shares (e.g. 1.111 instead of the pool-based 1.399). New `selectCollateralConversionRate()` (`modules/credit_pricing.ts`) prefers the live pool value for LP shares and otherwise keeps the offer price first with the pool rate as fallback; `scripts/analyze-credit.ts` uses it and tags `Avar. CR` rows with `pool`/`offer` while keeping the active deal's offer for `Curr. CR`, and `_resolveCreditConversionRate()` (`modules/credit_runtime.ts`) is pool-first for LP shares so collateral distribution matches the borrow gate. LP-share CR uses pure pool reserves/supply with no fee or slippage deduction; non-LP collateral is unchanged, and multi-item groups sharing an LP collateral now split at market-value CR. Covered by `test_credit_pricing`, `test_analyze_credit`, `test_credit_conversion_fallback` and `test_credit_runtime`.
30
+
5
31
  ## [1.6.16] - 2026-10-18 - Monolithic Per-Bot Control Routing, Candle-Cache Orientation Sharing, Chart Redraw Performance, Adapter Whitelist Sync, `dexbot rich` Symbol Canonicalization
6
32
 
7
33
  ### 2026-10-18
@@ -111,7 +111,7 @@ node dist/analysis/tradingview/analyze_tradingview.js \
111
111
  1. Reads `profiles/bots.json` to find the bot's `assetA`, `assetB`, and `ama` settings.
112
112
  2. Resolves the candle file at `market_adapter/data/market_adapter_<bot-key>_1h.json`.
113
113
  3. Looks up the matching market profile in `profiles/market_profiles.json` for AMA defaults.
114
- 4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.6).
114
+ 4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.5).
115
115
 
116
116
  > The candle file must exist — run the market adapter LP exporter first if needed (see [Getting Blockchain Data](#getting-blockchain-data)).
117
117
 
@@ -189,7 +189,7 @@ Indicator on/off state is not a generation-time flag: `SMA`, `VWMA`, `AMA`, `Ran
189
189
  | `--sma-period <n>` | SMA period | `500` |
190
190
  | `--ama-er-period <n>` | AMA ER period | `781` |
191
191
  | `--ama-fast-period <n>` | AMA fast period | `5.2` |
192
- | `--ama-slow-period <n>` | AMA slow period | `83.6` |
192
+ | `--ama-slow-period <n>` | AMA slow period | `83.5` |
193
193
  | `--vwap-bars <n>` | Rolling VWMA window | `500` |
194
194
  | `--no-sma` | Disable SMA | — |
195
195
  | `--no-vwap` | Disable VWMA | — |
@@ -166,7 +166,7 @@ All panels share aligned vertical time grid lines, and the bottom output panel s
166
166
  |------|-------|---------|---------|
167
167
  | **nz%** | 0–1 | 0.00 | Neutral zone: dead-band below which offset is forced to 0 |
168
168
  | **lb** | 4–32 | 16 | Logarithmic. Lookback bars for AMA slope calculation |
169
- | **amaS%** | 0.06–0.12 | 0.09 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
169
+ | **amaS%** | 0.06–0.12 | 0.1 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
170
170
  | **kalS%** | 0.75–1.5 | 1.2 | Logarithmic. Gear ratio for Kalman composite saturation |
171
171
  | **clip%** | 0–20 | 10 | Percentile clip: filters extreme inputs (0 = off) |
172
172
 
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.16",
3
+ "version": "1.6.17",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.6.16",
5
+ "version": "1.6.17",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.6.16",
4
+ "version": "1.6.17",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -177,11 +177,13 @@ function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel) {
177
177
  const move = results.map((r) => r.movement);
178
178
  const cacheSlow = metricCache.map((m) => m.slow);
179
179
  const cacheMove = metricCache.map((m) => m.movement);
180
+ // Current built-in presets: AMA1 is the λ=0.0031 fit, AMA2–AMA4 follow the
181
+ // exact −9%/step effective-smoothing ladder (see MARKET_ADAPTER.AMAS).
180
182
  const amaAnnotations = [
181
183
  { label: 'AMA1', lambda: 0.0031, slow: 62.1, color: '#ef5350' },
182
- { label: 'AMA2', lambda: 0.0025, slow: 72.0, color: '#fb8c00' },
183
- { label: 'AMA3', lambda: 0.00185, slow: 83.6, color: '#5c9ee6' },
184
- { label: 'AMA4', lambda: 0.0013, slow: 96.9, color: '#26a69a' },
184
+ { label: 'AMA2', lambda: 0.0025, slow: 71.5, color: '#fb8c00' },
185
+ { label: 'AMA3', lambda: 0.00185, slow: 83.5, color: '#5c9ee6' },
186
+ { label: 'AMA4', lambda: 0.0013, slow: 99.3, color: '#26a69a' },
185
187
  ].filter(a => a.lambda >= xs[0] && a.lambda <= xs[xs.length - 1]);
186
188
  return `<!DOCTYPE html>
187
189
  <html lang="en">
@@ -69,7 +69,7 @@ function gridSimNonNegativeInt(value, fallback) {
69
69
  * UNCLIPPED `slopePct`; the clipped value only feeds the range tilt.
70
70
  */
71
71
  function gridSimSlopeSignal(slopePct, clipThreshold, cfg) {
72
- const maxSlopePct = gridSimPositiveNumber(cfg?.maxSlopePct, 0.09);
72
+ const maxSlopePct = gridSimPositiveNumber(cfg?.maxSlopePct, 0.1);
73
73
  const neutralZonePct = Number.isFinite(Number(cfg?.neutralZonePct)) ? Number(cfg.neutralZonePct) : 0;
74
74
  const maxSlopeOffset = gridSimPositiveNumber(cfg?.maxSlopeOffset, 0.5);
75
75
  // null/undefined/NaN all mean "no slope this bar" (computeAmaSlopeWeights'
@@ -637,9 +637,9 @@ function generateHTML(data, title = 'TradingView Style Research') {
637
637
  <button type="button" class="step-btn" id="ama-slow-dec">▼</button>
638
638
  </span>
639
639
  <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA1" title="AMA1 (slow 62.1)">1</button>
640
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA2" title="AMA2 (slow 72.0)">2</button>
641
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA3" title="AMA3 (slow 83.6)">3</button>
642
- <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA4" title="AMA4 (slow 96.9)">4</button>
640
+ <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA2" title="AMA2 (slow 71.5)">2</button>
641
+ <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA3" title="AMA3 (slow 83.5)">3</button>
642
+ <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA4" title="AMA4 (slow 99.3)">4</button>
643
643
  </div>
644
644
  <div class="indicator" title="Range min/max built only from the live AMA price (red above, green below); Scale sizes it by AMA slope like the grid build. Turning either on also turns on what it needs (Range → AMA, Scale → Range + AMA)">
645
645
  <label><input type="checkbox" id="range-toggle"${defaults.rangeEnabled ? ' checked' : ''}> Range</label>
@@ -1723,7 +1723,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1723
1723
  const slopeCfg = payload.rangeSlope || {};
1724
1724
  const gridCfg = payload.grid || null;
1725
1725
  const lookback = resolveSlopeLookbackBars();
1726
- const maxSlope = Number(slopeCfg.maxSlopePct) > 0 ? Number(slopeCfg.maxSlopePct) : 0.09;
1726
+ const maxSlope = Number(slopeCfg.maxSlopePct) > 0 ? Number(slopeCfg.maxSlopePct) : 0.1;
1727
1727
  const neutral = Number(slopeCfg.neutralZonePct) >= 0 ? Number(slopeCfg.neutralZonePct) : 0;
1728
1728
  const maxSlopeOffset = Number(slopeCfg.maxSlopeOffset) > 0 ? Number(slopeCfg.maxSlopeOffset) : 0.5;
1729
1729
  const maxAsym = gridCfg && Number(gridCfg.maxAsymmetryFactor) > 0
@@ -196,7 +196,7 @@ function resolveAma(cfg) {
196
196
  if (cfg.er != null || cfg.fast != null || cfg.slow != null) {
197
197
  const er = cfg.er ?? 781;
198
198
  const fast = cfg.fast ?? 5.2;
199
- const slow = cfg.slow ?? 83.6;
199
+ const slow = cfg.slow ?? MA.AMAS.AMA3.slowPeriod;
200
200
  return { name: `custom(er=${er},f=${fast},s=${slow})`, er, fast, slow };
201
201
  }
202
202
  const presets = MA.AMAS;
@@ -157,6 +157,9 @@ declare function loadGeneralSettings(): {
157
157
  FILL_TOTALS_RETRY_MAX_MS: number;
158
158
  SPREAD_STALE_WARN_MS: number;
159
159
  SPREAD_STALE_ESCALATE_MS: number;
160
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
161
+ SPREAD_STALE_FUND_ESCALATE_MS: number;
162
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
160
163
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
161
164
  SPREAD_STALE_TRANSIENT_GRACE: number;
162
165
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
@@ -202,7 +202,7 @@ declare class MasterPasswordError extends Error {
202
202
  * @returns {boolean} True if the error indicates authentication could not complete
203
203
  */
204
204
  declare function isMasterPasswordFailure(err: unknown): boolean;
205
- type VaultSecret = {
205
+ export type VaultSecret = {
206
206
  kind: string;
207
207
  version: number;
208
208
  vaultKeyHex: string;
@@ -230,6 +230,9 @@ declare let TIMING: {
230
230
  FILL_TOTALS_RETRY_MAX_MS: number;
231
231
  SPREAD_STALE_WARN_MS: number;
232
232
  SPREAD_STALE_ESCALATE_MS: number;
233
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
234
+ SPREAD_STALE_FUND_ESCALATE_MS: number;
235
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
233
236
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
234
237
  SPREAD_STALE_TRANSIENT_GRACE: number;
235
238
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
@@ -773,6 +776,9 @@ declare function buildDefaultGeneralSettings(): {
773
776
  FILL_TOTALS_RETRY_MAX_MS: number;
774
777
  SPREAD_STALE_WARN_MS: number;
775
778
  SPREAD_STALE_ESCALATE_MS: number;
779
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: number;
780
+ SPREAD_STALE_FUND_ESCALATE_MS: number;
781
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: number;
776
782
  SPREAD_CORRECTION_MAX_ATTEMPTS: number;
777
783
  SPREAD_STALE_TRANSIENT_GRACE: number;
778
784
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
@@ -335,6 +335,28 @@ let TIMING = {
335
335
  // by moving the boundary). Time-based so it holds for any tick cadence.
336
336
  SPREAD_STALE_WARN_MS: 10 * 60 * 1000, // 10 minutes
337
337
  SPREAD_STALE_ESCALATE_MS: 30 * 60 * 1000, // 30 minutes
338
+ // SPREAD_STALE_IN_TOLERANCE_RESET_MS: how long the spread must stay
339
+ // continuously within tolerance before the persistence clock is cleared.
340
+ // A single in-tolerance reading between refusals must NOT clear it: the
341
+ // measured spread oscillates around the threshold, and resetting on each
342
+ // good glance let a live bot sit out of tolerance for 84 minutes while
343
+ // every individual cycle looked recoverable. A placed correction always
344
+ // clears the clock immediately.
345
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: 10 * 60 * 1000, // 10 minutes
346
+ // SPREAD_STALE_FUND_ESCALATE_MS: escalated window used when the correction
347
+ // reports a RAIL-OVERSUBSCRIBED fund stall (virtual reservation > chain
348
+ // free on the corrected side, e.g. free 454560 vs virtual 456046). That is
349
+ // not "wait for a fill" — the rail itself must be re-sized from chain
350
+ // truth, which the structural re-center does. A shorter window keeps the
351
+ // side dead for minutes instead of the 84 minutes observed live.
352
+ SPREAD_STALE_FUND_ESCALATE_MS: 5 * 60 * 1000, // 5 minutes
353
+ // SPREAD_STALE_GEOMETRY_ESCALATE_MS: escalated window used when the
354
+ // correction reports the geometry bind 'last-fill-blocked' — every
355
+ // tightening slot on the corrected side sits at/through the last fill, i.e.
356
+ // the sell window itself is behind the last sale (boundary/crawl lag). No
357
+ // amount of waiting fixes that; a re-center does. Waiting the structural
358
+ // 30 minutes just leaves the side unquoted.
359
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: 10 * 60 * 1000, // 10 minutes
338
360
  // SPREAD_CORRECTION_MAX_ATTEMPTS: bounded attempts for one spread-correction
339
361
  // cycle (initial broadcast + fresh-master re-plan retries). Kept next to the
340
362
  // other SPREAD_* tunables so the retry budget is centralized; a value < 1
@@ -1162,7 +1184,7 @@ let MARKET_ADAPTER = {
1162
1184
  // Lower values make the AMA channel reach maximum influence more easily.
1163
1185
  // Higher values require a stronger price move before AMA reaches full effect.
1164
1186
  // nob: amaS% (AMA Max Slope %)
1165
- DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: 0.09,
1187
+ DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: 0.1,
1166
1188
  // DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: Trend size that counts as "full strength" for
1167
1189
  // the Kalman composite branch. Kept separate from the AMA slope knob so the two
1168
1190
  // channels can saturate independently.
@@ -1383,9 +1405,15 @@ let MARKET_ADAPTER = {
1383
1405
  // DEFAULT_AMA_KEY: Built-in default profile for `gridPrice: "ama"` when no
1384
1406
  // pair-specific market_profiles entry exists.
1385
1407
  DEFAULT_AMA_KEY: 'AMA3',
1386
- // AMAS: Built-in AMA presets derived from the local LP 1.19.133 fitting results.
1387
- // Fitted with per-AMA λ weights (0.0031 / 0.0025 / 0.00185 / 0.0013) on 1h candles
1408
+ // AMAS: Built-in AMA presets. AMA1 is the fitted winner (λ=0.0031) on 1h candles
1388
1409
  // (2023-07 → 2026-07, SMA-warmup-aligned optimizer, ER=781 fixed, Fast=5.2 fixed).
1410
+ // AMA2–AMA4 are spaced from AMA1 on an exact −9%-per-step effective-smoothing
1411
+ // ladder evaluated at AMA_CONVERGENCE_ER_AVG (0.151):
1412
+ // smooth = (ER·(fastSC−slowSC) + slowSC)², fastSC = 2/(fastPeriod+1),
1413
+ // slowSC = 2/(slowPeriod+1).
1414
+ // Unrounded targets are 62.10 / 71.48 / 83.46 / 99.27; the values below are
1415
+ // rounded to one decimal (the optimizer's 0.1 quantum). Re-derive if
1416
+ // fastPeriod or AMA_CONVERGENCE_ER_AVG changes.
1389
1417
  // These serve as stable defaults for the market adapter and can be overridden by
1390
1418
  // pair-specific profiles in profiles/market_profiles.json.
1391
1419
  AMAS: {
@@ -1399,19 +1427,19 @@ let MARKET_ADAPTER = {
1399
1427
  name: 'AMA2',
1400
1428
  erPeriod: 781,
1401
1429
  fastPeriod: 5.2,
1402
- slowPeriod: 72.0,
1430
+ slowPeriod: 71.5,
1403
1431
  },
1404
1432
  AMA3: {
1405
1433
  name: 'AMA3',
1406
1434
  erPeriod: 781,
1407
1435
  fastPeriod: 5.2,
1408
- slowPeriod: 83.6,
1436
+ slowPeriod: 83.5,
1409
1437
  },
1410
1438
  AMA4: {
1411
1439
  name: 'AMA4',
1412
1440
  erPeriod: 781,
1413
1441
  fastPeriod: 5.2,
1414
- slowPeriod: 96.9,
1442
+ slowPeriod: 99.3,
1415
1443
  },
1416
1444
  },
1417
1445
  // AMA_CONVERGENCE_ER_AVG: Typical market Efficiency Ratio used to estimate
@@ -65,6 +65,25 @@ declare function borrowAmountForCollateral(collateralAmountInt: unknown, collate
65
65
  * accept op).
66
66
  */
67
67
  declare function capBorrowToCollateral(requestedBorrowInt: unknown, availableCollateralInt: unknown, collateralPrice: OfferPrice | null | undefined, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
68
+ /**
69
+ * Pick the conversion rate used to value collateral.
70
+ *
71
+ * LP-share collateral is a claim on pool reserves, so its market value comes
72
+ * from the live pool and must win over the credit offer's fixed contract price
73
+ * (which is a haircut that can go stale). Other collateral uses the offer
74
+ * price; the pool rate is only a fallback.
75
+ *
76
+ * Returns the selected rate plus its source, or null/ null when neither is
77
+ * usable.
78
+ */
79
+ declare function selectCollateralConversionRate({ offerRate, poolRate, isLiquidityPoolShare, }: {
80
+ offerRate?: unknown;
81
+ poolRate?: unknown;
82
+ isLiquidityPoolShare?: boolean;
83
+ }): {
84
+ rate: number | null;
85
+ source: 'offer' | 'pool' | null;
86
+ };
68
87
  /**
69
88
  * Per-deal CR from floats plus a conversion rate:
70
89
  * (collateralFloat * rate) / debtFloat.
@@ -94,5 +113,5 @@ declare function dailyOfferFeeRate(offer: {
94
113
  * (repay * feeRate + denom - 1) / denom. Zero when nothing is owed.
95
114
  */
96
115
  declare function creditDealFee(repayAmountInt: unknown, feeRate: unknown, feeDenom: unknown): number;
97
- export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
116
+ export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, selectCollateralConversionRate, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
98
117
  //# sourceMappingURL=credit_pricing.d.ts.map
@@ -179,6 +179,28 @@ function capBorrowToCollateral(requestedBorrowInt, availableCollateralInt, colla
179
179
  return null;
180
180
  return Math.min(requested, budgetBorrow);
181
181
  }
182
+ /**
183
+ * Pick the conversion rate used to value collateral.
184
+ *
185
+ * LP-share collateral is a claim on pool reserves, so its market value comes
186
+ * from the live pool and must win over the credit offer's fixed contract price
187
+ * (which is a haircut that can go stale). Other collateral uses the offer
188
+ * price; the pool rate is only a fallback.
189
+ *
190
+ * Returns the selected rate plus its source, or null/ null when neither is
191
+ * usable.
192
+ */
193
+ function selectCollateralConversionRate({ offerRate, poolRate, isLiquidityPoolShare, }) {
194
+ const offer = positiveOrNull(offerRate);
195
+ const pool = positiveOrNull(poolRate);
196
+ if (isLiquidityPoolShare && pool !== null)
197
+ return { rate: pool, source: 'pool' };
198
+ if (offer !== null)
199
+ return { rate: offer, source: 'offer' };
200
+ if (pool !== null)
201
+ return { rate: pool, source: 'pool' };
202
+ return { rate: null, source: null };
203
+ }
182
204
  /**
183
205
  * Per-deal CR from floats plus a conversion rate:
184
206
  * (collateralFloat * rate) / debtFloat.
@@ -243,5 +265,5 @@ function creditDealFee(repayAmountInt, feeRate, feeDenom) {
243
265
  return 0;
244
266
  return Number(((repay * rate) + denom - 1n) / denom);
245
267
  }
246
- export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
268
+ export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, selectCollateralConversionRate, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
247
269
  //# sourceMappingURL=credit_pricing.js.map
@@ -672,14 +672,32 @@ class CreditRuntime {
672
672
  const cached = positiveOrNull(this.state.positions[posKey]?.creditConversionRate);
673
673
  const cachedAt = this.state.positions[posKey]?.creditConversionRateAt || 0;
674
674
  const cachedIsFresh = cached !== null && (Date.now() - cachedAt) < CREDIT_RATE_MAX_AGE_MS;
675
- // Prefer the offer map (live-offer / owned-offer) — it provides an
676
- // authoritative conversion rate even for LP share collateral that has
677
- // an explicit entry in acceptable_collateral. Only when the offer map
678
- // has no entry for the debt/collateral pair do we fall back to pool
679
- // derivation (reserveA*priceA + reserveB*priceB / supply). This avoids
680
- // re-attempting deriveLiquidityPoolTokenValue on every hourly call
681
- // when a fresh live-offer rate exists and would otherwise log a pool
682
- // failure even though the offer would succeed.
675
+ // LP-share collateral is a claim on pool reserves, so its market value
676
+ // comes from the live pool and must win over the offer's fixed
677
+ // acceptable_collateral price (a contract haircut). This matches the
678
+ // borrow gate in _calculateCollateralValueInDebtAsset(). Other
679
+ // collateral uses the offer map; pool/market pricing is only a
680
+ // fallback for those pairs.
681
+ {
682
+ const debtAsset = await this._resolveAsset(debtAssetId);
683
+ const collateralAsset = await this._resolveAsset(collateralAssetId);
684
+ if (collateralAsset?.for_liquidity_pool && debtAsset?.id) {
685
+ const poolRate = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true).catch((e) => {
686
+ this.log(`credit runtime: pool token rate derivation failed for ${collateralAsset.id}/${debtAsset.id}: ${getErrorMessage(e)}`);
687
+ return null;
688
+ });
689
+ if (poolRate != null && Number.isFinite(poolRate) && poolRate > 0) {
690
+ if (!this.state.positions[posKey])
691
+ this.state.positions[posKey] = {};
692
+ this.state.positions[posKey].creditConversionRate = poolRate;
693
+ this.state.positions[posKey].creditConversionRateAt = Date.now();
694
+ return options.includeSource ? { price: poolRate, source: 'pool-derived' } : poolRate;
695
+ }
696
+ }
697
+ }
698
+ // Non-LP collateral uses the offer map (live-offer / owned-offer) —
699
+ // the offer's acceptable_collateral price is the contract's
700
+ // debt-per-collateral conversion rate.
683
701
  const offerIds = new Set();
684
702
  const deals = Array.isArray(this.state.positions[posKey]?.creditDeals)
685
703
  ? this.state.positions[posKey].creditDeals
@@ -747,14 +765,13 @@ class CreditRuntime {
747
765
  return options.includeSource ? { price: rate, source: 'live-offer' } : rate;
748
766
  }
749
767
  }
750
- // Offer map had no usable entry — fall back to pool derivation for LP
751
- // shares, then to universal DEX pricing (direct market, else bridge
752
- // hops via BTS) so every collateral/debt pair resolves a rate even
753
- // when the collateral or pool is not part of the credit offer.
754
- // Only attempt when cached is stale to avoid hourly
755
- // deriveLiquidityPoolTokenValue failures when a fresh live-offer rate
756
- // would already have returned. Reuses debtAsset/collateralAsset
757
- // resolved above.
768
+ // Offer map had no usable entry (or the LP pool valuation above
769
+ // failed) — fall back to pool derivation for LP shares, then to
770
+ // universal DEX pricing (direct market, else bridge hops via BTS) so
771
+ // every collateral/debt pair resolves a rate even when the collateral
772
+ // or pool is not part of the credit offer. Only attempt when cached is
773
+ // stale to avoid hourly deriveLiquidityPoolTokenValue failures.
774
+ // Reuses debtAsset/collateralAsset resolved above.
758
775
  if (!cachedIsFresh) {
759
776
  if (collateralAsset?.for_liquidity_pool && debtAsset?.id) {
760
777
  const poolRate = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true).catch((e) => {
@@ -189,9 +189,11 @@ declare class DEXBot implements BotLike {
189
189
  _outOfSpreadSince: number;
190
190
  _outOfSpreadStaleWarned: boolean;
191
191
  _outOfSpreadTransientCount: number;
192
+ /** When the spread first read within tolerance; cleared on any out-of-tolerance cycle. */
193
+ _outOfSpreadToleranceSince: number;
192
194
  _postRecoveryRebalanceDefers: number;
193
195
  _skipEmptyReadConfirmDelay: boolean;
194
- _spreadFundsExhausted: boolean;
196
+ _spreadStallArmed: boolean;
195
197
  _spreadCorrectionStall: SpreadCorrectionStall | null;
196
198
  _strandedHoldSince: Map<string, number>;
197
199
  _structuralGridResyncDeferCount: number;
@@ -217,9 +217,11 @@ class DEXBot {
217
217
  _outOfSpreadSince;
218
218
  _outOfSpreadStaleWarned;
219
219
  _outOfSpreadTransientCount;
220
+ /** When the spread first read within tolerance; cleared on any out-of-tolerance cycle. */
221
+ _outOfSpreadToleranceSince;
220
222
  _postRecoveryRebalanceDefers;
221
223
  _skipEmptyReadConfirmDelay;
222
- _spreadFundsExhausted;
224
+ _spreadStallArmed;
223
225
  _spreadCorrectionStall;
224
226
  _strandedHoldSince;
225
227
  _structuralGridResyncDeferCount;
@@ -279,6 +281,7 @@ class DEXBot {
279
281
  this._outOfSpreadSince = 0;
280
282
  this._outOfSpreadStaleWarned = false;
281
283
  this._outOfSpreadTransientCount = 0;
284
+ this._outOfSpreadToleranceSince = 0;
282
285
  this.logPrefix = options.logPrefix || '';
283
286
  this._credentialDaemonWatchdogInterval = null;
284
287
  this._credentialDaemonDown = false;
@@ -338,7 +341,7 @@ class DEXBot {
338
341
  // Spread-correction stall state: the boolean gate and its companion cause
339
342
  // are read by getTargetedSyncReason before the first spread check, so
340
343
  // initialize both rather than leaving them undefined.
341
- this._spreadFundsExhausted = false;
344
+ this._spreadStallArmed = false;
342
345
  this._spreadCorrectionStall = null;
343
346
  this._lightweightSyncCheckAt = 0;
344
347
  this._targetedDriftSyncCooldownMs = this.config.timing?.TARGETED_DRIFT_SYNC_COOLDOWN_MS;
@@ -8,6 +8,7 @@
8
8
  * the same pattern as dexbot_fill_runtime.ts.
9
9
  */
10
10
  import * as chainOrdersModule from './chain_orders.js';
11
+ import { isLastFillGuardBlocked } from './order/utils/system.js';
11
12
  /**
12
13
  * Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
13
14
  * geometry (boundaryIdx/_gapSlots at execution time). The stamp freezes
@@ -56,6 +57,19 @@ export interface CowResult extends JsonObj {
56
57
  workingIndexes: unknown;
57
58
  origin?: string;
58
59
  refillSlotIds?: string[];
60
+ /**
61
+ * Owed fill-crawl records this plan's derivation actually folded. The
62
+ * commit clears ONLY these; a record the derivation could not apply (a
63
+ * truncated cross-chunk shift, an edge-classified slot, a newer record for
64
+ * the same slot) stays owed. Without this the commit cleared the whole
65
+ * ledger and silently lost the difference (2026-10-25: 7 fills swept
66
+ * slots 147-153, boundary ended 7 levels behind).
67
+ */
68
+ consumedCrawlIds?: Array<{
69
+ slotId: string;
70
+ side: string;
71
+ ts?: number;
72
+ }>;
59
73
  fills?: unknown[];
60
74
  }
61
75
  /** A chain order enriched with the loose fields COW recovery reads. */
@@ -304,47 +318,24 @@ declare function recordRestampBuyAboveAnchor(bot: BotLike, price: unknown, type:
304
318
  * @returns {string[]} destinations inside the gap band
305
319
  */
306
320
  declare function collectGapBandPlacementShadowSlots(actions: CowAction[] | null | undefined, boundary: unknown, gapSlots: unknown): string[];
307
- /**
308
- * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
309
- * last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
310
- * SELL < x*(1 + i/2/100)
311
- * e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
312
- * Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
313
- * bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
314
- * bypass only via the violation-reducing allowance (origin='gap-evacuation',
315
- * UPDATE-only, frozen B-stamp or live-proven isEvacuationRotationAllowed) —
316
- * see the UPDATE rotation guard block.
317
- * The pivot is the latest fill of either side and is never expired: it stays
318
- * the durable mark (last sold level floors new sells; buy fills pull it down
319
- * and re-open the sell side, buy-below-sell is never gated).
320
- * @param {number} price - Target order price
321
- * @param {number} size - Order size (unused, kept for compat)
322
- * @param {string} type - ORDER_TYPES.BUY/SELL
323
- * @param {number|null} lastPrice - Most recent fill price
324
- * @param {string|null} lastType - Most recent fill side (BUY/SELL)
325
- * @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If assets object passed, falls back to default.
326
- * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
327
- */
328
- declare function isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, incrementPercent: number): {
329
- blocked: boolean;
330
- pivot: number | null;
331
- halfInc?: number;
332
- threshold?: number | null;
333
- };
334
321
  /**
335
322
  * Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
336
323
  *
337
- * The bypass exists so gap repair can close even after a recent fill (the
338
- * correction is tightening the spread, not chasing it). It must not become a
339
- * licence to place THROUGH the market the bot last traded at:
324
+ * Remaining purpose: the STARTUP BOOK SEED proxy. Before the first real fill a
325
+ * single-sided book arms the guard on our own resting quote (max bid / min
326
+ * ask) — a proxy that `b14a1fc8` deliberately keeps non-persistent ("a book
327
+ * seed never fossilizes into the snapshot as market truth") because it goes
328
+ * wrong whenever the book is not adjacent to the last fill. Blocking a
329
+ * tightening placement against that proxy would be arbitrary, so the correction
330
+ * is released from it while the local snapshot can be trusted.
331
+ *
332
+ * A real FILL reference always denies the bypass. Since the planner now filters
333
+ * candidates with the SAME predicate the guard applies, planner-built
334
+ * corrections never even propose an op that would need it — the bypass is a
335
+ * proxy-case valve, not a licence to trade through the last real fill.
340
336
  *
341
- * 1. A real fill pivot (`lastFillPivotSource === 'fill'`) is always honored —
342
- * no bypass. A sell below the last fill (or a buy above it) is the
343
- * issue-#31 adverse fill.
344
- * 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
345
- * fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
346
- * A stale snapshot (known-unmatched chain orders, or an old sync) can hide
347
- * the real window edge, so the bypass is withheld and the guard applies.
337
+ * Denied too when the snapshot is stale or has known-unmatched chain orders
338
+ * (a stale edge can hide the real window edge), fail-closed on a gate throw.
348
339
  *
349
340
  * Exported for tests.
350
341
  * @param {Object} bot