@reefclaw/openclaw-plugin 0.1.35 → 0.1.36

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/bridge/bridge.js CHANGED
@@ -1287,7 +1287,7 @@ export class Bridge {
1287
1287
  // 2026-07-11 — agent stranded on 0.0.5 with the tracker at 2.20.4). If
1288
1288
  // ANY agent-visible copy is behind the webapp version, re-apply anyway;
1289
1289
  // applySkillUpdate is idempotent across all copies.
1290
- const staleAgentCopies = readAgentVisibleSkillVersions().filter((v) => compareSemver(body.version, v) > 0);
1290
+ const staleAgentCopies = readAgentVisibleSkillVersions(this.paths.workspaceDir).filter((v) => compareSemver(body.version, v) > 0);
1291
1291
  if (compareSemver(body.version, this.currentSkillVersion) <= 0 && staleAgentCopies.length === 0) {
1292
1292
  logger.info(TAG, `SKILL.md webapp pull: local v${this.currentSkillVersion ?? 'unknown'} already >= webapp v${body.version} — nothing to do`);
1293
1293
  this.skillPullInFlight = false;
@@ -19,6 +19,29 @@ export interface CcxtPosition {
19
19
  notional?: number;
20
20
  [key: string]: unknown;
21
21
  }
22
+ /** Plugin-computed day figures that ride on every `fetch_balance` response.
23
+ *
24
+ * ★ WHY THE ANCHOR RIDES HERE (2026-09-20 rig incident): the plugin rolls its
25
+ * UTC-midnight Day-P&L anchor (`sessionStartNav`) at 00:00:01, but the bridge
26
+ * used to adopt it ONLY inside the reconnect snapshot (`fetchFreshBalance`).
27
+ * On a live box with no dashboard reconnect after midnight the bridge kept
28
+ * YESTERDAY's anchor for 7 h 15 m and the KPI strip showed two days of P&L as
29
+ * "today" (−12.31 vs the true −4.74) — and the RED-zone daily-drawdown math
30
+ * read the same stale anchor. This 10 s poll is the only balance read that
31
+ * runs unconditionally, so the anchor must be adopted from it. */
32
+ export interface BalanceExtras {
33
+ /** Σ realized today, net of fees + funding (plugin's income / day-anchor value). */
34
+ realizedPnlToday?: number;
35
+ /** wallet_at_UTC_midnight (+ capital flows since) — the Day-P&L anchor. */
36
+ sessionStartNav?: number;
37
+ /** Plugin's NAV (= wallet + Σ uPnl on live; simulator equity on paper). */
38
+ equity?: number;
39
+ }
40
+ /** Pull the finite numeric extras off a raw `fetch_balance` payload. Returns
41
+ * undefined when none is present (an old plugin, or a rate-limited empty
42
+ * response) so the consumer never mistakes "absent" for "zero". Pure — tested
43
+ * directly. */
44
+ export declare function extractBalanceExtras(data: unknown): BalanceExtras | undefined;
22
45
  /** Callbacks fired by the Poller when fresh data arrives from polls. */
23
46
  export interface PollerCallbacks {
24
47
  /** Ticker data from fetch_ticker — fires every 1s */
@@ -28,15 +51,14 @@ export interface PollerCallbacks {
28
51
  /** Raw CCXT positions from fetch_positions — fires every 3s */
29
52
  onPositions: (positions: CcxtPosition[]) => void;
30
53
  /** Parsed balance from fetch_balance — fires every 10s. `extras` carries the
31
- * plugin-computed day figures that ride on the same response when present. */
54
+ * plugin-computed day figures that ride on the same response when present
55
+ * (see `BalanceExtras`). */
32
56
  onBalance: (balance: {
33
57
  currency: string;
34
58
  total: number;
35
59
  available: number;
36
60
  locked: number;
37
- }, extras?: {
38
- realizedPnlToday?: number;
39
- }) => void;
61
+ }, extras?: BalanceExtras) => void;
40
62
  /** Parsed open orders from fetch_open_orders — fires every 3s */
41
63
  onOpenOrders: (orders: OrderData[]) => void;
42
64
  /** Multi-TF analysis from get_market_structure — fires every 30s */
@@ -43,6 +43,24 @@ export const OPEN_ORDERS_INTERVAL_MS = 60_000;
43
43
  export const MARKET_STRUCTURE_INTERVAL_MS = 60_000;
44
44
  const CRYPTO_METRICS_INTERVAL_MS = 60_000;
45
45
  const VOLUME_ANALYSIS_INTERVAL_MS = 15_000;
46
+ const BALANCE_EXTRA_KEYS = ['realizedPnlToday', 'sessionStartNav', 'equity'];
47
+ /** Pull the finite numeric extras off a raw `fetch_balance` payload. Returns
48
+ * undefined when none is present (an old plugin, or a rate-limited empty
49
+ * response) so the consumer never mistakes "absent" for "zero". Pure — tested
50
+ * directly. */
51
+ export function extractBalanceExtras(data) {
52
+ if (!data || typeof data !== 'object')
53
+ return undefined;
54
+ const rec = data;
55
+ let out;
56
+ for (const key of BALANCE_EXTRA_KEYS) {
57
+ const v = rec[key];
58
+ if (typeof v === 'number' && Number.isFinite(v)) {
59
+ (out ??= {})[key] = v;
60
+ }
61
+ }
62
+ return out;
63
+ }
46
64
  // ---- Poller class ----
47
65
  /** 429 exponential-backoff schedule (ms). After each consecutive 429 we
48
66
  * advance one step; a clean poll resets to step 0. Capped so we never go
@@ -378,8 +396,7 @@ export class Poller {
378
396
  const tool = this.toolMap.fetch_balance;
379
397
  const result = await this.http.invoke(tool, {});
380
398
  const balance = mapCcxtBalance(result.data, this.quoteCurrency);
381
- const realized = result.data?.realizedPnlToday;
382
- this.callbacks.onBalance(balance, typeof realized === 'number' && Number.isFinite(realized) ? { realizedPnlToday: realized } : undefined);
399
+ this.callbacks.onBalance(balance, extractBalanceExtras(result.data));
383
400
  }
384
401
  /** Poll positions NOW (same ban-gate + in-flight guard as the timer). The
385
402
  * RED-zone guard calls this when the wallet/positions snapshot is torn by a
@@ -415,6 +415,9 @@ export function parseSessionTranscript(text) {
415
415
  let lastAssistantText = null;
416
416
  let lastAnyText = null;
417
417
  let firstUserSeen = false;
418
+ // The model the session is currently running on (from model_change events
419
+ // and assistant messages) — a model_change only counts as a switch against it.
420
+ let currentModel = null;
418
421
  for (const raw of text.split('\n')) {
419
422
  const line = raw.trim();
420
423
  if (!line)
@@ -445,7 +448,26 @@ export function parseSessionTranscript(text) {
445
448
  }
446
449
  case 'model_change': {
447
450
  const pm = providerModel(rec.provider, rec.modelId);
448
- pushEvent(out, { kind: 'model_change', at, detail: pm ?? 'model changed' });
451
+ // A model_change is a SWITCH only when the session already ran on a
452
+ // different model. OpenClaw ≥ 2026.9 opens every isolated cron session
453
+ // with `{type:"model_change", parentId:null}` at seq 1 — the initial
454
+ // model assignment, one per beat, same model start to finish. Counting
455
+ // it made model health read "degraded: 1 model change" on every beat
456
+ // of every 2026.9 box (Ardi report #7: 52 sessions, 52 records, all at
457
+ // seq 1), so the dot could never be green. The first model seen sets
458
+ // the baseline (and still names the beat's model when no assistant
459
+ // message ever arrives); a repeat of the current model is a no-op.
460
+ if (pm && currentModel !== null && pm !== currentModel) {
461
+ pushEvent(out, { kind: 'model_change', at, detail: pm });
462
+ }
463
+ if (pm) {
464
+ // `models` stays "models that answered" (assistant messages); the
465
+ // baseline is the one exception so a beat that dies before any
466
+ // assistant message still reports the model it was assigned.
467
+ if (currentModel === null && out.models.length === 0)
468
+ out.models.push(pm);
469
+ currentModel = pm;
470
+ }
449
471
  break;
450
472
  }
451
473
  case 'thinking_level_change': {
@@ -474,6 +496,8 @@ export function parseSessionTranscript(text) {
474
496
  const pm = providerModel(m.provider, m.responseModel ?? m.model);
475
497
  if (pm && !out.models.includes(pm))
476
498
  out.models.push(pm);
499
+ if (pm)
500
+ currentModel = pm;
477
501
  if (typeof m.api === 'string' && !out.api)
478
502
  out.api = m.api;
479
503
  const u = m.usage;
@@ -64,6 +64,10 @@ export interface ConnectorUpdateOutcome {
64
64
  output?: string;
65
65
  /** True when the caller must re-submit with acknowledgeOpenPositions. */
66
66
  requiresPositionAck?: boolean;
67
+ /** Completed with the files in place, but the installer could not restart
68
+ * the gateway (its output carries INSTALLER_NOT_RESTARTED_MARKER) — the
69
+ * previous version is still running until the operator restarts it. */
70
+ restartRequired?: boolean;
67
71
  }
68
72
  /**
69
73
  * Map a gateway error from `terminal.open` onto an operator-readable outcome.
@@ -84,6 +88,13 @@ export declare function describeUpdateDisabled(): ConnectorUpdateOutcome;
84
88
  * broken, so the distinction is explicit and tested.
85
89
  */
86
90
  export declare function classifyTransportLoss(started: boolean): ConnectorUpdateStatus;
91
+ /** What the installer prints when it placed the new version but could not
92
+ * restart the gateway (installer/src/gateway-restart.ts NOT_RESTARTED_MARKER
93
+ * — inside a Docker container that is the normal outcome, only the host can
94
+ * restart the container). The installer still exits 0 (the files ARE
95
+ * installed), so completion is inspected for it. Pinned across packages. */
96
+ export declare const INSTALLER_NOT_RESTARTED_MARKER = "GATEWAY NOT RESTARTED";
97
+ export declare function installerReportedNoRestart(screen: string | null | undefined): boolean;
87
98
  /** Extract the exit code that follows the DONE sentinel, if it has appeared. */
88
99
  export declare function parseDoneSentinel(screen: string): {
89
100
  done: boolean;
@@ -122,8 +133,46 @@ export declare function checkPositionGuard(opts: StartOptions): ConnectorUpdateO
122
133
  export declare function startConnectorUpdate(rpc: TerminalRpc, opts: StartOptions,
123
134
  /** Exact connector release to install — from fetchPinnedConnectVersion, nowhere else. */
124
135
  version: string): Promise<ConnectorUpdateOutcome>;
125
- /** Read the current screen contents. Returns null when the session is gone. */
136
+ /** Read the current screen contents via `terminal.text`. Returns null when the
137
+ * session is gone. Prefer `createTerminalReader` — `terminal.text` no longer
138
+ * exists on OpenClaw ≥ 2026.8 (see there). */
126
139
  export declare function readTerminalText(rpc: TerminalRpc, sessionId: string): Promise<string | null>;
140
+ /** The gateway's reply to a method it does not have. A capability fact about
141
+ * the box, not a sign the box went away. */
142
+ export declare function isUnknownMethodError(err: unknown): boolean;
143
+ /** Reduce raw PTY output to the plain text a human (or the marker scan) would
144
+ * read — what the removed `terminal.text` used to do server-side. Handles the
145
+ * families a shell + npm + the installer emit: CSI (incl. private parameter
146
+ * bytes `<=>?:` and 8-bit `\x9b`), OSC (BEL- or ST-terminated), charset
147
+ * designations (`ESC ( B`), DEC save/restore/keypad (`ESC 7`, `ESC 8`,
148
+ * `ESC =`, `ESC >`), then carriage-return overwrites (progress bars redraw a
149
+ * line with `\r`; keep the last rendering) and stray C0 controls. */
150
+ export declare function stripAnsi(s: string): string;
151
+ export interface TerminalReader {
152
+ /** Current output of the session; null when the session/gateway is gone. */
153
+ read(sessionId: string): Promise<string | null>;
154
+ /** Which method served the last successful read (for the log line). */
155
+ readonly method: 'terminal.attach' | 'terminal.text' | null;
156
+ /** True once BOTH reads answered `unknown method`: the gateway is alive but
157
+ * offers no way to watch the PTY (no known OpenClaw does this; guarded so a
158
+ * null read from it is never mistaken for the restart). */
159
+ readonly unreadable: boolean;
160
+ }
161
+ /**
162
+ * Reads a PTY's output on any OpenClaw that has `terminal.open` at all.
163
+ *
164
+ * OpenClaw's 2026.7 terminal family offered two reads — `terminal.text` (the
165
+ * rendered screen) and `terminal.attach` (the raw replay `buffer`) — and
166
+ * REMOVED `terminal.text` in 2026.8 (gateway-protocol CHANGELOG, #121387). A
167
+ * bridge that only knew `terminal.text` got `unknown method` on every poll
168
+ * from 2026.8.1 on, counted the two rejections as the gateway dying, and
169
+ * reported "restarting" ~3 s into every one-click update with no output —
170
+ * while the installer kept running unwatched in a PTY that the dropped admin
171
+ * session left to be reaped. So: `terminal.attach` first (it exists wherever
172
+ * `terminal.open` does), `terminal.text` for a gateway that answers
173
+ * `unknown method` to attach, and an unknown-method reply is NEVER a dead read.
174
+ */
175
+ export declare function createTerminalReader(rpc: TerminalRpc): TerminalReader;
127
176
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
128
177
  export declare function closeTerminal(rpc: TerminalRpc, sessionId: string): Promise<void>;
129
178
  /** The subset of GatewayWsClient the admin session needs — injected so the
@@ -158,6 +207,8 @@ export interface RunOptions {
158
207
  maxPolls?: number;
159
208
  /** Injected for tests. */
160
209
  sleep?: (ms: number) => Promise<void>;
210
+ /** Injected for tests; defaults to createTerminalReader(rpc). */
211
+ reader?: TerminalReader;
161
212
  }
162
213
  /**
163
214
  * Poll the PTY and emit progress until the command finishes or the gateway
@@ -178,6 +178,19 @@ export function describeOpenFailure(err) {
178
178
  + `command to your agent, or ${manualUpdateHint()}. After that, updates are one click.`,
179
179
  };
180
180
  }
181
+ // No terminal RPC at all: OpenClaw < 2026.7 has no `terminal.*` methods, so
182
+ // the gateway answers `unknown method: terminal.open`. That is a fact about
183
+ // the box's OpenClaw version, not a fault, and no retry / "Update anyway"
184
+ // changes it (the rig on 2026.6.9 looped on exactly this, 2026-09-20).
185
+ if (/unknown method/.test(lower)) {
186
+ return {
187
+ ok: false,
188
+ status: 'blocked',
189
+ message: 'This box runs an OpenClaw older than 2026.7, which has no terminal API, so ReefClaw cannot run the '
190
+ + 'update for you. Upgrade OpenClaw to enable one-click updates; until then, paste the manual command '
191
+ + `to your agent, or ${manualUpdateHint()}.`,
192
+ };
193
+ }
181
194
  return {
182
195
  ok: false,
183
196
  status: 'failed',
@@ -203,6 +216,15 @@ export function describeUpdateDisabled() {
203
216
  export function classifyTransportLoss(started) {
204
217
  return started ? 'restarting' : 'failed';
205
218
  }
219
+ /** What the installer prints when it placed the new version but could not
220
+ * restart the gateway (installer/src/gateway-restart.ts NOT_RESTARTED_MARKER
221
+ * — inside a Docker container that is the normal outcome, only the host can
222
+ * restart the container). The installer still exits 0 (the files ARE
223
+ * installed), so completion is inspected for it. Pinned across packages. */
224
+ export const INSTALLER_NOT_RESTARTED_MARKER = 'GATEWAY NOT RESTARTED';
225
+ export function installerReportedNoRestart(screen) {
226
+ return typeof screen === 'string' && screen.includes(INSTALLER_NOT_RESTARTED_MARKER);
227
+ }
206
228
  /** Extract the exit code that follows the DONE sentinel, if it has appeared. */
207
229
  export function parseDoneSentinel(screen) {
208
230
  const idx = screen.lastIndexOf(DONE_SENTINEL);
@@ -296,7 +318,9 @@ version) {
296
318
  message: 'Update started. The agent restarts when it finishes, so the dashboard will reconnect on its own.',
297
319
  };
298
320
  }
