@reefclaw/openclaw-plugin 0.1.47 → 0.1.49

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 (43) hide show
  1. package/bridge/bridge.d.ts +39 -0
  2. package/bridge/bridge.js +229 -20
  3. package/bridge/gateway/heartbeat-cron.d.ts +64 -0
  4. package/bridge/gateway/heartbeat-cron.js +153 -3
  5. package/bridge/heartbeat-runs.d.ts +6 -0
  6. package/bridge/heartbeat-runs.js +43 -1
  7. package/bridge/index.js +3 -0
  8. package/bridge/provider.d.ts +12 -0
  9. package/bridge/providers/connector-update.js +20 -2
  10. package/bridge/providers/gateway.d.ts +21 -0
  11. package/bridge/providers/gateway.js +121 -9
  12. package/bridge/shock-wake.js +12 -2
  13. package/bridge/types.d.ts +17 -0
  14. package/bridge/utils/skill-version.d.ts +6 -0
  15. package/bridge/utils/skill-version.js +10 -0
  16. package/bridge/utils/webapp-edge.d.ts +145 -0
  17. package/bridge/utils/webapp-edge.js +366 -0
  18. package/config/agent-config-client.js +18 -2
  19. package/config/agent-config-poller.d.ts +4 -0
  20. package/config/agent-config-poller.js +46 -6
  21. package/http/webapp-edge.d.ts +116 -0
  22. package/http/webapp-edge.js +313 -0
  23. package/index.js +7 -0
  24. package/ingest/position-decisions-client.js +28 -7
  25. package/ingest/readiness-reporter.d.ts +13 -0
  26. package/ingest/readiness-reporter.js +78 -8
  27. package/ingest/trade-store-client.js +25 -4
  28. package/openclaw.plugin.json +1 -1
  29. package/package.json +1 -1
  30. package/release-integrity.json +10 -0
  31. package/release-notes.json +3 -1
  32. package/signals/stop-rules.d.ts +13 -0
  33. package/signals/stop-rules.js +35 -6
  34. package/signals/strategy-adapter.js +25 -6
  35. package/skills/reefclaw/SKILL.md +1 -1
  36. package/tools/assessment-validation.d.ts +10 -2
  37. package/tools/assessment-validation.js +19 -5
  38. package/tools/create-order.d.ts +4 -0
  39. package/tools/create-order.js +15 -0
  40. package/tools/get-market-intel.d.ts +3 -0
  41. package/tools/get-market-intel.js +24 -1
  42. package/tools/intel-cache.d.ts +14 -0
  43. package/tools/intel-cache.js +59 -0
@@ -1,6 +1,7 @@
1
1
  import { type ReadinessCheck, type ReadinessReport, type VenueId, type VenueReachabilityResult } from '@reefclaw/shared';
2
2
  import type { InstallChannel } from '../plugin-version.js';
3
3
  import type { PluginRuntimeIntegrity } from '../plugin-integrity.js';
4
+ import { type EdgeGateSnapshot } from '../http/webapp-edge.js';
4
5
  /** Who froze the loop. 'unknown' when the kernel counter is unreadable (not
5
6
  * Linux / no CONFIG_SCHEDSTATS / first cycle) — attribution is evidence, and
6
7
  * absent evidence stays absent rather than defaulting to a blame. */
@@ -30,6 +31,16 @@ export interface StopProtectionSnapshot {
30
31
  * branch by branch. Null snapshot → null (older wiring: omit the row rather
31
32
  * than fabricate a verdict). */
32
33
  export declare function stopProtectionCheck(snap: StopProtectionSnapshot | null, checkedAt: number): ReadinessCheck | null;
34
+ /** Fix hint for the `reefclaw_api_reachable` row. Assertive on purpose: the
35
+ * edge answered with its own header, so — like a 451 from Binance — this is
36
+ * reporting what the server said, not an inference. */
37
+ export declare const WEBAPP_EDGE_FIX_HINT: string;
38
+ /** Map the shared edge-gate snapshot to a readiness row. Pure. Blocked → fail;
39
+ * anything else → null (absent evidence stays absent — the row is omitted,
40
+ * never fabricated as a pass, and never a stale "warn" riding a POST that
41
+ * just succeeded). Built by hand rather than makeReadinessCheck because the
42
+ * id is newer than the shared copy map vendored on older boxes. */
43
+ export declare function webappApiCheck(snap: EdgeGateSnapshot, checkedAt: number): ReadinessCheck | null;
33
44
  /** Cross-cycle memory for the debounced rungs. Held by the interval loop and
34
45
  * passed in explicitly so `collectReadiness` stays a pure function of its
35
46
  * inputs — a module-global counter would leak between unit tests. */
@@ -89,6 +100,8 @@ export declare function collectReadiness(opts: Pick<ReadinessReporterOptions, 'v
89
100
  sampleHostStallMs?: () => number | null;
90
101
  /** Injected for tests; production reads /proc/self/schedstat. */
91
102
  sampleRunqueueWaitMs?: () => number | null;
103
+ /** Injected for tests; production reads the process-wide edge gate. */
104
+ webappEdgeSnapshot?: () => EdgeGateSnapshot;
92
105
  }): Promise<ReadinessReport>;
