dexterm-cli 0.1.7 → 0.2.0

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 (119) hide show
  1. package/dist/packages/agents/src/spectator.js +3 -1
  2. package/dist/packages/agents/src/tiers.js +9 -0
  3. package/dist/packages/agents/src/tools.js +10 -5
  4. package/dist/packages/autotrade/assets/limits.schema.json +569 -0
  5. package/dist/packages/autotrade/examples/executor/README.md +70 -0
  6. package/dist/packages/autotrade/examples/executor/jsonl-tail-executor.mjs +57 -0
  7. package/dist/packages/autotrade/examples/executor/kit.mjs +144 -0
  8. package/dist/packages/autotrade/examples/executor/signal-cmd-executor.mjs +25 -0
  9. package/dist/packages/autotrade/examples/executor/telegram-bot-recipe.md +47 -0
  10. package/dist/packages/autotrade/examples/executor/webhook-executor.mjs +47 -0
  11. package/dist/packages/autotrade/src/backtest.js +2 -1
  12. package/dist/packages/autotrade/src/chat/config.js +4 -2
  13. package/dist/packages/autotrade/src/chat/control.js +1 -0
  14. package/dist/packages/autotrade/src/chat/notify.js +16 -6
  15. package/dist/packages/autotrade/src/chat/secrets.js +25 -18
  16. package/dist/packages/autotrade/src/chat/service.js +3 -0
  17. package/dist/packages/autotrade/src/engine.js +16 -2
  18. package/dist/packages/autotrade/src/executor-health.js +217 -0
  19. package/dist/packages/autotrade/src/fleet.js +3 -0
  20. package/dist/packages/autotrade/src/forward.js +355 -0
  21. package/dist/packages/autotrade/src/index.js +19 -0
  22. package/dist/packages/autotrade/src/journey.js +477 -0
  23. package/dist/packages/autotrade/src/limits.js +682 -0
  24. package/dist/packages/autotrade/src/outbox.js +394 -0
  25. package/dist/packages/autotrade/src/paper-limits.js +87 -0
  26. package/dist/packages/autotrade/src/real-mode.js +688 -0
  27. package/dist/packages/autotrade/src/receipts.js +330 -0
  28. package/dist/packages/autotrade/src/report.js +168 -0
  29. package/dist/packages/autotrade/src/runner.js +62 -11
  30. package/dist/packages/autotrade/src/service-guard.js +125 -0
  31. package/dist/packages/autotrade/src/service-install.js +213 -0
  32. package/dist/packages/autotrade/src/service-recover.js +232 -0
  33. package/dist/packages/autotrade/src/service.js +289 -0
  34. package/dist/packages/autotrade/src/signal-channels.js +312 -0
  35. package/dist/packages/autotrade/src/signal.js +196 -0
  36. package/dist/packages/autotrade/src/strategy.js +3 -1
  37. package/dist/packages/autotrade/src/trade-ledger.js +2 -2
  38. package/dist/packages/cli/src/analyst/backend.js +3 -2
  39. package/dist/packages/cli/src/analyst/codex.js +3 -2
  40. package/dist/packages/cli/src/app-help-gen.js +14 -2
  41. package/dist/packages/cli/src/autotrade-cmd/audit.js +19 -2
  42. package/dist/packages/cli/src/autotrade-cmd/backtest.js +21 -4
  43. package/dist/packages/cli/src/autotrade-cmd/executor.js +91 -0
  44. package/dist/packages/cli/src/autotrade-cmd/fleet.js +8 -4
  45. package/dist/packages/cli/src/autotrade-cmd/forward.js +283 -0
  46. package/dist/packages/cli/src/autotrade-cmd/journey.js +208 -0
  47. package/dist/packages/cli/src/autotrade-cmd/limits.js +393 -0
  48. package/dist/packages/cli/src/autotrade-cmd/receipt.js +63 -0
  49. package/dist/packages/cli/src/autotrade-cmd/report.js +79 -0
  50. package/dist/packages/cli/src/autotrade-cmd/run.js +257 -13
  51. package/dist/packages/cli/src/autotrade-cmd/service.js +873 -0
  52. package/dist/packages/cli/src/autotrade-cmd/signal.js +824 -0
  53. package/dist/packages/cli/src/autotrade-cmd.js +50 -4
  54. package/dist/packages/cli/src/ledger-cmd.js +4 -2
  55. package/dist/packages/cli/src/pnl-card.js +4 -0
  56. package/dist/packages/cli/src/screens/autotrade-journey.js +134 -0
  57. package/dist/packages/cli/src/screens/autotrade-keys.js +13 -0
  58. package/dist/packages/cli/src/screens/autotrade-screen.js +57 -6
  59. package/dist/packages/cli/src/screens/autotrade-ui.js +17 -7
  60. package/dist/packages/cli/src/screens/autotrade-worker.js +4 -2
  61. package/dist/packages/cli/src/telegram-cmd.js +4 -1
  62. package/dist/packages/cli/src/version.js +1 -1
  63. package/dist/packages/data/src/trade/ledger/schema.js +1 -1
  64. package/dist/packages/mcp/assets/kb/app-help/autotrade-executor-kit.md +44 -0
  65. package/dist/packages/mcp/assets/kb/app-help/autotrade-journey.md +46 -0
  66. package/dist/packages/mcp/assets/kb/app-help/autotrade-limits.md +48 -0
  67. package/dist/packages/mcp/assets/kb/app-help/autotrade-real-signal.md +45 -0
  68. package/dist/packages/mcp/assets/kb/app-help/live-trading.md +1 -1
  69. package/dist/packages/mcp/assets/kb/app-help/screen-autotrade.md +12 -0
  70. package/dist/packages/mcp/assets/kb/app-help/trade-ledger.md +1 -1
  71. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-change-a-strategy-by-chat.md +3 -1
  72. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-on-the-q-screen.md +1 -0
  73. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-running-it-all-day.md +2 -2
  74. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-stopping-it.md +2 -0
  75. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-the-always-on-service.md +57 -0
  76. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-what-it-is-paper-self-directed.md +9 -2
  77. package/dist/packages/mcp/assets/kb/docs/docs-autotrade-what-it-will-not-do.md +1 -1
  78. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-1-ask-for-a-strategy.md +27 -0
  79. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-2-backtest-it-held-out-split.md +31 -0
  80. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-3-forward-test-it-on-live-data.md +44 -0
  81. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-4-promote-it-to-always-on-paper.md +36 -0
  82. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-5-real-only-if-you-choose.md +36 -0
  83. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-the-ladder.md +39 -0
  84. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-the-report.md +31 -0
  85. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat-what-the-analyst-knows.md +30 -0
  86. package/dist/packages/mcp/assets/kb/docs/docs-build-a-strategy-by-chat.md +24 -0
  87. package/dist/packages/mcp/assets/kb/docs/docs-getting-started-install.md +3 -3
  88. package/dist/packages/mcp/assets/kb/docs/docs-getting-started-requirements.md +1 -1
  89. package/dist/packages/mcp/assets/kb/docs/docs-going-real-executor-health.md +38 -0
  90. package/dist/packages/mcp/assets/kb/docs/docs-going-real-paper-vs-real.md +33 -0
  91. package/dist/packages/mcp/assets/kb/docs/docs-going-real-the-digest.md +36 -0
  92. package/dist/packages/mcp/assets/kb/docs/docs-going-real-the-executor-kit.md +48 -0
  93. package/dist/packages/mcp/assets/kb/docs/docs-going-real-the-whole-path.md +37 -0
  94. package/dist/packages/mcp/assets/kb/docs/docs-going-real-what-dexterm-does-and-never-does.md +44 -0
  95. package/dist/packages/mcp/assets/kb/docs/docs-going-real-your-limits.md +77 -0
  96. package/dist/packages/mcp/assets/kb/docs/docs-going-real.md +24 -0
  97. package/dist/packages/mcp/assets/kb/docs/docs-live-trading-changed-in-0-1-7.md +1 -1
  98. package/dist/packages/mcp/assets/kb/docs/docs-live-trading-real-mode-your-strategy-s-trades-to-your.md +31 -0
  99. package/dist/packages/mcp/assets/kb/docs/docs-live-trading-the-short-version.md +1 -1
  100. package/dist/packages/mcp/assets/kb/docs/docs-live-trading-using-a-trading-bot-with-dexterm.md +0 -2
  101. package/dist/packages/mcp/assets/kb/docs/docs-live-trading-what-dexterm-does-not-do.md +1 -1
  102. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-receipts-what-your-executor-did.md +42 -0
  103. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-safety.md +34 -0
  104. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-set-it-up.md +47 -0
  105. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-the-channels.md +42 -0
  106. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-the-signal.md +48 -0
  107. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-what-it-is.md +35 -0
  108. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-what-it-will-not-do.md +34 -0
  109. package/dist/packages/mcp/assets/kb/docs/docs-real-mode-where-you-see-it.md +34 -0
  110. package/dist/packages/mcp/assets/kb/docs/docs-real-mode.md +27 -0
  111. package/dist/packages/mcp/assets/kb/docs/docs-telegram-what-it-is.md +1 -1
  112. package/dist/packages/mcp/assets/kb/entries/autotrade.md +4 -2
  113. package/dist/packages/mcp/src/autotrade-tools.js +168 -5
  114. package/dist/packages/mcp/src/engine/restrictions.js +3 -3
  115. package/dist/packages/mcp/src/index.js +1 -1
  116. package/dist/packages/mcp/src/ledger-tools.js +155 -7
  117. package/dist/packages/mcp/src/server.js +21 -10
  118. package/dist/packages/tui/src/keymap.js +7 -0
  119. package/package.json +1 -1
