# Audit report

> AUDIT the imdUSD v2 keeper: one process per chain (Ethereum, and Robinhood Chain 4663 with `--chain 4663`), NO on-chain rights, report-only by default; the wave-4 fixes, every 4663 duty, the cross-chain bridge watcher and its auto-claim, at the pinned commit.
>
> imdUSD v2 is a multi-collateral CDP stablecoin. On 12-07 its capped beta launches on Ethereum AND Robinhood Chain (4663, incl. stock tokens), joined by a LayerZero V2 burn-and-mint bridge. README.md gives scope, invariants, trust model and known issues: read it first. Wave 4 findings: GET https://api.imd.fun/jobs/<id>/submissions (0cb1541e prices, ae48df88 keeper, 34e546c2 bridge, 549dae1c stocks).
>
> BUILD AND TEST (required; Node 20+): `npm ci && npm test` (unit tests with fakes, no network; ~7 min). Write each proof as a test under test/ (node:test), run it with `node --test <file>`, paste it with its output, then delete it.
>
> PROPERTIES:
> P1 Every duty happens within its bound on its chain (4663: never a Pulse gap (15 min) without a poke; a live stock auction read at least every TICK_SPAN (5 min); Liquidator.tick within a pass of each market open and close; MarketHoursFeed.sync once a multiplier step lands; writeOff no sooner than 1 h after arming) while its RPCs answer; otherwise an alert fires first, also when a loop is slow but does not throw.
> P2 Never more IMD than the cap, never two payments for one order, a sIMD median or 4663 IMD price+spot bought only on a fall with a loan at risk, only the pinned payTo, permits at most 900 s.
> P3 Fees per nonce bounded (MAX_GAS_GWEI, 4 replacements, the last a cancel); one writer per key machine-wide; the 4663 key is never the mainnet key.
> P4 Unreadable safety state never reads as empty; no alert is cleared by a failed read; a log range is marked read only once its contents are proven.
> P5 Every bridge Received or Queued with no matching Sent on the other chain is flagged critical once the source is read past it (measured in source blocks, never by comparing the chains' timestamps), and unverified within 30 min if it cannot be; a forged packet verified at the endpoint is flagged while it still waits; no honest transfer is ever flagged forged.
> P6 A Pulse grace never makes the keeper treat a position as closed (a bite seizing 0 in the grace), and every close that is due is sent after the grace ends.
> P7 Report-only mode sends nothing and pays nothing.
> P8 Every honest queued transfer on the keeper's chain is claimed in the first pass after it matures (queuedAt + the path's current, governable delay) while its path is open (not paused, not tripped, not under a cancel cutoff); no claim without an exact Sent match (guid, nonce, amount, recipient) is ever sent; no claim is sent twice (restarts, a crash after broadcast, dropped or pending sends, strangers claiming first, a lagging node).
>
> THREAT MODEL: a hostile or failing RPC controls what the keeper reads (empty logs, stale heads, lag; 4663's default is ONE public read RPC, rate-limited, no history); a hostile plane, a MITM or the ENS server record controls quotes and answers; an attester or wrong majority controls answers relayed; a searcher or builder controls ordering within and across blocks; an on-chain griefer races permissionless calls (claims, pokes, ticks); the operator controls config and may run two processes; a bridge forger (compromised DVNs) the watcher must catch, while anyone runs lzReceive the moment a packet is verified; a stock issuer controls pause, blocklist, adminBurn and multiplier steps; the 4663 sequencer controls outages, reorgs and a clock ahead of or behind L1; Safe signers may be slow or absent (Telegram only).
>
> PATH: keeper.mjs [--chain 4663] -> lib/* duties -> the contracts at github.com/imdusd/imdusd-v2-audit (its wave-5 commit; ABIs in lib/deployment.mjs, lib/robinhood.mjs); the watcher (lib/bridge.mjs) reads Sent, Received, Queued, Claimed, Held and Voided on both chains and PacketVerified at each EndpointV2; payments only on Ethereum (lib/orders.mjs, lib/x402.mjs); 4663 windows use L1 block numbers. Contract facts: Received is emitted after the mint; a transfer over the path's instant cap queues for the path's delay, then anyone claims it (launch 5,000/day, 12 h); pause, hold, voidPayload, cancelClaim and tripBreaker need the 2-of-3 Safe; past 50,000 queued in 4 UTC days a path's breaker trips itself and claims revert until a 48 h timelocked reset; Pulse gap 15 min, grace 1 h; TICK_SPAN 5 min; HOLD_TIME 72 h; the plane caps permits at 300 s; IMD answers on 4663 are off by default.
>
> CLAIMS TO CHECK: confirm or refute each with a test.
> C1 each wave-4 and wave-5 fix enforces its property under fuzz, not just the judge's proof;
> C2 one process per chain isolates a failure on one chain;
> C3 the watcher catches a forged Received or Queued despite log-RPC gaps, empty answers, reorgs, a rate-limited 4663 RPC or 4663 timestamps ahead of L1's, and a lone RPC serving a stale head cannot cause a false 'forged' (PacketVerified, hold and void logs move no counter, so two agreeing reads alone prove them; a fresh start that cannot read the counters at its first block takes that range unproven);
> C4 on 4663 (first-come-first-served sequencer, no public mempool, tip ignored; base fee 0.0202 gwei on 11-15) the replace/cancel model clears a stuck nonce, and the 1 / 0.1 gwei ceilings never block an urgent poke, tick or claim;
> C5 the serial loop order meets P1: no other loop's sends, waits, log paging or claims delay the Pulse past its gap or a live auction's read past 5 min;
> C6 an honest claim queued on mainnet is auto-claimed by the mainnet watcher (on in the example config), and a mainnet bridge with the watcher off alerts critical at startup.
>
> SOUNDNESS: with no bridge guardian and Telegram-only alerts (paging is not built), the watcher is the only detection and the Safe has DELAY (12 h) to pause or cancel a forged Queued. Does reading PacketVerified and Queued give that window reliably? Wave 4 found 4 defects each in failed-read handling and the paid-order lifecycle: is there one rule that makes each sound (an alert clears only on a successful read; an order ends only on chain proof)? Can serial loops in one process per chain meet P1 on 4663's RPC?
>
> PROOF STANDARD: tests with fakes over interleavings (timeouts, replacements, reorgs, failing, empty or disagreeing reads, clock skew, outages, crashes, several txs per block); fuzz rules over random event orders.
>
> Answer each:
> 1. (P2, P3) Find a double payment, a payment outside the rules, an unbounded fee spend, two writers on one key, or a mainnet key used on 4663.
> 2. (P1, P4, P6) For each 4663 duty, what stops it silently, acts in a grace, or clears an alert on a failed read (C5 included)?
> 3. (P5) Find a forged Received, Queued or verified packet the watcher misses or flags too late for the Safe's 12 h, or an honest transfer it flags, under the C3 conditions.
> 4. (P8) Find a double claim, a claim of a forged or unmatched transfer, or an honest matured claim never sent (incl. after a delay change).
> 5. (P7) Find any path that sends or pays with --execute off.
>
> Not findings: README 'Only against a mock' and 'Not proven at all' as written (worse than written IS a finding); test/ and mocks.
>
> Every finding: severity by impact; file, line, the lines copied; the call sequence; the failing state, expected vs actual; reachable with the deploy config or not; the smallest fix; a test that fails on this commit, RUN as BUILD says and pasted with its output (the judge reruns it). Answer every numbered question, including where nothing is wrong.

| | |
|---|---|
| Repository | https://github.com/imdusd/imdusd-v2-keeper-audit.git |
| Commit | `f30a9d0ed1b7894b8cfe5630577308b8576ff439` |
| Job | `76be5a3d-63b6-41b6-8331-0b711566dd39` |
| Judged | 2026-11-18 21:51 UTC |
| Findings | 4 high · 10 medium · 10 low · 1 info |

Four agents audited the code as it is at `f30a9d0`, each in one area (math, permissions, economics, control flow),
and a judge reproduced, merged and ranked what they found, then read the code once more itself. Nothing in the repository was changed or deployed.

## Findings

### 1. High: P5/C3 refuted: a source RPC whose head lags (stale but advancing, self-consistent) makes the watcher flag HONEST transfers FORGED and tell the Safe to pause and cancel

`lib/bridge.mjs:685`

```
  stampBounds(peerSide, await provider.getBlockNumber());
  stampBounds(homeSide, await peerProvider.getBlockNumber());
```

Merged from four specialist reports (math, flow, permissions, economics); reproduced. The one-clock rule (header lines 10-16) treats "the source head read after the Received was indexed" as a block at or above the honest Sent. srcBound is stamped from ONE node's eth_blockNumber (lines 685-686; lib/chain.mjs:56 sends getBlockNumber to the first URL only, never compared, never checked for freshness; lib/watch.mjs:17-19 raises rpc-stale for the HOME provider only). A node that follows the chain N seconds behind returns a head BELOW the honest Sent whenever N exceeds the delivery delay. One pass later (120 s) the same node has advanced past that stale bound, indexSide proves the range complete against that node's own (equally stale) counters, and absence is called forgery: matchDirection line 138 `if (r.srcBound !== undefined && src.throughBlock >= r.srcBound) {`, judgeQueued line 248, verifiedAlerts line 221; counterAlerts (line 256) fires one pass earlier from the stale sent().
CALL SEQUENCE (4663 keeper, mainnet peer 600 s behind): Sent(1) on mainnet at T0+900, Sent(2) at T0+960; 4663 Received(1) at +1140, Queued(2) at +1200; pass at ~+1260 indexes both, stamps srcBound = mainnet head as of +660; next passes: peer throughBlock >= srcBound, no Sent visible -> critical bridge-counters-4663 (+1150 s), bridge-forged-4663-1 (+1273 s: "mainnet never Sent that nonce ... FORGED. Safe: pause both paths now"), bridge-queued-forged-4663-2 (+1392 s: "pause(...) NOW, then cancelClaim"). The specialist's mirrored proof (mainnet keeper, lone 4663 RPC 600 s behind) also fails here: bridge-counters-mainnet, bridge-forged-mainnet-1, bridge-queued-forged-mainnet-2.
EXPECTED (P5 "no honest transfer is ever flagged forged"; C3 "a lone RPC serving a stale head cannot cause a false 'forged'"): at worst bridge-unverified-* after 30 min. ACTUAL: three criticals naming Safe acts only 48 h timelocks undo (UNPAUSE, UNCANCEL), and autoClaim skips the honest matured claim while the verdict stands (line 552), so P8 fails too. Only a FROZEN head is covered (the bound is then never reached).
REACHABLE WITH THE DEPLOY CONFIG: yes. config.example.js:65 gives the mainnet keeper ONE 4663 RPC; the 4663 keeper takes mainnet's head from the first of two public RPCs. "stale heads, lag" are in the threat model.
SMALLEST FIX: stamp srcBound (and evaluate counterAlerts) only from a source head proven fresh: the max head over all of the peer's RPCs whose own block timestamp is within READ_MAX_LAG_SECONDS of the keeper's wall clock (one chain against local time, never chain against chain); otherwise leave it unstamped so the transfer ends as unverified at 30 min, and raise a peer rpc-stale. For mainnet -> 4663 the bound can also be floored by the l1BlockNumber of the 4663 block holding the Received.

**Reproduction**

The specialist's attached proof (mainnet keeper, lone 4663 RPC lagging 10 min; kept as this finding's proof) was run and fails for the reason given: bridge-counters-mainnet at t+2234 s, bridge-forged-mainnet-1 and bridge-queued-forged-mainnet-2 at t+2352 s. The mirrored case below was also run. State: home 4663; two honest mainnet->4663 transfers (nonce 1 minted, nonce 2 queued) delivered 240 s after their Sent; every mainnet-peer answer (head, blocks, logs, counters) is what the chain held 600 s earlier. Expected: no forged/counters alert (the control with lag 0 passes). Actual: critical bridge-counters-4663, bridge-forged-4663-1, bridge-queued-forged-4663-2.
RUN (Node 20+, after npm ci): save the test below as test/zz-a.test.mjs, run `node --test test/zz-a.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-a.test.mjs -----
// P5/C3: a source RPC that LAGS (old but self-consistent head, logs, counters) makes the watcher call HONEST transfers FORGED.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-lag-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { bridgeCtx, E18, honest, makeBridgeWorld, T0 } = await import("./lib/bridge-world.mjs");
async function run(lagSeconds) {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 3, home: 4663 });
  honest(w, 1, 1, T0 + 900, 240, E18.mul(100)); // Sent on mainnet, Received on 4663 240 s later
  honest(w, 1, 2, T0 + 960, 240, E18.mul(9000), { queue: true }); // Sent on mainnet, Queued on 4663 240 s later
  const lagged = (fn) => async (...a) => { w.t -= lagSeconds; try { return await fn(...a); } finally { w.t += lagSeconds; } };
  for (const k of ["getBlockNumber", "getBlock", "getLogs"]) w.peer.provider[k] = lagged(w.peer.provider[k]);
  for (const k of ["sent", "received", "queued", "breakers", "paused"]) w.peer.bridgeContract[k] = lagged(w.peer.bridgeContract[k]);
  const raised = [];
  const ctx = bridgeCtx(w, raised);
  for (let t = T0 + 60; t <= T0 + 3600; t += 120) { if (w.t < t) w.t = t; await runBridge(ctx); }
  return raised.filter((a) => /forged|counters/.test(a.key));
}
test("control: with a fresh mainnet peer the two honest transfers raise no forged alert", async () => {
  assert.deepEqual((await run(0)).map((a) => a.key), []);
});
test("a mainnet peer lagging 10 min never makes an honest transfer FORGED", async () => {
  const forged = await run(600);
  const first = new Map();
  for (const a of forged) if (!first.has(a.key)) first.set(a.key, a);
  for (const a of first.values()) console.log(`+${Math.round(a.t - T0)}s ${a.level} ${a.key}: ${a.msg.slice(0, 200)}`);
  assert.deepEqual([...first.keys()], []);
});

----- OUTPUT on f30a9d0 -----
+1150s critical bridge-counters-4663: 4663 bridge received + queued 100.0 imdUSD in total, more than mainnet ever sent (0.0): 100.0 minted or queued without a burn. Safe: pause both paths
+1273s critical bridge-forged-4663-1: 4663 Received 100.0 imdUSD to 0x0000000000000000000000000000000000001001 at nonce 1 and mainnet never Sent that nonce (read through block 4219): FORGED. Safe: pause both paths now, void every waiting 
+1392s critical bridge-queued-forged-4663-2: 4663 QUEUED a FORGED claim: 9000.0 imdUSD to 0x0000000000000000000000000000000000001002 at nonce 2, guid 0x31bbc8eba6376e2a0174bf74c4ff6088523feccd475c3741809c2df3e1b80581 (tx 0x0000000000000000000000
✔ control: with a fresh mainnet peer the two honest transfers raise no forged alert (343.27449ms)
✖ a mainnet peer lagging 10 min never makes an honest transfer FORGED (252.890529ms)
ℹ tests 2
ℹ pass 1
ℹ fail 1

✖ failing tests:

test at test/zz-a.test.mjs:26:1
✖ a mainnet peer lagging 10 min never makes an honest transfer FORGED (252.890529ms)
  Assert

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// node:test proof (this repository is Node.js, it has no Solidity): save as test/zz-p1.test.mjs, run `npm ci && node --test test/zz-p1.test.mjs`; it fails on commit f30a9d0 and passes once the finding is fixed.
// AUDIT PROOF (C3 / P5): a source RPC that LAGS (a stale head that still advances) makes the watcher call an honest transfer FORGED.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-stale-head-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { E18, honest, makeBridgeWorld, runPasses, T0 } = await import("./lib/bridge-world.mjs");

/** The peer's RPC answers everything (head, blocks, logs, counters, settings) as the chain was `lag` seconds ago: one consistent, stale node. */
function lagPeer(w, lag) {
  for (const obj of [w.peer.provider, w.peer.bridgeContract]) {
    for (const [k, f] of Object.entries(obj)) {
      if (typeof f !== "function") continue;
      obj[k] = async (...a) => {
        w.t -= lag;
        try { return await f(...a); } finally { w.t += lag; }
      };
    }
  }
}

async function run(lag) {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 11, home: 1 }); // the MAINNET keeper; its peer is 4663, read through ONE RPC (config.example.js PEERS)
  if (lag) lagPeer(w, lag);
  honest(w, 4663, 1, T0 + 2000, 120, E18.mul(100)); // Sent on 4663, Received on mainnet 2 min later
  honest(w, 4663, 2, T0 + 2060, 120, E18.mul(6000), { queue: true }); // over the instant cap: Queued on mainnet
  const raised = await runPasses(w, runBridge, { horizon: 3600 });
  return raised.filter((a) => a.level === "critical" && /^bridge-(forged|queued-forged|counters)-/.test(a.key));
}

test("control: a fresh 4663 RPC, the two honest transfers raise nothing", async () => {
  assert.deepEqual((await run(0)).map((a) => a.key), []);
});

test("a lone 4663 RPC lagging 10 min (advancing, self-consistent) never makes an honest transfer FORGED", async () => {
  const bad = await run(600);
  for (const a of bad.filter((x, i) => bad.findIndex((y) => y.key === x.key) === i)) console.log(`t+${Math.round(a.t - T0)}s ${a.level} ${a.key}: ${a.msg.slice(0, 230)}`);
  assert.deepEqual([...new Set(bad.map((a) => a.key))], [], "honest transfers were flagged as forgeries");
});
```

### 2. High: P5/P1: runBridge raises its alerts only after the last read of the pass; a forged Received already indexed and judged is never flagged while any later read or send throws (only loop-failing-bridge app

`lib/bridge.mjs:722`

```
    if (await br.paused(eid)) raised.push({ level: "critical", key: `bridge-paused-${name}`, msg: `the ${name} bridge path to endpoint ${eid} is PAUSED (Safe act): only UNPAUSE (48 h) reopens it` });
```

Specialist (flow) finding; its attached proof was run and fails for the stated reason. runBridge collects every alert in `raised` and calls ctx.alerts.raise only in the loop at lines 746-749, after autoClaim, the paused/breaker reads and the supply equations. Anything between matchDirection (line 705) and that loop that throws drops the alerts already computed: `br.paused(eid)` for both chains (line 722, unguarded, while the breaker read on line 724 has a try/catch), `ctx.provider.getBlock("latest")` in autoClaim (line 547), settleIntents (line 583), and act() on a claim (line 617: lib/tx.mjs send() throws on a send-RPC error, a reverted claim a stranger won, any non-TIMEOUT wait error). The index was already saved (line 700), so the next pass re-derives the same alerts and drops them again.
CALL SEQUENCE: forged Received mints on 4663 -> indexed -> mainnet indexed past its srcBound -> matchDirection pushes critical bridge-forged-4663-1000 -> line 722 peerBridge.paused(...) throws 429 (a peer RPC that still answers heads, logs, counters) -> runRound logs "bridge loop error" -> nothing raised. After 5 passes the only alert is loop-failing-bridge, which does not say a forgery sits in state/bridge-watch.json.
EXPECTED: critical bridge-forged-4663-1000 within minutes (the control does it). ACTUAL: in 2 hours the only alert is critical loop-failing-bridge; the forged Received is in the state file with mainnet read through 4759 >= srcBound 4192.
This is the wave-4 failed-read defect class mirrored: a failed read does not clear an alert here, it stops a proven one from ever being raised. The Safe's 12 h window for a forged Queued rests on this alert. A griefer can also trigger it: each honest matured claim he front-runs makes the keeper's claim revert and that pass's alerts are lost.
REACHABLE WITH THE DEPLOY CONFIG: yes, both keepers (the rate-limited 4663 public RPC is the mainnet keeper's peer).
SMALLEST FIX: raise as soon as proven: wrap the body after line 700 in try/finally and run the raise loop in the finally (settle only when the pass completed), and give line 722 the try/catch line 724 has (unreadable = say so, keep the standing alert).

**Reproduction**

State: 4663 keeper; a forged Received on 4663 at T0+300 (nonce 1000, 5,000 imdUSD, no Sent on mainnet); the mainnet peer answers heads, logs, blocks and counters but paused(eid) throws "429 Too Many Requests" every pass; passes every 120 s for 2 h through keeper.mjs runRound. Expected: critical bridge-forged-4663-1000. Actual: only critical loop-failing-bridge.
RUN (Node 20+, after npm ci): save the test below as test/zz-p2.test.mjs, run `node --test test/zz-p2.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-p2.test.mjs -----
// AUDIT PROOF (P5 / P1): runBridge raises its alerts only at the very end, so any read that throws AFTER a forgery was indexed and judged
// drops the forged alert for that pass; while that read keeps failing the forgery is never flagged.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-dropped-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { runRound } = await import("../keeper.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, E18, forge, makeBridgeWorld, T0 } = await import("./lib/bridge-world.mjs");

