# Audit report

> Re-audit the viewer folder only (`build-lane.py` and its HTML output), at commit 3ae1cdf. It is a follow-up to audit job 5505b809, so check whether each of those findings is fixed, especially that a failed receipt read never renders as "matches" (build-lane.py:146). Treat every other folder as out of scope. Work offline and read-only. Give each finding a file and line, its impact, and steps to reproduce it.

| | |
|---|---|
| Repository | https://github.com/uxp-labs/flop-devnet-lab.git |
| Commit | `3ae1cdfa55707dd8e02678acdba57faec5aa50bf` |
| Job | `752d0a3b-e5f1-4967-a9c2-ea0aab821428` |
| Judged | 2026-11-10 16:37 UTC |
| Findings | 2 medium · 10 low · 2 info |

Four agents audited the code as it is at `3ae1cdf`, 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. Medium: key_expired receipt (a failed HTTP 401 read) is exempt from the failed-read branch and still renders "match matches" plus a stale observed spend; 5505b809 M1 is only partly fixed

`viewer/build-lane.py:113`

```
    if r.get("flag") != "key_expired" and (r.get("http") not in (None, 200) or present(r.get("error"))):
```

5505b809 M1 required that a failed receipt read never render as "matches". The v8 fix at line 113 routes failed reads (http not None/200, or a non-empty error string) to a red unknown row before the identity and disagree checks, but carves out flag == "key_expired". That flag is itself only ever written for a failed read: imd-flop sets it when the gateway answered HTTP 401 api_key_expired with a null receipt (imd-flop/src/receipts.ts:70, providers.ts:86), and `receipt --refresh` then keeps the stored state/settled/chain_final unchanged (cli.ts:426, not fresh). Such a receipt skips the line-113 branch, passes identity_ok and the disagree check, and reaches lines 155-163: it gets the red unknown chip and the 'key expired, can't re-check' flag, but line 162 still appends ["match", "matches"] and line 163 appends ["observed spend", settled] from the un-refreshed file. The row therefore says 'matches' and, for a previously settled receipt, prints the stale settled amount as observed spend on a receipt the gateway refused to serve. This contradicts the key-expired example row in lane-examples.json (chips sent + unknown, 'last seen', 'now unreadable: key_expired', observed spend blank, no 'match' line), which the v8 fix cites as its template. Two more symptoms of the same carve-out: (a) when the first read or a post-timeout refresh gets the 401, the producer stores request_id "" (run.ts:302-305, cli.ts:426), so the viewer takes the identity-mismatch branch and shows red 'mismatch' with 'receipt request_id (row says req-1)' and never mentions the key expiry, while the same inputs with http 404 correctly show 'unreadable: HTTP 404 not_found'; (b) a key-expired receipt whose stored state disagrees with the ledger shows only the amber disagree chip and drops the key-expired note. test_audit_v8's key-expired control only asserts the flag text and never asserts 'matches' is absent, so it passes. Fix: remove the key_expired exemption from the line-113 condition and, inside that branch, use the key-expired wording ('now unreadable: key_expired', flag "key expired, can't re-check") when flag == "key_expired"; never append match/observed-spend entries for it. Merged from audit_economics, audit_math, audit_flow and audit_permissions (each reported this once).

**Reproduction**

Offline, from viewer/, using lane() from test_audit_v7 (same harness as test_audit_v8). (1) ledger dict(LED, state='estimated'); receipt dict(REC, http=401, error='api_key_expired', flag='key_expired'). Actual: rows[0]['flop'] == [['chain final', ...not checked yet], ['match','matches'], ['observed spend', None]], visible text 'sent unknown chain final not checked yet match matches observed spend key expired, can't re-check'. Expected: no 'matches' anywhere, 'now unreadable: key_expired', reservation 0.198 shown, observed spend blank. (2) ledger dict(LED, state='settled', spend=0.198); receipt dict(REC, state='settled', settled=0.198, http=401, error='api_key_expired', flag='key_expired'). Actual: flop ends [['match','matches'], ['observed spend', 0.198]] and the page shows 'observed spend 0.198' beside "key expired, can't re-check". Expected: observed spend blank. (3) ledger dict(LED, state='timeout_unknown', reason='TimeoutError'); receipt dict(REC, request_id='', state=None, http=401, error='api_key_expired', flag='key_expired'). Actual: chips [grey sent, red mismatch, red unknown], flop starts [['receipt request_id', ' (row says req-1)'], ...], 'key expired' appears nowhere. Control: the same receipt with http=404, error='not_found' renders 'now unreadable: HTTP 404 not_found'. (4) CLI: write the ledger line {"job":"j","request_id":"req-1","seat":"1234","did":"did:key:z","provider":"mock","network":"devnet","ts":"2026-11-10T00:00:00.000Z","quote_padded":0.198,"cap_charge":0.198,"per_call_cap":0.25,"daily_cap":0.5,"spent_before":0,"state":"estimated"} to <dir>/ledger.jsonl and {"request_id":"req-1","job":"j","seat":"1234","did":"did:key:z","state":"estimated","settled":null,"stage":"gateway observed","chain_final":false,"flag":"key_expired","http":401,"error":"api_key_expired"} to <dir>/req-1.json, run `python3 build-lane.py <dir>`: the rebuilt HTML contains '<span class="k">match</span> matches' on the key-expired row. One-liner that fails on 3ae1cdf: python3 -c "from test_audit_v7 import *; r,p=lane([dict(LED,state='settled',spend=0.198)],{'req-1':dict(REC,state='settled',settled=0.198,http=401,error='api_key_expired',flag='key_expired')}); assert 'matches' not in visible(p)"

