@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.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @reefclaw/openclaw-plugin
2
+
3
+ The ReefClaw trading plugin for OpenClaw. It gives an OpenClaw agent a supervised trading toolkit and connects it to the operator's ReefClaw dashboard. Everything runs on the operator's own machine; ReefClaw's servers host the dashboard, a relay and a market-data API, and never execute trades.
4
+
5
+ This file is the plain-language ledger of what the package does on the machine it is installed on: what runs, what it writes, what it sends, what it never does, and how to switch each part off. Every line is checkable against the shipped source.
6
+
7
+ ## What runs
8
+
9
+ - **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`.
10
+ - **One connector process** (the `bridge/` folder) is started and supervised by the plugin. It holds the outbound connection to the ReefClaw relay, runs the agent's scheduled heartbeat, and delivers signed instruction updates. If it exits, the plugin restarts it.
11
+ - The agent starts in **PAPER mode**: real market data, simulated fills, no exchange account and no API keys. Moving to real money is a separate step the **operator** takes from the dashboard (PAPER → MICRO_LIVE → LIVE), and the tools that change mode or store credentials refuse calls that do not carry operator provenance from the dashboard.
12
+
13
+ ## What it writes on this machine
14
+
15
+ | Path | What | Why |
16
+ | --- | --- | --- |
17
+ | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
18
+ | `~/.reefclaw/credential-transport-key.json` | A key pair used to receive exchange credentials from the dashboard in encrypted form | So credentials cross the relay encrypted to this box; the private half never leaves it |
19
+ | Other files under `~/.reefclaw/` | Paper-trading state, the protective-order ledger, position state, a cached copy of the account's central config, market-data caches | Local bookkeeping so a restart resumes where it left off |
20
+ | `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted | So the connector can reach the operator's own dashboard room. Nothing else in that file is touched, and **nothing under `gateway` is ever written** |
21
+ | OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API | The scheduled position review; remove it with the OpenClaw cron commands |
22
+ | The `reefclaw` skill's `SKILL.md` in the agent workspace, in `~/.openclaw/skills/`, and in this package's `skills/` folder | The agent's trading instructions, kept identical in the places OpenClaw reads them | The bundled copy is a bootstrap; the full instructions arrive after connect and are applied only after their Ed25519 signature verifies against a key pinned in this build |
23
+ | The agent's `sessions.json` (older OpenClaw builds only) | One cached skills-snapshot key is cleared after an instruction update | So the running session re-reads the updated skill; nothing else in that file changes |
24
+
25
+ It **reads** the agent's heartbeat transcripts (OpenClaw's SQLite store on 2026.9+, JSONL before) to build the heartbeat flight recorder described below.
26
+
27
+ ## What leaves this machine
28
+
29
+ Everything below goes to the operator's own ReefClaw account and nowhere else.
30
+
31
+ | Flow | What is sent | Switch |
32
+ | --- | --- | --- |
33
+ | Dashboard relay | Order, position, balance and agent-state events; dashboard chat both ways | none, it is the product |
34
+ | Journal / trade feed | Fills, position entries, heartbeat reviews and closes with the agent's stated reasoning | none, it is the product |
35
+ | Heartbeat flight recorder | For every heartbeat: the tool calls it made (arguments and results truncated, credential-shaped tools redacted), its final report, the model that answered and raw token counts | `RC_HEARTBEAT_RECORDER=off` |
36
+ | Shock wakes | Nothing is sent; the connector polls the account's `shockWake` setting and, when the operator turned it on, delivers up to 8 extra agent turns a day on a sharp market move | `RC_SHOCK_WAKE=off` |
37
+ | Intelligence | Market-context reads; the plugin sends symbols and parameters, never keys | none, tools degrade without it |
38
+ | Version report | The installed plugin and connector versions, so the dashboard can offer an update | none |
39
+
40
+ Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the intelligence API, the exchange when credentials are present, and the npm registry only during an operator-triggered update. The package opens no listening port.
41
+
42
+ ## What it never does
43
+
44
+ - **It never changes the gateway's auth settings.** If the gateway withholds the scope the connector needs, the connector logs the exact manual remedy and stops; the decision stays with the operator.
45
+ - **It never sends exchange API keys to ReefClaw.** A test in this package drives the real outbound clients and asserts no credential reaches the wire. On Hyperliquid the key is an agent key, which cannot withdraw or transfer funds; on Binance the operator is asked to create keys without withdrawal permission.
46
+ - **It never runs an unpinned install.** The install line in the bundled skill names the exact connector release this plugin was published with, and the dashboard's one-click update installs exactly the release ReefClaw's public release endpoint reports. If that lookup fails, the update does not run.
47
+ - **It never trades real money on its own initiative.** Live trading requires credentials and a mode change that only the operator can make from the dashboard; every live position carries exchange-native protective stops; and the operator's pause, flatten and kill controls are never gated behind subscription state.
48
+
49
+ ## Switches and removal
50
+
51
+ | Setting | Effect |
52
+ | --- | --- |
53
+ | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box |
54
+ | `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
55
+ | `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
56
+ | `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
57
+
58
+ To remove the plugin: uninstall it with OpenClaw's plugin commands, delete `~/.reefclaw/`, remove the `reefclaw` skill folder(s), the `skills.entries.reefclaw` entry in `openclaw.json`, and the `reefclaw-heartbeat` cron job.
59
+
60
+ ## Install
61
+
62
+ - From ClawHub on OpenClaw 2026.8.1 or newer: Control UI → Plugins → Discover → search "reefclaw" → Install, then accept the listed capabilities; or in chat `/plugins install clawhub:@reefclaw/openclaw-plugin`, then the same command with `--accept-capabilities` after reading the capability list (the chat command needs `commands.plugins: true` in `openclaw.json`).
63
+ - Or with the ReefClaw connect installer from npm (`@reefclaw/connect`), run once in a terminal on the OpenClaw host and pinned to the exact release named in the bundled skill and on the onboarding page.
64
+
65
+ Support: support@reefclaw.com · https://reefclaw.com
@@ -28,17 +28,16 @@ export declare function writeOpenClawConfig(token: string, userId?: string, rela
28
28
  * never gets to run — this is the equivalent proven-need signal for it. */
29
29
  export declare function isDeviceIdentityRejection(code: number | undefined, reason: string | undefined): boolean;
30
30
  export declare function handshakeLacksWriteScope(scopes: readonly string[] | undefined): boolean;
31
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
32
+ * keep `operator.write` on a connection without device identity. Named here
33
+ * ONLY so the remedy text can spell them out — this module never writes them. */
34
+ export declare const LEGACY_GATEWAY_AUTH_FLAGS: readonly ["gateway.controlUi.dangerouslyDisableDeviceAuth", "gateway.controlUi.allowInsecureAuth"];
31
35
  /**
32
- * LAST RESORT: relax the local gateway's device-identity auth because a
33
- * completed handshake proved the gateway is withholding `operator.write`
34
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
35
- * no-op once the flags are set — so it warns exactly once per box, at the
36
- * moment the need is demonstrated.
37
- *
38
- * Returns true if it changed the config (⇒ the gateway must be restarted for
39
- * the flags to take effect; they are read at gateway boot).
36
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
37
+ * rejects the handshake for missing device identity). Pure: it builds text
38
+ * and changes nothing on disk.
40
39
  */
41
- export declare function relaxGatewayDeviceAuth(reason: string): boolean;
40
+ export declare function describeGatewayWriteScopeRemedy(reason: string): string;
42
41
  export interface CliArgs {
43
42
  provider: 'mock' | 'gateway';
44
43
  token?: string;
package/bridge/config.js CHANGED
@@ -17,13 +17,13 @@ const DEFAULT_RELAY_URL = 'wss://reefclaw.radunlupsa.partykit.dev';
17
17
  // during onboarding, so the connector can pick the connection up and persist
18
18
  // it across restarts). Every other key in the file is preserved verbatim.
19
19
  //
20
- // It deliberately does NOT weaken the local gateway's auth. Until 2026-07-29
21
- // it also set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
- // allowInsecureAuth} = true on EVERY write — a security-relevant downgrade of
23
- // the user's own gateway, applied pre-emptively whether or not their OpenClaw
24
- // needed it. That relaxation now happens only on PROVEN need, via
25
- // relaxGatewayDeviceAuth() below, which the bridge calls if and only if a
26
- // completed handshake shows the gateway actually withheld `operator.write`.
20
+ // It deliberately does NOT touch the local gateway's auth settings. Until
21
+ // 2026-07-29 the connector set gateway.controlUi.{dangerouslyDisableDeviceAuth,
22
+ // allowInsecureAuth} = true on every write, and until 2026-09-19 it still
23
+ // wrote them as a "last resort" when a handshake came back without
24
+ // `operator.write`. Both are gone: this software never changes the user's
25
+ // gateway security posture. When the gateway withholds the scope, the bridge
26
+ // logs the exact manual remedy (describeGatewayWriteScopeRemedy) and stops.
27
27
  /** Read the OpenClaw config file and extract ReefClaw skill settings.
28
28
  * Prefers the schema-valid nested shape (entry.config.*), falls back to the
29
29
  * legacy flat shape per-field. */
@@ -80,8 +80,9 @@ export function writeOpenClawConfig(token, userId, relayUrl) {
80
80
  delete entry.token;
81
81
  delete entry.userId;
82
82
  delete entry.relayUrl;
83
- // NOTE: no gateway.controlUi relaxation here. Saving a connection must not
84
- // change the user's gateway security posture — see relaxGatewayDeviceAuth().
83
+ // NOTE: nothing under gateway.controlUi is touched here or anywhere else in
84
+ // the connector. Saving a connection must not change the user's gateway
85
+ // security posture — see describeGatewayWriteScopeRemedy().
85
86
  // Write — file holds the connection token, so restrict to owner.
86
87
  mkdirSync(OPENCLAW_DIR, { recursive: true, mode: 0o700 });
87
88
  writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
@@ -104,43 +105,15 @@ function restrictConfigPermissions() {
104
105
  logger.debug(TAG, `Could not chmod ${CONFIG_PATH} to 0600: ${err instanceof Error ? err.message : String(err)}`);
105
106
  }
106
107
  }
107
- // ---- Gateway device-auth relaxation (LAST RESORT, proven need only) ----
108
+ // ---- Gateway scope: report, never relax ----
108
109
  //
109
- // Some OpenClaw builds (observed on v2026.4.2) clear `operator.write` from a WS
110
- // connection that carries no device identity — the bridge then cannot place or
111
- // cancel orders. The historical workaround was to set
112
- // gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth} = true
113
- // on every install and every config save, whether or not the user's OpenClaw
114
- // actually behaved that way. That is a real downgrade of the user's gateway
115
- // applied on speculation, and the flag name says so.
116
- //
117
- // Since 2026-07-29 the relaxation is applied ONLY when a completed handshake
118
- // proves it is needed: the bridge inspects the granted scopes from hello-ok and
119
- // calls relaxGatewayDeviceAuth() if `operator.write` is missing. On the
120
- // supported range (the plugin's compat floor is pluginApi >=2026.6.0) the
121
- // handshake keeps its scopes and these flags are never written at all. Boxes
122
- // that already have them keep them — nothing here removes an existing flag,
123
- // because clearing it mid-session would strip the running bridge's scopes.
124
- /** Set the two relaxation flags on an in-memory config. Returns true if either
125
- * changed, so callers only write + disclose when something actually flipped. */
126
- function applyGatewayAuthRelaxation(config) {
127
- if (!config.gateway)
128
- config.gateway = {};
129
- const gw = config.gateway;
130
- if (!gw.controlUi)
131
- gw.controlUi = {};
132
- const cui = gw.controlUi;
133
- let changed = false;
134
- if (cui.dangerouslyDisableDeviceAuth !== true) {
135
- cui.dangerouslyDisableDeviceAuth = true;
136
- changed = true;
137
- }
138
- if (cui.allowInsecureAuth !== true) {
139
- cui.allowInsecureAuth = true;
140
- changed = true;
141
- }
142
- return changed;
143
- }
110
+ // Some OpenClaw builds withhold `operator.write` from a connection that
111
+ // carries no device identity, and OpenClaw >= 2026.9 rejects such a handshake
112
+ // outright. From 2026-07-29 to 2026-09-19 the connector answered that by
113
+ // writing gateway.controlUi.{dangerouslyDisableDeviceAuth, allowInsecureAuth}
114
+ // = true into the user's openclaw.json itself. It no longer does: a downgrade
115
+ // of the user's gateway auth is the user's decision, made by hand. The helpers
116
+ // below only DETECT the condition and DESCRIBE the remedy.
144
117
  /** True when the bridge lacks the write scope it needs to trade — i.e. the
145
118
  * gateway granted a scope set without `operator.write`. Read from the
146
119
  * handshake, so it reflects what the gateway ACTUALLY did, not a version
@@ -165,37 +138,29 @@ export function handshakeLacksWriteScope(scopes) {
165
138
  return false;
166
139
  return !scopes.includes('operator.write');
167
140
  }
141
+ /** The two legacy gateway flags older OpenClaw builds needed before they would
142
+ * keep `operator.write` on a connection without device identity. Named here
143
+ * ONLY so the remedy text can spell them out — this module never writes them. */
144
+ export const LEGACY_GATEWAY_AUTH_FLAGS = [
145
+ 'gateway.controlUi.dangerouslyDisableDeviceAuth',
146
+ 'gateway.controlUi.allowInsecureAuth',
147
+ ];
168
148
  /**
169
- * LAST RESORT: relax the local gateway's device-identity auth because a
170
- * completed handshake proved the gateway is withholding `operator.write`
171
- * (without it the bridge cannot place or cancel orders). Idempotent, and a
172
- * no-op once the flags are set — so it warns exactly once per box, at the
173
- * moment the need is demonstrated.
174
- *
175
- * Returns true if it changed the config (⇒ the gateway must be restarted for
176
- * the flags to take effect; they are read at gateway boot).
149
+ * Operator-facing remedy for a gateway that withholds `operator.write` (or
150
+ * rejects the handshake for missing device identity). Pure: it builds text
151
+ * and changes nothing on disk.
177
152
  */
178
- export function relaxGatewayDeviceAuth(reason) {
179
- try {
180
- const raw = readFileSync(CONFIG_PATH, 'utf-8');
181
- const config = JSON5.parse(raw);
182
- if (!applyGatewayAuthRelaxation(config))
183
- return false; // already relaxed
184
- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
185
- restrictConfigPermissions(); // mode above is ignored on an existing file
186
- logger.warn(TAG, `Enabled gateway.controlUi.{dangerouslyDisableDeviceAuth,allowInsecureAuth} in ` +
187
- `${CONFIG_PATH} because ${reason}. This RELAXES your local gateway's ` +
188
- `device-identity auth — it is the only way this OpenClaw build will keep ` +
189
- `operator.write on the bridge connection, which trading requires. Keep the ` +
190
- `gateway bound to localhost. RESTART the gateway for it to take effect. If ` +
191
- `you would rather not run with it, upgrade OpenClaw (builds meeting the ` +
192
- `plugin's compat floor keep the scope without this) and remove both flags.`);
193
- return true;
194
- }
195
- catch {
196
- // Config missing/unparseable — setup hasn't run yet; nothing to relax.
197
- return false;
198
- }
153
+ export function describeGatewayWriteScopeRemedy(reason) {
154
+ return (`The OpenClaw gateway did not grant the connector operator.write (${reason}), so order ` +
155
+ `placement and cancellation would fail on this connection. ReefClaw does not change your ` +
156
+ `gateway's auth settings; the fix is yours to apply. Options: (1) upgrade OpenClaw to a build ` +
157
+ `that meets this plugin's compat floor — those keep the scope for the connector's ` +
158
+ `local-backend identity with no flags at all; (2) on OpenClaw 2026.9+, pair the connector as a ` +
159
+ `device or run the gateway with device pairing configured (see the gateway auth section of ` +
160
+ `${CONFIG_PATH}); (3) on older builds the historical workaround was setting ` +
161
+ `${LEGACY_GATEWAY_AUTH_FLAGS.join(' and ')} to true in ${CONFIG_PATH} and restarting the gateway — ` +
162
+ `that relaxes device-identity auth for every client, so only do it on a gateway bound to ` +
163
+ `localhost. Trading tools stay blocked until the gateway grants the scope.`);
199
164
  }
