dexbot 1.6.15 → 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 (130) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +4 -4
  3. package/analysis/tradingview/README.md +2 -2
  4. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  5. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  6. package/claw/modules/chain_queries.ts +3 -3
  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/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  21. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +23 -9
  22. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  23. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  24. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  25. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  26. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  27. package/dist/dexbot.js +89 -138
  28. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  29. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  30. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  31. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  32. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  33. package/dist/market_adapter/inputs/window_cache.js +53 -17
  34. package/dist/market_adapter/lp_chart_core.js +1 -0
  35. package/dist/market_adapter/utils/chain.js +4 -3
  36. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  37. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  38. package/dist/modules/account_bots.d.ts +40 -3
  39. package/dist/modules/account_bots.js +77 -37
  40. package/dist/modules/account_orders.d.ts +4 -1
  41. package/dist/modules/account_orders.js +4 -1
  42. package/dist/modules/bitshares-native/resolvers.js +3 -3
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_settings.js +3 -3
  46. package/dist/modules/chain_keys.d.ts +6 -2
  47. package/dist/modules/chain_keys.js +5 -1
  48. package/dist/modules/chain_orders.d.ts +6 -2
  49. package/dist/modules/chain_orders.js +6 -2
  50. package/dist/modules/constants.d.ts +11 -0
  51. package/dist/modules/constants.js +41 -7
  52. package/dist/modules/credit_pricing.d.ts +20 -1
  53. package/dist/modules/credit_pricing.js +23 -1
  54. package/dist/modules/credit_runtime.js +33 -16
  55. package/dist/modules/dexbot_class.d.ts +6 -2
  56. package/dist/modules/dexbot_class.js +8 -3
  57. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  58. package/dist/modules/dexbot_cow_runtime.js +47 -66
  59. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  60. package/dist/modules/graceful_shutdown.d.ts +6 -2
  61. package/dist/modules/graceful_shutdown.js +6 -2
  62. package/dist/modules/launcher/bot_supervisor.js +4 -0
  63. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  64. package/dist/modules/launcher/credential_daemon.js +60 -26
  65. package/dist/modules/launcher/launch_modes.js +6 -3
  66. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  67. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  68. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  69. package/dist/modules/launcher/runtime_mode.js +223 -0
  70. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  71. package/dist/modules/market_adapter_whitelist.js +8 -0
  72. package/dist/modules/order/accounting.d.ts +15 -1
  73. package/dist/modules/order/accounting.js +15 -1
  74. package/dist/modules/order/async_lock.d.ts +9 -3
  75. package/dist/modules/order/async_lock.js +9 -3
  76. package/dist/modules/order/export.d.ts +0 -5
  77. package/dist/modules/order/export.js +0 -5
  78. package/dist/modules/order/format.d.ts +6 -4
  79. package/dist/modules/order/format.js +6 -4
  80. package/dist/modules/order/grid.d.ts +36 -18
  81. package/dist/modules/order/grid.js +186 -33
  82. package/dist/modules/order/index.d.ts +16 -1
  83. package/dist/modules/order/index.js +1 -1
  84. package/dist/modules/order/logger_state.d.ts +1 -1
  85. package/dist/modules/order/logger_state.js +1 -1
  86. package/dist/modules/order/manager.d.ts +30 -7
  87. package/dist/modules/order/manager.js +108 -12
  88. package/dist/modules/order/strategy.d.ts +5 -0
  89. package/dist/modules/order/strategy.js +23 -2
  90. package/dist/modules/order/sync_engine.d.ts +26 -11
  91. package/dist/modules/order/sync_engine.js +26 -11
  92. package/dist/modules/order/utils/math.d.ts +100 -22
  93. package/dist/modules/order/utils/math.js +106 -22
  94. package/dist/modules/order/utils/order.d.ts +77 -20
  95. package/dist/modules/order/utils/order.js +125 -27
  96. package/dist/modules/order/utils/system.d.ts +107 -11
  97. package/dist/modules/order/utils/system.js +176 -11
  98. package/dist/modules/order/utils/validate.d.ts +8 -3
  99. package/dist/modules/order/utils/validate.js +10 -3
  100. package/dist/modules/types.d.ts +35 -2
  101. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  102. package/dist/modules/utils/asset_symbols.js +5 -5
  103. package/dist/modules/utils/errors.d.ts +2 -1
  104. package/dist/modules/utils/errors.js +2 -1
  105. package/dist/scripts/analyze-credit.js +64 -23
  106. package/dist/scripts/bts_distribution.d.ts +66 -0
  107. package/dist/scripts/bts_distribution.js +2102 -0
  108. package/dist/scripts/rich_list.d.ts +32 -0
  109. package/dist/scripts/rich_list.js +16 -8
  110. package/dist/scripts/token_distribution.d.ts +45 -0
  111. package/dist/scripts/token_distribution.js +1870 -0
  112. package/dist/unlock.js +91 -42
  113. package/docs/BITSHARES_ONBOARDING.md +7 -0
  114. package/docs/COW_INVARIANTS.md +7 -1
  115. package/docs/DEXBOT_COMPARISON.md +5 -5
  116. package/docs/EVOLUTION.md +10 -8
  117. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -3
  118. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  119. package/docs/GRID_RECALCULATION.md +18 -6
  120. package/docs/LIFECYCLE.md +8 -8
  121. package/docs/LOGGING.md +9 -0
  122. package/docs/MPA_CREDIT_USAGE.md +3 -2
  123. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +121 -4
  124. package/docs/README.md +1 -1
  125. package/docs/WORKFLOW.md +5 -5
  126. package/docs/architecture.md +98 -1
  127. package/market_adapter/README.md +10 -3
  128. package/package.json +5 -1
  129. package/scripts/README.md +85 -148
  130. package/tests/README.md +29 -0