@@ -0,0 +1,196 @@
1
+ // dexterm autotrade — the LIVE TRADE FIRE signal, `dexterm-trade-fire/1` (task-1645, 0.2.0 card A).
2
+ //
3
+ // A strategy in mode "real" trades exactly like paper (same clamp, exits, monitor and ledger: the paper fill model is
4
+ // the monitor's own view), and every buy or sell it fills also becomes one of these signals for the user's OWN
5
+ // executor (a Telegram trading bot of their choice, or any script). dexterm holds no key, signs no transaction and
6
+ // builds none: a signal is a request the executor may act on, ignore, or reject.
7
+ //
8
+ // type "trade" side buy|sell, mint, sanitized symbol, size in SOL / USD / % of book (a sell also as the fraction
9
+ // of the position), price + mcap + liquidity context, exit reason for a sell, strategy id/version/
10
+ // hash, run id, account id, nonce, idempotency key, issued/expires, `paper: false`
11
+ // type "halted" the run stopped (end, halt, kill, a lost runner): every outstanding signal's nonce, a reason, and
12
+ // `open`: the mints dexterm still counts as held for the account (the next real run of the
13
+ // strategy takes them over and keeps their exits; they still count against the open-position cap)
14
+ // type "test" `dexterm autotrade signal test`: proves the channel; an executor must never trade on it
15
+ //
16
+ // Rules an executor follows (and SignalReceiver below implements, for scripts and the tests' fake executors):
17
+ // 1. verify the HMAC header when a secret is set (`x-dexterm-signature: t=<unix s>,v1=<hex>` over "<t>.<body>")
18
+ // 2. ignore anything past `expiresAt` (the TTL): a late signal is never acted on
19
+ // 3. dedupe by nonce (and the idempotency key `id`): delivery is at-least-once, so a repeat is normal
20
+ // 4. act only on the account id it was set up for
21
+ //
22
+ // Firewall: nothing token-authored rides along except the symbol, reduced to [A-Za-z0-9._$-] (16 chars). No name,
23
+ // no description, no links, no agent text, no paths, no keys. Every other field is an engine number or an id that
24
+ // dexterm validated itself.
25
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
26
+ export const TRADE_FIRE_SCHEMA = 'dexterm-trade-fire/1';
27
+ export const SIGNAL_TTL_DEFAULT_SEC = 60;
28
+ export const SIGNAL_TTL_MIN_SEC = 10;
29
+ export const SIGNAL_TTL_MAX_SEC = 600;
30
+ /** How far a signature's timestamp may sit from the receiver's clock. */
31
+ export const SIGNATURE_TOLERANCE_SEC = 300;
32
+ const SOL_MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
33
+ const ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
34
+ export const ACCOUNT_ID_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
35
+ const RUN_RE = /^[A-Za-z0-9._:-]{1,96}$/;
36
+ const HEX32 = /^[0-9a-f]{32}$/;
37
+ /** The only token text a signal carries: NFKC, then [A-Za-z0-9._$-] only, 16 chars, '?' when nothing is left. */
38
+ export function sanitizeSymbol(s) {
39
+ const t = String(s ?? '').normalize('NFKC').replace(/[^A-Za-z0-9._$-]/g, '').slice(0, 16);
40
+ return t || '?';
41
+ }
42
+ /** An engine reason ("hard-stop", "time_review:no-answer") reduced to [a-z0-9:_-], 40 chars. */
43
+ export function sanitizeReason(s) {
44
+ return String(s ?? '').toLowerCase().replace(/[^a-z0-9:_-]/g, '-').replace(/-+/g, '-').slice(0, 40) || 'unknown';
45
+ }
46
+ export const signalIdOf = (accountId, runId, nonce) => createHash('sha256').update(`${TRADE_FIRE_SCHEMA}|${accountId}|${runId}|${nonce}`).digest('hex').slice(0, 32);
47
+ export const clampTtl = (sec) => Math.min(SIGNAL_TTL_MAX_SEC, Math.max(SIGNAL_TTL_MIN_SEC, Math.round(Number.isFinite(sec) ? sec : SIGNAL_TTL_DEFAULT_SEC)));
48
+ const r6 = (v) => Math.round(v * 1e6) / 1e6;
49
+ const r2 = (v) => Math.round(v * 100) / 100;
50
+ const fin = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
51
+ function base(type, h) {
52
+ const ttlSec = clampTtl(h.ttlSec);
53
+ return {
54
+ schema: TRADE_FIRE_SCHEMA, type, id: signalIdOf(h.accountId, h.runId, h.nonce), nonce: h.nonce, issuedAt: h.now, expiresAt: h.now + ttlSec * 1000, ttlSec,
55
+ runId: h.runId, accountId: h.accountId, strategy: { id: h.strategy.id, version: h.strategy.version, hash: h.strategy.hash.slice(0, 64) }, paper: false,
56
+ };
57
+ }
58
+ /** A trade signal; throws on anything that is not a plain engine value (fail closed: no signal rather than a bad one). */
59
+ export function buildTradeSignal(t, h) {
60
+ if (!SOL_MINT_RE.test(t.mint))
61
+ throw new Error('signal: mint is not a base58 address');
62
+ if (!(t.solUsd > 0))
63
+ throw new Error('signal: no SOL/USD price');
64
+ // A buy states a positive size; a sell's size is the modelled proceeds and can be ~0 (a rug exit must still go out).
65
+ if (t.side === 'buy' ? !(t.sizeUsd > 0) : !(t.sizeUsd >= 0))
66
+ throw new Error('signal: size must be positive');
67
+ const s = {
68
+ ...base('trade', h), type: 'trade', side: t.side, mint: t.mint, symbol: sanitizeSymbol(t.symbol),
69
+ sizeSol: r6(t.sizeUsd / t.solUsd), sizeUsd: r2(t.sizeUsd), pctOfBook: t.bookUsd > 0 ? Math.round((t.sizeUsd / t.bookUsd) * 1000) / 10 : 0,
70
+ sellFraction: t.side === 'sell' ? Math.min(1, Math.max(0, r6(t.sellFraction ?? 1))) : null,
71
+ price: { usd: fin(t.priceUsd), mcap: fin(t.mcap), liqUsd: fin(t.liqUsd), solUsd: r2(t.solUsd) },
72
+ exitReason: t.side === 'sell' ? sanitizeReason(t.exitReason) : null,
73
+ slippageBps: Math.round(t.slippageBps), maxImpactPct: t.maxImpactPct, positionId: t.positionId && /^[A-Za-z0-9._-]{1,48}$/.test(t.positionId) ? t.positionId : null,
74
+ ...(t.model ? { model: { priceUsd: fin(t.model.priceUsd), tokens: fin(t.model.tokens) } } : {}),
75
+ };
76
+ const v = validateSignal(s);
77
+ if (!v.ok)
78
+ throw new Error(`signal: ${v.error}`);
79
+ return s;
80
+ }
81
+ export function buildHaltedSignal(reason, outstanding, h, open = []) {
82
+ return { ...base('halted', h), type: 'halted', reason: sanitizeReason(reason), outstanding: [...new Set(outstanding)].filter((n) => Number.isInteger(n) && n > 0).sort((a, b) => a - b).slice(0, 500), open: [...new Set(open)].filter((m) => SOL_MINT_RE.test(m)).sort().slice(0, 100) };
83
+ }
84
+ export function buildTestSignal(h) {
85
+ return { ...base('test', h), type: 'test', test: true, note: 'channel test: never trade on this' };
86
+ }
87
+ /** One line of JSON, fixed key order (the webhook body, the hook's stdin, the stream line: byte-identical). */
88
+ export const signalLine = (s) => JSON.stringify(s);
89
+ /** Strict shape check: used on replay of the outbox and by receivers. */
90
+ export function validateSignal(x) {
91
+ const s = x;
92
+ if (!s || typeof s !== 'object')
93
+ return { ok: false, error: 'not an object' };
94
+ if (s.schema !== TRADE_FIRE_SCHEMA)
95
+ return { ok: false, error: 'schema' };
96
+ if (s.type !== 'trade' && s.type !== 'halted' && s.type !== 'test')
97
+ return { ok: false, error: 'type' };
98
+ if (!Number.isSafeInteger(s.nonce) || s.nonce < 1)
99
+ return { ok: false, error: 'nonce' };
100
+ if (typeof s.id !== 'string' || !HEX32.test(s.id))
101
+ return { ok: false, error: 'id' };
102
+ if (typeof s.accountId !== 'string' || !ACCOUNT_ID_RE.test(s.accountId))
103
+ return { ok: false, error: 'accountId' };
104
+ if (typeof s.runId !== 'string' || !RUN_RE.test(s.runId))
105
+ return { ok: false, error: 'runId' };
106
+ if (s.id !== signalIdOf(s.accountId, s.runId, s.nonce))
107
+ return { ok: false, error: 'id does not match account/run/nonce' };
108
+ if (s.paper !== false)
109
+ return { ok: false, error: 'paper must be false' };
110
+ if (!fin(s.issuedAt) || !fin(s.expiresAt) || s.expiresAt <= s.issuedAt)
111
+ return { ok: false, error: 'times' };
112
+ const st = s.strategy;
113
+ if (!st || typeof st.id !== 'string' || !ID_RE.test(st.id) || typeof st.version !== 'string' || typeof st.hash !== 'string')
114
+ return { ok: false, error: 'strategy' };
115
+ if (s.type === 'trade') {
116
+ if (s.side !== 'buy' && s.side !== 'sell')
117
+ return { ok: false, error: 'side' };
118
+ if (typeof s.mint !== 'string' || !SOL_MINT_RE.test(s.mint))
119
+ return { ok: false, error: 'mint' };
120
+ if (typeof s.symbol !== 'string' || s.symbol !== sanitizeSymbol(s.symbol))
121
+ return { ok: false, error: 'symbol' };
122
+ if (s.side === 'buy' ? !(fin(s.sizeSol) > 0) || !(fin(s.sizeUsd) > 0) : !(fin(s.sizeSol) >= 0) || !(fin(s.sizeUsd) >= 0))
123
+ return { ok: false, error: 'size' };
124
+ if (s.side === 'sell' && !(fin(s.sellFraction) > 0 && s.sellFraction <= 1))
125
+ return { ok: false, error: 'sellFraction' };
126
+ }
127
+ if (s.type === 'test' && s.test !== undefined && s.test !== true)
128
+ return { ok: false, error: 'test' };
129
+ if (s.type === 'test' && 'mint' in s)
130
+ return { ok: false, error: 'a test signal names no mint' };
131
+ if (s.type === 'trade' && s.model !== undefined && (typeof s.model !== 'object' || s.model === null))
132
+ return { ok: false, error: 'model' };
133
+ if (s.type === 'halted' && s.open !== undefined && (!Array.isArray(s.open) || s.open.length > 100 || !s.open.every((m) => typeof m === 'string' && SOL_MINT_RE.test(m))))
134
+ return { ok: false, error: 'open' };
135
+ return { ok: true, signal: s };
136
+ }
137
+ // ───────────────────────────── HMAC ─────────────────────────────
138
+ /** `t=<unix s>,v1=<hex sha256 hmac of "<t>.<body>">`. */
139
+ export function signBody(secret, body, nowMs) {
140
+ const t = Math.floor(nowMs / 1000);
141
+ return `t=${t},v1=${createHmac('sha256', secret).update(`${t}.${body}`).digest('hex')}`;
142
+ }
143
+ export function verifyBody(secret, header, body, nowMs, toleranceSec = SIGNATURE_TOLERANCE_SEC) {
144
+ const m = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/.exec(String(header ?? ''));
145
+ if (!m)
146
+ return { ok: false, why: 'signature-missing' };
147
+ const t = Number(m[1]);
148
+ if (Math.abs(nowMs / 1000 - t) > toleranceSec)
149
+ return { ok: false, why: 'signature-stale' };
150
+ const want = createHmac('sha256', secret).update(`${t}.${body}`).digest();
151
+ const got = Buffer.from(m[2], 'hex');
152
+ return got.length === want.length && timingSafeEqual(got, want) ? { ok: true } : { ok: false, why: 'signature-bad' };
153
+ }
154
+ /**
155
+ * What a well-behaved executor does with an incoming signal: signature (when a secret is set), shape, account, TTL,
156
+ * replay (nonce and id). A duplicate is reported as such so a transport can ack it (at-least-once delivery).
157
+ * Exported for users' scripts and for the fake executors of the tests; dexterm itself never executes anything.
158
+ */
159
+ export class SignalReceiver {
160
+ seen = new Set();
161
+ maxNonce = 0;
162
+ o;
163
+ constructor(o) { this.o = o; }
164
+ receive(body, signature) {
165
+ const now = (this.o.now ?? Date.now)();
166
+ if (this.o.secret) {
167
+ const v = verifyBody(this.o.secret, signature, body, now);
168
+ if (!v.ok)
169
+ return { ok: false, why: v.why };
170
+ }
171
+ let raw;
172
+ try {
173
+ raw = JSON.parse(body);
174
+ }
175
+ catch {
176
+ return { ok: false, why: 'not-json' };
177
+ }
178
+ const v = validateSignal(raw);
179
+ if (!v.ok)
180
+ return { ok: false, why: `invalid:${v.error}` };
181
+ const s = v.signal;
182
+ if (s.accountId !== this.o.accountId)
183
+ return { ok: false, why: 'wrong-account', signal: s };
184
+ if (this.seen.has(s.id) || this.seen.has(`n${s.nonce}`))
185
+ return { ok: false, why: 'duplicate', signal: s };
186
+ if (now > s.expiresAt)
187
+ return { ok: false, why: 'expired', signal: s };
188
+ // A nonce at or below one already acted on (that is not a duplicate of it) is a replay of an old signal.
189
+ if (s.nonce <= this.maxNonce && s.type !== 'halted')
190
+ return { ok: false, why: 'nonce-replay', signal: s };
191
+ this.seen.add(s.id);
192
+ this.seen.add(`n${s.nonce}`);
193
+ this.maxNonce = Math.max(this.maxNonce, s.nonce);
194
+ return { ok: true, signal: s };
195
+ }
196
+ }
@@ -59,7 +59,7 @@ export const SCHEMAS = {
59
59
  kind: { type: 'string', enum: ['strategy'] },
60
60
  schema: { type: 'string', enum: [STRATEGY_SCHEMA] },
61
61
  id: str(32, ID), name: str(40), version: str(16, SEMVER), description: str(600),
62
- mode: { type: 'string', enum: ['paper', 'live'] },
62
+ mode: { type: 'string', enum: ['paper', 'real', 'live'] },
63
63
  highRisk: { type: 'boolean' },
64
64
  bankroll: obj({ startUsd: num(1, 1e7), source: { type: 'string', enum: ['fixed', 'desk'] } }, ['startUsd']),
65
65
  entry: obj({
@@ -213,6 +213,8 @@ export function validateStrategy(doc, library = builtinProfiles()) {
213
213
  warnings.push({ path: '/bankroll/source', msg: 'desk reads the paper desk book during a run; backtests use startUsd' });
214
214
  if (s.entry.safety.larp)
215
215
  warnings.push({ path: '/entry/safety/larp', msg: 'the LARP gate needs the live web (live data runs only); replays and backtests do not evaluate it' });
216
+ if (s.mode === 'real')
217
+ warnings.push({ path: '/mode', msg: 'mode real sends a LIVE TRADE FIRE signal for every trade to your own executor; it runs only after `dexterm autotrade signal arm` on your own terminal, at this exact version' });
216
218
  if (s.mode === 'live')
217
219
  warnings.push({ path: '/mode', msg: 'mode live does not run: dexterm runs strategies on paper only (it holds no key and places no live order); live trading happens in the Telegram trading bot of your choice' });
218
220
  if (errors.length)
@@ -9,7 +9,7 @@
9
9
  //
10
10
  // Where each ledger field comes from:
11
11
  // strategy run_start: strategy id, version and strategyHash
12
- // wallet mode run_start.mode (paper; a live run's executor name says devnet or mainnet)
12
+ // wallet mode run_start.mode (paper; real = a real-mode run, task-1655; a live run's executor name says devnet or mainnet)
13
13
  // profile the entry fill's profile; 'structured' when the agent's DECISION named it, else 'default'
14
14
  // (the strategy's default profile), 'rule' for a mechanical (auto) entry
15
15
  // entry reason the agent's DECISION {"action":"enter","reason":…} of the session that entered (structured)
@@ -70,7 +70,7 @@ export function importRunLedger(path, runId) {
70
70
  const start = events.find((e) => e.kind === 'run_start') ?? null;
71
71
  const strategy = start && str(start.strategy) ? { id: String(start.strategy), version: str(start.version), hash: str(start.strategyHash) } : null;
72
72
  const executor = String(start?.executor ?? '');
73
- const walletMode = start?.mode === 'live' ? (/mainnet/.test(executor) ? 'live' : 'devnet') : 'paper';
73
+ const walletMode = start?.mode === 'real' ? 'real' : start?.mode === 'live' ? (/mainnet/.test(executor) ? 'live' : 'devnet') : 'paper';
74
74
  const auto = start?.decide === 'auto';
75
75
  // task-1538: a parallel-run strategy on a shared paper account names it in its first line (and run_start).
76
76
  const memberLine = events.find((e) => e.kind === 'fleet_member') ?? null;
@@ -14,7 +14,7 @@ import path from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { ACTION_FILE_ENV, ACTION_TOKEN_ENV, ANALYST_ACTION_TYPES, parseActionLine } from '../../../data/src/index.js';
16
16
  import { basisLanguage, DEFAULT_PRICE_BASIS, fmtCap, isPriceBasis, knownSupply, NO_SUPPLY_REASON, pickBasis } from '../../../data/src/basis.js';
17
- import { firewall, userSkillPreamble, PARALLEL_CONTROL_TOOLS, STRATEGY_PROPOSE_TOOLS } from '../../../mcp/src/index.js';
17
+ import { firewall, userSkillPreamble, JOURNEY_CONTROL_TOOLS, JOURNEY_PROPOSE_TOOLS, PARALLEL_CONTROL_TOOLS, STRATEGY_PROPOSE_TOOLS } from '../../../mcp/src/index.js';
18
18
  import { skillStore } from "../kb-skill-cmd.js";
19
19
  import { applyCodexEvent, buildCodexArgv, codexAllowedTools, codexDeveloperInstructions, codexFailure, expandSkillPrompt, newCodexTurn, strictSchema } from "./codex.js";
20
20
  import { runOllamaTurn } from "./ollama.js";
@@ -37,7 +37,8 @@ export function deniedActionTools(actionTypes) {
37
37
  return [];
38
38
  // task-1507: an observe-only session (AI scan) cannot propose a strategy edit either
39
39
  // task-1529: nor start or stop a parallel strategy
40
- const propose = actionTypes.length === 0 ? [...STRATEGY_PROPOSE_TOOLS, ...PARALLEL_CONTROL_TOOLS] : [];
40
+ // task-1647: nor start / stop a forward test or propose a promotion
41
+ const propose = actionTypes.length === 0 ? [...STRATEGY_PROPOSE_TOOLS, ...PARALLEL_CONTROL_TOOLS, ...JOURNEY_CONTROL_TOOLS, ...JOURNEY_PROPOSE_TOOLS] : [];
41
42
  return [...ANALYST_ACTION_TYPES.filter((t) => !actionTypes.includes(t)), ...propose].map((t) => `mcp__dexterm__${t}`);
42
43
  }
43
44
  /**
@@ -17,7 +17,7 @@
17
17
  import fs from 'node:fs';
18
18
  import path from 'node:path';
19
19
  import { ACTION_FILE_ENV, ACTION_TOKEN_ENV, ANALYST_ACTION_TYPES } from '../../../data/src/index.js';
20
- import { READ_ONLY_TOOLS, STRATEGY_PROPOSE_TOOLS } from '../../../mcp/src/index.js';
20
+ import { JOURNEY_PROPOSE_TOOLS, READ_ONLY_TOOLS, STRATEGY_PROPOSE_TOOLS } from '../../../mcp/src/index.js';
21
21
  import { skillStore } from "../kb-skill-cmd.js";
22
22
  /** The analyst engines dexterm can drive: the user's own claude or codex CLI, or (task-1543) a local model on their Ollama. */
23
23
  export const ANALYST_ENGINES = ['claude', 'codex', 'ollama'];
@@ -75,7 +75,8 @@ export function codexAllowedTools(actionTypes) {
75
75
  const reads = READ_ONLY_TOOLS.filter((n) => !/^paper_/.test(n) && !ANALYST_ACTION_TYPES.includes(n));
76
76
  const actions = ANALYST_ACTION_TYPES.filter((t) => !actionTypes || actionTypes.includes(t));
77
77
  // task-1507: strategy PROPOSALS (never applied by a tool) for a chat turn; an observe-only scan gets none
78
- const propose = actionTypes && actionTypes.length === 0 ? [] : STRATEGY_PROPOSE_TOOLS;
78
+ // task-1647: promotion PROPOSALS too (a file the user applies); forward-test control stays off codex, like parallel control
79
+ const propose = actionTypes && actionTypes.length === 0 ? [] : [...STRATEGY_PROPOSE_TOOLS, ...JOURNEY_PROPOSE_TOOLS];
79
80
  return [...reads, ...actions, ...propose];
80
81
  }
81
82
  const tomlString = (s) => JSON.stringify(s); // a JSON string is a valid TOML basic string
@@ -232,7 +232,7 @@ const TOPICS = [
232
232
  body: '`dexterm autotrade run <id|file> --paper` runs one strategy on paper, headless, one runner per machine: the screener feeds it the same live data as the app (every 10 s, candidate and held coins every 5 s), and each coin that matches gets one session on your own Claude login with the full picture first, then only what changed. Your agent answers with a typed decision (enter, wait, skip, hold, exit, tighten, reprofile); every size is clamped by your strategy and the exits run on their own. At most 2 sessions at once, $0.50 per session and the day caps in ~/.dexterm/autotrade/runner.json (which Claude account, sessions and spend per day, a usage guard). Every step goes to ~/.dexterm/autotrade/runs/<run>.jsonl, hash-chained. `--replay FILE` paces a recorded tape instead of live data; `--stub` uses a scripted agent with no Claude cost. Paper only: a run never signs or touches a wallet, and there is no `--live` (dexterm holds no key and places no live order). Not financial advice. Full docs: https://dexterm.xyz/docs/autotrade/#the-runner-and-candidate-sessions' },
233
233
  { id: 'live-trading', title: 'Live trading: dexterm holds no key; a Telegram trading bot of your choice trades', screen: 'all', tags: ['live', 'trading', 'real', 'money', 'telegram', 'bot', 'key', 'wallet', 'custody', 'signer', 'mainnet'],
234
234
  commands: ['telegram', 'wallet', 'live'], feature: 'live-trading',
235
- body: 'dexterm never holds a key and never signs or sends a transaction: there is no trading wallet, no signer and no live order in dexterm. Live trading happens in a Telegram trading bot of your choice, which holds its own wallet; you act in that bot. dexterm\'s part is the Telegram connector to your OWN bot (`dexterm telegram setup`): alerts, signals and run control for your paper runs. dexterm 0.1.7 does not place orders in a trading bot for you. Paper trading (the ticket, paper accounts, paper autotrade) is local. `dexterm wallet link` keeps a Phantom public key for display only. Not financial advice. Full docs: https://dexterm.xyz/docs/live-trading/' },
235
+ body: 'dexterm never holds a key and never signs or sends a transaction: there is no trading wallet, no signer and no live order in dexterm. Live trading happens in a Telegram trading bot of your choice, which holds its own wallet; you act in that bot. dexterm\'s part is the Telegram connector to your OWN bot (`dexterm telegram setup`): alerts, signals and run control for your paper runs. dexterm does not place orders in a trading bot for you: in real mode (0.2.0, experimental) a strategy you armed on your own terminal sends a signal for each trade to an executor you run, and your executor places the order by its own rules (`dexterm autotrade signal`, https://dexterm.xyz/docs/real-mode/). Paper trading (the ticket, paper accounts, paper autotrade) is local. `dexterm wallet link` keeps a Phantom public key for display only. Not financial advice. Full docs: https://dexterm.xyz/docs/live-trading/' },
236
236
  { id: 'live-yolo', title: 'The full-port yolo strategy on paper: replay and a paper run (HIGH RISK)', screen: 'all', tags: ['yolo', 'full', 'port', 'all-in', 'high', 'risk', 'preset', 'replay', 'paper'],
237
237
  commands: ['autotrade'], feature: 'yolo-preset',
238
238
  body: 'HIGH RISK, PAPER only; not financial advice. The `yolo` preset enters one young pair at a time on an early 5-minute push after the holder-safety gates (LP burned or locked, no mint or freeze authority, a LARP score of 49 or less checked live before a coin becomes a candidate, liquidity of $25K or more), takes the cost back at about 2x, lets the rest ride on a loose 50% trail, exits at once on a liquidity pull, a dev sell or dead volume, has a -50% stop and a 45-minute time stop, and never buys the same coin twice. On paper it caps an entry at 25% like every strategy. `dexterm autotrade yolo-replay yolo` measures every entry at full port over your recorded history (rugs, the loss spread, how often it zeroed the wallet); `dexterm autotrade run yolo --paper` runs it on paper (`--replay builtin:yolo-rehearsal --stub` for a short fixture run; next to other strategies, or on a shared paper account, through `autotrade.json` and `dexterm autotrade run --all --paper`). Stop: `dexterm autotrade stop`, /kill in Telegram, Ctrl-C. dexterm places no live order. Full docs: https://dexterm.xyz/docs/yolo/' },
@@ -245,13 +245,25 @@ const TOPICS = [
245
245
  { id: 'autotrade-telegram', title: 'Your own Telegram bot for the autotrade runner: notify, control, one-tap approvals (dexterm telegram)', screen: 'all', tags: ['telegram', 'bot', 'phone', 'mobile', 'notify', 'notifications', 'approve', 'approval', 'approvals', 'pair', 'pairing', 'kill', 'pause', 'remote', 'botfather'],
246
246
  commands: ['telegram'], feature: 'autotrade-telegram',
247
247
  body: 'Create a bot with @BotFather, then run `dexterm telegram setup`: paste the token at the hidden prompt (never as an argument), dexterm checks it and keeps it in your keychain (or the system keyring, or a 0600 file), then shows a 6-digit code; send `/pair <code>` to your bot from your own private chat and confirm the account it shows (@username and id) with `y` on your computer. Pairing is refused while a webhook or another program polls the bot. Only that account in that chat is answered. `dexterm autotrade run <id> --paper` then starts the bot by itself (`--no-telegram` keeps it off): entries, exits, PnL cards, halts and a daily summary reach your phone; `/status`, `/positions`, `/pause`, `/resume` (a pause only), `/kill`, `/flatten` and `/use` (each after a confirm button, `/use` only to an equal-or-tighter strategy; a change it cannot rank counts as looser) and `/approvals on` work from chat, which can make things safer and never less safe. With `entry.decide: "agent+approve"` or approvals on, every entry is a card with [Approve] [Half size] [Skip]: only a button approves, once, for that proposal, your account and your private chat; the price and your limits are checked again at the tap; no answer is a skip. Typed messages are never trades. `dexterm telegram status|test|audit --verify|revoke`. Nothing is hosted; paper only; never send keys or seed phrases in chat. Not financial advice. Full docs: https://dexterm.xyz/docs/telegram/' },
248
+ { id: 'autotrade-real-signal', title: 'Real mode: send a strategy\'s trades to your own executor as LIVE TRADE FIRE signals (dexterm autotrade signal)', screen: 'all', tags: ['real', 'mode', 'live', 'trade', 'fire', 'signal', 'signals', 'executor', 'webhook', 'hook', 'jsonl', 'receipt', 'receipts', 'arm', 'caps', 'kill', 'outbox', 'nonce'],
249
+ commands: ['autotrade'], tools: ['trade_fire_feed'], feature: 'autotrade-real-signal',
250
+ body: 'Real mode runs a strategy exactly like paper (the same clamp, exits, monitor and run file) and sends every buy and sell it fills, first, as a LIVE TRADE FIRE signal (`dexterm-trade-fire/1`: buy or sell, mint, symbol, size in SOL and % of book, the sell fraction and exit reason, strategy, run, account, an always-growing nonce, an idempotency id and an expiry) to YOUR executor: a Telegram trading bot of your choice or any script. dexterm holds no key and signs nothing. Set channels with `dexterm autotrade signal channels --webhook URL | --signal-cmd \'["/abs/path"]\' | --jsonl on | --mcp on | --telegram on` (they live in connectors.json next to the Telegram setup; a bot cannot read another bot, so the Telegram copy alone is not enough), a webhook HMAC secret with `signal secret generate --out FILE`, hard caps with `signal caps set` (raising needs a typed confirmation), then arm on your own terminal with `dexterm autotrade signal arm <id>` (evidence panel + a typed phrase with a one-time code; any later edit disarms; below the evidence floor, a completed forward test with your `minForwardTrades` closed paper trades and a backtest of these exact rules, or past a missing rung of the ladder, it refuses unless you first type a separate OVERRIDE phrase, which is journaled) and run `dexterm autotrade run <id> --real` (live data only, in the foreground: in 0.2.0 the always-on service runs paper strategies only). Delivery is at least once from a restart-safe outbox, in nonce order, retried until acked or expired; the executor dedupes by nonce, ignores expired signals and acts only on its own account. Every run ends with a `halted` signal that lists the positions still open; the run\'s last lines and the Telegram copy name them too. Open positions are carried to the next real run of the same strategy and account, whose exits keep firing; while no real run is running NO signal goes out, sells included, so manage them in your executor. Positions stay unconfirmed until `dexterm autotrade receipt <nonce> executed|rejected|failed` (data only). `signal kill` stops every signal; `signal status`, `signal tail`, `receipt list` and `autotrade audit` show the outbox, receipts and drift; agents can read the MCP feed with trade_fire_feed. No model, tool or chat tap can arm real mode, raise a cap or lift the kill switch. Experimental; not financial advice.' },
251
+ { id: 'autotrade-limits', title: 'Set your own real-mode limits: per trade, per day, open positions, loss stops, the breaker (dexterm autotrade limits)', screen: 'all', tags: ['limits', 'limit', 'caps', 'cap', 'size', 'sizing', 'per', 'trade', 'daily', 'loss', 'drawdown', 'breaker', 'streak', 'exposure', 'slippage', 'ttl', 'rate', 'raise', 'lower', 'scope'],
252
+ commands: ['autotrade'], tools: ['trading_limits', 'limits_propose'], feature: 'autotrade-limits',
253
+ body: 'Every limit real mode enforces is yours to set, in one file (`~/.dexterm/autotrade/real/limits.json`, schema `dexterm-limits/1`): per trade as SOL or as % of the book (the smaller wins), SOL and buys per day, open positions, exposure, min and max position, per coin per day, a daily loss stop, a drawdown breaker, a loss-streak pause, max hold time, the evidence floor for arming (`minForwardTrades`: closed paper trades in a completed forward test, placeholder 10), min liquidity and market cap, max slippage and price impact, the signal TTL, a buy rate limit, an optional sell rate (sells are never capped unless you set one) and how long a silent executor may stay silent. `dexterm autotrade limits show [--strategy ID] [--account ID]` lists what is in force and where each number comes from; `limits set perTradeSol=0.5 dailyLossSol=0.3` (or `--scope real|paper|strategy:ID|account:ID`) changes them: a global number replaces the placeholder default, every other scope can only tighten, and the stricter always wins. Paper runs ignore them unless you add a `paper` scope; then a single paper run (not `run --all`) obeys them on its own state (a replay then needs `--sol-usd N`). Daily counters cover the whole home (every strategy and account), so a strategy or account number can only stop buys sooner. Lowering is immediate, even for a running real run; raising shows the old -> new diff and needs the typed phrase on your own terminal, and applies from the next run. `limits diff`, `limits accept` (a hand-edited file), `limits reset`, `limits breaker reset` (typed) and `limits explain` do the rest. The defaults (0.25 SOL a trade, 1 SOL a day, 20 buys, 3 open, stop at -0.5 SOL a day) are placeholders: arming asks for your own numbers first. The analyst can read and explain them (`trading_limits`) and propose a change as a diff card (`limits_propose`); it can never apply one.' },
254
+ { id: 'autotrade-executor-kit', title: 'Wire up a test executor, check it is alive, and get the digest (dexterm autotrade executor, signal test, report)', screen: 'all', tags: ['executor', 'kit', 'example', 'heartbeat', 'alive', 'silent', 'health', 'test', 'webhook', 'receiver', 'dry', 'run', 'digest', 'report', 'daily', 'weekly', 'divergence', 'slippage', 'latency'],
255
+ commands: ['autotrade'], feature: 'autotrade-executor-kit',
256
+ body: '`dexterm autotrade executor kit --out ~/my-executor` copies the reference executors: a webhook receiver, a `--signal-cmd` hook and a JSONL tail. Each verifies the HMAC, dedupes by nonce, honours the TTL, writes a receipt and a heartbeat, and is DRY RUN: it only logs what it would do, with no wallet code in it. Start one, point a channel at it (`dexterm autotrade signal channels --webhook http://127.0.0.1:8787/signal`), then `dexterm autotrade signal test` sends a test signal (`test: true`, no coin, nothing to trade) and shows, per channel, whether it was delivered, how long it took and the executor\'s receipt. `dexterm autotrade executor status` shows the last heartbeat, the last receipt and the lag; a real run pauses new buy signals (exits still go out) when nothing is heard for longer than your `executorSilenceMin` limit, and tells you. With receipts that carry fills, `signal status`, `autotrade audit` and `dexterm autotrade report` show paper vs real: slippage against dexterm\'s own paper fill, latency, partial fills and rejections. `report [--period day|week] [--telegram]` is the digest per strategy and mode with the win rate\'s interval and a small-sample note; `report --schedule daily|weekly` makes a run with your bot on send it.' },
248
257
  { id: 'autotrade-chat', title: 'Change an autotrade strategy by chat (paper)', screen: 'autotrade', tags: ['autotrade', 'strategy', 'chat', 'analyst', 'proposal', 'tune', 'change', 'diff', 'looser', 'less', 'safe'],
249
258
  actions: [{ action: 'analyst.toggle' }, { action: 'autotrade.proposal', screen: 'autotrade' }],
250
259
  tools: ['strategy_list', 'strategy_get', 'strategy_validate', 'strategy_propose_edit', 'strategy_propose_new', 'strategy_backtest', 'autotrade_status'], feature: 'autotrade-chat',
251
260
  body: 'Ask the analyst to change one of your strategies ("make my swing exit faster"). It can only PROPOSE: the change arrives as a card on the AUTOTRADE screen (`Q`) with the field lines that change, the validation result and TIGHTER, NEUTRAL or LOOSER. `o` opens the card, `y` applies it as a new version (journaled with who proposed it), `n` dismisses it. When any risk number gets less safe (bigger size or exposure, more loss, a stop or safety gate removed) the edit is LOOSER and needs a second `y` on the less-safe popup. The mode, the book, the daily session budget and the exit-liquidity floor are yours only: the analyst cannot change them. It can backtest a proposal next to the current version on your recorded history (up to 14 days, read-only). Paper only.' },
261
+ { id: 'autotrade-journey', title: 'Build a strategy by chat, back-test it, forward-test it, then promote it (paper, then real)', screen: 'all', tags: ['autotrade', 'strategy', 'build', 'chat', 'journey', 'ladder', 'backtest', 'held-out', 'forward', 'test', 'promote', 'promotion', 'always-on', 'real', 'evidence'],
262
+ commands: ['autotrade'], tools: ['strategy_journey', 'strategy_forward_start', 'strategy_forward_stop', 'strategy_forward_report', 'strategy_promote_propose'], feature: 'autotrade-journey',
263
+ body: 'A strategy climbs one ladder, one rung at a time: draft → backtested → forward-tested → always-on (paper) → real. Each rung needs evidence measured on that strategy\'s exact rules; any rule change starts it again (a rename or arming keeps it). Ask the analyst to build one ("build me a strategy that buys young pairs on a 5-minute push and takes profit at 2x"): it proposes a copy of a preset with changes (strategy_propose_new), you apply it on the Q screen. BACKTESTED: `dexterm autotrade backtest <id>` or strategy_backtest runs it on recorded history and on each half of the held-out split (the newest 30% of coins); verdict rule 6 allows gain wording only with at least 20 trades in both halves and a held-out net above 0. FORWARD-TESTED: `dexterm autotrade forward start <id> --hours 24` (or `--trades N`, or strategy_forward_start from the chat) runs the same version on the LIVE tape, on paper, with its own bankroll and run file, in the background next to the always-on service; `forward status`, `forward stop` and `forward report` (the forward numbers next to the backtest: trades, win rate with its interval, net, drawdown, rug rate, fill cost drift, and a plain line when a sample is too small). Only a test that ran its whole window on live data counts. ALWAYS-ON: the analyst can propose it (strategy_promote_propose), you apply it with `dexterm autotrade promote apply <pp-id>` (y on your own terminal) or on the Q screen journey view (`J`, then `y`); it joins autotrade.json and the always-on service runs it on paper. REAL: you set your own limits (`dexterm autotrade limits set`; `signal caps set` sets four of them), then `dexterm autotrade promote <id> --to real` hands over to `signal arm` (evidence panel, typed phrase with a one-time code). No tool or model can apply a promotion, skip a rung, set a cap, pick a bankroll or arm real mode. `dexterm autotrade journey <id>` shows where a strategy stands. Paper by default; not financial advice.' },
252
264
  { id: 'trade-ledger', title: 'See every trade in one ledger: win rate, profiles, exit reasons, strategy versions (dexterm ledger)', screen: 'all', tags: ['ledger', 'journal', 'trades', 'history', 'results', 'stats', 'win', 'rate', 'drawdown', 'profile', 'exit', 'reason', 'compare', 'export', 'csv', 'equity', 'mfe', 'mae'],
253
265
  commands: ['ledger'], tools: ['ledger_trades', 'ledger_positions', 'ledger_summary', 'ledger_equity', 'ledger_compare', 'candidate_dossier', 'outcomes_lookup', 'trading_status', 'telegram_status', 'backtest_requests'], feature: 'trade-ledger',
254
- body: '`dexterm ledger trades` lists every round trip dexterm booked, from the paper ticket, the agent paper desk and autotrade runs, newest first: strategy version, the exit profile and entry reason it was opened with (marked * when not declared with the fill), the exit reason, size and % of book, entry and exit market cap, P/L, hold and MFE/MAE. `positions` shows the open ones. `summary` gives the win rate with its 95% interval, P/L, profit factor, drawdown and rug rate by profile, exit reason, strategy, source and mode; `equity` the realized equity curve; `compare` strategy versions side by side (for strategies run in parallel); `export csv|json|parquet-lite [--out FILE]`; `card <tradeId>` a PnL card from a row. Filters: --source, --mode paper|devnet|live, --strategy id[@version], --profile, --exit, --mint, --run, --days, --status. Reads never write; `dexterm ledger sync` appends to ~/.dexterm/ledger/trades.jsonl (sha256-chained) and `dexterm ledger verify` names the first edited line. Agents read the same rows with the read-only ledger_* tools; `trading_status` and `telegram_status` show settings and state, never a key, address, exact balance, bot token or chat id. A backtest an agent asks for (backtest_request) only runs when you run it: `dexterm autotrade requests`. PAPER rows are simulated; filter by --mode before comparing. Not financial advice. Full docs: https://dexterm.xyz/docs/paper-trading/#the-trade-ledger' },
266
+ body: '`dexterm ledger trades` lists every round trip dexterm booked, from the paper ticket, the agent paper desk and autotrade runs, newest first: strategy version, the exit profile and entry reason it was opened with (marked * when not declared with the fill), the exit reason, size and % of book, entry and exit market cap, P/L, hold and MFE/MAE. `positions` shows the open ones. `summary` gives the win rate with its 95% interval, P/L, profit factor, drawdown and rug rate by profile, exit reason, strategy, source and mode; `equity` the realized equity curve; `compare` strategy versions side by side (for strategies run in parallel); `export csv|json|parquet-lite [--out FILE]`; `card <tradeId>` a PnL card from a row. Filters: --source, --mode paper|devnet|live|real (real = a real-mode run: dexterm\'s model of the trades it signalled), --strategy id[@version], --profile, --exit, --mint, --run, --days, --status. Reads never write; `dexterm ledger sync` appends to ~/.dexterm/ledger/trades.jsonl (sha256-chained) and `dexterm ledger verify` names the first edited line. Agents read the same rows with the read-only ledger_* tools; `trading_status` and `telegram_status` show settings and state, never a key, address, exact balance, bot token or chat id. A backtest an agent asks for (backtest_request) only runs when you run it: `dexterm autotrade requests`. PAPER rows are simulated; filter by --mode before comparing. Not financial advice. Full docs: https://dexterm.xyz/docs/paper-trading/#the-trade-ledger' },
255
267
  { id: 'coin-images', title: 'Turn coin images on or off', screen: 'all', tags: ['images', 'image', 'pictures', 'icons', 'logos', 'off'],
256
268
  flags: ['--no-images'], feature: 'coin-images',
257
269
  body: 'Coin pictures render as real pixels in image-capable terminals (kitty/iTerm2/sixel) and as block art everywhere else. Turn them off with `--no-images` (or `DEXTERM_IMAGES=0`, or `enabled:false` in `~/.dexterm/images.json`). `dexterm doctor` has a Coin images line that says which path you get.' },
@@ -4,7 +4,8 @@
4
4
  // hash covers the previous hash and its own content) and checks it against the run's summary, so an edited, added,
5
5
  // dropped, reordered or cut-off line is named with its event number. Exit 1 when any checked run is broken.
6
6
  import { dextermHome } from '../../../custom/src/index.js';
7
- import { auditRun, listRunIds } from '../../../autotrade/src/index.js';
7
+ import { existsSync } from 'node:fs';
8
+ import { Outbox, allOutboxSignals, auditRun, divergenceLines, divergenceReport, driftReport, listRunIds, outboxPath, readReceipts } from '../../../autotrade/src/index.js';
8
9
  import { parseArgs } from "./strategies.js";
9
10
  export const AUDIT_USAGE = 'dexterm autotrade audit [<run-id>|--last] [--verify] [--json]';
10
11
  function line(a, verify) {
@@ -38,8 +39,19 @@ export async function auditCmd(argv, io) {
38
39
  const verify = !!opts.verify;
39
40
  const audits = ids.map((id) => auditRun(home, id));
40
41
  const broken = verify ? audits.filter((a) => !a.ok) : [];
42
+ // task-1645: real mode: the drift between the trade-fire signals and the executor's receipts.
43
+ let real = null;
44
+ // task-1654: paper vs real: each receipted fill against dexterm's own paper fill (every outbox file, archives too).
45
+ let divergence = null;
46
+ if (existsSync(outboxPath(home))) {
47
+ const receipts = readReceipts(home).receipts;
48
+ const { rows: _rows, ...rest } = driftReport(Outbox.open(home, { channels: [], noLock: true }).signals(), receipts, Date.now());
49
+ real = rest;
50
+ const { rows: _r2, ...dv } = divergenceReport(allOutboxSignals(home), receipts);
51
+ divergence = dv;
52
+ }
41
53
  if (opts.json) {
42
- io.stdout.write(`${JSON.stringify({ verified: verify, runs: audits, broken: broken.length }, null, 2)}\n`);
54
+ io.stdout.write(`${JSON.stringify({ verified: verify, runs: audits, broken: broken.length, ...(real ? { realSignals: real } : {}), ...(divergence ? { paperVsReal: divergence } : {}) }, null, 2)}\n`);
43
55
  return broken.length ? 1 : 0;
44
56
  }
45
57
  if (!audits.length) {
@@ -53,5 +65,10 @@ export async function auditCmd(argv, io) {
53
65
  io.stdout.write(broken.length ? `${broken.length} broken ledger${broken.length === 1 ? '' : 's'}: the lines from that event on cannot be trusted\n` : 'every chain verifies\n');
54
66
  else
55
67
  io.stdout.write('add --verify to recompute the hash chains\n');
68
+ if (real)
69
+ io.stdout.write(`real-mode signals vs receipts · executed ${real.counts.executed} · rejected ${real.counts.rejected} · failed ${real.counts.failed} · unconfirmed ${real.unconfirmed}${real.sizeDrift ? ` · size drift on ${real.sizeDrift}` : ''}${real.orphanReceipts ? ` · ${real.orphanReceipts} orphan receipt(s)` : ''} (dexterm autotrade receipt list)\n`);
70
+ if (divergence?.receipted)
71
+ for (const l of divergenceLines(divergence))
72
+ io.stdout.write(`${l}\n`);
56
73
  return broken.length ? 1 : 0;
57
74
  }
@@ -1,11 +1,12 @@
1
1
  // `dexterm autotrade backtest|sweep|extract` (task-1503 AT-1, AUTOTRADE-SPEC §3/§3a). PAPER, recorded data only:
2
2
  // the recorder DB is opened read-only, fills are modelled, no network, no model, no keys. Mechanical entries
3
3
  // (`auto`): the agent's judgement is what the runner card measures, so a backtest never spawns a session.
4
+ import { dextermHome } from '../../../custom/src/index.js';
4
5
  import { defaultDbPath } from '../../../data/src/index.js';
5
6
  import { openHistoryReadOnly } from '../../../recorder/src/index.js';
6
- import { backtest, everyCandidate, fmtIssue, loadTape, renderRecall, renderReport, renderSweep, renderYoloReplay, builtinTapePath, runnerRecall, saveTape, sweep, tapeFromDb, tapeFromDoc, yoloReplay, } from '../../../autotrade/src/index.js';
7
+ import { backtest, backtestEvidence, everyCandidate, recordBacktestEvidence, renderHeldOut, fmtIssue, loadTape, renderRecall, renderReport, renderSweep, renderYoloReplay, builtinTapePath, runnerRecall, saveTape, sweep, tapeFromDb, tapeFromDoc, yoloReplay, } from '../../../autotrade/src/index.js';
7
8
  import { parseArgs, resolveStrategyArg, storeFor } from "./strategies.js";
8
- const BOOL = ['json', 'every-candidate'];
9
+ const BOOL = ['json', 'every-candidate', 'no-held-out'];
9
10
  function strategyFrom(pos, opts, io, usage, anyMode = false) {
10
11
  const arg = typeof opts.strategy === 'string' ? opts.strategy : pos[0];
11
12
  const r = resolveStrategyArg(arg, io);
@@ -99,7 +100,8 @@ export function tapeFrom(opts, io) {
99
100
  }
100
101
  export async function backtestCmd(argv, io) {
101
102
  const { pos, opts } = parseArgs(argv, BOOL);
102
- const usage = 'dexterm autotrade backtest <id|file> [--tape FILE | --db PATH] [--days N | --since T] [--until T] [--every-candidate [--unit-usd 20]] [--recall 5,10] [--json]';
103
+ const usage = 'dexterm autotrade backtest <id|file> [--tape FILE | --db PATH] [--days N | --since T] [--until T] [--every-candidate [--unit-usd 20]] [--recall 5,10] [--no-held-out] [--json]';
104
+ const arg = typeof opts.strategy === 'string' ? opts.strategy : pos[0];
103
105
  const s0 = strategyFrom(pos, opts, io, usage);
104
106
  if (!s0)
105
107
  return 2;
@@ -116,11 +118,26 @@ export async function backtestCmd(argv, io) {
116
118
  }
117
119
  catch { /* the line is a convenience for `list`; never fail a backtest on it */ }
118
120
  }
121
+ // task-1647: a stored strategy's backtest is journey evidence: the same rules on each half of the held-out split.
122
+ let evidence = null;
123
+ const stored = !!arg && !opts['every-candidate'] && !opts['no-held-out'] && storeFor(io).get(arg)?.ok === true && arg === s.id;
124
+ if (stored) {
125
+ const days = numOpt(opts, 'days', 0);
126
+ evidence = (await backtestEvidence(s, tape, { by: 'user', days: days > 0 ? days : null, full: { report, run } })).evidence;
127
+ try {
128
+ recordBacktestEvidence(dextermHome(io.env), evidence);
129
+ }
130
+ catch (e) {
131
+ io.stderr.write(`warning: the journey record was not written (${e.message})\n`);
132
+ }
133
+ }
119
134
  if (opts.json) {
120
- io.stdout.write(JSON.stringify(recall ? { ...report, recall } : report, null, 2) + '\n');
135
+ io.stdout.write(JSON.stringify({ ...report, ...(recall ? { recall } : {}), ...(evidence ? { heldOut: evidence.heldOut, evidence: { verdict: evidence.verdict, claim: evidence.claim, rulesHash: evidence.rulesHash } } : {}) }, null, 2) + '\n');
121
136
  return 0;
122
137
  }
123
138
  io.stdout.write(renderReport(report) + '\n');
139
+ if (evidence)
140
+ io.stdout.write(renderHeldOut(evidence).join('\n') + `\n journey: recorded as the backtest of ${s.id} v${s.version} (dexterm autotrade journey ${s.id})\n`);
124
141
  if (opts['every-candidate'])
125
142
  io.stdout.write(` every-candidate copy of ${s0.id}: each candidate entered at $${numOpt(opts, 'unit-usd', 20)} with the book caps lifted (an evaluation, not a strategy to run)\n`);
126
143
  if (recall)
@@ -0,0 +1,91 @@
1
+ // `dexterm autotrade executor …` (task-1654, 0.2.0 card E): is YOUR executor alive?
2
+ //
3
+ // status the last heartbeat, the last receipt, the receipt lag, and whether a real run would pause new buys now
4
+ // heartbeat append one heartbeat (for executors that prefer to shell out; the kit appends or POSTs its own)
5
+ // kit copy the executor reference kit (webhook / signal-cmd / JSONL tail, all dry run) to a folder of yours
6
+ //
7
+ // A heartbeat is data: it can only keep new buy signals from pausing. It cannot raise a limit, lift the kill switch,
8
+ // reset the breaker or confirm a position (receipts do that, and only as data).
9
+ import { copyFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';
10
+ import { join, resolve } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { dextermHome } from '../../../custom/src/index.js';
13
+ import { Outbox, appendHeartbeat, effectiveLimits, executorHealth, healthLine, heartbeatPath, loadLimits, readReceipts, ACCOUNT_ID_RE } from '../../../autotrade/src/index.js';
14
+ import { parseArgs } from "./strategies.js";
15
+ /** The kit inside the app (shipped in the npm package too: build-dist copies examples/). */
16
+ export const KIT_DIR = fileURLToPath(new URL('../../../autotrade/examples/executor/', import.meta.url));
17
+ const out = (io, s) => { io.stdout.write(`${s}\n`); };
18
+ const err = (io, s) => { io.stderr.write(`dexterm autotrade executor: ${s}\n`); };
19
+ export async function executorCmd(argv, io, deps = {}) {
20
+ const home = dextermHome(io.env);
21
+ const now = deps.now ?? Date.now;
22
+ const { pos, opts } = parseArgs(argv.slice(1), ['json', 'dry-run']);
23
+ switch (argv[0]) {
24
+ case undefined:
25
+ case 'help':
26
+ out(io, 'dexterm autotrade executor status [--json] | heartbeat [--name N] [--account ID] [--dry-run] [--nonce N] [--note TEXT] | kit --out DIR');
27
+ return 0;
28
+ case 'kit': {
29
+ if (typeof opts.out !== 'string') {
30
+ err(io, 'kit --out DIR (a new or empty folder)');
31
+ return 2;
32
+ }
33
+ const dir = resolve(opts.out);
34
+ if (existsSync(dir) && readdirSync(dir).length) {
35
+ err(io, `${dir} is not empty`);
36
+ return 1;
37
+ }
38
+ mkdirSync(dir, { recursive: true });
39
+ const files = readdirSync(KIT_DIR).filter((f) => /\.(mjs|md)$/.test(f));
40
+ for (const f of files)
41
+ copyFileSync(join(KIT_DIR, f), join(dir, f));
42
+ out(io, `executor reference kit (DRY RUN: it logs what it would do; no wallet code) copied to ${dir}: ${files.join(', ')}`);
43
+ out(io, ` start one: node ${join(dir, 'webhook-executor.mjs')} --account main`);
44
+ out(io, ' wire it: dexterm autotrade signal channels --webhook http://127.0.0.1:8787/signal');
45
+ out(io, ' prove it: dexterm autotrade signal test (then dexterm autotrade executor status)');
46
+ return 0;
47
+ }
48
+ case 'status': {
49
+ const l = loadLimits(home);
50
+ const e = effectiveLimits(l.ok ? l.doc : null, { strategyId: '-', accountId: '-', mode: 'real' });
51
+ const ob = Outbox.open(home, { channels: [], noLock: true });
52
+ const h = executorHealth(home, { now: now(), windowMin: e.values.executorSilenceMin ?? null, signal: (n) => ob.get(n), receipts: readReceipts(home).receipts });
53
+ if (opts.json) {
54
+ out(io, JSON.stringify(h, null, 2));
55
+ return 0;
56
+ }
57
+ out(io, `executor ${healthLine(h)}`);
58
+ out(io, ` heartbeats: ${heartbeatPath(home)} (append, POST to the run's listener, or dexterm autotrade executor heartbeat)`);
59
+ if (h.alive === false)
60
+ out(io, ' a real run would PAUSE new buy signals now (exits still go out); start your executor, then dexterm autotrade signal test');
61
+ return 0;
62
+ }
63
+ case 'heartbeat': {
64
+ if (pos.length) {
65
+ err(io, `unexpected ${pos.join(' ')}`);
66
+ return 2;
67
+ }
68
+ const accountId = typeof opts.account === 'string' ? opts.account : null;
69
+ if (accountId && !ACCOUNT_ID_RE.test(accountId)) {
70
+ err(io, '--account: lowercase letters, digits, - and _');
71
+ return 2;
72
+ }
73
+ const nonce = opts.nonce === undefined ? null : Number(opts.nonce);
74
+ try {
75
+ const hb = appendHeartbeat(home, { at: now(), executor: typeof opts.name === 'string' ? opts.name : 'cli', accountId, dryRun: opts['dry-run'] === true ? true : null, lastNonce: nonce, note: typeof opts.note === 'string' ? opts.note : null });
76
+ if (opts.json)
77
+ out(io, JSON.stringify(hb));
78
+ else
79
+ out(io, `heartbeat from ${hb.executor} recorded`);
80
+ return 0;
81
+ }
82
+ catch (e) {
83
+ err(io, e.message);
84
+ return 2;
85
+ }
86
+ }
87
+ default:
88
+ err(io, `unknown subcommand ${JSON.stringify(argv[0])}`);
89
+ return 2;
90
+ }
91
+ }
@@ -161,7 +161,7 @@ export async function fleetRunCmd(argv, io, over = {}) {
161
161
  continue;
162
162
  }
163
163
  if (r.strategy.mode !== 'paper') {
164
- problems.push(`${m.id}: ${r.strategy.id} is mode "${r.strategy.mode}"; the runner refuses anything but paper`);
164
+ problems.push(`${m.id}: ${r.strategy.id} is mode "${r.strategy.mode}"; the runner refuses anything but paper${r.strategy.mode === 'real' ? ` in a parallel run (real mode runs one strategy on its own: dexterm autotrade run ${r.strategy.id} --real)` : ''}`);
165
165
  continue;
166
166
  }
167
167
  const acct = m.account ? accountOf.get(m.account) : undefined;
@@ -174,7 +174,8 @@ export async function fleetRunCmd(argv, io, over = {}) {
174
174
  }
175
175
  const { strategy, basedOn } = memberStrategy(r.strategy, m, b.usd);
176
176
  const sol = acct ? (acct.sol !== undefined ? { sol: acct.sol, solUsd: acct.solUsd } : {}) : m.bankroll && 'sol' in m.bankroll ? { sol: m.bankroll.sol, solUsd: solUsd } : {};
177
- members.push({ config: m, strategy, basedOn, bankroll: { usd: strategy.bankroll.startUsd, ...sol } });
177
+ const adopt = over.adopt?.(m.id);
178
+ members.push({ config: m, strategy, basedOn, bankroll: { usd: strategy.bankroll.startUsd, ...sol }, ...(adopt?.length ? { adopt } : {}) });
178
179
  }
179
180
  if (problems.length) {
180
181
  io.stderr.write(`dexterm autotrade run --all: nothing started:\n${problems.map((p) => ` ${p}`).join('\n')}\n`);
@@ -199,6 +200,7 @@ export async function fleetRunCmd(argv, io, over = {}) {
199
200
  clearMemberControls(home, fleetId);
200
201
  const { ledger: fleetLedger, files: fleetFiles } = fileLedger(home, fleetId);
201
202
  const startedAt = Date.now();
203
+ over.onStarted?.(fleetId, fleetLedger);
202
204
  const guard = new FleetGuard(fleetCfg.global, runnerCfg, { loadavg: over.loadavg });
203
205
  const rawPath = opts.raw ? join(home, 'autotrade', 'runs', `${fleetId}.stream.jsonl`) : null;
204
206
  const sessions = over.sessions ?? (opts.stub
@@ -300,11 +302,13 @@ export async function fleetRunCmd(argv, io, over = {}) {
300
302
  const res = await runFleet({
301
303
  fleetId, home, members, tape, source, runner: runnerCfg, guard, fleetLedger, fleetLedgerPath: fleetFiles.ledger, ...(accounts.length ? { accounts } : {}),
302
304
  pacing: replay ? { mode: 'paced', msPerTick: num(opts['ms-per-tick'], 2000) } : { mode: 'live' },
303
- sessions, dossier, vet, newRunId: (id) => newRunId(id), verbose: true, onLine: say,
305
+ sessions, dossier, vet: over.vetWrap ? (m) => over.vetWrap(m, vet?.(m)) : vet, newRunId: (id) => newRunId(id), verbose: true, onLine: say,
304
306
  globalSafety: () => {
305
307
  if (Date.now() >= stopAt)
306
308
  stop('max-minutes');
307
- const v = safety.step();
309
+ const s0 = safety.step();
310
+ const extra = over.extraSafety?.().pauseEntries ?? null;
311
+ const v = extra && !s0.pauseEntries ? { ...s0, pauseEntries: extra } : s0;
308
312
  return stopping && !v.halt ? { ...v, halt: 'runner-stopped', detail: 'a signal or --max-minutes', endWhenFlat: true } : v;
309
313
  },
310
314
  hooks: {