93
106
  /** Test-only — reset the singleton guard between unit tests. */
94
107
  export declare function __resetReadinessReporterForTests(): void;
@@ -11,6 +11,7 @@
11
11
  import { makeReadinessCheck, deriveOverallReadiness, GEO_BLOCK_FIX_HINT, HOST_STALL_FIX_HINT, } from '@reefclaw/shared';
12
12
  import { logger, formatError } from '../logger.js';
13
13
  import { startEventLoopMonitor, sampleEventLoopDelayMs, sampleRunqueueWaitMs, } from './event-loop-monitor.js';
14
+ import { noteWebappResponse, webappEdgeGate, webappHeaders, } from '../http/webapp-edge.js';
14
15
  const TAG = 'readiness';
15
16
  const DEFAULT_INTERVAL_MS = 300_000; // 5 min — geo/clock state changes rarely.
16
17
  const MIN_INTERVAL_MS = 60_000;
@@ -85,6 +86,36 @@ export function stopProtectionCheck(snap, checkedAt) {
85
86
  checkedAt,
86
87
  });
87
88
  }
89
+ /** Fix hint for the `reefclaw_api_reachable` row. Assertive on purpose: the
90
+ * edge answered with its own header, so — like a 451 from Binance — this is
91
+ * reporting what the server said, not an inference. */
92
+ export const WEBAPP_EDGE_FIX_HINT = "ReefClaw's edge protection is denying this host's IP (an automatic Vercel DDoS mitigation — not your account, token or anything on this machine). " +
93
+ 'The agent keeps trading with its safety floor intact, but the position journal, central config and instruction updates pause until it lifts. ' +
94
+ 'It usually clears within 30 minutes on its own; if it keeps coming back, email support@reefclaw.com with the time and your hosting provider so ReefClaw can add an allow rule.';
95
+ /** Map the shared edge-gate snapshot to a readiness row. Pure. Blocked → fail;
96
+ * anything else → null (absent evidence stays absent — the row is omitted,
97
+ * never fabricated as a pass, and never a stale "warn" riding a POST that
98
+ * just succeeded). Built by hand rather than makeReadinessCheck because the
99
+ * id is newer than the shared copy map vendored on older boxes. */
100
+ export function webappApiCheck(snap, checkedAt) {
101
+ if (!snap.blocked)
102
+ return null;
103
+ const since = snap.firstDeniedAt ? new Date(snap.firstDeniedAt).toISOString().slice(11, 16) + ' UTC' : '?';
104
+ const rid = snap.lastRequestId ? `, request ${snap.lastRequestId}` : '';
105
+ const base = {
106
+ id: 'reefclaw_api_reachable',
107
+ label: 'ReefClaw API reachable',
108
+ phase: 'connect',
109
+ checkedAt,
110
+ };
111
+ const left = snap.blockedUntil ? Math.max(1, Math.ceil((snap.blockedUntil - checkedAt) / 60_000)) : null;
112
+ return {
113
+ ...base,
114
+ status: 'fail',
115
+ detail: `edge firewall 403 (${snap.lastAction ?? 'deny'}) since ${since}, ${snap.deniedCount} denied${rid}${left ? `; retrying in ${left} min` : ''}`,
116
+ fixHint: WEBAPP_EDGE_FIX_HINT,
117
+ };
118
+ }
88
119
  export function createReadinessCycleState() {
89
120
  return { consecutiveReachFailures: 0 };
90
121
  }
@@ -126,6 +157,19 @@ export async function collectReadiness(opts, bootWarmup = false, deps = {}) {
126
157
  detail: `${opts.toolCount} tools`,
127
158
  checkedAt: now,
128
159
  }));
160
+ // reefclaw_api_reachable — the shared edge gate's verdict on the webapp
161
+ // itself. Omitted while nothing has ever been denied. NOTE: when this row
162
+ // is 'fail' the report usually cannot be POSTed (the POST is what is being
163
+ // denied) — the connector carries the same episode over the relay
164
+ // (agent_state health.webappApi), which is how the dashboard learns of it.
165
+ try {
166
+ const edgeRow = webappApiCheck((deps.webappEdgeSnapshot ?? (() => webappEdgeGate().snapshot()))(), now);
167
+ if (edgeRow)
168
+ checks.push(edgeRow);
169
+ }
170
+ catch (err) {
171
+ logger.warn(TAG, `edge-gate snapshot failed (row omitted): ${formatError(err)}`);
172
+ }
129
173
  // live_stop_protection — a local config/adapter read, no network. Resolved
130
174
  // per cycle so a paper→live flip surfaces on the next report without a
131
175
  // restart. Resolver failure → omit the row (absent evidence stays absent).
