dexbot 1.7.2 → 1.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +6 -0
  11. package/dist/modules/bot_defaults.js +6 -1
  12. package/dist/modules/constants.d.ts +12 -0
  13. package/dist/modules/constants.js +66 -0
  14. package/dist/modules/dexbot_class.d.ts +17 -0
  15. package/dist/modules/dexbot_class.js +56 -1
  16. package/dist/modules/dexbot_cow_runtime.js +231 -19
  17. package/dist/modules/dexbot_maintenance_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_maintenance_runtime.js +164 -11
  19. package/dist/modules/dexbot_state_recovery.js +15 -1
  20. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  21. package/dist/modules/launcher/instance_lock.js +131 -0
  22. package/dist/modules/order/grid.d.ts +19 -0
  23. package/dist/modules/order/grid.js +40 -14
  24. package/dist/modules/order/index.d.ts +15 -1
  25. package/dist/modules/order/manager.d.ts +21 -0
  26. package/dist/modules/order/manager.js +119 -12
  27. package/dist/modules/order/placement_lock.d.ts +30 -0
  28. package/dist/modules/order/placement_lock.js +48 -0
  29. package/dist/modules/order/utils/order.d.ts +39 -1
  30. package/dist/modules/order/utils/order.js +73 -2
  31. package/dist/modules/order/utils/system.d.ts +112 -3
  32. package/dist/modules/order/utils/system.js +368 -6
  33. package/dist/modules/paths.d.ts +1 -0
  34. package/dist/modules/paths.js +1 -0
  35. package/dist/modules/timing_policy.js +2 -0
  36. package/dist/modules/types.d.ts +27 -0
  37. package/dist/pm2.js +126 -0
  38. package/dist/unlock.js +26 -1
  39. package/docs/DEXBOT_COMPARISON.md +5 -5
  40. package/docs/EVOLUTION.md +10 -9
  41. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  42. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +155 -2
  43. package/docs/README.md +1 -1
  44. package/modules/README.md +1 -0
  45. package/package.json +2 -1
