@reefclaw/connect 0.1.36 → 0.1.37

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 (34) hide show
  1. package/assets/bridge/index.js +17 -0
  2. package/assets/bridge/shock-wake.d.ts +80 -0
  3. package/assets/bridge/shock-wake.js +291 -0
  4. package/assets/plugin/config/agent-config-client.d.ts +3 -1
  5. package/assets/plugin/config/agent-config-client.js +4 -0
  6. package/assets/plugin/config/gate-store.d.ts +3 -0
  7. package/assets/plugin/config/gate-store.js +11 -2
  8. package/assets/plugin/config/loss-streak-config.d.ts +2 -0
  9. package/assets/plugin/config/loss-streak-config.js +33 -0
  10. package/assets/plugin/config/plugin-config-io.d.ts +19 -0
  11. package/assets/plugin/config/reentry-cooldown-config.d.ts +7 -0
  12. package/assets/plugin/config/reentry-cooldown-config.js +59 -0
  13. package/assets/plugin/index.js +5 -0
  14. package/assets/plugin/ingest/position-auto-capture.js +35 -2
  15. package/assets/plugin/openclaw.plugin.json +1 -1
  16. package/assets/plugin/portfolio/directional-scoreboard.d.ts +17 -0
  17. package/assets/plugin/portfolio/directional-scoreboard.js +71 -0
  18. package/assets/plugin/portfolio/reentry-tracker.d.ts +38 -1
  19. package/assets/plugin/portfolio/reentry-tracker.js +49 -0
  20. package/assets/plugin/signals/change-of-character.d.ts +38 -0
  21. package/assets/plugin/signals/change-of-character.js +93 -0
  22. package/assets/plugin/simulator/types.d.ts +11 -0
  23. package/assets/plugin/strategy/evaluator.d.ts +4 -0
  24. package/assets/plugin/tools/create-order.js +72 -2
  25. package/assets/plugin/tools/reentry-cooldown.d.ts +33 -0
  26. package/assets/plugin/tools/reentry-cooldown.js +74 -0
  27. package/assets/plugin/tools/scan-pairs.d.ts +7 -0
  28. package/assets/plugin/tools/scan-pairs.js +47 -0
  29. package/assets/shared/signals/change-of-character.d.ts +38 -0
  30. package/assets/shared/signals/change-of-character.js +86 -0
  31. package/assets/skill/SKILL.md +2 -2
  32. package/dist/cli.js +11 -2
  33. package/dist/plugin.js +70 -28
  34. package/package.json +1 -1
@@ -16,6 +16,7 @@ import { MockProvider } from './providers/mock.js';
16
16
  import { GatewayProvider } from './providers/gateway.js';
17
17
  import { resolveConfig } from './config.js';
18
18
  import { resolveGatewayConfig, validateGatewayConfig } from './gateway/gateway-config.js';
19
+ import { ShockWakePoller } from './shock-wake.js';
19
20
  import { runSetup } from './setup.js';
20
21
  import { resolveRelayInstanceId } from './utils/instance-id.js';
21
22
  const TAG = 'main';
@@ -192,6 +193,7 @@ async function main() {
192
193
  }
193
194
  // Create provider
194
195
  let provider;