200
165
  /**
201
166
  * Resolve config with priority:
@@ -120,7 +120,7 @@ export async function ensureHeartbeatCron(opts) {
120
120
  // right for boxes with a chat channel (the heartbeat's summary reaches the
121
121
  // operator). On a FRESH box with no channels configured, cron.add REJECTS
122
122
  // announce/'last' (no resolvable recipient — observed live on a first
123
- // real npx onboarding, 2026-07-22; the old setup-time CLI path failed the
123
+ // real connect-installer onboarding, 2026-07-22; the old setup-time CLI path failed the
124
124
  // same way, silently). Fall back to delivery mode 'none': a heartbeat that
125
125
  // runs without announcing beats no heartbeat at all, and the operator sees
126
126
  // the results on the dashboard anyway.
@@ -27,12 +27,15 @@ export interface PollerCallbacks {
27
27
  onCandle: (data: CandleData) => void;
28
28
  /** Raw CCXT positions from fetch_positions — fires every 3s */
29
29
  onPositions: (positions: CcxtPosition[]) => void;
30
- /** Parsed balance from fetch_balance — fires every 10s */
30
+ /** Parsed balance from fetch_balance — fires every 10s. `extras` carries the
31
+ * plugin-computed day figures that ride on the same response when present. */
31
32
  onBalance: (balance: {
32
33
  currency: string;
33
34
  total: number;
34
35
  available: number;
35
36
  locked: number;
37
+ }, extras?: {
38
+ realizedPnlToday?: number;
36
39
  }) => void;
