dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
package/dist/pm2.js CHANGED
@@ -79,6 +79,7 @@ const require = createRequire(import.meta.url);
79
79
  import { setUmask } from './modules/config.js';
80
80
  import { path } from './modules/path_api.js';
81
81
  import { spawn, execSync } from 'node:child_process';
82
+ import { existsSync } from 'node:fs';
82
83
  import { parseJsonWithComments } from './modules/order/utils/system.js';
83
84
  import { readBotsFileWithLock } from './modules/bots_file_lock.js';
84
85
  import { loadSettingsFile, selectActiveBotEntries } from './modules/bot_settings.js';
@@ -208,8 +209,7 @@ function buildEcosystemApps(bots, { includeUpdater = true } = {}) {
208
209
  error_file: path.join(LOGS_DIR, `${botName}-error.log`),
209
210
  out_file: path.join(LOGS_DIR, `${botName}.log`),
210
211
  log_date_format: 'YY-MM-DD HH:mm:ss.SSS',
211
- merge_logs: false,
212
- combine_logs: true,
212
+ merge_logs: true,
213
213
  max_size: '100M',
214
214
  max_restarts: 13,
215
215
  min_uptime: 86400000,
@@ -227,8 +227,7 @@ function buildEcosystemApps(bots, { includeUpdater = true } = {}) {
227
227
  error_file: path.join(LOGS_DIR, 'dexbot-adapter-error.log'),
228
228
  out_file: path.join(LOGS_DIR, 'dexbot-adapter.log'),
229
229
  log_date_format: 'YY-MM-DD HH:mm:ss.SSS',
230
- merge_logs: false,
231
- combine_logs: true,
230
+ merge_logs: true,
232
231
  max_size: '100M',
233
232
  max_restarts: 13,
234
233
  min_uptime: 60000,
@@ -259,8 +258,7 @@ function buildCredentialDaemonApp({ credentialEnv = {} } = {}) {
259
258
  error_file: path.join(LOGS_DIR, 'dexbot-cred-error.log'),
260
259
  out_file: path.join(LOGS_DIR, 'dexbot-cred.log'),
261
260
  log_date_format: 'YY-MM-DD HH:mm:ss.SSS',
262
- merge_logs: false,
263
- combine_logs: true,
261
+ merge_logs: true,
264
262
  max_size: '100M',
265
263
  env: {
266
264
  DEXBOT_CRED_DAEMON_SOCKET: CREDENTIAL_SOCKET_PATH,
@@ -657,23 +655,35 @@ async function ensurePm2Logrotate() {
657
655
  }
658
656
  }
659
657
  /**
660
- * Check if PM2 is installed locally or globally.
661
- * @returns {boolean} True if PM2 is found.
658
+ * Resolve the npm CLI that belongs to the running Node.
659
+ *
660
+ * The npm beside `process.execPath` shares this Node's global root; a version
661
+ * manager (nvm/fnm/volta) can put a different Node's npm first on PATH, which
662
+ * would install pm2 into a prefix this Node cannot see. Falls back to the bare
663
+ * name (PATH lookup) for unusual launcher layouts such as npx or shims.
664
+ *
665
+ * On Windows the shim is spawned through the shell, where an absolute path
666
+ * such as `C:\Program Files\nodejs\npm.cmd` would need quoting; the PATH
667
+ * lookup already resolves the right shim, so keep the bare name there.
668
+ * @returns {string} Absolute npm path, or 'npm' when none is found.
669
+ */
670
+ function resolveNpmBinary() {
671
+ if (process.platform === 'win32')
672
+ return 'npm';
673
+ const candidate = path.join(path.dirname(process.execPath), 'npm');
674
+ return existsSync(candidate) ? candidate : 'npm';
675
+ }
676
+ /**
677
+ * Check whether the pm2 CLI is reachable.
678
+ * @returns {boolean} True if `pm2 --version` succeeds.
662
679
  */
663
680
  function checkPM2Installed() {
664
681
  try {
665
- require.resolve('pm2');
682
+ execSync('pm2 --version', { stdio: 'ignore' });
666
683
  return true;
667
684
  }
668
- catch (e) {
669
- // Check if pm2 is available in PATH
670
- try {
671
- execSync('pm2 --version', { stdio: 'ignore' });
672
- return true;
673
- }
674
- catch (err) {
675
- return false;
676
- }
685
+ catch (err) {
686
+ return false;
677
687
  }
678
688
  }
679
689
  /**
@@ -688,11 +698,13 @@ async function installPM2() {
688
698
  return new Promise((resolve, reject) => {
689
699
  rl.question('PM2 is not installed. Install now? (Y/n): ', (answer) => {
690
700
  rl.close();
691
- if (answer.toLowerCase() === 'n') {
701
+ const normalized = answer.trim().toLowerCase();
702
+ if (normalized === 'n' || normalized === 'no') {
692
703
  console.log('PM2 installation cancelled. Run: npm install -g pm2');
693
704
  process.exit(1);
694
705
  }
695
706
  console.log('Installing PM2...');
707
+ const npmBin = resolveNpmBinary();
696
708
  // Helper to run installation command
697
709
  const runInstall = (command, args) => {
698
710
  return new Promise((res, rej) => {
@@ -709,22 +721,29 @@ async function installPM2() {
709
721
  proc.on('error', (err) => rej(err));
710
722
  });
711
723
  };
724
+ // npm can report success while writing into a global bin dir that is
725
+ // not on this PATH, so confirm `pm2` is actually reachable before
726
+ // declaring victory.
727
+ const confirmInstalled = (message) => {
728
+ if (checkPM2Installed()) {
729
+ console.log(pm2Success(message));
730
+ resolve();
731
+ }
732
+ else {
733
+ console.error(pm2Error('PM2 was installed, but `pm2` is not on PATH. Add the npm global bin directory to PATH and rerun.'));
734
+ reject(new Error('PM2 installed but not found on PATH'));
735
+ }
736
+ };
712
737
  // Try standard install first
713
- runInstall('npm', ['install', '-g', 'pm2'])
714
- .then(() => {
715
- console.log(pm2Success('PM2 installed successfully!'));
716
- resolve();
717
- })
738
+ runInstall(npmBin, ['install', '-g', 'pm2'])
739
+ .then(() => confirmInstalled('PM2 installed successfully!'))
718
740
  .catch((_err) => {
719
741
  // If failed and not on Windows, try sudo
720
742
  if (process.platform !== 'win32') {
721
743
  console.log('\nStandard installation failed (likely permissions). Trying with sudo...');
722
744
  console.log('This covers Linux and macOS. Please enter your password if prompted:');
723
- runInstall('sudo', ['npm', 'install', '-g', 'pm2'])
724
- .then(() => {
725
- console.log(pm2Success('PM2 installed successfully with sudo!'));
726
- resolve();
727
- })
745
+ runInstall('sudo', [npmBin, 'install', '-g', 'pm2'])
746
+ .then(() => confirmInstalled('PM2 installed successfully with sudo!'))
728
747
  .catch((_finalErr) => {
729
748
  reject(new Error('PM2 installation failed even with sudo'));
730
749
  });
@@ -782,6 +801,8 @@ async function execPM2Command(action, target, { suppressStderrOnError = false, s
782
801
  args.push(target);
783
802
  }
784
803
  const pm2 = spawn('pm2', args, {
804
+ cwd: PATHS.PROJECT_ROOT,
805
+ env: buildScopedChildEnv(),
785
806
  stdio: 'pipe',
786
807
  shell: process.platform === 'win32'
787
808
  });
@@ -837,9 +858,9 @@ async function stopPM2Processes(target) {
837
858
  console.log(`Stopping PM2 processes: ${target}`);
838
859
  if (target === 'all') {
839
860
  console.log('');
840
- // Stop credential daemon first — it holds the only handle to keys.
841
- // If managed apps were stopped first they'd lose key access; this order
842
- // ensures the daemon is the last process released.
861
+ // Stop the credential daemon first: it holds the only handle to keys,
862
+ // so releasing it up front is the safety stop. Managed apps are stopped
863
+ // afterwards; they can no longer sign, but they are already shutting down.
843
864
  await execPM2CommandIgnoreMissing('stop', CREDENTIAL_DAEMON_APP_NAME);
844
865
  if (storage.exists(ECOSYSTEM_FILE)) {
845
866
  await runManagedAppsPm2Action('stop');
@@ -932,18 +953,18 @@ async function restartPM2Processes(target, { headless = false, passwordFile = nu
932
953
  console.log(`Restarting PM2 processes: ${target}`);
933
954
  if (target === 'all') {
934
955
  generateEcosystemConfig({ clawOnly: false, exitOnError: false });
935
- await ensureCredentialDaemonPM2({ logReuse: false, headless, passwordFile });
956
+ await ensureCredentialDaemonPM2({ headless, passwordFile });
936
957
  await runManagedAppsPm2Action('restart');
937
958
  console.log('Managed dexbot PM2 apps restarted. dexbot-cred was left on the safe wrapper path.');
938
959
  return;
939
960
  }
940
961
  if (target === CREDENTIAL_DAEMON_APP_NAME) {
941
- await ensureCredentialDaemonPM2({ forceRefresh: true, logReuse: false, headless, passwordFile });
962
+ await ensureCredentialDaemonPM2({ forceRefresh: true, headless, passwordFile });
942
963
  console.log(`Credential daemon '${target}' restarted with a fresh unlock.`);
943
964
  return;
944
965
  }
945
966
  target = await assertActiveBotTarget(target);
946
- await ensureCredentialDaemonPM2({ logReuse: false, headless, passwordFile });
967
+ await ensureCredentialDaemonPM2({ headless, passwordFile });
947
968
  await execPM2Command('restart', target);
948
969
  console.log(`PM2 process '${target}' restarted.`);
949
970
  }
@@ -217,9 +217,8 @@ class RepoAnalyzer {
217
217
  *
218
218
  * Displays:
219
219
  * 1. Summary stats: Total commits, lines added/deleted, net change
220
- * 2. File listing: All tracked files with their change counts
221
- * 3. Add/Delete ratio: Metric for code quality (more adds vs deletes)
222
- * 4. Daily activity: Last 10 days of changes (trend analysis)
220
+ * 2. Add/Delete ratio: Metric for code quality (more adds vs deletes)
221
+ * 3. Daily activity: Last 10 days of changes (trend analysis)
223
222
  *
224
223
  * Output format uses Unicode box drawing and padding for readability
225
224
  * Suitable for terminal display with fixed-width fonts
@@ -238,18 +237,6 @@ class RepoAnalyzer {
238
237
  console.log(` Total Lines Changed: ${this.stats.totalEdits.toLocaleString()}`);
239
238
  console.log(` Net Change: ${(this.stats.totalAdded - this.stats.totalDeleted).toLocaleString()}`);
240
239
  console.log();
241
- // All tracked files
242
- console.log('📋 All Tracked Files:');
243
- console.log('─'.repeat(80));
244
- console.log(`${'File'.padEnd(45)} ${'Added'.padStart(10)} ${'Deleted'.padStart(10)} ${'Total'.padStart(10)}`);
245
- console.log('─'.repeat(80));
246
- const allFiles = Object.entries(this.stats.files)
247
- .sort((a, b) => b[1].edits - a[1].edits);
248
- for (const [file, stats] of allFiles) {
249
- const fileName = file.length > 43 ? '...' + file.slice(-40) : file;
250
- console.log(`${fileName.padEnd(45)} ${stats.added.toString().padStart(10)} ${stats.deleted.toString().padStart(10)} ${stats.edits.toString().padStart(10)}`);
251
- }
252
- console.log();
253
240
  // Add/Delete ratio
254
241
  console.log('🎯 Add vs Delete Ratio:');
255
242
  console.log('─'.repeat(80));
@@ -63,7 +63,7 @@ interface BotConfig {
63
63
  targetSpreadPercent?: unknown;
64
64
  incrementPercent?: unknown;
65
65
  gridPrice?: unknown;
66
- activeOrders?: unknown;
66
+ coreOrders?: unknown;
67
67
  botFunds?: JsonObj;
68
68
  weightDistribution?: JsonObj;
69
69
  [key: string]: unknown;
@@ -539,7 +539,7 @@ function analyzeOrder(botData, config, botKey) {
539
539
  sell: sellSlots
540
540
  },
541
541
  // Target active orders from config
542
- activeOrdersTarget: config ? config.activeOrders : null,
542
+ coreOrdersTarget: config ? config.coreOrders : null,
543
543
  // Bot fund allocation settings from config (normalized to strings for
544
544
  // the display paths; bots.json allows percentage strings or numbers)
545
545
  botFunds: config && config.botFunds
@@ -1137,9 +1137,9 @@ function formatAnalysis(analysisInput) {
1137
1137
  lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} | Incr.:${formatPercent(analysis.increment.avg).padStart(6)}`);
1138
1138
  }
1139
1139
  // Active orders comparison
1140
- if (analysis.hasConfig && analysis.activeOrdersTarget) {
1141
- const buyTarget = analysis.activeOrdersTarget.buy;
1142
- const sellTarget = analysis.activeOrdersTarget.sell;
1140
+ if (analysis.hasConfig && analysis.coreOrdersTarget) {
1141
+ const buyTarget = analysis.coreOrdersTarget.buy;
1142
+ const sellTarget = analysis.coreOrdersTarget.sell;
1143
1143
  const buyActual = analysis.slots.activeBuy;
1144
1144
  const sellActual = analysis.slots.activeSell;
1145
1145
  // Collect raw buy/sell values across Active, Weight, Funds for column alignment
@@ -38,7 +38,7 @@ import { fetchMarketCandlesSequentially } from '../market_adapter/inputs/fetch_b
38
38
  import { fetchFeedCandlesSequentially } from '../market_adapter/inputs/kibana_feed_source.js';
39
39
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
40
40
  import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
41
- import { slugPart } from '../market_adapter/interval_utils.js';
41
+ import { slugPart, parseChainTimeToMs } from '../market_adapter/interval_utils.js';
42
42
  import { monthsToHours } from '../modules/utils/time_range.js';
43
43
  const INTERVAL_SECONDS = 3600;
44
44
  const DEFAULT_MONTHS = 3;
@@ -152,7 +152,7 @@ async function pickFeedContext(symA, symB, source, bitsharesClient) {
152
152
  function feedAgeMs(ctx, nowMs = Date.now()) {
153
153
  if (!ctx?.feedPublicationTime)
154
154
  return null;
155
- const ts = Date.parse(ctx.feedPublicationTime.endsWith('Z') ? ctx.feedPublicationTime : `${ctx.feedPublicationTime}Z`);
155
+ const ts = parseChainTimeToMs(ctx.feedPublicationTime);
156
156
  if (!Number.isFinite(ts))
157
157
  return null;
158
158
  return nowMs - ts;
@@ -6,6 +6,10 @@
6
6
  * this gate makes progress monotonic by failing when the code-line count rises
7
7
  * above the committed budget in `any-budget.json`.
8
8
  *
9
+ * The root scopes (`modules/`, `market_adapter/`, `analysis/`, `scripts/`) and
10
+ * the experimental `claw/` subtree are tracked with independent budgets so the
11
+ * now-clean root count is not inflated by claw, which is still being paid down.
12
+ *
9
13
  * Counts `any` tokens on code lines only (comment / JSDoc lines are ignored so
10
14
  * documentation cleanup is not double-counted).
11
15
  *
@@ -6,6 +6,10 @@
6
6
  * this gate makes progress monotonic by failing when the code-line count rises
7
7
  * above the committed budget in `any-budget.json`.
8
8
  *
9
+ * The root scopes (`modules/`, `market_adapter/`, `analysis/`, `scripts/`) and
10
+ * the experimental `claw/` subtree are tracked with independent budgets so the
11
+ * now-clean root count is not inflated by claw, which is still being paid down.
12
+ *
9
13
  * Counts `any` tokens on code lines only (comment / JSDoc lines are ignored so
10
14
  * documentation cleanup is not double-counted).
11
15
  *
@@ -23,6 +27,9 @@ const ROOT = PATHS.PROJECT_ROOT;
23
27
  const BUDGET_FILE = path.join(ROOT, 'any-budget.json');
24
28
  const SCAN_DIRS = ['modules', 'market_adapter', 'analysis', 'scripts'];
25
29
  const SCAN_ROOT_FILES = true;
30
+ const ROOT_SCOPE = 'root';
31
+ const CLAW_SCOPE = 'claw';
32
+ const CLAW_DIR = 'claw';
26
33
  // `any` as an explicit type token only: not preceded by an identifier char or
27
34
  // `.` (so the `Promise.any` built-in / member named `any` is not counted) and
28
35
  // not inside a string or template literal (log/help prose is not counted).
@@ -78,6 +85,9 @@ function sourceFiles() {
78
85
  }
79
86
  return files;
80
87
  }
88
+ function clawFiles() {
89
+ return [...walk(path.join(ROOT, CLAW_DIR))];
90
+ }
81
91
  function countAny(file) {
82
92
  const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
83
93
  let count = 0;
@@ -90,37 +100,59 @@ function countAny(file) {
90
100
  }
91
101
  return count;
92
102
  }
93
- const counts = sourceFiles()
94
- .map((file) => ({ file: path.relative(ROOT, file), count: countAny(file) }))
95
- .filter((entry) => entry.count > 0)
96
- .sort((a, b) => b.count - a.count);
97
- const total = counts.reduce((sum, entry) => sum + entry.count, 0);
103
+ function countScope(scope, files) {
104
+ const fileCounts = files
105
+ .map((file) => ({ file: path.relative(ROOT, file), count: countAny(file) }))
106
+ .filter((entry) => entry.count > 0)
107
+ .sort((a, b) => b.count - a.count);
108
+ return { scope, files: fileCounts, total: fileCounts.reduce((sum, entry) => sum + entry.count, 0) };
109
+ }
110
+ const scopes = [
111
+ countScope(ROOT_SCOPE, sourceFiles()),
112
+ countScope(CLAW_SCOPE, clawFiles())
113
+ ];
98
114
  const listMode = process.argv.includes('--list');
99
115
  const updateMode = process.argv.includes('--update');
100
116
  if (listMode) {
101
- for (const entry of counts)
102
- console.log(`${String(entry.count).padStart(5)} ${entry.file}`);
103
- console.log(`${String(total).padStart(5)} TOTAL (${counts.length} files)`);
117
+ for (const scope of scopes) {
118
+ for (const entry of scope.files)
119
+ console.log(`${String(entry.count).padStart(5)} ${entry.file}`);
120
+ console.log(`${String(scope.total).padStart(5)} ${scope.scope.toUpperCase()} SUBTOTAL (${scope.files.length} files)`);
121
+ }
104
122
  process.exit(0);
105
123
  }
106
124
  if (updateMode) {
107
- fs.writeFileSync(BUDGET_FILE, `${JSON.stringify({ total, updated: new Date().toISOString().slice(0, 10) }, null, 2)}\n`);
108
- console.log(`budget file updated: total=${total}`);
125
+ const next = {
126
+ root: scopes.find((scope) => scope.scope === ROOT_SCOPE).total,
127
+ claw: scopes.find((scope) => scope.scope === CLAW_SCOPE).total,
128
+ updated: new Date().toISOString().slice(0, 10)
129
+ };
130
+ fs.writeFileSync(BUDGET_FILE, `${JSON.stringify(next, null, 2)}\n`);
131
+ console.log(`budget file updated: root=${next.root} claw=${next.claw}`);
109
132
  process.exit(0);
110
133
  }
111
- let budget = Infinity;
112
- if (fs.existsSync(BUDGET_FILE)) {
113
- budget = JSON.parse(fs.readFileSync(BUDGET_FILE, 'utf8')).total;
134
+ const fileBudget = fs.existsSync(BUDGET_FILE)
135
+ ? JSON.parse(fs.readFileSync(BUDGET_FILE, 'utf8'))
136
+ : {};
137
+ let exceeded = false;
138
+ for (const scope of scopes) {
139
+ const committed = typeof fileBudget[scope.scope] === 'number'
140
+ ? fileBudget[scope.scope]
141
+ // Backward compatibility with the original single-scope `{ total }` file.
142
+ : (scope.scope === ROOT_SCOPE && typeof fileBudget.total === 'number' ? fileBudget.total : Infinity);
143
+ if (scope.total > committed) {
144
+ console.error(`\u2716 explicit type budget exceeded [${scope.scope}]: ${scope.total} > ${committed}`);
145
+ exceeded = true;
146
+ }
147
+ else if (scope.total < committed) {
148
+ console.log(`\u2713 [${scope.scope}] explicit type count ${scope.total} is below budget ${committed}. Lower the budget file to ${scope.total} to lock in the gain.`);
149
+ }
150
+ else {
151
+ console.log(`\u2713 [${scope.scope}] explicit type count ${scope.total} is at budget ${committed}.`);
152
+ }
114
153
  }
115
- if (total > budget) {
116
- console.error(`\u2716 explicit type budget exceeded: ${total} > ${budget}`);
154
+ if (exceeded) {
117
155
  console.error(' Reduce usages, or run `node dist/scripts/check_any.js --update` only when lowering the budget.');
118
156
  process.exit(1);
119
157
  }
120
- if (total < budget) {
121
- console.log(`\u2713 explicit type count ${total} is below budget ${budget}. Lower the budget file to ${total} to lock in the gain.`);
122
- }
123
- else {
124
- console.log(`\u2713 explicit type count ${total} is at budget ${budget}.`);
125
- }
126
158
  //# sourceMappingURL=check_any.js.map
@@ -9,6 +9,7 @@ const require = createRequire(import.meta.url);
9
9
  */
10
10
  const { BitShares, waitForConnected } = require('../modules/bitshares_client');
11
11
  const { getErrorMessage } = require('../modules/utils/errors');
12
+ const { parseChainTimeToMs } = require('../market_adapter/interval_utils');
12
13
  const POOL_ID = process.argv.includes('--pool')
13
14
  ? process.argv[process.argv.indexOf('--pool') + 1]
14
15
  : '1.19.133';
@@ -30,12 +31,6 @@ function fmt(obj) {
30
31
  return String(obj);
31
32
  }
32
33
  }
33
- function parseChainTimeToMs(timeStr) {
34
- if (!timeStr)
35
- return Number.NaN;
36
- const s = String(timeStr);
37
- return Date.parse(s.endsWith('Z') ? s : `${s}Z`);
38
- }
39
34
  function extractReceived(row) {
40
35
  const r = row;
41
36
  const resultPayload = Array.isArray(r?.op?.result) ? r.op.result[1] : null;
@@ -73,21 +73,21 @@ lines.forEach((line) => {
73
73
  // Filter out partial orders from divergence calculation
74
74
  // Include: 'active' and 'virtual' orders - these represent the intended grid structure
75
75
  // Exclude: 'partial' orders - these are temporarily filled and in transition
76
- const activeOrders = orders.filter((o) => o.state !== 'partial');
77
- const partialOrdersCount = orders.length - activeOrders.length;
76
+ const nonPartialOrders = orders.filter((o) => o.state !== 'partial');
77
+ const partialOrdersCount = orders.length - nonPartialOrders.length;
78
78
  // Calculate divergence metric: sum of ((calculated - persisted) / persisted)^2 / count
79
79
  let sumSquaredDiff = 0;
80
- activeOrders.forEach((order) => {
80
+ nonPartialOrders.forEach((order) => {
81
81
  const relativeError = (order.calculated - order.persisted) / order.persisted;
82
82
  sumSquaredDiff += relativeError * relativeError;
83
83
  });
84
- const normalizedMetric = activeOrders.length > 0 ? sumSquaredDiff / activeOrders.length : 0;
84
+ const normalizedMetric = nonPartialOrders.length > 0 ? sumSquaredDiff / nonPartialOrders.length : 0;
85
85
  const promille = normalizedMetric * 1000;
86
86
  // Calculate real error as √(promille / 1000)
87
87
  const realErrorPercent = Math.sqrt(promille / 1000) * 100;
88
88
  console.log('=== QUADRATIC DIVERGENCE ANALYSIS ===\n');
89
89
  console.log(`Total orders in input: ${orders.length}`);
90
- console.log(`Orders analyzed: ${activeOrders.length}`);
90
+ console.log(`Orders analyzed: ${nonPartialOrders.length}`);
91
91
  if (partialOrdersCount > 0) {
92
92
  console.log(`Partial orders excluded: ${partialOrdersCount}`);
93
93
  }
@@ -102,7 +102,7 @@ console.log(` Status: ${promille <= 1 ? '✓ WITHIN THRESHOLD' : '✗ EXCEEDS T
102
102
  // Show min/max errors
103
103
  let minError = Infinity, maxError = -Infinity;
104
104
  let minErrorOrder = null, maxErrorOrder = null;
105
- activeOrders.forEach((order, idx) => {
105
+ nonPartialOrders.forEach((order, idx) => {
106
106
  const absError = Math.abs((order.calculated - order.persisted) / order.persisted);
107
107
  if (absError < minError) {
108
108
  minError = absError;
@@ -32,7 +32,6 @@ const liveTestFiles = new Set([
32
32
  'dist/tests/test_debug_orderbook.js',
33
33
  'dist/tests/test_twentix_only.js',
34
34
  'dist/tests/test_fee_cache.js',
35
- 'dist/tests/test_fee_cache_twentix.js',
36
35
  'dist/tests/test_subscriptions.js',
37
36
  'dist/tests/test_fills.js',
38
37
  'dist/tests/test_funds.js',
@@ -66,16 +66,6 @@ const targets = [
66
66
  return JSON.stringify(json, null, 2) + '\n';
67
67
  },
68
68
  },
69
- {
70
- file: 'analysis/trend_detection/package.json',
71
- update(content, version) {
72
- const json = JSON.parse(content);
73
- if (json.version === version)
74
- return null;
75
- json.version = version;
76
- return JSON.stringify(json, null, 2) + '\n';
77
- },
78
- },
79
69
  // ── Source files (regex replacements) ──────────────────────
80
70
  {
81
71
  file: 'claw/tests/test_claw_mcp_transport.ts',
@@ -6,7 +6,7 @@
6
6
  * for each bot entry. This is a health check to ensure configurations are
7
7
  * valid before being used by the system.
8
8
  *
9
- * Required fields for each bot: assetA, assetB, activeOrders, botFunds
9
+ * Required fields for each bot: assetA, assetB, coreOrders, botFunds
10
10
  * Optional field: gridPrice (number | null | "ama"/"ama1".."ama4")
11
11
  *
12
12
  * Usage: node dist/scripts/validate_bots.js
@@ -6,7 +6,7 @@
6
6
  * for each bot entry. This is a health check to ensure configurations are
7
7
  * valid before being used by the system.
8
8
  *
9
- * Required fields for each bot: assetA, assetB, activeOrders, botFunds
9
+ * Required fields for each bot: assetA, assetB, coreOrders, botFunds
10
10
  * Optional field: gridPrice (number | null | "ama"/"ama1".."ama4")
11
11
  *
12
12
  * Usage: node dist/scripts/validate_bots.js
@@ -27,7 +27,7 @@ const livePath = PATHS.PROFILES.BOTS_JSON;
27
27
  * Required fields:
28
28
  * - assetA: Base currency symbol (e.g., 'XRP')
29
29
  * - assetB: Quote currency symbol (e.g., 'BTS')
30
- * - activeOrders: Number of orders in the grid
30
+ * - coreOrders: Number of orders in the grid
31
31
  * - botFunds: Amount of funds allocated to the bot
32
32
  *
33
33
  * Output:
@@ -44,7 +44,7 @@ function checkConfig(obj, src) {
44
44
  const bots = Array.isArray(o.bots) && o.bots.length ? o.bots : [o];
45
45
  console.log(`\n== Checking ${src}: found ${bots.length} bot entries`);
46
46
  // List of required fields that every bot must have
47
- const required = ['assetA', 'assetB', 'activeOrders', 'botFunds'];
47
+ const required = ['assetA', 'assetB', 'coreOrders', 'botFunds'];
48
48
  let anyMissing = false;
49
49
  let anyGridPriceWarnings = false;
50
50
  // Validate each bot entry
package/dist/unlock.js CHANGED
@@ -56,8 +56,6 @@ import { buildRuntimeScriptArgs } from './modules/launcher/runtime_entry.js';
56
56
  import { sendControlCommand } from './modules/launcher/supervisor_control.js';
57
57
  import { registerCleanup, setupGracefulShutdown } from './modules/graceful_shutdown.js';
58
58
  import { normalizeBotEntry, resolveRawBotEntries, loadSettingsFile } from './modules/bot_settings.js';
59
- import { main as runBotEditor } from './modules/account_bots.js';
60
- import { setSuppressConnectionLog, disconnectClient } from './modules/bitshares_client.js';
61
59
  import { selectStartOnboardingCommand } from './modules/cli_start_onboarding.js';
62
60
  import * as chainKeys from './modules/chain_keys.js';
63
61
  import * as credentialPolicy from './modules/credential_policy.js';
@@ -421,6 +419,13 @@ async function runStartOnboardingIfNeeded({ allowInteractive = true, nonInteract
421
419
  await chainKeys.main();
422
420
  return true;
423
421
  }
422
+ // The interactive bot editor drags in the heavyweight native chain client
423
+ // (~80 ms of module graph). It is only needed on this onboarding path, so
424
+ // load it lazily instead of eagerly on every `unlock`/`start` invocation.
425
+ const [{ main: runBotEditor }, { setSuppressConnectionLog, disconnectClient }] = await Promise.all([
426
+ import('./modules/account_bots.js'),
427
+ import('./modules/bitshares_client.js'),
428
+ ]);
424
429
  setSuppressConnectionLog(true);
425
430
  try {
426
431
  await runBotEditor();
@@ -415,18 +415,17 @@ npm prefix -g # must be a directory you own
415
415
 
416
416
  Check with `dexbot --help`.
417
417
 
418
- ### "npm says it blocked dexbot's install scripts (`prepare` / `postinstall`)"
418
+ ### "npm says it blocked dexbot's install scripts (`prepare`)"
419
419
 
420
420
  npm 12+ no longer runs lifecycle scripts of installed packages unless they
421
421
  are allowlisted (supply-chain hardening,
422
422
  [npm/rfcs#868](https://github.com/npm/rfcs/blob/master/text/0868-allow-scripts.md)).
423
- You'll see `npm warn install-scripts ... blocked` listing dexbot's
424
- `postinstall` and `prepare`. It shows up with `npm link` because link adds
425
- your checkout to the **global** install tree as a `file:` dependency — npm
426
- treats it like any third-party package and blocks its scripts. The warning's
427
- own advice (`npm install-scripts ls` / `approve`) is a dead end here: in your
428
- project the checkout is the project root, which npm deliberately never lists
429
- or approves. Don't chase it.
423
+ With `npm link` you'll see `npm warn install-scripts ... blocked` listing
424
+ dexbot's `prepare`: link adds your checkout to the **global** install tree as
425
+ a `file:` dependency — npm treats it like any third-party package and blocks
426
+ its scripts. The warning's own advice (`npm install-scripts ls` / `approve`)
427
+ is a dead end here: in your project the checkout is the project root, which
428
+ npm deliberately never lists or approves. Don't chase it.
430
429
 
431
430
  A plain `npm install` is **not** gated — it runs the project's own `prepare`
432
431
  directly, so the correct from-source order is:
@@ -438,10 +437,7 @@ npm link # a blocked prepare here is harmless
438
437
  ```
439
438
 
440
439
  If you skipped the install (or want to be sure), run `npm run build`. Bins
441
- are never gated, so once `dist/` exists the linked `dexbot` works. The
442
- blocked `postinstall` is only the "DEXBot2 installed!" banner — cosmetic;
443
- `npm i -g dexbot` may warn about the same banner and that's harmless too
444
- (the published package ships prebuilt).
440
+ are never gated, so once `dist/` exists the linked `dexbot` works.
445
441
 
446
442
  ### "`Unknown command: dexbot` right after installing/linking"
447
443
 
@@ -95,7 +95,6 @@ boundary position and slot BUY/SELL roles during blockchain execution.
95
95
  ├─> Create WorkingGrid (clone master)
96
96
  ├─> Calculate target grid (from strategy)
97
97
  ├─> Reconcile against working copy
98
- ├─> Validate working grid funds
99
98
  └─> Return { workingGrid, actions, ... }
100
99
 
101
100
  2. updateOrdersOnChainBatch(result)
@@ -233,7 +232,7 @@ syncFromMaster(masterGrid, orderId, masterVersion?) {
233
232
  | `WorkingGrid.buildDelta(masterGrid)` | Delta between master and working copy (`modules/order/working_grid.ts:205`, delegating to `utils/order.ts`) |
234
233
  | `_commitWorkingGrid(workingGrid, indexes, boundary, options = {})` | Atomic swap to master |
235
234
  | `_setRebalanceState(state)` | Track rebalance state |
236
- | `_currentWorkingGrid` | Reference to working grid during rebalance for fill sync |
235
+ | `_currentWorkingGridStack` | Stack of active working-grid references during rebalance for fill sync; peek the innermost via `_peekWorkingGrid()`, managed with `_pushWorkingGridRef`/`_popWorkingGridRef`/`_releaseWorkingGridRef`/`_clearWorkingGridRef` |
237
236
  | `_applyOrderUpdate(order, context, options = {})` | Lock-free order update (immutable swap); routes fill sync to `_syncWorkingGridFromMasterMutation` |
238
237
  | `_syncWorkingGridFromMasterMutation(orderId, context)` | Adapter: planning-state gate → `markStale()` + `syncFromMaster()` → sync error handling |
239
238
 
@@ -265,7 +264,7 @@ During Rebalance**.
265
264
 
266
265
  ## Safety Guardrails
267
266
 
268
- 1. **Accountant Dry-Run:** `Accountant.validateTargetGrid(targetMap)` verifies that the entire proposed grid fits within `Liquid + CurrentOrderValue` *before* broadcasting.
267
+ 1. **Planning-time budget feasibility:** order sizes are derived from `funds.allocated` via `getSideBudget` / `_getSizingContext`, so a proposed grid cannot exceed the side budget by construction. (The historical `Accountant.validateTargetGrid` dry-run was removed — it had no production caller.)
269
268
  2. **Atomic Transaction Semantics:** Large boundary shifts (>5 slots) are inherently safe because the COW pattern only commits after successful blockchain confirmation. If market volatility causes rapid shifts during planning, the plan is caught by the **pre-broadcast staleness guard** (`evaluateCommit` against `_gridVersion`): it re-plans ONCE from the fresh master with the same fills (`replanStaleBatch`, bounded by `STALE_PLAN_REPLAN_LIMIT`), then proceeds + structural resync if still stale — never a silent discard that drops the fill set. If the master changes *during* broadcast, the commit-time guard refuses the commit and the placed orders are adopted from chain so on-chain state never runs ahead of the grid.
270
269
  3. **Resync on Error:** If any blockchain action fails (e.g., "Insufficient funds"), the bot discards the working grid and triggers `grid_reconcile.ts` for a fresh blockchain sync ([GRID_RECONCILE.md](GRID_RECONCILE.md)).
271
270