196
+ let intelligenceUrlForWakes;
195
197
  if (args.provider === 'mock') {
196
198
  logger.info(TAG, 'Using MockProvider');
197
199
  provider = new MockProvider();
@@ -218,6 +220,7 @@ async function main() {
218
220
  gwConfig.connectionToken = token;
219
221
  logger.info(TAG, `Using GatewayProvider (url=${gwConfig.gatewayUrl}, symbol=${gwConfig.symbol})`);
220
222
  provider = new GatewayProvider(gwConfig);
223
+ intelligenceUrlForWakes = gwConfig.intelligenceUrl;
221
224
  }
222
225
  // Create bridge
223
226
  const connectorConfig = {
@@ -229,6 +232,18 @@ async function main() {
229
232
  instanceId: resolveRelayInstanceId(),
230
233
  };
231
234
  const bridge = new Bridge(provider, connectorConfig);
235
+ // Shock-wake poller (WS3, docs/MARKET_ADAPTIVITY_PLAN.md) — watches intel's
236
+ // /api/shocks (the WS2 change-of-character flags) and delivers an
237
+ // out-of-band re-evaluation turn to the agent on a genuine market shift.
238
+ // Inert until the central gate agent_config.gates.shockWake leaves 'off'.
239
+ const shockWake = intelligenceUrlForWakes
240
+ ? new ShockWakePoller({ provider, token, intelligenceUrl: intelligenceUrlForWakes })
241
+ : null;
242
+ if (shockWake) {
243
+ // Delivery confirmation: any agent turn STARTING proves the main-session
244
+ // lane is alive — the gateway ack alone cannot (swallowed-turn class).
245
+ provider.on('chatMessageStart', () => shockWake.noteAssistantActivity());
246
+ }
232
247
  // Handle graceful shutdown
233
248
  let shuttingDown = false;
234
249
  async function shutdown(signal) {
@@ -243,6 +258,7 @@ async function main() {
243
258
  }
244
259
  catch { /* best-effort */ }
245
260
  }
261
+ shockWake?.stop();
246
262
  bridge.stop();
247
263
  // Allow 1s for final cleanup before force exit
248
264
  setTimeout(() => process.exit(0), 1000);
@@ -252,5 +268,6 @@ async function main() {
252
268
  // Start
253
269
  logger.info(TAG, `Starting ReefClaw skill (provider=${args.provider}, relay=${relayUrl})`);
254
270
  bridge.start();
271
+ shockWake?.start();
255
272
  }
256
273
  main();
@@ -0,0 +1,80 @@
1
+ export type ShockWakeMode = 'off' | 'shadow' | 'on';
2
+ export interface ShockEntry {
3
+ symbol: string;
4
+ time: string;
5
+ flags: string[];
6
+ shock30mAtr: number;
7
+ range30mAtr: number;
8
+ return1hPct: number;
9
+ return4hPct: number;
10
+ tape4hAtr: number;
11
+ regime: string;
12
+ summary?: string;
13
+ }
14
+ /** 'BTCUSDT' / 'HL_BTC' / 'BTC/USDC' → 'BTC'. Best-effort market vocabulary
15
+ * for the wake message — never used to address an order. */
16
+ export declare function coinOf(intelSymbol: string): string;
17
+ /** Parse gates.shockWake off the raw /api/internal/config payload. Central-only
18
+ * gate — absent/garbage → 'off'. */
19
+ export declare function parseShockWakeGate(raw: unknown): ShockWakeMode;
20
+ export interface WakeAssessment {
21
+ wake: boolean;
22
+ reason?: 'leader_shock' | 'broad_shock';
23
+ /** Fresh 'shock'-flagged entries, extreme-first (as served). */
24
+ shocked: ShockEntry[];
25
+ }
26
+ /** Pure wake-worthiness rule. `nowMs` gates staleness. Broad rule (2026-09-06):
27
+ * ≥`minBroadCount` distinct coins shocked, OR ≥3 when a major participates. */
28
+ export declare function assessWakeWorthiness(shocks: ShockEntry[], nowMs: number, minBroadCount?: number): WakeAssessment;
29
+ /** The out-of-band agent turn. Clearly machine-labeled (never impersonates the
30
+ * operator), mandates re-evaluation, orders nothing. */
31
+ export declare function buildWakeMessage(a: WakeAssessment): string;
32
+ export interface ShockWakeOpts {
33
+ provider: {
34
+ handleChat(content: string): Promise<{
35
+ received: boolean;
36
+ error?: string;
37
+ }>;
38
+ };
39
+ token: string;
40
+ intelligenceUrl: string;
41
+ webappUrl?: string;
42
+ fetchImpl?: typeof fetch;
43
+ now?: () => number;
44
+ }
45
+ export declare class ShockWakePoller {
46
+ private readonly opts;
47
+ private mode;
48
+ private pollTimer;
49
+ private gateTimer;
50
+ private lastWakeAtMs;
51
+ private wakesToday;
52
+ private wakeDayUtc;
53
+ private polling;
54
+ private readonly pollMs;
55
+ private readonly gatePollMs;
56
+ private readonly cooldownMs;
57
+ private readonly dailyCap;
58
+ private readonly minBroad;
59
+ private readonly replyTimeoutMs;
60
+ private lastAssistantAtMs;
61
+ private awaitingSinceMs;
62
+ private awaitingDeadlineMs;
63
+ private suspectedSwallows;
64
+ constructor(opts: ShockWakeOpts);
65
+ start(): void;
66
+ stop(): void;
67
+ getMode(): ShockWakeMode;
68
+ /** Fed by the bridge from provider `chatMessageStart` — any agent turn
69
+ * beginning counts (the wake's reply, or an operator chat's; either proves
70
+ * the lane is alive, which is what the swallow check needs). */
71
+ noteAssistantActivity(atMs?: number): void;
72
+ /** Suspected-swallow count this process (test/telemetry seam). */
73
+ getSuspectedSwallows(): number;
74
+ private checkPendingReply;
75
+ private refreshGate;
76
+ /** One poll cycle. Exposed for tests. */
77
+ tick(): Promise<void>;
78
+ /** Test seam. */
79
+ __setModeForTest(mode: ShockWakeMode): void;
80
+ }
@@ -0,0 +1,291 @@
1
+ // Shock-wake poller — WS3 of docs/MARKET_ADAPTIVITY_PLAN.md.
2
+ //
3
+ // The agent thinks on a 15–30 min heartbeat; an announcement lands mid-cycle
4
+ // and isn't reconsidered until the next one — the adaptivity investigation's
5
+ // core latency gap. This poller watches intel's /api/shocks (the WS2
6
+ // change-of-character flags, computed each fact pass) and, when the market
7
+ // genuinely changes character, delivers ONE out-of-band agent turn through
8
+ // the same gateway path operator chat uses (provider.handleChat — the
9
+ // precedent is the trade-mission presenter).
10
+ //
11
+ // Guardrails (every one deliberately boring):
12
+ // - Central gate `agent_config.gates.shockWake`: off (default) → shadow
13
+ // (logs WOULD WAKE, delivers nothing) → on. Polled from the webapp
14
+ // every ~5 min; absent/garbage/outage → off. No local file fallback —
15
+ // this gate is central-only.
16
+ // - Wake-worthy = a market LEADER (BTC/ETH) flagged 'shock', OR a broad
17
+ // correlated move: ≥5 distinct coins shocked (env RC_SHOCK_WAKE_MIN_BROAD),
18
+ // or ≥3 when a MAJOR (BTC/ETH/BNB/SOL/XRP) is among them. Disagreement-only
19
+ // flags never wake — they are slow-moving and already ride scan_pairs
20
+ // indication. (Broad bar raised from a flat ≥3 on 2026-09-06: the first
21
+ // live night delivered 7 wakes on rotating 3-coin mid-cap alt clusters —
22
+ // routine alt volatility, not announcements. Replayed against the new
23
+ // rule, those 7 become 1.)
24
+ // - Stale shocks (fact older than 10 min) are ignored.
25
+ // - Global cooldown 60 min between wakes + daily cap 8 (UTC), armed in
26
+ // shadow too so the shadow soak counts exactly what 'on' would deliver.
27
+ // A FAILED delivery does not arm the cooldown (retry next tick).
28
+ // (Cooldown default raised 30→60 min 2026-09-05: the shadow soak showed a
29
+ // single sustained 09-03 event re-firing 4 would-wakes in 95 min — one
30
+ // re-ping per hour during a long move is the intended cadence.)
31
+ // - The wake is INDICATION: it mandates re-evaluation, never an action.
32
+ // - DELIVERY CONFIRMATION (2026-09-06): the gateway acks the RPC even when
33
+ // the main-session lane silently swallows the turn (the 2026-07-22
34
+ // OpenClaw class — 7 of the first night's 9 wakes died this way). The
35
+ // bridge wires provider `chatMessageStart` into noteAssistantActivity();
36
+ // if no agent turn STARTS within RC_SHOCK_WAKE_REPLY_TIMEOUT_MS (10 min)
37
+ // of a delivered wake, a WARN names the swallow suspicion (dashboard chat
38
+ // is likely dead too) and a counter increments. Observability only — no
39
+ // auto-retry into a wedged lane.
40
+ //
41
+ // Env overrides: RC_SHOCK_WAKE_POLL_MS (60s), RC_SHOCK_WAKE_GATE_POLL_MS
42
+ // (5 min), RC_SHOCK_WAKE_COOLDOWN_MS (30 min), RC_SHOCK_WAKE_DAILY_CAP (8).
43
+ import { logger, formatError } from './logger.js';
44
+ const TAG = 'shock-wake';
45
+ /** Leaders whose lone shock is wake-worthy, as base coins (venue-stripped). */
46
+ const LEADER_COINS = new Set(['BTC', 'ETH']);
47
+ /** Majors (the platform's liquidation-pulse majors group): their participation
48
+ * lowers the broad-shock coin bar from 5 to 3 — a SOL-led cluster is market
49
+ * information; three rotating meme-alts are Tuesday. */
50
+ const MAJOR_COINS = new Set(['BTC', 'ETH', 'BNB', 'SOL', 'XRP']);
51
+ const STALE_SHOCK_MS = 10 * 60_000;
52
+ function envInt(name, fallback) {
53
+ const v = Number(process.env[name]);
54
+ return Number.isFinite(v) && v > 0 ? v : fallback;
55
+ }
56
+ /** 'BTCUSDT' / 'HL_BTC' / 'BTC/USDC' → 'BTC'. Best-effort market vocabulary
57
+ * for the wake message — never used to address an order. */
58
+ export function coinOf(intelSymbol) {
59
+ return intelSymbol
60
+ .replace(/^HL_/, '')
61
+ .replace(/\/.*$/, '')
62
+ .replace(/(USDT|USDC|BUSD)$/i, '')
63
+ .toUpperCase();
64
+ }
65
+ /** Parse gates.shockWake off the raw /api/internal/config payload. Central-only
66
+ * gate — absent/garbage → 'off'. */
67
+ export function parseShockWakeGate(raw) {
68
+ if (!raw || typeof raw !== 'object')
69
+ return 'off';
70
+ const gates = raw.gates;
71
+ if (!gates || typeof gates !== 'object')
72
+ return 'off';
73
+ const v = gates.shockWake;
74
+ return v === 'shadow' || v === 'on' ? v : 'off';
75
+ }
76
+ /** Pure wake-worthiness rule. `nowMs` gates staleness. Broad rule (2026-09-06):
77
+ * ≥`minBroadCount` distinct coins shocked, OR ≥3 when a major participates. */
78
+ export function assessWakeWorthiness(shocks, nowMs, minBroadCount = 5) {
79
+ const fresh = shocks.filter((s) => {
80
+ const t = Date.parse(s.time);
81
+ return Number.isFinite(t) && nowMs - t <= STALE_SHOCK_MS;
82
+ });
83
+ const shocked = fresh.filter((s) => s.flags.includes('shock'));
84
+ // One coin can appear per-venue (BTCUSDT + HL_BTC) — count coins, not rows.
85
+ const coins = new Set(shocked.map((s) => coinOf(s.symbol)));
86
+ const leader = shocked.find((s) => LEADER_COINS.has(coinOf(s.symbol)));
87
+ if (leader)
88
+ return { wake: true, reason: 'leader_shock', shocked };
89
+ const hasMajor = [...coins].some((c) => MAJOR_COINS.has(c));
90
+ if (coins.size >= minBroadCount || (hasMajor && coins.size >= 3)) {
91
+ return { wake: true, reason: 'broad_shock', shocked };
92
+ }
93
+ return { wake: false, shocked };
94
+ }
95
+ /** The out-of-band agent turn. Clearly machine-labeled (never impersonates the
96
+ * operator), mandates re-evaluation, orders nothing. */
97
+ export function buildWakeMessage(a) {
98
+ const seen = new Set();
99
+ const lines = [];
100
+ for (const s of a.shocked) {
101
+ const coin = coinOf(s.symbol);
102
+ if (seen.has(coin))
103
+ continue;
104
+ seen.add(coin);
105
+ const sign = (v) => (v >= 0 ? '+' : '');
106
+ lines.push(`- ${coin}: 30m ${Math.max(s.shock30mAtr, s.range30mAtr).toFixed(1)}×ATR, ` +
107
+ `1h ${sign(s.return1hPct)}${s.return1hPct}%, 4h ${sign(s.return4hPct)}${s.return4hPct}% ` +
108
+ `(regime label: ${s.regime})`);
109
+ if (lines.length >= 6)
110
+ break;
111
+ }
112
+ return [
113
+ '[AUTOMATED MARKET-SHIFT ALERT — from the ReefClaw system, NOT the operator]',
114
+ '',
115
+ a.reason === 'leader_shock'
116
+ ? 'A market leader just moved sharply — the market may have changed character:'
117
+ : 'Multiple symbols moved sharply together — the market may have changed character:',
118
+ ...lines,
119
+ '',
120
+ 'Do this NOW, ahead of your scheduled heartbeat:',
121
+ '1. Re-derive your directional bias from FRESH data (scan_pairs, get_regime) — do NOT lean on theses formed before this move; regime labels may LAG it (see market_shift_caution in scan results).',
122
+ '2. For EVERY open position: check the pinned invalidation FIRST. If price is through it, act on your own plan.',
123
+ '3. Hold off on new entries until the re-derived bias and the tape agree.',
124
+ '',
125
+ 'This alert is indication only — it does not order you to close anything. Reply with a brief assessment so the operator sees your read.',
126
+ ].join('\n');
127
+ }
128
+ export class ShockWakePoller {
129
+ opts;
130
+ mode = 'off';
131
+ pollTimer = null;
132
+ gateTimer = null;
133
+ lastWakeAtMs = 0;
134
+ wakesToday = 0;
135
+ wakeDayUtc = '';
136
+ polling = false;
137
+ pollMs = envInt('RC_SHOCK_WAKE_POLL_MS', 60_000);
138
+ gatePollMs = envInt('RC_SHOCK_WAKE_GATE_POLL_MS', 5 * 60_000);
139
+ cooldownMs = envInt('RC_SHOCK_WAKE_COOLDOWN_MS', 60 * 60_000);
140
+ dailyCap = envInt('RC_SHOCK_WAKE_DAILY_CAP', 8);
141
+ minBroad = envInt('RC_SHOCK_WAKE_MIN_BROAD', 5);
142
+ replyTimeoutMs = envInt('RC_SHOCK_WAKE_REPLY_TIMEOUT_MS', 10 * 60_000);
143
+ // Delivery confirmation (see header): a wake is only proven delivered when
144
+ // an agent turn STARTS after it. lastAssistantAtMs is fed by the bridge's
145
+ // chatMessageStart wiring; awaitingSince/deadline track one in-flight wake
146
+ // (the 60-min cooldown guarantees no overlap with the 10-min timeout).
147
+ lastAssistantAtMs = 0;
148
+ awaitingSinceMs = null;
149
+ awaitingDeadlineMs = 0;
150
+ suspectedSwallows = 0;
151
+ constructor(opts) {
152
+ this.opts = opts;
153
+ }
154
+ start() {
155
+ if (this.pollTimer)
156
+ return;
157
+ const refresh = () => { void this.refreshGate(); };
158
+ refresh();
159
+ this.gateTimer = setInterval(refresh, this.gatePollMs);
160
+ this.gateTimer.unref?.();
161
+ this.pollTimer = setInterval(() => { void this.tick(); }, this.pollMs);
162
+ this.pollTimer.unref?.();
163
+ logger.info(TAG, `started (poll ${this.pollMs / 1000}s, cooldown ${this.cooldownMs / 60000}m, cap ${this.dailyCap}/day, gate polled ${this.gatePollMs / 60000}m)`);
164
+ }
165
+ stop() {
166
+ if (this.pollTimer)
167
+ clearInterval(this.pollTimer);
168
+ if (this.gateTimer)
169
+ clearInterval(this.gateTimer);
170
+ this.pollTimer = null;
171
+ this.gateTimer = null;
172
+ }
173
+ getMode() {
174
+ return this.mode;
175
+ }
176
+ /** Fed by the bridge from provider `chatMessageStart` — any agent turn
177
+ * beginning counts (the wake's reply, or an operator chat's; either proves
178
+ * the lane is alive, which is what the swallow check needs). */
179
+ noteAssistantActivity(atMs) {
180
+ const t = atMs ?? this.opts.now?.() ?? Date.now();
181
+ this.lastAssistantAtMs = t;
182
+ if (this.awaitingSinceMs !== null && t >= this.awaitingSinceMs) {
183
+ logger.info(TAG, `wake reply confirmed — agent turn started ${Math.round((t - this.awaitingSinceMs) / 1000)}s after delivery`);
184
+ this.awaitingSinceMs = null;
185
+ }
186
+ }
187
+ /** Suspected-swallow count this process (test/telemetry seam). */
188
+ getSuspectedSwallows() {
189
+ return this.suspectedSwallows;
190
+ }
191
+ checkPendingReply(nowMs) {
192
+ if (this.awaitingSinceMs === null || nowMs <= this.awaitingDeadlineMs)
193
+ return;
194
+ this.suspectedSwallows++;
195
+ logger.warn(TAG, `wake delivered at ${new Date(this.awaitingSinceMs).toISOString()} but NO agent turn started ` +
196
+ `within ${Math.round(this.replyTimeoutMs / 60_000)}m — the main-session lane may be silently ` +
197
+ `swallowing turns (known OpenClaw class, 2026-07-22; dashboard chat is likely affected too). ` +
198
+ `Suspected swallows this process: ${this.suspectedSwallows}`);
199
+ this.awaitingSinceMs = null;
200
+ }
201
+ async refreshGate() {
202
+ const base = (this.opts.webappUrl ?? process.env.REEFCLAW_API_URL ?? 'https://www.reefclaw.com').replace(/\/$/, '');
203
+ try {
204
+ const doFetch = this.opts.fetchImpl ?? fetch;
205
+ const res = await doFetch(`${base}/api/internal/config`, {
206
+ headers: { Authorization: `Bearer ${this.opts.token}` },
207
+ });
208
+ if (!res.ok)
209
+ return; // keep last-known mode on outage (fail toward inert)
210
+ const next = parseShockWakeGate(await res.json());
211
+ if (next !== this.mode) {
212
+ logger.info(TAG, `gate: shockWake ${this.mode} → ${next}`);
213
+ this.mode = next;
214
+ }
215
+ }
216
+ catch (err) {
217
+ logger.debug(TAG, `gate poll failed (keeping ${this.mode}): ${formatError(err)}`);
218
+ }
219
+ }
220
+ /** One poll cycle. Exposed for tests. */
221
+ async tick() {
222
+ const tickNowMs = this.opts.now?.() ?? Date.now();
223
+ // Runs even when the gate is off — a wake delivered just before an
224
+ // operator rollback still deserves its confirmation verdict.
225
+ this.checkPendingReply(tickNowMs);
226
+ if (this.mode === 'off' || this.polling)
227
+ return;
228
+ this.polling = true;
229
+ try {
230
+ const nowMs = tickNowMs;
231
+ const doFetch = this.opts.fetchImpl ?? fetch;
232
+ const base = this.opts.intelligenceUrl.replace(/\/$/, '');
233
+ const res = await doFetch(`${base}/api/shocks`, {
234
+ headers: { Authorization: `Bearer ${this.opts.token}` },
235
+ });
236
+ if (!res.ok)
237
+ return;
238
+ const body = (await res.json());
239
+ if (!Array.isArray(body?.shocks))
240
+ return;
241
+ const a = assessWakeWorthiness(body.shocks, nowMs, this.minBroad);
242
+ if (!a.wake)
243
+ return;
244
+ // Rate limits — checked only for wake-worthy ticks so quiet markets
245
+ // never touch the counters.
246
+ const day = new Date(nowMs).toISOString().slice(0, 10);
247
+ if (day !== this.wakeDayUtc) {
248
+ this.wakeDayUtc = day;
249
+ this.wakesToday = 0;
250
+ }
251
+ if (nowMs - this.lastWakeAtMs < this.cooldownMs)
252
+ return;
253
+ if (this.wakesToday >= this.dailyCap) {
254
+ logger.warn(TAG, `daily cap ${this.dailyCap} reached — suppressing further wakes today`);
255
+ return;
256
+ }
257
+ const coins = [...new Set(a.shocked.map((s) => coinOf(s.symbol)))].join(', ');
258
+ if (this.mode === 'shadow') {
259
+ this.lastWakeAtMs = nowMs;
260
+ this.wakesToday++;
261
+ logger.warn(TAG, `WOULD WAKE (shadow): ${a.reason} — ${coins} (${this.wakesToday}/${this.dailyCap} today)`);
262
+ return;
263
+ }
264
+ const message = buildWakeMessage(a);
265
+ const out = await this.opts.provider.handleChat(message);
266
+ if (out.received) {
267
+ this.lastWakeAtMs = nowMs;
268
+ this.wakesToday++;
269
+ // Arm the delivery-confirmation window (see checkPendingReply).
270
+ this.awaitingSinceMs = nowMs;
271
+ this.awaitingDeadlineMs = nowMs + this.replyTimeoutMs;
272
+ logger.warn(TAG, `WAKE delivered: ${a.reason} — ${coins} (${this.wakesToday}/${this.dailyCap} today)`);
273
+ }
274
+ else {
275
+ // Delivery failed (gateway not connected etc.) — no cooldown, retry
276
+ // on the next tick while the shock is still fresh.
277
+ logger.warn(TAG, `wake delivery FAILED (${out.error ?? 'unknown'}) — will retry next tick`);
278
+ }
279
+ }
280
+ catch (err) {
281
+ logger.debug(TAG, `tick failed: ${formatError(err)}`);
282
+ }
283
+ finally {
284
+ this.polling = false;
285
+ }
286
+ }
287
+ /** Test seam. */
288
+ __setModeForTest(mode) {
289
+ this.mode = mode;
290
+ }
291
+ }
@@ -6,12 +6,14 @@
6
6
  * `positionReviewMode` (slice 3, the Position Decision Journal
7
7
  * heartbeat-mandate + superset gate, file key `positionReview.mode`) →
8
8
  * `approvalMode` (slice 4, per-trade operator approval, file key
9
- * `approval.mode`). The first two ride the same four-stage
9
+ * `approval.mode`) `reentryCooldown` (create_order re-entry cooldown, file
10
+ * key `reentryCooldown.mode`). All but approvalMode ride the same four-stage
10
11
  * `off → shadow → observe → enforce` ladder; approvalMode has its own. */
11
12
  export interface AgentGates {
12
13
  exitGate?: 'off' | 'shadow' | 'observe' | 'enforce';
13
14
  positionReviewMode?: 'off' | 'shadow' | 'observe' | 'enforce';
14
15
  approvalMode?: 'off' | 'per_trade';
16
+ reentryCooldown?: 'off' | 'shadow' | 'observe' | 'enforce';
15
17
  }
16
18
  /** Server-resolved entitlement verdict (webapp lib/entitlements.ts, computed
17
19
  * from the users row and delivered on the config channel). The plugin NEVER
@@ -125,6 +125,10 @@ function validateGates(raw) {
125
125
  if (typeof approvalMode === 'string' && APPROVAL_MODE_VALUES.has(approvalMode)) {
126
126
  gates.approvalMode = approvalMode;
127
127
  }
128
+ const reentryCooldown = obj.reentryCooldown;
129
+ if (typeof reentryCooldown === 'string' && MODE_LADDER_VALUES.has(reentryCooldown)) {
130
+ gates.reentryCooldown = reentryCooldown;
131
+ }
128
132
  return gates;
129
133
  }
130
134
  /** Version-monotonic acceptance (basic rollback/replay protection): a fetched
@@ -18,6 +18,9 @@ declare class GateStore {
18
18
  * is the pre-existing autonomous behaviour, so neither value can leave a
19
19
  * position unprotected. */
20
20
  getApprovalMode(): AgentGates['approvalMode'] | null;
21
+ /** The central reentryCooldown mode, or null when central has no value (or
22
+ * the kill-switch is on) — null tells the reader to fall back to the file. */
23
+ getReentryCooldown(): AgentGates['reentryCooldown'] | null;
21
24
  /** Test-only. */
22
25
  __reset(): void;
23
26
  }