### 2. Medium: A settlement above the reservation and per-call cap renders green 'chain final' and 'matches'; a negative daily-cap-left carries no flag

`viewer/build-lane.py:141`

```
        disagree = st not in SETTLES or settled is None or amount(e.get("spend")) != settled
```

For a settled receipt the only green condition is that the ledger state settles and ledger spend == receipt settled. Nothing compares the settled amount with the reservation (cap_charge/quote_padded), per_call_cap or daily_cap, and the computed daily_left is never checked for sign. A settlement 20x the per-call cap therefore shows the green chain-final chip and 'match matches', and the spend column prints 'daily cap left -4.5' on an unflagged row (bad False, spend_flags empty). Surfacing a cap breach is what the lane is for; here it looks like the healthiest row on the page. Fix: when settled (or ledger spend) exceeds reservation or per_call_cap, or daily_left < 0, mark the row bad, block the green chip and add a visible flag such as 'settled above cap'. This keeps the equality rule. From audit_economics; the audit_math '-0.0' case (line 94) is the same unflagged-overrun gap at the rounding boundary and is reported separately as low.

**Reproduction**

From viewer/ with lane() from test_audit_v7: ledger dict(LED, state='settled', spend=5.0, cap_charge=5.0) (per_call_cap 0.25, daily_cap 0.5, spent_before 0); receipt dict(REC, state='settled', settled=5.0, chain_final=True, http=200). Actual: rows[0]['bad'] is False, chips [[grey,sent],[amber,gateway observed],[green,chain final]], greens(page) == ['chain final'], visible 'match matches observed spend 5.0 ... per-call cap 0.25 daily cap left -4.5', no flag. Expected: bad row, no green chip, a cap-breach flag. Same result with cap_charge left at 0.198 (settled 5.0 against reservation 0.198): still green, 'daily cap left 0.302'.

### 3. Low: Negative settled/spend amounts pass amount() and render as a green chain-final 'matches' row, unlike imd-flop's knownSettledSpend

`viewer/build-lane.py:23`

```
    if isinstance(v, bool) or not isinstance(v, (int, float)) or v != v or v in (float("inf"), float("-inf")): return None
```

amount() accepts any finite non-bool number including negatives, and feeds the receipt's settled value (line 137), the ledger spend (line 141) and cap_charge (line 92). The producer's rule (imd-flop/src/receipts.ts knownSettledSpend) is that a settlement counts only when finite and >= 0; anything else is unknown. In the viewer a negative settled/spend pair satisfies the equality check, so the row goes green with 'observed spend -0.05', and a negative cap_charge raises 'daily cap left' above the daily cap (0.55 against a 0.5 cap). Fix: return None from amount() for v < 0 (matching knownSettledSpend); a None settled already routes to the disagree branch. Merged from audit_economics and audit_math.

**Reproduction**

lane([dict(LED, state='settled', spend=-0.05, cap_charge=-0.05)], {'req-1': dict(REC, state='settled', settled=-0.05, chain_final=True, http=200)}). Actual: bad False, greens == ['chain final'], visible 'match matches observed spend -0.05 ... daily cap left 0.55'. Expected: settled treated as unknown (blank observed spend, amber disagree, no green), daily cap left not above 0.5.

### 4. Low: Failed-read test at line 113 accepts a non-string error with http null, so a receipt carrying an object or numeric error renders as a clean 'matches' row

`viewer/build-lane.py:113`

```
    if r.get("flag") != "key_expired" and (r.get("http") not in (None, 200) or present(r.get("error"))):
```

