dexbot 1.7.0 → 1.7.1

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 (105) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +3 -3
  3. package/analysis/README.md +33 -13
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_liquidity.js +15 -4
  9. package/dist/analysis/bot_key_utils.d.ts +44 -1
  10. package/dist/analysis/bot_key_utils.js +76 -7
  11. package/dist/analysis/fills_cache.js +2 -1
  12. package/dist/analysis/grid_correction_check.d.ts +1 -19
  13. package/dist/analysis/grid_correction_check.js +12 -30
  14. package/dist/analysis/liquidity/liquidity_chart_generator.js +190 -20
  15. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
  16. package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
  17. package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
  18. package/dist/analysis/liquidity/liquidity_view.js +11 -0
  19. package/dist/analysis/resolve_bot_accounts.js +7 -6
  20. package/dist/analysis/trade_profitability.js +2 -1
  21. package/dist/credential-daemon.js +13 -2
  22. package/dist/dexbot.js +4 -4
  23. package/dist/modules/account_bots.d.ts +11 -1
  24. package/dist/modules/account_orders.d.ts +12 -0
  25. package/dist/modules/account_orders.js +30 -0
  26. package/dist/modules/bitshares-native/transport.js +24 -6
  27. package/dist/modules/bitshares_client.d.ts +24 -6
  28. package/dist/modules/bitshares_client.js +44 -7
  29. package/dist/modules/bot_settings.d.ts +2 -0
  30. package/dist/modules/constants.d.ts +26 -3
  31. package/dist/modules/constants.js +63 -8
  32. package/dist/modules/dexbot_class.d.ts +1 -6
  33. package/dist/modules/dexbot_class.js +14 -0
  34. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  35. package/dist/modules/dexbot_cow_runtime.js +620 -132
  36. package/dist/modules/dexbot_fill_runtime.js +124 -35
  37. package/dist/modules/dexbot_maintenance_runtime.js +226 -73
  38. package/dist/modules/dexbot_startup_runtime.js +32 -20
  39. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  40. package/dist/modules/dexbot_state_recovery.js +167 -5
  41. package/dist/modules/node_connect_policy.d.ts +8 -1
  42. package/dist/modules/node_connect_policy.js +18 -2
  43. package/dist/modules/node_flap_score.d.ts +87 -0
  44. package/dist/modules/node_flap_score.js +124 -0
  45. package/dist/modules/node_health_cache.d.ts +40 -3
  46. package/dist/modules/node_health_cache.js +66 -20
  47. package/dist/modules/node_manager.d.ts +101 -19
  48. package/dist/modules/node_manager.js +255 -65
  49. package/dist/modules/order/accounting.js +56 -7
  50. package/dist/modules/order/format.d.ts +24 -10
  51. package/dist/modules/order/format.js +30 -10
  52. package/dist/modules/order/grid.js +82 -11
  53. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  54. package/dist/modules/order/grid_reconcile.js +333 -210
  55. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  56. package/dist/modules/order/grid_reconcile_internal.js +207 -87
  57. package/dist/modules/order/index.d.ts +4 -0
  58. package/dist/modules/order/lifecycle.d.ts +353 -0
  59. package/dist/modules/order/lifecycle.js +1109 -0
  60. package/dist/modules/order/manager.d.ts +271 -5
  61. package/dist/modules/order/manager.js +651 -48
  62. package/dist/modules/order/placement_lock.d.ts +102 -0
  63. package/dist/modules/order/placement_lock.js +222 -0
  64. package/dist/modules/order/strategy.js +13 -1
  65. package/dist/modules/order/sync_engine.d.ts +13 -1
  66. package/dist/modules/order/sync_engine.js +153 -53
  67. package/dist/modules/order/utils/math.d.ts +22 -1
  68. package/dist/modules/order/utils/math.js +54 -1
  69. package/dist/modules/order/utils/order.d.ts +75 -5
  70. package/dist/modules/order/utils/order.js +158 -9
  71. package/dist/modules/order/utils/system.d.ts +18 -0
  72. package/dist/modules/order/utils/system.js +84 -8
  73. package/dist/modules/order/utils/validate.d.ts +7 -1
  74. package/dist/modules/order/utils/validate.js +48 -2
  75. package/dist/modules/outcome.d.ts +54 -0
  76. package/dist/modules/outcome.js +51 -0
  77. package/dist/modules/settings_merge.d.ts +4 -0
  78. package/dist/modules/settings_merge.js +9 -0
  79. package/dist/modules/timing_policy.d.ts +82 -0
  80. package/dist/modules/timing_policy.js +244 -0
  81. package/dist/modules/types.d.ts +132 -0
  82. package/dist/scripts/analyze-credit.js +54 -17
  83. package/dist/scripts/analyze-orders.d.ts +4 -2
  84. package/dist/scripts/analyze-orders.js +113 -34
  85. package/dist/scripts/chart_targets.js +11 -15
  86. package/dist/scripts/test-credit-renewal.js +12 -5
  87. package/docs/COW_INVARIANTS.md +67 -8
  88. package/docs/DEXBOT_COMPARISON.md +6 -6
  89. package/docs/EVOLUTION.md +9 -8
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  91. package/docs/GRID_PRICE_INVARIANT.md +1 -1
  92. package/docs/GRID_RECONCILE.md +17 -12
  93. package/docs/LOGGING.md +25 -1
  94. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +175 -26
  95. package/docs/README.md +23 -2
  96. package/docs/WORKFLOW.md +9 -3
  97. package/docs/architecture.md +42 -5
  98. package/docs/developer_guide.md +25 -8
  99. package/modules/README.md +3 -0
  100. package/package.json +1 -1
  101. package/scripts/README.md +16 -0
  102. package/scripts/pdev.sh +14 -1
  103. package/scripts/pmain.sh +23 -8
  104. package/scripts/ptest.sh +7 -0
  105. package/tests/README.md +30 -1