@@ -31,12 +31,14 @@ class GateStore {
31
31
  const next = gates ?? {};
32
32
  const changed = next.exitGate !== this.gates.exitGate ||
33
33
  next.positionReviewMode !== this.gates.positionReviewMode ||
34
- next.approvalMode !== this.gates.approvalMode;
34
+ next.approvalMode !== this.gates.approvalMode ||
35
+ next.reentryCooldown !== this.gates.reentryCooldown;
35
36
  this.gates = { ...next };
36
37
  if (changed) {
37
38
  logger.info(TAG, `applied central gates: exitGate=${next.exitGate ?? UNSET} ` +
38
39
  `positionReviewMode=${next.positionReviewMode ?? UNSET} ` +
39
- `approvalMode=${next.approvalMode ?? UNSET}`);
40
+ `approvalMode=${next.approvalMode ?? UNSET} ` +
41
+ `reentryCooldown=${next.reentryCooldown ?? UNSET}`);
40
42
  }
41
43
  }
42
44
  /** The central exitGate mode, or null when central has no value (or the
@@ -66,6 +68,13 @@ class GateStore {
66
68
  return null;
67
69
  return this.gates.approvalMode ?? null;
68
70
  }
71
+ /** The central reentryCooldown mode, or null when central has no value (or
72
+ * the kill-switch is on) — null tells the reader to fall back to the file. */
73
+ getReentryCooldown() {
74
+ if (!centralGatesEnabled())
75
+ return null;
76
+ return this.gates.reentryCooldown ?? null;
77
+ }
69
78
  /** Test-only. */
