@reefclaw/openclaw-plugin 0.1.51 → 0.1.53

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 CHANGED
@@ -8,6 +8,8 @@ This file is the plain-language ledger of what the package does on the machine i
8
8
 
9
9
  - **The plugin** loads into the OpenClaw gateway at startup (`activation.onStartup` in the manifest) and registers the trading tools listed under `contracts.tools`. The manifest also declares each of those tools a member of OpenClaw's "coding" tool profile (`toolMetadata`, one entry per tool and nothing else), so agents whose OpenClaw uses that profile can see them. That is a declaration in this package's own manifest: no OpenClaw config file is edited for it.
10
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
+ - **Pause, Kill and Flatten are enforced on this box.** When the operator presses one of them in the dashboard, the connector records a halt in `~/.reefclaw/plugin-config.json` (`operatorHalt`) through the operator-only `set_operator_halt` tool, and while it is set `create_order` refuses new orders. `close_position`, stops and protective orders keep working; a partial exit through `create_order` waits until Resume, which clears the halt. When Flatten has to close through `create_order` (no `close_position` on the gateway), it closes before it sets the halt. `RC_OPERATOR_HALT_GATE=off` is a break-glass switch that stops the enforcement.
12
+ - **Keeping the heartbeat's instructions current.** When the connector starts and the `reefclaw-heartbeat` job still carries, byte for byte, an instruction text an earlier version of this package wrote, it replaces that text, and nothing else in the job, with the current one, over a short-lived `operator.admin` gateway session it opens only when needed: for that write, and on older OpenClaw versions where listing scheduled jobs itself needs it. A job whose text was changed is never touched. `RC_HEARTBEAT_MESSAGE_REFRESH=off`, or switching one-click updates off, stops it.
11
13
  - **One-click update, for a copy OpenClaw installed from ClawHub.** When the operator presses Update in the ReefClaw dashboard, the connector asks the LOCAL gateway, over the `operator.admin` session it already uses for gateway restarts, to install from ClawHub exactly the version of this package (`@reefclaw/openclaw-plugin`) that ReefClaw's release endpoint names (`plugins.install` with `mode: "update"`), then restarts the gateway so that version loads. It never installs any other package or version, and never runs without that click. A copy placed by the connect installer is updated by that installer instead, pinned to the exact release the same endpoint names.
12
14
  - **First start on a fresh box.** When the connection saved in OpenClaw's config (`~/.openclaw/openclaw.json` by default) carries the exchange picked during onboarding (`skills.entries.reefclaw.config.venue`) and ReefClaw has never run on this box (no plugin state, credential transport key or first-start marker, and `plugin-config.json` absent or holding only what the connect installer wrote), the plugin applies it once. For Hyperliquid it writes the keyless Hyperliquid `exchange` block into `~/.reefclaw/plugin-config.json`, the same block the dashboard's exchange switch writes, and nothing else there; Binance is the default and writes nothing. It never overwrites an existing setting, never adds keys and never enables live trading. Separately, whenever OpenClaw keeps its state somewhere other than `~/.openclaw`, the plugin leaves a small marker (`first-start.json`) in that state dir on the first start that finds none, whether or not an exchange was saved (a box upgrading to this release gets one too), so a later start is never mistaken for a first one; it is never rewritten. `RC_FIRST_START_VENUE=off` switches all of this off, the marker included.
13
15
  - 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 an operator-provenance secret — a per-boot value the plugin mints in memory and hands only to the connector it supervises (never a file, argv or environment variable, so it cannot be read back from the config or supplied in conversation). While trading is live a new entry without a protective stop is refused whatever the settings say.
@@ -16,11 +18,11 @@ This file is the plain-language ledger of what the package does on the machine i
16
18
 
17
19
  | Path | What | Why |
18
20
  | --- | --- | --- |