package/dist/unlock.js CHANGED
@@ -25,10 +25,13 @@ const __dirname = _esmDirname(__filename);
25
25
  * dexbot start --headless Non-interactive (requires env var or --password-file)
26
26
  * dexbot start --headless --password-file <path>
27
27
  * dexbot stat, status Runtime status
28
- * dexbot stop Stop the monolithic runtime
29
- * dexbot reload Reload the monolithic runtime (leaves credential daemon untouched)
30
- * dexbot restart Restart the monolithic runtime (re-unlocks credential daemon)
31
- * dexbot delete Shut down and clean up
28
+ * dexbot stop [<bot>] Stop the runtime. In monolithic mode a target folds
29
+ * into the whole runtime (one worker owns every bot);
30
+ * under --isolated it stops just that bot.
31
+ * dexbot reload [<bot>] Reload without re-unlocking the credential daemon
32
+ * (same target rules as stop)
33
+ * dexbot restart [<bot>] Restart (re-unlocks the credential daemon)
34
+ * dexbot delete Shut down and clean up (whole runtime only)
32
35
  *
33
36
  * Repo-root users can run `./unlock` instead.
34
37
  * `dexbot unlock` is kept as a legacy alias for `dexbot start`.
@@ -44,7 +47,7 @@ import { setUmask } from './modules/config.js';
44
47
  import fs from 'node:fs';
45
48
  import { path } from './modules/path_api.js';
46
49
  import { getStorage } from './modules/storage/index.js';
47
- import { createCredentialDaemonController } from './modules/launcher/credential_daemon.js';
50
+ import { createCredentialDaemonController, clearVaultSecret } from './modules/launcher/credential_daemon.js';
48
51
  import { buildScopedChildEnv } from './modules/launcher/child_env.js';
49
52
  import { parseUnlockArgs } from './modules/launcher/launch_modes.js';
50
53
  import { UPDATER, LAUNCHER } from './modules/constants.js';
@@ -71,7 +74,8 @@ const storage = getStorage();
71
74
  const { ensureDir } = storage;
72
75
  const { createBotSupervisor, SOCKET_PATH, forwardSignal, isPidAlive, waitForPidExit, readMarketAdapterLockPid, stopMarketAdapterFromLock, usesAmaGridPrice, waitForChildSpawn, pidMatchesScriptCandidates, candidateRuntimeScriptPaths, } = require('./modules/launcher/bot_supervisor');
73
76
  const { statusTitle, statusLabel, statusBool, statusActiveBotName, statusSuccess, statusError, colorStatus, STATUS_COLORS, readProcStat, readProcMemMB, readProcCpuTime, readProcCpuPercent, readProcUptime, formatMemoryWithUptime, printControlStatus, } = require('./modules/launcher/status_reporting');
74
- 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, printControlActionSummary, formatBotCount, } = require('./modules/launcher/monolithic_runtime');
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');
75
79
  const CODE_ROOT = __dirname;
76
80
  const BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
77
81
  const LOGS_DIR = PATHS.LOGS_DIR;