@@ -239,6 +239,15 @@ export interface BotLike {
239
239
  * persistence clock — it must hold for SPREAD_STALE_IN_TOLERANCE_RESET_MS.
240
240
  */
241
241
  _outOfSpreadToleranceSince: number;
242
+ /**
243
+ * One-shot level-triggered spread recheck while the grid is out of
244
+ * tolerance (the base maintenance cadence can be hours; every watchdog
245
+ * clock assumes the check is evaluated).
246
+ */
247
+ _spreadRecheckTimer: ReturnType<typeof setTimeout> | null;
248
+ _spreadRecheckInFlight: boolean;
249
+ /** A placement that did not reduce the violation was already reported. */
250
+ _outOfSpreadNoProgressWarned: boolean;
242
251
  _strandedHoldSince: Map<string, number>;
243
252
  _recoverySyncInFlight: number;
244
253
  _batchInFlight: number;
@@ -536,6 +545,16 @@ export interface BotMetrics extends UnknownRecord {
536
545
  spreadCorrectionRefusalCauses: Record<string, number>;
537
546
  /** Bounded re-plan retries attempted after a transient spread-correction refusal. */
538
547
  spreadCorrectionRetryCount: number;
548
+ /** Stale plans dropped because there was no fill context to re-plan from (batch not broadcast). */
549
+ stalePlanDroppedCount: number;
550
+ /** Stale fill batches that proceeded anyway at the re-plan limit (bounded policy). */
551
+ stalePlanProceedCount: number;
552
+ /** Size updates skipped because a PARTIAL slot's booked remaining already matched (post-fill growth refused). */
553
+ clampedNoopUpdateCount: number;
554
+ /** Planned operations thrown away when a definitive chunk failure aborted the remaining chunks. */
555
+ chunkAbortedOpCount: number;
556
+ /** Rails re-placed by the post-recovery rebalance (snapshot reload / repair contexts). */
557
+ reloadReplacedRailCount: number;
539
558
  }
540
559
  /** An unmatched chain order surfaced by a sync pass. */
541
560
  export interface UnmatchedChainOrder extends UnknownRecord {
@@ -1187,6 +1206,14 @@ export interface OrderManagerLike {
1187
1206
  _lastMarketFillPrice?: number | null;
1188
1207
  _lastMarketFillType?: string | null;
1189
1208
  _lastMarketFillAt?: number | null;
1209
+ /**
1210
+ * Refused (off-market) fill level: a fill the pivot-arming policy refused
1211
+ * (§9.12/P1) still marks its own level as a same-level re-fill block for a
1212
+ * short TTL (§9.12/P2 amended). In-memory only — never persisted.
1213
+ */
1214
+ _lastRefusedFillPrice?: number | null;
1215
+ _lastRefusedFillType?: string | null;
1216
+ _lastRefusedFillAt?: number | null;
1190
1217
  _liveMarketPrice?: number | null;
1191
1218
  _liveMarketPriceAt?: number | null;
1192
1219
  _liveMarketPriceAttemptedAt?: number | null;
package/dist/pm2.js CHANGED
@@ -83,6 +83,7 @@ import { existsSync } from 'node:fs';
83
83
  import { parseJsonWithComments } from './modules/order/utils/system.js';
84
84
  import { readBotsFileWithLock } from './modules/bots_file_lock.js';
85
85
  import { loadSettingsFile, selectActiveBotEntries } from './modules/bot_settings.js';
86
+ import { getProcessDiscovery } from './modules/process_discovery.js';
86
87
  import * as chainKeys from './modules/chain_keys.js';
87
88
  import * as credentialPolicy from './modules/credential_policy.js';
88
89
  import { readHeadlessPassword } from './modules/launcher/headless_password.js';
@@ -436,6 +437,20 @@ async function main({ botNameFilter = null, clawOnly = false, headless = false,
436
437
  // prefixed lines process-wide to keep the launcher banner and the
437
438
  // connection confirmation as the only startup output.
438
439
  muteChainLogs();
440
+ // DOUBLE-CONTROLLER GUARD: a monolithic instance started via
441
+ // `dexbot start` is a live controller for the same accounts this PM2
442
+ // fleet is about to own. Two controllers on one account corrupt each
443
+ // other's grids and fills (observed live 2026-11-14), so refuse here
444
+ // instead of letting the per-bot instance lock kill each PM2 app 3
445
+ // seconds later.
446
+ const monoPid = readLiveMonolithicPidLite();
447
+ if (monoPid > 0) {
448
+ console.error(pm2Error(`DEXBot2 is already running outside PM2 (monolithic PID ${monoPid}).\n` +
449
+ `Starting the PM2 fleet now would put two controllers on the same accounts.\n` +
450
+ `Stop it first with 'dexbot stop', then rerun this command.`));
451
+ await flushVersionStatusOrHeader(versionStatus);
452
+ process.exit(1);
453
+ }
439
454
  await waitForConnected(TIMING.CONNECTION_TIMEOUT_MS);
440
455
  console.log(pm2Success('Connected to BitShares'));
441
456
  }
@@ -471,6 +486,7 @@ async function main({ botNameFilter = null, clawOnly = false, headless = false,
471
486
  console.log();
472
487
  // Step 4: Start PM2
473
488
  console.log(clawOnly ? 'Starting PM2 with credential daemon only...' : 'Starting PM2 with all services...');
489
+ await warnStaleDexbotApps(apps);
474
490
  await startManagedAppsPM2(apps);
475
491
  console.log();
476
492
  console.log('='.repeat(50));
@@ -522,6 +538,116 @@ function startManagedAppsPM2(apps) {
522
538
  }
523
539
  return startPM2Process(['start', ECOSYSTEM_FILE]);
524
540
  }
541
+ /**
542
+ * Lightweight "a `dexbot start` monolithic instance is live" probe.
543
+ *
544
+ * Reads the monolithic pid file, so it must confirm the pid still belongs to
545
+ * an unlock process (a recycled pid must not block PM2 forever). Kept local
546
+ * instead of importing launcher/monolithic_runtime: pm2.ts is loaded by the
547
+ * ESM-mocked launcher tests, and that module drags in the whole launcher graph
548
+ * (bot settings, supervisor, credential runtime) for one check. The
549
+ * authoritative backstop remains the per-bot instance lock.
550
+ *
551
+ * @returns {number} Live monolithic pid, or 0 when absent/dead/unrelated
552
+ */
553
+ function readLiveMonolithicPidLite() {
554
+ try {
555
+ const pid = Number(storage.readFile(PATHS.PROFILES.MONOLITHIC_PID).trim());
556
+ if (!Number.isInteger(pid) || pid <= 0)
557
+ return 0;
558
+ const discovery = getProcessDiscovery();
559
+ if (!discovery.isAlive(pid))
560
+ return 0;
561
+ const cmdline = discovery.readCmdline(pid);
562
+ if (!/(^|[\\/])unlock\.(?:js|ts)(?:\0|$| )/.test(cmdline))
563
+ return 0;
564
+ return pid;
565
+ }
566
+ catch (_) {
567
+ return 0;
568
+ }
569
+ }
570
+ /**
571
+ * Names of PM2 apps that are RUNNING dexbot bot/runtime scripts from this
572
+ * project root. Returns [] when pm2 is unavailable or the query fails — the
573
+ * caller treats that as "cannot know", never as "none running".
574
+ */
575
+ async function listRunningDexbotAppNames() {
576
+ try {
577
+ const list = await runPm2Raw(['jlist'], { timeoutMs: 15000 });
578
+ if (list.code !== 0)
579
+ return [];
580
+ const parsed = JSON.parse(list.stdout || '[]');
581
+ if (!Array.isArray(parsed))
582
+ return [];
583
+ const names = [];
584
+ for (const app of parsed) {
585
+ const env = app?.pm2_env;
586
+ if (!env)
587
+ continue;
588
+ if (String(env.pm_cwd || '') !== PATHS.PROJECT_ROOT)
589
+ continue;
590
+ if (!/(^|[\\/])(bot|dexbot|market_adapter|credential-daemon)\.(?:js|ts)$/.test(String(env.pm_exec_path || '')))
591
+ continue;
592
+ const status = String(env.status || '');
593
+ if (status && status !== 'online' && status !== 'launching')
594
+ continue;
595
+ if (typeof app.name === 'string' && app.name)
596
+ names.push(app.name);
597
+ }
598
+ return names;
599
+ }
600
+ catch (_) {
601
+ return [];
602
+ }
603
+ }
604
+ /**
605
+ * Warn about RUNNING dexbot apps from this project root whose names are not in
606
+ * the current bots.json set (renamed bots, leftovers from an older ecosystem
607
+ * generation, a hung interactive-unlock attempt). Such an app comes back on
608
+ * every `pm2 resurrect`/reboot and can double-run an account against the
609
+ * freshly generated fleet — the exact double-controller incident of
610
+ * 2026-11-14. Warn only (never auto-delete): the single-controller instance
611
+ * lock refuses them at runtime, and deleting operator processes silently
612
+ * would hide the misconfiguration instead of surfacing it.
613
+ *
614
+ * Compared against the FULL configured bot set (not the possibly bot-filtered
615
+ * `apps` subset) so `dexbot pm2 <bot>` does not flag the operator's other,
616
+ * legitimately configured bots.
617
+ */
618
+ async function warnStaleDexbotApps(apps) {
619
+ try {
620
+ const running = await listRunningDexbotAppNames();
621
+ if (running.length === 0)
622
+ return;
623
+ const current = new Set((apps || []).map((a) => a.name));
624
+ // Full configured set from bots.json (not the possibly bot-filtered
625
+ // `apps` subset). Best-effort: a settings read failure just narrows
626
+ // the comparison to `apps` instead of blocking startup.
627
+ const configured = new Set();
628
+ try {
629
+ if (storage.exists(BOTS_JSON)) {
630
+ const { config } = loadSettingsFile(BOTS_JSON);
631
+ for (const b of selectActiveBotEntries(config)) {
632
+ if (b && b.active !== false && b.name)
633
+ configured.add(String(b.name));
634
+ }
635
+ }
636
+ }
637
+ catch (_) { /* best-effort */ }
638
+ const serviceNames = new Set(['dexbot-adapter', 'dexbot-update', 'dexbot-cred']);
639
+ for (const name of running) {
640
+ if (current.has(name) || configured.has(name) || serviceNames.has(name))
641
+ continue;
642
+ if ([...current].some((n) => isSameBotName(n, name)) || [...configured].some((n) => isSameBotName(n, name)))
643
+ continue;
644
+ console.warn(`[PM2] Stale dexbot app '${name}' is RUNNING but not in the current bots.json set ` +
645
+ `(renamed bot or leftover from an older config). It will keep running across reboots and ` +
646
+ `can double-run an account. Remove it with: pm2 delete ${name} && pm2 save`);
647
+ }
648
+ }
649
+ catch (_) { /* diagnostics only — must never block startup */ }
650
+ }
525
651
  function startCredentialDaemonPM2({ credentialEnv = {} } = {}) {
526
652
  const app = buildCredentialDaemonApp({ credentialEnv });
527
653
  const args = [
package/dist/unlock.js CHANGED
@@ -75,7 +75,7 @@ const { ensureDir } = storage;
75
75
  const { createBotSupervisor, SOCKET_PATH, forwardSignal, isPidAlive, waitForPidExit, readMarketAdapterLockPid, stopMarketAdapterFromLock, usesAmaGridPrice, waitForChildSpawn, pidMatchesScriptCandidates, candidateRuntimeScriptPaths, } = require('./modules/launcher/bot_supervisor');
76
76
  const { statusTitle, statusLabel, statusBool, statusActiveBotName, statusSuccess, statusError, colorStatus, STATUS_COLORS, readProcStat, readProcMemMB, readProcCpuTime, readProcCpuPercent, readProcUptime, formatMemoryWithUptime, printControlStatus, } = require('./modules/launcher/status_reporting');
77
77
  const { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, isProcessInDstate, stopCredentialDaemonPid, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, cleanupCredentialRuntimeFiles, readCredentialDaemonStatus, ensureLogDir: ensureMonolithicLogDir, buildDexbotStartArgs, createUpdateScheduler, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, botNotFoundMessage, printControlActionSummary, formatBotCount, } = require('./modules/launcher/monolithic_runtime');
78
- const { isConfiguredBotName } = require('./modules/launcher/runtime_mode');
78
+ const { isConfiguredBotName, listDexbotPm2Processes } = require('./modules/launcher/runtime_mode');
79
79
  const CODE_ROOT = __dirname;
80
80
  const BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
81
81
  const LOGS_DIR = PATHS.LOGS_DIR;
@@ -519,6 +519,31 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
519
519
  return;
520
520
  }
521
521
  }
522
+ // DOUBLE-CONTROLLER GUARD: refuse to start bots that a PM2 fleet is
523
+ // already running (same names). Two controllers on one account corrupt
524
+ // each other's grids and fills (observed live 2026-11-14); fail here with
525
+ // the offending app names instead of letting the per-bot instance lock
526
+ // kill the freshly unlocked bots one by one. Internal children skip the
527
+ // check — their parent launcher already ran it.
528
+ if (!clawOnly && !dryrun && !isInternalChild && launchedBotNames.length > 0) {
529
+ // listDexbotPm2Processes() already gates on the pm2 daemon pid file
530
+ // (no subprocess when PM2 was never run) and keeps only DEXBot2's own
531
+ // processes, so this stays a cheap, offline-safe probe.
532
+ const runningApps = listDexbotPm2Processes()
533
+ .map((p) => String(p?.name || ''))
534
+ .filter(Boolean);
535
+ const overlap = runningApps.filter((appName) => launchedBotNames.some((b) => isSameBotName(b, appName)));
536
+ if (overlap.length > 0) {
537
+ printLauncherHeader({ botName: effectiveBotName || botName, clawOnly, creditOnly, isolated, dryrun, headless });
538
+ console.error(`The following bot(s) are already running under PM2: ${overlap.join(', ')}.\n` +
539
+ `Starting them here too would put two controllers on the same accounts.\n` +
540
+ `Stop the PM2 fleet first: dexbot pm2 stop ${overlap.join(' ')}\n` +
541
+ ` (or run the bots under PM2 instead: dexbot pm2)`);
542
+ await flushVersionStatusOrHeader(versionStatus);
543
+ process.exitCode = 1;
544
+ return;
545
+ }
546
+ }
522
547
  try {
523
548
  if (!isDetachedSupervisorChild) {
524
549
  printLauncherHeader({ botName: effectiveBotName || botName, clawOnly, creditOnly, isolated, dryrun, headless });
@@ -1,7 +1,7 @@
1
1
  # DEXBot vs DEXBot2 — Detailed Comparison Report
2
2
 
3
3
  > **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
4
- > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.7.2).
4
+ > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.7.3).
5
5
  > **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
6
6
 
7
7
  ---
@@ -36,7 +36,7 @@
36
36
 
37
37
  | Attribute | DEXBot (original) | DEXBot2 |
38
38
  |---|---|---|
39
- | **Release Track** | 1.0.0 | v1.7.2 |
39
+ | **Release Track** | 1.0.0 | v1.7.3 |
40
40
  | **Language** | Python 3.6+ | TypeScript 5.x |
41
41
  | **Status** | Released 1.0.0, unmaintained | Active development |
42
42
  | **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
@@ -776,10 +776,10 @@ Where:
776
776
 
777
777
  | Metric | DEXBot | DEXBot2 |
778
778
  |---|---|---|
779
- | **Release Track** | 1.0.0 | v1.7.2 |
779
+ | **Release Track** | 1.0.0 | v1.7.3 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
- | **Last Commit** | May 23, 2020 | 2026-11-04 |
782
- | **Total Commits** | 2281 | 2,506 (current HEAD, v1.7.2 line) |
781
+ | **Last Commit** | May 23, 2020 | 2026-11-17 |
782
+ | **Total Commits** | 2281 | 2,517 (current HEAD, v1.7.3 line) |
783
783
  | **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
784
784
  | **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
785
785
  | **Test Files** | 16 Python test files | 367 `test_*.ts` files (350 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
package/docs/EVOLUTION.md CHANGED
@@ -2,14 +2,14 @@
2
2
 
3
3
  ## Executive Summary
4
4
 
5
- DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.7.2 stable release.
5
+ DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.7.3 stable release.
6
6
 
7
7
  ### Key Milestones
8
8
  - **Project Inception**: December 2, 2025
9
- - **Growth Phase**: 2,506 commits over ~9 active months
9
+ - **Growth Phase**: 2,517 commits over ~11 active months
10
10
  - **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
11
- - **Stability**: Progression from manual testing to a suite of 358 automated test files (live tests included in `test:live`)
12
- - **Releases**: 153 changelog entries (v0.1.0 to v1.7.2)
11
+ - **Stability**: Progression from manual testing to a suite of 366 automated test files (live tests included in `test:live`)
12
+ - **Releases**: 154 changelog entries (v0.1.0 to v1.7.3)
13
13
 
14
14
  > **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
15
15
  > bug families, and lessons — lives in
@@ -149,7 +149,7 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
149
149
 
150
150
  ## Version History
151
151
 
152
- Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-11-04). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,385 (`v0.1.0..HEAD`) and 2,492 (`HEAD`); the `v1.4.x` era rows overlap slightly because `v1.4.13` is not an ancestor of `v1.4.25` in the current history. Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
152
+ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-11-17). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,410 (`v0.1.0..HEAD`) and 2,517 (`HEAD`); the `v1.4.x` era rows overlap slightly because `v1.4.13` is not an ancestor of `v1.4.25` in the current history. Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
153
153
 
154
154
  | Era | Commits | Theme |
155
155
  |-----|--------:|-------|
@@ -177,13 +177,14 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
177
177
  | v1.6.16 → v1.6.17 | 11 | Last-fill direction guard, placeable-slot spread planning with named stalls, chain-truth funding + fill-anchored boundary re-anchor, owed-crawl consumption, restart auth-before-stop with cleared vault secret, pool-priced LP-share collateral, AMA slowPeriod/slope retune, BTS & per-token supply distribution analyzers |
178
178
  | v1.6.17 → v1.6.18 | 19 | Partial-fill re-anchor recovery (stale-evac skip, residual allow-list, crawl subsumption, rotation-only repair), rail-derived boundary + live fill/chain prices, edge-fill pivot exclusion, guard arity pinning with explicit re-arm, per-slot last-fill exclusion count, CLI `--flag=value` walker, `__test` seam guard, export-surface cleanup |
179
179
  | v1.6.18 → v1.7.0 | 11 | Liquidity depth chart + `dexbot liquid`/`liq`/`liqu`, `dexbot asset` supply distribution shortcut, pool id/pool-token chart targets + shared spawn runner, case-insensitive asset lookup, asset-report chain-request cuts, shared CLI terminal output, orphan-fill attribution + dark-level revive, stale-grid re-buy discipline, pivot clock provenance & read-time TTL |
180
- | v1.7.1 → v1.7.2 | 13 | One fill contract + fill-pipeline ratchet, fail-closed grid-update blockers with bounded escalation, single fill identity (`fill_ledger`), credit-time fill-key claim with all-or-nothing balance credits, single-winner concurrent claim, removal of the duplicate applied-amount channel and the second grace-stamp writer, COW broadcast-region leak repair, chain-observed wrong-side cancel exemptions, fill side derived from the paid asset + rail-geometry repair check, fill-anchored rebuild/load boundary, spread rotation into orphaned rail slots, consecutive grid-blocked escalation counter, live-suite env fix |
181
180
  | v1.7.0 → v1.7.1 | 22 | One existence record per slot (life-cycle registry, unknown-is-never-gone), typed three-valued broadcast outcome, timing-window policy inventory, reconciliation interleaving fuzzer, one writer per life-cycle clock, serialized placement region with lease re-verification, fill-marker idempotency, forced-retreat gap evacuation + committed-geometry sweep, unknown-gap-geometry fix, replay-safe stranded-boundary repair, stability-ranked node selection + flap scoring, chain-account `<bot>` targets for `credit`/`order`, fee-adjusted pool depth chart with both spreads, atomic branch promotion preflight |
181
+ | v1.7.1 → v1.7.2 | 14 | One fill contract + fill-pipeline ratchet, fail-closed grid-update blockers with bounded escalation, single fill identity (`fill_ledger`), credit-time fill-key claim with all-or-nothing balance credits, single-winner concurrent claim, removal of the duplicate applied-amount channel and the second grace-stamp writer, COW broadcast-region leak repair, chain-observed wrong-side cancel exemptions, fill side derived from the paid asset + rail-geometry repair check, fill-anchored rebuild/load boundary, spread rotation into orphaned rail slots, consecutive grid-blocked escalation counter, live-suite env fix |
182
+ | v1.7.2 → v1.7.3 | 10 | Plan-region serialization (`plan → broadcast → commit`), per-account single-controller lock & cross-runtime start guards, market-bounded last-fill pivot + stale pivot expiry, refused-fill same-level refill guard & policy-aware audit mirror, in-place missing UPDATE target repair, settled-pipeline structural resync gate, snapshot reload absence-grace preservation, clamped PARTIAL-growth update skip |
182
183
 
183
184
  ---
184
185
 
185
186
  **Report Originally Generated**: February 19, 2026
186
- **Last Updated**: November 4, 2026
187
- **Total Commits**: 2,506
188
- **Date Range**: December 2, 2025 – November 4, 2026
187
+ **Last Updated**: November 17, 2026
188
+ **Total Commits**: 2,517
189
+ **Date Range**: December 2, 2025 – November 17, 2026
189
190
  **Repository**: DEXBot2 (BitShares DEX Trading Bot)
@@ -805,4 +805,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
805
805
  **TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
806
806
 
807
807
  ---
808
- *Technical Reference for DEXBot2 v1.7.2 release*
808
+ *Technical Reference for DEXBot2 v1.7.3 release*
@@ -10,11 +10,12 @@
10
10
  >
11
11
  > **Scope / snapshot:** v1.0.0 → v1.7.1 (`2a85a501`, 2026-11-04), extended through the
12
12
  > post-1.7.1 work at `bc20d574` (2026-11-04). §9 is the v1.6.4 → v1.6.17
13
- > addendum; §9.10 closes the v1.6.18 review pass and §9.11 carries v1.6.18 → v1.7.1.
13
+ > addendum; §9.10 closes the v1.6.18 review pass, §9.11 carries v1.6.18 → v1.7.1,
14
+ > and §9.12 records the subsequent revised-priority review.
14
15
  >
15
16
  > **Section numbering:** Part II deliberately keeps its original `§0`–`§8` numbers because
16
17
  > source-code comments and tests cite them (e.g. `… §2 fix #1`, `… §3 lineage`); §9 is a
17
- > later addendum (v1.6.4 → v1.6.17, with §9.10/§9.11 extending it) that adds to, and does not
18
+ > later addendum (v1.6.4 → v1.6.17, with §9.10–§9.12 extending it) that adds to, and does not
18
19
  > renumber, that range. Part I uses `R1`–`R5` so the two never collide. The closing appendix
19
20
  > is unnumbered (`A`).
20
21
  >
@@ -50,6 +51,7 @@
50
51
  - 9. COW Broadcast, Resync & Geometry Safety (v1.6.4 → v1.6.17) — addendum
51
52
  - 9.10 Review pass over v1.6.12 → v1.6.17 (findings P1–P5), released in v1.6.18
52
53
  - 9.11 v1.6.18 → v1.7.1: fill identity, absence and the geometry budget
54
+ - 9.12 Revised priority list: counter-orders, pivot evidence and level-triggered repair
53
55
  - A. Grid-Price Invariant — former failure trace (appendix)
54
56
 
55
57
  ---
@@ -1004,6 +1006,157 @@ re-planning instead of letting its cancel teeth destroy the rotation (`7618f299`
1004
1006
  is not a style complaint. Every family above is that pattern applied to a
1005
1007
  different noun — price, fill, existence.
1006
1008
 
1009
+ ##### 9.12 Revised priority list: counter-orders, pivot evidence and level-triggered repair
1010
+
1011
+ This review followed the live out-of-spread incident in priority order. The ordering
1012
+ matters: a later watchdog cannot repair a counter-order that an earlier hard veto
1013
+ removed, and a pivot policy cannot be trusted if rotation has already corrupted the
1014
+ ladder it anchors.
1015
+
1016
+ **P0 — keep the counter-order executable.** `describeMarketCrossingActions` uses the
1017
+ single recency-aware `resolveSpreadCrossingFloor` only for an observation. It reports
1018
+ CREATE/UPDATE actions across the floor but never removes them. The internal crossed-book
1019
+ assertion remains blocking: BUY-versus-SELL collisions inside the bot's own simulated
1020
+ book are a different invariant. A stale bot-mid must not provide a second floor or veto
1021
+ the only action that can narrow a gap.
1022
+
1023
+ **P1 — only current-window evidence may arm the pivot.** Fill provenance now has two
1024
+ market-bound checks while the cached market read is fresh: wrong-side fills are refused,
1025
+ and fills more than `GRID_LIMITS.LAST_FILL_PIVOT_MAX_MID_DISTANCE_STEPS` ladder steps
1026
+ from the market are refused symmetrically. The check fails open when the read is absent
1027
+ or stale. Separately, `OrderManager.recordLastFilledPrices` skips fills whose current
1028
+ slot is in the gap band: those are stranded residuals, not window trades. Edge-pinned
1029
+ fills remain excluded by the existing shared classifier. A rail/window fill is still
1030
+ recorded once, by the existing pivot writer.
1031
+
1032
+ **P2 — the pivot may not veto its own counter-order territory.** The shared
1033
+ `evaluateLastFillGuard` verdict is used by both COW placement checks and the final
1034
+ pre-broadcast gate. A SELL strictly below a SELL pivot, inside the band that the fill
1035
+ anchor itself derives, is allowed only when `boundary >= pivotIdx - gapSlots`; this is
1036
+ geometry evidence that the crawl is not behind the fill. The exact pivot level remains
1037
+ blocked as a same-level re-fill, and the BUY mirror remains blocked. Unknown geometry,
1038
+ off-ladder prices and book-seeded pivots fail closed for the exemption.
1039
+
1040
+ **P3 — a rotation moves ownership, not ladder identity.** In
1041
+ `buildCowResultFromPlan`, a rotation UPDATE has two effects: the source becomes a hole
1042
+ at its own genesis price, while the destination receives the planned price/size. The
1043
+ source is never re-priced to the destination. The invariant is checked before apply and
1044
+ again by the post-commit transition; non-rotation partial UPDATEs remain in-place size
1045
+ updates.
1046
+
1047
+ **P4 — a repair must reduce the measured violation.** The entry and post-placement
1048
+ readings share `measureSpreadExcess`, including the same slot-N live-window filter and
1049
+ one-sided handling. `trackOutOfSpreadStaleness` clears its clock after a placement only
1050
+ when `excessAfter < excessBefore`; an unchanged placement is logged and remains stale.
1051
+ If a caller cannot measure the post-placement value, the compatibility fail-open path
1052
+ preserves the established behavior rather than inventing a negative result.
1053
+
1054
+ **P5 — every stale level owns its retry.** While out of tolerance, the watchdog arms one
1055
+ shutdown-safe, deduplicated `SPREAD_STALE_RECHECK_MS` timer. It is not dependent on a
1056
+ future fill or the four-hour blockchain-fetch cadence, so the 5/10/20/30-minute stale
1057
+ windows can actually run. The timer re-enters the normal maintenance pipeline and is
1058
+ cancelled with the bot. A healthy reading must hold for the configured in-tolerance
1059
+ reset window before clearing stale geometry memory.
1060
+
1061
+ **P6 — fill ownership was audited, not duplicated.** The fill history path and orphan
1062
+ fill path both book accounting first and delegate unmatched attribution to the shared
1063
+ `attributeUnmatchedFillToGrid` owner. Replay keys make the pivot/crawl mutation once per
1064
+ fill. No second fill writer was introduced; the regression coverage documents this
1065
+ contract instead of changing working attribution code.
1066
+
1067
+ **Regression gates added/updated:** `test_last_fill_pivot_market_bound` (distance leg
1068
+ and observation/floor recency), `test_pivot_geometry_eligibility` (in-band pivot
1069
+ eligibility and veto territory), `test_rotation_source_level` (source/destination
1070
+ ladder identity), `test_incident_replay` (end-to-end band evacuation), and
1071
+ `test_stale_grid_hardening` (no-progress watchdog and level-triggered recheck). The
1072
+ production build, test build and these incident suites must all pass before promotion.
1073
+
1074
+ **Addendum (2026-11-16, offline audit reconciliation): the checker must audit the gate
1075
+ the runtime actually ran.** During a fast sweep of the bot's own premium rail on a live
1076
+ market-pair bot, the offline direction checker (`analysis/grid_correction_check.ts`)
1077
+ flagged six SELL re-quotes as discipline breaches while the runtime had passed every one
1078
+ of them through its own final gate. The two sides disagreed because they used different
1079
+ pivots:
1080
+
1081
+ - The runtime pivots on `_lastFilledPrice` at decision time, and since P1 above a fill
1082
+ refused from arming (wrong-side, too-far premium sweep, gap-band stranded residual)
1083
+ leaves the pivot behind the true last fill — by up to ~15 grid steps during the sweep.
1084
+ - The strict checker fed true consecutive fills into the same predicate
1085
+ (`isLastFillGuardBlocked`), so it judged each re-quote against a pivot the runtime
1086
+ never held at that gate.
1087
+
1088
+ The runtime did not breach its own rule: its `mode=`/Final-gate lines show
1089
+ `checked/passed` counts consistent with the pivots it held, and every flagged re-quote
1090
+ priced above the runtime's (older, lower) pivot, so no sell landed below realized cost.
1091
+ The refusal policy is deliberate — reverting it would re-introduce the unquoted-side
1092
+ deadlock P1 was written against — so the fix is on the audit side:
1093
+
1094
+ - `analysis/pivot_timeline.ts` reconstructs the runtime's pivot timeline from the bot
1095
+ log's own bookkeeping (`[FILL-PIVOT]`, `mode=`, Final-gate, refusal and allowance
1096
+ lines). "Pivot refreshed from N pending queued fill(s)" is deliberately not an
1097
+ observation: it logs queue content that may be exactly the fill the arming policy just
1098
+ refused.
1099
+ - The checker's default mode is now policy-aware: each strict candidate is re-judged
1100
+ against the pivot the runtime held when the filled order was last priced. Verdicts:
1101
+ `violation` (the runtime's own pivot would have blocked it — a real gate failure),
1102
+ `policy-divergence` (expected under the P1 arming policy; reported in its own section,
1103
+ not counted as FAIL), `unverifiable` (no placement event / pivot observation near the
1104
+ gate — kept as a violation, failing toward reporting). `--strict` preserves the legacy
1105
+ all-fills behaviour; a missing log falls back to strict with a notice.
1106
+ - Order-id joins normalize the Kibana operation suffix (`1.7.x:…` vs the log's plain
1107
+ `1.7.x`), naive Kibana timestamps are read as UTC, and the placement anchor is the
1108
+ order event whose price matches the fill (a post-fill rotation to another level must
1109
+ not become the anchor, or the fill is judged against the pivot it armed itself).
1110
+
1111
+ Lesson: an offline checker that re-implements gate inputs drifts from the gate it
1112
+ audits; it must reconstruct the gate's actual state, and every reconciliation shortcut
1113
+ (timestamps, ids, anchors) is a potential false verdict in either direction.
1114
+
1115
+ **Addendum 2 (2026-11-16, same-level re-fill loop): the P1 refusal silently suspended
1116
+ the P2 same-level block.** The sweep window that produced the six policy divergences
1117
+ above also produced a second, previously invisible pattern: one premium
1118
+ spread-correction slot was re-armed by the correction loop at the identical level and
1119
+ refilled five times in ~2.5 minutes (each cycle: full fill → slot orphaned → next
1120
+ correction cycle re-activates the same slot at the same grid price → immediate fill).
1121
+ Economically benign — every fill priced well above the day's cost basis and the taker
1122
+ kept paying a ~2.9% premium — but a real rule gap:
1123
+
1124
+ - §9.12/P2 blocks the exact pivot level as a same-level re-fill; that block keys off
1125
+ the ARMED pivot. §9.12/P1 refuses off-market (premium-sweep) fills from arming.
1126
+ Together: exactly while a sweep runs, the same-level re-fill protection is
1127
+ suspended — the one window it is needed most.
1128
+ - The offline checker passed the loop: realized fill prices of the re-placed level
1129
+ differ by sub-sat rounding dust, so the strict "sell→sell must rise" float compare
1130
+ saw a rise at every cycle. §0's ground truth ("equal is a violation") is about the
1131
+ LEVEL, not the float.
1132
+
1133
+ Amended policy (both sides of the audit line):
1134
+
1135
+ 1. Runtime (`modules/order/utils/system.ts`): a refused fill writes an in-memory,
1136
+ TTL-bounded (`GRID_LIMITS.LAST_FILL_REFUSED_LEVEL_TTL_MS`, 30 min) refused-level
1137
+ marker; `evaluateLastFillGuard` (the shared verdict) and
1138
+ `isLastFillPlacementBlocked` refuse a same-side placement within half a grid step
1139
+ (`pricesWithinHalfStep`) of the marked level, surfaced as `refusedLevel` /
1140
+ reason `refused-level` at every skip site. It vetoes exactly one level and nothing
1141
+ else — the counter-side stays governed by the older direction pivot and spread
1142
+ correction keeps trading around the live market, so the unquoted-side deadlock P1
1143
+ was written against cannot re-open through it. Deliberately NOT a cooldown or
1144
+ backoff on the correction loop (R4/§9.10/P4 "observability instead of a veto";
1145
+ §9.12/P5 owns stale-level retries; a hard pause would have left the sell side
1146
+ unquoted mid-sweep — the marked slot was the only placeable one at the time).
1147
+ 2. Checker (`analysis/grid_correction_check.ts`): same-level transitions (same
1148
+ direction, different orders) are detected with the runtime's OWN
1149
+ `pricesWithinHalfStep` and become strict candidates. In policy-aware mode a
1150
+ same-level candidate whose just-filled level carries a fresh refusal marker in the
1151
+ runtime log is a VIOLATION (the amended gate would have blocked the re-placement;
1152
+ it filled anyway); without marker evidence it is a policy divergence tagged
1153
+ `sameLevel`. `--strict` counts every same-level candidate as a violation.
1154
+
1155
+ Pinned by `tests/test_refused_level_refill_block.ts` (REFUSED-1..9) and
1156
+ `tests/test_same_level_refill_check.ts` (SL-1..10). With the amendment applied, the
1157
+ 2026-11-16 audit baseline reads: 10 strict candidates = 4 same-level violations (the
1158
+ loop) + 6 policy divergences (the sweep re-quotes, unchanged).
1159
+
1007
1160
  ---
1008
1161
 
1009
1162
  ### A. Grid-Price Invariant — former failure trace
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.7.2 (released).
5
+ **Version context:** v1.7.3 (released).
6
6
 
7
7
  ---
8
8
 
package/modules/README.md CHANGED
@@ -132,6 +132,7 @@ modules/
132
132
  │ ├── credential_secret.ts secret management
133
133
  │ ├── foreign_cred_daemon.ts external daemon client
134
134
  │ ├── headless_password.ts headless password storage
135
+ │ ├── instance_lock.ts per-account single-controller lock
135
136
  │ ├── launch_modes.ts monolithic vs isolated routing
136
137
  │ ├── market_adapter_runtime.ts adapter process lifecycle
137
138
  │ ├── market_adapter_watchdog.ts adapter process watchdog
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot",
3
- "version": "1.7.2",
3
+ "version": "1.7.3",
4
4
  "description": "The first open source trading bot with zero runtime dependencies and a fully adaptive market making strategy.",
5
5
  "main": "dist/modules/dexbot_class.js",
6
6
  "exports": {
@@ -163,6 +163,7 @@
163
163
  "./dist/modules/launcher/status_reporting.js": false,
164
164
  "./dist/modules/launcher/supervisor_control.js": false,
165
165
  "./dist/modules/launcher/monolithic_runtime.js": false,
166
+ "./dist/modules/launcher/instance_lock.js": false,
166
167
  "./dist/modules/launcher/runtime_mode.js": false,
167
168
  "./dist/modules/launcher/market_adapter_runtime.js": false,
168
169
  "./dist/modules/launcher/market_adapter_watchdog.js": false,