async function run(failPeerPaused) {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 7, home: 4663 });
  forge(w, 4663, 1000, T0 + 300, E18.mul(5000)); // a forged Received on 4663: minted, no Sent on mainnet
  // The mainnet peer RPC answers heads, logs, blocks and counters; ONE later read fails (rate limit): paused(eid), lib/bridge.mjs:722.
  if (failPeerPaused) w.peer.bridgeContract.paused = async () => { throw Object.assign(new Error("429 Too Many Requests"), { code: "SERVER_ERROR" }); };
  const raised = [];
  const ctx = bridgeCtx(w, raised, { loops: [{ name: "bridge", run: runBridge }] });
  for (let p = T0 + 60; p <= T0 + 2 * 3600; p += 120) { // 2 hours of passes, through keeper.mjs runRound (as the daemon runs it)
    if (w.t < p) w.t = p;
    await runRound(ctx, ["bridge"]);
  }
  return { raised, state: readStateOr("bridge-watch.json", {}) };
}

test("control: with every read answering, the forged Received is flagged critical within minutes", async () => {
  const { raised } = await run(false);
  const hit = raised.find((a) => a.key === "bridge-forged-4663-1000");
  assert.ok(hit && hit.level === "critical" && hit.t - (T0 + 300) < 600);
});

test("a forged Received already indexed and judged is flagged even if a LATER read of the pass throws", async () => {
  const { raised, state } = await run(true);
  const r = state.home?.received?.["30101:1000"];
  console.log(`state/bridge-watch.json holds the forged Received: ${JSON.stringify(r)}; mainnet read through ${state.peer?.throughBlock}`);
  console.log(`alerts raised in 2 h: ${JSON.stringify([...new Set(raised.map((a) => `${a.level} ${a.key}`))])}`);
  assert.ok(r && state.peer.throughBlock >= r.srcBound, "the watcher holds the proof (source read past the Received, no Sent)");
  assert.ok(raised.some((a) => a.key === "bridge-forged-4663-1000"), "the forged Received was NEVER flagged in 2 hours");
});
----- OUTPUT on f30a9d0 -----
state/bridge-watch.json holds the forged Received: {"guid":"0xc3c8ad01d5e77c0d27f9731e3177d0546ed06960aedf01f6f86336befe662b8e","to":"0x000000000000000000000000000000000000176c","amount":"5000000000000000000000","block":50300,"time":1800000300,"tx":"0x0000000000000000000000000000000000000000000000000000000000000004","srcBound":4192}; mainnet read through 4759
alerts raised in 2 h: ["critical loop-failing-bridge"]
✔ control: with every read answering, the forged Received is flagged critical within minutes (535.000858ms)
✖ a forged Received already indexed and judged is flagged even if a LATER read of the pass throws (490.156823ms)
ℹ tests 2
ℹ pass 1
ℹ fa

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// node:test proof (this repository is Node.js, it has no Solidity): save as test/zz-p2.test.mjs, run `npm ci && node --test test/zz-p2.test.mjs`; it fails on commit f30a9d0 and passes once the finding is fixed.
// AUDIT PROOF (P5 / P1): runBridge raises its alerts only at the very end, so any read that throws AFTER a forgery was indexed and judged
// drops the forged alert for that pass; while that read keeps failing the forgery is never flagged.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-dropped-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { runRound } = await import("../keeper.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, E18, forge, makeBridgeWorld, T0 } = await import("./lib/bridge-world.mjs");

async function run(failPeerPaused) {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 7, home: 4663 });
  forge(w, 4663, 1000, T0 + 300, E18.mul(5000)); // a forged Received on 4663: minted, no Sent on mainnet
  // The mainnet peer RPC answers heads, logs, blocks and counters; ONE later read fails (rate limit): paused(eid), lib/bridge.mjs:722.
  if (failPeerPaused) w.peer.bridgeContract.paused = async () => { throw Object.assign(new Error("429 Too Many Requests"), { code: "SERVER_ERROR" }); };
  const raised = [];
  const ctx = bridgeCtx(w, raised, { loops: [{ name: "bridge", run: runBridge }] });
  for (let p = T0 + 60; p <= T0 + 2 * 3600; p += 120) { // 2 hours of passes, through keeper.mjs runRound (as the daemon runs it)
    if (w.t < p) w.t = p;
    await runRound(ctx, ["bridge"]);
  }
  return { raised, state: readStateOr("bridge-watch.json", {}) };
}

test("control: with every read answering, the forged Received is flagged critical within minutes", async () => {
  const { raised } = await run(false);
  const hit = raised.find((a) => a.key === "bridge-forged-4663-1000");
  assert.ok(hit && hit.level === "critical" && hit.t - (T0 + 300) < 600);
});

test("a forged Received already indexed and judged is flagged even if a LATER read of the pass throws", async () => {
  const { raised, state } = await run(true);
  const r = state.home?.received?.["30101:1000"];
  console.log(`state/bridge-watch.json holds the forged Received: ${JSON.stringify(r)}; mainnet read through ${state.peer?.throughBlock}`);
  console.log(`alerts raised in 2 h: ${JSON.stringify([...new Set(raised.map((a) => `${a.level} ${a.key}`))])}`);
  assert.ok(r && state.peer.throughBlock >= r.srcBound, "the watcher holds the proof (source read past the Received, no Sent)");
  assert.ok(raised.some((a) => a.key === "bridge-forged-4663-1000"), "the forged Received was NEVER flagged in 2 hours");
});
```

### 3. High: P1/C5/C2 refuted: loops are awaited serially with no deadline and no slow-loop alert; one pass that is slow but does not throw silently holds the Pulse poke, auction ticks, Liquidator.tick, bites and

`keeper.mjs:177`

```
    for (const l of ctx.loops) {
      if ((only && !only.includes(l.name)) || Date.now() < next.get(l.name)) continue;
      await runRound(ctx, [l.name]);
      next.set(l.name, Date.now() + l.every(cfg) * 1000);
    }
```

Merged from four specialist reports; reproduced with the attached proof and a second test. main() awaits each loop to its end (keeper.mjs:176-181) and runRound alerts only on a THROW (loop-failing-<loop>, line 97). Nothing measures a pass, no read has a deadline (lib/chain.mjs:18-20 builds StaticJsonRpcProvider with ethers' defaults: 120 s per request, and up to 12 backed-off retries on HTTP 429), a send holds the thread SEND_WAIT_SECONDS. P1 requires "an alert fires first, also when a loop is slow but does not throw": no code implements it (no watchdog, deadline or elapsed-time check in keeper.mjs or lib/).
CALL SEQUENCE (4663, config.example.js as shipped): pulse pokes; the bridge loop starts its first pass and pages mainnet's logs from BRIDGE_WATCH.peer.fromBlock 0 (see the indexSide finding): 11,787 RPC calls, 3,536 s at the project fake's own 0.05-0.55 s per call; meanwhile runPulse (gap 900 s, poke due at 480 s), runStocks (TICK_SPAN 300 s) and runPositions never run; the next Pulse pass pokes after 3,636 s of silence, which opens the 1 h grace (no seizure, redemption refused). The first alert of any kind is pulse-grace, after the fact. A plain 20 min pass under mocked timers gives the same: alerts raised = [].
C2: each process awaits the OTHER chain's RPC inline in its only queue (bridge loop on both; imdfeeds on 4663), so one process per chain does not isolate a slow peer RPC.
EXPECTED: no other loop's log paging, waits or sends delay the Pulse past its gap or an auction read past 5 min; if it would, an alert first. ACTUAL: Pulse 3,636 s silent, zero alerts before the gap.
REACHABLE WITH THE DEPLOY CONFIG: yes (first start of either keeper; again whenever a peer RPC is slow or rate-limiting).
SOUNDNESS ANSWER: serial loops in one process can meet P1 on 4663's RPC only if every pass is bounded in time; today none is.
SMALLEST FIX: race each l.run(ctx) against a deadline well under the Pulse gap and raise critical loop-slow-<name> when it passes; give every read/peer provider an explicit short timeout and throttle limit; run the Pulse check on its own timer (or before every other loop pass) so nothing can hold it past pokeAfterSeconds.

**Reproduction**

State: 4663 keeper, fresh state, ROBINHOOD_LOOPS through runRound in main()'s order; BRIDGE_WATCH.peer.fromBlock 0 as config.example.js ships; mainnet fake at height 26,444,548, no bridge traffic; the Pulse poked 100 s before. Expected: poke within 900 s or an alert before the gap. Actual: one bridge pass = 11,787 RPC calls / 3,536 s; Pulse poked after 3,636 s; first alert critical pulse-grace at t+3,536 s. A second, independent test (runRound with a 20 min non-throwing bridge pass under mocked timers) also fails: "held the single thread 1200 s ... and NO alert was raised: []".
RUN (Node 20+, after npm ci): save the test below as test/zz-p3.test.mjs, run `node --test test/zz-p3.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-p3.test.mjs -----
// AUDIT PROOF (C5 / P1): the loops are serial with no time budget and no watchdog. One bridge pass that pages the peer's logs from
// BRIDGE_WATCH.peer.fromBlock = 0 (config.example.js) holds the queue past the Pulse gap, silently; and the backfill is all-or-nothing.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-pulse-"));
const { ROBINHOOD_LOOPS, runRound } = await import("../keeper.mjs");
const { CHAIN_DEFAULTS } = await import("../lib/chains.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, makeBridgeWorld, setDelay, T0 } = await import("./lib/bridge-world.mjs");

const GAP = 900, GRACE = 3600;
const MAINNET_HEAD = 26_444_548; // eth_blockNumber on 2026-11-18

function world() {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 3, home: 4663 }); // the 4663 keeper; each fake RPC call takes 0.05-0.55 s (the project's own model)
  w.chains[1].genesis = T0 - MAINNET_HEAD * 12; // mainnet at its real height
  // As ImdBridge does: no delay before the path is configured, then DelaySet in the logs (an hour ago), so the settings proof holds.
  w.chains[1].settings[0][1] = { delay: 0, cutoff: 0 };
  const t = w.t;
  w.t = T0 - 3600;
  setDelay(w, 1, { delay: w.delay });
  w.t = t;
  const raised = [];
  const pulse = { last: 0, graceUntil: 0, pokes: [] };
  const now = () => w.home.timeOf(w.home.headAt(w.t));
  const ctx = bridgeCtx(w, raised, {
    loops: ROBINHOOD_LOOPS,
    // What `--chain 4663` runs on with config.example.js: CHAIN_DEFAULTS[4663].LOGS for home, and for the peer NO peerLogs (chunk 9,000) and fromBlock 0.
    cfg: { CHAIN_ID: 4663, LOGS: CHAIN_DEFAULTS[4663].LOGS, PULSE: {}, BRIDGE_WATCH: { peer: { bridge: w.peer.bridge, fromBlock: 0 }, directions: "both" } },
    actHook: async (label, c, fn) => {
      if (fn !== "poke") throw new Error(`unexpected act ${fn}`);
      if (now() - pulse.last > GAP) pulse.graceUntil = now() + GRACE; // Pulse.poke past the gap opens the grace
      pulse.pokes.push({ t: w.t, silence: now() - pulse.last });
      pulse.last = now();
      return { hash: "0x01" };
    },
  });
  ctx.book.pulse = { lastPulse: async () => pulse.last, gap: async () => GAP, graceUntil: async () => pulse.graceUntil, inGrace: async () => now() < pulse.graceUntil || now() - pulse.last > GAP };
  pulse.last = now() - 100; // somebody poked 100 s ago
  return { w, ctx, raised, pulse, now };
}