37
40
  /** Parsed open orders from fetch_open_orders — fires every 3s */
38
41
  onOpenOrders: (orders: OrderData[]) => void;
@@ -134,6 +137,11 @@ export declare class Poller {
134
137
  private pollOhlcv;
135
138
  private pollPositions;
136
139
  private pollBalance;
140
+ /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
141
+ * RED-zone guard calls this when the wallet/positions snapshot is torn by a
142
+ * fresh fill, so the tear closes in ~100 ms instead of waiting out the
143
+ * 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
144
+ refreshPositionsNow(): Promise<void>;
137
145
  private pollOpenOrders;
138
146
  private pollMarketStructure;
139
147
  /**
@@ -378,7 +378,17 @@ export class Poller {
378
378
  const tool = this.toolMap.fetch_balance;
379
379
  const result = await this.http.invoke(tool, {});
380
380
  const balance = mapCcxtBalance(result.data, this.quoteCurrency);
381
- this.callbacks.onBalance(balance);
381
+ const realized = result.data?.realizedPnlToday;
382
+ this.callbacks.onBalance(balance, typeof realized === 'number' && Number.isFinite(realized) ? { realizedPnlToday: realized } : undefined);
383
+ }
384
+ /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
385
+ * RED-zone guard calls this when the wallet/positions snapshot is torn by a
386
+ * fresh fill, so the tear closes in ~100 ms instead of waiting out the
387
+ * 10 s cadence (Ardi, report #6). No-op while paused/stopped/in-flight. */
388
+ refreshPositionsNow() {
389
+ if (!this.toolMap.fetch_positions)
390
+ return Promise.resolve();
391
+ return this.guardedExec('fetch_positions', () => this.pollPositions());
382
392
  }
383
393
  async pollOpenOrders() {
384
394
  const tool = this.toolMap.fetch_open_orders;
@@ -22,6 +22,9 @@ export declare const MAX_PER_SCAN = 5;
22
22
  export declare const MAX_POST_ATTEMPTS = 5;
23
23
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
24
24
  export declare const CRON_RUNS_COOLDOWN_MS: number;
25
+ /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
26
+ * (a store the recorder cannot read must not stay silent — Ardi, report #5). */
27
+ export declare const BLIND_PROBE_INTERVAL_MS: number;
25
28
  export type { AgentRunLifecycleData };
26
29
  /** What the recorder needs from the provider — kept narrow so it is trivially
27
30
  * mockable and the provider stays the only thing that talks to the gateway. */
@@ -41,6 +44,9 @@ export interface HeartbeatRunRecorderOptions {
41
44
  token: string;
42
45
  webappUrl?: string;
43
46
  sessionsDir?: string;
47
+ /** The agent database (OpenClaw >= 2026.9 transcript store); derived from
48
+ * `sessionsDir` when omitted. */
49
+ agentDbPath?: string;
44
50
  stateFile?: string;
45
51
  fetchImpl?: typeof fetch;
46
52
  now?: () => number;
@@ -58,6 +64,7 @@ export interface PostOutcome {
58
64
  export declare class HeartbeatRunRecorder {
59
65
  private readonly opts;
60
66
  private readonly sessionsDir;
67
+ private readonly agentDbPath;
61
68
  private readonly stateFile;
62
69
  private timer;
63
70
  private kickTimer;
@@ -67,6 +74,9 @@ export declare class HeartbeatRunRecorder {
67
74
  private readonly attempts;
68
75
  private cronRunsUnavailableUntil;
69
76
  private probeLogged;
77
+ private store;
78
+ private lastBlindProbeAt;
79
+ private blindWarned;
70
80
  /** Counters for a one-line health summary in logs. */
71
81
  readonly stats: {
72
82
  scans: number;
@@ -78,6 +88,9 @@ export declare class HeartbeatRunRecorder {
78
88
  };
79
89
  constructor(opts: HeartbeatRunRecorderOptions);
80
90
  private now;
91
+ /** Which store(s) are readable; logs on first sight and whenever it changes
92
+ * (the database appears when a gateway is upgraded under a running bridge). */
93
+ private detectStore;
81
94
  start(): void;
82
95
  stop(): void;
83
96
  /** A cron-session turn ended → scan shortly (debounced). */
@@ -88,8 +101,13 @@ export declare class HeartbeatRunRecorder {
88
101
  processed: number;
89
102
  deferred: number;
90
103
  }>;
91
- /** Is this session a heartbeat? Head marker first (cheap), trajectory key
92
- * second (covers a prompt without the marker), else not a heartbeat. */
104
+ /** Nothing to read this scan — were there beats anyway? `cron.runs` knows;
105
+ * a finished, unrecorded run inside the window means the recorder cannot
106
+ * see the store it should be reading. Warn once per process. */
107
+ private probeBlind;
108
+ /** Is this session a heartbeat? Session key first (the database carries it),
109
+ * head marker second (cheap), trajectory key third (covers a prompt without
110
+ * the marker), else not a heartbeat. */
93
111
  private classify;
94
112
  private fetchCronRunsSafe;
95
113
  /** POST one record to the webapp. Never throws. */
@@ -2,8 +2,10 @@
2
2
  // + webapp POST). File reads live in heartbeat-transcript.ts / -state.ts.
3
3
  //
4
4
  // What it does, every 60s and ~4s after any cron-session turn ends:
5
- // 1. list transcripts in the OpenClaw sessions dir newer than the last
6
- // scan watermark (minus slack) that are not yet recorded;
5
+ // 1. list transcripts newer than the last scan watermark (minus slack) that
6
+ // are not yet recorded — from the agent database (OpenClaw >= 2026.9)
7
+ // and the sessions dir (*.jsonl, older gateways); with nothing to read,
8
+ // ask cron.runs whether beats ran anyway and WARN once if so;
7
9
  // 2. keep the ones whose first user message carries the `[cron:…]`
8
10
  // heartbeat marker (or whose trajectory key is a cron key); mark every
9
11
  // other session (the main chat session, subagents) as skipped once so
@@ -23,7 +25,7 @@
23
25
  // Deliberately NOT recorded: shock wakes and operator chat turns (they run in
24
26
  // the main session, whose transcript is one long file). Heartbeats only.
25
27
  import { logger } from './logger.js';
26
- import { buildHeartbeatRunRecord, isCronSessionKey, listSessionCandidates, readCronMarker, readSession, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
28
+ import { buildHeartbeatRunRecord, describeTranscriptStore, isCronSessionKey, listAllSessionCandidates, readCandidateCronMarker, readSession, resolveAgentDbPath, resolveSessionsDir, shrinkRecord, } from './heartbeat-transcript.js';
27
29
  import { defaultStateFile, loadState, markRecorded, saveState } from './heartbeat-runs-state.js';
28
30
  const TAG = 'heartbeat-runs';
29
31
  /** Regular scan cadence. */
@@ -47,9 +49,13 @@ export const MAX_PER_SCAN = 5;
47
49
  export const MAX_POST_ATTEMPTS = 5;
48
50
  /** Cool down `cron.runs` for this long after it errors (older gateway). */
49
51
  export const CRON_RUNS_COOLDOWN_MS = 60 * 60_000;
52
+ /** With nothing to read, ask `cron.runs` this often whether beats ran anyway
53
+ * (a store the recorder cannot read must not stay silent — Ardi, report #5). */
54
+ export const BLIND_PROBE_INTERVAL_MS = 10 * 60_000;
50
55
  export class HeartbeatRunRecorder {
51
56
  opts;
52
57
  sessionsDir;
58
+ agentDbPath;
53
59
  stateFile;
54
60
  timer = null;
55
61
  kickTimer = null;
@@ -59,16 +65,36 @@ export class HeartbeatRunRecorder {
59
65
  attempts = new Map();
60
66
  cronRunsUnavailableUntil = 0;
61
67
  probeLogged = false;
68
+ store = null;
69
+ lastBlindProbeAt;
70
+ blindWarned = false;
62
71
  /** Counters for a one-line health summary in logs. */
63
72
  stats = { scans: 0, recorded: 0, posted: 0, postFailed: 0, skippedNonCron: 0, deferred: 0 };
64
73
  constructor(opts) {
65
74
  this.opts = opts;
66
75
  this.sessionsDir = opts.sessionsDir ?? resolveSessionsDir();
76
+ this.agentDbPath = opts.agentDbPath ?? resolveAgentDbPath(this.sessionsDir);
67
77
  this.stateFile = opts.stateFile ?? defaultStateFile();
78
+ this.lastBlindProbeAt = this.now();
68
79
  }
69
80
  now() {
70
81
  return this.opts.now?.() ?? Date.now();
71
82
  }
83
+ /** Which store(s) are readable; logs on first sight and whenever it changes
84
+ * (the database appears when a gateway is upgraded under a running bridge). */
85
+ detectStore() {
86
+ const next = describeTranscriptStore(this.sessionsDir, this.agentDbPath);
87
+ if (this.store?.label !== next.label) {
88
+ const changed = this.store !== null;
89
+ this.store = next;
90
+ if (changed)
91
+ logger.info(TAG, `transcript store changed: store=${next.label}`);
92
+ if (next.kind === 'sqlite-unsupported') {
93
+ logger.warn(TAG, `agent database present but this Node (${process.version}) has no node:sqlite — heartbeat telemetry stays empty until Node is upgraded (>= 22.13; OpenClaw >= 2026.9.3 needs 24)`);
94
+ }
95
+ }
96
+ return this.store;
97
+ }
72
98
  start() {
73
99
  if (this.stopped)
74
100
  return;
@@ -79,7 +105,7 @@ export class HeartbeatRunRecorder {
79
105
  this.kick(FIRST_SCAN_DELAY_MS);
80
106
  this.timer = setInterval(() => void this.scan(), interval);
81
107
  this.timer.unref?.();
82
- logger.info(TAG, `Heartbeat flight recorder started (dir=${this.sessionsDir}, every ${Math.round(interval / 1000)}s)`);
108
+ logger.info(TAG, `Heartbeat flight recorder started (store=${this.detectStore().label}, every ${Math.round(interval / 1000)}s)`);
83
109
  }
84
110
  stop() {
85
111
  this.stopped = true;
@@ -124,9 +150,12 @@ export class HeartbeatRunRecorder {
124
150
  const state = loadState(this.stateFile);
125
151
  const since = state.lastScanMtimeMs > 0 ? state.lastScanMtimeMs - SCAN_SLACK_MS : now - BOOTSTRAP_LOOKBACK_MS;
126
152
  const exclude = new Set(state.recorded);
127
- const candidates = listSessionCandidates(this.sessionsDir, { minMtimeMs: since, exclude })
153
+ this.detectStore();
154
+ const candidates = listAllSessionCandidates({ sessionsDir: this.sessionsDir, dbPath: this.agentDbPath }, { minMtimeMs: since, exclude })
128
155
  .filter((c) => now - c.mtimeMs >= SETTLE_MS)
129
156
  .sort((a, b) => a.mtimeMs - b.mtimeMs);
157
+ if (candidates.length === 0)
158
+ await this.probeBlind(now, since, state);
130
159
  let cronRuns; // undefined = not fetched yet
131
160
  let dirty = false;
132
161
  for (const c of candidates) {
@@ -221,10 +250,35 @@ export class HeartbeatRunRecorder {
221
250
  }
222
251
  return { processed, deferred };
223
252
  }
224
- /** Is this session a heartbeat? Head marker first (cheap), trajectory key
225
- * second (covers a prompt without the marker), else not a heartbeat. */
253
+ /** Nothing to read this scan — were there beats anyway? `cron.runs` knows;
254
+ * a finished, unrecorded run inside the window means the recorder cannot
255
+ * see the store it should be reading. Warn once per process. */
256
+ async probeBlind(now, since, state) {
257
+ if (this.blindWarned || now - this.lastBlindProbeAt < BLIND_PROBE_INTERVAL_MS)
258
+ return;
259
+ this.lastBlindProbeAt = now;
260
+ const runs = await this.fetchCronRunsSafe(now);
261
+ if (!runs)
262
+ return;
263
+ const recorded = new Set(state.recorded);
264
+ const missed = runs.filter((r) => (r.status === 'ok' || r.status === 'error') &&
265
+ r.runAtMs != null &&
266
+ r.runAtMs >= since &&
267
+ !(r.sessionId && recorded.has(r.sessionId)) &&
268
+ !(r.runId && recorded.has(r.runId)));
269
+ if (!missed.length)
270
+ return;
271
+ this.blindWarned = true;
272
+ logger.warn(TAG, `recorder is BLIND: cron.runs reports ${missed.length} finished heartbeat(s) since ${new Date(since).toISOString()} ` +
273
+ `but no transcript was found (store=${this.detectStore().label}) — heartbeat telemetry stays empty until the store is readable`);
274
+ }
275
+ /** Is this session a heartbeat? Session key first (the database carries it),
276
+ * head marker second (cheap), trajectory key third (covers a prompt without
277
+ * the marker), else not a heartbeat. */
226
278
  classify(c) {
227
- const marker = readCronMarker(c.file);
279
+ if (isCronSessionKey(c.sessionKey))
280
+ return c.sizeBytes === 0 ? 'unreadable' : 'cron';
281
+ const marker = readCandidateCronMarker(c);
228
282
  if (marker === undefined) {
229
283
  // Inconclusive head — fall back to the trajectory key when present.
230
284
  if (c.trajectoryFile) {
@@ -103,13 +103,68 @@ export interface CronRunLogLite {
103
103
  * bridge historically read a non-existent OPENCLAW_HOME; honour both). */
104
104
  export declare function resolveOpenClawStateDir(env?: NodeJS.ProcessEnv): string;
105
105
  export declare function resolveSessionsDir(agentId?: string, env?: NodeJS.ProcessEnv): string;
106
+ export declare const AGENT_DB_BASENAME = "openclaw-agent.sqlite";
107
+ /** The agent database beside a `<state>/agents/<id>/sessions` dir
108
+ * (OpenClaw's `resolveOpenClawAgentSqlitePath`: `agents/<id>/agent/openclaw-agent.sqlite`). */
109
+ export declare function resolveAgentDbPath(sessionsDir: string): string;
110
+ export interface SqliteStatement {
111
+ all(...params: unknown[]): unknown[];
112
+ run(...params: unknown[]): unknown;
113
+ }
114
+ export interface SqliteDatabase {
115
+ prepare(sql: string): SqliteStatement;
116
+ exec(sql: string): void;
117
+ close(): void;
118
+ }
119
+ export interface SqliteModule {
120
+ DatabaseSync: new (path: string, opts?: {
121
+ readOnly?: boolean;
122
+ }) => SqliteDatabase;
123
+ }
124
+ /** `node:sqlite`, or null when this Node has none. Cached. */
125
+ export declare function loadSqlite(): SqliteModule | null;
126
+ /** Test seam: swap the loader (pass null to simulate a Node without node:sqlite). */
127
+ export declare function setSqliteLoaderForTests(loader: (() => SqliteModule | null) | null): void;
128
+ export type TranscriptStoreKind = 'sqlite' | 'sqlite-unsupported' | 'jsonl';
129
+ export interface TranscriptStoreInfo {
130
+ kind: TranscriptStoreKind;
131
+ /** One-line label for logs, e.g. `sqlite(<db>)+jsonl(<dir>)`. Starts with the kind. */
132
+ label: string;
133
+ }
134
+ /** Which store(s) the recorder can read right now. `sqlite-unsupported` = the
135
+ * agent database exists but this Node has no node:sqlite (upgrade Node). */
136
+ export declare function describeTranscriptStore(sessionsDir: string, dbPath: string): TranscriptStoreInfo;
106
137
  export interface SessionCandidate {
107
138
  sessionId: string;
139
+ /** 'jsonl' = `<sessionId>.jsonl` (+ sidecar) in the sessions dir;
140
+ * 'sqlite' = rows in the agent database (OpenClaw >= 2026.9). */
141
+ source: 'jsonl' | 'sqlite';
142
+ /** The transcript file (jsonl) or the agent database (sqlite). */
108
143
  file: string;
109
144
  trajectoryFile: string | null;
145
+ /** The gateway's session key when the store carries it (sqlite) — a `:cron:`
146
+ * key identifies a heartbeat without reading the transcript. */
147
+ sessionKey: string | null;
110
148
  mtimeMs: number;
149
+ /** File size (jsonl) or transcript event count (sqlite); 0 = nothing to read yet. */
111
150
  sizeBytes: number;
112
151
  }
152
+ /** Candidates from both stores, newest store first: a session present in the
153
+ * database wins over a same-id `.jsonl` (post-migration leftovers). Never throws. */
154
+ export declare function listAllSessionCandidates(paths: {
155
+ sessionsDir: string;
156
+ dbPath: string;
157
+ }, opts?: {
158
+ minMtimeMs?: number;
159
+ exclude?: Set<string>;
160
+ }): SessionCandidate[];
161
+ /** Every session in the agent database whose transcript changed at/after
162
+ * `minMtimeMs`, excluding `exclude`d ids. [] when the database is missing,
163
+ * locked, unreadable, or shaped unlike the 2026.9 schema. */
164
+ export declare function listSqliteSessionCandidates(dbPath: string, opts?: {
165
+ minMtimeMs?: number;
166
+ exclude?: Set<string>;
167
+ }): SessionCandidate[];
113
168
  /** Every `<sessionId>.jsonl` transcript in `dir` (not sidecars, checkpoints,
114
169
  * topic files or retired copies) modified at/after `minMtimeMs`, excluding
115
170
  * `exclude`d session ids. Never throws — a missing dir yields []. */
@@ -122,6 +177,8 @@ export interface CronMarker {
122
177
  jobName: string | null;
123
178
  }
124
179
  export declare function parseCronMarker(text: string | null | undefined): CronMarker | null;
180
+ /** `readCronMarker` for either store. */
181
+ export declare function readCandidateCronMarker(c: SessionCandidate): CronMarker | null | undefined;
125
182
  /** Read only the head of a transcript and report whether its first user
126
183
  * message carries the `[cron:…]` marker. `null` = inconclusive (no user
127
184
  * message within the head) — callers then fall back to the trajectory key. */
@@ -205,5 +262,5 @@ export interface ReadSessionResult {
205
262
  trajectory: ParsedTrajectory | null;
206
263
  }
207
264
  /** Read + parse a candidate's transcript and (when present) its trajectory.
208
- * Never throws on a missing/torn file — a missing transcript yields null. */
265
+ * Never throws on a missing/torn file or an unreadable database — yields null. */
209
266
  export declare function readSession(c: SessionCandidate): ReadSessionResult | null;