@reefclaw/openclaw-plugin 0.1.33 → 0.1.35

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.
@@ -7,7 +7,7 @@ import { homedir } from 'os';
7
7
  import { logger, formatError } from '../logger.js';
8
8
  import { isTradingMode } from '../types.js';
9
9
  import { deriveModelHealth } from '../model-health.js';
10
- import { handshakeLacksWriteScope, isDeviceIdentityRejection, relaxGatewayDeviceAuth } from '../config.js';
10
+ import { describeGatewayWriteScopeRemedy, handshakeLacksWriteScope, isDeviceIdentityRejection } from '../config.js';
11
11
  import { toIntelSymbol } from '@reefclaw/shared';
12
12
  import { GatewayHttpClient } from '../gateway/gateway-http-client.js';
13
13
  import { GatewayWsClient } from '../gateway/gateway-ws-client.js';
@@ -16,10 +16,10 @@ import { EventParser, mapCcxtBalance, mapCcxtOrder, extractLiquidationFields, ex
16
16
  import { Poller } from '../gateway/poller.js';
17
17
  import { ensureHeartbeatCron, isHeartbeatLikeName } from '../gateway/heartbeat-cron.js';
18
18
  import { parseIdentityName } from '../utils/identity-name.js';
19
- import { computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
19
+ import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
20
20
  import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
21
21
  import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
22
- import { startConnectorUpdate, runConnectorUpdate, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
22
+ import { startConnectorUpdate, runConnectorUpdate, fetchPinnedConnectVersion, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
23
23
  import { DEFAULT_AGENT_ID, isForeignAgentEvent, resolveAgentEventOwner } from '../gateway/agent-scope.js';
24
24
  const TAG = 'gateway';
25
25
  // ---- Day-start NAV persistence ----
@@ -758,10 +758,11 @@ export class GatewayProvider {
758
758
  * Operator-only. Update the ReefClaw connector on this box to the latest
759
759
  * published version.
760
760
  *
761
- * Runs `npx -y @reefclaw/connect@latest` over the gateway's PTY. There is no
762
- * command/version/args parameter and there never should be — the whole
763
- * security argument for this feature is that the string is a constant (see
764
- * providers/connector-update.ts).
761
+ * Runs the connect installer over the gateway's PTY, pinned to the exact
762
+ * connector release ReefClaw's public release endpoint reports. The
763
+ * RPC carries no command/version/args parameter and never should — the
764
+ * version is looked up server-side by this process, never taken from the
765
+ * caller (see providers/connector-update.ts).
765
766
  *
766
767
  * The installer restarts the gateway when it finishes, which kills both the
767
768
  * PTY and this process's own transport. That is the SUCCESS path: we report
@@ -792,6 +793,12 @@ export class GatewayProvider {
792
793
  const blocked = checkPositionGuard(guardArgs);
793
794
  if (blocked)
794
795
  return blocked;
796
+ // Which version? Only the one ReefClaw vouches for, fetched by THIS
797
+ // process from the public release endpoint — never `@latest`, never a
798
+ // caller-supplied string. No confirmed version ⇒ no update.
799
+ const pinned = await fetchPinnedConnectVersion({});
800
+ if (!pinned.ok)
801
+ return pinned.outcome;
795
802
  // terminal.* is operator.admin-only (OpenClaw method-scopes, since 2026.7).
796
803
  // The long-lived session runs on operator.read/write by design, so open a
797
804
  // SEPARATE short-lived admin session for this update. Reconnects are
@@ -808,7 +815,7 @@ export class GatewayProvider {
808
815
  if (!session.ok)
809
816
  return session.outcome;
810
817
  const rpc = (method, params) => admin.sendRpc(method, params);
811
- const started = await startConnectorUpdate(rpc, guardArgs);
818
+ const started = await startConnectorUpdate(rpc, guardArgs, pinned.version);
812
819
  if (started.status !== 'started' || !started.sessionId) {
813
820
  admin.destroy();
814
821
  return started;
@@ -1258,7 +1265,7 @@ export class GatewayProvider {
1258
1265
  logger.error(TAG, `positions handler failed: ${formatError(err)}`);
1259
1266
  });
1260
1267
  },
1261
- onBalance: (balance) => this.onPollerBalance(balance),
1268
+ onBalance: (balance, extras) => this.onPollerBalance(balance, extras),
1262
1269
  onOpenOrders: (orders) => this.onPollerOpenOrders(orders),
1263
1270
  onMarketStructure: (data) => this.onPollerMarketStructure(data),
1264
1271
  onCryptoMetrics: (data) => this.onPollerCryptoMetrics(data),
@@ -1290,37 +1297,26 @@ export class GatewayProvider {
1290
1297
  });
1291
1298
  this.wsClient.on('agent', (payload) => this.onAgentEvent(payload));
1292
1299
  }
1293
- /** Whether we've already acted on a missing write scope this process. */
1294
- writeScopeRelaxationApplied = false;
1295
- /** Least-privilege escalation, gated on evidence. Some OpenClaw builds strip
1296
- * `operator.write` from a WS connection with no device identity; without it
1297
- * the bridge cannot place or cancel orders. Rather than pre-emptively
1298
- * relaxing every user's gateway auth at install time (what we did until
1299
- * 2026-07-29), we read the scopes the gateway ACTUALLY granted and relax
1300
- * only when it demonstrably withheld the one we need. On the supported
1301
- * range the scope survives and nothing is written. */
1302
- deviceIdentityRelaxationApplied = false;
1300
+ /** The gateway withheld `operator.write` from this connection (or rejected
1301
+ * the handshake for missing device identity). The connector used to react
1302
+ * by writing OpenClaw's legacy auth-relaxation flags itself (2026-07-29 →
1303
+ * 2026-09-19). It no longer touches the gateway's auth settings at all: it
1304
+ * reports the exact manual remedy once per process and leaves the decision
1305
+ * to the operator. */
1306
+ writeScopeRemedyReported = false;
1303
1307
  /** Handshake rejected outright for missing device identity (see
1304
- * isDeviceIdentityRejection). Same escalation as the withheld-write-scope
1308
+ * isDeviceIdentityRejection). Same report as the withheld-write-scope
1305
1309
  * case, keyed on the rejection instead of on hello-ok scopes. */
1306
1310
  onHandshakeRejectedForDeviceIdentity(reason) {
1307
- if (this.deviceIdentityRelaxationApplied)
1311
+ if (this.writeScopeRemedyReported)
1308
1312
  return;
1309
- this.deviceIdentityRelaxationApplied = true;
1313
+ this.writeScopeRemedyReported = true;
1310
1314
  const tried = this.wsClient?.getClientId() ?? 'unknown';
1311
1315
  logger.error(TAG, `Gateway REJECTED the connector handshake under every client identity (last: ${tried}): ${reason}. ` +
1312
- `OpenClaw >= 2026.9 admits only a local-backend client (gateway-client) or a device-paired one — ` +
1313
- `the retired gateway.controlUi relaxation no longer applies — and this gateway did neither. The ` +
1314
- `dashboard cannot reach this agent (no tools, no state, no updates) until the handshake completes.`);
1315
- // Last resort for OLDER builds only: on 2026.9+ the flags are retired and
1316
- // ignored (a config migration deletes them), so this is best-effort and
1317
- // says so.
1318
- const changed = relaxGatewayDeviceAuth(`the gateway rejected the connector handshake (${reason})`);
1319
- if (changed) {
1320
- logger.warn(TAG, 'Wrote the legacy gateway.controlUi relaxation flags in case this is an older OpenClaw build — ' +
1321
- 'RESTART the gateway to find out. On OpenClaw >= 2026.9 they are ignored: check the gateway ' +
1322
- 'auth config / device pairing instead.');
1323
- }
1316
+ `OpenClaw >= 2026.9 admits only a local-backend client (gateway-client) or a device-paired one, ` +
1317
+ `and this gateway did neither. The dashboard cannot reach this agent (no tools, no state, no ` +
1318
+ `updates) until the handshake completes. ` +
1319
+ describeGatewayWriteScopeRemedy(`the handshake was rejected: ${reason}`));
1324
1320
  this.agentMode = 'ERROR';
1325
1321
  this.emitAgentState();
1326
1322
  }
@@ -1328,21 +1324,11 @@ export class GatewayProvider {
1328
1324
  const scopes = helloOk.auth?.scopes;
1329
1325
  if (!handshakeLacksWriteScope(scopes))
1330
1326
  return;
1331
- if (this.writeScopeRelaxationApplied)
1327
+ if (this.writeScopeRemedyReported)
1332
1328
  return;
1333
- this.writeScopeRelaxationApplied = true;
1334
- logger.warn(TAG, `Gateway granted [${(scopes ?? []).join(', ')}] — operator.write is MISSING, ` +
1335
- `so order placement and cancellation would fail on this connection.`);
1336
- const changed = relaxGatewayDeviceAuth('the gateway completed a handshake without granting operator.write');
1337
- if (changed) {
1338
- logger.warn(TAG, 'Gateway config updated — RESTART the OpenClaw gateway to regain operator.write. ' +
1339
- 'Trading tools will keep failing until you do.');
1340
- }
1341
- else {
1342
- logger.error(TAG, 'operator.write is missing and the relaxation flags are ALREADY set — this is ' +
1343
- 'not the known device-identity case. Check gateway auth config; trading is ' +
1344
- 'blocked until the gateway grants operator.write.');
1345
- }
1329
+ this.writeScopeRemedyReported = true;
1330
+ logger.error(TAG, `Gateway granted [${(scopes ?? []).join(', ')}] — operator.write is MISSING. ` +
1331
+ describeGatewayWriteScopeRemedy('the handshake completed without operator.write'));
1346
1332
  }
1347
1333
  onWsConnected(helloOk) {
1348
1334
  if (!this.started)
@@ -1775,7 +1761,12 @@ export class GatewayProvider {
1775
1761
  const action = isClose ? 'CLOSE' : 'OPEN';
1776
1762
  this.emitTradeJournal(pos.symbol, side, action, quantity, fillPrice);
1777
1763
  }
1778
- onPollerBalance(balance) {
1764
+ onPollerBalance(balance, extras) {
1765
+ // Keep today's realized P&L as fresh as the wallet: the RED-zone
1766
+ // plausibility bound (assessDrawdownPlausibility) needs it on every
1767
+ // evaluation, and fetchFreshBalance() only runs on a reconnect snapshot.
1768
+ if (typeof extras?.realizedPnlToday === 'number')
1769
+ this.realizedPnlToday = extras.realizedPnlToday;
1779
1770
  // Defensive guard: never downgrade a known-good wallet balance to zero.
1780
1771
  // Binance Futures 429 rate-limits were causing fetchBalance responses
1781
1772
  // to come back with an empty currency map; mapCcxtBalance then returned
@@ -2577,10 +2568,13 @@ export class GatewayProvider {
2577
2568
  // only — a $186 account with a $20 short showed as -89% drawdown, triggering
2578
2569
  // an auto-flatten loop every minute. If we don't have fresh wallet data we
2579
2570
  // cannot trust the drawdown number; wait for the next poll.
2580
- // 3. Sanity floor: a single-minute drawdown more negative than -50% is
2581
- // physically impossible under normal market conditions on a bracketed
2582
- // account. If the math says worse than that, it's bad data — log loudly
2583
- // and skip instead of closing real positions on a calculation error.
2571
+ // 3. Plausibility bound (Ardi, report #6 — replaces the old "-50% feels
2572
+ // impossible" constant): a book cannot lose more than what is open
2573
+ // (at entry) plus what it already realized today. A claimed loss
2574
+ // beyond that is a calculation artifact — log loudly and refuse
2575
+ // instead of closing real positions on it. True at every account
2576
+ // size, paper and live alike; the -50% constant only remains as the
2577
+ // fallback while today's realized P&L is still unknown.
2584
2578
  // 4. Persistence debounce (issue #213): the balance poll and the position
2585
2579
  // snapshot are not atomic. In PAPER mode the simulator deducts FULL
2586
2580
  // NOTIONAL from the wallet at open, so in the seconds after a fill the
@@ -2629,19 +2623,40 @@ export class GatewayProvider {
2629
2623
  // component is the worse failure direction, so the tear only ever BUYS
2630
2624
  // TIME; past the ceiling the ordinary #213 debounce governs again.
2631
2625
  const tornSnapshotBlocks = !positionsCoverLatestFill && redForMs < MAX_TORN_SNAPSHOT_DEFER_MS;
2626
+ // Ardi #6: the claimed loss versus what THIS book could have lost —
2627
+ // computed from the same snapshot, so a torn one (missing notional)
2628
+ // shows up as a loss the known positions cannot explain.
2629
+ const plausibility = assessDrawdownPlausibility({
2630
+ sessionStartNav: this.sessionStartNav,
2631
+ equity: this.computeEquity(),
2632
+ positions: this.positions,
2633
+ realizedPnlToday: this.realizedPnlToday,
2634
+ });
2635
+ const impossibleForBook = plausibility.verdict === 'impossible' ||
2636
+ (plausibility.verdict === 'unknown' && metrics.utilization.dailyDrawdown < IMPOSSIBLE_DRAWDOWN);
2632
2637
  if (uptimeMs < STARTUP_GRACE_PERIOD_MS) {
2633
2638
  logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but within startup grace period (${Math.round(uptimeMs / 1000)}s) — skipping auto-flatten`);
2634
2639
  }
2635
2640
  else if (!this.hasReceivedBalance || this.balance.total <= 0) {
2636
2641
  logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but balance data is stale/missing (received=${this.hasReceivedBalance}, total=${this.balance.total}) — skipping auto-flatten, waiting for fresh wallet data`);
2637
2642
  }
2638
- else if (metrics.utilization.dailyDrawdown < IMPOSSIBLE_DRAWDOWN) {
2639
- logger.error(TAG, `RED zone drawdown ${(metrics.utilization.dailyDrawdown * 100).toFixed(1)}% exceeds sanity floor ${IMPOSSIBLE_DRAWDOWN * 100}% — refusing auto-flatten, likely equity calculation error (balance.total=${this.balance.total}, sessionStartNav=${this.sessionStartNav}, positions=${this.positions.length})`);
2643
+ else if (tornSnapshotBlocks) {
2644
+ // The snapshot is torn BY DEFINITION (a fill debited the wallet after
2645
+ // the last positions refresh) — the verdict is not evidence of
2646
+ // anything yet. Close the tear now instead of waiting out the 10 s
2647
+ // poll, and say so at info: this is the expected paper fill race,
2648
+ // not an alarm (it read as one — Ardi #6).
2649
+ logger.info(TAG, `RED verdict on a torn snapshot (${metrics.drawdownZoneMessage}; fill ${Math.round((Date.now() - this.lastFillAt) / 1000)}s ago, positions from ${Math.round((Date.now() - this.positionsUpdatedAt) / 1000)}s ago) — refreshing positions before judging it`);
2650
+ void this.poller?.refreshPositionsNow().catch((err) => {
2651
+ logger.debug(TAG, `positions refresh after torn snapshot failed: ${formatError(err)}`);
2652
+ });
2653
+ }
2654
+ else if (impossibleForBook) {
2655
+ logger.error(TAG, `RED zone drawdown ${(metrics.utilization.dailyDrawdown * 100).toFixed(1)}% is more than this book could have lost (claimed ${plausibility.claimedLossUsd.toFixed(2)} vs open-at-entry ${plausibility.entryGrossUsd.toFixed(2)} + realized-today ${plausibility.realizedLossUsd?.toFixed(2) ?? 'unknown'}${plausibility.verdict === 'unknown' ? `; sanity floor ${IMPOSSIBLE_DRAWDOWN * 100}%` : ''}) — refusing auto-flatten, equity input is wrong (balance.total=${this.balance.total}, sessionStartNav=${this.sessionStartNav}, positions=${this.positions.length})`);
2640
2656
  }
2641
2657
  else if (this.redZoneStreak < REQUIRED_RED_STREAK ||
2642
2658
  redForMs < MIN_RED_PERSISTENCE_MS ||
2643
- !survivedPositionsRefresh ||
2644
- tornSnapshotBlocks) {
2659
+ !survivedPositionsRefresh) {
2645
2660
  logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) — deferring auto-flatten until the verdict persists (streak ${this.redZoneStreak}/${REQUIRED_RED_STREAK}, ${Math.round(redForMs / 1000)}s/${MIN_RED_PERSISTENCE_MS / 1000}s, survivedPositionsRefresh=${survivedPositionsRefresh}, positionsCoverLatestFill=${positionsCoverLatestFill}, tornSnapshotBlocks=${tornSnapshotBlocks}). A fresh entry's notional reads as phantom drawdown until the position snapshot catches up (issues #213/#248); a real drawdown will persist and flatten on a later evaluation.`);
2646
2661
  }
2647
2662
  else {
@@ -233,7 +233,7 @@ export async function executeProvisionHlAgentWallet(ctx, args) {
233
233
  if (!tool || !ctx.http) {
234
234
  return {
235
235
  ok: false,
236
- message: 'hl_provision_agent_wallet tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
236
+ message: 'hl_provision_agent_wallet tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
237
237
  venue: 'hyperliquid',
238
238
  mode: 'PAPER',
239
239
  };
@@ -261,7 +261,7 @@ export async function executeSubmitHlAgentApproval(ctx, args) {
261
261
  if (!tool || !ctx.http) {
262
262
  return {
263
263
  ok: false,
264
- message: 'hl_submit_agent_approval tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
264
+ message: 'hl_submit_agent_approval tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
265
265
  };
266
266
  }
267
267
  try {
@@ -285,7 +285,7 @@ export async function executeHlAgentWalletStatus(ctx) {
285
285
  if (!tool || !ctx.http) {
286
286
  return {
287
287
  ok: false,
288
- message: 'hl_agent_wallet_status tool not available on gateway — update the ReefClaw plugin (npx @reefclaw/connect@latest)',
288
+ message: 'hl_agent_wallet_status tool not available on gateway — update the ReefClaw plugin (re-run the ReefClaw connect installer)',
289
289
  configured: false,
290
290
  };
291
291
  }
@@ -102,6 +102,37 @@ export declare function applyVolatilityAdjustment(baseLimits: RiskLimits, volFac
102
102
  export declare function getDrawdownZone(drawdownRatio: number, thresholds?: DrawdownThresholds): DrawdownZone;
103
103
  /** Human-readable message for a drawdown zone. */
104
104
  export declare function getDrawdownZoneMessage(zone: DrawdownZone, ratio: number): string;
105
+ export interface DrawdownPlausibility {
106
+ /** 'impossible' = the claimed loss exceeds what this book could have lost;
107
+ * 'unknown' = no session anchor or today's realized P&L not known yet. */
108
+ verdict: 'plausible' | 'impossible' | 'unknown';
109
+ claimedLossUsd: number;
110
+ /** Σ |contracts| × contractSize × entryPrice — what computeEquity adds back. */
111
+ entryGrossUsd: number;
112
+ realizedLossUsd: number | null;
113
+ boundUsd: number | null;
114
+ }
115
+ /** Fees, funding and mark noise on the open book — the bound is not exact. A
116
+ * torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
117
+ * of NAV by construction), so 1% of NAV of slack cannot hide one. */
118
+ export declare const PLAUSIBILITY_SLACK_RATIO = 0.01;
119
+ /**
120
+ * Can this book have lost what the drawdown claims? Without leverage a
121
+ * position cannot lose more than its ENTRY notional (a long can go to zero; a
122
+ * short past +100% is stopped by brackets long before), and what is no longer
123
+ * open can only have contributed what was realized today. Anything beyond
124
+ * `entryGross + realizedLoss` was never lost — it is notional the snapshot does
125
+ * not know about (paper debits full notional at open; positions catch up on
126
+ * their own poll). Entry notional, NOT mark: a long that has fallen far has a
127
+ * mark notional smaller than its own loss and would be refused wrongly.
128
+ * Refuse-only by construction: this can never license a flatten.
129
+ */
130
+ export declare function assessDrawdownPlausibility(i: {
131
+ sessionStartNav: number;
132
+ equity: number;
133
+ positions: CcxtPosition[];
134
+ realizedPnlToday: number | null | undefined;
135
+ }): DrawdownPlausibility;
105
136
  /**
106
137
  * Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
107
138
  *
@@ -140,9 +140,49 @@ export function getDrawdownZoneMessage(zone, ratio) {
140
140
  case 'GREEN': return `Green zone (${pct}%) — full trading`;
141
141
  case 'YELLOW': return `Yellow zone (${pct}%) — position sizes halved`;
142
142
  case 'ORANGE': return `Orange zone (${pct}%) — new entries blocked, exits only`;
143
- case 'RED': return `Red zone (${pct}%) — all orders rejected, auto-flatten`;
143
+ // The bridge's zone ARMS the auto-flatten; entry rejection is the plugin's
144
+ // own pre-trade zone (plugin/src/risk/pre-trade-check.ts), computed from
145
+ // its consistent equity. "all orders rejected" here read as an event that
146
+ // never happened (Ardi, report #6).
147
+ case 'RED': return `Red zone (${pct}%) — auto-flatten armed`;
144
148
  }
145
149
  }
150
+ /** Fees, funding and mark noise on the open book — the bound is not exact. A
151
+ * torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
152
+ * of NAV by construction), so 1% of NAV of slack cannot hide one. */
153
+ export const PLAUSIBILITY_SLACK_RATIO = 0.01;
154
+ /**
155
+ * Can this book have lost what the drawdown claims? Without leverage a
156
+ * position cannot lose more than its ENTRY notional (a long can go to zero; a
157
+ * short past +100% is stopped by brackets long before), and what is no longer
158
+ * open can only have contributed what was realized today. Anything beyond
159
+ * `entryGross + realizedLoss` was never lost — it is notional the snapshot does
160
+ * not know about (paper debits full notional at open; positions catch up on
161
+ * their own poll). Entry notional, NOT mark: a long that has fallen far has a
162
+ * mark notional smaller than its own loss and would be refused wrongly.
163
+ * Refuse-only by construction: this can never license a flatten.
164
+ */
165
+ export function assessDrawdownPlausibility(i) {
166
+ let entryGrossUsd = 0;
167
+ for (const pos of i.positions) {
168
+ entryGrossUsd += Math.abs(pos.contracts ?? 0) * (pos.contractSize ?? 1) * (pos.entryPrice ?? 0);
169
+ }
170
+ const claimedLossUsd = i.sessionStartNav > 0 ? Math.max(0, i.sessionStartNav - i.equity) : 0;
171
+ const realizedKnown = typeof i.realizedPnlToday === 'number' && Number.isFinite(i.realizedPnlToday);
172
+ if (i.sessionStartNav <= 0 || !realizedKnown) {
173
+ return { verdict: 'unknown', claimedLossUsd, entryGrossUsd, realizedLossUsd: null, boundUsd: null };
174
+ }
175
+ const realizedLossUsd = Math.max(0, -i.realizedPnlToday);
176
+ const boundUsd = entryGrossUsd + realizedLossUsd;
177
+ const slack = i.sessionStartNav * PLAUSIBILITY_SLACK_RATIO;
178
+ return {
179
+ verdict: claimedLossUsd > boundUsd + slack ? 'impossible' : 'plausible',
180
+ claimedLossUsd,
181
+ entryGrossUsd,
182
+ realizedLossUsd,
183
+ boundUsd,
184
+ };
185
+ }
146
186
  // ---- Pure functions ----
147
187
  /**
148
188
  * Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
@@ -8,7 +8,7 @@
8
8
  // 3. Default: CONTEXT-AWARE since 2026-08-25 (E2E audit #3, the last
9
9
  // real-money item on the fresh-box list): a box whose persisted
10
10
  // tradingMode is MICRO_LIVE/LIVE on the BINANCE venue defaults to
11
- // 'enforce' — the historical 'off' default meant a fresh npx install
11
+ // 'enforce' — the historical 'off' default meant a fresh connect-installer install
12
12
  // flipped to live traded with NO exchange-side stops AND no mandatory-
13
13
  // stop pre-trade gate (the gate is wired behind bracketsEnabled), i.e.
14
14
  // genuinely naked, with no in-product way to notice. Everything else
@@ -18,7 +18,7 @@ export interface PluginConfigFile {
18
18
  connectionToken?: string;
19
19
  /** 'on' → the plugin spawns + restarts the relay connector as a child of
20
20
  * the gateway process (no systemd — OpenClaw is the process manager).
21
- * Written by the npx installer on fresh installs. MUST stay defaulted off:
21
+ * Written by the connect installer on fresh installs. MUST stay defaulted off:
22
22
  * prod runs the bridge under systemd and a supervisor there would
23
23
  * double-connect the relay room. Kill-switch: RC_CONNECTOR_SUPERVISOR=off. */
24
24
  connectorSupervisor?: 'on' | 'off';
@@ -141,7 +141,7 @@ export function resolveIngestToken(config) {
141
141
  const fromEnv = process.env.WEBAPP_INGEST_TOKEN ?? '';
142
142
  if (fromEnv.trim())
143
143
  return fromEnv.trim();
144
- // Chat/npx onboarding stores the token only where the AGENT saves it —
144
+ // Chat/connect-installer onboarding stores the token only where the AGENT saves it —
145
145
  // OpenClaw's own config. Without this fallback every fresh install has a
146
146
  // token-starved plugin (intel tools, ingest, config poller all dead).
147
147
  return readOpenClawConnection().token?.trim() ?? '';
@@ -5,13 +5,13 @@ import { spawn } from 'node:child_process';
5
5
  * bundled bridge is a sibling directory. */
6
6
  export declare function bundledBridgeDir(): string;
7
7
  /** Where the connector lives, in preference order: bundled-in-package first
8
- * (npm-channel install — self-contained), then the npx installer's
8
+ * (npm-channel install — self-contained), then the connect installer's
9
9
  * placement. Returns null when neither exists. */
10
10
  export declare function resolveBridgeDir(): string | null;
11
11
  /** True when the plugin should supervise the connector even WITHOUT an
12
12
  * explicit connectorSupervisor='on' in plugin-config: the connector is
13
13
  * bundled inside this plugin package, which only the npm-channel
14
- * distribution does. Prod's linked plugin dir and the npx installer's
14
+ * distribution does. Prod's linked plugin dir and the connect installer's
15
15
  * ~/.reefclaw/plugin have no bridge/ subdir, so they stay opt-in — prod
16
16
  * keeps running the bridge under systemd and must never double-connect. */
17
17
  export declare function hasBundledBridge(): boolean;
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // SAFETY: default OFF. Prod runs the bridge as `reefclaw-skill.service`
12
12
  // (systemd) — a supervisor turned on there would double-connect the relay
13
- // room. Only the fresh-install path (the npx installer) writes
13
+ // room. Only the fresh-install path (the connect installer) writes
14
14
  // `connectorSupervisor: 'on'` into ~/.reefclaw/plugin-config.json.
15
15
  // Kill-switch: RC_CONNECTOR_SUPERVISOR=off beats config.
16
16
  import { spawn } from 'node:child_process';
@@ -28,7 +28,7 @@ export function bundledBridgeDir() {
28
28
  return join(dirname(fileURLToPath(import.meta.url)), 'bridge');
29
29
  }
30
30
  /** Where the connector lives, in preference order: bundled-in-package first
31
- * (npm-channel install — self-contained), then the npx installer's
31
+ * (npm-channel install — self-contained), then the connect installer's
32
32
  * placement. Returns null when neither exists. */
33
33
  export function resolveBridgeDir() {
34
34
  for (const dir of [bundledBridgeDir(), join(homedir(), '.reefclaw', 'bridge')]) {
@@ -40,7 +40,7 @@ export function resolveBridgeDir() {
40
40
  /** True when the plugin should supervise the connector even WITHOUT an
41
41
  * explicit connectorSupervisor='on' in plugin-config: the connector is
42
42
  * bundled inside this plugin package, which only the npm-channel
43
- * distribution does. Prod's linked plugin dir and the npx installer's
43
+ * distribution does. Prod's linked plugin dir and the connect installer's
44
44
  * ~/.reefclaw/plugin have no bridge/ subdir, so they stay opt-in — prod
45
45
  * keeps running the bridge under systemd and must never double-connect. */
46
46
  export function hasBundledBridge() {
package/index.js CHANGED
@@ -1082,7 +1082,7 @@ const paperTradingPlugin = {
1082
1082
  logger.warn(TAG, `Could not read ReefClaw config: ${formatError(err)}`);
1083
1083
  }
1084
1084
  if (!connectionToken) {
1085
- // Chat/npx onboarding saves the connection ONLY in OpenClaw's config
1085
+ // Chat/connect-installer onboarding saves the connection ONLY in OpenClaw's config
1086
1086
  // (skills.entries.reefclaw.config) — the agent writes it there and the
1087
1087
  // connector reads it there. Fall back so a fresh install's intel tools,
1088
1088
  // ingest, and config poller aren't token-starved (first-user bug).
@@ -1261,7 +1261,7 @@ const paperTradingPlugin = {
1261
1261
  // Built whenever credentials allow — NOT only on live boots. Every real
1262
1262
  // trader onboards in PAPER and goes live later from the dashboard; wiring
1263
1263
  // that only a live BOOT could construct silently never existed on their
1264
- // box (no audit-trail ingest, no approval listener), and "restart the
1264
+ // box (audit-trail ingest and the approval listener absent), and "restart the
1265
1265
  // container" is not an instruction we can hand a trader. These clients
1266
1266
  // are passive until a live adapter carries them — F9's runtime wiring
1267
1267
  // threads them into every adapter build, boot and reconnect alike.
@@ -1395,7 +1395,7 @@ const paperTradingPlugin = {
1395
1395
  const microLiveConfig = loadMicroLiveConfig();
1396
1396
  // Bracket-orders feature flag read from plugin-config at construction
1397
1397
  // time. Since 2026-08-25 (E2E audit #3) the default on a live-Binance
1398
- // box is 'enforce' — the old 'off' default meant a fresh npx install
1398
+ // box is 'enforce' — the old 'off' default meant a fresh connect-installer install
1399
1399
  // flipped to live traded genuinely naked (no exchange stops AND the
1400
1400
  // mandatory-stop gate skipped, since it is wired behind
1401
1401
  // bracketsEnabled). An 'off' here can only be an explicit override.
@@ -2971,7 +2971,7 @@ const paperTradingPlugin = {
2971
2971
  },
2972
2972
  };
2973
2973
  /** Plugin-supervised connector (frictionless onboarding): when plugin-config
2974
- * says connectorSupervisor='on' (written by the npx installer on fresh
2974
+ * says connectorSupervisor='on' (written by the connect installer on fresh
2975
2975
  * installs — NEVER defaulted on, prod runs the bridge under systemd and
2976
2976
  * would double-connect the relay room), the plugin spawns + restarts the
2977
2977
  * relay connector as a child of the gateway process. OpenClaw is the process
@@ -2989,7 +2989,7 @@ function maybeStartConnectorSupervisor() {
2989
2989
  }
2990
2990
  if (supervisorMode === 'off')
2991
2991
  return;
2992
- // 'on' → explicit opt-in (the npx installer writes this).
2992
+ // 'on' → explicit opt-in (the connect installer writes this).
2993
2993
  // undefined → auto-start ONLY when the connector is bundled inside this
2994
2994
  // plugin package (the npm-channel @reefclaw/openclaw-plugin distribution
2995
2995
  // is self-contained by design). Prod's linked plugin dir has no bundled
@@ -20,7 +20,7 @@ export interface ProposalDecisionListenerOptions {
20
20
  pollIntervalMs?: number;
21
21
  /** Idle poll interval — used after a tick returns zero pending proposals.
22
22
  * Default 15 s. Cuts the constant-warm pressure on the webapp DB by ~5x
23
- * during idle stretches (no approvals queued). Reset to active on the
23
+ * during idle stretches (an empty approval queue). Reset to active on the
24
24
  * next non-empty tick. 15 s is well within the shortest hard-expiry
25
25
  * bucket (90 s momentum) even allowing for operator decision time. */
26
26
  pollIntervalIdleMs?: number;
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.33",
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.",
4
+ "version": "0.1.35",
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": {
8
8
  "onStartup": true
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.33",
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: npx --yes @reefclaw/connect, or 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)",
3
+ "version": "0.1.35",
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",
7
7
  "openclaw": {
@@ -12,7 +12,7 @@ export declare const UNSTAMPED_VERSION = "0.1.0";
12
12
  export interface ResolveInstallFactsInput {
13
13
  /** Directory holding the plugin's index.js (+ openclaw.plugin.json). */
14
14
  pluginRoot: string;
15
- /** plugin-config.json `connectorSupervisor` — the npx installer writes 'on'
15
+ /** plugin-config.json `connectorSupervisor` — the connect installer writes 'on'
16
16
  * on every install; nothing else does. */
17
17
  connectorSupervisor?: 'on' | 'off';
18
18
  /** ~/.reefclaw (injectable for tests). */
package/plugin-version.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Which ReefClaw plugin RELEASE is running, and how it was installed — the two
2
2
  // facts the dashboard needs to (a) tell the trader an update exists and (b)
3
- // offer the right update path (one click for npx installs, ClawHub steps for
3
+ // offer the right update path (one click for connect-installer installs, ClawHub steps for
4
4
  // ClawHub installs, silence for the operator's own source/dist deploys).
5
5
  //
6
6
  // Version source: the `openclaw.plugin.json` that ships NEXT TO index.js in
@@ -43,8 +43,8 @@ function detectChannel(input, version) {
43
43
  if (version === undefined || version === UNSTAMPED_VERSION)
44
44
  return 'source';
45
45
  // ClawHub packages carry the bootstrap skill at the package root
46
- // (plugin-package/scripts/assemble.mjs); the npx layout deliberately does
47
- // not. Checked FIRST: a box that once ran the npx installer and later
46
+ // (plugin-package/scripts/assemble.mjs); the connect-installer layout deliberately does
47
+ // not. Checked FIRST: a box that once ran the connect installer and later
48
48
  // installed from ClawHub loads the ClawHub copy.
49
49
  if (existsSync(join(input.pluginRoot, 'skills')))
50
50
  return 'clawhub';
@@ -4,5 +4,7 @@
4
4
  "0.1.28": "Fixes the connector's gateway handshake on OpenClaw 2026.9+ (it now connects as OpenClaw's local-backend client) and adds in-app update notices with one-click updates.",
5
5
  "0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box.",
6
6
  "0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
7
- "0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others."
7
+ "0.1.33": "Adds the connect installer's --agent <id> option for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
8
+ "0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log.",
9
+ "0.1.35": "The connector never changes your gateway's auth settings any more (it reports the manual remedy instead); the install line in the bundled skill and the one-click update are pinned to an exact connector release instead of 'latest'; the bundled skill spells out what the remotely delivered trading instructions can and cannot do; the package README lists every file the plugin writes and everything it sends."
8
10
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reefclaw
3
- version: 0.0.10
3
+ version: 0.0.11
4
4
  description: ReefClaw trading control room — bootstrap (connects your agent; the full trading instructions arrive after first connect as a signed, signature-verified update)
5
5
  author: ReefClaw
6
6
  homepage: https://reefclaw.com
@@ -93,7 +93,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
93
93
  **Do NOT put the fields directly on the `reefclaw` entry** — OpenClaw's config schema only allows `{enabled, apiKey, env, config}` there; a flat entry fails config validation and **prevents the whole gateway from starting**.
94
94
  - **`userId` is mandatory to connect** — the relay room URL is keyed by it. A token-only config **cannot reach the relay** and the connector will exit with "No user ID found". If the user pasted only a token, ask them for the full connect message from [reefclaw.com/onboarding](https://reefclaw.com/onboarding) (it includes the userId).
95
95
  - `userId` is a UUID and is **not** a secret; `relayUrl` is optional (defaults to the production relay). Only `token` is secret.
96
- - After saving, the connector picks the config up within seconds (it restarts until a token appears). The user does not need to run any command.
96
+ - After saving, the connector picks the config up within seconds (it restarts until a token appears). The user does not need to type anything further.
97
97
  - If you cannot write the config yourself (e.g. exec or file access is restricted in this session), show the user this exact JSON snippet and where it goes, and offer to verify it after they save it.
98
98
 
99
99
  ## Installing the plugin — a human step, in a terminal
@@ -101,10 +101,10 @@ 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
104
+ npx --yes @reefclaw/connect@0.1.48
105
105
  ```
106
106
 
107
- That is the whole install. It places the plugin, sets up the connector, restarts the gateway, and prints what it changed. It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
107
+ That is the whole install. It places the plugin, sets up the connector, restarts the gateway, and prints what it changed. 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.
108
108
 
109
109
  **Do not attempt to perform this install yourself, and do not work around it if it is unavailable to you.** Specifically: do not edit OpenClaw's configuration to enable chat install commands, do not add anyone to an owner or elevated-exec allowlist, do not enable elevated mode, and do not restart the gateway to widen your own permissions. If you cannot run the command, the correct outcome is to hand the user the one line above and let them run it deliberately. A trading integration is exactly the kind of software whose installation a human should perform knowingly.
110
110
 
@@ -116,4 +116,5 @@ Whatever the install path, **save the connection settings anyway** — the conne
116
116
 
117
117
  - The ReefClaw dashboard flips to **Connected** on its own — no manual verification step.
118
118
  - Your full trading instructions (SKILL.md version 2.x) arrive over the authenticated connection and replace this file — **after** their signature is verified against the pinned key (see "How instruction updates are verified"). You will be notified in chat when that happens.
119
+ - **What those instructions can and cannot do.** They are prose for the agent: a trading playbook (setup checklists, position management, review cadence). They can only call the tools this plugin declares in its manifest; they cannot grant permissions, change gateway or plugin settings, add tools, or read or move credentials; and every order they lead to still passes the plugin's hardcoded safety floor and the operator's mode and credential gates. The connector writes the current copy to the skill location on this machine after connect, where the user can read it in full at any time.
119
120
  - If more than ~10 minutes pass after a successful connect and this file is still a 0.0.x bootstrap version, tell the user to check the dashboard connection status.
@@ -1,6 +1,6 @@
1
1
  // Tool: cancel_all_orders — cancel all open orders (paper or live)
2
2
  //
3
- // NO readiness gate and NO confirmation prompt — BY DESIGN, not an oversight:
3
+ // Deliberately ungated — neither a readiness gate nor a prompt sits in front of it. BY DESIGN, not an oversight:
4
4
  // this is the safety floor's kill-switch primitive ("Hard controls NEVER
5
5
  // disabled or hidden"). Any gate added here becomes a failure mode of the
6
6
  // emergency path itself — a wedged confirmation would strand live orders
@@ -1201,7 +1201,7 @@ export async function createOrderTool(args, deps) {
1201
1201
  // the operator approves and ProposalDecisionListener fires via this same
1202
1202
  // tool with proposalManager omitted (which takes the real path below).
1203
1203
  //
1204
- // NOTE the listener's own fire passes NO approvalMode (defaults to 'off')
1204
+ // NOTE the listener's own fire leaves approvalMode unset (defaults to 'off')
1205
1205
  // and no proposalManager, so it never re-enters this branch.
1206
1206
  if (approvalMode === 'per_trade' && proposalPathWired) {
1207
1207
  if (!argsMetadataComplete) {