test("no loop holds the queue past the Pulse gap without an alert first (first bridge pass, peer.fromBlock 0)", async () => {
  const { w, ctx, raised, pulse } = world();
  const t0 = w.t, calls0 = w.calls;
  // keeper.mjs main(): the loops in order, one at a time; then the next due one. Here: pulse, bridge, pulse.
  await runRound(ctx, ["pulse", "bridge"]);
  const held = w.t - t0;
  await runRound(ctx, ["pulse"]);
  const firstAlert = raised[0];
  console.log(`one bridge pass: ${w.calls - calls0} RPC calls, ${Math.round(held)} s ($

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// node:test proof (this repository is Node.js, it has no Solidity): save as test/zz-p3.test.mjs, run `npm ci && node --test test/zz-p3.test.mjs`; it fails on commit f30a9d0 and passes once the finding is fixed.
// AUDIT PROOF (C5 / P1): the loops are serial with no time budget and no watchdog. One bridge pass that pages the peer's logs from
// BRIDGE_WATCH.peer.fromBlock = 0 (config.example.js) holds the queue past the Pulse gap, silently; and the backfill is all-or-nothing.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-pulse-"));
const { ROBINHOOD_LOOPS, runRound } = await import("../keeper.mjs");
const { CHAIN_DEFAULTS } = await import("../lib/chains.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, makeBridgeWorld, setDelay, T0 } = await import("./lib/bridge-world.mjs");

const GAP = 900, GRACE = 3600;
const MAINNET_HEAD = 26_444_548; // eth_blockNumber on 2026-11-18

function world() {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 3, home: 4663 }); // the 4663 keeper; each fake RPC call takes 0.05-0.55 s (the project's own model)
  w.chains[1].genesis = T0 - MAINNET_HEAD * 12; // mainnet at its real height
  // As ImdBridge does: no delay before the path is configured, then DelaySet in the logs (an hour ago), so the settings proof holds.
  w.chains[1].settings[0][1] = { delay: 0, cutoff: 0 };
  const t = w.t;
  w.t = T0 - 3600;
  setDelay(w, 1, { delay: w.delay });
  w.t = t;
  const raised = [];
  const pulse = { last: 0, graceUntil: 0, pokes: [] };
  const now = () => w.home.timeOf(w.home.headAt(w.t));
  const ctx = bridgeCtx(w, raised, {
    loops: ROBINHOOD_LOOPS,
    // What `--chain 4663` runs on with config.example.js: CHAIN_DEFAULTS[4663].LOGS for home, and for the peer NO peerLogs (chunk 9,000) and fromBlock 0.
    cfg: { CHAIN_ID: 4663, LOGS: CHAIN_DEFAULTS[4663].LOGS, PULSE: {}, BRIDGE_WATCH: { peer: { bridge: w.peer.bridge, fromBlock: 0 }, directions: "both" } },
    actHook: async (label, c, fn) => {
      if (fn !== "poke") throw new Error(`unexpected act ${fn}`);
      if (now() - pulse.last > GAP) pulse.graceUntil = now() + GRACE; // Pulse.poke past the gap opens the grace
      pulse.pokes.push({ t: w.t, silence: now() - pulse.last });
      pulse.last = now();
      return { hash: "0x01" };
    },
  });
  ctx.book.pulse = { lastPulse: async () => pulse.last, gap: async () => GAP, graceUntil: async () => pulse.graceUntil, inGrace: async () => now() < pulse.graceUntil || now() - pulse.last > GAP };
  pulse.last = now() - 100; // somebody poked 100 s ago
  return { w, ctx, raised, pulse, now };
}

test("no loop holds the queue past the Pulse gap without an alert first (first bridge pass, peer.fromBlock 0)", async () => {
  const { w, ctx, raised, pulse } = world();
  const t0 = w.t, calls0 = w.calls;
  // keeper.mjs main(): the loops in order, one at a time; then the next due one. Here: pulse, bridge, pulse.
  await runRound(ctx, ["pulse", "bridge"]);
  const held = w.t - t0;
  await runRound(ctx, ["pulse"]);
  const firstAlert = raised[0];
  console.log(`one bridge pass: ${w.calls - calls0} RPC calls, ${Math.round(held)} s (${(held / 60).toFixed(1)} min) with no other loop running`);
  console.log(`the next Pulse pass poked after ${pulse.pokes[0]?.silence} s of silence (gap ${GAP} s): grace until +${pulse.graceUntil ? GRACE : 0} s`);
  console.log(`first alert of any kind: ${firstAlert ? `${firstAlert.level} ${firstAlert.key} at t+${Math.round(firstAlert.t - t0)} s` : "none"}`);
  assert.ok(pulse.pokes.every((p) => p.silence <= GAP) || (firstAlert && firstAlert.t - t0 < GAP - 100), `the Pulse went ${pulse.pokes[0].silence} s without a poke (gap ${GAP} s) and nothing alerted before the gap`);
});

test("a backfill that fails on its last range keeps what it proved (the cursor moves)", async () => {
  const { w, ctx } = world();
  const real = w.peer.provider.getLogs;
  let n = 0;
  w.peer.provider.getLogs = async (f) => { if (++n === 11_700) throw new Error("429 Too Many Requests"); return real(f); };
  await runRound(ctx, ["bridge"]);
  const s = readStateOr("bridge-watch.json", {});
  console.log(`after ${n} getLogs calls and one failure: peer cursor = ${s.peer?.next ?? "nothing saved (starts again from block 0)"}`);
  assert.ok((s.peer?.next ?? 0) > 0, "11,699 answered log reads were thrown away: the next pass starts again from block 0");
});
```

### 4. High: C2 refuted / P5 / P8: while the PEER chain's RPC does not answer the bridge loop throws at its first peer read: a FORGED claim queued at home is never named (neither forged nor unverified) for its who

`lib/bridge.mjs:666`

```
  const peerSent = await peerBridge.sent();
```

Specialist (economics) finding, rated medium there; its test was truncated, so it was rewritten, and extended with the forged case, which raises it to high. runBridge reads the peer's counters and head first (lines 666-668, 672) and indexes the peer before it matches or claims anything; each of those reads is unguarded. When the peer RPC does not answer, the pass throws at line 666: autoClaim never runs for claims whose Sent was already indexed and judged honest on earlier passes (the claim itself needs only the home chain and the saved index), the home path's paused / breaker / supply checks do not run, and no bridge-* alert is raised (not even bridge-unverified-* for a Received or Queued that arrived just before the outage: the throw precedes matchDirection). The only signal is the generic loop-failing-bridge after 5 passes.
So a 4663 RPC outage or rate limit stops the MAINNET keeper's claims (and the reverse): the cross-chain coupling "one process per chain" is meant to remove (lib/chains.mjs: one chain's RPC failing never holds the other chain's duties).
FORGED CASE (added by this review): with the peer unreadable from +850 s, a forged 40,000 imdUSD claim is Queued on the home chain at +900 s. Every home-chain read works, but the pass throws before the home side is even indexed: in the 12 h until the claim matures (361 passes) NO bridge alert names it. P5 requires "unverified within 30 min if it cannot be" (bridge-queued-unverified-* exists for exactly this, lines 161-162) and the Safe's whole DELAY passes with only keeper.mjs's generic loop-failing-bridge ("mainnet RPC: 503"), which does not say a forged claim is waiting. On the 4663 keeper the peer is two public mainnet RPCs that must BOTH answer (lib/chain.mjs _agreed), so one of them failing is enough.
EXPECTED (P8 "claimed in the first pass after it matures while its path is open"; C2): the claim of an already-matched transfer goes out (the control sends it in the first pass after +900 s). ACTUAL: verdict "honest" on disk before the outage, 16 passes threw "mainnet RPC: 503", 0 claims sent by +2700 s, no bridge alert.
REACHABLE WITH THE DEPLOY CONFIG: yes (any peer RPC outage, including the rate-limited public 4663 RPC seen from the mainnet keeper).
SMALLEST FIX: catch a failed peer read in runBridge: index the home side regardless, keep the standing alerts, raise critical bridge-peer-unread-<chain>, run matchDirection on the saved peer index (so a new Received/Queued goes unverified at 30 min in the home clock), and still run autoClaim (verdict "honest" comes from the saved, proven index and needs no new peer read) and the home-only checks.

**Reproduction**

State: 4663 keeper; an honest transfer Sent on mainnet at +100 s, Queued on 4663 at +300 s with delay 600 s (matures +900 s), indexed and judged honest by +780 s; from +850 s every mainnet RPC call fails. Expected: claim sent at the +900 s pass. Actual: 0 sends through +2700 s. Second state: a forged 40,000 imdUSD Queued on 4663 at +900 s with the peer down from +850 s for 12 h. Expected: bridge-queued-unverified-4663-1000 (or forged) within 30 min. Actual: no bridge alert names it before it matures at +44,100 s.
RUN (Node 20+, after npm ci): save the test below as test/zz-u.test.mjs, run `node --test test/zz-u.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-u.test.mjs -----
// C2/P8: while the PEER chain's RPC is down the bridge loop throws before anything else: a matured claim already matched to its Sent is not sent
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, utils } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runBridge, judgeQueued } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { EID } = await import("../lib/robinhood.mjs");
const { BRIDGE_IFACE, bridgeCtx, E18, honest, makeBridgeWorld, guidOf, settleClaim, T0 } = await import("./lib/bridge-world.mjs");
const fresh = () => rmSync(process.env.STATE_DIR, { recursive: true, force: true });
const addr = (i) => utils.getAddress(utils.hexZeroPad(utils.hexlify(i), 20));
/** Alerts as lib/alerts.mjs keeps them: raise makes a key stand, settle clears every key of the prefix this pass did not raise. */
const recorder = (w) => {
  const standing = new Map(), log = [];
  return { standing, log,
    raise: async (level, key, msg) => { standing.set(key, level); log.push({ t: Math.round(w.t - T0), level, key, msg }); },
    settle: async (prefix, held) => { for (const k of [...standing.keys()]) if (k.startsWith(prefix) && !held.has(k)) { log.push({ t: Math.round(w.t - T0), level: "cleared", key: k, was: standing.get(k) }); standing.delete(k); } } };
};
/** The watcher every 120 s, as keeper.mjs runs it: a pass that throws is logged and the next one runs. */
async function passes(w, ctx, from, to, each = () => {}) {
  const errors = [];
  for (let p = from; p <= to; p += 120) { if (w.t < p) w.t = p; await each(p); try { await runBridge(ctx); } catch (e) { errors.push({ t: p - T0, e: e.message }); } }
  return errors;
}
async function run(outage) {
  fresh();
  const w = makeBridgeWorld({ seed: 5, home: 4663, delay: 600 });
  const rec = honest(w, 1, 1, T0 + 100, 200, E18.mul(100), { queue: true }); // Sent on mainnet +100 s, Queued on 4663 +300 s, matures +900 s
  const sends = [];
  const a = recorder(w);
  const ctx = bridgeCtx(w, [], { alerts: a, execute: true, settleSends: async () => {},
    actHook: async (label) => { sends.push({ t: Math.round(w.t - T0), label }); settleClaim(w, 4663, rec.claim, 2); return { hash: utils.hexZeroPad("0x01", 32), block: 0, gas: "1" }; } });
  let down = false;
  for (const o of [w.peer.provider, w.peer.bridgeContract]) for (const k of Object.keys(o)) if (typeof o[k] === "function") { const f = o[k]; o[k] = async (...x) => { if (down) throw new Error("mainnet RPC: 503"); return f(...x); }; }
  const verdictBefore = [];
  const errors = await passes(w, ctx, T0 + 60, T0 + 2700, (p) => {
    if (outage && p >= T0 + 850 && !down) { // the claim is indexed and judged before the peer goes down
      const s = readStateOr("bridge-watch.json", {});
      verdictBefore.push(judgeQueued(Object.values(s.home.queue)[0], "1", s.peer, EID[4663]).verdict);
      down = true;
    }
  });
  return { sends, errors, verdictBefore, alerts: [...new Set(a.log.map((x) => `${x.level} ${x.key}`))] };
}
test("control: with the mainnet RPC up, the honest matu

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// node:test proof (this repository is Node.js, it has no Solidity): save as test/zz-u.test.mjs, run `npm ci && node --test test/zz-u.test.mjs`; it fails on commit f30a9d0 and passes once the finding is fixed.
// C2/P8: while the PEER chain's RPC is down the bridge loop throws before anything else: a matured claim already matched to its Sent is not sent
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, utils } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runBridge, judgeQueued } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { EID } = await import("../lib/robinhood.mjs");
const { BRIDGE_IFACE, bridgeCtx, E18, honest, makeBridgeWorld, guidOf, settleClaim, T0 } = await import("./lib/bridge-world.mjs");
const fresh = () => rmSync(process.env.STATE_DIR, { recursive: true, force: true });
const addr = (i) => utils.getAddress(utils.hexZeroPad(utils.hexlify(i), 20));
/** Alerts as lib/alerts.mjs keeps them: raise makes a key stand, settle clears every key of the prefix this pass did not raise. */
const recorder = (w) => {
  const standing = new Map(), log = [];
  return { standing, log,
    raise: async (level, key, msg) => { standing.set(key, level); log.push({ t: Math.round(w.t - T0), level, key, msg }); },
    settle: async (prefix, held) => { for (const k of [...standing.keys()]) if (k.startsWith(prefix) && !held.has(k)) { log.push({ t: Math.round(w.t - T0), level: "cleared", key: k, was: standing.get(k) }); standing.delete(k); } } };
};
/** The watcher every 120 s, as keeper.mjs runs it: a pass that throws is logged and the next one runs. */
async function passes(w, ctx, from, to, each = () => {}) {
  const errors = [];
  for (let p = from; p <= to; p += 120) { if (w.t < p) w.t = p; await each(p); try { await runBridge(ctx); } catch (e) { errors.push({ t: p - T0, e: e.message }); } }
  return errors;
}
async function run(outage) {
  fresh();
  const w = makeBridgeWorld({ seed: 5, home: 4663, delay: 600 });
  const rec = honest(w, 1, 1, T0 + 100, 200, E18.mul(100), { queue: true }); // Sent on mainnet +100 s, Queued on 4663 +300 s, matures +900 s
  const sends = [];
  const a = recorder(w);
  const ctx = bridgeCtx(w, [], { alerts: a, execute: true, settleSends: async () => {},
    actHook: async (label) => { sends.push({ t: Math.round(w.t - T0), label }); settleClaim(w, 4663, rec.claim, 2); return { hash: utils.hexZeroPad("0x01", 32), block: 0, gas: "1" }; } });
  let down = false;
  for (const o of [w.peer.provider, w.peer.bridgeContract]) for (const k of Object.keys(o)) if (typeof o[k] === "function") { const f = o[k]; o[k] = async (...x) => { if (down) throw new Error("mainnet RPC: 503"); return f(...x); }; }
  const verdictBefore = [];
  const errors = await passes(w, ctx, T0 + 60, T0 + 2700, (p) => {
    if (outage && p >= T0 + 850 && !down) { // the claim is indexed and judged before the peer goes down
      const s = readStateOr("bridge-watch.json", {});
      verdictBefore.push(judgeQueued(Object.values(s.home.queue)[0], "1", s.peer, EID[4663]).verdict);
      down = true;
    }
  });
  return { sends, errors, verdictBefore, alerts: [...new Set(a.log.map((x) => `${x.level} ${x.key}`))] };
}
test("control: with the mainnet RPC up, the honest matured claim is sent in the first pass after it matures", async () => {
  const r = await run(false);
  assert.equal(r.sends.length, 1);
  assert.ok(r.sends[0].t >= 900 && r.sends[0].t <= 1030, `sent at +${r.sends[0].t}s`);
});
test("a matured claim already matched to its Sent is sent while the PEER chain's RPC is down", async () => {
  const r = await run(true);
  console.log(`verdict saved before the outage: ${r.verdictBefore}; passes that threw: ${r.errors.length} ("${r.errors[0]?.e}"); bridge alerts in 30 min: [${r.alerts}]`);
  assert.equal(r.sends.length, 1, `matured at +900 s, verdict "${r.verdictBefore}" already on disk, ${r.errors.length} passes threw, ${r.sends.length} claims sent by +2700 s`);
});
test("P5: a FORGED claim queued at home while the peer RPC is down is flagged (forged or unverified) long before it matures", async () => {
  fresh();
  const { forgeQueued } = await import("./lib/bridge-world.mjs");
  const w = makeBridgeWorld({ seed: 9, home: 4663 }); // delay 12 h
  const f = forgeQueued(w, 4663, 1000, T0 + 900, E18.mul(40_000)); // queued on 4663 at +900 s, claimable by anyone 12 h later
  const a = recorder(w);
  const ctx = bridgeCtx(w, [], { alerts: a });
  let down = false;
  for (const o of [w.peer.provider, w.peer.bridgeContract]) for (const k of Object.keys(o)) if (typeof o[k] === "function") { const fn = o[k]; o[k] = async (...x) => { if (down) throw new Error("mainnet RPC: 503"); return fn(...x); }; }
  const errors = await passes(w, ctx, T0 + 60, T0 + 900 + 43_200, (p) => { if (p >= T0 + 850) down = true; });
  const named = a.log.filter((x) => /-1000$/.test(x.key));
  console.log(`forged claim of 40,000 imdUSD queued at +900 s, matured at +${Math.round(f.claim.mature - T0)} s; passes that threw: ${errors.length}; bridge alerts naming it in 12 h: [${named.map((x) => x.key)}]; all bridge alerts: [${[...new Set(a.log.map((x) => x.key))]}]`);
  assert.ok(named.length > 0, `home-chain reads worked all along, yet in 12 h no bridge alert named the forged Queued (only loop-failing-bridge from keeper.mjs after 5 passes)`);
});
```

### 5. Medium: P1/C3/C5: the watcher's log walk is unbounded and all-or-nothing inside one pass; with the shipped peer.fromBlock 0 a fresh start walks the peer chain from genesis (10,448 serial getLogs for mainnet)

`lib/bridge.mjs:383`

```
    while (next <= top) {
```

Merged from three specialist reports; reproduced. indexSide walks [side.next, head - lag] in ONE call (line 383), holding every event back; the cursor moves only after the counter proof at the very end (lines 460-463) and runBridge writes bridge-watch.json only after both sides return (line 700). There is no per-pass budget and no saved progress. config.example.js ships `BRIDGE_WATCH.peer: { bridge: null, fromBlock: 0 }` for mainnet (line 64) and CHAINS[4663] (line 103), its comment asks the operator only for peer.bridge, and runBridge seeds the peer side with emptySide(Number(W.peer.fromBlock ?? 0)) (line 660) and the default 9,000-block chunk (W.peerLogs unset, line 682). The home side has record.deployBlock; the peer side has no such default.
CALL SEQUENCE: first bridge pass of the 4663 keeper -> indexSide(peer = mainnet, from 0): 2,612 ranges x 2 agreeing bridge reads + 2 agreeing reads of EVERY PacketVerified on EndpointV2 (receiver not indexed) = 10,448 eth_getLogs before anything is folded or written (measured in the test; the mainnet keeper does the same over 4663's ~117M blocks on the ONE rate-limited public RPC: ~52,000). A single non-refused error mid-walk (a 429, a 30 s timeout) throws the pass away: side.next is still 0 and the next pass, 120 s later, starts again from block 0 and holds the serial queue again (previous finding: no alert, Pulse gap passes).
EXPECTED: a pass does a bounded amount of paging, keeps each proven range and resumes. ACTUAL: cursor still at block 0 after 8 agreeing reads and one 429; 10,448 log reads in one pass.
SEVERITY: medium on its own (the watcher cannot get past its backfill on a rate-limited RPC and judges nothing meanwhile); it is the shipped trigger of the high scheduler finding (keeper.mjs:177), whose proof also exercises this walk.
REACHABLE WITH THE DEPLOY CONFIG: yes as shipped (fromBlock 0), at first start, after bridge-watch.json is moved aside as unreadable, or when the peer bridge address changes (line 660 resets the side).
SMALLEST FIX: prove and fold PER CHUNK (countersAt(to) after each agreed chunk, then addEvents, side.next = to + 1, writeState); cap the chunks walked per pass and return so the next pass continues; refuse a peer fromBlock of 0 when a bridge is set (require or discover the peer bridge's deploy block).

**Reproduction**

State: emptySide(0) as runBridge builds for the peer on the shipped config; (a) head 100,000, the 9th getLogs answers "429 Too Many Requests"; (b) head 23,500,000, endpoint watched, empty logs. Expected: (a) side.next > 0 (four agreed chunks kept); (b) a bounded number of reads. Actual: (a) cursor 0; (b) 10,448 getLogs in the one pass.
RUN (Node 20+, after npm ci): save the test below as test/zz-b2.test.mjs, run `node --test test/zz-b2.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-b2.test.mjs -----
// P1/C5: indexSide folds and persists NOTHING until a whole walk from the cursor to head-lag is done; peer.fromBlock ships as 0.
import { test } from "node:test";
import assert from "node:assert/strict";
import { BigNumber } from "ethers";
import { emptySide, indexSide } from "../lib/bridge.mjs";
import { chainConfig } from "../lib/chains.mjs";
import example from "../config.example.js";
const bridge = { address: "0x00000000000000000000000000000000000B0001", sent: async () => BigNumber.from(0), received: async () => BigNumber.from(0) };
const makeProvider = (head, failAt = Infinity) => {
  const p = { getLogsCalls: 0 };
  p.getBlockNumber = async () => head;
  p.getLogs = async () => { p.getLogsCalls++; if (p.getLogsCalls === failAt) throw new Error("429 Too Many Requests"); return []; };
  p.getBlock = async (n) => ({ number: n, timestamp: 1_800_000_000 + Number(n) });
  p.getCode = async () => "0x6000";
  return p;
};
test("the shipped config starts the peer side at block 0 on both keepers", () => {
  assert.deepEqual([chainConfig(example, 1).BRIDGE_WATCH.peer.fromBlock, chainConfig(example, 4663).BRIDGE_WATCH.peer.fromBlock, chainConfig(example, 4663).BRIDGE_WATCH.peerLogs], [0, 0, undefined]);
});
test("a read that fails after four proven chunks keeps what it proved (the cursor moves)", async () => {
  const provider = makeProvider(100_000, 9); // 4 chunks read twice each and agreeing; the 9th read fails
  const side = emptySide(0);
  await assert.rejects(indexSide(provider, bridge, side, { lag: 3, chunk: 9_000 }), /429/);
  assert.ok(side.next > 0, `cursor still at block ${side.next} after 8 agreeing reads: nothing proven is kept, the next pass starts from 0 again`);
});
test("one pass from fromBlock 0 at mainnet's height is bounded", async () => {
  const provider = makeProvider(23_500_000);
  const side = emptySide(0);
  await indexSide(provider, bridge, side, { lag: 3, chunk: 9_000 }, "0x1a44076050125825900e736c501f859c50fE728c", null);
  console.log(`getLogs calls in the one pass: ${provider.getLogsCalls}`);
  assert.ok(provider.getLogsCalls <= 100, `${provider.getLogsCalls} serial log reads in ONE pass (at 0.5 s each: ${Math.round(provider.getLogsCalls / 2)} s with no Pulse poke meanwhile; gap 900 s)`);
});

----- OUTPUT on f30a9d0 -----
getLogs calls in the one pass: 10448
✔ the shipped config starts the peer side at block 0 on both keepers (1.562137ms)
✖ a read that fails after four proven chunks keeps what it proved (the cursor moves) (5.259406ms)
✖ one pass from fromBlock 0 at mainnet's height is bounded (48.811311ms)
ℹ tests 3
ℹ pass 1
ℹ fail 2

✖ failing tests:

test at test/zz-b2.test.mjs:20:1
✖ a read that fails after four proven chunks keeps what it proved (the cursor moves) (5.259406ms)
  AssertionError [ERR_ASSERTION]: cursor still at block 0 after 8 agreeing reads: nothing proven is kept, the next pass starts from 0 again
    code: 'ERR_ASSERTION',
    actual: false,
    expected: true,
  }

test at test/zz-b2.test.mjs:26:1
✖ one pass from fromBlock 0 at mainnet's height is bounded (48.811311ms)
  AssertionError [ERR_ASSERTION]: 10448 serial log reads in ONE pass (at 0.5 s each: 5224 s with no Pulse poke meanwhile; gap 900 s)
    code: 'ERR_ASSERTION',
    actual: false,
    expected: true,
  }

### 6. Medium: C3 (range-capped / rate-limited 4663 RPC): with ONE log RPC a refused getLogs range is never halved; the watcher and the position index throw every pass

`lib/chain.mjs:65`

```
    if (nodes.length === 1) return nodes[0](method, p);
```

Merged from two specialist reports; reproduced. indexSide halves a range only when the error carries e.refused (lib/bridge.mjs:389, :399 `if (!e.refused || size <= minChunk) throw e;`), and the position index does the same (lib/index.mjs:37). `refused` is set only on AgreeingProvider's multi-node path (lib/chain.mjs:74-78). With one node _agreed returns the node's promise untouched (line 65), so a "range too large" / 429 error from a lone RPC has no refused flag and is rethrown at the first, largest range. The lone RPC is the 4663 default (CHAIN_DEFAULTS[4663].READ_RPC_URLS has one URL; LOG_RPC_URLS is left out while BLOCKSCOUT_KEY is unset; config.example.js PEERS[4663] has one URL), the 4663 home chunk is 50,000 blocks (lib/chains.mjs:50), and lib/bridge.mjs:338 itself says "the 4663 public RPC caps ranges".
EFFECT once any range is refused: the bridge loop throws every pass (no Received, Queued or PacketVerified on that chain is indexed or judged, no claim sent: P5, P8); on 4663 runPositions/runStocks (loadIndex/freshIndex) throw the same way, so no bite, mark or auction tick goes out (P1). It is loud (loop-failing-* after 5 passes) but nothing recovers.
EXPECTED: the lone RPC is asked for 4,500, 2,250, 1,125 blocks like two RPCs are (control passes: "indexed through 99997"). ACTUAL: THREW "query exceeds max block range 2000" (refused=undefined) after asking 9000 blocks.
REACHABLE WITH THE DEPLOY CONFIG: yes whenever the single RPC caps a range under the configured chunk or rate-limits it. Not verified against the live public RPC (whether today's node caps below 50,000 / 9,000 blocks rests on the repository's own comment).
SMALLEST FIX: in _agreed, for nodes.length === 1, catch a transport error (revertData(e) starting "transport:") and rethrow it with refused = true.

**Reproduction**

State: the real AgreeingProvider with one URL, its log node refusing any range over 2,000 blocks (SERVER_ERROR); indexSide(chunk 9,000, lag 3) from block 1 to head 100,000. Expected: "indexed through 99997" (as with two URLs). Actual: throws at the first 9,000-block request.
RUN (Node 20+, after npm ci): save the test below as test/zz-d.test.mjs, run `node --test test/zz-d.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-d.test.mjs -----
// C3: with ONE log RPC a refused range is never halved.
import { test } from "node:test";
import assert from "node:assert/strict";
import { BigNumber } from "ethers";
import { indexSide, emptySide } from "../lib/bridge.mjs";
import { AgreeingProvider } from "../lib/chain.mjs";
const BRIDGE = "0x00000000000000000000000000000000000B4663";
const zero = BigNumber.from(0);
test("a lone RPC that refuses a log range is asked for a smaller one, as two RPCs are", async () => {
  const run = async (urls) => {
    const ap = new AgreeingProvider(urls, 4663);
    ap.getBlockNumber = async () => 100_000;
    ap.getBlock = async (n) => ({ number: Number(n), timestamp: 1_800_000_000 });
    const asked = [];
    const node = { perform: async (m, p) => {
      const span = Number(p.filter.toBlock) - Number(p.filter.fromBlock) + 1;
      asked.push(span);
      if (span > 2_000) throw Object.assign(new Error("query exceeds max block range 2000"), { code: "SERVER_ERROR" });
      return [];
    } };
    ap.logProviders = urls.map(() => node);
    const side = emptySide(1);
    try {
      await indexSide(ap, { address: BRIDGE, sent: async () => zero, received: async () => zero }, side, { chunk: 9_000, lag: 3 });
      return `indexed through ${side.throughBlock}`;
    } catch (e) { return `THREW "${e.message}" (refused=${e.refused}) after asking ${asked} blocks`; }
  };
  const u = "http://127.0.0.1:1";
  assert.equal(await run([u, u]), "indexed through 99997", "control: with two log RPCs the range is halved until it fits");
  assert.equal(await run([u]), "indexed through 99997", "the lone RPC (CHAIN_DEFAULTS[4663].READ_RPC_URLS, PEERS[4663])");
});

----- OUTPUT on f30a9d0 -----
✖ a lone RPC that refuses a log range is asked for a smaller one, as two RPCs are (2613.114316ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-d.test.mjs:9:1
✖ a lone RPC that refuses a log range is asked for a smaller one, as two RPCs are (2613.114316ms)
  AssertionError [ERR_ASSERTION]: the lone RPC (CHAIN_DEFAULTS[4663].READ_RPC_URLS, PEERS[4663])
  + actual - expected
  
  + 'THREW "query exceeds max block range 2000" (refused=undefined) after asking 9000 blocks'
  - 'indexed through 99997'
  
    code: 'ERR_ASSERTION',
    actual: 'THREW "query exceeds max block range 2000" (refused=undefined) after asking 9000 blocks',
    expected: 'indexed through 99997',
  }

### 7. Medium: P1/P5: an alert that escalates from warn to critical under the same key is swallowed until an hour after the warn (the 30-minute bridge-index-gap critical is emitted at 60 minutes)

`lib/alerts.mjs:9`

```
export function shouldFire(seen, level, nowSec) {
  if (!seen) return true;
  return nowSec - seen.at >= (REPEAT[level] ?? REPEAT.warn);
}
```

Merged from two specialist reports; reproduced. shouldFire looks only at when the KEY last fired, with the repeat interval of the NEW level; it never compares levels. A key first raised as warn at t0 and raised as critical afterwards is not emitted (log, alerts.jsonl, Telegram) until t0 + 3600 s, and seen.level stays "warn". Keys that escalate in place: bridge-index-gap-* (warn at once, critical after unverifiedSeconds = 30 min, lib/bridge.mjs:697: the one state in which the watcher judges nothing), bridge-claims-closed-* (warn PAUSED -> critical tripped, :574/:621), bridge-verified-forged-* (warn -> critical, :229-233), bridge-queued-forged-* (warn cancelled -> critical pending again after ClaimRestored, :158-160), bridge-stuck-* (warn 30 min -> critical 2 h).
EXPECTED (README: bridge-index-gap "critical after 30 min"; P5 "unverified within 30 min"): the CRITICAL line in the pass in which the condition becomes critical. ACTUAL: "60 min: ALERT CRITICAL". While the cursor is stalled the per-transfer bridge-unverified-* alerts cannot fire either (their clock is the stalled side's throughTime).
REACHABLE WITH THE DEPLOY CONFIG: yes, it is the default alert path. With Telegram-only alerts and a 12 h window, warn (repeats every 6 h) vs critical (hourly) is the signal the signers act on.
SMALLEST FIX: fire at once when the level rises: `if (!seen || rank[level] > rank[seen.level]) return true;` with rank { info: 0, warn: 1, critical: 2 } (raise() already stores level beside at).

**Reproduction**

State: makeAlerts on a fresh state dir; raise("warn", "bridge-index-gap-4663") at 0 min, the same key every 2 min, at "critical" from 30 min on (what lib/bridge.mjs:697 does). Expected: first CRITICAL line at 30 min. Actual: at 60 min.
RUN (Node 20+, after npm ci): save the test below as test/zz-e.test.mjs, run `node --test test/zz-e.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-e.test.mjs -----
// P1/P5: an alert that escalates warn -> critical on the same key is swallowed until an hour after the warn.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-esc-"));
const { makeAlerts } = await import("../lib/alerts.mjs");
test("an alert that escalates from warn to critical fires when it becomes critical", async (t) => {
  t.mock.timers.enable({ apis: ["Date"], now: 1_800_000_000_000 });
  const lines = [];
  const alerts = makeAlerts((s) => lines.push(s));
  await alerts.raise("warn", "bridge-index-gap-4663", "logs cannot be proven complete"); // lib/bridge.mjs:697, first pass of a gap
  const fired = [];
  for (let min = 2; min <= 90; min += 2) { // the watcher's passes; from 30 min on it raises the SAME key at critical
    t.mock.timers.setTime(1_800_000_000_000 + min * 60_000);
    const before = lines.length;
    await alerts.raise(min >= 30 ? "critical" : "warn", "bridge-index-gap-4663", "logs cannot be proven complete");
    if (lines.length > before) fired.push(`${min} min: ${lines.at(-1).slice(0, 14)}`);
  }
  assert.deepEqual(fired[0], "30 min: ALERT CRITICAL", `the critical first reached the log/Telegram at ${fired[0]}`);
});

----- OUTPUT on f30a9d0 -----
✖ an alert that escalates from warn to critical fires when it becomes critical (12.971443ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-e.test.mjs:9:1
✖ an alert that escalates from warn to critical fires when it becomes critical (12.971443ms)
  AssertionError [ERR_ASSERTION]: the critical first reached the log/Telegram at 60 min: ALERT CRITICAL
  + actual - expected
  
  + '60 min: ALERT CRITICAL'
  - '30 min: ALERT CRITICAL'
  
    code: 'ERR_ASSERTION',
    actual: '60 min: ALERT CRITICAL',
    expected: '30 min: ALERT CRITICAL',
  }

### 8. Medium: P4/C3: a standing bridge-index-gap alert is cleared, and its 30 min count to critical restarted, by a pass that read nothing (a stale head at or below the cursor)

`lib/bridge.mjs:698`

```
    } else delete side.gapSince;
```

Merged from two specialist reports; reproduced. indexSide returns {} without reading anything when the head it is given is at or below the cursor (line 357 `if (side.next > top) return {};`). runBridge reads "no gap in the result" as "the gap is over": line 698 deletes side.gapSince, no bridge-index-gap-* is pushed, and the settle at line 752 clears the standing alert ("cleared (was warn)"). The unproven range is still unread and the cursor has not moved. The head comes from the first read RPC alone (lib/chain.mjs:56).
CALL SEQUENCE: 4663's log RPC answers [] for a range holding a Received (the counters move, so every pass returns gap): warn at +300 s, gapSince set. At +660 s the RPC serves a head at cursor + 2 (under the 3-block lag): indexSide -> {} -> gapSince deleted, alert cleared. At +780 s the gap is found again with held = 0 s. Repeated every 10 min, held never reaches 1800 s.
EXPECTED (P4 "no alert is cleared by a failed read; a log range is marked read only once its contents are proven"): held every pass, critical after 30 min. ACTUAL over 84 min of an unrepaired gap: cleared 8 times, critical NEVER. Whatever sits behind the cursor (equally a forged Received hidden by empty log answers) is never judged, and the signers see warn / cleared / warn.
REACHABLE WITH THE DEPLOY CONFIG: yes on 4663 as shipped (one public RPC serves head and logs; "empty logs, stale heads" are both in the threat model); it needs a head as old as the cursor (a hostile or badly lagging backend), not an ordinary hiccup.
SMALLEST FIX: only a walk that PROVED a range ends a gap: return { idle: true } from the early exit and, in runBridge, keep gapSince and re-push the standing alert when side.gapSince !== undefined and the result is idle; treat a head below the last proven block as a failed read. Related: fixing only this or only the escalation finding still leaves the gap without a timely critical.

**Reproduction**

State: real runBridge over the repo's bridge-world, home 4663; one Received on 4663 at T0+300 whose log the log RPC never returns; from the 6th pass every 5th pass eth_blockNumber answers cursor + 2; 90 min of passes every 120 s. Expected: bridge-index-gap-4663 in settle()'s held set on every pass after it is first raised, critical after 30 min. Actual: cleared at +660, +1260, ... +4860 s (8 times); critical NEVER.
RUN (Node 20+, after npm ci): save the test below as test/zz-f.test.mjs, run `node --test test/zz-f.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-f.test.mjs -----
// P4/P5: a standing bridge-index-gap alert is cleared, and its 30 min clock restarted, by a pass that read nothing (stale head).
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-stale-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, E18, honest, makeBridgeWorld, T0 } = await import("./lib/bridge-world.mjs");
test("while 4663's bridge logs stay unprovable, the gap alert is held every pass and goes critical after 30 min", async () => {
  const w = makeBridgeWorld({ seed: 2, home: 4663 });
  honest(w, 1, 1, T0 + 100, 200, E18.mul(100)); // a Received on 4663 at T0 + 300
  const getLogs = w.home.provider.getLogs;
  w.home.provider.getLogs = async (f) => (await getLogs(f)).filter((l) => l.address.toLowerCase() !== w.home.bridge.toLowerCase());
  let stale = null;
  const head = w.home.provider.getBlockNumber;
  w.home.provider.getBlockNumber = async () => (stale === null ? head() : (await head(), stale));
  const passes = [];
  let cur;
  const ctx = bridgeCtx(w, [], { alerts: { raise: async (level, key) => cur.raised.push(`${level}:${key}`), settle: async (prefix, held) => { cur.held = held; } } });
  for (let i = 0, t = T0 + 60; t <= T0 + 5400; t += 120, i++) {
    if (w.t < t) w.t = t;
    const cursor = readStateOr("bridge-watch.json", {}).home?.next;
    stale = i > 4 && i % 5 === 0 ? cursor + 2 : null; // every 5th pass: a head at or below what was already read
    cur = { at: Math.round(w.t - T0), stale: stale !== null, raised: [], held: new Set() };
    await runBridge(ctx);
    passes.push(cur);
  }
  const KEY = "bridge-index-gap-4663";
  const first = passes.findIndex((p) => p.raised.some((k) => k.endsWith(KEY)));
  assert.ok(first >= 0, "the gap is seen at all");
  const after = passes.slice(first);
  const cleared = after.filter((p) => !p.held.has(KEY));
  const critical = after.find((p) => p.raised.includes(`critical:${KEY}`));
  console.log(`gap first raised at +${after[0].at}s, never repaired; ${after.length} passes over ${Math.round((after.at(-1).at - after[0].at) / 60)} min`);
  console.log(`passes that CLEARED the alert: ${cleared.map((p) => `+${p.at}s${p.stale ? " (stale head)" : ""}`).join(", ") || "none"}`);
  console.log(`critical raised: ${critical ? `+${critical.at}s` : "NEVER"}`);
  assert.deepEqual(cleared.map((p) => p.at), [], "the standing gap alert was cleared by passes that read nothing");
  assert.ok(critical, "never critical");
});

----- OUTPUT on f30a9d0 -----
gap first raised at +300s, never repaired; 43 passes over 84 min
passes that CLEARED the alert: +660s (stale head), +1260s (stale head), +1860s (stale head), +2460s (stale head), +3060s (stale head), +3660s (stale head), +4260s (stale head), +4860s (stale head)
critical raised: NEVER
✖ while 4663's bridge logs stay unprovable, the gap alert is held every pass and goes critical after 30 min (486.920441ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-f.test.mjs:11:1
✖ while 4663's bridge logs stay unprovable, the gap alert is held every pass and goes critical after 30 min (486.920441ms)
  AssertionError [ERR_ASSERT

### 9. Medium: P3: the fee ceiling is skipped when the first read RPC's latest block carries no baseFeePerGas; a legacy transaction is signed at whatever eth_gasPrice answers after the ceiling check (5,000 gwei sign

`lib/tx.mjs:119`

```
    const base = (await provider.getBlock("latest")).baseFeePerGas;
    if (!base) return null;
```

Merged from two specialist reports (rated medium and high); reproduced through the real send() + guardedSigner + ethers Wallet. feesNow() returns null when the latest block has no baseFeePerGas (lines 119-120). signer.sendTransaction then adds no fees (line 169 `if (fees) tx = ...`) and signs whatever ethers' populateTransaction picks (line 176): with no base fee that is a LEGACY transaction at eth_gasPrice, read again at that moment. The only ceiling on this path is send()'s EARLIER, separate provider.getGasPrice() read (lines 234-239). Nothing bounds the populated transaction before signTransaction. getBlock and getGasPrice are unpinned: they come from the FIRST read RPC alone even when two agreeing RPCs are configured (lib/chain.mjs:56).
CALL SEQUENCE: act -> send(): getGasPrice answers 5 gwei (under the ceiling) -> simulate -> signer.sendTransaction -> feesNow(): block without baseFeePerGas -> null -> populateTransaction -> eth_gasPrice 5,000 gwei -> signTransaction -> recordIntent -> broadcast to SEND_RPC_URLS, where a legacy transaction pays its whole gasPrice (everything over the base fee goes to the block's builder).
EXPECTED (README guard rails "nothing is ever signed above MAX_GAS_GWEI per gas"; P3): refused or capped. ACTUAL: type-0 transaction at 5,000 gwei: 1.5 ETH for one 300,000-gas send. signer.bump() returns null for a non-type-2 intent (line 139), so the 4-replacement / cancel bound does not apply either; every later urgent send goes the same way on the next nonce. The spend is bounded only by the key's ETH balance, after which every duty stops on the ETH floor.
REACHABLE WITH THE DEPLOY CONFIG: yes when the first READ_RPC_URLS entry is hostile, MITMed or broken (the example's first entry is a public RPC; the threat model's first actor); not while that RPC honestly serves a post-London chain. On 4663 the sequencer charges only the base fee, so the over-bid is not collected there. Severity medium: needs a hostile RPC, loss bounded by a hot key's balance.
SMALLEST FIX: in signer.sendTransaction, after populateTransaction and before signTransaction, refuse (throw, nothing signed) unless the transaction is type 2 with maxFeePerGas <= feeCeiling(cfg, tier); treat feesNow() === null as a refused read instead of falling back to ethers' defaults.

**Reproduction**

State: the first read RPC returns a latest block without baseFeePerGas; eth_gasPrice = 5 gwei on the first call (send()'s check) and 5,000 gwei after; balance 2 ETH; MAX_GAS_GWEI 100 (config.example.js). Call send(signer, "bark #1", ..., { tier: "urgent" }) with a 300,000-gas transaction. Expected: nothing signed above 100 gwei per gas. Actual: the journalled signed transaction is type 0 at gasPrice 5,000 gwei (1.5 ETH).
RUN (Node 20+, after npm ci): save the test below as test/zz-g.test.mjs, run `node --test test/zz-g.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-g.test.mjs -----
// P3: nothing is ever signed above MAX_GAS_GWEI per gas, whatever the first read RPC answers for the block and the gas price
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { feeCeiling, guardedSigner, send } = await import("../lib/tx.mjs");
const { pendingIntents } = await import("../lib/journal.mjs");
const example = (await import("../config.example.js")).default;
const h32 = (n) => utils.hexZeroPad(utils.hexlify(n), 32);
const gwei = (n) => utils.parseUnits(String(n), "gwei");
test("P3: no transaction is signed above MAX_GAS_GWEI when the latest block carries no baseFeePerGas", async () => {
  // The FIRST read RPC serves head, blocks and gas price alone (lib/chain.mjs:56). Hostile or broken: its latest block has no
  // baseFeePerGas; eth_gasPrice says 5 gwei when send() checks the ceiling (lib/tx.mjs:234) and 5,000 gwei when ethers populates.
  let gasPriceCalls = 0;
  class Rpc extends providers.StaticJsonRpcProvider {
    async perform(method) {
      if (method === "getBlock") return { hash: h32(1), parentHash: h32(2), number: "0x10", timestamp: "0x6b49d200", nonce: "0x0000000000000000", difficulty: "0x0", gasLimit: "0x1c9c380", gasUsed: "0x0", miner: "0x0000000000000000000000000000000000000001", extraData: "0x", transactions: [] };
      if (method === "getGasPrice") return (++gasPriceCalls === 1 ? gwei(5) : gwei(5000)).toHexString();
      if (method === "getBalance") return utils.parseEther("2").toHexString();
      if (method === "getTransactionCount") return "0x0";
      if (method === "getBlockNumber") return "0x10";
      throw new Error(`unexpected ${method}`);
    }
  }
  const provider = new Rpc("http://127.0.0.1:1", 1);
  const cfg = { ...example, SEND_RPC_URLS: [] }; // MAX_GAS_GWEI 100; no relay here, so the signed bytes stay in the send journal
  const signer = guardedSigner(Wallet.fromMnemonic("test test test test test test test test test test test junk").connect(provider), provider, cfg, "tx");
  const r = await send(signer, "bark #1", async () => {}, () => signer.sendTransaction({ to: "0x00000000000000000000000000000000000000aa", data: "0x", gasLimit: 300_000 }), cfg, { tier: "urgent" }).catch((e) => ({ threw: String(e?.message ?? e).slice(0, 80) }));
  const [intent] = pendingIntents("tx");
  assert.ok(intent, `setup: send() passed its ceiling check and the transaction was signed and journalled (${JSON.stringify(r)})`);
  const t = utils.parseTransaction(intent.signed);
  const perGas = t.maxFeePerGas ?? t.gasPrice;
  assert.ok(perGas.lte(feeCeiling(cfg, "urgent")), `signed type ${t.type} at ${utils.formatUnits(perGas, "gwei")} gwei per gas (ceiling ${utils.formatUnits(feeCeiling(cfg, "urgent"), "gwei")}): ${utils.formatEther(perGas.mul(t.gasLimit))} ETH for this one transaction, and signer.bump cannot replace or cancel it (not type 2)`);
});

----- OUTPUT on f30a9d0 -----
✖ P3: no transaction is signed above MAX_GAS_GWEI when the latest block carries no baseFeePerGas (140.303569ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-g.test.mjs:14:1
✖ P3: no transaction is signed a

### 10. Medium: C3 refuted / P5 / P8: the proven index is never re-checked after a reorg deeper than the lag (3 blocks on the peer side): honest transfers stay 'FORGED' for good, the honest queued claim is never sent

`lib/bridge.mjs:460`

```
    addEvents(side, events);
    side.next = through + 1;
    side.throughBlock = through;
```

Specialist (economics) finding; its test was truncated, so two tests were written and run here. Once a range passes the counter proof its events are folded and the cursor moves (lines 460-462); no block hash is kept and nothing below the cursor is ever read again. The lag is 3 blocks (indexSide default; LOGS.lag 3; the PEER side always uses the default because BRIDGE_WATCH.peerLogs is unset: on 4663 that is about a second, on Ethereum 36 s; the 4663 home side uses lag 20, about 5 s).
(a) A source reorg that changes a folded Sent but not the totals: two bridge sends of one 4663 block re-sequenced the other way round (nonce 1 -> U2, nonce 2 -> U1; same guids, since a guid is the path's nonce; same amounts; same sent counter). The canonical deliveries then do not match the stale index: line 132-134 raises critical bridge-forged-<dst>-<nonce> ("does NOT match ... FORGED. Safe: pause the path") for the honest Received, lines 155-158 raise bridge-queued-forged-* for the honest Queued, and autoClaim skips it for ever (line 552). Nothing repairs it until a human deletes bridge-watch.json.
(b) A reorg that changes the totals of the proven range (an indexed Sent re-included in a later block, or dropped): the counter equation can never hold again from the stored side.counted, so the cursor stops for good behind bridge-index-gap-* and nothing past it is judged or claimed.
EXPECTED (C3 "despite ... reorgs"; P5; P8): the index follows the canonical chain. ACTUAL: (a) still standing an hour later: bridge-forged-mainnet-1, bridge-queued-forged-mainnet-2, queued verdict "forged"; (b) 4663 cursor at block 50182 before the reorg and an hour later (head 53915).
REACHABLE WITH THE DEPLOY CONFIG: yes given a 4663 sequencer reorg deeper than 3 blocks (in the threat model) or an Ethereum reorg deeper than 3 blocks (rare).
SMALLEST FIX: keep the block hash of the last proven block (and of each folded event's block); at the start of indexSide re-read them and, on a mismatch, rewind the side to the last checkpoint that still matches (drop events above it, restore its counters) and read again. Index the peer at a real depth (Ethereum's "finalized"/"safe" tag, or a lag in seconds) instead of 3 blocks.

**Reproduction**

State: mainnet keeper. (a) A 4663 block at T0+100 holds Sent(nonce 1 -> U1, 100) and Sent(nonce 2 -> U2, 100); indexed and proven; the block is reorged to Sent(nonce 1 -> U2), Sent(nonce 2 -> U1); mainnet gets Received(nonce 1 -> U2, 100) and Queued(nonce 2 -> U1, 100). Expected: no forged alert, judgeQueued "honest". Actual: both critical, verdict "forged". (b) One Sent at T0+100, indexed; reorged to T0+200 (past the cursor). Expected: the cursor keeps moving. Actual: it never moves again.
RUN (Node 20+, after npm ci): save the test below as test/zz-l.test.mjs, run `node --test test/zz-l.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-l.test.mjs -----
// C3/P5/P8: the proven index is never re-checked after a reorg deeper than the lag (3 blocks on the peer side)
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, utils } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runBridge, judgeQueued } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { EID } = await import("../lib/robinhood.mjs");
const { BRIDGE_IFACE, bridgeCtx, E18, honest, makeBridgeWorld, guidOf, settleClaim, T0 } = await import("./lib/bridge-world.mjs");
const fresh = () => rmSync(process.env.STATE_DIR, { recursive: true, force: true });
const addr = (i) => utils.getAddress(utils.hexZeroPad(utils.hexlify(i), 20));
/** Alerts as lib/alerts.mjs keeps them: raise makes a key stand, settle clears every key of the prefix this pass did not raise. */
const recorder = (w) => {
  const standing = new Map(), log = [];
  return { standing, log,
    raise: async (level, key, msg) => { standing.set(key, level); log.push({ t: Math.round(w.t - T0), level, key, msg }); },
    settle: async (prefix, held) => { for (const k of [...standing.keys()]) if (k.startsWith(prefix) && !held.has(k)) { log.push({ t: Math.round(w.t - T0), level: "cleared", key: k, was: standing.get(k) }); standing.delete(k); } } };
};
/** The watcher every 120 s, as keeper.mjs runs it: a pass that throws is logged and the next one runs. */
async function passes(w, ctx, from, to, each = () => {}) {
  const errors = [];
  for (let p = from; p <= to; p += 120) { if (w.t < p) w.t = p; await each(p); try { await runBridge(ctx); } catch (e) { errors.push({ t: p - T0, e: e.message }); } }
  return errors;
}
const put = (c, t, name, args, d) => {
  const encoded = BRIDGE_IFACE.encodeEventLog(BRIDGE_IFACE.getEvent(name), args);
  const block = c.headAt(t);
  c.logs.push({ block, address: c.bridge, name, encoded, topic0: encoded.topics[0], tx: utils.hexZeroPad(utils.hexlify(0x7000 + c.logs.length), 32), logIndex: c.logs.filter((l) => l.block === block).length, d });
  c.logs.sort((a, b) => a.block - b.block || a.logIndex - b.logIndex);
};
test("a 4663 reorg that re-sequences two sends of one block never turns the honest deliveries into 'forged' ones", async () => {
  fresh();
  const w = makeBridgeWorld({ seed: 2, home: 1 }); // the mainnet keeper; 4663 is read with the default 3-block lag (BRIDGE_WATCH.peerLogs unset)
  const src = w.chains[4663], dst = w.chains[1];
  const U1 = addr(0xa1), U2 = addr(0xa2), amt = E18.mul(100);
  const sent = (to, nonce) => put(src, T0 + 100, "Sent", [guidOf(4663, nonce), EID[1], addr(0xf0), utils.hexZeroPad(to, 32), amt, nonce], { sent: amt });
  sent(U1, 1); sent(U2, 2); // two users bridge in one 4663 block: nonce 1 -> U1, nonce 2 -> U2
  const a = recorder(w);
  const ctx = bridgeCtx(w, [], { alerts: a });
  await passes(w, ctx, T0 + 60, T0 + 300); // indexed and proven
  assert.equal(Object.keys(readStateOr("bridge-watch.json", {}).peer.sent).length, 2, "setup: both Sent are in the proven index");
  // The 4663 block is reorged (the sequencer re-sequences): the two sends land t

### 11. Medium: P5/P4/C3: PacketVerified (and hold / void) logs are 'proven' by two reads of the same node: a lone log RPC answering [] for the endpoint's logs marks the range read, and a forged packet waiting at the

`lib/bridge.mjs:397`

```
          epLogs = await readAgreed(provider, { address: endpoint, topics: [verifiedTopic], fromBlock: next, toBlock: to }, maxReads);
```

This review's own finding (no specialist reported it). C3 states that PacketVerified, hold and void logs move no counter, "so two agreeing reads alone prove them". readAgreed (lines 287-299) calls provider.getLogs repeatedly and accepts the range when the last two answers are equal. With two log RPCs the AgreeingProvider compares the nodes; with ONE (the 4663 default, CHAIN_DEFAULTS[4663].READ_RPC_URLS, and mainnet's PEERS[4663]) the "two agreeing reads" are the same node asked twice within milliseconds. A node that answers [] for the EndpointV2 filter (a result-capped or lagging log backend, a log-only door behind the head, a hostile RPC: "empty logs" in the threat model) agrees with itself, epLogs is [] (line 397), no counter covers these events, the walk folds nothing for them and the cursor moves past the block (lines 460-462). Nothing below the cursor is ever read again, so the PacketVerified is lost for good.
CALL SEQUENCE: forged packet verified at 4663's endpoint at T0+300, not executed (it waits: a paused path, the inbound limit, a hold) -> runBridge on 4663 -> indexSide(home): bridge logs honest, endpoint logs [] twice -> range marked read, cursor past block 50300 -> verifiedAlerts sees nothing. After one hour the RPC answers the endpoint's logs honestly: the cursor is far past, nothing is re-read.
EXPECTED (P5 "a forged packet verified at the endpoint is flagged while it still waits"; P4 "a log range is marked read only once its contents are proven"): critical bridge-verified-forged-4663-1000 (the control flags it within minutes), or a gap. ACTUAL: alerts in 4 h: []; the cursor is at 64341. The Safe loses the only window in which hold(srcEid, nonce) / voidPayload(hash) can stop the packet before it runs; the forgery is then seen only from its Received (after the mint) or its Queued. The same holds for HoldPlaced / Voided logs of the bridge when no counter-moving event shares the answer.
REACHABLE WITH THE DEPLOY CONFIG: yes on the shipped single-RPC settings, given a node that returns an empty answer for that filter.
SMALLEST FIX: prove verified packets against the endpoint's own state instead of its logs: each pass read EndpointV2.inboundNonce(receiver, srcEid, sender) (LayerZero V2 MessagingChannel) at the block read through and require a PacketVerified in the index (or read inboundPayloadHash directly) for every nonce between the last delivered one and it; a nonce the endpoint says is verified with no log is a gap (cursor stays, bridge-index-gap). With one RPC, never call two reads of the same node "agreeing".

**Reproduction**

State: 4663 keeper on one log RPC; a forged packet (nonce 1000, 40,000 imdUSD) verified at 4663's EndpointV2 at T0+300 and NOT executed; the RPC answers [] for every getLogs on the endpoint address until T0+3600, then honestly; passes every 120 s for 4 h. Expected: critical bridge-verified-forged-4663-1000. Actual: no alert in 4 h; state/bridge-watch.json's home cursor is at 64341, past the PacketVerified's block 50300.
RUN (Node 20+, after npm ci): save the test below as test/zz-v.test.mjs, run `node --test test/zz-v.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-v.test.mjs -----
// P5/P4/C3: PacketVerified (and hold / void) logs are "proven" by two agreeing reads of the SAME node set. On a lone log RPC that answers
// [] for the endpoint's logs (empty answers, a lagging log door) both reads agree, the range is marked read, and a forged packet
// waiting at the endpoint is never flagged, not even after the RPC answers honestly again.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-verified-"));
const { runBridge } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { bridgeCtx, E18, forge, makeBridgeWorld, T0 } = await import("./lib/bridge-world.mjs");
async function run(hideUntil) {
  rmSync(process.env.STATE_DIR, { recursive: true, force: true });
  const w = makeBridgeWorld({ seed: 8, home: 4663 });
  forge(w, 4663, 1000, T0 + 300, E18.mul(40_000), { execute: false }); // verified at 4663's endpoint, NOT executed: it waits there
  const getLogs = w.home.provider.getLogs;
  // The lone 4663 log RPC answers [] for the EndpointV2's logs until `hideUntil` (every read, so two reads agree); bridge logs are honest.
  w.home.provider.getLogs = async (f) => { const logs = await getLogs(f); return w.t < hideUntil && String(f.address).toLowerCase() === w.home.endpoint.toLowerCase() ? [] : logs; };
  const raised = [];
  const ctx = bridgeCtx(w, raised);
  for (let t = T0 + 60; t <= T0 + 4 * 3600; t += 120) { if (w.t < t) w.t = t; await runBridge(ctx); }
  const s = readStateOr("bridge-watch.json", {});
  return { keys: [...new Set(raised.map((a) => `${a.level} ${a.key}`))], first: raised.find((a) => /verified-forged/.test(a.key)), cursor: s.home.next, block: w.home.headAt(T0 + 300) };
}
test("control: an honest log RPC: the forged packet waiting at the endpoint is flagged critical within minutes", async () => {
  const r = await run(0);
  assert.ok(r.first && r.first.level === "critical" && r.first.t - T0 < 900, JSON.stringify(r.keys));
});
test("a lone log RPC answering [] for the endpoint's logs for one hour: the waiting forged packet is still flagged", async () => {
  const r = await run(T0 + 3600);
  console.log(`alerts in 4 h: [${r.keys}]; the PacketVerified is in block ${r.block}, the cursor is at ${r.cursor} (the range was marked read)`);
  assert.ok(r.first, `the forged packet has waited at the endpoint for 4 h (3 of them with an honest RPC) and was never flagged: its range was marked read on two agreeing empty answers`);
});

----- OUTPUT on f30a9d0 -----
alerts in 4 h: []; the PacketVerified is in block 50300, the cursor is at 64341 (the range was marked read)
✔ control: an honest log RPC: the forged packet waiting at the endpoint is flagged critical within minutes (1038.6747ms)
✖ a lone log RPC answering [] for the endpoint's logs for one hour: the waiting forged packet is still flagged (832.490341ms)
ℹ tests 2
ℹ pass 1
ℹ fail 1

✖ failing tests:

test at test/zz-v.test.mjs:30:1
✖ a lone log RPC answering [] for the endpoint's logs for one hour: the waiting forged packet is still flagged (832.490341ms)
  AssertionError [ERR_ASSERTION]: the forged packet has waited at the endpoint for 4 h (3 of them with an honest RP

### 12. Medium: Paid-order lifecycle: a paid order whose admission does not fit its questions throws in awaitAdmission on every pass: it never becomes 'lost', raises nothing, and blocks its purpose's buying for good

`lib/orders.mjs:261`

```
    const children = kids.map((requestId, i) => ({ requestId, role: o.questions[i].role, leaf: o.questions[i].leaf, state: "waiting" }));
```

Specialist (economics) finding; reproduced. awaitAdmission maps the plane's admission onto the order's questions (line 261, `role: o.questions[i].role`). An admission that lists more requests than the order has questions (a hostile plane, a MITM, the ENS server record, or a plane that splits a question) makes that line throw a TypeError; advanceOrders catches it and only logs (lines 174-176). The throw is BEFORE the admission-timeout code (lines 280-284), so the order stays "paying" on every pass, for ever: it never becomes "lost", critical feeds-order-lost never fires, the hold on ALL buying never starts, and the chain is never asked about the permit. Meanwhile openOrders("fall") is non-empty, so the fall decisions answer "an order for these legs is still open": no fall is bought again for that purpose, across restarts, with no alert. The 0.5 IMD a question may have been taken.
EXPECTED (README "Paying for answers": a paid order not admitted within admissionTimeoutSeconds becomes lost, raises a critical and holds all buying; P1 "otherwise an alert fires first"): stage "lost" + critical. ACTUAL: stage "paying", alerts [], log "order k-1 paying: Cannot read properties of undefined (reading 'role')".
SOUNDNESS: this is a fifth paid-order-lifecycle defect of the wave-4 class. The one rule "an order ends only on chain proof" is sound only if no exception can keep a paid order out of the path that asks the chain.
REACHABLE WITH THE DEPLOY CONFIG: yes, by whoever answers as the plane (in the threat model).
SMALLEST FIX: treat an admission that does not fit the order as a paid refusal (if kids.length !== o.questions.length raise the critical and update(o, { stage: "refused-paid" })), and run the admission-timeout check before parsing (or in a finally) so no exception can keep a paid order out of "lost".

**Reproduction**

State: orders.json holds one order { stage: "paying", purpose: "fall", paidAt: 2 h ago, questions: [1 question] }; the plane's GET /requests/<id> answers { admission: { result: { requests: [{requestId:"a"},{requestId:"b"}] } } }. Call advanceOrders(ctx) five times. Expected: stage "lost", alert critical feeds-order-lost. Actual: stage "paying", no alert, fall buying blocked by the open order.
RUN (Node 20+, after npm ci): save the test below as test/zz-n.test.mjs, run `node --test test/zz-n.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-n.test.mjs -----
// Paid-order lifecycle: a paid order whose admission throws in awaitAdmission never becomes 'lost', raises nothing, and blocks its purpose's buying
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { advanceOrders, loadOrders, openOrders } = await import("../lib/orders.mjs");
const { writeState } = await import("../lib/state.mjs");
const example = (await import("../config.example.js")).default;
const E18 = BigNumber.from(10).pow(18);
test("a paid order whose admission cannot be used still becomes 'lost' (critical, all buying held) after admissionTimeoutSeconds", async () => {
  const raised = [], logs = [];
  writeState("orders.json", { list: [{ key: "k-1", stage: "paying", purpose: "fall", action: "oracle.request", planeOrder: "po-1", requestKey: "r-1", at: new Date(Date.now() - 3 * 3600_000).toISOString(), paidAt: new Date(Date.now() - 2 * 3600_000).toISOString(), amount: E18.div(2).toString(), permitNonce: "7", permitDeadline: 1, questions: [{ role: "price", leaf: "0x00000000000000000000000000000000000000aa" }] }] });
  const ctx = { execute: true, cfg: example, log: (s) => logs.push(s), signer: { address: "0x00000000000000000000000000000000000000bb" }, provider: {},
    alerts: { raise: async (level, key) => raised.push(`${level} ${key}`), settle: async () => {} },
    // The plane (hostile, a MITM, or just a newer plane) answers a ONE-question order with an admission naming TWO requests.
    planeClient: { order: async () => ({ status: 200, body: { status: "admitted", admission: { result: { requests: [{ requestId: "a" }, { requestId: "b" }] } } } }) } };
  for (let i = 0; i < 5; i++) await advanceOrders(ctx);
  const o = loadOrders()[0];
  assert.deepEqual({ stage: o.stage, alerts: raised, fallBuyingBlockedByOpenOrder: openOrders("fall").length > 0, log: logs.at(-1) }, { stage: "lost", alerts: ["critical feeds-order-lost"], fallBuyingBlockedByOpenOrder: true, log: logs.at(-1) });
});

----- OUTPUT on f30a9d0 -----
✖ a paid order whose admission cannot be used still becomes 'lost' (critical, all buying held) after admissionTimeoutSeconds (5.75197ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-n.test.mjs:13:1
✖ a paid order whose admission cannot be used still becomes 'lost' (critical, all buying held) after admissionTimeoutSeconds (5.75197ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
    {
  +   alerts: [],
  -   alerts: [
  -     'critical feeds-order-lost'
  -   ],
      fallBuyingBlockedByOpenOrder: true,
      log: "order   k-1 paying: Cannot read properties of undefined (reading 'role')",
  +   stage: 'paying'
  -   stage: 'lost'
    }
  
    code: 'ERR_ASSERTION',
    actual: { stage: 'paying', alerts: [], fallBuyingBlockedByOpenOrder: true, log: "order   k-1 paying: Cannot read properties of undefined (reading 'role')" },
    expected: { stage: 'lost', alerts: [ 'critical feeds-order-lost' ], fallBuyingBlockedByOpenOrder: true, log: "order   k-1 paying: Cannot read properties of undefined (reading 'role')" },
  }

### 13. Medium: P1/C4: a due send the guard skips (gas over the tier ceiling, ETH under the floor, an open send, STOP) raises no alert: bites, Liquidator.tick, stock ticks, sync and write-offs stop silently; on 4663

`lib/act.mjs:31`

```
  if (r.stuck) await ctx.alerts?.raise?.("critical", "send-stuck", `${r.stuck.why}: every send waits behind nonce ${r.stuck.nonce}`)?.catch(() => {});
  else if (r.hash) await ctx.alerts?.settle?.("send-stuck", new Set())?.catch(() => {});
```

Merged: the economics specialist's silent-skip finding and the math specialist's C4 ceiling finding (lib/chains.mjs:42 MAX_GAS_GWEI 1); both reproduced in one test. lib/tx.mjs send() returns { skipped } when gas is over the tier's ceiling / 1.125 (tx.mjs:238-240), when the key is under the tier's ETH floor (:242-244), when a send is open (:217) and under the kill switch (:209). act() only logs that result: the single alert it knows is send-stuck (lib/act.mjs:31-32), and the duty loops ignore what act() returns (lib/positions.mjs:68, 114-123: a skipped liquidate falls through to a bark that is skipped too; lib/stocks.mjs:77, 83, 95). So while gas is over the ceiling every bite, liquidation, Liquidator.tick, stock tick, MarketHoursFeed.sync and writeOff is skipped every pass and nothing is raised by those loops; the only signals are the Pulse's own pulse-silent / pulse-grace on 4663 and bridge-claim-late after an hour.
C4 ("the 1 / 0.1 gwei ceilings never block an urgent poke, tick or claim") is false by construction above 0.888888888 gwei (MAX_GAS_GWEI 1 / 1.125), 44x the base fee read on 11-15: the real send() on chainConfig(config.example.js, 4663) at eth_gasPrice 0.9 gwei returns skipped "gas 0.9 gwei above the urgent sending ceiling 0.888888888" for a Pulse poke that would cost about 4.5e-5 ETH. Whether 4663's base fee reaches that under congestion was not measured; the ceiling is a deliberate bound, the defect is that hitting it is silent. A gas spike is when positions go under water.
EXPECTED (P1: every duty within its bound "while its RPCs answer; otherwise an alert fires first"): an alert naming the skipped duty and the reason. ACTUAL: positions: 60 due sends (liquidate, bark) skipped in 30 passes, stocks: 30 due ticks skipped, alerts raised: none.
REACHABLE WITH THE DEPLOY CONFIG: yes whenever gas is above the configured ceiling, the key is under MIN_ETH (keeper-eth-low comes from the watch loop every 5 min), or an earlier send holds the queue.
SMALLEST FIX: in act(), when an urgent duty's result is skipped raise warn send-skipped-urgent with send()'s reason, critical once it has lasted a duty's bound (5 min), and settle it on the next send that lands. For C4, bound urgent 4663 sends by cost (gas x price budget) or raise MAX_GAS_GWEI for 4663; keep the per-nonce replacement bound.

**Reproduction**

State: (a) one unhealthy position with no mark (liquidate due); (b) a live stock auction last read 300 s ago (tick due). Every send returns what the real lib/tx.mjs send() returns on the shipped 4663 config at eth_gasPrice 0.9 gwei (computed in the test). 30 passes of runPositions / runStocks. Expected: at least one alert. Actual: none.
RUN (Node 20+, after npm ci): save the test below as test/zz-j1.test.mjs, run `node --test test/zz-j1.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-j1.test.mjs -----
// P1: a due liquidation or stock tick that the send guard skips (gas over the ceiling) raises no alert
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runPositions } = await import("../lib/positions.mjs");
const { runStocks } = await import("../lib/stocks.mjs");
const { send } = await import("../lib/tx.mjs");
const { chainConfig } = await import("../lib/chains.mjs");
const example = (await import("../config.example.js")).default;
const { makeWorld } = await import("./lib/rh-world.mjs");
test("a due liquidation or stock tick that the send guard skips raises an alert", async () => {
  // What lib/tx.mjs send() really returns on 4663's shipped config at eth_gasPrice 0.9 gwei (44x the 11-15 base fee), urgent tier:
  const signer = { address: "0x00000000000000000000000000000000000Ad004", provider: { getGasPrice: async () => utils.parseUnits("0.9", "gwei"), getBalance: async () => utils.parseEther("1") } };
  const skipped = await send(signer, "pulse poke (500s silent)", async () => {}, async () => { throw new Error("must not be sent"); }, chainConfig(example, 4663), { tier: "urgent" });
  console.log(`send() on 4663 at 0.9 gwei, urgent: ${JSON.stringify(skipped)}`);
  assert.ok(skipped.skipped, "setup: the urgent send is held by the ceiling");
  const silent = [];
  for (const duty of ["positions", "stocks"]) {
    process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-skip-"));
    const ETH = utils.id("ETH"), SPY = utils.id("SPY");
    const { w, ctx } = duty === "positions"
      ? makeWorld({ types: [{ id: ETH, name: "ETH" }], positions: [{ id: 1, ilk: ETH }] }) // unhealthy, no mark: liquidate is due
      : makeWorld({ types: [{ id: SPY, name: "STOCK-SPY", auction: true, stock: true }], positions: [{ id: 7, ilk: SPY }] });
    if (duty === "stocks") w.auctions.set("7", { startAt: w.now - 600, lastTick: w.now - 300, ran: 0 }); // a live auction last read 300 s ago
    const raised = [], asked = [];
    ctx.alerts = { raise: async (level, key) => raised.push(`${level} ${key}`), settle: async () => {} };
    ctx.actHook = async (label, c, fn) => { asked.push(fn.split("(")[0]); return skipped; }; // act() passes send()'s result on (lib/act.mjs:27-33)
    for (let pass = 0; pass < 30; pass++) { w.now += 60; await (duty === "positions" ? runPositions : runStocks)(ctx); }
    assert.ok(asked.length > 0, `setup: ${duty} wanted to send`);
    if (!raised.length) silent.push(`${duty}: ${asked.length} due sends (${[...new Set(asked)]}) skipped in 30 passes, alerts raised: none`);
  }
  assert.deepEqual(silent, []);
});

----- OUTPUT on f30a9d0 -----
send() on 4663 at 0.9 gwei, urgent: {"skipped":"gas 0.9 gwei above the urgent sending ceiling 0.888888888 (MAX_GAS_GWEI / 1.125)"}
✖ a due liquidation or stock tick that the send guard skips raises an alert (30.290274ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-j1.test.mjs:15:1
✖ a due liquidation or stock tick that the send guard skips raises an alert (30.290274ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'positions: 60 due sends (liquidate,bark) skipped in 30 pass

### 14. Medium: readSupply's terms are read at 'latest' with no blockTag: on a lone read RPC (4663's default) a mint, burn or borrow landing between the reads raises a false critical bridge-supply-*

`lib/bridge.mjs:475`

```
  const [totalSupply, reserveBacked, migrator, pegKeeper, received, sent] = await Promise.all([
    c(a.usd, SUPPLY_ABI).totalSupply(), ledger.reserveBacked(),
    a.migrator ? c(a.migrator, SUPPLY_ABI).outstanding() : zero, a.pegHook ? c(a.pegHook, PEG_HOOK_ABI).outstanding() : zero,
    bridge.received(), bridge.sent(),
  ]);
```

Specialist (math) finding; reproduced. supplyCheck is documented as "All terms read at one block of one chain" (line 260) and alerts critical past 1 imdUSD of drift (supplyToleranceWei 1e18). readSupply (lines 469-481) makes its calls in three sequential rounds (ilkCount; ilks(i) and ilkState; the six terms) with NO blockTag. With two or more read RPCs the AgreeingProvider pins eth_call to a common block (for 3 s at a time, lib/chain.mjs:33), but the 4663 default is ONE RPC (lib/chains.mjs:39, config.example.js:87) for which perform() is not pinned at all (lib/chain.mjs:56): every call goes at "latest", and 4663 produces about 4 blocks a second. Any Received/Claimed mint (received and totalSupply both move), Sent burn, borrow or repay (debt and totalSupply move) that lands between two of the reads leaves the equation off by that amount. The same holds for the peer side read through PEERS[4663] (one URL) by the mainnet keeper.
EXPECTED: diff 0 for an honest chain. ACTUAL: every eth_call carries blockTag "latest"; totalSupply reads 1000 and received reads 1050: critical bridge-supply-4663 "off by -50.0" to the Safe's signers. It clears itself next pass and returns at the next coincidence: with regular traffic a recurring false critical on the only detector's channel.
REACHABLE WITH THE DEPLOY CONFIG: yes (one 4663 RPC by default).
SMALLEST FIX: in readSupply read the head once and pass { blockTag } to every call (ilkCount, ilks, ilkState, totalSupply, reserveBacked, outstanding x2, received, sent), as countersAt already does for the bridge counters.

**Reproduction**

State: one read RPC; block 100 has totalSupply 1000 and bridge.received 1000; an honest 50 imdUSD Received lands in block 101 right after the first term is read. Expected: no alert (all terms at block 100, or all at 101, balance). Actual: blockTags used: latest; diff -50.0; critical bridge-supply-4663.
RUN (Node 20+, after npm ci): save the test below as test/zz-i.test.mjs, run `node --test test/zz-i.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-i.test.mjs -----
// readSupply says 'all terms read at one block' but passes no blockTag: on ONE read RPC a mint between two reads raises a false critical bridge-supply-*
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
import { Contract } from "ethers";
const { readSupply, supplyCheck } = await import("../lib/bridge.mjs");
const { BRIDGE_ABI } = await import("../lib/robinhood.mjs");
const sel = (sig) => utils.id(sig).slice(0, 10);
const E18 = BigNumber.from(10).pow(18);
const enc = (n) => utils.defaultAbiCoder.encode(["uint256"], [n]);
test("a mint between the reads of totalSupply and bridge.received() on a lone RPC raises no supply alert", async () => {
  const stateAt = (b) => (Number(b) >= 101 ? { supply: E18.mul(1050), received: E18.mul(1050) } : { supply: E18.mul(1000), received: E18.mul(1000) });
  let head = 100, calls = 0;
  const tags = [];
  const fake = { request: async ({ method, params }) => {
    if (method === "eth_chainId") return "0x1237";
    if (method === "eth_blockNumber") return utils.hexValue(head);
    if (method === "eth_call") {
      const [tx, tag] = params;
      tags.push(tag);
      const s = stateAt(tag === "latest" || tag === undefined ? head : Number(tag));
      const selector = tx.data.slice(0, 10);
      calls++;
      if (calls === 2) head = 101; // an honest 50 imdUSD Received lands right after the first term is read
      if (selector === sel("ilkCount()")) return enc(0);
      if (selector === sel("totalSupply()")) return enc(s.supply);
      if (selector === sel("reserveBacked()")) return enc(0);
      if (selector === sel("received()")) return enc(s.received);
      if (selector === sel("sent()")) return enc(0);
      throw new Error(`unexpected call ${selector}`);
    }
    throw new Error(`unexpected ${method}`);
  } };
  const provider = new providers.Web3Provider(fake, 4663);
  const bridge = new Contract("0x00000000000000000000000000000000000b4663", BRIDGE_ABI, provider);
  const a = { ledger: "0x00000000000000000000000000000000000ad001", params: "0x00000000000000000000000000000000000ad002", usd: "0x00000000000000000000000000000000000ad003", pegHook: null, migrator: null };
  const r = supplyCheck({ ...(await readSupply(provider, a, bridge)), toleranceWei: 10n ** 18n, name: "4663" });
  console.log(`blockTags used: ${[...new Set(tags)].join(",")}; diff ${utils.formatEther(r.diff)}`);
  assert.equal(r.alert, null, `false critical: ${r.alert?.msg}`);
});

----- OUTPUT on f30a9d0 -----
blockTags used: latest; diff -50.0
✖ a mint between the reads of totalSupply and bridge.received() on a lone RPC raises no supply alert (21.979604ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-i.test.mjs:15:1
✖ a mint between the reads of totalSupply and bridge.received() on a lone RPC raises no supply alert (21.979604ms)
  AssertionError [ERR_ASSERTION]: false critical: 4663: imdUSD totalSupply 1000.0 != debt + bad debt + reserveBacked + migrator + peg keeper + bridge received - sent (1050.0), off by -50.0
  + actual - expected
  
  + {
  +   key: 'bridge-supply-4663',
  +   level: 'critical',
  +   msg: '4663: imdUSD totalSupply 1000.0 != debt + bad debt + reserveBacked + migrator + peg keeper + bridge received -

### 15. Low: P4: runBridge clears standing bridge alerts whose condition was NOT read this pass: a failed claims() read clears the critical bridge-claim-mismatch (and bridge-claim-late / -refused)

`lib/bridge.mjs:752`

```
  await ctx.alerts.settle("bridge-", new Set([...raised.map((a) => a.key), ...unreadSupply]));
```

Specialist (economics) finding; its test was truncated, rewritten and run here. The bridge loop settles the whole "bridge-" prefix against the keys raised this pass; only the supply equation gets the unread treatment (unreadSupply). In autoClaim, when claims(srcEid, guid) throws it raises warn bridge-claim-unread-* and continues (lines 602-605), so the standing CRITICAL bridge-claim-mismatch-* for that claim (and bridge-claim-late-* / bridge-claim-refused-*) is not re-raised and the settle clears it. Likewise matchDirection line 182 (`if (dst.gapSince !== undefined) continue;`) drops every bridge-stuck-* the moment the destination's logs become unprovable (by design the gap alert speaks instead, but the stuck critical is still "cleared").
EXPECTED (P4; README "a read that fails keeps the standing alert (and raises an -unread one)"): the critical stands while its condition cannot be read. ACTUAL: "+913s critical bridge-claim-mismatch-4663-1", "+1034s warn bridge-claim-unread-4663-1", "+1034s cleared bridge-claim-mismatch-4663-1".
SOUNDNESS: the one rule "an alert clears only on a successful read" is not implemented as a rule in runBridge; it is implemented per alert (supply only). The stale-head gap finding is the same class.
REACHABLE WITH THE DEPLOY CONFIG: yes (any failed claims() read on the rate-limited RPC). Low: the mismatch state itself is rare and the warn says the read failed.
SMALLEST FIX: collect the keys whose condition could not be read this pass (per claim nonce when claims() fails; bridge-stuck-<src>-* while dst.gapSince is set) and add them to the held set passed to settle, as unreadSupply already does.

**Reproduction**

State: 4663 keeper, a matured honest Queued; at the +900 s pass claims() returns a record that is not the indexed Queued (critical bridge-claim-mismatch-4663-1 raised); from +1020 s claims() throws 429. Expected: the critical stays. Actual: cleared at +1034 s with only the warn bridge-claim-unread-4663-1 standing.
RUN (Node 20+, after npm ci): save the test below as test/zz-m.test.mjs, run `node --test test/zz-m.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-m.test.mjs -----
// P4: runBridge clears a standing bridge alert whose condition was NOT read this pass (a failed claims() read clears the critical bridge-claim-mismatch)
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, utils } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runBridge, judgeQueued } = await import("../lib/bridge.mjs");
const { readStateOr } = await import("../lib/state.mjs");
const { EID } = await import("../lib/robinhood.mjs");
const { BRIDGE_IFACE, bridgeCtx, E18, honest, makeBridgeWorld, guidOf, settleClaim, T0 } = await import("./lib/bridge-world.mjs");
const fresh = () => rmSync(process.env.STATE_DIR, { recursive: true, force: true });
const addr = (i) => utils.getAddress(utils.hexZeroPad(utils.hexlify(i), 20));
/** Alerts as lib/alerts.mjs keeps them: raise makes a key stand, settle clears every key of the prefix this pass did not raise. */
const recorder = (w) => {
  const standing = new Map(), log = [];
  return { standing, log,
    raise: async (level, key, msg) => { standing.set(key, level); log.push({ t: Math.round(w.t - T0), level, key, msg }); },
    settle: async (prefix, held) => { for (const k of [...standing.keys()]) if (k.startsWith(prefix) && !held.has(k)) { log.push({ t: Math.round(w.t - T0), level: "cleared", key: k, was: standing.get(k) }); standing.delete(k); } } };
};
/** The watcher every 120 s, as keeper.mjs runs it: a pass that throws is logged and the next one runs. */
async function passes(w, ctx, from, to, each = () => {}) {
  const errors = [];
  for (let p = from; p <= to; p += 120) { if (w.t < p) w.t = p; await each(p); try { await runBridge(ctx); } catch (e) { errors.push({ t: p - T0, e: e.message }); } }
  return errors;
}
test("a failed claims() read never clears the standing critical bridge-claim-mismatch", async () => {
  fresh();
  const w = makeBridgeWorld({ seed: 4, home: 4663, delay: 600 });
  honest(w, 1, 1, T0 + 100, 200, E18.mul(100), { queue: true }); // queued on 4663 at +300 s, matures at +900 s
  const realClaims = w.home.bridgeContract.claims;
  let mode = "ok";
  w.home.bridgeContract.claims = async (...x) => {
    if (mode === "fail") throw new Error("429 Too Many Requests");
    if (mode === "other") return { to: addr(0xbad), amountSD: BigNumber.from(1), queuedAt: 0, state: 1 }; // the chain's record is not the indexed Queued
    return realClaims(...x);
  };
  const a = recorder(w);
  await passes(w, bridgeCtx(w, [], { alerts: a }), T0 + 60, T0 + 1500, (p) => { mode = p >= T0 + 1020 ? "fail" : p >= T0 + 900 ? "other" : "ok"; });
  const KEY = "bridge-claim-mismatch-4663-1";
  const story = a.log.filter((x) => x.key === KEY || x.key.startsWith("bridge-claim-unread")).map((x) => `+${x.t}s ${x.level} ${x.key}`);
  console.log(story.join("\n"));
  assert.ok(story.some((s) => s.includes(`critical ${KEY}`)), "setup: the mismatch was raised critical");
  assert.deepEqual(a.log.filter((x) => x.level === "cleared" && x.key === KEY).map((x) => `cleared at +${x.t}s while claims() was unreadable`), []);
});

----- OUTPUT on f30a9d0 -----
+913s critical bridge-claim-mismatch-4663-1
+1034s warn bridge-claim-unread-4663-1
+1034s cleared bridge-claim-mismatch-4663-1
+1154s warn bridge-claim-unread-4663-1
+1272s warn bridge-claim-unread-4663-1
+1393s warn bridge

### 16. Low: P3: the 'mainnet key on 4663' check compares mnemonic STRINGS, not the keys they derive: the same phrase with another case or spacing is accepted, and nothing is compared when KEEPER_MNEMONIC is absen

`lib/tx.mjs:98`

```
  if (name !== "KEEPER_MNEMONIC" && env.KEEPER_MNEMONIC && env.KEEPER_MNEMONIC.trim() === env[name].trim()) {
    throw new Error(`${name} is the mainnet keeper's KEEPER_MNEMONIC: each chain runs on its own key`);
  }
```

Merged from two specialist reports (rated medium and low); reproduced. keeperSigner refuses KEEPER_MNEMONIC_4663 only when it is string-equal (after trim) to KEEPER_MNEMONIC. ethers' wordlist lower-cases the phrase and splits on runs of spaces before deriving, so the same phrase typed with a double space, in upper case or with a capital first letter derives the SAME key and passes. The guard also does nothing when the 4663 process's environment does not carry KEEPER_MNEMONIC (`env.KEEPER_MNEMONIC &&`), the usual layout of one unit file per process. What is left is takeKeyLock (lib/state.mjs:56-58): by address, but it refuses only while the other process is ALIVE on the same machine under the same HOME (keyLockDir() is join(homedir(), ...), line 48), and foreignPending sees nothing on 4663 (no public mempool).
STATE: one key, two state dirs: two imd-spend.json ledgers (IMD.dailyCap 5 counted once per chain, so 10 IMD a day can leave one key against one Permit2 allowance: P2 "never more IMD than the cap"), two order latches, two journals; lib/tx.mjs:91-92 states the consequence itself.
EXPECTED (P3 "the 4663 key is never the mainnet key"): refused. ACTUAL: accepted for all three variants, address 0xf39F...2266 (the mainnet key); only the byte-identical string is refused.
REACHABLE WITH THE DEPLOY CONFIG: only by operator error (the threat model gives the operator the config and two processes; the check exists for exactly this mistake). Low.
SMALLEST FIX: compare addresses (Wallet.fromMnemonic(env.KEEPER_MNEMONIC).address === wallet.address), and bind each key to a chain durably in the key-lock directory (an <address>.chain file written at first --execute; refuse when it names another chain) so the refusal does not depend on the other process being alive or on its environment.

**Reproduction**

State: chainConfig(config.example.js, 4663); env { KEEPER_MNEMONIC: M, KEEPER_MNEMONIC_4663: M typed with two spaces / in upper case / with a capital first letter }, M = the standard test phrase. Expected: keeperSigner throws "each chain runs on its own key" (it does for the identical string: the control). Actual: a signer for the mainnet keeper's address in all three cases.
RUN (Node 20+, after npm ci): save the test below as test/zz-h.test.mjs, run `node --test test/zz-h.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-h.test.mjs -----
// P3: the 4663 key is never the mainnet key: lib/tx.mjs:98 compares mnemonic STRINGS, not the keys they derive
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { keeperSigner } = await import("../lib/tx.mjs");
const { chainConfig } = await import("../lib/chains.mjs");
const file = (await import("../config.example.js")).default;
const M = "test test test test test test test test test test test junk";
test("the 4663 keeper refuses the mainnet keeper's key however the mnemonic is typed", () => {
  const cfg = chainConfig(file, 4663);
  const provider = new providers.StaticJsonRpcProvider("http://rpc.invalid", 4663);
  const mainnetKey = Wallet.fromMnemonic(M).address;
  assert.throws(() => keeperSigner(provider, cfg, { KEEPER_MNEMONIC: M, KEEPER_MNEMONIC_4663: M }), /each chain runs on its own key/); // control
  const accepted = [];
  for (const [how, variant] of [["two spaces between two words", M.replace(" ", "  ")], ["upper case", M.toUpperCase()], ["capitalised first word", `T${M.slice(1)}`]]) {
    let signer = null;
    try { signer = keeperSigner(provider, cfg, { KEEPER_MNEMONIC: M, KEEPER_MNEMONIC_4663: variant }); } catch { /* refused: good */ }
    if (signer?.address === mainnetKey) accepted.push(how);
  }
  assert.deepEqual(accepted, [], `the 4663 process signs with the MAINNET keeper's key ${mainnetKey} when KEEPER_MNEMONIC_4663 is the same phrase typed with: ${accepted.join("; ")}`);
});

----- OUTPUT on f30a9d0 -----
✖ the 4663 keeper refuses the mainnet keeper's key however the mnemonic is typed (184.32277ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-h.test.mjs:13:1
✖ the 4663 keeper refuses the mainnet keeper's key however the mnemonic is typed (184.32277ms)
  AssertionError [ERR_ASSERTION]: the 4663 process signs with the MAINNET keeper's key 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 when KEEPER_MNEMONIC_4663 is the same phrase typed with: two spaces between two words; upper case; capitalised first word
  + actual - expected
  
  + [
  +   'two spaces between two words',
  +   'upper case',
  +   'capitalised first word'
  + ]
  - []
  
    code: 'ERR_ASSERTION',
    actual: [ 'two spaces between two words', 'upper case', 'capitalised first word' ],
    expected: [],
  }

### 17. Low: P8/C4: a matured honest claim is sent on the ROUTINE tier for its first hour, so gas over the routine ceiling (mainnet 13.33 gwei, 4663 0.0889 gwei), any open send or ETH under the routine floor holds

`lib/bridge.mjs:617`

```
    const r = await act(ctx, label, bridge, "claim", [srcEid, q.guid], { tier: late > urgentAfter ? "urgent" : "routine" });
```

Merged from two specialist reports; reproduced with the real autoClaim and the real lib/tx.mjs send() on config.example.js for both chains. The claim is sent at tier "routine" until it is claimUrgentSeconds (1 h) late (line 617). send() refuses the routine tier above ROUTINE_MAX_GAS_GWEI / 1.125 (13.33 gwei on mainnet; 0.0889 gwei on 4663, 4.4x the base fee read on 11-15), under ROUTINE_MIN_ETH, and behind ANY open send with no time limit (tx.mjs:216). The only alert for an unclaimed matured transfer is gated on the same hour (line 623 `if (late > urgentAfter && ctx.execute && !r?.pending)`), so for up to 60 min the user's funds wait with no send and no alert.
EXPECTED (P8 "claimed in the first pass after it matures"; C4 "the 1 / 0.1 gwei ceilings never block ... a claim"): sent, or an alert naming why not. ACTUAL: 0 claims sent, 0 alerts on both chains ("gas 14.0 gwei above the routine sending ceiling 13.333333333"; "gas 0.09 gwei above the routine sending ceiling 0.088888888"). After an hour the tier turns urgent and it goes: late, not lost.
REACHABLE WITH THE DEPLOY CONFIG: yes (example ceilings).
SMALLEST FIX: send claims on the urgent tier from maturity (one transaction; the user has already waited 12 h), or keep routine and raise a warn the first pass a matured claim is skipped, with send()'s reason.

**Reproduction**

State: one honest queued claim (exact Sent match) matured 30 min ago, path open, keeper balance 1 ETH, no open sends; mainnet at eth_gasPrice 14 gwei, 4663 at 0.09 gwei. Expected: one claim sent or an alert. Actual: send() skips it on the routine ceiling and autoClaim returns no alert.
RUN (Node 20+, after npm ci): save the test below as test/zz-j2.test.mjs, run `node --test test/zz-j2.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-j2.test.mjs -----
// P8/C4: a matured honest claim goes on the ROUTINE tier for its first hour; over the routine ceiling it is neither sent nor alerted
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { autoClaim } = await import("../lib/bridge.mjs");
const { send } = await import("../lib/tx.mjs");
const { chainConfig } = await import("../lib/chains.mjs");
const file = (await import("../config.example.js")).default;
const NOW = 1_800_100_000, DELAY = 43_200;
const to = `0x${"11".repeat(20)}`;
const amount = BigNumber.from(10).pow(18).mul(9000).toString();
for (const [chain, gas, srcEid, dstEid] of [[1, "14", 30416, 30101], [4663, "0.09", 30101, 30416]]) {
  test(`chain ${chain}: an honest claim matured 30 min ago at ${gas} gwei is sent, or the keeper says why not`, async () => {
    const cfg = chainConfig(file, chain);
    const guid = `0x${"12".repeat(32)}`, queuedAt = NOW - DELAY - 1800;
    const bridge = { address: "0x00000000000000000000000000000000000B0001", breakers: async () => ({ delay: DELAY, cancelledFrom: 0, tripped: false }), paused: async () => false,
      claims: async () => ({ to, amountSD: BigNumber.from(amount).div(1e12), queuedAt, state: 1 }) };
    const side = { queue: { [`${srcEid}:5`]: { guid, to, amount, queuedAt, claimableAt: queuedAt + DELAY, state: "pending" } } };
    const src = { throughBlock: 100, sent: { [`${dstEid}:5`]: { guid, to: utils.hexZeroPad(to, 32), amount } } }; // the exact Sent: honest
    const sent = [];
    const signer = { address: `0x${"77".repeat(20)}`, provider: { getGasPrice: async () => utils.parseUnits(gas, "gwei"), getBalance: async () => utils.parseEther("1") } };
    const ctx = { execute: true, cfg, log: () => {}, book: { bridge }, settleSends: async () => {},
      provider: { getBlock: async () => ({ timestamp: NOW }), getTransactionReceipt: async () => null },
      actHook: async (label, c, fn, args, opts) => { // the REAL lib/tx.mjs send() with the example config's ceilings
        const r = await send(signer, label, async () => {}, async () => { sent.push(label); return { hash: "0x01", wait: async () => ({ blockNumber: 1, gasUsed: BigNumber.from(1) }) }; }, cfg, opts);
        console.log(`chain ${chain} send() tier ${opts.tier}: ${JSON.stringify(r)}`);
        return r;
      } };
    const out = await autoClaim(ctx, { side, src, srcEid, dstEid, name: String(chain), W: cfg.BRIDGE_WATCH });
    assert.ok(sent.length === 1 || out.length > 0, `matured 30 min ago: ${sent.length} claim sent and ${out.length} alert raised`);
  });
}

----- OUTPUT on f30a9d0 -----
chain 1 send() tier routine: {"skipped":"gas 14.0 gwei above the routine sending ceiling 13.333333333 (ROUTINE_MAX_GAS_GWEI / 1.125)"}
chain 4663 send() tier routine: {"skipped":"gas 0.09 gwei above the routine sending ceiling 0.088888888 (ROUTINE_MAX_GAS_GWEI / 1.125)"}
✖ chain 1: an honest claim matured 30 min ago at 14 gwei is sent, or the keeper says why not (3.898794ms)
✖ chain 4663: an honest claim matured 30 min ago at 0.09 gwei is sent, or the keeper says why not (1.214142ms)
ℹ tests 2
ℹ pass 0
ℹ fail 2

✖ failing tests:

test at test/zz-j2.test.mjs:17:3
✖ chain 1: an honest claim matured 30 min ago at 14 gwei is sent, or the keeper says why n

### 18. Low: P1/C5: tickAfterSeconds 240 plus a 60 s loop scheduled after the pass returns leaves no margin inside TICK_SPAN: a live stock auction's read is decided 301 s or more after the last one

`lib/stocks.mjs:35`

```
  return { live, lapsed: !live, tick: live && now - Number(a.lastTick) >= tickAfter };
```

Merged from two specialist reports; reproduced. auctionStep ticks once the last read is tickAfter (240 s) old; a pass that finds it 239 s old does nothing, and the next stocks pass is not 60 s later but 60 s after the previous pass RETURNED plus every other loop that runs in between (keeper.mjs:180 sets next after the await; the loops are serial), plus the time to sign, simulate and mine. The opening bite, a taker's tick or a griefer's tick puts lastTick at any phase of the keeper's minute, so the worst case is always reachable. test/rh-duties.test.mjs passes because it steps the loop every 30-60 s, a period the scheduler cannot produce. StockJoin counts at most TICK_SPAN per read, so each second over 300 is auction descent never counted (the price falls late); nothing is seized wrongly and no alert says a tick was late.
EXPECTED (P1 "a live stock auction read at least every TICK_SPAN (5 min)"): <= 300 s. ACTUAL: decided 301 s after the last read with 2 s of other work in the round, 329 s with 30 s, 359 s with one 60 s send wait (SEND_WAIT_SECONDS on 4663), before it is mined.
REACHABLE WITH THE DEPLOY CONFIG: yes (STOCKS.tickAfterSeconds 240, stocksSeconds 60).
SMALLEST FIX: leave real headroom: tick when now - lastTick + stocksSeconds + the round's measured duration >= TICK_SPAN (e.g. tickAfterSeconds 150-180), schedule from the pass's START, and warn stocks-tick-late-* when now - lastTick > TICK_SPAN at a tick.

**Reproduction**

State: auction lastTick = 1000; a stocks pass at now = 1239 (no tick); the next at 1239 + 60 + round. Expected: tick decided <= 300 s after the last read. Actual: 301 s for round = 2 s, 329 s for 30 s, 359 s for 60 s.
RUN (Node 20+, after npm ci): save the test below as test/zz-k.test.mjs, run `node --test test/zz-k.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-k.test.mjs -----
// P1: tickAfterSeconds 240 + a 60 s loop scheduled after the pass returns leaves no margin inside TICK_SPAN (300 s)
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { ROBINHOOD_LOOPS } = await import("../keeper.mjs");
const { chainConfig } = await import("../lib/chains.mjs");
const { auctionStep } = await import("../lib/stocks.mjs");
const example = (await import("../config.example.js")).default;
test("a live stock auction is read within TICK_SPAN (300 s) at the shipped cadence", () => {
  const cfg = chainConfig(example, 4663);
  const every = ROBINHOOD_LOOPS.find((l) => l.name === "stocks").every(cfg), tickAfter = cfg.STOCKS.tickAfterSeconds;
  assert.deepEqual([every, tickAfter], [60, 240]);
  const a = { startAt: 1000, lastTick: 1000 }; // the opening bite, or anyone's tick, lands at any phase of the keeper's minute
  const p1 = 1000 + tickAfter - 1; // a pass 239 s after the last read
  assert.equal(auctionStep({ a, now: p1, auctionTime: 3600, tickAfter }).tick, false, "not ticked at 239 s");
  // keeper.mjs:180 schedules the next pass `every` seconds AFTER the pass returns, and every other loop runs in between (serial).
  const late = [];
  for (const round of [2, 30, 60]) {
    const p2 = p1 + every + round;
    assert.equal(auctionStep({ a, now: p2, auctionTime: 3600, tickAfter }).tick, true);
    if (p2 - a.lastTick > 300) late.push(`${round} s of other work -> tick DECIDED ${p2 - a.lastTick} s after the last read`);
  }
  assert.deepEqual(late, [], "TICK_SPAN is 300 s, and the tick is not yet mined when it is decided");
});

----- OUTPUT on f30a9d0 -----
✖ a live stock auction is read within TICK_SPAN (300 s) at the shipped cadence (2.176104ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-k.test.mjs:13:1
✖ a live stock auction is read within TICK_SPAN (300 s) at the shipped cadence (2.176104ms)
  AssertionError [ERR_ASSERTION]: TICK_SPAN is 300 s, and the tick is not yet mined when it is decided
  + actual - expected
  
  + [
  +   '2 s of other work -> tick DECIDED 301 s after the last read',
  +   '30 s of other work -> tick DECIDED 329 s after the last read',
  +   '60 s of other work -> tick DECIDED 359 s after the last read'
  + ]
  - []
  
    code: 'ERR_ASSERTION',
    actual: [ '2 s of other work -> tick DECIDED 301 s after the last read', '30 s of other work -> tick DECIDED 329 s after the last read', '60 s of other work -> tick DECIDED 359 s after the last read' ],
    expected: [],
  }

### 19. Low: P6: Pulse.inGrace() is read once per pass; when the grace opens during the pass a close that simulates 'seized 0' is sent with minSeized 0 and counted as landed

`lib/positions.mjs:113`

```
      const q = await liq.callStatic[fn](id, 0, keeperAddress ? { from: keeperAddress } : {});
      const r = await act(ctx, `${plan.fn} ${short} (seize ${q.seized})`, liq, fn, [id, minSeized(q.seized, tolerance)], { tier: "urgent" });
```

Specialist (economics) finding; reproduced. runPositions reads book.pulse.inGrace() once, before the loop over types and positions (line 62), and closeOne trusts that flag for every later position. The only other protection, minSeized, is derived from the simulation itself: when the simulation already runs inside the grace it returns seized 0 (the file's own header says a simulated bite then "succeeds" seizing 0), minSeized(0) is 0, the transaction is sent and returned as landed (line 115), so no mark is placed in that pass either. The grace opens mid-pass whenever the first transaction of the pass (the keeper's own tick, bark or bite, or anyone's Ledger call) lands past the 900 s gap: every Ledger accrual, mark and bite pokes (lib/pulse.mjs:6). That is reached exactly when the poke was late (the slow-loop and skipped-send findings).
EXPECTED (P6 "A Pulse grace never makes the keeper treat a position as closed (a bite seizing 0 in the grace)"): no close with seized 0; the position is marked instead. ACTUAL: "SENT liquidate ETH #2 (seize 0) with minSeized 0". Cost: gas for a transaction that seizes nothing and one pass without the mark; the next pass (inGrace true) marks, and the close is sent after the grace ends, so the second half of P6 holds.
REACHABLE WITH THE DEPLOY CONFIG: yes, in the pass that straddles the gap.
SMALLEST FIX: in closeOne, when q.seized is zero do not send: treat it as held (mark if there is no live mark), and re-read inGrace() there.

**Reproduction**

State: two unhealthy positions, no marks, lull 0; inGrace() false at the start of the pass; the first transaction of the pass opens the grace, after which callStatic liquidate/bite returns seized 0. Expected: no liquidate/bite with minSeized 0. Actual: liquidate #2 sent with minSeized 0.
RUN (Node 20+, after npm ci): save the test below as test/zz-o.test.mjs, run `node --test test/zz-o.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-o.test.mjs -----
// P6: Pulse.inGrace() is read once per pass; when the grace opens during the pass a close that simulates 'seized 0' is sent with minSeized 0
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { runPositions } = await import("../lib/positions.mjs");
const { makeWorld } = await import("./lib/rh-world.mjs");
const E18 = BigNumber.from(10).pow(18);
test("no bite or liquidation that seizes 0 is sent when the Pulse grace opens during the pass", async () => {
  const ETH = utils.id("ETH");
  const { w, ctx, book } = makeWorld({ types: [{ id: ETH, name: "ETH" }], positions: [{ id: 1, ilk: ETH }, { id: 2, ilk: ETH }] });
  // inGrace() is false when the pass starts (lib/positions.mjs:62 reads it ONCE). The first transaction lands past the 900 s gap and its own
  // poke opens the grace; from then on the simulated close "succeeds" seizing 0 (lib/positions.mjs:10-11).
  const sim = async () => ({ seized: w.grace ? BigNumber.from(0) : E18 });
  book.liquidator.callStatic = { "liquidate(uint256,uint256)": sim, "bite(uint256,uint256)": sim };
  const hook = ctx.actHook;
  ctx.actHook = async (...a) => { const r = await hook(...a); w.grace = true; return r; };
  await runPositions(ctx);
  assert.deepEqual(w.acts.filter((a) => /^(bite|liquidate)/.test(a.fn) && a.args[1] === "0").map((a) => `SENT ${a.label} with minSeized ${a.args[1]}`), []);
});

----- OUTPUT on f30a9d0 -----
✖ no bite or liquidation that seizes 0 is sent when the Pulse grace opens during the pass (9.936052ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-o.test.mjs:12:1
✖ no bite or liquidation that seizes 0 is sent when the Pulse grace opens during the pass (9.936052ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
  + [
  +   'SENT liquidate ETH #2 (seize 0) with minSeized 0'
  + ]
  - []
  
    code: 'ERR_ASSERTION',
    actual: [ 'SENT liquidate ETH #2 (seize 0) with minSeized 0' ],
    expected: [],
  }

### 20. Low: C6: bridge-watch-off looks only at BRIDGE_WATCH.enabled on mainnet; the watcher or auto-claim switched off another way (BRIDGE_ENABLED false, --only, autoClaim false; any way on 4663) raises nothing a

`lib/bridge.mjs:636`

```
  if (!b || /^0x0{40}$/i.test(b) || cfg.BRIDGE_WATCH?.enabled) return null;
```

Specialist (economics) finding; reproduced. C6's first half holds: loopsFor() adds the bridge loop on mainnet when BRIDGE_WATCH.enabled (true in config.example.js) and the repo's own test covers the startup alert for enabled: false. But runRound skips any loop whose <NAME>_ENABLED is false (keeper.mjs:83) and the daemon honours --only (keeper.mjs:178), while bridgeWatchOff returns null for every chain but mainnet (line 634) and, on mainnet, whenever BRIDGE_WATCH.enabled is true (line 636). So a record that names a bridge with BRIDGE_ENABLED: false, with --only not listing bridge, or with BRIDGE_WATCH.autoClaim: false (line 526) runs with no watcher or no auto-claim and no startup alert, on either chain: transfers queued there are never claimed and no forged Queued is watched. (With the example's enabled: true and peer.bridge left null the loop throws every pass instead: loop-failing-bridge after 5 passes, about 10 minutes, not at startup.)
EXPECTED (C6 "a mainnet bridge with the watcher off alerts critical at startup"): critical bridge-watch-off. ACTUAL: null for the three configurations in the test.
REACHABLE WITH THE DEPLOY CONFIG: by operator configuration only (the threat model gives the operator the config). Low.
SMALLEST FIX: decide from what will actually run: in makeContext raise bridge-watch-off when the record names a bridge and the bridge loop is not among the loops that will run after _ENABLED and --only, or autoClaim is false, on both chains.

**Reproduction**

State: record.bridge set; cfg = config.example.js with BRIDGE_ENABLED: false (mainnet and 4663), or BRIDGE_WATCH.autoClaim: false. Expected: bridgeWatchOff(cfg, record) returns the message raised critical at startup. Actual: null in all three; runRound does not run the bridge loop.
RUN (Node 20+, after npm ci): save the test below as test/zz-p.test.mjs, run `node --test test/zz-p.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-p.test.mjs -----
// C6: a deployment with a bridge and NO running watcher or auto-claim says so at startup
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { bridgeWatchOff } = await import("../lib/bridge.mjs");
const { loopsFor, runRound } = await import("../keeper.mjs");
const { chainConfig } = await import("../lib/chains.mjs");
const example = (await import("../config.example.js")).default;
test("bridge-watch-off covers the generic loop switch and autoClaim off", async () => {
  const record = { bridge: "0x00000000000000000000000000000000000B0001" };
  const off = { ...example, BRIDGE_ENABLED: false }; // keeper.mjs:83: the per-loop switch every loop has
  const ran = [];
  const ctx = { cfg: off, provider: {}, log: () => {}, alerts: { raise: async () => {}, settle: async () => {} }, loops: loopsFor(off).map((l) => ({ ...l, run: async () => ran.push(l.name) })) };
  await runRound(ctx);
  assert.equal(ran.includes("bridge"), false, "setup: the bridge loop does not run");
  const silent = [];
  if (!bridgeWatchOff(off, record)) silent.push("mainnet: BRIDGE_ENABLED false (BRIDGE_WATCH.enabled true)");
  if (!bridgeWatchOff({ ...chainConfig(example, 4663), BRIDGE_ENABLED: false }, record)) silent.push("4663: BRIDGE_ENABLED false");
  if (!bridgeWatchOff({ ...example, BRIDGE_WATCH: { ...example.BRIDGE_WATCH, autoClaim: false } }, record)) silent.push("mainnet: BRIDGE_WATCH.autoClaim false (queued transfers never claimed)");
  assert.deepEqual(silent, [], "no bridge-watch-off at startup for");
});

----- OUTPUT on f30a9d0 -----
✖ bridge-watch-off covers the generic loop switch and autoClaim off (4.75194ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-p.test.mjs:13:1
✖ bridge-watch-off covers the generic loop switch and autoClaim off (4.75194ms)
  AssertionError [ERR_ASSERTION]: no bridge-watch-off at startup for
  + actual - expected
  
  + [
  +   'mainnet: BRIDGE_ENABLED false (BRIDGE_WATCH.enabled true)',
  +   '4663: BRIDGE_ENABLED false',
  +   'mainnet: BRIDGE_WATCH.autoClaim false (queued transfers never claimed)'
  + ]
  - []
  
    code: 'ERR_ASSERTION',
    actual: [ 'mainnet: BRIDGE_ENABLED false (BRIDGE_WATCH.enabled true)', '4663: BRIDGE_ENABLED false', 'mainnet: BRIDGE_WATCH.autoClaim false (queued transfers never claimed)' ],
    expected: [],
  }

### 21. Low: P1/P5: an alert is recorded as fired before Telegram is tried and a failed or refused delivery is swallowed: the Safe's signers hear nothing for the repeat interval (1 h for a critical)

`lib/alerts.mjs:42`

```
      s[key] = { at: now, level };
      writeState("alerts.json", s);
      await emit(level, key, msg);
```

Specialist (economics) finding; reproduced. raise() writes { at: now, level } for the key and only then calls emit(); telegram() catches every error (line 25 `catch { /* the log and the file still hold it */ }`) and never looks at the HTTP status, so a timeout (8 s), a network error or a 429/5xx from api.telegram.org leaves the key marked as fired. shouldFire then holds it back for REPEAT[level]: a critical bridge-queued-forged-* or bridge-verified-forged-* whose first delivery fails reaches nobody for an hour (a warn for 6 h), out of a 12 h window, and for a verified packet that can execute, out of a window that may be minutes. The README lists "Telegram delivery is not tested"; this is worse than untested: a failed delivery is treated as a delivery, and Telegram is the only channel (paging is not built).
EXPECTED: a delivery that failed is retried on the next pass. ACTUAL: Telegram tried at minute 0 only during the first hour.
REACHABLE WITH THE DEPLOY CONFIG: yes (any Telegram or network failure at the moment an alert first fires).
SMALLEST FIX: make telegram() return whether the message was accepted (response.ok) and, when it was not, store delivered: false for the key so shouldFire returns true until it is delivered.

**Reproduction**

State: TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID set; the first fetch to api.telegram.org throws ETIMEDOUT, later ones succeed. raise("critical", "bridge-queued-forged-mainnet-7", ...) every 2 minutes for an hour. Expected: fetch at minutes [0, 2]. Actual: [0].
RUN (Node 20+, after npm ci): save the test below as test/zz-q.test.mjs, run `node --test test/zz-q.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-q.test.mjs -----
// P1/P5: an alert is recorded as fired before Telegram is tried, and a failed delivery is swallowed for the repeat interval
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { makeAlerts } = await import("../lib/alerts.mjs");
test("a critical alert whose Telegram delivery failed is sent again at the next pass, not an hour later", async (t) => {
  t.mock.timers.enable({ apis: ["Date"], now: 1_800_000_000_000 });
  process.env.TELEGRAM_BOT_TOKEN = "x"; process.env.TELEGRAM_CHAT_ID = "1";
  const calls = [];
  const realFetch = globalThis.fetch;
  globalThis.fetch = async () => { calls.push((Date.now() - 1_800_000_000_000) / 60_000); if (calls.length === 1) throw new Error("ETIMEDOUT"); return { ok: true }; };
  try {
    const alerts = makeAlerts(() => {});
    for (let min = 0; min <= 58; min += 2) { // the watcher's passes for an hour, the forgery standing
      t.mock.timers.setTime(1_800_000_000_000 + min * 60_000);
      await alerts.raise("critical", "bridge-queued-forged-mainnet-7", "QUEUED a FORGED claim ... NOT MINTED YET");
    }
  } finally { globalThis.fetch = realFetch; delete process.env.TELEGRAM_BOT_TOKEN; delete process.env.TELEGRAM_CHAT_ID; }
  assert.deepEqual(calls, [0, 2], `Telegram was tried at minutes [${calls}] of the first hour; the first try failed (the only channel to the Safe's signers)`);
});

----- OUTPUT on f30a9d0 -----
✖ a critical alert whose Telegram delivery failed is sent again at the next pass, not an hour later (5.815193ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-q.test.mjs:10:1
✖ a critical alert whose Telegram delivery failed is sent again at the next pass, not an hour later (5.815193ms)
  AssertionError [ERR_ASSERTION]: Telegram was tried at minutes [0] of the first hour; the first try failed (the only channel to the Safe's signers)
  + actual - expected
  
    [
      0,
  -   2
    ]
  
    code: 'ERR_ASSERTION',
    actual: [ 0 ],
    expected: [ 0, 2 ],
  }

### 22. Low: P8: a claim the keeper's own journal records as mined is sent again when the read node lags (the journal's 'mined' record is never read)

`lib/bridge.mjs:592`

```
    for (const h of journal.signed.get(label) ?? []) {
      const rc = await ctx.provider.getTransactionReceipt(h).catch(() => null);
      if (rc && rc.status === 1) mined = h;
    }
```

Specialist (permissions) finding; reproduced. "One the journal shows mined: done" (header line 52, comment line 589) is not what the code does. claimJournal (lines 488-506) keeps only the "signed" lines; whether a signed claim mined is then asked of the read node again (lines 592-595). lib/tx.mjs already wrote the answer to the same file when the receipt came back (clearIntent(nonce, "mined", ...), tx.mjs:195), and that record is ignored. Receipts, claims() and the simulation all come from the node, so a node behind the claim's block (a load-balanced backend; the brief's "lagging node") shows no receipt, state 1 (pending) and a passing simulation.
CALL SEQUENCE: pass 1: claim sent at nonce 7, mined, receipt seen, journal: signed + mined. Pass 2 (120 s later) is served by a node behind that block: journal.open is empty; getTransactionReceipt(hash) = null; claims() = pending, matured; act(... "claim") is called again. On chain the second transaction reverts (already claimed), or the wait throws, which throws out of runBridge and loses that pass's alerts (the alerts-dropped finding).
EXPECTED (P8 "no claim is sent twice (... a lagging node)"): no second send. ACTUAL: claim(30416, 0xabab...) sent again. No double mint is possible (the bridge's own state stops it); the cost is gas and a failed bridge pass.
REACHABLE WITH THE DEPLOY CONFIG: yes on 4663 (one public RPC); it needs a backend more than one pass behind.
SMALLEST FIX: in claimJournal also collect the hashes of "mined" steps (same scope) and skip a label any of whose signed hashes the journal shows mined, before asking the node; un-skip only when a later proven log shows ClaimRestored.

**Reproduction**

State: the real autoClaim; state/journal.jsonl holds what lib/tx.mjs writes for a claim that mined ("signed" then "mined", same hash, label "bridge claim 30416:0xabab..."); the read node lags: getTransactionReceipt -> null, claims() -> state 1, matured 5 min ago; path open; exact Sent match. Expected: no act. Actual: claim sent again.
RUN (Node 20+, after npm ci): save the test below as test/zz-t.test.mjs, run `node --test test/zz-t.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-t.test.mjs -----
// P8: a claim the keeper's own journal records as MINED is sent again when the read node lags
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { autoClaim, claimLabel } = await import("../lib/bridge.mjs");
const { logStep } = await import("../lib/journal.mjs");
const NOW = 1_800_100_000, DELAY = 43_200;
const to = `0x${"11".repeat(20)}`;
const amount = BigNumber.from(10).pow(18).mul(9000).toString();
test("a claim the keeper's journal shows MINED is not sent again when the read node lags behind it", async () => {
  const guid = `0x${"ab".repeat(32)}`, hash = `0x${"cd".repeat(32)}`, queuedAt = NOW - DELAY - 300;
  const bridge = { address: "0x00000000000000000000000000000000000B0001", breakers: async () => ({ delay: DELAY, cancelledFrom: 0, tripped: false }), paused: async () => false,
    claims: async () => ({ to, amountSD: BigNumber.from(amount).div(1e12), queuedAt, state: 1 }) }; // the lagging node: still pending
  const side = { queue: { "30416:5": { guid, to, amount, queuedAt, claimableAt: queuedAt + DELAY, state: "pending" } } };
  const src = { throughBlock: 100, sent: { "30101:5": { guid, to: utils.hexZeroPad(to, 32), amount } } };
  // What lib/tx.mjs wrote when the first claim went out and its receipt came back (recordIntent, then clearIntent(..., "mined")).
  logStep("signed", { nonce: 7, hash, label: claimLabel(30416, guid), scope: "tx" });
  logStep("mined", { nonce: 7, scope: "tx", hash, block: 21_000_000 });
  const acts = [];
  const ctx = { execute: true, cfg: {}, log: () => {}, book: { bridge }, settleSends: async () => {},
    provider: { getBlock: async () => ({ timestamp: NOW }), getTransactionReceipt: async () => null }, // a node behind that block: no receipt
    actHook: async (label, c, fn, args) => { acts.push(`${fn}(${args.join(", ")})`); return { hash: `0x${"ef".repeat(32)}` }; } };
  await autoClaim(ctx, { side, src, srcEid: 30416, dstEid: 30101, name: "mainnet", W: {} });
  assert.deepEqual(acts, [], "a second claim transaction was sent for a claim the journal had already recorded as mined");
});

----- OUTPUT on f30a9d0 -----
✖ a claim the keeper's journal shows MINED is not sent again when the read node lags behind it (3.489865ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-t.test.mjs:14:1
✖ a claim the keeper's journal shows MINED is not sent again when the read node lags behind it (3.489865ms)
  AssertionError [ERR_ASSERTION]: a second claim transaction was sent for a claim the journal had already recorded as mined
  + actual - expected
  
  + [
  +   'claim(30416, 0xabababababababababababababababababababababababababababababababab)'
  + ]
  - []
  
    code: 'ERR_ASSERTION',
    actual: [ 'claim(30416, 0xabababababababababababababababababababababababababababababababab)' ],
    expected: [],
  }

### 23. Low: P2: the 900 s permit bound is whatever PLANE.maxPermitSeconds says: a config above 900 is taken as is and the permit is signed for that long

`lib/orders.mjs:220`

```
  const { paymentHeader, quoteSignature, nonce, deadline } = await signPayment(ctx.signer, ch.body, cfg.PLANE?.maxPermitSeconds ? { maxPermitSeconds: cfg.PLANE.maxPermitSeconds } : {});
```

Specialist (economics) finding; reproduced. MAX_PERMIT_SECONDS (lib/x402.mjs, 900) is only the DEFAULT of two parameters: pay() passes cfg.PLANE.maxPermitSeconds to challengeProblem (lib/orders.mjs:208) and to signPayment (line 220), and neither clamps it to the constant (lib/x402.mjs:71, :98), although signPayment's own doc comment says "The deadline is never more than MAX_PERMIT_SECONDS away, whatever the challenge asks" (x402.mjs:89). With PLANE.maxPermitSeconds = 86400 a challenge asking maxTimeoutSeconds 86400 is accepted and the Permit2 signature is valid for a day: the payment can be taken long after the order was dropped, and the order holds as paying/lost until that deadline because only the chain past the deadline ends it.
EXPECTED (P2 "permits at most 900 s"): refused, or signed for at most 900 s. ACTUAL: accepted (problem null), signed for 86400 s.
REACHABLE WITH THE DEPLOY CONFIG: no (the example ships 900; the plane caps at 300 s); by operator configuration only. Low.
SMALLEST FIX: clamp at the source: const cap = Math.min(maxPermitSeconds, MAX_PERMIT_SECONDS) in both challengeProblem and signPayment, or refuse to start with PLANE.maxPermitSeconds > 900.

**Reproduction**

State: cfg.PLANE.maxPermitSeconds = 86400; challenge accepts[0].maxTimeoutSeconds = 86400, amount 0.5 IMD, payTo the pinned address. Call challengeProblem(...) and signPayment(...) as lib/orders.mjs:208/:220 do. Expected: a refusal or deadline - now <= 900. Actual: null and 86400.
RUN (Node 20+, after npm ci): save the test below as test/zz-r.test.mjs, run `node --test test/zz-r.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-r.test.mjs -----
// P2: the 900 s permit bound is whatever PLANE.maxPermitSeconds says
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
const { challengeProblem, signPayment, IMD, MAX_PERMIT_SECONDS } = await import("../lib/x402.mjs");
test("no signed payment stays takeable more than 900 s, whatever PLANE.maxPermitSeconds says", async () => {
  const payTo = "0x4e0fa57bde726079356537e2f34d671e9f41adbc", h = utils.hexZeroPad("0x01", 32);
  const ch = { accepts: [{ asset: IMD, payTo, amount: "500000000000000000", maxTimeoutSeconds: 86_400 }], resource: "r", resourceUrl: "u", requesterScopeHash: h, quote: { id: "q", quoteHash: h, action: "oracle.request", expiresAt: 1_900_000_000, payment: { asset: IMD, amount: "500000000000000000", payTo, network: "eip155:1" } } };
  const cfg = { PLANE: { payTo, maxPermitSeconds: 86_400 } }; // an operator's config
  const problem = challengeProblem(ch, 1, utils.parseEther("0.5"), cfg.PLANE.payTo, cfg.PLANE.maxPermitSeconds); // lib/orders.mjs:208
  const { deadline } = await signPayment(Wallet.createRandom(), ch, { maxPermitSeconds: cfg.PLANE.maxPermitSeconds }); // lib/orders.mjs:220
  const life = deadline - Math.floor(Date.now() / 1000);
  assert.ok(problem !== null || life <= MAX_PERMIT_SECONDS, `the challenge was accepted (${problem}) and the permit signed for ${life} s (MAX_PERMIT_SECONDS ${MAX_PERMIT_SECONDS})`);
});

----- OUTPUT on f30a9d0 -----
✖ no signed payment stays takeable more than 900 s, whatever PLANE.maxPermitSeconds says (100.984102ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-r.test.mjs:10:1
✖ no signed payment stays takeable more than 900 s, whatever PLANE.maxPermitSeconds says (100.984102ms)
  AssertionError [ERR_ASSERTION]: the challenge was accepted (null) and the permit signed for 86400 s (MAX_PERMIT_SECONDS 900)
    code: 'ERR_ASSERTION',
    actual: false,
    expected: true,
  }

### 24. Low: P2: the 402 challenge is checked for its payment terms only; the quote id, action, resource URL and requester scope the keeper signs are whatever the answering server sends, so its IMD can be signed o

`lib/orders.mjs:208`

```
  const problem = challengeProblem(ch.body, questions, utils.parseEther(String(cfg.IMD?.pricePerQuestion ?? 0.5)), cfg.PLANE?.payTo, cfg.PLANE?.maxPermitSeconds);
```

Specialist (economics) finding; the keeper-side behaviour is reproduced, the plane-side consequence is NOT verified (see below). challengeProblem checks asset, network, payTo, amount and the permit's life. Nothing compares the challenge with the order being paid: signPayment signs the QuoteApproval over challenge.quote.id, quote.quoteHash, quote.action, challenge.resourceUrl and challenge.requesterScopeHash as received, and the Permit2 witness (to, validAfter) pays the pinned payTo. Whoever answers as the plane (ctx.planeState.base comes from the ENS text record first; PLANE_BEARER is sent to that server with every call) can hand the keeper the real plane's challenge for ANOTHER order: another id, another action, another requester scope.
CALL SEQUENCE: step(quoted) -> pay() -> plane.challenge(o.planeOrder) answers 402 with a foreign quote -> challengeProblem: null -> buyHold ok -> signPayment -> recordSpend -> stage "paying" -> plane.submit(...).
EXPECTED: a challenge that is not for this order is refused unpaid. ACTUAL: stage "paying", 0.5 IMD counted as spent, the signed payment for https://api.imd.fun/requests/SOMEONE-ELSES-ORDER/submit (action agent.run) handed to the answering server.
BOUND AND LIMIT OF THIS PROOF: the payee is still the pinned address; at most 0.5 IMD a question and IMD.dailyCap (5 IMD) a day, only when the keeper has a reason to buy. Whether the real plane settles a payment whose payer is not the order's requester was not tested (no plane access here): if it refuses, the harm is the keeper's own order going lost and the day's cap being counted.
REACHABLE WITH THE DEPLOY CONFIG: yes for a hostile plane, a MITM or the ENS server record (all in the threat model).
SMALLEST FIX: bind the challenge to the order before signing: require challenge.quote.action === o.action and challenge.resourceUrl === <the base the order was quoted at>/requests/<o.planeOrder>/submit, and keep the quote id / hash returned at the quote step and require the challenge to carry the same.

**Reproduction**

State: one order { stage: "quoted", action: "oracle.request", planeOrder: "po-1" }; the challenge answers 402 with quote { id: 9999..., action: "agent.run" }, resourceUrl ".../requests/SOMEONE-ELSES-ORDER/submit", payment 0.5 IMD to the pinned payTo. Call advanceOrders(ctx). Expected: order refused, nothing signed, 0 spent. Actual: stage "paying", payment handed over, 0.5 IMD spent.
RUN (Node 20+, after npm ci): save the test below as test/zz-s.test.mjs, run `node --test test/zz-s.test.mjs`, then delete it. It FAILS on commit f30a9d0 (run by this reviewer; output below).
----- TEST test/zz-s.test.mjs -----
// P2: the 402 challenge is checked for its payment terms only; the keeper signs for whatever order, action and scope the answering server sends
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { BigNumber, providers, utils, Wallet } from "ethers";
process.env.STATE_DIR = mkdtempSync(join(tmpdir(), "audit-"));
process.env.PLANE_BEARER = "test-bearer";
const { advanceOrders, loadOrders, spentToday } = await import("../lib/orders.mjs");
const { IMD } = await import("../lib/x402.mjs");
const { writeState } = await import("../lib/state.mjs");
const example = (await import("../config.example.js")).default;
test("the keeper signs a payment only for ITS order: a challenge quoting another order and action is refused unpaid", async () => {
  const h = `0x${"cc".repeat(32)}`;
  writeState("orders.json", { list: [{ key: "k-1", stage: "quoted", purpose: "fall", action: "oracle.request", input: {}, planeOrder: "po-1", requestKey: "r-1", at: new Date().toISOString(), questions: [{ role: "price", leaf: "0x00000000000000000000000000000000000000aa" }] }] });
  const payment = { network: "eip155:1", asset: IMD, amount: utils.parseEther("0.5").toString(), payTo: example.PLANE.payTo, decimals: 18 };
  // Whoever answers as the plane returns the 402 challenge of SOMEONE ELSE's order on the real plane (payment terms are the real plane's).
  const foreign = { resource: { url: "https://api.imd.fun/requests/SOMEONE-ELSES-ORDER/submit", description: "agent.run" }, resourceUrl: "https://api.imd.fun/requests/SOMEONE-ELSES-ORDER/submit", requesterScopeHash: h,
    accepts: [{ scheme: "exact", ...payment, maxTimeoutSeconds: 300 }], quote: { id: "99999999-2222-4333-8444-555555555555", quoteHash: h, action: "agent.run", expiresAt: 1_900_000_000, payment } };
  const submitted = [], raised = [], logs = [];
  const big = utils.parseEther("30");
  const ctx = { execute: true, cfg: example, log: (s) => logs.push(s), signer: Wallet.createRandom(), planeState: { ok: true, base: "https://plane.example" },
    provider: { getBalance: async () => utils.parseEther("1"), getGasPrice: async () => utils.parseUnits("5", "gwei") },
    book: { token: () => ({ balanceOf: async () => big, allowance: async () => big }) },
    alerts: { raise: async (level, key) => raised.push(`${level} ${key}`), settle: async () => {} },
    planeClient: { challenge: async () => ({ status: 402, body: foreign }),
      submit: async (orderId, quoteSignature, paymentHeader) => { submitted.push({ orderId, signedFor: JSON.parse(Buffer.from(paymentHeader, "base64").toString()).resource?.url ?? "?" }); return { status: 200, body: {} }; },
      order: async () => ({ status: 200, body: {} }) } };
  await advanceOrders(ctx);
  console.log(logs.join("\n"), raised.join(","));
  assert.deepEqual({ stage: loadOrders()[0]?.stage ?? "refused", signedAndHandedOver: submitted, spentToday: utils.formatEther(spentToday()) }, { stage: "refused", signedAndHandedOver: [], spentToday: "0.0" });
});

----- OUTPUT on f30a9d0 -----
order   fall: paid 0.5 IMD, plane says 200 
✖ the keeper signs a payment only for ITS order: a challenge quoting another order and action is refused unpaid (123.4364ms)
ℹ tests 1
ℹ pass 0
ℹ fail 1

✖ failing tests:

test at test/zz-s.test.mjs

### 25. Info: Answers to questions 1-5, claims C1-C6 and the soundness questions; what was merged; coverage and limits of this review

`README.md:1`

```
# imdUSD v2 keeper
```

WHAT RAN. npm ci && npm test on f30a9d0: tests 151, pass 151, fail 0 (87 s here). The 38 specialist findings (math 4, flow 5, permissions 8, economics 21) were each re-run as a node:test file under test/ against this commit and deleted afterwards; duplicates were merged into 23 findings; one more (verified-packet logs on a lone RPC, lib/bridge.mjs:397) is this review's own. None failed to reproduce; three specialist tests arrived truncated (reorg, peer RPC down, failed claims() read) and were rewritten here. The three attached proofs were run: all fail for the reason their finding gives. One lead is NOT kept as a finding because it was not reproduced: lockFile (lib/state.mjs) replaces a dead holder's lock by read, remove, create, so two processes starting together over one stale lock might both take it.
Q1 (P2, P3). No double payment found (the latch and the day's spend are written before the payment leaves; a latched order is only polled; it ends unpaid only when the chain shows the Permit2 nonce unused past the deadline). Payment outside the rules: the challenge is not bound to the order (low), PLANE.maxPermitSeconds is not clamped to 900 (low, operator config). Unbounded fee: yes (medium, lib/tx.mjs:119). Two writers on one key: the key lock is per HOME directory and per live process; no race reproduced. Mainnet key on 4663: accepted when the phrase is typed differently or KEEPER_MNEMONIC is absent from the 4663 process (low).
Q2 (P1, P4, P6, C5), per 4663 duty. Pulse poke: held silently by any slow pass (high, keeper.mjs:177; the bridge walk is the shipped trigger, lib/bridge.mjs:383); a skipped poke says nothing itself, pulse-silent warns at 675 s. Stock tick: same two, plus no margin inside TICK_SPAN (low). Liquidator.tick, sync, writeOff, bites: held by a slow pass, skipped silently over the gas ceiling / under the ETH floor / behind an open send (medium, lib/act.mjs:31), and stopped (loudly, after 5 passes) by a refused log range on the lone RPC (medium, lib/chain.mjs:65). Acts in a grace: a close seizing 0 can be sent in the pass in which the grace opens (low); writeOff is held in the grace and sent after it; arming precedes the write-off by WRITEOFF_DELAY 3600 s (read, not separately tested). Alert cleared on a failed read: the bridge loop only (medium lib/bridge.mjs:698, low :752); runPulse and runStocks await every read before they settle, so a failed read throws and their alerts stand.
Q3 (P5). Honest transfer flagged: lagging source head (high, :685), reorg below the cursor (medium, :460), false critical supply drift on one RPC (medium, :475). Forgery missed or late: alerts computed then dropped by a later throw (high, :722), gap alert reset by a stale head (medium), escalation swallowed for an hour (medium), no bridge alert naming a forged Queued for its whole 12 h while the peer RPC is down (high, :666), a forged packet waiting at the endpoint never flagged when a lone log RPC answers [] for the endpoint's logs (medium, :397) or while the first-start walk runs (high), a failed Telegram delivery not retried for an hour (low). No case was found where a forged Received/Queued whose logs are served completely and whose source is readable is not judged forged by the next completed pass.
Q4 (P8). No double mint is possible and no claim of an unmatched transfer was found: judgeQueued requires guid, amount and recipient to equal the indexed Sent before any act (:552) and claims() is compared again before the send (:609). A repeat send with a lagging node (low, :592). Honest matured claims not sent: after a reorg (never), while the peer RPC is down, while a lagging source head makes the verdict "forged", and for up to an hour on the routine tier (low, :617). A delay change is followed: breakers() is read every pass and the chain's own queuedAt + delay is checked before the send (:615).
Q5 (P7). Nothing found. Every send goes through act(), which only simulates without --execute (lib/act.mjs:15); advanceOrders returns at

**Reproduction**

Not a defect: the review's answers and coverage. npm ci && npm test on f30a9d0: tests 151, pass 151, fail 0. Each finding above carries its own test and output.

---

Judge's submission `b436ca36668e76199b6e775067d42f6d25e268b56633ce78bcc52b6339e43d17`, accepted on the IdentityMD network. Acceptance means the report met the job's checks;
it is not a guarantee that the code has no other defects.