@@ -306,17 +350,30 @@ async function postReadiness(apiBaseUrl, token, report, fetchImpl, timeoutMs) {
306
350
  const ac = new AbortController();
307
351
  const tid = setTimeout(() => ac.abort(), timeoutMs);
308
352
  try {
353
+ const startedAt = Date.now();
309
354
  const res = await fetchImpl(url, {
310
355
  method: 'POST',
311
- headers: {
312
- 'content-type': 'application/json',
313
- authorization: `Bearer ${token}`,
314
- },
356
+ headers: webappHeaders(token, { 'content-type': 'application/json' }),
315
357
  body: JSON.stringify(report),
316
358
  signal: ac.signal,
317
359
  });
318
360
  if (res.status < 200 || res.status >= 300) {
319
- logger.warn(TAG, `POST ${url} → ${res.status}`);
361
+ let bodyText = null;
362
+ if (res.status === 403) {
363
+ try {
364
+ bodyText = (await res.text()).slice(0, 200);
365
+ }
366
+ catch {
367
+ /* classify on headers alone */
368
+ }
369
+ }
370
+ const edge = noteWebappResponse(res, '/api/internal/agent-readiness', bodyText);
371
+ // The gate logs the episode once at warn; repeats stay at debug.
372
+ const level = edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn';
373
+ logger[level](TAG, `POST ${url} → ${res.status}${edge ? ` (edge firewall ${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''} — not an account problem)` : ''}`);
374
+ }
375
+ else {
376
+ noteWebappResponse(res, '/api/internal/agent-readiness', undefined, startedAt);
320
377
  }
321
378
  }
322
379
  catch (err) {
@@ -364,10 +421,23 @@ export function startReadinessReporter(opts) {
364
421
  installChannel: opts.installChannel,
365
422
  runtime: opts.runtime,
366
423
  }, bootWarmup, { state });
367
- await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
424
+ if (webappEdgeGate().isBlocked()) {
425
+ // Every POST during the block is another denied request feeding it.
426
+ // The gate reopens on its own (≤30 min); the next cycle re-probes.
427
+ logger.debug(TAG, `readiness POST skipped — webapp edge-denied (${Math.ceil(webappEdgeGate().msUntilOpen() / 60_000)} min left)`);
428
+ }
429
+ else {
430
+ await postReadiness(opts.apiBaseUrl, opts.token, report, fetchImpl, timeoutMs);
431
+ }
368
432
  if (report.overall === 'fail') {
369
- const failing = report.checks.filter((c) => c.status === 'fail').map((c) => c.id).join(', ');
370
- logger.warn(TAG, `readiness FAIL: ${failing}`);
433
+ // The edge row is already logged (once) by the gate — repeating it
434
+ // every 5 min as "readiness FAIL" would alarm a customer for nothing.
435
+ const failing = report.checks
436
+ .filter((c) => c.status === 'fail' && c.id !== 'reefclaw_api_reachable')
437
+ .map((c) => c.id)
438
+ .join(', ');
439
+ if (failing)
440
+ logger.warn(TAG, `readiness FAIL: ${failing}`);
371
441
  }
372
442
  }