19
- | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, the exchange in use (on a fresh box's first start, the keyless Hyperliquid block when that was picked during onboarding), and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
21
+ | `~/.reefclaw/plugin-config.json` (owner-only permissions) | Trading mode, per-box switches, the operator's Pause / Kill halt, the exchange in use (on a fresh box's first start, the keyless Hyperliquid block when that was picked during onboarding), and exchange credentials once the operator adds them | The only place exchange keys ever live; used only to sign requests to the exchange |
20
22
  | `~/.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 |
21
23
  | 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 |
22
24
  | `~/.openclaw/openclaw.json` → `skills.entries.reefclaw.config` only | The connection token, user id and relay URL the operator pasted, and the exchange picked during onboarding (`venue`) | 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** |
23
- | 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 |
25
+ | OpenClaw's cron store | One heartbeat job (`reefclaw-heartbeat`), created through the gateway's own cron API; its instruction text is updated when it is still an earlier ReefClaw default | The scheduled position review; remove it with the OpenClaw cron commands |
24
26
  | 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 |
25
27
  | 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 |
26
28
  | `first-start.json` in `<OpenClaw state dir>/plugins/reefclaw-paper-trading/`, only when OpenClaw keeps its state outside `~/.openclaw` | A first-start timestamp and a one-line note, written on the first start that finds none (whether or not an exchange was saved) and never overwritten | So the exchange picked during onboarding is applied on the first start only, even where the home directory is reset between restarts |
@@ -55,6 +57,8 @@ Network access is outbound only: the relay (WebSocket), `www.reefclaw.com`, the
55
57
  | --- | --- |
56
58
  | `REEFCLAW_ALLOW_CONNECTOR_UPDATE=0` (or `connectorUpdate: "off"` in `plugin-config.json`) | The dashboard's one-click update is refused on this box, by either route (connect installer or ClawHub) |
57
59
  | `RC_HEARTBEAT_RECORDER=off` | Heartbeat transcripts are not read or reported |
60
+ | `RC_HEARTBEAT_MESSAGE_REFRESH=off` | The connector never rewrites the heartbeat job's instructions |
61
+ | `RC_OPERATOR_HALT_GATE=off` | Break-glass: the dashboard's Pause / Kill / Flatten no longer block new entries on this box |
58
62
  | `RC_SHOCK_WAKE=off` | Shock wakes are never constructed, whatever the account setting says |
59
63
  | `RC_FIRST_START_VENUE=off` | First start neither reads nor applies the exchange saved with the connection, and writes no first-start marker |
60
64
  | `SKILL_OTA_REQUIRE_SIGNATURE=off` | Break-glass: accept an *unsigned* instruction update on this box (a forged signature is still always refused) |
@@ -2,6 +2,8 @@ export declare const HEARTBEAT_CRON_NAME = "reefclaw-heartbeat";
2
2
  export declare const HEARTBEAT_EVERY_MS: number;
3
3
  export declare const HEARTBEAT_TIMEOUT_SECONDS = 780;
4
4
  export declare const HEARTBEAT_MESSAGE: string;
5
+ /** True for a message that is byte-identical to one of our superseded defaults. */
6
+ export declare function isSupersededHeartbeatMessage(message: unknown): boolean;
5
7
  export interface CronRpcClient {
6
8
  sendRpc(method: string, params?: Record<string, unknown>): Promise<unknown>;
7
9
  }
@@ -54,6 +56,40 @@ export declare function reconcileHeartbeatDelivery(opts: {
54
56
  agentId?: string;
55
57
  agentIsDefault?: boolean;
56
58
  }): Promise<'patched' | 'unchanged' | 'skipped' | 'failed'>;
59
+ /** A gateway session that may call cron.update (operator.admin). `close`
60
+ * tears down a session opened only for this; a shared one passes a no-op. */
61
+ export interface HeartbeatAdminSession {
62
+ rpc: CronRpcClient;
63
+ close: () => void;
64
+ }
65
+ export type RefreshHeartbeatMessageOutcome = 'refreshed' | 'current' | 'untouched' | 'failed';
66
+ /**
67
+ * Bring OUR untouched heartbeat job up to date with HEARTBEAT_MESSAGE.
68
+ *
69
+ * Why (2026-10-24): the message reaches a job only when it is created (once
70
+ * per install), so every box created from a superseded default kept a beat
71
+ * with no entry check, and the small-model ones never traded. Only a message
72
+ * BYTE-IDENTICAL to one we shipped is replaced (isSupersededHeartbeatMessage):
73
+ * an edited job, a user's own job and the older Decision Loop message are
74
+ * left exactly as they are, so a box that trades today does not change.
75
+ * Nothing else of the job changes either: cron.update REPLACES the payload
76
+ * block, so the full stored payload goes back with only `message` swapped (a
77
+ * partial payload would drop timeoutSeconds and toolsAllow), and the enabled
78
+ * state is never touched — a job the user switched off stays off.
79
+ *
80
+ * cron.list runs on the long-lived read/write session; the admin session is
81
+ * opened only when a job needs the update, and the job is checked again on
82
+ * that session right before the write. Runs on every bridge start (one
83
+ * cron.list). Never throws.
84
+ */
85
+ export declare function refreshHeartbeatMessage(opts: {
86
+ rpc: CronRpcClient;
87
+ /** Opened only when a job needs the update; null = no admin scope granted. */
88
+ openAdmin: () => Promise<HeartbeatAdminSession | null>;
89
+ log: (msg: string) => void;
90
+ agentId?: string;
91
+ agentIsDefault?: boolean;
92
+ }): Promise<RefreshHeartbeatMessageOutcome>;
57
93
  /**
58
94
  * Whether an existing cron job counts as "the heartbeat already exists".
59
95
  * Union of the two matchers already in the codebase: the old setup path
@@ -80,6 +116,27 @@ export declare function isReefclawHeartbeatJob(job: {
80
116
  name?: unknown;
81
117
  payload?: unknown;
82
118
  } | null | undefined): boolean;
119
+ /**
120
+ * Is this cron job ReefClaw's — the only kind whose runs the heartbeat
121
+ * recorder may read or upload? Every other automation on the user's OpenClaw
122
+ * (OpenClaw's own memory consolidation, a user's private reminders) is theirs,
123
+ * not ours: on 2026-10-22 a customer's nightly memory job was uploaded with
124
+ * their private notes. ReefClaw's = named after ReefClaw (`reefclaw-heartbeat`,
125
+ * a user's own `reef-*` trading jobs — Ardi), or instructions naming ReefClaw.
126
+ * Wider than isReefclawHeartbeatJob on purpose: that one decides which job the
127
+ * bridge may ADOPT as the heartbeat; this one decides whose runs are ours.
128
+ */
129
+ export declare function isReefclawCronJob(job: {
130
+ name?: unknown;
131
+ payload?: unknown;
132
+ } | null | undefined): boolean;
133
+ /** The same verdict from a run alone, for when its job is unknown (a one-shot
134
+ * job already deleted, or cron.list unavailable): the job name carried in the
135
+ * run's `[cron:<id> <name>]` marker, else the run's prompt (the job message). */
136
+ export declare function isReefclawCronRun(run: {
137
+ jobName?: string | null;
138
+ prompt?: string | null;
139
+ }): boolean;
83
140
  /** The job whose state the dashboard shows as the agent's heartbeat: ours by
84
141
  * name first, then any ReefClaw heartbeat, then (legacy display fallback)
85
142
  * anything heartbeat-named. */
@@ -13,6 +13,7 @@
13
13
  // completion. Without it, a user who deliberately deleted their heartbeat cron
14
14
  // would get it resurrected on every bridge boot — the old setup-time path ran
15
15
  // once, and that operator-override behaviour must be preserved.
16
+ import { createHash } from 'crypto';
16
17
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
17
18
  import { dirname } from 'path';
18
19
  export const HEARTBEAT_CRON_NAME = 'reefclaw-heartbeat';
@@ -34,20 +35,37 @@ export const HEARTBEAT_TIMEOUT_SECONDS = 780;
34
35
  // measured costs on prod (2026-08-04): the agent paged the whole ~110KB
35
36
  // SKILL.md through sed/rg every beat (~100KB of tool output before any
36
37
  // trading work), and Steps 0-9 predate the pinned-plan/exit-gate discipline —
37
- // Step 8's exit rules are the scratch-the-winners instructions. SKILL.md is
38
- // consulted only when preparing a NEW entry.
39
- // NOTE: once-per-install marker semantics mean this message only reaches NEW
40
- // installs; existing boxes need a one-time `openclaw cron edit <id> --message`
41
- // (done on prod at deploy).
38
+ // Step 8's exit rules are the scratch-the-winners instructions.
39
+ // NOTE: the ensure writes this message only when it CREATES the job (once per
40
+ // install). A job still carrying one of our earlier defaults byte-for-byte is
41
+ // brought up to date on connect by refreshHeartbeatMessage below; an edited
42
+ // job, or one on the Decision Loop message, is never touched.
42
43
  // ★ The mandatory items are ENUMERATED here on purpose. The first (softer)
43
44
  // version of this message — "Run the HEARTBEAT.md checklist" — produced
44
45
  // 85-second beats on gpt-5.4-mini that skipped record_position_reviews,
45
46
  // get_wave9_status, and the liquidity batch entirely (observed on prod
46
47
  // 2026-08-04 12:25/12:40 UTC): the checklist being in context is not enough,
47
48
  // the beat prompt itself must name what cannot be skipped.
48
- export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read the checklist file skills/reefclaw/HEARTBEAT.md (it sits beside your ReefClaw SKILL.md; one read call) ' +
49
+ // ★ 2026-10-24: item (5), the ENTRY CHECK. The enumerated list had no entry
50
+ // step, and small models run exactly the list: a new user's agent
51
+ // (qwen3.7-flash) made 125 beats with 0 scan_pairs / 0 create_order, and the
52
+ // ClawHub canary (deepseek-v4-flash) 418 beats with none, while the boxes
53
+ // whose beat is the old Decision Loop message ran scan_pairs every beat and
54
+ // traded daily. It is worded as a MINIMUM so a model that already runs its
55
+ // own entry process is not narrowed by it, and it keeps every quality gate:
56
+ // scan_pairs at min_score 5 (SKILL.md G2), score_setup (the operator's
57
+ // Explore / Balanced / Selective GO bar lives there — an entry opens only on
58
+ // GO / STRONG_GO), get_sizing for the amount, and the full create_order
59
+ // field set named inline so no model invents or re-reads SKILL.md for it.
60
+ // It never relies on the agent seeing a Pause: the plugin refuses
61
+ // create_order while the operator has paused or stopped trading
62
+ // (plugin/src/config/operator-halt.ts). The checklist is named by its
63
+ // folder, not by a relative path: `skills/reefclaw/` resolves under the
64
+ // workspace, and a ClawHub install keeps its skill elsewhere
65
+ // (~/.openclaw/plugin-skills/reefclaw/), so that read failed there.
66
+ export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read HEARTBEAT.md from the folder that holds your ReefClaw SKILL.md (e.g. skills/reefclaw/HEARTBEAT.md; one read call) ' +
49
67
  'and execute EVERY checkbox in it. If that read fails, the items below ARE the checklist — do not look anywhere else for it, ' +
50
- 'and do NOT re-read SKILL.md from disk unless preparing a NEW entry. ' +
68
+ 'and do NOT re-read SKILL.md from disk: item (5) names everything an entry needs. ' +
51
69
  'NON-SKIPPABLE every beat: (1) query_trades({hours:1}) stop-watcher reconcile; ' +
52
70
  '(2) get_wave9_status() once, unconditionally; ' +
53
71
  '(3) if ANY position is open and the Position Decision Journal is enabled (record_position_reviews reports off-mode when it is not): ' +
@@ -56,10 +74,50 @@ export const HEARTBEAT_MESSAGE = 'Heartbeat. FIRST read the checklist file skill
56
74
  'plus get_resting_liquidity + get_liquidation_levels + get_liquidation_pulse for ALL positions in one parallel batch; ' +
57
75
  "(4) the Market Assessment reads — every tool takes ONE object argument, e.g. get_regime({symbol:'BTCUSDT'}), " +
58
76
  "get_market_structure({symbol:'BTC/USDT'}), get_market_intel({category:'news'}), get_crypto_metrics({symbol:'BTC/USDT'}); " +
59
- "where tools are reached through tool_call, pass {id:'<tool name>', args:{...}}. " +
77
+ '(5) the ENTRY CHECK — a minimum, never a limit on your own entry process. get_risk_summary() and get_liquidation_pulse() first; ' +
78
+ 'no new entry when get_risk_summary shows operator_halt, heat is elevated or higher, a risk limit is breached, or an active cascade runs against the side. Otherwise ' +
79
+ 'scan_pairs({min_score:5}) once and take the top-ranked setup without a reentry_caution, passing its symbol as printed to the read tools: ' +
80
+ "get_setup_detail({symbol}) gives direction, entry, stop and its first target; " +
81
+ "score_setup({symbol, direction:'LONG' or 'SHORT', setup_type:'<its strategy>', entry_price, stop_price, target_price}) gives the verdict. " +
82
+ 'Open it ONLY on GO or STRONG_GO, after the Pre-Entry checks in HEARTBEAT.md (track record, funding, learnings): ' +
83
+ 'get_sizing({symbol}) → amount = fetch_balance equity × sizePct ÷ |entry − stop|, at most 0.4 × equity ÷ entry; then ' +
84
+ "create_order({symbol written BASE/QUOTE (Binance prints BTCUSDT: write BTC/USDT; Hyperliquid already prints BTC/USDC), side:'buy' for long or 'sell' for short, " +
85
+ "type:'market', amount, stopPrice, target_price, invalidation_price (usually the stop), realization_rule ({type:'fixed_target'} unless you plan otherwise), " +
86
+ 'setup_type, thesis (1-2 sentences), regime, regime_confidence (get_setup_detail gives 0-1: multiply by 100), scorecard_verdict, confluence_score}); ' +
87
+ 'if it rejects the size, retry ONCE at the effective max it names ÷ entry. ' +
88
+ 'Otherwise say in ONE line why not. If create_order answers operator_halt or entitlement_expired, make no further entry this beat. ' +
89
+ "Where tools are reached through tool_call, pass {id:'<tool name>', args:{...}}. " +
60
90
  'Manage open positions by their pinned plan (invalidation_price / realization_rule) — do not re-argue the entry thesis each beat. ' +
61
91
  'Check tradingMode from fetch_balance — the source of truth for paper vs live. ' +
62
92
  'Batch independent tool calls in parallel. Trading tools only: no subagents, no web browsing.';
93
+ /**
94
+ * sha256 of every EARLIER default HEARTBEAT_MESSAGE without the entry check,
95
+ * byte-exact as shipped (git history of this file; OpenClaw stores the
96
+ * message verbatim — verified on the canary fleet 2026-10-24). A job whose
97
+ * message hashes to one of these is our untouched default, so it can be
98
+ * brought up to date. The 2026-07-22..24 "full Decision Loop (Steps 0-9)"
99
+ * message is deliberately NOT here: the Decision Loop includes the entry
100
+ * scan, and boxes still on it trade.
101
+ */
102
+ const SUPERSEDED_HEARTBEAT_MESSAGE_SHA256 = new Set([
103
+ '1b0bea9637111ddcf786d7fdb3cf2f1c2ceab3558b40abfaa8e0ed22f37f5615', // 251bef68 2026-08-04
104
+ '358cc3ec6b3b7ed647ac07c93e38cc3d79d1ffeebfc553db4beb7e27a34bdeb7', // da9f867a 2026-08-04
105
+ '09fdd0d906dcfa2847d5d7a28f0732081246536bc3e8fab620c38b8434a88323', // fb5dc39a 2026-08-04 .. c635209e 2026-09-27
106
+ 'df932f264b8a2fcd5d648cca913252b44fbf228b6f6e192cf43ae4d2facb9f66', // f2ccab02 2026-09-27
107
+ '475a3a5b57811a5ebc6b2f195403b7cba1a68fd9df8fe33ffa69f75ff8432610', // 5f44b304 2026-09-27
108
+ 'aef39fabcc76b8a2fa7ee4738b58a937ed17efdcd51c4f1022da6ac4b8b8aff8', // 595edbd1 2026-09-27 .. 100c1042 2026-10-22
109
+ // Interim drafts of item (5), never released: they ran only on the
110
+ // onboard-050c canary (2026-10-24/25 tests), which then gets the final text
111
+ // like any box.
112
+ 'b0a6ba3c205b3f9a44254d2ae9b203d6808573660c962cdd6e2004ca6a2ba5f2',
113
+ '880bbcecf4c812fbe4de681808e61d5a512605aa73a6cbf38548e07d70a9557c',
114
+ ]);
115
+ /** True for a message that is byte-identical to one of our superseded defaults. */
116
+ export function isSupersededHeartbeatMessage(message) {
117
+ if (typeof message !== 'string' || message.length === 0)
118
+ return false;
119
+ return SUPERSEDED_HEARTBEAT_MESSAGE_SHA256.has(createHash('sha256').update(message, 'utf8').digest('hex'));
120
+ }
63
121
  /**
64
122
  * Does this OpenClaw have at least one chat channel configured? Read from
65
123
  * openclaw.json `channels` (telegram / discord / whatsapp / … entries).
@@ -149,6 +207,116 @@ export async function reconcileHeartbeatDelivery(opts) {
149
207
  return 'failed';
150
208
  }
151
209
  }
210
+ /**
211
+ * Bring OUR untouched heartbeat job up to date with HEARTBEAT_MESSAGE.
212
+ *
213
+ * Why (2026-10-24): the message reaches a job only when it is created (once
214
+ * per install), so every box created from a superseded default kept a beat
215
+ * with no entry check, and the small-model ones never traded. Only a message
216
+ * BYTE-IDENTICAL to one we shipped is replaced (isSupersededHeartbeatMessage):
217
+ * an edited job, a user's own job and the older Decision Loop message are
218
+ * left exactly as they are, so a box that trades today does not change.
219
+ * Nothing else of the job changes either: cron.update REPLACES the payload
220
+ * block, so the full stored payload goes back with only `message` swapped (a
221
+ * partial payload would drop timeoutSeconds and toolsAllow), and the enabled
222
+ * state is never touched — a job the user switched off stays off.
223
+ *
224
+ * cron.list runs on the long-lived read/write session; the admin session is
225
+ * opened only when a job needs the update, and the job is checked again on
226
+ * that session right before the write. Runs on every bridge start (one
227
+ * cron.list). Never throws.
228
+ */
229
+ export async function refreshHeartbeatMessage(opts) {
230
+ const agentId = opts.agentId?.trim().toLowerCase() || undefined;
231
+ const agentIsDefault = opts.agentIsDefault ?? true;
232
+ const listJobs = async (rpc) => {
233
+ const resp = (await rpc.sendRpc('cron.list', { includeDisabled: true }));
234
+ return Array.isArray(resp?.jobs) ? resp.jobs : null;
235
+ };
236
+ const payloadOf = (job) => job.payload != null && typeof job.payload === 'object' ? job.payload : undefined;
237
+ const ours = (job) => cronJobBelongsToAgent(job, agentId, agentIsDefault);
238
+ const due = (jobs) => jobs.filter((j) => typeof j?.id === 'string' && ours(j) && payloadOf(j)?.kind === 'agentTurn' && isSupersededHeartbeatMessage(payloadOf(j)?.message));
239
+ let admin = null;
240
+ let adminTried = false;
241
+ const adminSession = async () => {
242
+ if (!adminTried) {
243
+ adminTried = true;
244
+ admin = await opts.openAdmin();
245
+ }
246
+ return admin;
247
+ };
248
+ const noAdmin = () => {
249
+ opts.log('Heartbeat cron: instructions not updated (the gateway gave no admin session) — retried on the next bridge start');
250
+ return 'failed';
251
+ };
252
+ try {
253
+ let jobs;
254
+ try {
255
+ jobs = await listJobs(opts.rpc);
256
+ }
257
+ catch (err) {
258
+ // OpenClaw 2026.7.x scoped cron.list itself to operator.admin.
259
+ if (!/missing scopes?:/i.test(err instanceof Error ? err.message : String(err)))
260
+ throw err;
261
+ const a = await adminSession();
262
+ if (!a)
263
+ return noAdmin();
264
+ jobs = await listJobs(a.rpc);
265
+ }
266
+ if (!jobs) {
267
+ opts.log('Heartbeat cron: instructions check skipped (cron.list returned no job list)');
268
+ return 'failed';
269
+ }
270
+ if (due(jobs).length === 0) {
271
+ return jobs.some((j) => ours(j) && payloadOf(j)?.message === HEARTBEAT_MESSAGE) ? 'current' : 'untouched';
272
+ }
273
+ const a = await adminSession();
274
+ if (!a)
275
+ return noAdmin();
276
+ // Checked again on the session that writes: a job edited since the first
277
+ // list is left alone.
278
+ const fresh = await listJobs(a.rpc);
279
+ if (!fresh) {
280
+ opts.log('Heartbeat cron: instructions not updated (cron.list returned no job list) — retried on the next bridge start');
281
+ return 'failed';
282
+ }
283
+ const confirmed = due(fresh);
284
+ if (confirmed.length === 0)
285
+ return 'untouched';
286
+ for (const job of confirmed) {
287
+ const payload = { ...payloadOf(job), message: HEARTBEAT_MESSAGE };
288
+ await a.rpc.sendRpc('cron.update', { id: job.id, patch: { payload } });
289
+ }
290
+ // Read it back: a gateway that accepted the update but ignored or
291
+ // reshaped the payload must not be reported as done (and every other
292
+ // field of the job must still be there).
293
+ const after = (await listJobs(a.rpc)) ?? [];
294
+ const stuck = (job) => {
295
+ const now = after.find((j) => j?.id === job.id);
296
+ const p = now ? payloadOf(now) : undefined;
297
+ if (!p || p.message !== HEARTBEAT_MESSAGE)
298
+ return false;
299
+ return Object.keys(payloadOf(job) ?? {}).every((k) => k in p);
300
+ };
301
+ const notStuck = confirmed.filter((job) => !stuck(job));
302
+ for (const job of confirmed.filter(stuck)) {
303
+ opts.log(`Heartbeat cron: instructions updated — each beat now includes the entry check (${String(job.name)})`);
304
+ }
305
+ if (notStuck.length > 0) {
306
+ opts.log(`Heartbeat cron: instructions update did not stick for ${notStuck.map((j) => String(j.name)).join(', ')} — ` +
307
+ 'the job is as the gateway keeps it; retried on the next bridge start');
308
+ return 'failed';
309
+ }
310
+ return 'refreshed';
311
+ }
312
+ catch (err) {
313
+ opts.log(`Heartbeat cron: instructions update failed (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — retried on the next bridge start`);
314
+ return 'failed';
315
+ }
316
+ finally {
317
+ admin?.close();
318
+ }
319
+ }
152
320
  /**
153
321
  * Whether an existing cron job counts as "the heartbeat already exists".
154
322
  * Union of the two matchers already in the codebase: the old setup path
@@ -189,6 +357,42 @@ export function isReefclawHeartbeatJob(job) {
189
357
  const msg = typeof payload?.message === 'string' ? payload.message : typeof payload?.text === 'string' ? payload.text : '';
190
358
  return REEFCLAW_BEAT_MESSAGE.test(msg);
191
359
  }
360
+ /** Instructions that make an automation ReefClaw's: the product name, a
361
+ * ReefClaw-only tool, or the Decision Loop of the pre-2026-08 beat message. */
362
+ const REEFCLAW_JOB_TEXT = /reef\s*claw|Decision Loop|record_position_reviews|query_trades|get_wave9_status/i;
363
+ /** `reefclaw-*` / `ReefClaw …`, or a user's own `reef-*` / `reef_*` job —
364
+ * never a bare "reef" ("Reef tank check" is not ours). */
365
+ const REEFCLAW_JOB_NAME = /reef\s*claw|^reef[-_]/i;
366
+ /**
367
+ * Is this cron job ReefClaw's — the only kind whose runs the heartbeat
368
+ * recorder may read or upload? Every other automation on the user's OpenClaw
369
+ * (OpenClaw's own memory consolidation, a user's private reminders) is theirs,
370
+ * not ours: on 2026-10-22 a customer's nightly memory job was uploaded with
371
+ * their private notes. ReefClaw's = named after ReefClaw (`reefclaw-heartbeat`,
372
+ * a user's own `reef-*` trading jobs — Ardi), or instructions naming ReefClaw.
373
+ * Wider than isReefclawHeartbeatJob on purpose: that one decides which job the
374
+ * bridge may ADOPT as the heartbeat; this one decides whose runs are ours.
375
+ */
376
+ export function isReefclawCronJob(job) {
377
+ // Any job the bridge may adopt as THE heartbeat is ours too, or its beats
378
+ // would be skipped while the dashboard reads its state.
379
+ if (isReefclawHeartbeatJob(job))
380
+ return true;
381
+ const name = job?.name;
382
+ if (typeof name === 'string' && REEFCLAW_JOB_NAME.test(name))
383
+ return true;
384
+ const payload = job?.payload;
385
+ const msg = typeof payload?.message === 'string' ? payload.message : typeof payload?.text === 'string' ? payload.text : '';
386
+ return REEFCLAW_JOB_TEXT.test(msg);
387
+ }
388
+ /** The same verdict from a run alone, for when its job is unknown (a one-shot
389
+ * job already deleted, or cron.list unavailable): the job name carried in the
390
+ * run's `[cron:<id> <name>]` marker, else the run's prompt (the job message). */
391
+ export function isReefclawCronRun(run) {
392
+ if (typeof run.jobName === 'string' && REEFCLAW_JOB_NAME.test(run.jobName))
393
+ return true;
394
+ return typeof run.prompt === 'string' && REEFCLAW_JOB_TEXT.test(run.prompt);
395
+ }
192
396
  /** The job whose state the dashboard shows as the agent's heartbeat: ours by
193
397
  * name first, then any ReefClaw heartbeat, then (legacy display fallback)
194
398
  * anything heartbeat-named. */
@@ -3,7 +3,7 @@ import { GatewayHttpClient, GatewayHttpError } from './gateway-http-client.js';
3
3
  * Logical tool names used by ReefClaw internally.
4
4
  * Each maps to one or more candidate actual tool names on the gateway.
5
5
  */
6
- export type LogicalTool = 'fetch_ticker' | 'fetch_balance' | 'fetch_ohlcv' | 'fetch_positions' | 'fetch_open_orders' | 'cancel_all_orders' | 'cancel_order' | 'close_position' | 'create_order' | 'get_market_structure' | 'get_crypto_metrics' | 'get_market_intel' | 'set_trading_mode' | 'set_exchange_credentials' | 'test_exchange_credentials' | 'clear_exchange_credentials' | 'hl_provision_agent_wallet' | 'hl_agent_wallet_status' | 'hl_submit_agent_approval' | 'get_bracket_config' | 'set_bracket_requirement';
6
+ export type LogicalTool = 'fetch_ticker' | 'fetch_balance' | 'fetch_ohlcv' | 'fetch_positions' | 'fetch_open_orders' | 'cancel_all_orders' | 'cancel_order' | 'close_position' | 'create_order' | 'get_market_structure' | 'get_crypto_metrics' | 'get_market_intel' | 'set_trading_mode' | 'set_exchange_credentials' | 'test_exchange_credentials' | 'clear_exchange_credentials' | 'hl_provision_agent_wallet' | 'hl_agent_wallet_status' | 'hl_submit_agent_approval' | 'get_bracket_config' | 'set_bracket_requirement' | 'set_operator_halt';
7
7
  /**
8
8
  * Build the test args used when probing each logical tool.
9
9
  *
@@ -25,6 +25,7 @@ const OPTIONAL_TOOLS = [
25
25
  'hl_submit_agent_approval',
26
26
  'get_bracket_config',
27
27
  'set_bracket_requirement',
28
+ 'set_operator_halt',
28
29
  ];
29
30
  /**
30
31
  * Candidate actual tool names to probe for each logical tool.
@@ -52,6 +53,7 @@ const CANDIDATES = {
52
53
  hl_submit_agent_approval: ['hl_submit_agent_approval'],
53
54
  get_bracket_config: ['get_bracket_config'],
54
55
  set_bracket_requirement: ['set_bracket_requirement'],
56
+ set_operator_halt: ['set_operator_halt'],
55
57
  };
56
58
  /** Default probe symbol when the caller does not supply the configured one.
57
59
  * Kept for back-compat with pre-symbol callers; real deployments should pass
@@ -126,6 +128,8 @@ export function buildProbeArgs(symbol = DEFAULT_PROBE_SYMBOL) {
126
128
  // Bracket-config probes: no-arg read; set with an invalid flag triggers early-return.
127
129
  get_bracket_config: {},
128
130
  set_bracket_requirement: { flag: '__probe__', value: false },
131
+ // No mode = a read: the probe can never set or clear a halt.
132
+ set_operator_halt: {},
129
133
  };
130
134
  }
131
135
  // ---- Discovery logic ----
@@ -18,6 +18,9 @@ export declare const SCAN_SLACK_MS: number;
18
18
  export declare const BOOTSTRAP_LOOKBACK_MS: number;
19
19
  /** Records processed per scan (bounds CPU + POST burst on a backfill). */
20
20
  export declare const MAX_PER_SCAN = 5;
21
+ /** Transcripts parsed per scan, recorded or skipped (bounds a backfill of
22
+ * the user's own frequent jobs when cron.list can't name them). */
23
+ export declare const MAX_PARSES_PER_SCAN = 20;
21
24
  /** Give up on a run after this many failed POST cycles. */
22
25
  export declare const MAX_POST_ATTEMPTS = 5;
23
26
  /** While the bridge's edge gate is closed a record is DEFERRED (no attempt
@@ -30,11 +33,20 @@ export declare const CRON_RUNS_COOLDOWN_MS: number;
30
33
  * (a store the recorder cannot read must not stay silent — Ardi, report #5). */
31
34
  export declare const BLIND_PROBE_INTERVAL_MS: number;
32
35
  export type { AgentRunLifecycleData };
36
+ /** A `cron.list` row, as far as telling ReefClaw's jobs apart needs it. */
37
+ export interface CronJobLite {
38
+ id?: unknown;
39
+ name?: unknown;
40
+ payload?: unknown;
41
+ }
33
42
  /** What the recorder needs from the provider — kept narrow so it is trivially
34
43
  * mockable and the provider stays the only thing that talks to the gateway. */
35
44
  export interface HeartbeatRunSource {
36
45
  /** `cron.runs` for the heartbeat job, newest first; null when unavailable. */
37
46
  fetchCronRuns(limit: number): Promise<CronRunLogLite[] | null>;
47
+ /** `cron.list` (disabled jobs included); null when unavailable. Absent →
48
+ * runs are judged by their own marker name / prompt. */
49
+ fetchCronJobs?(): Promise<readonly CronJobLite[] | null>;
38
50
  /** Dashboard hook: the provider stores a compact summary + model health. */
39
51
  noteHeartbeatRun(record: HeartbeatRunRecord): void;
40
52
  /** Active trading book, for the record's mode tag. */
@@ -64,6 +76,8 @@ export interface PostOutcome {
64
76
  terminal: boolean;
65
77
  status: number | null;
66
78
  error?: string;
79
+ /** The webapp accepted the POST but did not store the run (its reason). */
80
+ skipped?: string;
67
81
  }
68
82
  export declare class HeartbeatRunRecorder {
69
83
  private readonly opts;
@@ -83,6 +97,8 @@ export declare class HeartbeatRunRecorder {
83
97
  private store;
84
98
  private lastBlindProbeAt;
85
99
  private blindWarned;
100
+ /** Non-ReefClaw jobs already logged as skipped (one line per job). */
101
+ private readonly foreignJobsLogged;
86
102
  /** Counters for a one-line health summary in logs. */
87
103
  readonly stats: {
88
104
  scans: number;
@@ -90,6 +106,7 @@ export declare class HeartbeatRunRecorder {
90
106
  posted: number;
91
107
  postFailed: number;
92
108
  skippedNonCron: number;
109
+ skippedForeign: number;
93
110
  deferred: number;
94
111
  };
95
112
  constructor(opts: HeartbeatRunRecorderOptions);
@@ -115,6 +132,13 @@ export declare class HeartbeatRunRecorder {
115
132
  * head marker second (cheap), trajectory key third (covers a prompt without
116
133
  * the marker), else not a heartbeat. */
117
134
  private classify;
135
+ /** Does this cron run belong to a ReefClaw job? The live job definition
136
+ * decides when cron.list has it (the job id may only be in the trajectory
137
+ * key); otherwise the run's marker name, else its prompt. */
138
+ private judgeRun;
139
+ /** Mark a non-ReefClaw run done for good (one log line per job). */
140
+ private skipForeign;
141
+ private fetchCronJobsSafe;
118
142
  private fetchCronRunsSafe;
119
143
  /** POST one record to the webapp. Never throws. */
120
144
  post(record: HeartbeatRunRecord): Promise<PostOutcome>;