299
- /** Read the current screen contents. Returns null when the session is gone. */
321
+ /** Read the current screen contents via `terminal.text`. Returns null when the
322
+ * session is gone. Prefer `createTerminalReader` — `terminal.text` no longer
323
+ * exists on OpenClaw ≥ 2026.8 (see there). */
300
324
  export async function readTerminalText(rpc, sessionId) {
301
325
  try {
302
326
  const res = await rpc('terminal.text', { sessionId });
@@ -315,6 +339,122 @@ export async function readTerminalText(rpc, sessionId) {
315
339
  return null;
316
340
  }
317
341
  }
342
+ /** The gateway's reply to a method it does not have. A capability fact about
343
+ * the box, not a sign the box went away. */
344
+ export function isUnknownMethodError(err) {
345
+ return /unknown method/i.test(err instanceof Error ? err.message : String(err));
346
+ }
347
+ /** Reduce raw PTY output to the plain text a human (or the marker scan) would
348
+ * read — what the removed `terminal.text` used to do server-side. Handles the
349
+ * families a shell + npm + the installer emit: CSI (incl. private parameter
350
+ * bytes `<=>?:` and 8-bit `\x9b`), OSC (BEL- or ST-terminated), charset
351
+ * designations (`ESC ( B`), DEC save/restore/keypad (`ESC 7`, `ESC 8`,
352
+ * `ESC =`, `ESC >`), then carriage-return overwrites (progress bars redraw a
353
+ * line with `\r`; keep the last rendering) and stray C0 controls. */
354
+ export function stripAnsi(s) {
355
+ return (s
356
+ // npm's spinner redraws its line with "cursor to column 1" (CSI 1G) +
357
+ // "clear line" instead of \r; make it an overwrite point too, so the
358
+ // pane shows the last frame rather than a wall of braille glyphs.
359
+ // eslint-disable-next-line no-control-regex
360
+ .replace(/(?:\u001b\[|\u009b)0?1?G/g, '\r')
361
+ // eslint-disable-next-line no-control-regex
362
+ .replace(/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/g, '') // CSI
363
+ // eslint-disable-next-line no-control-regex
364
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, '') // OSC
365
+ // eslint-disable-next-line no-control-regex
366
+ .replace(/\u001b[()*+][0-~]/g, '') // charset designation, e.g. ESC ( B
367
+ // eslint-disable-next-line no-control-regex
368
+ .replace(/\u001b[@-Z\\-_=>78]/g, '') // lone ESC + final (Fe / Fp)
369
+ .replace(/\r+\n/g, '\n') // CRLF → LF
370
+ .replace(/(^|\n)[^\n]*\r(?=[^\n])/g, '$1') // `\r` overwrite: keep what came after
371
+ .replace(/\r/g, '')
372
+ // eslint-disable-next-line no-control-regex
373
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '') // other C0 / DEL
374
+ );
375
+ }
376
+ /**
377
+ * Reads a PTY's output on any OpenClaw that has `terminal.open` at all.
378
+ *
379
+ * OpenClaw's 2026.7 terminal family offered two reads — `terminal.text` (the
380
+ * rendered screen) and `terminal.attach` (the raw replay `buffer`) — and
381
+ * REMOVED `terminal.text` in 2026.8 (gateway-protocol CHANGELOG, #121387). A
382
+ * bridge that only knew `terminal.text` got `unknown method` on every poll
383
+ * from 2026.8.1 on, counted the two rejections as the gateway dying, and
384
+ * reported "restarting" ~3 s into every one-click update with no output —
385
+ * while the installer kept running unwatched in a PTY that the dropped admin
386
+ * session left to be reaped. So: `terminal.attach` first (it exists wherever
387
+ * `terminal.open` does), `terminal.text` for a gateway that answers
388
+ * `unknown method` to attach, and an unknown-method reply is NEVER a dead read.
389
+ */
390
+ export function createTerminalReader(rpc) {
391
+ let attachSupported = null; // null = not yet probed
392
+ let textSupported = null;
393
+ let method = null;
394
+ const viaAttach = async (sessionId) => {
395
+ try {
396
+ const res = (await rpc('terminal.attach', { sessionId }));
397
+ const buffer = res && typeof res === 'object' && typeof res.buffer === 'string' ? res.buffer : '';
398
+ return stripAnsi(buffer);
399
+ }
400
+ catch (err) {
401
+ return isUnknownMethodError(err) ? 'unsupported' : null;
402
+ }
403
+ };
404
+ const viaText = async (sessionId) => {
405
+ try {
406
+ const res = await rpc('terminal.text', { sessionId });
407
+ if (typeof res === 'string')
408
+ return res;
409
+ if (res && typeof res === 'object') {
410
+ const t = res;
411
+ if (typeof t.text === 'string')
412
+ return t.text;
413
+ if (typeof t.data === 'string')
414
+ return t.data;
415
+ }
416
+ return '';
417
+ }
418
+ catch (err) {
419
+ return isUnknownMethodError(err) ? 'unsupported' : null;
420
+ }
421
+ };
422
+ return {
423
+ get method() {
424
+ return method;
425
+ },
426
+ get unreadable() {
427
+ return attachSupported === false && textSupported === false;
428
+ },
429
+ async read(sessionId) {
430
+ if (attachSupported !== false) {
431
+ const r = await viaAttach(sessionId);
432
+ if (r !== 'unsupported') {
433
+ attachSupported = true;
434
+ if (r !== null)
435
+ method = 'terminal.attach';
436
+ return r;
437
+ }
438
+ attachSupported = false;
439
+ logger.info(TAG, 'terminal.attach is not available on this gateway — reading via terminal.text');
440
+ }
441
+ if (textSupported !== false) {
442
+ const r = await viaText(sessionId);
443
+ if (r !== 'unsupported') {
444
+ textSupported = true;
445
+ if (r !== null)
446
+ method = 'terminal.text';
447
+ return r;
448
+ }
449
+ textSupported = false;
450
+ }
451
+ // Neither read exists: the gateway is alive but we cannot watch the PTY
452
+ // (`unreadable` tells the loop this null is not the restart).
453
+ logger.warn(TAG, 'neither terminal.attach nor terminal.text is available on this gateway — cannot watch the update');
454
+ return null;
455
+ },
456
+ };
457
+ }
318
458
  /** Best-effort PTY cleanup. Never throws — cleanup failure must not mask an outcome. */