@@ -329,7 +333,7 @@ async function runIsolated({ botName, botEntry = null, stayResident = false, sta
329
333
  if (botName) {
330
334
  const bot = botEntry || resolveBotEntryForName(botName);
331
335
  if (!bot) {
332
- throw new Error(`Bot '${botName}' not found in bots.json`);
336
+ throw new Error(botNotFoundMessage(botName));
333
337
  }
334
338
  supervisor = createBotSupervisor({ bots: [bot] });
335
339
  }
@@ -502,7 +506,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
502
506
  const shouldStartMonolithicBackground = !clawOnly && !isolated && !isDetachedSupervisorChild && !isMonolithicBgChild && !forceForeground;
503
507
  let daemonReleased = false;
504
508
  if (botName && !selectedBot) {
505
- throw new Error(`Bot '${botName}' not found in bots.json`);
509
+ throw new Error(botNotFoundMessage(botName));
506
510
  }
507
511
  if (shouldStartMonolithicBackground) {
508
512
  const { pid } = readLiveMonolithicPid();
@@ -914,32 +918,69 @@ async function drainMonolithicWorkers(deadlineMs = 15000) {
914
918
  return false;
915
919
  }
916
920
  async function handleControl({ cmd, target }) {
917
- const effectiveCmd = cmd === 'shutdown' ? 'delete' : cmd === 'stat' ? 'status' : cmd;
921
+ // Resolve the whole-runtime vs per-bot contract in one place. A live
922
+ // monolithic runtime owns every active bot in a single worker, so a bot
923
+ // target cannot be honored and degrades to the whole-runtime command with
924
+ // a printed notice (see resolveControlRouting). `all` is an alias for the
925
+ // whole runtime; `delete` rejects a bot target and `status` validates then
926
+ // ignores one.
927
+ const monolithic = readLiveMonolithicPid();
928
+ const routing = resolveControlRouting({ cmd, target, monolithicLive: monolithic.pid > 0 });
929
+ const effectiveCmd = routing.cmd;
930
+ const effectiveTarget = routing.target;
918
931
  const actionLabel = getControlActionLabel(cmd);
919
- if ((effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'status' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all') && !target) {
920
- const { pid, stale } = readLiveMonolithicPid();
932
+ if (routing.reject) {
933
+ console.error(statusError(routing.reject));
934
+ process.exitCode = 1;
935
+ return;
936
+ }
937
+ // Validate a target only when it is about to be folded into a whole-runtime
938
+ // action (monolithic, or an ignored `status`): a typo must not reload/stop
939
+ // every bot by mistake. A pass-through to the isolated supervisor is
940
+ // validated there against the bots it actually runs, so a bot renamed or
941
+ // removed from bots.json while running can still be controlled by name.
942
+ const requestedTarget = routing.requestedTarget;
943
+ if (routing.folded && requestedTarget && !isConfiguredBotName(requestedTarget)) {
944
+ console.error(statusError(botNotFoundMessage(requestedTarget)));
945
+ process.exitCode = 1;
946
+ return;
947
+ }
948
+ if (routing.notice)
949
+ console.warn(routing.notice);
950
+ if ((effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'status' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all') && !effectiveTarget) {
951
+ const { pid, stale } = monolithic;
921
952
  if (pid > 0) {
922
953
  const summaryBotNames = getControlBotNames(undefined, true);
923
954
  const summaryServiceNames = getControlServiceNames(effectiveCmd, summaryBotNames);
924
955
  if (effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all') {
925
956
  if (effectiveCmd === 'restart-all' && process.stdin.isTTY) {
926
- const credResult = await stopCredentialDaemon();
927
- if (credResult.signaled) {
928
- console.log('Stop signal sent to credential daemon');
929
- }
957
+ // Verify the master password BEFORE stopping the live
958
+ // daemon. A wrong or cancelled password must leave the
959
+ // existing daemon (and every bot's key access) intact
960
+ // instead of killing it and then failing to re-unlock.
930
961
  const daemonOpts = { detached: true };
931
- const unlockedNow = await controller.ensureCredentialDaemon(daemonOpts);
932
- if (unlockedNow) {
933
- console.log(statusSuccess('✓ Authentication successful'));
934
- }
935
- const newCredPid = controller.getManagedDaemonPid();
936
- if (newCredPid) {
937
- try {
938
- storage.writeFile(MONOLITHIC_CRED_PID_FILE, String(newCredPid), { mode: 0o600 });
962
+ const vaultSecret = await controller.authenticateCredential();
963
+ try {
964
+ const credResult = await stopCredentialDaemon();
965
+ if (credResult.signaled) {
966
+ console.log('Stop signal sent to credential daemon');
939
967
  }
940
- catch (_) { }
968
+ const unlockedNow = await controller.ensureCredentialDaemon({ ...daemonOpts, vaultSecret });
969
+ if (unlockedNow) {
970
+ console.log(statusSuccess('✓ Authentication successful'));
971
+ }
972
+ const newCredPid = controller.getManagedDaemonPid();
973
+ if (newCredPid) {
974
+ try {
975
+ storage.writeFile(MONOLITHIC_CRED_PID_FILE, String(newCredPid), { mode: 0o600 });
976
+ }
977
+ catch (_) { }
978
+ }
979
+ controller.releaseManagedDaemon();
980
+ }
981
+ finally {
982
+ clearVaultSecret(vaultSecret);
941
983
  }
942
- controller.releaseManagedDaemon();
943
984
  }
944
985
  // reload-all intentionally skips the credential daemon
945
986
  // stop/re-unlock above: bots keep their key access while the
@@ -1093,11 +1134,11 @@ async function handleControl({ cmd, target }) {
1093
1134
  // wrapper was killed without leaving a pid file, or cleanupStateFiles
1094
1135
  // already ran). Drain before the isolated fall-through so that path cannot
1095
1136
  // race a start into a duplicate worker.
1096
- if (!target && effectiveCmd !== 'status'
1137
+ if (!effectiveTarget && effectiveCmd !== 'status'
1097
1138
  && (effectiveCmd === 'stop-all' || effectiveCmd === 'delete' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all')) {
1098
1139
  await drainMonolithicWorkers();
1099
1140
  }
1100
- if (effectiveCmd === 'delete' && !target && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
1141
+ if (effectiveCmd === 'delete' && !effectiveTarget && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
1101
1142
  await sendIsolatedDeleteIfAvailable();
1102
1143
  const credResult = await stopCredentialDaemon();
1103
1144
  if (credResult.signaled) {
@@ -1111,21 +1152,29 @@ async function handleControl({ cmd, target }) {
1111
1152
  }
1112
1153
  // Fall through to isolated supervisor socket
1113
1154
  const controlCmd = { cmd: effectiveCmd };
1114
- if (target)
1115
- controlCmd.bot = target;
1155
+ if (effectiveTarget)
1156
+ controlCmd.bot = effectiveTarget;
1116
1157
  // Restart credential daemon for restart-all (no target) in isolated mode
1117
- if (!target && effectiveCmd === 'restart-all' && process.stdin.isTTY) {
1118
- const ownerPid = findCredentialSocketOwnerPid();
1119
- if (ownerPid > 0 && isLikelyCredentialDaemonProcess(ownerPid)) {
1120
- await stopCredentialDaemonPid(ownerPid);
1121
- }
1122
- cleanupCredentialRuntimeFiles();
1158
+ if (!effectiveTarget && effectiveCmd === 'restart-all' && process.stdin.isTTY) {
1159
+ // Authenticate first: the running daemon is only stopped once the
1160
+ // master password is confirmed, so a failed restart keeps keys live.
1123
1161
  const daemonOpts = { detached: true };
1124
- const unlockedNow = await controller.ensureCredentialDaemon(daemonOpts);
1125
- if (unlockedNow) {
1126
- console.log(statusSuccess('✓ Authentication successful'));
1162
+ const vaultSecret = await controller.authenticateCredential();
1163
+ try {
1164
+ const ownerPid = findCredentialSocketOwnerPid();
1165
+ if (ownerPid > 0 && isLikelyCredentialDaemonProcess(ownerPid)) {
1166
+ await stopCredentialDaemonPid(ownerPid);
1167
+ }
1168
+ cleanupCredentialRuntimeFiles();
1169
+ const unlockedNow = await controller.ensureCredentialDaemon({ ...daemonOpts, vaultSecret });
1170
+ if (unlockedNow) {
1171
+ console.log(statusSuccess('✓ Authentication successful'));
1172
+ }
1173
+ controller.releaseManagedDaemon();
1174
+ }
1175
+ finally {
1176
+ clearVaultSecret(vaultSecret);
1127
1177
  }
1128
- controller.releaseManagedDaemon();
1129
1178
  }
1130
1179
  try {
1131
1180
  const resp = await sendControlCommand(controlCmd);
@@ -1133,8 +1182,8 @@ async function handleControl({ cmd, target }) {
1133
1182
  printControlStatus(resp.status);
1134
1183
  }
1135
1184
  else {
1136
- if (target || effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete') {
1137
- const summaryBotNames = getControlBotNames(target, !target && (effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete'));
1185
+ if (effectiveTarget || effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete') {
1186
+ const summaryBotNames = getControlBotNames(effectiveTarget, !effectiveTarget && (effectiveCmd === 'stop-all' || effectiveCmd === 'restart-all' || effectiveCmd === 'reload-all' || effectiveCmd === 'delete'));
1138
1187
  const summaryServiceNames = getControlServiceNames(effectiveCmd, summaryBotNames);
1139
1188
  printControlActionSummary(actionLabel, summaryBotNames, summaryServiceNames);
1140
1189
  }
@@ -1142,7 +1191,7 @@ async function handleControl({ cmd, target }) {
1142
1191
  }
1143
1192
  }
1144
1193
  catch (err) {
1145
- if (effectiveCmd === 'delete' && !target && isSupervisorTransientError(err)) {
1194
+ if (effectiveCmd === 'delete' && !effectiveTarget && isSupervisorTransientError(err)) {
1146
1195
  console.log('No runtime processes found.');
1147
1196
  return;
1148
1197
  }
@@ -304,6 +304,13 @@ You can re-run `dexbot bot` and save while the bot runs:
304
304
  - **Market/account changes** — run `dexbot reload` (reloads the runtime
305
305
  without logging you out; a full `restart` also works).
306
306
 
307
+ > `dexbot reload` / `restart` / `stop` are **whole-runtime** in the default
308
+ > monolithic mode: every active bot shares one worker process, so passing a bot
309
+ > name (e.g. `dexbot reload <bot>`) is validated and then applied to the whole
310
+ > runtime with a notice. To act on a single bot, start with `dexbot start
311
+ > --isolated` first. `delete` is whole-runtime and rejects a bot name; `status`
312
+ > is whole-runtime and validates, then ignores, one.
313
+
307
314
  The editor prints exactly which group your save falls into every time it
308
315
  saves, so you always know whether anything else is needed.
309
316
 
@@ -71,6 +71,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
71
71
  - `INV-COW-008` Owed fill crawls survive unapplied commits
72
72
  - `order/strategy.ts` records a crawl per shift-eligible fill at intake (slot-level dedupe, capped at 500); `deriveTargetBoundary` folds still-owed `_pendingFillCrawls` into the next derivation, excluding the current batch's slots, edge slots, and window members — a window that reaches the grid edge is not an edge order, using the same window exclusion every placement picker and `countLiveEdgeOrders` apply.
73
73
  - `_commitWorkingGrid` clears them only when the plan's boundary was actually applied — a held boundary (`boundaryHeld`), a gate-rejected boundary, and a null boundary all leave them owed.
74
+ - A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. Fail-closed preconditions: fill-provenanced pivot with a recorded side, on-ladder price within one increment, and `validatePersistedBoundary` (a strand refuses the re-anchor). This is what unblocks a sweep whose crawls were lost, without a rebuild.
75
+ - Consumption is SCOPED to what the derivation applied: `deriveTargetBoundary` returns `consumedCrawlIds` (the owed records whose shift it folded, plus the records it deliberately never counts — current-batch slots, edge-classified slots, malformed records), the plan carries it (`buildSuccessResult` → `CowResult` → `_commitWorkingGrid` options), and `_consumePendingFillCrawls` drops exactly those, logging `Dropped N … kept=M`. A capped fold consumes only the entries it actually applied (same-side prefix up to the applied magnitude), so the remainder stays owed exactly once. `_clearPendingFillCrawls` remains the explicit allowed-loss path (rebuild, rejected snapshot, restart replay) and drops everything.
76
+ - A commit **without** the wire consumes nothing (a create-only plan never derived a boundary): clearing it would be the old silent-loss bug (2026-10-25: 7 slots 147–153 swept, every record dropped, boundary ending 7 levels behind).
74
77
  - `consumePendingFillCrawls` applies them onto a restored finite boundary; `applyPersistedPendingCrawls` is the shared startup/recovery wrapper used before sync/reconcile; `_clearPendingFillCrawls` drops them when the boundary is re-anchored (grid rebuild via `initializeGrid`, rejected snapshot via `rejectCorruptedGridSnapshot`, persisted snapshot wipe via `AccountOrders.clearGrid`).
75
78
 
76
79
  - `INV-COW-009` LAST-FILL-GUARD pivot survives restarts with the snapshot, and only as a fill fact
@@ -85,6 +88,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
85
88
  - `checkSpreadCondition` holds the refcounted broadcast region (`startBroadcasting` / `stopBroadcasting`, released in `finally`) across its whole attempt loop, so a fill-driven rebalance defers rather than committing a master-version bump between the initial plan and its broadcast. This narrows the race; the COW commit guard remains the backstop.
86
89
  - Before broadcasting, `resolveOccupiedCorrection` re-derives a plan whose CREATE destination became a live order since planning (`getOccupiedCorrectionSlots`), or withholds it — a known-taken slot is never shipped. The COW build layer stays authoritative against a detector false positive.
87
90
  - A transient refusal re-plans ONCE from fresh master (`replanSpreadCorrectionFromFreshMaster`, bounded by `TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`); a non-transient refusal (`commit-refused` / `update-target-missing` / `unmatched-chain-orders` / `shutdown`) is not retried and counts toward the out-of-spread stale clock.
91
+ - Candidates are tightening-edge-only on real grid slots (`tightensSpread` + distance-to-edge ordering + `doesNotCrossMarket`) AND last-fill consistent: the planner applies the guard's own direction rule (`passesLastFill`, same pivot, same predicate) before the quota slice, so a batch is never built from ops the broadcast guard would drop. An unplaceable side reports the geometry bind `last-fill-blocked` instead of a wasted "prepared but not executed" cycle.
92
+ - The budget spent by the loop is chain-truth for a known candidate set: `available = chainFree − virtualReservation` is circular when the reservation describes the very slots being funded, so an over-sized projection (rail sized from a larger balance or from inventory locked in resting orders) would read 0 forever (`planned 3, placing 0`, 84 minutes live). `deriveChainTruthFundBudget` re-derives it as `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available` is 0 **and** the reservation exceeds chain free (a zero caused by fees or an empty balance is a real constraint and is honoured); the chain stays the final arbiter.
93
+ - Terminal stalls are named and escalated on their own windows rather than the structural 30 minutes: rail oversubscription (`availableFund = chainFree − virtual` reads 0 while the side still holds inventory) on `SPREAD_STALE_FUND_ESCALATE_MS`, the `last-fill-blocked` geometry bind on `SPREAD_STALE_GEOMETRY_ESCALATE_MS`, and the persistence clock clears only after sustained tolerance (`SPREAD_STALE_IN_TOLERANCE_RESET_MS`) or a placement.
88
94
  - This is the grid layer's counterpart to `INV-COW-003` (COW-layer pre-broadcast re-plan) and to `INV-COW-007`'s broadcast-flag deferral contract.
89
95
 
90
96
  - `INV-PROJ-001` New projected orders remain virtual
@@ -257,7 +263,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
257
263
 
258
264
  - `INV-BATCH-001` Illegal state batch abort
259
265
  - `executeBatch` throws `ILLEGAL_SPREAD_STATE` on an illegal grid layout (emitted at `modules/order/utils/validate.ts`, propagated via `modules/order/manager.ts` `_throwOnIllegalState`).
260
- - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:501`) is a test-only dead branch — production never emits that code; only a test stub uses it.
266
+ - The `_handleBatchHardAbort` catch for `ILLEGAL_ORDER_STATE` (`dexbot_class.ts:533`) is a test-only dead branch — production never emits that code; only a test stub uses it.
261
267
  - In production, recovery + cooldown are armed on the next maintenance tick via `_abortFlowIfIllegalState` (the `INV-MAINT-002` path), returning `abortedForIllegalState: true` to the caller. The caller does not need to return immediately; the maintenance tick handles recovery.
262
268
  - Hard abort triggers one immediate recovery sync (`_triggerStateRecoverySync`) plus arms one maintenance cooldown cycle (`_maintenanceCooldownCycles = Math.max(current, 1)`).
263
269
 
@@ -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.6.15).
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.6.17).
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.6.15 |
39
+ | **Release Track** | 1.0.0 | v1.6.17 |
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.6.15 |
779
+ | **Release Track** | 1.0.0 | v1.6.17 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
- | **Last Commit** | May 23, 2020 | 2026-10-16 |
782
- | **Total Commits** | 2281 | 2,411 (current HEAD, v1.6.15 line) |
781
+ | **Last Commit** | May 23, 2020 | 2026-10-30 |
782
+ | **Total Commits** | 2281 | 2,438 (current HEAD, v1.6.17 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 | 327 `test_*.ts` files (310 `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.6.15 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.6.17 release.
6
6
 
7
7
  ### Key Milestones
8
8
  - **Project Inception**: December 2, 2025
9
- - **Growth Phase**: 2,411 commits over ~9 active months
9
+ - **Growth Phase**: 2,438 commits over ~9 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 310 automated test files
12
- - **Releases**: 147 version entries in the changelog (v0.1.0 to v1.6.15)
11
+ - **Stability**: Progression from manual testing to a suite of 321 automated test files
12
+ - **Releases**: 149 version entries in the changelog (v0.1.0 to v1.6.17)
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-10-16). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,304 (`v0.1.0..HEAD`) and 2,411 (`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-10-30). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,331 (`v0.1.0..HEAD`) and 2,438 (`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
  |-----|--------:|-------|
@@ -173,11 +173,13 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
173
173
  | v1.6.12 → v1.6.13 | 21 | Spread-stall cause reporting + chain sync on every stall, resync-cascade guards (uncertain broadcast / suspended persistence), month-shard candle cache, dedup & dead-code purge, npm 12 install & PM2 fixes |
174
174
  | v1.6.13 → v1.6.14 | 18 | Last-fill guard + live market floor for spread correction, committed-size drift resize, COW pre-broadcast guards & P2 counters, fail-closed unknown geometry, order-key rename, worker-thread test runner |
175
175
  | v1.6.14 → v1.6.15 | 20 | Spread-correction resilience (atomic plan/retry, bounded re-plan, transient-refusal grace), price-vs-amount level identity for low-precision assets, credit-renewal free-collateral top-up, TradingView 1h/chart fixes & live data-age badge, per-asset `dexbot rich`, ~4x parallel test runner |
176
+ | v1.6.15 → v1.6.16 | 14 | Monolithic per-bot control routing, orientation-shared candle cache, market-profile orientation tolerance, chart log-axis hang fix + viewport-clipped draw hooks, Firefox Playwright chart suite, adapter-whitelist rename/copy sync, `dexbot rich` symbol canonicalization, doc reconciliation |
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 |
176
178
 
177
179
  ---
178
180
 
179
181
  **Report Originally Generated**: February 19, 2026
180
- **Last Updated**: October 16, 2026
181
- **Total Commits**: 2,411
182
- **Date Range**: December 2, 2025 – October 16, 2026
182
+ **Last Updated**: October 30, 2026
183
+ **Total Commits**: 2,438
184
+ **Date Range**: December 2, 2025 – October 30, 2026
183
185
  **Repository**: DEXBot2 (BitShares DEX Trading Bot)
@@ -52,7 +52,9 @@ funds.allocated → _getSizingContext() (budget for spread correction)
52
52
  **Key points:**
53
53
  - `botFunds` percentage applies to **total** capital (free + locked in orders), not just free. A bot at `"50%"` gets half of everything, not half of what's currently idle.
54
54
  - `funds.allocated` is the ceiling for each side. Existing orders already consume part of it; the remaining free portion is available for new placements.
55
- - The downstream `applyBotFundsAllocation()` (`manager.ts:1296`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
55
+ - The downstream `applyBotFundsAllocation()` (`manager.ts:1287`) also caps `funds.available` to `<= allocated` as a safety net, but the primary budget chokepoint is `getSideBudget` / `_getSizingContext` reading `allocated` directly (v1.2.6).
56
+ - `funds.available[side] = max(0, chainFree − virtualReservation − fees)`. When the empty rail already reserves more than the chain holds, this reads 0 while the side still holds inventory — the **rail oversubscribed** state. Spread correction names it in the log, flags it on the manager, and the out-of-spread watchdog escalates it on `TIMING.SPREAD_STALE_FUND_ESCALATE_MS`: the durable repair is re-sizing the rail from chain truth (structural re-center).
57
+ - For a KNOWN candidate set the reservation must not veto the placement it describes: `deriveChainTruthFundBudget` (`utils/math.ts`) re-derives `min(chainFree, min(virtualReservation, Σ candidate ideals))` when `available` reads 0, so an over-sized projection cannot deadlock placement. The chain rejects an over-commit at broadcast, so this cannot spend more than exists.
56
58
 
57
59
  ---
58
60
 
@@ -123,7 +125,7 @@ See [developer_guide.md#order-state-helper-functions](developer_guide.md#order-s
123
125
  **Per-Batch Execution**:
124
126
 
125
127
  1. **Peek & Pop**: Check `_incomingFillQueue`, pop up to N fills (batch size)
126
- 2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:303`)
128
+ 2. **Replay-safe Accounting Pass**: Each fill is accounted individually via `processFillAccounting(fillOp, fillKey)` with replay-safe dedup (`applyReplaySafeFillAccounting`, `dexbot_fill_runtime.ts:300`)
127
129
  - Proceeds credited directly to `chainFree` (via `adjustTotalBalance`)
128
130
  - Same-order fill batching (sync_engine Phase 6 cumulative transition) aggregates multiple fill transitions on one order before a single rebalance
129
131
  - All proceeds immediately available to next rebalance cycle (not split across cycles)
@@ -803,4 +805,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
803
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.
804
806
 
805
807
  ---
806
- *Technical Reference for DEXBot2 v1.6.15 release*
808
+ *Technical Reference for DEXBot2 v1.6.17 release*
@@ -116,6 +116,12 @@ fixture), as is a destination hole carrying an already-corrupted price (28%).
116
116
 
117
117
  ### The seventh gate: final pre-broadcast pivot re-check
118
118
 
119
+ The per-action LAST-FILL-GUARD rule is direction-only relative to that pivot —
120
+ a BUY is blocked at/above it, a SELL at/below it (equal price is a re-place at
121
+ the just-filled level). The spread-correction planner applies the SAME predicate
122
+ to its candidates before planning, so a correction batch never contains an op
123
+ the guard would drop.
124
+
119
125
  The per-action LAST-FILL-GUARD checks run against the pivot frozen at batch
120
126
  start. A fill queued between that freeze and the broadcast passes every
121
127
  per-action check on a stale pivot and ships (live incident: freeze at 0.745,
@@ -158,13 +158,19 @@ node dist/market_adapter/market_adapter.js --deltaPercent 2
158
158
  ```json
159
159
  {
160
160
  "ama": {
161
- "erPeriod": 10, // Efficiency Ratio lookback period (candles)
162
- "fastPeriod": 2, // Fast smoothing period for trending markets
163
- "slowPeriod": 30 // Slow smoothing period for choppy markets
161
+ "erPeriod": 781, // Efficiency Ratio lookback period (candles)
162
+ "fastPeriod": 5.2, // Fast smoothing period for trending markets
163
+ "slowPeriod": 83.5 // Slow smoothing period for choppy markets
164
164
  }
165
165
  }
166
166
  ```
167
167
 
168
+ > Optional. A bot-level `ama` block overrides the preset (or matched pair profile)
169
+ > field by field, and supplying any period marks the bot's AMA as `custom` in the
170
+ > adapter state. The values above are the built-in `AMA3` defaults
171
+ > (`MARKET_ADAPTER.AMAS`): `erPeriod: 781` and `fastPeriod: 5.2` are shared, while
172
+ > `slowPeriod` runs `62.1` (AMA1) to `99.3` (AMA4).
173
+
168
174
  > **`gridPrice` is the only switch.** A bot is AMA-driven when `gridPrice` says
169
175
  > so — `usesAmaGridPrice()`, the source of truth shared by the bot, maintenance
170
176
  > and launcher runtimes. There is deliberately no `ama.enabled`: a second switch
@@ -199,9 +205,15 @@ The pool is fetched directly by ID, bypassing pool discovery. Useful when the tr
199
205
  - Higher = more lag, filters noise
200
206
  - Built-in presets range from `AMA1` (fastest) to `AMA4` (slowest) — see `MARKET_ADAPTER.AMAS` in `modules/constants.ts` for the exact `slowPeriod` values
201
207
 
202
- AMA parameters are resolved exclusively from **presets** (`AMA1`–`AMA4`): a matched
203
- pair profile in `profiles/market_profiles.json` wins, otherwise the built-in defaults
204
- (`MARKET_ADAPTER.AMAS` in `modules/constants.ts`, default key `AMA3`) are used.
208
+ AMA parameters resolve in this order: a matched pair profile in
209
+ `profiles/market_profiles.json` wins for that pair; otherwise the bot's own `ama`
210
+ block overrides the preset field by field; any period the bot does not supply is
211
+ taken from the preset named by `gridPrice` (`"ama"` → the pair's `defaultAma`,
212
+ which falls back to `AMA3`; `"ama1"`–`"ama4"` → that exact preset); and any
213
+ remaining missing field falls back to the built-in `MARKET_ADAPTER.AMAS` defaults
214
+ (`modules/constants.ts`, default key `AMA3`). A bot that hand-writes any of the
215
+ three periods is reported as `custom` in the adapter state rather than by a preset
216
+ name.
205
217
 
206
218
  ### How It Works
207
219
 
package/docs/LIFECYCLE.md CHANGED
@@ -90,7 +90,7 @@ sequenceDiagram
90
90
  participant CO as chain_orders (broadcast)
91
91
  participant STORE as Storage
92
92
 
93
- CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:466)
93
+ CH->>Q: enqueue fill(s) (dexbot_fill_runtime.ts:463)
94
94
  FR->>FR: drain queue -> _processFillsWithBatching
95
95
  FR->>OM: processFilledOrders() (manager.ts)
96
96
  OM->>AC: processFillAccounting() (single call, batch)
@@ -134,9 +134,9 @@ sequenceDiagram
134
134
  participant STORE as Storage
135
135
 
136
136
  MA->>CL: AMA center snapshot updated
137
- CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1720)
137
+ CL->>CL: _performPeriodicGridChecks() (dexbot_class.ts:1747)
138
138
  CL->>RT: performPeriodicGridChecks() (dexbot_maintenance_runtime.ts:1677)
139
- RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2953)
139
+ RT->>RT: runGridMaintenance(bot,'periodic') (dexbot_maintenance_runtime.ts:2981)
140
140
  RT->>RT: executeMaintenanceLogic() (dexbot_maintenance_runtime.ts:2462)
141
141
  RT->>AC: recalculate funds from balances
142
142
  RT->>GD: promote AMA center -> grid center
@@ -157,13 +157,13 @@ The AMA signal stack (AMA/Kalman/Hurst/PE) is *research-tuned* in `analysis/` an
157
157
  the parameters.
158
158
 
159
159
  > Note: `runMaintenance()` is a **different** subsystem — the credit/MPA debt
160
- > runtime (`modules/credit_runtime.ts:3441`, reached via
161
- > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1837`). The grid maintenance
160
+ > runtime (`modules/credit_runtime.ts:3623`, reached via
161
+ > `_runCreditRuntimeMaintenance` at `dexbot_class.ts:1864`). The grid maintenance
162
162
  > chain above is the one that matters for order/price upkeep.
163
163
 
164
- References: `modules/dexbot_class.ts:1720` (`_performPeriodicGridChecks`) →
164
+ References: `modules/dexbot_class.ts:1747` (`_performPeriodicGridChecks`) →
165
165
  `modules/dexbot_maintenance_runtime.ts:1677` (`performPeriodicGridChecks`) →
166
- `:2953` (`runGridMaintenance`) → `:2462` (`executeMaintenanceLogic`),
166
+ `:2981` (`runGridMaintenance`) → `:2462` (`executeMaintenanceLogic`),
167
167
  `docs/GRID_RECALCULATION.md`, `docs/GRID_RECONCILE.md`.
168
168
 
169
169
  ---
@@ -192,7 +192,7 @@ enforced*, not compiler-enforced — learn them or you will introduce fund bugs.
192
192
  | How a fill becomes orders | `modules/dexbot_fill_runtime.ts` → `modules/order/manager.ts` |
193
193
  | Grid math / recalculation | `modules/order/grid.ts`, `docs/GRID_RECALCULATION.md` |
194
194
  | Funds & accounting | `modules/order/accounting.ts`, `docs/FUND_MOVEMENT_AND_ACCOUNTING.md` |
195
- | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1720` |
195
+ | Periodic loop & AMA hook | `modules/dexbot_maintenance_runtime.ts`, `modules/dexbot_class.ts:1747` |
196
196
  | Market signal source | `market_adapter/market_adapter.ts`, `analysis/README.md` |
197
197
  | Startup & orchestration | `modules/dexbot_class.ts`, `docs/developer_guide.md` §"Startup Sequence" |
198
198
  | Why COW exists | `docs/architecture.md` §"Copy-on-Write (COW) Grid Pattern", `docs/COW_INVARIANTS.md` |
package/docs/LOGGING.md CHANGED
@@ -307,6 +307,15 @@ re-plan retries). Kept separate from the generic `refusedCommitCount`.
307
307
  | `[SPREAD-CORRECTION] Plan-time dedupe: N planned slot(s) occupied since planning (...); re-planning from fresh master` | A planned CREATE destination was taken after planning; the plan is re-derived from fresh master |
308
308
  | `[SPREAD-CORRECTION] Plan-time dedupe: ...; no re-plan candidate — refusing this cycle` | Collision detected but no fresh candidate exists; the colliding plan is withheld (never broadcast) |
309
309
  | `[SPREAD-CORRECTION] Batch refused (cause); re-planning from fresh master (attempt 2/2)` | Transient refusal; the bounded fresh-master re-plan is in progress |
310
+ | `[SPREAD-CORRECTION] Excluded N candidate(s) from <side> planning: SELL must be above / BUY must be below the last fill ... (the broadcast guard would drop them)` | The planner dropped tightening-edge candidates that the LAST-FILL-GUARD would veto. They were never planned, so no batch is wasted on a guaranteed refusal |
311
+ | `[SPREAD-CORRECTION] No placeable <side> slot: every tightening slot is at/through the last fill ...` | Honest no-op: the side cannot be tightened against the last fill (a boundary move or a new fill must restore headroom). Not a batch refusal |
312
+ | `[SPREAD-CORRECTION] <side> rail is OVERSUBSCRIBED: virtual reservation X exceeds chain free Y by Z — no correction can be funded until the rail is re-sized ...` | `availableFund` is `free − virtual`, so an oversubscribed rail reads 0 while the side still holds inventory. The watchdog escalates this on its short fund window |
313
+ | `[SPREAD-STALE] Spread out of tolerance for Nmin ... (outOfSpread=..., stall=...)` | Persistence warn with the last stall cause; the clock survives single in-tolerance readings and the terminal cases escalate early: `stall=last-fill-blocked` (sell window behind the last fill) on the 10-minute geometry window, a rail oversubscription on the 5-minute fund window |
314
+ | `[SPREAD-STALE] ... (sell window behind the last fill — re-centering)` | The `last-fill-blocked` geometry bind is escalating; placement cannot repair it, a re-center can |
315
+ | `[BOUNDARY] Re-anchored from the last fill: SELL filled at slot 153 (0.447640); boundary 146 -> 149 so the fill sits outside its own window` | The window was behind the fill and a ±1 crawl cannot catch up; the fill now anchors the geometry. Refusals are silent by design (cold/off-ladder/unsafe preconditions) |
316
+ | `[SPREAD-CORRECTION] sell projection exceeds chain free by 1485.41092974; funding the candidates from chain truth (2171.2 for 2171.2 of ideal size) instead of placing nothing` | The virtual reservation is the projection of these very candidates and is larger than the chain free balance; the correction funds what the chain actually holds instead of deadlocking on a circular budget |
317
+ | `[BOUNDARY] Dropped N owed fill crawl(s) (boundary commit): buy=B sell=S net=N±M oldest=Ns kept=M boundary X -> Y` | The commit consumed the records the derivation folded (`kept=M` = records that stayed owed — a capped fold or a re-recorded slot) |
318
+ | `[BOUNDARY] Kept N owed fill crawl(s) unconsumed (boundary commit)` | The commit arrived without a consumed-set (a plan that never derived a boundary) or folded nothing it could apply; the records stay owed for the next derivation |
310
319
  | `Spread correction batch was prepared but not executed. Keeping local state unchanged. (cause=...)` | Terminal refusal; `cause` is the classified `SPREAD_CORRECTION_REFUSAL` value |
311
320
  | `Shutdown complete. Final metrics: ... spreadCorrectionRefusals=N [cause=count, ...], spreadCorrectionRetries=M` | Refusal breakdown on shutdown; the suffix appears only when at least one refusal occurred |
312
321
 
@@ -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