70
79
  __reset() {
71
80
  this.gates = {};
@@ -0,0 +1,2 @@
1
+ export type LossStreakSizingMode = 'off' | 'log' | 'enforce';
2
+ export declare function resolveLossStreakSizingMode(): LossStreakSizingMode;
@@ -0,0 +1,33 @@
1
+ // WS1 (docs/MARKET_ADAPTIVITY_PLAN.md §3) — mode resolver for the LIVE
2
+ // loss-streak sizing brake feed.
3
+ //
4
+ // preTradeRiskCheck has always had a graduated loss-streak brake (0.5× /
5
+ // 0.25× position size at the operator-tunable lossStreakHalfSize /
6
+ // lossStreakQuarterSize thresholds — never a hard block), but live fed it a
7
+ // hardcoded consecutiveLosses=0 ("would come from intelligence DB — use 0
8
+ // for now"). The real feed now comes from the ReentryTracker exit records
9
+ // (wasLoss + book tag, persisted).
10
+ //
11
+ // Env RC_LOSS_STREAK_SIZING:
12
+ // 'enforce' (DEFAULT since 2026-09-05) — feed the real streak to the risk
13
+ // check; the graduated size reduction applies on
14
+ // live exactly as it always has on paper. Promoted
15
+ // from 'log' after the pre-registered soak: 3 days
16
+ // of clean streak logs (1→3 tracked + reset
17
+ // correctly) and an 18/18 loss-sign agreement audit
18
+ // between the agent's r_multiple_at_close and DB
19
+ // realized_r.
20
+ // 'log' — compute + log on entries; sizing UNAFFECTED
21
+ // (riskCheck still sees 0). The rollout soak mode.
22
+ // 'off' — no compute, no log; byte-identical to the
23
+ // pre-WS1 path (kill-switch).
24
+ //
25
+ // Deliberately env-based (not the central gate channel): it is a
26
+ // live/paper-parity bug fix on a risk-reduction mechanism, not a new policy
27
+ // ladder — and its only enforce-direction effect is SMALLER size.
28
+ export function resolveLossStreakSizingMode() {
29
+ const raw = (process.env.RC_LOSS_STREAK_SIZING ?? '').toLowerCase();
30
+ if (raw === 'off' || raw === 'log')
31
+ return raw;
32
+ return 'enforce';
33
+ }
@@ -197,6 +197,25 @@ export interface PluginConfigFile {
197
197
  stopWatcher?: {
198
198
  intervalMs?: number;
199
199
  };
200
+ /** Re-entry cooldown gate — blocks (mode-laddered) a NEW create_order entry
201
+ * on a symbol whose last close within `minutes` was a LOSS. See
202
+ * plugin/src/tools/reentry-cooldown.ts for the evidence + semantics.
203
+ *
204
+ * mode='off' (default) — gate never runs; behaviour identical to today.
205
+ * mode='shadow' — gate runs; verdict logged + tagged into
206
+ * position_entries.metadata.reentry_cooldown;
207
+ * the order always fires.
208
+ * mode='observe' — as shadow, but a triggered verdict logs at WARN.
209
+ * mode='enforce' — triggered verdict hard-rejects create_order.
210
+ *
211
+ * `mode` here is the LOCAL fallback — once the central gate
212
+ * (agent_config.gates.reentryCooldown) is set, central rules (kill-switch
213
+ * RC_CENTRAL_GATES=off). `minutes` is local-only (default 60, clamped
214
+ * 5–1440). */
215
+ reentryCooldown?: {
216
+ mode?: 'off' | 'shadow' | 'observe' | 'enforce';
217
+ minutes?: number;
218
+ };
200
219
  [extra: string]: unknown;
201
220
  }
202
221
  export declare function defaultConfigPath(): string;
@@ -0,0 +1,7 @@
1
+ import { type PluginConfigFile } from './plugin-config-io.js';
2
+ import type { ReentryCooldownMode } from '../tools/reentry-cooldown.js';
3
+ export declare const DEFAULT_REENTRY_COOLDOWN_MINUTES = 60;
4
+ export declare function getReentryCooldownMode(config?: PluginConfigFile): ReentryCooldownMode;
5
+ export declare function loadReentryCooldownMode(): ReentryCooldownMode;
6
+ export declare function getReentryCooldownMinutes(config?: PluginConfigFile): number;
7
+ export declare function loadReentryCooldownMinutes(): number;
@@ -0,0 +1,59 @@
1
+ // Feature-flag readers for the re-entry cooldown gate (create_order).
2
+ //
3
+ // Mode default 'off' so the gate ships dead-code; the cooldown window default
4
+ // (60 min) matches the 2026-09-02 measurement window that motivated the gate.
5
+ // Mode resolution follows the exitGate pattern (config-service slice 2):
6
+ //
7
+ // central (agent_config.gates.reentryCooldown via gate-store)
8
+ // → plugin-config.json reentryCooldown.mode
9
+ // → 'off'
10
+ //
11
+ // create_order reads the mode PER CALL, so a dashboard/API flip via
12
+ // scripts/enable-reentry-cooldown.py hot-applies within one config poll —
13
+ // no restart. Kill-switch RC_CENTRAL_GATES=off hands control back to the
14
+ // local file. The minutes knob is LOCAL-only (mechanism tunable, not a
15
+ // ladder) — central carries only the mode.
16
+ import { readPluginConfig } from './plugin-config-io.js';
17
+ import { gateStore } from './gate-store.js';
18
+ const VALID_MODES = new Set([
19
+ 'off',
20
+ 'shadow',
21
+ 'observe',
22
+ 'enforce',
23
+ ]);
24
+ export const DEFAULT_REENTRY_COOLDOWN_MINUTES = 60;
25
+ const MIN_COOLDOWN_MINUTES = 5;
26
+ const MAX_COOLDOWN_MINUTES = 1440;
27
+ export function getReentryCooldownMode(config) {
28
+ const raw = config?.reentryCooldown?.mode;
29
+ if (typeof raw === 'string' && VALID_MODES.has(raw)) {
30
+ return raw;
31
+ }
32
+ return 'off';
33
+ }
34
+ export function loadReentryCooldownMode() {
35
+ const central = gateStore.getReentryCooldown();
36
+ if (central)
37
+ return central;
38
+ try {
39
+ return getReentryCooldownMode(readPluginConfig());
40
+ }
41
+ catch {
42
+ return 'off';
43
+ }
44
+ }
45
+ export function getReentryCooldownMinutes(config) {
46
+ const raw = config?.reentryCooldown?.minutes;
47
+ if (typeof raw === 'number' && Number.isFinite(raw)) {
48
+ return Math.max(MIN_COOLDOWN_MINUTES, Math.min(MAX_COOLDOWN_MINUTES, raw));
49
+ }
50
+ return DEFAULT_REENTRY_COOLDOWN_MINUTES;
51
+ }
52
+ export function loadReentryCooldownMinutes() {
53
+ try {
54
+ return getReentryCooldownMinutes(readPluginConfig());
55
+ }
56
+ catch {
57
+ return DEFAULT_REENTRY_COOLDOWN_MINUTES;
58
+ }
59
+ }
@@ -2637,6 +2637,11 @@ const paperTradingPlugin = {
2637
2637
  decisionsClient: positionDecisionsClient,
2638
2638
  userId: positionDecisionsUserId,
2639
2639
  reentryTracker,
2640
+ // WS2 directional scoreboard (docs/MARKET_ADAPTIVITY_PLAN.md §3):
2641
+ // tracked positions from the state store (no exchange round-trip)
2642
+ // + book resolved per call so a paper↔live flip follows.
2643
+ openPositions: () => positionStateStore.getAll().map((e) => ({ side: e.side })),
2644
+ book: () => (runtime.adapter.isLive ? 'live' : 'paper'),
2640
2645
  })),
2641
2646
  },
2642
2647
  {