@@ -0,0 +1,82 @@
1
+ /**
2
+ * modules/timing_policy.ts - Timing window classification
3
+ *
4
+ * The engine has 84 timing knobs. The reason that number kept growing is that
5
+ * every "the state was briefly wrong" bug got fixed by adding a window, and
6
+ * nothing ever removed one. A window is a substitute for evidence: it says
7
+ * "wait, then guess". Some of that is unavoidable (a block takes as long as it
8
+ * takes); most of it is not.
9
+ *
10
+ * This module is the audit. Every window key is classified into one of four
11
+ * kinds, and a test fails when a new unclassified window appears — so the
12
+ * inventory can only shrink by decision, never grow by accident.
13
+ *
14
+ * EXTERNAL encodes how long the OUTSIDE world takes. Legitimate.
15
+ * (block time, node lag, RPC deadline, poll cadence)
16
+ * BOUND a leak/GC bound. Caps retention, never a correctness gate.
17
+ * Deleting one leaks memory; it cannot create a wrong decision.
18
+ * POLICY a deliberate product choice (grace, cooldown, backoff).
19
+ * Defensible, but each one is a place where behaviour is
20
+ * encoded in milliseconds instead of in state.
21
+ * SELF_HEALING compensates for our OWN lost or divergent state.
22
+ * REMOVAL TARGET: the fix is evidence (a lifecycle phase),
23
+ * not patience. See `removal` for the precondition.
24
+ *
25
+ * `derived` marks a value computed from another timing. Those are the worst
26
+ * offenders when they are also user-tunable, because the relationship is
27
+ * correctness and the surface is a settings file. constants.ts recomputes them
28
+ * post-merge and throws on a broken ordering, so they are safe to keep — but
29
+ * they must be declared, not discovered.
30
+ *
31
+ * Browser-safe: no Node APIs.
32
+ */
33
+ /** What a timing window means. See the module doc for the definitions. */
34
+ export type TimingClass = 'external' | 'bound' | 'policy' | 'self-healing';
35
+ export interface TimingClassification {
36
+ /** What kind of thing this window is. */
37
+ kind: TimingClass;
38
+ /** Why it exists, in one line. */
39
+ rationale: string;
40
+ /**
41
+ * For `self-healing`: what evidence must exist before the window can be
42
+ * deleted. Absent for other kinds.
43
+ */
44
+ removal?: string;
45
+ /** Computed from another timing rather than declared. */
46
+ derived?: boolean;
47
+ }
48
+ /**
49
+ * Classifications keyed by TIMING key.
50
+ *
51
+ * Keep entries alphabetical. A key that is not here and looks like a window
52
+ * fails `tests/test_timing_policy.ts` — that is the point.
53
+ */
54
+ export declare const TIMING_CLASSIFICATIONS: Readonly<Record<string, TimingClassification>>;
55
+ /**
56
+ * Keys that must never be classified as a time window (units, flags, counts).
57
+ * Kept explicit so the audit list stays honest.
58
+ */
59
+ export declare const NON_WINDOW_KEYS: ReadonlySet<string>;
60
+ /** True when the key looks like a time window (and is not a declared non-window). */
61
+ export declare function looksLikeTimingWindow(key: string): boolean;
62
+ /** Classify a timing key, or null when it is not a window or not classified. */
63
+ export declare function classifyTiming(key: string): TimingClassification | null;
64
+ /**
65
+ * Timing keys that look like windows but carry no classification.
66
+ *
67
+ * This is the growth gate: a new window with no rationale fails the test.
68
+ *
69
+ * @param timing - The live TIMING map (or a fixture)
70
+ * @returns {string[]} Unclassified window keys, sorted
71
+ */
72
+ export declare function unclassifiedTimingKeys(timing: Record<string, unknown>): string[];
73
+ /** All classified self-healing windows, ordered by key. */
74
+ export declare function selfHealingWindows(): Array<{
75
+ key: string;
76
+ classification: TimingClassification;
77
+ }>;
78
+ /** All classified derived timings (computed from another timing). */
79
+ export declare function derivedTimings(): string[];
80
+ /** Count of classified keys per kind, for reporting. */
81
+ export declare function timingKindCounts(): Record<TimingClass, number>;
82
+ //# sourceMappingURL=timing_policy.d.ts.map
@@ -0,0 +1,244 @@
1
+ /**
2
+ * modules/timing_policy.ts - Timing window classification
3
+ *
4
+ * The engine has 84 timing knobs. The reason that number kept growing is that
5
+ * every "the state was briefly wrong" bug got fixed by adding a window, and
6
+ * nothing ever removed one. A window is a substitute for evidence: it says
7
+ * "wait, then guess". Some of that is unavoidable (a block takes as long as it
8
+ * takes); most of it is not.
9
+ *
10
+ * This module is the audit. Every window key is classified into one of four
11
+ * kinds, and a test fails when a new unclassified window appears — so the
12
+ * inventory can only shrink by decision, never grow by accident.
13
+ *
14
+ * EXTERNAL encodes how long the OUTSIDE world takes. Legitimate.
15
+ * (block time, node lag, RPC deadline, poll cadence)
16
+ * BOUND a leak/GC bound. Caps retention, never a correctness gate.
17
+ * Deleting one leaks memory; it cannot create a wrong decision.
18
+ * POLICY a deliberate product choice (grace, cooldown, backoff).
19
+ * Defensible, but each one is a place where behaviour is
20
+ * encoded in milliseconds instead of in state.
21
+ * SELF_HEALING compensates for our OWN lost or divergent state.
22
+ * REMOVAL TARGET: the fix is evidence (a lifecycle phase),
23
+ * not patience. See `removal` for the precondition.
24
+ *
25
+ * `derived` marks a value computed from another timing. Those are the worst
26
+ * offenders when they are also user-tunable, because the relationship is
27
+ * correctness and the surface is a settings file. constants.ts recomputes them
28
+ * post-merge and throws on a broken ordering, so they are safe to keep — but
29
+ * they must be declared, not discovered.
30
+ *
31
+ * Browser-safe: no Node APIs.
32
+ */
33
+ /**
34
+ * Classifications keyed by TIMING key.
35
+ *
36
+ * Keep entries alphabetical. A key that is not here and looks like a window
37
+ * fails `tests/test_timing_policy.ts` — that is the point.
38
+ */
39
+ export const TIMING_CLASSIFICATIONS = Object.freeze({
40
+ // --- transport / external world -----------------------------------------
41
+ ACCOUNT_TOTALS_TIMEOUT_MS: { kind: 'external', rationale: 'RPC deadline for the account-balances read.' },
42
+ BLOCKCHAIN_FETCH_INTERVAL_MIN: { kind: 'external', rationale: 'How often chain state is polled (minutes).' },
43
+ BLOCKCHAIN_SETTLE_DELAY_MS: { kind: 'external', rationale: 'Block-production latency before a write is expected to be visible.' },
44
+ BOTS_CONFIG_POLL_INTERVAL_MS: { kind: 'external', rationale: 'Bots-config file poll cadence.' },
45
+ BROADCAST_DEFER_SAFETY_MARGIN_MS: { kind: 'external', rationale: 'Headroom over the stale-broadcast watchdog; feeds a derived bound.', derived: true },
46
+ BROADCAST_STALE_CLEAR_MS: { kind: 'external', rationale: 'Single authority for how long a broadcast may stay unresolved before the watchdog clears it.' },
47
+ CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Readiness poll cadence.' },
48
+ CONNECTION_TIMEOUT_MS: { kind: 'external', rationale: 'Connection-establishment deadline.' },
49
+ CREDENTIAL_BROADCAST_TIMEOUT_MS: { kind: 'external', rationale: 'Outer deadline for a daemon broadcast.' },
50
+ CREDENTIAL_DAEMON_BROADCAST_BACKOFF_MS: { kind: 'external', rationale: 'Delay between pinned-node broadcast attempts.' },
51
+ CREDENTIAL_DAEMON_INNER_DEADLINE_MS: { kind: 'external', rationale: 'Inner daemon deadline, deliberately under the outer timeout.' },
52
+ CREDENTIAL_DAEMON_SOCKET_TIMEOUT_MS: { kind: 'external', rationale: 'Idle socket timeout for the credential daemon.' },
53
+ DAEMON_PING_TIMEOUT_MS: { kind: 'external', rationale: 'Daemon healthcheck deadline.' },
54
+ DAEMON_STARTUP_TIMEOUT_MS: { kind: 'external', rationale: 'Daemon startup deadline.' },
55
+ FETCH_HISTORY_PAGE_TIMEOUT_MS: { kind: 'external', rationale: 'Per-page fill-history deadline.' },
56
+ FETCH_HISTORY_TOTAL_DEADLINE_MS: { kind: 'external', rationale: 'Total fill-history crawl deadline.' },
57
+ LOGGER_DRAIN_TIMEOUT_MS: { kind: 'bound', rationale: 'Caps how long shutdown waits for the log sink.' },
58
+ MPA_FEED_MAX_AGE_MS: { kind: 'external', rationale: 'External feed staleness (on-chain feed publication cadence).' },
59
+ OFFER_CACHE_TTL_MS: { kind: 'bound', rationale: 'Cache-retention bound for credit offers.' },
60
+ SAFETY_NET_SYNC_TIMEOUT_MS: { kind: 'external', rationale: 'Deadline for the end-of-tick safety-net sync.' },
61
+ SAFETY_PAUSE_TIMEOUT_MS: { kind: 'external', rationale: 'Upper bound on a paused pipeline before the watchdog releases it.' },
62
+ SLOW_RECONNECT_INTERVAL_MS: { kind: 'external', rationale: 'Reconnect cadence for a slow/flapping node.' },
63
+ SYNC_DELAY_MS: { kind: 'external', rationale: 'Pacing between sync attempts; keeps a burst from hammering the node.' },
64
+ SYNC_EMPTY_READ_CONFIRM_DELAY_MS: { kind: 'external', rationale: 'Node lag: wait before re-reading a suspiciously empty snapshot.' },
65
+ SYNC_LOCK_TIMEOUT_MS: { kind: 'external', rationale: 'Lock acquisition deadline; also the observed-latency scale for in-flight windows.' },
66
+ CREDIT_DEAL_CHECK_INTERVAL_MIN: { kind: 'external', rationale: 'Credit-deal poll cadence.' },
67
+ CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS: { kind: 'external', rationale: 'External deal expiry horizon.' },
68
+ CREDIT_RATE_MAX_AGE_MS: { kind: 'external', rationale: 'Staleness bound for an externally quoted rate.' },
69
+ CREDIT_DEAL_SPLIT_MAX_PIECES: { kind: 'bound', rationale: 'Caps how many pieces a credit deal may be split into.' },
70
+ CREDIT_REBORROW_MAX_ATTEMPTS: { kind: 'policy', rationale: 'Retry budget for reborrowing.' },
71
+ DUST_HEALTH_CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Dust-sweep cadence.' },
72
+ DUST_CANCEL_TIMEOUT_MS: { kind: 'external', rationale: 'How long a dust cancel waits for the fill-processing lock.' },
73
+ LIGHTWEIGHT_SYNC_CHECK_INTERVAL_MS: { kind: 'external', rationale: 'Cadence for the cheap open-orders check.' },
74
+ RUN_LOOP_DEFAULT_MS: { kind: 'external', rationale: 'Default open-orders sync cycle length.' },
75
+ SHARED_ACCOUNT_FETCH_INTERVAL_MIN: { kind: 'external', rationale: 'Shared-account balance fetch cadence.' },
76
+ BTS_ACQUIRE_COOLDOWN_MIN: { kind: 'policy', rationale: 'Cooldown between attempts to acquire BTS for fees.' },
77
+ // --- retry / backoff (bounded policy) -----------------------------------
78
+ RETRY_BACKOFF_CAP_MS: { kind: 'policy', rationale: 'Upper bound on exponential backoff.' },
79
+ FILL_TOTALS_RETRY_BASE_MS: { kind: 'policy', rationale: 'Backoff base for re-processing a fill whose totals were unavailable.' },
80
+ FILL_TOTALS_RETRY_MAX_MS: { kind: 'policy', rationale: 'Backoff ceiling for the same retry.' },
81
+ CREDENTIAL_DAEMON_BROADCAST_RETRIES: { kind: 'policy', rationale: 'Attempt budget for a pinned-node broadcast.' },
82
+ CREDENTIAL_DAEMON_WATCHDOG_MS: { kind: 'external', rationale: 'Watchdog poll cadence.' },
83
+ CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD: { kind: 'policy', rationale: 'Consecutive watchdog failures that mark the daemon dead.' },
84
+ // --- resource bounds (never a correctness gate) -------------------------
85
+ AUDIT_LOG_MAX_FILES: { kind: 'bound', rationale: 'Audit-log rotation bound.' },
86
+ AUDIT_LOG_MAX_SIZE: { kind: 'bound', rationale: 'Audit-log size bound.' },
87
+ CREDENTIAL_DAEMON_MAX_BUFFER_SIZE: { kind: 'bound', rationale: 'Daemon socket buffer bound.' },
88
+ FILL_RECORD_RETENTION_MS: { kind: 'bound', rationale: 'How long persisted fill records are kept (double-credit window).' },
89
+ PROCESSED_FILL_PERSIST_BATCH_SIZE: { kind: 'bound', rationale: 'Coalescing bound for processed-fill writes.' },
90
+ PROCESSED_FILL_PERSIST_BATCH_MS: { kind: 'bound', rationale: 'Coalescing window for processed-fill writes.' },
91
+ MILLISECONDS_PER_SECOND: { kind: 'bound', rationale: 'Unit constant, not a window.' },
92
+ OPEN_ORDERS_SYNC_LOOP_ENABLED: { kind: 'policy', rationale: 'Feature flag, not a window.' },
93
+ GRID_LOCK_HOLD_WARN_MS: { kind: 'bound', rationale: 'Observability: warn when a grid lock is held too long.' },
94
+ LOG_THROTTLE_INTERVAL_MS: { kind: 'bound', rationale: 'Log rate limit.' },
95
+ STALE_TOTALS_WARN_RATE_LIMIT_MS: { kind: 'bound', rationale: 'Log rate limit.' },
96
+ LOCK_REFRESH_MIN_MS: { kind: 'bound', rationale: 'Lease-refresh cadence during long operations.' },
97
+ LOCK_TIMEOUT_MS: { kind: 'external', rationale: 'Order-lock lease length (network latency scale).' },
98
+ MAX_ACCOUNT_TOTALS_AGE_MS: { kind: 'bound', rationale: 'Staleness bound before totals are refetched.' },
99
+ // --- policy windows (real product choices) ------------------------------
100
+ BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on boundary-hold resync escalation.' },
101
+ BOUNDARY_HOLD_RESYNC_THRESHOLD: { kind: 'policy', rationale: 'Consecutive boundary holds before escalation.' },
102
+ GRID_BLOAT_RESYNC_GRACE_MS: { kind: 'policy', rationale: 'Grace before a bloat resync is re-requested.' },
103
+ GRID_PRICE_INVARIANT_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on invariant resync escalation.' },
104
+ GRID_PRICE_INVARIANT_RESYNC_THRESHOLD: { kind: 'policy', rationale: 'Consecutive invariant failures before escalation.' },
105
+ SPREAD_CORRECTION_MAX_ATTEMPTS: { kind: 'policy', rationale: 'Attempt budget for spread correction.' },
106
+ SPREAD_CORRECTION_SYNC_FRESH_MS: { kind: 'policy', rationale: 'How fresh the last sync must be to trust a spread decision.' },
107
+ SPREAD_STALE_ESCALATE_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before escalation.' },
108
+ SPREAD_STALE_FUND_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is fundability.' },
109
+ SPREAD_STALE_GEOMETRY_ESCALATE_MS: { kind: 'policy', rationale: 'Shortened escalation window when the cause is geometry.' },
110
+ SPREAD_STALE_IN_TOLERANCE_RESET_MS: { kind: 'policy', rationale: 'How long in-tolerance must hold before the watchdog resets.' },
111
+ SPREAD_STALE_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on spread-correction resyncs.' },
112
+ SPREAD_STALE_TRANSIENT_GRACE: { kind: 'policy', rationale: 'Consecutive transient corrections tolerated before escalating.' },
113
+ SPREAD_STALE_WARN_MS: { kind: 'policy', rationale: 'Out-of-spread persistence before a warning.' },
114
+ TARGETED_DRIFT_SYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on targeted drift syncs.' },
115
+ DEFERRED_HOLD_ESCALATE_MS: { kind: 'policy', rationale: 'How long an unchanged deferred-hold signature is tolerated.' },
116
+ DEFERRED_HOLD_RESYNC_COOLDOWN_MS: { kind: 'policy', rationale: 'Rate limit on deferred-hold resyncs.' },
117
+ // --- self-healing windows -----------------------------------------------
118
+ //
119
+ // These exist because the engine could not tell two local states apart.
120
+ // modules/order/lifecycle.ts now records the difference explicitly, so each
121
+ // of these is a candidate for deletion once its evidence path is proven in
122
+ // live operation.
123
+ SURPLUS_CANCEL_GRACE_MS: {
124
+ kind: 'self-healing',
125
+ rationale: 'A just-placed order may be missing from a slightly stale reconcile snapshot; wait instead of cancelling it.',
126
+ removal: 'Delete when the COW planner reads the chain id from the lifecycle record (phase landed) instead of tolerating its absence.',
127
+ },
128
+ PENDING_BROADCAST_TTL_MS: {
129
+ kind: 'self-healing',
130
+ rationale: 'A CREATE whose receipt was lost used to be forgotten after a timeout; now it also becomes lifecycle phase unknown.',
131
+ removal: 'Keep as a GC/abandon bound until lost receipts are resolved by evidence (adoption or confirmed absence). The correctness role is already gone — only the retention cap remains.',
132
+ },
133
+ CHAIN_SIZE_APPLIED_MARKER_TTL_MS: {
134
+ kind: 'self-healing',
135
+ rationale: 'Dedupe marker for a chain-size resize already absorbed by sync pass 1.',
136
+ removal: 'Delete when the fill-history path can identify an already-applied resize from the lifecycle record rather than a timestamped marker.',
137
+ },
138
+ BATCH_INFLIGHT_STALE_MS: {
139
+ kind: 'bound',
140
+ rationale: 'Leak watchdog for an in-flight batch flag. Cannot affect a decision.',
141
+ },
142
+ RECOVERY_INFLIGHT_STALE_MS: {
143
+ kind: 'bound',
144
+ rationale: 'Leak watchdog for an in-flight recovery flag.',
145
+ },
146
+ PLACEMENT_STALE_CLEAR_MS: {
147
+ kind: 'bound',
148
+ rationale: 'Leak watchdog for a placement lease.',
149
+ },
150
+ STRUCTURAL_REBUILD_DEFER_MAX_MS: {
151
+ kind: 'self-healing',
152
+ rationale: 'Caps how long a fill-driven rebalance may defer behind a structural rebuild.',
153
+ removal: 'Delete when the rebuild publishes a completion event the rebalance can await instead of polling a deadline.',
154
+ },
155
+ FILL_BROADCAST_DEFER_MAX_MS: {
156
+ kind: 'self-healing',
157
+ rationale: 'Bound on fill-consumer deferral while a broadcast is unresolved.',
158
+ removal: 'Delete when the fill consumer can query the lifecycle phase instead of a clock.',
159
+ derived: true,
160
+ },
161
+ SYNC_LOCK_FORCE_RELEASE_AGE_MS: {
162
+ kind: 'bound',
163
+ rationale: 'Force-release a sync lock held past 2× its timeout (deadlock escape hatch).',
164
+ removal: 'Keep: this is a liveness bound on a lock, not a state guess.',
165
+ derived: true,
166
+ },
167
+ SYNC_SUSPECT_EMPTY_READ_LIMIT: {
168
+ kind: 'policy', rationale: 'Consecutive empty reads before an empty snapshot is believed.',
169
+ },
170
+ FILL_DEDUPE_WINDOW_MS: {
171
+ kind: 'self-healing',
172
+ rationale: 'Coalescing window for duplicate fill events.',
173
+ removal: 'Delete when fill identity is a chain tuple (tx+op) everywhere; the window would then be redundant with that key.',
174
+ },
175
+ });
176
+ /**
177
+ * Keys that must never be classified as a time window (units, flags, counts).
178
+ * Kept explicit so the audit list stays honest.
179
+ */
180
+ export const NON_WINDOW_KEYS = new Set([
181
+ 'AUDIT_LOG_MAX_FILES',
182
+ 'CREDENTIAL_DAEMON_BROADCAST_RETRIES',
183
+ 'CREDIT_DEAL_SPLIT_MAX_PIECES',
184
+ 'CREDIT_REBORROW_MAX_ATTEMPTS',
185
+ 'MILLISECONDS_PER_SECOND',
186
+ 'OPEN_ORDERS_SYNC_LOOP_ENABLED',
187
+ 'PROCESSED_FILL_PERSIST_BATCH_SIZE',
188
+ 'SPREAD_CORRECTION_MAX_ATTEMPTS',
189
+ 'SPREAD_STALE_TRANSIENT_GRACE',
190
+ 'BOUNDARY_HOLD_RESYNC_THRESHOLD',
191
+ 'GRID_PRICE_INVARIANT_RESYNC_THRESHOLD',
192
+ 'CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD',
193
+ 'CREDENTIAL_DAEMON_MAX_BUFFER_SIZE',
194
+ 'AUDIT_LOG_MAX_SIZE',
195
+ 'SYNC_SUSPECT_EMPTY_READ_LIMIT',
196
+ ]);
197
+ /** Name shape that makes a key look like a time window. */
198
+ const WINDOW_PATTERN = /(_MS|_MIN|_HOURS|_TTL|_GRACE|_COOLDOWN|_WINDOW|_DELAY|_INTERVAL|_DEADLINE|_TIMEOUT|_AGE|_LIFETIME)$/;
199
+ /** True when the key looks like a time window (and is not a declared non-window). */
200
+ export function looksLikeTimingWindow(key) {
201
+ if (NON_WINDOW_KEYS.has(key))
202
+ return false;
203
+ return WINDOW_PATTERN.test(key);
204
+ }
205
+ /** Classify a timing key, or null when it is not a window or not classified. */
206
+ export function classifyTiming(key) {
207
+ return TIMING_CLASSIFICATIONS[key] ?? null;
208
+ }
209
+ /**
210
+ * Timing keys that look like windows but carry no classification.
211
+ *
212
+ * This is the growth gate: a new window with no rationale fails the test.
213
+ *
214
+ * @param timing - The live TIMING map (or a fixture)
215
+ * @returns {string[]} Unclassified window keys, sorted
216
+ */
217
+ export function unclassifiedTimingKeys(timing) {
218
+ return Object.keys(timing)
219
+ .filter((key) => looksLikeTimingWindow(key) && classifyTiming(key) === null)
220
+ .sort();
221
+ }
222
+ /** All classified self-healing windows, ordered by key. */
223
+ export function selfHealingWindows() {
224
+ return Object.entries(TIMING_CLASSIFICATIONS)
225
+ .filter(([, classification]) => classification.kind === 'self-healing')
226
+ .map(([key, classification]) => ({ key, classification }))
227
+ .sort((a, b) => a.key.localeCompare(b.key));
228
+ }
229
+ /** All classified derived timings (computed from another timing). */
230
+ export function derivedTimings() {
231
+ return Object.entries(TIMING_CLASSIFICATIONS)
232
+ .filter(([, classification]) => classification.derived === true)
233
+ .map(([key]) => key)
234
+ .sort();
235
+ }
236
+ /** Count of classified keys per kind, for reporting. */
237
+ export function timingKindCounts() {
238
+ const counts = { external: 0, bound: 0, policy: 0, 'self-healing': 0 };
239
+ for (const classification of Object.values(TIMING_CLASSIFICATIONS)) {
240
+ counts[classification.kind] += 1;
241
+ }
242
+ return counts;
243
+ }
244
+ //# sourceMappingURL=timing_policy.js.map
@@ -969,6 +969,64 @@ interface ManagerRecoveryState {
969
969
  * (e.g. `requestStructuralGridResync`, `notifyBoundaryUpdate`) or read only
970
970
  * defensively; keep them optional so partial test doubles still type-check.
971
971
  */
972
+ /**
973
+ * Three-valued result of an operation whose outcome is not always knowable.
974
+ *
975
+ * The engine used to encode this as an ad-hoc `uncertain: true` property next
976
+ * to a second ad-hoc flag (`ambiguousRead`), so the two could disagree and no
977
+ * consumer was forced to handle the third case. `unknown` is now a real
978
+ * alternative in the type: code that branches on "applied or not" fails to
979
+ * compile until it says what it does when it does not know.
980
+ */
981
+ export type OutcomeKind = 'applied' | 'rejected' | 'unknown';
982
+ /** Why the outcome is unknown. Every `unknown` must say which one it is. */
983
+ export type UnknownCause = 'timeout' | 'ambiguous-read' | 'lost-receipt' | 'unavailable';
984
+ export interface AppliedOutcome<T> {
985
+ kind: 'applied';
986
+ value: T;
987
+ }
988
+ export interface RejectedOutcome {
989
+ kind: 'rejected';
990
+ reason: string;
991
+ }
992
+ export interface UnknownOutcome {
993
+ kind: 'unknown';
994
+ cause: UnknownCause;
995
+ detail?: string;
996
+ }
997
+ export type Outcome<T = unknown> = AppliedOutcome<T> | RejectedOutcome | UnknownOutcome;
998
+ /**
999
+ * Structural mirror of `LifecycleView` (modules/order/lifecycle.ts).
1000
+ *
1001
+ * Declared here rather than imported so `types.ts` stays dependency-free; the
1002
+ * registry's own view type is structurally assignable to it.
1003
+ */
1004
+ export interface OrderLifecycleViewLike {
1005
+ slotId: string | null;
1006
+ orderId: string | null;
1007
+ phase: 'intent' | 'broadcasting' | 'landed' | 'filling' | 'gone' | 'unknown';
1008
+ evidence: 'none' | 'local' | 'broadcast-receipt' | 'chain-snapshot' | 'fill-history' | 'adoption';
1009
+ recordedAt: number;
1010
+ observedAt: number;
1011
+ assignedAt: number;
1012
+ placedAt: number;
1013
+ committedAt: number;
1014
+ isUnknown: boolean;
1015
+ /** Phase is `unknown` or `broadcasting`: unresolved evidence, not absence. */
1016
+ isUnresolved: boolean;
1017
+ mayExistOnChain: boolean;
1018
+ isConfirmedGone: boolean;
1019
+ isIntentOnly: boolean;
1020
+ isOnChain: boolean;
1021
+ isFreshlyPlaced(graceMs?: number, now?: number): boolean;
1022
+ isRecentlyAssigned(windowMs?: number, now?: number): boolean;
1023
+ isRecentlyCommitted(windowMs?: number, now?: number): boolean;
1024
+ isInFlight(windowMs?: number, now?: number): boolean;
1025
+ isUnresolvedFresh(now?: number): boolean;
1026
+ appliedFillMatches(filledInt: number): boolean;
1027
+ /** True when the phase was recorded by evidence from outside the process. */
1028
+ isChainBacked(): boolean;
1029
+ }
972
1030
  /** Minimal surface of the credit runtime consumed by the bot/manager layer. */
973
1031
  export interface CreditRuntimeLike {
974
1032
  config: GridConfig;
@@ -979,6 +1037,29 @@ export interface CreditRuntimeLike {
979
1037
  shutdown(): Promise<unknown>;
980
1038
  }
981
1039
  export interface OrderManagerLike {
1040
+ /**
1041
+ * Unified order-lifecycle read surface (see modules/order/lifecycle.ts).
1042
+ * Answers "does this order exist on chain, and how sure are we" from ONE
1043
+ * record instead of the per-site subsets the engine used to consult.
1044
+ */
1045
+ _lifecycle?: {
1046
+ view(identity: string | null | undefined): OrderLifecycleViewLike;
1047
+ markUnknown?(orderId: string | null | undefined, input?: {
1048
+ slotId?: string | null;
1049
+ evidence?: OrderLifecycleViewLike['evidence'];
1050
+ }): OrderLifecycleViewLike;
1051
+ markLanded?(orderId: string | null | undefined, input?: {
1052
+ slotId?: string | null;
1053
+ evidence?: OrderLifecycleViewLike['evidence'];
1054
+ phase?: OrderLifecycleViewLike['phase'];
1055
+ }): OrderLifecycleViewLike;
1056
+ };
1057
+ getLifecycle(identity: string | null | undefined): OrderLifecycleViewLike;
1058
+ getSlotLifecycle(slot: {
1059
+ id?: string;
1060
+ orderId?: string | null;
1061
+ createUncertain?: boolean;
1062
+ } | null | undefined): OrderLifecycleViewLike;
982
1063
  _consecutiveBoundaryHolds?: number;
983
1064
  /**
984
1065
  * Set by the spread-correction planner when the corrected side's rail reserves
@@ -1023,6 +1104,8 @@ export interface OrderManagerLike {
1023
1104
  targetGrid?: unknown;
1024
1105
  initialSpreadCount: number;
1025
1106
  currentSpreadCount: number;
1107
+ /** True once the spread metric has been measured (load/create); both counters are 0 before that. */
1108
+ _spreadCountKnown?: boolean;
1026
1109
  outOfSpread: number;
1027
1110
  btsBalance?: {
1028
1111
  free: number;
@@ -1142,6 +1225,10 @@ export interface OrderManagerLike {
1142
1225
  _gridBloatDetectedAt?: number;
1143
1226
  isRebalancing(): boolean;
1144
1227
  isBootstrapping(): boolean;
1228
+ beginStructuralRebuild?(reason?: string): void;
1229
+ endStructuralRebuild?(): void;
1230
+ isStructuralRebuildInProgress?(): boolean;
1231
+ structuralRebuildReason?(): string | null;
1145
1232
  isBroadcastingActive(): boolean;
1146
1233
  isPlanningActive(): boolean;
1147
1234
  setShuttingDown(value: boolean): void;
@@ -1149,6 +1236,51 @@ export interface OrderManagerLike {
1149
1236
  finishBootstrap(): void;
1150
1237
  startBroadcasting(): void;
1151
1238
  stopBroadcasting(): void;
1239
+ /** Exclusive placement region shared by every chain-mutating path. */
1240
+ acquirePlacement?: (kind: string, options?: {
1241
+ timeoutMs?: number;
1242
+ isShuttingDown?: () => boolean;
1243
+ }) => Promise<{
1244
+ kind: string;
1245
+ release(): void;
1246
+ } | null>;
1247
+ tryAcquirePlacement?: (kind: string) => {
1248
+ kind: string;
1249
+ release(): void;
1250
+ } | null;
1251
+ isPlacementActive?: () => boolean;
1252
+ /** Whether this lease still owns the region (authoritative nesting check). */
1253
+ isPlacementLeaseCurrent?: (lease: {
1254
+ kind: string;
1255
+ release(): void;
1256
+ } | null | undefined) => boolean;
1257
+ withPlacement?<T>(kind: string, fn: (lease: {
1258
+ kind: string;
1259
+ release(): void;
1260
+ }) => Promise<T>, options?: {
1261
+ timeoutMs?: number;
1262
+ isShuttingDown?: () => boolean;
1263
+ }): Promise<T | null>;
1264
+ placementKind?: () => string | null;
1265
+ placementHeldForMs?: () => number;
1266
+ /** Force-release a placement region held longer than the leak watchdog. */
1267
+ _clearStalePlacementRegion?: (maxAgeMs?: number, options?: {
1268
+ batchInFlightMs?: number;
1269
+ }) => boolean;
1270
+ /** Pass-1 chain-size markers (see note/consumeChainSizeAppliedFill). */
1271
+ _chainSizeAppliedFills?: Map<string, {
1272
+ filledInt: number;
1273
+ at: number;
1274
+ }>;
1275
+ noteChainSizeAppliedFill?: (orderId: string, filledInt: number, maxAgeMs?: number) => void;
1276
+ consumeChainSizeAppliedFillAmount?: (orderId: string, filledInt: number, maxAgeMs?: number) => number;
1277
+ consumeChainSizeAppliedFill?: (orderId: string, filledInt: number, maxAgeMs?: number) => boolean;
1278
+ snapshotChainSizeAppliedFills?: () => Record<string, {
1279
+ filledInt: number;
1280
+ at: number;
1281
+ }>;
1282
+ restoreChainSizeAppliedFills?: (payload: unknown) => void;
1283
+ isStructuralRebuildStale?: (reason: unknown) => boolean;
1152
1284
  addBroadcastRegionEndListener(listener: () => void): void;
1153
1285
  _applySync(data: unknown, src: string): Promise<unknown>;
1154
1286
  synchronizeWithChain(data: unknown, src: string): Promise<SyncResult>;
@@ -28,20 +28,29 @@ const require = createRequire(import.meta.url);
28
28
  * debt_asset, debt_amount, collateral_asset, collateral_amount.
29
29
  *
30
30
  * Usage:
31
- * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
- * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
31
+ * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
+ * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
33
+ * node dist/scripts/analyze-credit.js <account> # every bot on that account
34
+ *
35
+ * The positional target matches a bot name/key, or the chain account the bot
36
+ * trades from (`preferredAccount` as a name or 1.2.x id, or the `accountId`
37
+ * stamped beside it by analysis/account_resolver.ts). Account matching is what
38
+ * makes `dexbot credit <account>` work on a shared account, where one account
39
+ * hosts several bot entries — the same target spelling `dexbot pnl` accepts.
33
40
  */
34
41
  const { BitShares, waitForConnected, disconnectClient, setSuppressConnectionLog } = require('../modules/bitshares_client');
35
42
  const { FEE_PARAMETERS } = require('../modules/constants');
36
43
  const { PATHS } = require('../modules/paths');
37
44
  const { getErrorMessage } = require('../modules/utils/errors');
38
- const { sanitizeKey } = require('../modules/utils/sanitize_key');
39
45
  const { normalizeAssetRef, normalizeAssetSymbol, isSameAssetSymbol } = require('../modules/utils/asset_symbols');
40
46
  const { loadSettingsFile, resolveRawBotEntries, normalizeBotEntries } = require('../modules/bot_settings');
41
47
  import { pathToFileURL } from 'node:url';
42
48
  // Terminal colors: centralized palette (modules/cli_colors.ts), shared with
43
49
  // `dexbot order` so both analyzers stay visually in lockstep.
44
50
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
51
+ // `<bot|account>` target matching lives in analysis/bot_key_utils so `credit`,
52
+ // `order`, `pnl` and the chart commands share one rule set.
53
+ import { matchBotTargetIn } from '../analysis/bot_key_utils.js';
45
54
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
46
55
  import { setGlobalConsoleLevel } from '../modules/order/logger.js';
47
56
  import { deriveLiquidityPoolTokenValue } from '../modules/order/utils/system.js';
@@ -186,29 +195,57 @@ function mpaCollateralRaw(order) {
186
195
  async function main() {
187
196
  const rawArgs = process.argv.slice(2);
188
197
  if (rawArgs.includes('-h') || rawArgs.includes('--help')) {
189
- console.log('Usage: dexbot credit [<bot>]');
198
+ console.log('Usage: dexbot credit [<bot|account>]');
190
199
  console.log(' No args Summed MPA + borrowed-credit positions for credit-enabled bots.');
191
- console.log(' <bot> Only the named bot (matches name or sanitized key).');
200
+ console.log(' <bot> Only the named bot (matches name or bot key).');
201
+ console.log(' <account> Only the bots trading that account (preferredAccount name or 1.2.x id);');
202
+ console.log(' a shared account lists every bot entry that uses it.');
192
203
  console.log('Live chain data via get_margin_positions + get_credit_deals_by_borrower per preferredAccount.');
193
204
  process.exit(0);
194
205
  }
195
206
  const botFilter = rawArgs.find((a) => !a.startsWith('-'))?.trim().toLowerCase() || null;
196
207
  const { config } = loadSettingsFile(BOTS_FILE);
197
- let bots = normalizeBotEntries(resolveRawBotEntries(config))
198
- .filter((b) => b && b.active !== false && hasLending(b));
199
- if (botFilter) {
200
- const sanitized = sanitizeKey(botFilter);
201
- const matched = bots.filter((b) => String(b.name || '').toLowerCase() === botFilter ||
202
- sanitizeKey(String(b.name || '')) === sanitized ||
203
- String(b.botKey || '').toLowerCase() === botFilter);
204
- if (matched.length === 0) {
205
- console.log(`${colors.sell}No credit bot found for '${botFilter}'.${colors.reset}`);
208
+ // Keep every entry (with its file-order index, which unnamed bots' keys are
209
+ // derived from) so target matching cannot drift from what the runtime writes.
210
+ const allBots = normalizeBotEntries(resolveRawBotEntries(config)).filter((b) => Boolean(b));
211
+ const activeBots = allBots.filter((b) => b.active !== false);
212
+ // One account can back several bot entries, so a matched account selects all
213
+ // of them — the account-level view `dexbot credit <account>` promises.
214
+ const targets = botFilter ? matchBotTargetIn(allBots, botFilter) : [];
215
+ const targeted = botFilter ? new Set(targets.map((m) => m.meta)) : null;
216
+ let bots = activeBots.filter((b) => hasLending(b) && (!targeted || targeted.has(b)));
217
+ if (botFilter && bots.length === 0) {
218
+ const matchedEntries = targets.map((m) => m.meta);
219
+ const describe = (b) => ` - ${b.name || b.botKey || 'unnamed'}${b.preferredAccount ? ` (account: ${b.preferredAccount})` : ''}${hasLending(b) ? '' : ' (no debtPolicy)'}${b.active === false ? ' (inactive)' : ''}`;
220
+ // The `Available bots` hint keeps listing inactive entries so a disabled
221
+ // bot's name and account stay discoverable.
222
+ if (matchedEntries.length === 0) {
223
+ console.log(`${colors.sell}No credit bot or account found for '${botFilter}'.${colors.reset}`);
206
224
  console.log('Available bots:');
207
- const all = normalizeBotEntries(resolveRawBotEntries(config));
208
- all.forEach((b) => console.log(` - ${b.name}${hasLending(b) ? '' : ' (no debtPolicy)'}`));
225
+ allBots.forEach((b) => console.log(describe(b)));
226
+ process.exit(0);
227
+ }
228
+ const enabledMatches = matchedEntries.filter((b) => b.active !== false);
229
+ if (enabledMatches.length === 0) {
230
+ // Disabled bots are never reported, whatever their policy.
231
+ console.log(`${colors.yellow}Matched '${botFilter}' only on inactive entries:${colors.reset}`);
232
+ matchedEntries.forEach((b) => console.log(describe(b)));
233
+ console.log('Enable it with `dexbot enable <bot>`, or drop the filter to sum the active credit bots.');
209
234
  process.exit(0);
210
235
  }
211
- bots = matched;
236
+ // Enabled match(es) without a debtPolicy: that policy also supplies the
237
+ // per-bot asset filter, so without it a shared account's positions cannot
238
+ // be attributed. List every match — an inactive entry may still carry the
239
+ // policy and only need enabling.
240
+ console.log(`${colors.yellow}Matched '${botFilter}' but no enabled entry has debtPolicy.lending:${colors.reset}`);
241
+ matchedEntries.forEach((b) => console.log(describe(b)));
242
+ // Every enabled match lacks the policy here (a credit-enabled one would have
243
+ // been reported), so both remedies are always offered.
244
+ console.log('Add a debtPolicy via `dexbot bot` to include it in `dexbot credit`.');
245
+ if (matchedEntries.some((b) => b.active === false)) {
246
+ console.log('Disabled entries also need `dexbot enable <bot>` first.');
247
+ }
248
+ process.exit(0);
212
249
  }
213
250
  if (bots.length === 0) {
214
251
  console.log(`No credit-enabled bots found in ${BOTS_FILE} (debtPolicy.lending is empty everywhere).`);
@@ -10,13 +10,15 @@
10
10
  * - Grid slot distribution (% near center) vs grid composition
11
11
  *
12
12
  * Usage:
13
- * node dist/scripts/analyze-orders.js # terminal output
14
- * node dist/scripts/analyze-orders.js --export # standalone HTML report
13
+ * node dist/scripts/analyze-orders.js # terminal output
14
+ * node dist/scripts/analyze-orders.js <bot|account> # one bot, or every bot on an account
15
+ * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
16
  */
16
17
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
17
18
  /** Loose JSON-object view used across the analyzer. */
18
19
  type JsonObj = Record<string, unknown>;
19
20
  interface GridSlot {
21
+ id?: string;
20
22
  type?: string;
21
23
  state?: string;
22
24
  price: number;