319
459
  export async function closeTerminal(rpc, sessionId) {
320
460
  await rpc('terminal.close', { sessionId }).catch(() => undefined);
@@ -373,11 +513,26 @@ export async function runConnectorUpdate(rpc, sessionId, emit, opts = {}) {
373
513
  // Generous: an npm install on a small VPS is slow (240 × 1.5 s = 6 min).
374
514
  const maxPolls = opts.maxPolls ?? 240;
375
515
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
516
+ const reader = opts.reader ?? createTerminalReader(rpc);
376
517
  let lastEmitted = '';
377
518
  let consecutiveDeadReads = 0;
378
519
  for (let i = 0; i < maxPolls; i++) {
379
520
  await sleep(pollMs);
380
- const screen = await readTerminalText(rpc, sessionId);
521
+ const screen = await reader.read(sessionId);
522
+ if (screen === null && reader.unreadable) {
523
+ // Alive but unwatchable — not a restart, not a completion. Leave the PTY
524
+ // running (the installer is in it) and say exactly that.
525
+ const outcome = {
526
+ ok: false,
527
+ status: 'failed',
528
+ sessionId,
529
+ output: lastEmitted,
530
+ message: 'The update was started, but this gateway offers no way to watch the terminal (neither terminal.attach nor '
531
+ + 'terminal.text), so its outcome cannot be reported here. Check the plugin version notice on the dashboard in a few minutes.',
532
+ };
533
+ emit(outcome);
534
+ return outcome;
535
+ }
381
536
  if (screen !== null)
382
537
  consecutiveDeadReads = 0;
383
538
  else if (++consecutiveDeadReads < 2)
@@ -402,15 +557,25 @@ export async function runConnectorUpdate(rpc, sessionId, emit, opts = {}) {
402
557
  if (isCredibleCompletion(screen)) {
403
558
  const { exitCode } = parseDoneSentinel(screen);
404
559
  const ok = exitCode === 0;
560
+ // Exit 0 + the installer's own "not restarted" verdict: the files are in
561
+ // place but the OLD gateway is still running (a Docker box, or any
562
+ // unmanaged gateway the CLI cannot signal). Say so — "the agent restarts
563
+ // to load it" would be false, and no restart is coming from this side.
564
+ const restartRequired = ok && installerReportedNoRestart(screen);
405
565
  const outcome = {
406
566
  ok,
407
567
  status: 'completed',
408
568
  sessionId,
409
569
  exitCode,
410
570
  output: screen,
411
- message: ok
412
- ? 'Connector updated. The agent restarts to load it.'
413
- : `The updater exited with code ${exitCode}. The connector was left as it was.`,
571
+ ...(restartRequired ? { restartRequired: true } : {}),
572
+ message: !ok
573
+ ? `The updater exited with code ${exitCode}. The connector was left as it was.`
574
+ : restartRequired
575
+ ? 'Connector files updated, but the gateway was NOT restarted, so the previous version is still running. '
576
+ + 'If OpenClaw runs in Docker, restart the container from the host machine (docker restart <container>); '
577
+ + 'otherwise restart OpenClaw. The new version loads then.'
578
+ : 'Connector updated. The agent restarts to load it.',
414
579
  };
415
580
  emit(outcome);
416
581
  await closeTerminal(rpc, sessionId);
@@ -352,6 +352,14 @@ export declare class GatewayProvider implements OpenClawProvider {
352
352
  */
353
353
  private emitSyntheticFill;
354
354
  private onPollerBalance;
355
+ /**
356
+ * Adopt the plugin-provided Day-P&L anchor whenever it differs from ours.
357
+ * Shared by the 10 s balance poll and the reconnect snapshot so the two can
358
+ * never disagree about which anchor is current. No-op for a missing / zero /
359
+ * garbage value (old plugin, torn response) — the self-seed fallback in
360
+ * trySetSessionStartNav covers plugins that emit nothing.
361
+ */
362
+ private syncPluginSessionNav;
355
363
  /**
356
364
  * Set session start NAV once both balance AND positions have been received.
357
365
  * Checks persisted file first — if today's NAV was already captured in a
@@ -1781,9 +1781,41 @@ export class GatewayProvider {
1781
1781
  }
1782
1782
  this.balance = balance;
1783
1783
  this.hasReceivedBalance = true;
1784
+ // ★ Adopt the plugin's Day-P&L anchor from THIS poll, not only from the
1785
+ // reconnect snapshot. The plugin rolls `sessionStartNav` at UTC midnight;
1786
+ // before this the bridge only picked the new value up in
1787
+ // fetchFreshBalance() (a dashboard reconnect), so a live box with no
1788
+ // reconnect after midnight showed yesterday's anchor for hours — the
1789
+ // 2026-09-20 rig incident: Day P&L −12.31 (two UTC days) while the true
1790
+ // figure was −4.74, until a reconnect at 07:15 UTC synced it. The same
1791
+ // stale anchor feeds the RED-zone daily-drawdown math, so this is a
1792
+ // safety-floor input, not just a KPI. Must run BEFORE trySetSessionStartNav
1793
+ // (so the self-seed fallback never fires when the plugin has an anchor)
1794
+ // and BEFORE emitRiskUpdate (so the emitted numbers use the fresh anchor).
1795
+ if (typeof extras?.equity === 'number')
1796
+ this.equity = extras.equity;
1797
+ this.syncPluginSessionNav(extras?.sessionStartNav);
1784
1798
  this.trySetSessionStartNav();
1785
1799
  this.emitRiskUpdate();
1786
1800
  }
1801
+ /**
1802
+ * Adopt the plugin-provided Day-P&L anchor whenever it differs from ours.
1803
+ * Shared by the 10 s balance poll and the reconnect snapshot so the two can
1804
+ * never disagree about which anchor is current. No-op for a missing / zero /
1805
+ * garbage value (old plugin, torn response) — the self-seed fallback in
1806
+ * trySetSessionStartNav covers plugins that emit nothing.
1807
+ */
1808
+ syncPluginSessionNav(pluginNav) {
1809
+ if (!shouldSyncPluginSessionNav(pluginNav, this.sessionStartNav))
1810
+ return;
1811
+ const prev = this.sessionStartNav;
1812
+ this.sessionStartNav = pluginNav;
1813
+ // Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
1814
+ // re-anchors on a stale sessionDate) doesn't flap against the sync.
1815
+ this.sessionDate = todayDateStr();
1816
+ saveSessionStartNav(this.workspaceDir(), pluginNav);
1817
+ logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
1818
+ }
1787
1819
  /**
1788
1820
  * Set session start NAV once both balance AND positions have been received.
1789
1821
  * Checks persisted file first — if today's NAV was already captured in a
@@ -2012,19 +2044,9 @@ export class GatewayProvider {
2012
2044
  // Crossing UTC midnight is handled automatically — the plugin's anchor
2013
2045
  // refreshes, the skill syncs next poll. The skill's self-seed
2014
2046
  // (trySetSessionStartNav) remains only as a fallback for plugins too old
2015
- // to emit sessionStartNav.
2016
- {
2017
- const pluginNav = result.data.sessionStartNav;
2018
- if (shouldSyncPluginSessionNav(pluginNav, this.sessionStartNav)) {
2019
- const prev = this.sessionStartNav;
2020
- this.sessionStartNav = pluginNav;
2021
- // Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
2022
- // re-anchors on a stale sessionDate) doesn't flap against the sync.
2023
- this.sessionDate = todayDateStr();
2024
- saveSessionStartNav(this.workspaceDir(), pluginNav);
2025
- logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
2026
- }
2027
- }
2047
+ // to emit sessionStartNav. The 10 s balance poll (onPollerBalance) runs
2048
+ // the SAME sync, so a midnight rollover never waits for a reconnect.
2049
+ this.syncPluginSessionNav(result.data.sessionStartNav);
2028
2050
  return mapCcxtBalance(result.data, this.quoteCurrency);
2029
2051
  }
2030
2052
  catch (err) {
@@ -2,15 +2,20 @@
2
2
  export declare function parseSkillVersion(content: string): string | null;
3
3
  /** Read current SKILL.md version from disk */
4
4
  export declare function readLocalSkillVersion(workspaceDir?: string): string | null;
5
- /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
6
- * plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
7
- * — what OpenClaw's skill loader actually reads on chat-channel installs.
8
- * A plugin (re)install resets these to the bundled bootstrap while the
9
- * workspace copy (the version tracker above) survives, so the tracker alone
10
- * cannot be trusted for "already up to date" (observed live 2026-07-11: agent
11
- * stranded on bootstrap 0.0.5 while the tracker read 2.20.4). Fail-soft:
12
- * unreadable dirs/files are skipped; no extensions dir → empty list. */
13
- export declare function readAgentVisibleSkillVersions(): string[];
5
+ /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies — the files
6
+ * OpenClaw's skill loader actually reads, as opposed to the workspace tracker
7
+ * above. Two layouts:
8
+ * - `~/.openclaw/extensions/<plugin>/skills/<skill>/SKILL.md` (chat-channel
9
+ * installs). A plugin (re)install resets it to the bundled bootstrap while
10
+ * the tracker survives (observed live 2026-07-11: agent stranded on 0.0.5
11
+ * with the tracker at 2.20.4).
12
+ * - `<workspace>/skills/<skill>/SKILL.md` (every npx-installer box). The
13
+ * same reset happens there whenever anything re-runs
14
+ * `openclaw skills install --force` on the placed bootstrap
15
+ * (found 2026-09-19 while reviewing the installer's re-run path).
16
+ * The tracker alone cannot be trusted for "already up to date" in either
17
+ * layout. Fail-soft: unreadable dirs/files are skipped. */
18
+ export declare function readAgentVisibleSkillVersions(workspaceDir?: string): string[];
14
19
  /**
15
20
  * Compare two semver strings.
16
21
  * Returns 1 if a > b, -1 if a < b, 0 if equal.
@@ -19,46 +19,57 @@ export function readLocalSkillVersion(workspaceDir = DEFAULT_WORKSPACE_DIR) {
19
19
  return null;
20
20
  }
21
21
  }
22
- /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
23
- * plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
24
- * — what OpenClaw's skill loader actually reads on chat-channel installs.
25
- * A plugin (re)install resets these to the bundled bootstrap while the
26
- * workspace copy (the version tracker above) survives, so the tracker alone
27
- * cannot be trusted for "already up to date" (observed live 2026-07-11: agent
28
- * stranded on bootstrap 0.0.5 while the tracker read 2.20.4). Fail-soft:
29
- * unreadable dirs/files are skipped; no extensions dir → empty list. */
30
- export function readAgentVisibleSkillVersions() {
22
+ /** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies — the files
23
+ * OpenClaw's skill loader actually reads, as opposed to the workspace tracker
24
+ * above. Two layouts:
25
+ * - `~/.openclaw/extensions/<plugin>/skills/<skill>/SKILL.md` (chat-channel
26
+ * installs). A plugin (re)install resets it to the bundled bootstrap while
27
+ * the tracker survives (observed live 2026-07-11: agent stranded on 0.0.5
28
+ * with the tracker at 2.20.4).
29
+ * - `<workspace>/skills/<skill>/SKILL.md` (every npx-installer box). The
30
+ * same reset happens there whenever anything re-runs
31
+ * `openclaw skills install --force` on the placed bootstrap
32
+ * (found 2026-09-19 while reviewing the installer's re-run path).
33
+ * The tracker alone cannot be trusted for "already up to date" in either
34
+ * layout. Fail-soft: unreadable dirs/files are skipped. */
35
+ export function readAgentVisibleSkillVersions(workspaceDir = DEFAULT_WORKSPACE_DIR) {
31
36
  const versions = [];
32
37
  const extensionsDir = join(homedir(), '.openclaw', 'extensions');
33
- let extEntries;
38
+ let extEntries = [];
34
39
  try {
35
40
  extEntries = readdirSync(extensionsDir, { withFileTypes: true });
36
41
  }
37
42
  catch {
38
- return versions;
43
+ // no extensions dir — the workspace layout below may still apply
39
44
  }
40
45
  for (const ext of extEntries) {
41
46
  if (!ext.isDirectory() || !ext.name.includes('reefclaw'))
42
47
  continue;
43
- const skillsDir = join(extensionsDir, ext.name, 'skills');
44
- let skillEntries;
48
+ versions.push(...readSkillDirVersions(join(extensionsDir, ext.name, 'skills')));
49
+ }
50
+ versions.push(...readSkillDirVersions(join(workspaceDir, 'skills')));
51
+ return versions;
52
+ }
53
+ /** Versions of every `<skillsDir>/<*reefclaw*>/SKILL.md`; [] when unreadable. */
54
+ function readSkillDirVersions(skillsDir) {
55
+ const versions = [];
56
+ let skillEntries;
57
+ try {
58
+ skillEntries = readdirSync(skillsDir, { withFileTypes: true });
59
+ }
60
+ catch {
61
+ return versions;
62
+ }
63
+ for (const s of skillEntries) {
64
+ if (!s.isDirectory() || !s.name.includes('reefclaw'))
65
+ continue;
45
66
  try {
46
- skillEntries = readdirSync(skillsDir, { withFileTypes: true });
67
+ const v = parseSkillVersion(readFileSync(join(skillsDir, s.name, 'SKILL.md'), 'utf-8'));
68
+ if (v)
69
+ versions.push(v);
47
70
  }
48
71
  catch {
49
- continue;
50
- }
51
- for (const s of skillEntries) {
52
- if (!s.isDirectory() || !s.name.includes('reefclaw'))
53
- continue;
54
- try {
55
- const v = parseSkillVersion(readFileSync(join(skillsDir, s.name, 'SKILL.md'), 'utf-8'));
56
- if (v)
57
- versions.push(v);
58
- }
59
- catch {
60
- // unreadable/absent copy — nothing to report for this entry
61
- }
72
+ // unreadable/absent copy — nothing to report for this entry
62
73
  }
63
74
  }
64
75
  return versions;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.35",
4
+ "version": "0.1.36",
5
5
  "description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
6
6
  "author": "ReefClaw",
7
7
  "activation": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reefclaw/openclaw-plugin",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
4
4
  "description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -6,5 +6,6 @@
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
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
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."
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.",
10
+ "0.1.36": "Day P&L no longer shows two days as 'today' after midnight UTC: the connector now takes the exchange-anchored figure on every balance read, not only when the dashboard reconnects. The one-click update tells the truth on Docker and other unmanaged gateways (a restart the installer could not perform is reported, never assumed), shows live progress again on OpenClaw 2026.8+, and never resets the live skill with a forced reinstall; a box whose OpenClaw has no terminal API gets a clear 'update from a shell' notice instead of a retry loop."
10
11
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reefclaw
3
- version: 0.0.11
3
+ version: 0.0.12
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
@@ -101,14 +101,14 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
101
101
  If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
102
102
 
103
103
  ```
104
- npx --yes @reefclaw/connect@0.1.48
104
+ npx --yes @reefclaw/connect@0.1.49
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. 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.
107
+ That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
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
 
111
- **If the user installs via ClawHub instead** — no terminal needed on OpenClaw 2026.8.1 or newer: either OpenClaw's Control UI (Plugins → Discover → search "reefclaw" → Install → accept the listed capabilities), or the chat command `/plugins install clawhub:@reefclaw/openclaw-plugin` followed, after reading the capability list it replies with, by the same command plus `--accept-capabilities` (the chat command needs `commands.plugins: true` in openclaw.json, which only the user sets). ClawHub labels the plugin "Security scan: suspicious". That is expected and honest — ReefClaw discloses live-trading capability, exchange-credential storage, and remote instruction updates, which ClawHub flags for review (its linked security page has the details; VirusTotal reports the artifact clean). OpenClaw 2026.8.1+ shows that audit and continues once the capabilities are accepted; OpenClaw 2026.7.x still blocks the chat command on that label — there the user runs the `npx` line above, or `openclaw plugins install clawhub:@reefclaw/openclaw-plugin --acknowledge-clawhub-risk` in a terminal.
111
+ **If the user installs via ClawHub instead** — no terminal needed on OpenClaw 2026.8.1 or newer: either OpenClaw's Control UI (Plugins → Discover → search "reefclaw" → Install → accept the listed capabilities), or the chat command `/plugins install clawhub:@reefclaw/openclaw-plugin` followed, after reading the capability list it replies with, by the same command plus `--accept-capabilities` (the chat command needs `commands.plugins: true` in openclaw.json, which only the user sets). ClawHub scans every release with an automated security reviewer; the current release passes it (no warning at install). If a newer release ever shows a "Review" label, OpenClaw 2026.8.1+ shows the audit and continues once the capabilities are accepted, while OpenClaw 2026.7.x may block the chat command on it — there the user runs the `npx` line above.
112
112
 
113
113
  Whatever the install path, **save the connection settings anyway** — the connector picks them up automatically the moment the plugin is running.
114
114
 
@@ -964,6 +964,26 @@ export async function createOrderTool(args, deps) {
964
964
  }
965
965
  return { error: `${wave9Claimed ? 'Wave 9 runtime divergence; daily event latched. ' : ''}${message}` };
966
966
  };
967
+ // A refusal that touched nothing at the venue and is NOT a market divergence
968
+ // (an operator config gate, a size/exposure limit, the drawdown zone) hands
969
+ // the capability back instead of burning the day: the account is exactly as
970
+ // the batch projected it, so a fresh authorization for the same candidate is
971
+ // safe once the cause is fixed — the same contract as every other
972
+ // pre-mutation refusal below (mode / venue / activation / readiness /
973
+ // brackets). Ardi report #7 item 0: one pre-trade gate refusal latched the
974
+ // whole daily event and the next window was 24h away.
975
+ const releaseWave9BeforeMutation = (message, code) => {
976
+ if (wave9Lease) {
977
+ deps.wave9AdmissionGuard.abort(wave9Lease, code, { retryable: true, latchEvent: false });
978
+ wave9Lease = undefined;
979
+ }
980
+ return {
981
+ error: `${wave9Claimed
982
+ ? 'Wave 9 order refused before any venue mutation; authorization released, daily event NOT latched — ' +
983
+ 'fix the cause, then call get_wave9_status for a fresh authorization inside the entry window. '
984
+ : ''}${message}`,
985
+ };
986
+ };
967
987
  // From beginEntry onward, every unexpected failure must release the
968
988
  // in-flight capability. Explicit geometry/risk divergences still use the
969
989
  // latching helper above; infrastructure/pure-computation throws are
@@ -1067,7 +1087,9 @@ export async function createOrderTool(args, deps) {
1067
1087
  });
1068
1088
  if (!riskCheck.allowed) {
1069
1089
  const reasons = riskCheck.violations.map(v => v.message).join('; ');
1070
- return rejectWave9Divergence(`Order REJECTED by risk gate [${riskCheck.drawdownZone} zone]: ${reasons}`, `generic_pretrade_divergence:${riskCheck.violations.map((v) => v.rule).join(',')}`);
1090
+ // Nothing reached the venue and the account is unchanged: release the
1091
+ // wave9 capability rather than latching the daily event (see helper).
1092
+ return releaseWave9BeforeMutation(`Order REJECTED by risk gate [${riskCheck.drawdownZone} zone]: ${reasons}`, `generic_pretrade_refusal:${riskCheck.violations.map((v) => v.rule).join(',')}`);
1071
1093
  }
1072
1094
  // ---- Re-entry cooldown gate (mode-laddered; ships 'off') ----
1073
1095
  // Generic NEW entries only: wave9 has its own frozen admission policy,
@@ -90,8 +90,16 @@ export class BinanceUsdmWave9EvidenceProvider {
90
90
  const fourHourBars = ohlcvRows(fourHourRaw, `${symbol} 4h`)
91
91
  .filter((bar) => bar.time.getTime() >= fromMs && bar.time.getTime() <= eventMs)
92
92
  .sort((left, right) => left.time.getTime() - right.time.getTime());
93
+ // Both window edges carry the same jitter tolerance. Binance stamps the
94
+ // PREVIOUS day's boundary settlement a few ms late as routinely as any
95
+ // other (a real 2026-09-18T00:00:00.003Z row blocked three nights of
96
+ // entries — Ardi report #7): with a bare `> fromMs` lower bound that row
97
+ // survives the filter, the list runs one settlement long, and the whole
98
+ // universe is refused as "partial or stale" although every expected
99
+ // settlement is present. A row jittered past the tolerance still fails
100
+ // closed below, exactly like an interior settlement would.
93
101
  const fundingRowsInWindow = fundingRows(fundingRaw, symbol)
94
- .filter((row) => row.time.getTime() > fromMs
102
+ .filter((row) => row.time.getTime() > fromMs + FUNDING_TIME_TOLERANCE_MS
95
103
  && row.time.getTime() <= eventMs + FUNDING_TIME_TOLERANCE_MS)
96
104
  .sort((left, right) => left.time.getTime() - right.time.getTime());
97
105
  requireExactTimes(dailyBars, expectedDaily, `${symbol} completed 1d evidence`);