The failed-read condition only fires for an http other than None/200 or for a non-empty *string* error (present() requires str). A receipt with http null and error set to an object such as {"message":"HTTP 500"} or a number is not a failed read: bad False, amber 'gateway observed', 'match matches'. The current imd-flop writer always writes a string error, so this needs a hand-edited or foreign receipt, but the viewer's stated rule is that any file value it cannot vouch for is not shown as OK. Fix: treat error as failed when it is anything other than None or "", and http as failed when it is anything other than the int 200 (or None). From audit_economics.

**Reproduction**

lane([dict(LED, state='estimated')], {'req-1': dict(REC, http=None, error={'message': 'HTTP 500'})}) and the same with error=500. Actual (both): rows[0]['bad'] False, chips [[grey,sent],[amber,gateway observed]], flop contains ['match','matches'], rendered as class="row" (not bad). Expected: red unknown row, 'receipt read failed', no 'matches'.

### 5. Low: A non-fresh refresh stored with http 200 and last_known_at renders as a clean 'matches' row; the viewer ignores the producer's not-fresh marker

`viewer/build-lane.py:113`

```
    if r.get("flag") != "key_expired" and (r.get("http") not in (None, 200) or present(r.get("error"))):
```

imd-flop's `receipt --refresh` (cli.ts:420-426) treats a read as fresh only when http === 200 and the body is an object; otherwise it keeps the stored state/settled and writes last_known_at. A 200 answer with a null or non-object body therefore produces a stored receipt with http 200, error null and last_known_at set. The viewer's failed-read test looks only at http and error, so this receipt renders as class="row" with amber 'gateway observed' and 'match matches', the outcome v8 item 4 was meant to rule out. Precondition is gateway/SDK behaviour returning 200 without a receipt object, hence low. Fix: also treat a receipt carrying last_known_at (the producer's not-fresh marker) as a failed read. From audit_flow.

**Reproduction**

lane([dict(LED, state='estimated')], {'req-1': dict(REC, http=200, error=None, last_known_at='2026-11-10T15:00:00Z')}). Actual: bad False, chips [[grey,sent],[amber,gateway observed]], flop contains ['match','matches']. Expected: red unknown, no 'matches', since the producer recorded this receipt as not re-read.

### 6. Low: read_receipts catches only ValueError: an unreadable receipt path (directory, mode 000, dangling symlink) aborts the whole rebuild and leaves the previous lane, possibly saying 'matches', in the HTML

`viewer/build-lane.py:65`

```
        except ValueError:
```

read_receipts wraps open()/json.load in `except ValueError` only. An OSError (IsADirectoryError for a directory named x.json, PermissionError for a mode-000 file, FileNotFoundError for a dangling symlink) propagates out of from_files() and main() before line 200 rewrites the HTML. The script dies with a traceback and settlement-viewer-2026-11-09.html keeps its previous lane byte for byte, including any earlier clean 'matches' or green row. This contradicts the stated design that one bad item becomes a red 'unreadable' row and never aborts the lane (lines 36-37, 78). Fix: catch OSError as well and map it to {"_unreadable": True}. Merged from audit_economics and audit_flow.

**Reproduction**

Copy viewer/ to a temp dir and run `python3 build-lane.py` once (md5 of the HTML noted). Then `mkdir mock-receipts/stray.json` and run `python3 build-lane.py` again. Actual: 'IsADirectoryError: [Errno 21] Is a directory: .../mock-receipts/stray.json' and the HTML md5 is unchanged. Same with `chmod 000 mock-receipts/mock-1234-561407c257de792a.json` as a non-root user: PermissionError, HTML unchanged. Expected: a rebuilt lane with a red 'unreadable' row for the bad entry.

### 7. Low: read_ledger decodes the file outside the per-line try: one non-UTF-8 byte in ledger.jsonl aborts the rebuild instead of producing an unreadable row

`viewer/build-lane.py:47`

```
        for n, line in enumerate(fh, 1):
```

The text-mode iteration `for n, line in enumerate(fh, 1)` decodes each chunk before the per-line try at line 49, so a UnicodeDecodeError from a torn or corrupted append escapes read_ledger, from_files and main, and the previous lane stays in the HTML. The docstring promises that unreadable lines become unreadable rows. Fix: open with errors='surrogateescape' or in binary mode and decode each line inside the try, so the bad line becomes unreadable(f'ledger line {n}', ...). Merged from audit_economics and audit_flow.

**Reproduction**

Copy viewer/ to a temp dir, `printf '\xff\xfe garbage\n' >> mock-receipts/ledger.jsonl`, then `python3 build-lane.py`. Actual: "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 3101: invalid start byte" and the HTML is byte-identical to before. Expected: the 3 demo rows plus a red 'ledger line 6' unreadable row.

### 8. Low: A timeout row whose receipt file is corrupt loses its 'timeout: spend unknown, not retried' note

`viewer/build-lane.py:110`

```
        row["flags"] = ["receipt file unreadable: not shown as OK"]
```

The _unreadable branch (lines 108-112) returns without appending unresolved_flag, while the failed-read branch (line 122), the mismatch branch (line 134) and the disagree branch (line 150) all add it for timeout_unknown/error ledger states. A timed-out call whose receipt file is broken therefore no longer tells the reader that spend is unknown and the call was not retried. Fix: append unresolved_flag (and keep the red chip) when unresolved, as line 134 does. From audit_economics.

**Reproduction**

lane([dict(LED, state='timeout_unknown', reason='TimeoutError')], {'req-1': '{not json'}). Actual: flags == ['receipt file unreadable: not shown as OK'], visible text has no 'timeout' note. Expected: flags also include 'timeout: spend unknown, not retried'.

### 9. Low: Missing receipt file drops the held reservation and hard-codes 'last seen sent' regardless of ledger state; the flags list gets the raw state string

`viewer/build-lane.py:105`

```
        row["flop"] = [["last seen", "sent"], ["observed spend", None]]
```

When no receipt file exists for a request_id (always the case after a timeout, since the producer writes none) the branch at lines 103-107 shows only ['last seen','sent'] and a blank observed spend. Unlike the unreadable, failed-read, mismatch and disagree branches it omits ['reservation', reservation] although the ledger still holds cap_charge against the daily cap, which goes against the 3ae1cdf FIXER rule that an unresolved row never drops the reservation display. 'last seen' is the literal 'sent' even when the latest ledger line is 'estimated' or 'settled', and line 106 appends unresolved_flag unconditionally, so a settled ledger row with no receipt file shows the bare word 'settled' as a flag. The committed HTML shows the demo-job-2 row (timeout_unknown, cap_charge 0.15) with no reservation line while 'daily cap left 0.152' already subtracts it. Fix: append ['reservation', reservation], use esc(st) for 'last seen', and only add unresolved_flag when unresolved. From audit_flow.

**Reproduction**

lane([dict(LED, state='timeout_unknown', reason='TimeoutError')], {}). Actual: flop == [['last seen','sent'], ['observed spend', None]], no reservation entry. Expected: a 'reservation 0.198' entry as the other unresolved branches render. lane([dict(LED, state='settled', spend=0.198)], {}): actual 'last seen sent' and flags == ['settled']. In the committed viewer/settlement-viewer-2026-11-09.html the demo-job-2 row has no '<span class="k">reservation</span>' while its daily cap left is 0.152.

### 10. Low: A pending or null-state receipt's settled amount is shown as observed spend on a clean 'matches' row without any ledger agreement check

`viewer/build-lane.py:144`

```
        disagree = st in SETTLES or chain_final
```

For a receipt in a settled state the viewer requires the ledger to agree on the amount before showing it (line 141). For any other receipt state, including null (imd-flop writes null for every state it does not recognise, receipts.ts:49-51), the pending branch only checks the ledger state and chain_final and ignores settled. The row then renders unflagged with amber 'gateway observed', 'match matches' and 'observed spend <settled>' from line 163, although imd-flop never books that amount in the ledger (cli.ts:441, run.ts:330 only take settled when the state settles). The lane thus displays a spend figure the ledger does not hold, and an unrecognised receipt state is indistinguishable from a normal pending one. Fix: in the pending branch treat settled is not None as a disagreement, and flag a null receipt state as unknown rather than pending. From audit_permissions.

**Reproduction**

lane([dict(LED, state='estimated')], {'req-1': dict(REC, state='estimated', settled=0.05, http=200)}). Actual: bad False, chips [[grey,sent],[amber,gateway observed]], flop ends [['match','matches'], ['observed spend', 0.05]], no flag. Same with state=None. Expected: the amber DISAGREE chip or a blank observed spend, row flagged; a null state named as unknown. Control: the same ledger with receipt state='settled', settled=0.05 correctly yields the DISAGREE chip.

### 11. Low: Receipts without a readable ledger line are silently dropped; a missing ledger renders 'No receipts found.' beside existing receipt files

`viewer/build-lane.py:72`

```
    if not os.path.exists(led): return []
```

from_files() iterates ledger entries only and looks receipts up by request_id, so a receipt whose request_id has no readable ledger line is never rendered, and the 'N receipt rows' count in main() counts ledger entries. Two cases: (1) ledger.jsonl absent: from_files returns [] and the viewer says 'No receipts found.' although settled receipt files are in the directory; (2) one ledger line truncated by a partial append (the failure mode cli.ts anticipates): read_ledger emits a red 'ledger line N' row but the receipt for that request_id, with its settled amount, appears nowhere, so the lane under-reports spend without saying a receipt was skipped. Fix: after building rows, render every receipt key not consumed as a red 'unmatched receipt' row (request_id and state shown, never green), and when the ledger is missing report the count of receipt files instead of 'No receipts found.'. From audit_permissions.

**Reproduction**

From viewer/ with load_lane() from test_lane_disagree. Case 1: temp dir containing only req-9.json = dict(REC, request_id='req-9', state='settled', settled=0.198), no ledger.jsonl; sys.argv = ['build-lane.py', tmp]; from_files() returns [] (actual), main() would print 'No receipts found.'. Expected: one row for req-9 marked unmatched. Case 2: ledger.jsonl = json.dumps(LED) + '\n' + json.dumps(dict(LED, request_id='req-9', job='k'))[:80] + '\n'; receipts req-1.json = REC, req-9.json = dict(REC, request_id='req-9', job='k', state='settled', settled=0.198). Actual: row labels ['ledger line 2', 'j'] and any('req-9' in json.dumps(r) for r in rows) is False. Expected: a visible row naming req-9 as a receipt with no readable ledger line.

### 12. Low: A daily-cap overrun is never flagged in the spend column, and an overrun under 5e-7 FLOP rounds to '-0.0'

`viewer/build-lane.py:94`

```
    row["daily_left"] = r6(daily - spent_before - cap_charge) if None not in (daily, spent_before, cap_charge) else None
```

r6() rounds daily - spent_before - cap_charge to 6 decimals via float(f'{x:.6f}'). Any overrun smaller than 5e-7 rounds to -0.0, which num() renders as '-0.0', reading as zero left rather than over the cap. Larger overruns render as a plain negative number (e.g. -0.1) on a row that is not bad and has no spend flag. Fix: normalise -0.0 to 0.0 (r6(x) + 0.0) and add an explicit cap-exceeded flag whenever daily_left < 0 rather than letting the sign carry the message. From audit_math; the line-141 medium covers the settled-above-cap case.

**Reproduction**

lane([dict(LED, state='estimated', daily_cap=0.5, spent_before=0.3480004, cap_charge=0.152)], {'req-1': dict(REC, http=200)}). Actual: rows[0]['daily_left'] == -0.0, page shows 'daily cap left -0.0', bad False. lane([dict(LED, state='estimated', daily_cap=0.5, spent_before=0.3, cap_charge=0.3)], ...): daily_left -0.1, bad False, spend_flags []. Expected: an over-cap flag on both rows and no signed zero.

### 13. Info: A failed read with http null renders the literal 'HTTP None' in the visible error text

`viewer/build-lane.py:118`

```
        why = esc(err) if err.startswith("HTTP ") else esc(f"HTTP {r.get('http')} {err}".strip())
```

When http is None and the error string does not start with 'HTTP ', the f-string at line 118 writes 'HTTP None <error>' into the row. Fix: omit the status when http is not an int. From audit_economics.

**Reproduction**

lane([dict(LED, state='estimated')], {'req-1': dict(REC, http=None, error='fetch failed')}). Actual: flop contains ['now', 'unreadable: <span class="mono">HTTP None fetch failed</span>'] and the visible text reads 'unreadable: HTTP None fetch failed'. Expected: 'unreadable: fetch failed'.

### 14. Info: A missing or null payer is displayed as 'payer: holder'

`viewer/build-lane.py:88`

```
    row = dict(label=esc(e.get("job")), sub=sub, payer=esc(e.get("payer") or "holder"), flags=[], spend_flags=[], flop=[],
```

esc(e.get('payer') or 'holder') turns a null, empty or absent payer into 'holder', attributing the spend to the seat holder when the file does not say who paid. This departs from the lane's 'unknown, never a default' rule for spend. The current producer refuses unknown payers before writing (run.ts v8 item 1), so this needs a hand-edited or older ledger line. Fix: render 'unknown' when payer is not one of the known payer strings. From audit_economics.

**Reproduction**

lane([dict(LED, payer=None)], {'req-1': dict(REC, http=200)}). Actual: rows[0]['payer'] == 'holder', page shows 'payer: holder'. Expected: 'payer: unknown'.

---

Judge's submission `9cbff7cb13b54033df55d83d5476760d7f79c28f99c661a6bcc7c457e5f95cae`, 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.