373
443
  catch (err) {
@@ -25,6 +25,7 @@
25
25
  // background. In-flight requests are tracked so `drain()` can be awaited at
26
26
  // shutdown to avoid losing the last fills before stop.
27
27
  import { logger, formatError } from '../logger.js';
28
+ import { noteWebappResponse, webappEdgeGate, webappHeaders } from '../http/webapp-edge.js';
28
29
  import { retryAfterMs, sleepMs } from './retry-after.js';
29
30
  const TAG = 'trade-store-client';
30
31
  export class TradeStoreClient {
@@ -75,19 +76,23 @@ export class TradeStoreClient {
75
76
  async run(userId, fill) {
76
77
  const url = `${this.opts.baseUrl}/api/internal/trades`;
77
78
  const body = JSON.stringify(fill);
79
+ // Fill WRITES are never gated: the trades ledger has no other ingress
80
+ // (the gap filler only runs on a WS resync), a fill is a rare one-off
81
+ // call, and the ban may have lifted since the gate closed. If the edge
82
+ // still denies us, the 403 below drops the row exactly as before.
78
83
  for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
79
84
  try {
80
85
  const ac = new AbortController();
81
86
  const tid = setTimeout(() => ac.abort(), this.opts.requestTimeoutMs);
82
87
  let res;
88
+ const startedAt = Date.now();
83
89
  try {
84
90
  res = await this.opts.fetchImpl(url, {
85
91
  method: 'POST',
86
- headers: {
92
+ headers: webappHeaders(this.opts.ingestToken, {
87
93
  'content-type': 'application/json',
88
- authorization: `Bearer ${this.opts.ingestToken}`,
89
94
  'x-user-id': userId,
90
- },
95
+ }),
91
96
  body,
92
97
  signal: ac.signal,
93
98
  });
@@ -97,6 +102,7 @@ export class TradeStoreClient {
97
102
  }
98
103
  if (res.status >= 200 && res.status < 300) {
99
104
  this.totalSucceeded++;
105
+ noteWebappResponse(res, '/api/internal/trades', undefined, startedAt);
100
106
  return;
101
107
  }
102
108
  if (res.status === 429) {
@@ -110,8 +116,23 @@ export class TradeStoreClient {
110
116
  else if (res.status >= 400 && res.status < 500) {
111
117
  // Terminal — re-tries won't change the outcome. 409 is a duplicate
112
118
  // (idempotency win); 400/401/404 are bugs we want logged loudly.
119
+ // A 403 from the EDGE (not the app) is named as such: it is the
120
+ // host being blocked, not a caller bug.
113
121
  this.totalDroppedTerminal++;
114
- logger.warn(TAG, `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
122
+ let errBody = '';
123
+ if (res.status === 403) {
124
+ try {
125
+ errBody = (await res.text()).slice(0, 200);
126
+ }
127
+ catch {
128
+ // ignore
129
+ }
130
+ }
131
+ const edge = noteWebappResponse(res, '/api/internal/trades', errBody);
132
+ // The gate logs the episode once at warn; repeats stay at debug.
133
+ logger[edge && webappEdgeGate().snapshot().deniedCount > 1 ? 'debug' : 'warn'](TAG, edge
134
+ ? `POST ${url} → 403 from the edge firewall (${edge.action ?? 'deny'}${edge.requestId ? `, request ${edge.requestId}` : ''}) — dropped; not an account/token problem. userId=${userId} tradeId=${fill.exchangeTradeId}`
135
+ : `POST ${url} → ${res.status} (terminal, dropped). userId=${userId} tradeId=${fill.exchangeTradeId}`);
115
136
  return;
116
137
  }
117
138
  else {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.47",
4
+ "version": "0.1.49",
5
5
  "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
6
6
  "author": "ReefClaw",
7
7
  "activation": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.47",
3
+ "version": "0.1.49",
4
4
  "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -33,5 +33,15 @@
33
33
  "index.js": "833343d35aeecb17f77ebb23ab816abae8df9c0d1d2dbf6c0f0622e96d7cd5a1",
34
34
  "tools/create-order.js": "b0244ff69cb5b4a44e18c7ceaf91669ee19649d0e6b18bb857aa47ca80f63b2a",
35
35
  "risk/pre-trade-check.js": "15ba2c91e7a1f5ea03a2452eda40d489eda406a434e3bc3e9b7e024190f6a22f"
36
+ },
37
+ "0.1.47": {
38
+ "index.js": "47477ea63083abeb07c3088481acd723c0366a9170f6069a67a055362f61a878",
39
+ "tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
40
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
41
+ },
42
+ "0.1.48": {
43
+ "index.js": "7ee02a477ed7a508cc0e628f011eb5055e9dc6ad65a383f4830ac4a881c77832",
44
+ "tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
45
+ "risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
36
46
  }
37
47
  }
@@ -17,5 +17,7 @@
17
17
  "0.1.43": "Connector fixes. The ReefClaw heartbeat is now created even when your OpenClaw already has its own job named like a heartbeat (before, the connector could mistake that job for ours, so the agent's trading heartbeat never ran); a box affected by this repairs itself after updating. The trading instructions (SKILL.md) are re-applied correctly when an older copy is found, instead of failing on every reconnect.",
18
18
  "0.1.44": "Heartbeats on a box without a chat channel (no Telegram etc.) are no longer recorded as errors: the heartbeat job is created without a chat delivery, existing jobs are repaired automatically, and a failed announcement no longer counts as a failed heartbeat. get_regime, get_crypto_metrics and get_market_intel now work when called without arguments (they default to your trading symbol / the overview category), which removes the rejected calls seen on OpenClaw 2026.9.",
19
19
  "0.1.45": "Every market-data and analysis tool now works when called without a symbol (it uses your configured trading symbol), so agents on OpenClaw 2026.9 no longer waste calls on rejected arguments. Trading actions still require an explicit symbol. The heartbeat prompt no longer sends the agent looking for a checklist file that is not installed.",
20
- "0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped."
20
+ "0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped.",
21
+ "0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only.",
22
+ "0.1.49": "Fixes for new and stuck agents. On a fresh install the first market check now starts as soon as the full trading instructions arrive, instead of 15 minutes after connecting. An agent whose ReefClaw heartbeat was never created, because an older version mistook one of your own scheduled jobs for it, now gets the heartbeat with this update and runs its first check straight away. The heartbeat job can no longer be created twice when the gateway answers slowly. New installs from the dashboard's paste message start on the exchange you picked there. New entries now need a stop at least 0.3 x ATR away, the rule the order checks always described (only the 30 bps minimum was enforced before); when ATR is unavailable the 30 bps minimum applies as before. The local signal evaluator (off by default) applies the same minimum stop distance as the server."
21
23
  }
@@ -1,3 +1,16 @@
1
1
  import type { MarketContext, Direction } from './types.js';
2
2
  import type { StopRuleConfig, ConditionContext } from './conditions/types.js';
3
+ /** Discipline floor for a protective stop, mirrored from the plugin's
4
+ * create_order gate (`validateProtectiveGeometry`): the stop must sit at
5
+ * least max(0.3 × ATR, 30 bps of price) from entry. Applied at SIGNAL time
6
+ * by the strategy adapter and again at FILL time by the backtest engine, so
7
+ * a stop that no exchange order could carry never becomes a signal or a
8
+ * simulated trade (2026-09-28: the swing_atr rule with swingCount 1 was
9
+ * landing stops at or above price after a breakdown; the unsigned risk then
10
+ * produced wrong-side targets and, in the backtester, near-zero-risk trades
11
+ * sized to tens of millions of notional — see
12
+ * memory/project_ardi_report10_backtest_geometry_sep28.md). */
13
+ export declare const MIN_STOP_DISTANCE_BPS = 30;
14
+ export declare const MIN_STOP_ATR_FRACTION = 0.3;
15
+ export declare function stopDistanceFloor(price: number, atr14: number): number;
3
16
  export declare function computeStop(rule: StopRuleConfig, ctx: MarketContext, direction: Direction, condCtx: ConditionContext): number;
@@ -7,6 +7,22 @@
7
7
  // @reefclaw/shared runtime code across the deploy boundary.
8
8
  // Stop level calculation for declarative strategies.
9
9
  import { findSwingPoints } from '../shared/indicators.js';
10
+ /** Discipline floor for a protective stop, mirrored from the plugin's
11
+ * create_order gate (`validateProtectiveGeometry`): the stop must sit at
12
+ * least max(0.3 × ATR, 30 bps of price) from entry. Applied at SIGNAL time
13
+ * by the strategy adapter and again at FILL time by the backtest engine, so
14
+ * a stop that no exchange order could carry never becomes a signal or a
15
+ * simulated trade (2026-09-28: the swing_atr rule with swingCount 1 was
16
+ * landing stops at or above price after a breakdown; the unsigned risk then
17
+ * produced wrong-side targets and, in the backtester, near-zero-risk trades
18
+ * sized to tens of millions of notional — see
19
+ * memory/project_ardi_report10_backtest_geometry_sep28.md). */
20
+ export const MIN_STOP_DISTANCE_BPS = 30;
21
+ export const MIN_STOP_ATR_FRACTION = 0.3;
22
+ export function stopDistanceFloor(price, atr14) {
23
+ const atrFloor = Number.isFinite(atr14) && atr14 > 0 ? atr14 * MIN_STOP_ATR_FRACTION : 0;
24
+ return Math.max(atrFloor, price * (MIN_STOP_DISTANCE_BPS / 10_000));
25
+ }
10
26
  export function computeStop(rule, ctx, direction, condCtx) {
11
27
  switch (rule.type) {
12
28
  case 'swing_atr': {
@@ -14,15 +30,28 @@ export function computeStop(rule, ctx, direction, condCtx) {
14
30
  const atrFraction = (rule.params.atrFraction ?? 0.3) * ctx.atr14;
15
31
  const fallbackAtrMult = rule.params.fallbackAtrMultiple ?? 2;
16
32
  const swings = findSwingPoints(ctx.ohlcv1h.slice(-48), 3);
33
+ // A confirmed swing is always ≥3 bars old. When price has since broken
34
+ // THROUGH it (a breakdown below the last swing low on a long, a breakout
35
+ // above the last swing high on a short), or sits so close that the
36
+ // derived stop is inside the discipline floor, the structural level is
37
+ // not a usable stop — treat both exactly like "no swing" and fall back
38
+ // to the ATR stop. Falling back only on the wrong-side case would leave
39
+ // a dead band (a shallow breakdown yields no signal while a deeper one
40
+ // re-arms on the fallback); the floor check makes the rule continuous.
41
+ const floor = stopDistanceFloor(ctx.currentPrice, ctx.atr14);
17
42
  if (direction === 'LONG') {
18
- return swings.lows.length > 0
19
- ? Math.min(...swings.lows.slice(-swingCount)) - atrFraction
20
- : ctx.currentPrice - ctx.atr14 * fallbackAtrMult;
43
+ const fallback = ctx.currentPrice - ctx.atr14 * fallbackAtrMult;
44
+ if (swings.lows.length === 0)
45
+ return fallback;
46
+ const level = Math.min(...swings.lows.slice(-swingCount)) - atrFraction;
47
+ return ctx.currentPrice - level >= floor ? level : fallback;
21
48
  }
22
49
  else {
23
- return swings.highs.length > 0
24
- ? Math.max(...swings.highs.slice(-swingCount)) + atrFraction
25
- : ctx.currentPrice + ctx.atr14 * fallbackAtrMult;
50
+ const fallback = ctx.currentPrice + ctx.atr14 * fallbackAtrMult;
51
+ if (swings.highs.length === 0)
52
+ return fallback;
53
+ const level = Math.max(...swings.highs.slice(-swingCount)) + atrFraction;
54
+ return level - ctx.currentPrice >= floor ? level : fallback;
26
55
  }
27
56
  }
28
57
  case 'recent_extreme_atr': {
@@ -8,7 +8,7 @@
8
8
  import { evaluateConditions } from './conditions/registry.js';
9
9
  import { resolveDirection } from './direction-rules.js';
10
10
  import { computeEntry } from './entry-rules.js';
11
- import { computeStop } from './stop-rules.js';
11
+ import { computeStop, stopDistanceFloor } from './stop-rules.js';
12
12
  import { computeATR } from '../shared/indicators.js';
13
13
  /**
14
14
  * Higher-timeframe tick gating state, keyed by
@@ -192,18 +192,37 @@ export function adaptStrategy(config, gateNamespace) {
192
192
  }
193
193
  const allMet = finalConditions.every(c => c.met);
194
194
  let trade;
195
+ let geometryRejection;
195
196
  if (allMet && direction) {
196
197
  const entryZone = computeEntry(config.entryRule, ectx, direction, condCtx);
197
198
  const stopLevel = computeStop(config.stopRule, ectx, direction, condCtx);
199
+ // SIGNED risk: negative means the stop is on the wrong side of the
200
+ // signal price. Before 2026-09-28 this was used unsigned — a stop
201
+ // above a long's price produced targets BELOW it and the backtester
202
+ // took |risk|, so a 2-cent stop became a $17M-notional "trade".
198
203
  const risk = direction === 'LONG'
199
204
  ? ectx.currentPrice - stopLevel
200
205
  : stopLevel - ectx.currentPrice;
201
- const targets = config.targetRMultiples.map(rm => direction === 'LONG'
202
- ? ectx.currentPrice + risk * rm
203
- : ectx.currentPrice - risk * rm);
204
- trade = { entryZone, stopLevel, targets };
206
+ const floor = stopDistanceFloor(ectx.currentPrice, ectx.atr14);
207
+ // `!(risk >= floor)` also catches NaN (a NaN stop must never emit).
208
+ if (!(risk >= floor)) {
209
+ geometryRejection = {
210
+ reason: !Number.isFinite(risk) ? 'invalid' : risk <= 0 ? 'wrong_side' : 'below_floor',
211
+ stopLevel,
212
+ risk,
213
+ floor,
214
+ };
215
+ }
216
+ else {
217
+ const targets = config.targetRMultiples.map(rm => direction === 'LONG'
218
+ ? ectx.currentPrice + risk * rm
219
+ : ectx.currentPrice - risk * rm);
220
+ trade = { entryZone, stopLevel, targets };
221
+ }
205
222
  }
206
- return { direction, conditions: finalConditions, trade };
223
+ return geometryRejection
224
+ ? { direction, conditions: finalConditions, trade, geometryRejection }
225
+ : { direction, conditions: finalConditions, trade };
207
226
  },
208
227
  };
209
228
  }
@@ -101,7 +101,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
101
101
  If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
102
102
 
103
103
  ```
104
- npx --yes @reefclaw/connect@0.1.60
104
+ npx --yes @reefclaw/connect@0.1.62
105
105
  ```
106
106
 
107
107
  That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
@@ -1,8 +1,14 @@
1
1
  import type { RealizationRule } from '../simulator/types.js';
2
2
  /** Minimum pre-entry stop distance in basis points (the SKILL v2.10.0
3
- * discipline floor's fixed component; the ATR component is enforced by the
4
- * live bracket path where ATR is authoritative). */
3
+ * discipline floor's fixed component). ★ 2026-09-29: the 0.3×ATR component
4
+ * used to exist ONLY in the error text — no code path enforced it (a
5
+ * customer read the compiled module and said so). It is now applied here
6
+ * whenever the caller can supply `atr14` (create_order reads it from the
7
+ * cached intel fact; absent → the fixed 30 bps floor alone, fail-open). */
5
8
  export declare const MIN_STOP_DISTANCE_BPS = 30;
9
+ /** Re-exported from the synced signal-side floor so the two can never drift
10
+ * (plugin/src/signals/stop-rules.ts is generated from shared/). */
11
+ export { MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
6
12
  export interface ProtectiveGeometryArgs {
7
13
  side: 'buy' | 'sell';
8
14
  /** Reference entry price: the limit price, or last trade for market orders. */
@@ -10,6 +16,8 @@ export interface ProtectiveGeometryArgs {
10
16
  stopPrice?: number;
11
17
  invalidationPrice?: number;
12
18
  targetPrice?: number;
19
+ /** ATR(14) in price units when known; enables the 0.3×ATR floor term. */
20
+ atr14?: number;
13
21
  }
14
22
  /** Validate stop / invalidation / target geometry against the entry side.
15
23
  *
@@ -13,11 +13,18 @@
13
13
  // live mode.
14
14
  // Tested in: assessment-validation.test.ts.
15
15
  import { normalizeBracketSymbol } from '../live/bracket-ledger.js';
16
+ import { stopDistanceFloor, MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
16
17
  // ---- protective geometry (create_order, issue #200) ----
17
18
  /** Minimum pre-entry stop distance in basis points (the SKILL v2.10.0
18
- * discipline floor's fixed component; the ATR component is enforced by the
19
- * live bracket path where ATR is authoritative). */
19
+ * discipline floor's fixed component). ★ 2026-09-29: the 0.3×ATR component
20
+ * used to exist ONLY in the error text — no code path enforced it (a
21
+ * customer read the compiled module and said so). It is now applied here
22
+ * whenever the caller can supply `atr14` (create_order reads it from the
23
+ * cached intel fact; absent → the fixed 30 bps floor alone, fail-open). */
20
24
  export const MIN_STOP_DISTANCE_BPS = 30;
25
+ /** Re-exported from the synced signal-side floor so the two can never drift
26
+ * (plugin/src/signals/stop-rules.ts is generated from shared/). */
27
+ export { MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
21
28
  /** Validate stop / invalidation / target geometry against the entry side.
22
29
  *
23
30
  * Before this existed the wrong-side check ran ONLY on the wave9 path
@@ -41,10 +48,17 @@ export function validateProtectiveGeometry(args) {
41
48
  `protective stop must be ${side === 'buy' ? 'below' : 'above'} entry. A wrong-side stop is ` +
42
49
  `instantly "breached" and the stop-watcher closes the position seconds after entry.`);
43
50
  }
44
- const distanceBps = (Math.abs(refPrice - stop) / refPrice) * 10_000;
45
- if (distanceBps < MIN_STOP_DISTANCE_BPS) {
51
+ const distance = Math.abs(refPrice - stop);
52
+ const distanceBps = (distance / refPrice) * 10_000;
53
+ const atr = typeof args.atr14 === 'number' && Number.isFinite(args.atr14) && args.atr14 > 0 ? args.atr14 : null;
54
+ // stopDistanceFloor = max(0.3×ATR, 30 bps of price); with no ATR it is the bps term alone.
55
+ const floor = stopDistanceFloor(refPrice, atr ?? 0);
56
+ if (distance < floor) {
57
+ const atrNote = atr !== null
58
+ ? `0.3×ATR = ${(atr * MIN_STOP_ATR_FRACTION / refPrice * 10_000).toFixed(1)}bps (ATR ${atr.toPrecision(4)}) and `
59
+ : '';
46
60
  return (`stopPrice ${stop} is only ${distanceBps.toFixed(1)}bps from entry ${refPrice} — below the ` +
47
- `${MIN_STOP_DISTANCE_BPS}bps discipline floor. Place the stop at a structural level ` +
61
+ `discipline floor of max(${atrNote}${MIN_STOP_DISTANCE_BPS}bps). Place the stop at a structural level ` +
48
62
  `(≥ max(0.3×ATR, ${MIN_STOP_DISTANCE_BPS}bps) from entry).`);
49
63
  }
50
64
  }
@@ -77,6 +77,10 @@ export declare function createOrderTool(args: {
77
77
  available: boolean;
78
78
  active: boolean;
79
79
  }>;
80
+ /** ATR(14) for the symbol (price units) for the protective-geometry
81
+ * floor's 0.3×ATR term. Optional and FAIL-OPEN: null/throw/slow (>2 s)
82
+ * → the fixed 30 bps floor alone, exactly the pre-2026-09-29 behaviour. */
83
+ readAtr14?: (symbol: string) => Promise<number | null>;
80
84
  refreshPaperState?: () => void;
81
85
  wave9TradingModeCheck?: () => string;
82
86
  wave9VenueCheck?: () => string;
@@ -1006,12 +1006,27 @@ export async function createOrderTool(args, deps) {
1006
1006
  // by the stop-watcher seconds later (7 sub-5-minute kills on the 2026-07 HL
1007
1007
  // soak — one spawned the −$117.86 journal fabrication of issue #199).
1008
1008
  if (!wave9Claimed) {
1009
+ // ATR term of the floor (2026-09-29). Bounded so a slow intel read can
1010
+ // never delay an order by more than 2 s; any failure = no ATR = 30 bps only.
1011
+ let atr14;
1012
+ if (deps.readAtr14 && args.stopPrice !== undefined) {
1013
+ // Promise.resolve().then(...) also converts a SYNCHRONOUS throw from the
1014
+ // dep into a rejection — the outer catch would otherwise refuse the
1015
+ // entry (fail-closed) against this gate's fail-open contract.
1016
+ const reader = deps.readAtr14;
1017
+ const read = Promise.resolve().then(() => reader(args.symbol)).catch(() => null);
1018
+ const timeout = new Promise(resolve => { const t = setTimeout(() => resolve(null), 2_000); t.unref?.(); });
1019
+ const v = await Promise.race([read, timeout]);
1020
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0)
1021
+ atr14 = v;
1022
+ }
1009
1023
  const geometryError = validateProtectiveGeometry({
1010
1024
  side: side,
1011
1025
  refPrice: orderPrice,
1012
1026
  stopPrice: args.stopPrice,
1013
1027
  invalidationPrice: args.invalidation_price,
1014
1028
  targetPrice: args.target_price,
1029
+ atr14,
1015
1030
  });
1016
1031
  if (geometryError) {
1017
1032
  return { error: `create_order rejected (protective geometry): ${geometryError}` };
@@ -1,3 +1,6 @@
1
+ /** What the agent is told when the EDGE (not the app) denies the host. Names
2
+ * the real cause; the old branch called every 403 a subscription problem. */
3
+ export declare const MARKET_INTEL_EDGE_DENIED_MESSAGE: string;
1
4
  export type MarketIntelCategory = 'sentiment' | 'news' | 'calendar' | 'overview' | 'derivatives' | 'onchain' | 'social';
2
5
  export interface MarketIntelDeps {
3
6
  connectionToken: string;
@@ -13,6 +13,11 @@
13
13
  // order (the create_order gate still applies) — and makes injected directives
14
14
  // far less likely to be followed.
15
15
  import { keepAliveFetch } from '../http/keepalive-fetch.js';
16
+ import { noteWebappResponse, webappEdgeGate, webappUserAgent } from '../http/webapp-edge.js';
17
+ /** What the agent is told when the EDGE (not the app) denies the host. Names
18
+ * the real cause; the old branch called every 403 a subscription problem. */
19
+ export const MARKET_INTEL_EDGE_DENIED_MESSAGE = "ReefClaw's edge firewall is currently denying this host's IP (automatic DDoS mitigation — not a subscription or token problem). " +
20
+ 'Market intelligence is unavailable until it lifts (usually within 30 minutes); trading continues normally with exchange data.';
16
21
  /** Categories whose payloads contain attacker-influenceable free text.
17
22
  * `overview` carries CoinGecko coin names / trending titles and `sentiment`
18
23
  * carries provider labels — third-party strings like the other three
@@ -99,16 +104,34 @@ export async function getMarketIntelTool(args, deps) {
99
104
  if (symbols?.length) {
100
105
  url.searchParams.set('symbols', symbols.join(','));
101
106
  }
107
+ // Edge-denied host: answer without a request (each one feeds the block).
108
+ if (webappEdgeGate().isBlocked()) {
109
+ return { error: MARKET_INTEL_EDGE_DENIED_MESSAGE };
110
+ }
102
111
  try {
112
+ const startedAt = Date.now();
103
113
  const res = await keepAliveFetch(url.toString(), {
104
- headers: { Authorization: `Bearer ${connectionToken}` },
114
+ // Capitalised key on purpose: the tool test pins `headers.Authorization`.
115
+ headers: { Authorization: `Bearer ${connectionToken}`, 'user-agent': webappUserAgent() },
105
116
  signal: AbortSignal.timeout(10_000),
106
117
  });
107
118
  if (res.status === 403) {
119
+ let bodyText = null;
120
+ try {
121
+ bodyText = (await res.text()).slice(0, 200);
122
+ }
123
+ catch {
124
+ /* classify on headers alone */
125
+ }
126
+ if (noteWebappResponse(res, url.pathname, bodyText)) {
127
+ return { error: MARKET_INTEL_EDGE_DENIED_MESSAGE };
128
+ }
108
129
  return {
109
130
  error: 'Market intelligence requires a Pro subscription at reefclaw.com. Trading continues normally with Binance data.',
110
131
  };
111
132
  }
133
+ if (res.ok)
134
+ noteWebappResponse(res, url.pathname, undefined, startedAt);
112
135
  if (res.status === 401) {
113
136
  return { error: 'Invalid or expired ReefClaw connection token.' };
114
137
  }
@@ -23,3 +23,17 @@ export declare function getStrategiesCached(deps: IntelApiDeps): Promise<Strateg
23
23
  export declare const __testing__: {
24
24
  resetCaches(): void;
25
25
  };
26
+ export declare function _resetAtrLastKnownGoodForTests(): void;
27
+ /** ATR(14) for the symbol (price units), for create_order's stop-distance
28
+ * floor. Venue-aware symbol resolution mirrors get_setup_detail (the raw
29
+ * 'AVAX/USDC' form never hits the HL_ cache key). Order of preference:
30
+ * a fact returned within the budget → its atr14 (and remember it);
31
+ * otherwise the last-known-good value if younger than 30 min; otherwise
32
+ * null — the caller fails open to the fixed 30 bps floor. Never throws. */
33
+ export declare function readAtr14FromFacts(rawSymbol: string, deps: IntelApiDeps, opts?: {
34
+ getFact?: (symbol: string, deps: IntelApiDeps) => Promise<SymbolFact | {
35
+ error: string;
36
+ }>;
37
+ now?: () => number;
38
+ budgetMs?: number;
39
+ }): Promise<number | null>;