# Project Agents.md Guide

This is a [MoonBit](https://docs.moonbitlang.com) project.

You can browse and install extra skills here:
<https://github.com/moonbitlang/skills>

## Project Structure

- MoonBit packages are organized per directory; each directory contains a
  `moon.pkg` file listing its dependencies. Each package has its files and
  blackbox test files (ending in `_test.mbt`) and whitebox test files (ending in
  `_wbtest.mbt`).

- In the toplevel directory, there is a `moon.mod` file listing module
  metadata.

## Coding convention

- MoonBit code is organized in block style, each block is separated by `///|`,
  the order of each block is irrelevant. In some refactorings, you can process
  block by block independently.

- Try to keep deprecated blocks in file called `deprecated.mbt` in each
  directory.

## Tooling

- `moon fmt` is used to format your code properly.

- `moon ide` provides project navigation helpers like `peek-def`, `outline`, and
  `find-references`. See $moonbit-agent-guide for details.

- `moon info` is used to update the generated interface of the package, each
  package has a generated interface file `.mbti`, it is a brief formal
  description of the package. If nothing in `.mbti` changes, this means your
  change does not bring the visible changes to the external package users, it is
  typically a safe refactoring.

- In the last step, run `moon info && moon fmt` to update the interface and
  format the code. Check the diffs of `.mbti` file to see if the changes are
  expected.

- Run `moon test` to check tests pass. MoonBit supports snapshot testing; when
  changes affect outputs, run `moon test --update` to refresh snapshots.

- Prefer `assert_eq` or `assert_true(pattern is Pattern(...))` for results that
  are stable or very unlikely to change. For snapshot tests that record
  structured debugging output, derive `Debug` and use `debug_inspect`, rather
  than deriving `Show` for debugging. For solid, well-defined results (e.g.
  scientific computations), prefer assertion tests. You can use
  `moon coverage analyze > uncovered.log` to see which parts of your code are
  not covered by tests.

## Project-Specific: Triple-Blind Crypto Verification

This is a cryptographic port of OpenSSH. Every crypto module must be
**byte-exact** cross-checked against two independent references before being
trusted: (1) the OpenBSD C reference, (2) a Python stdlib/library
implementation. The MoonBit implementation is the third leg.

### Layout

```
verify_c/             ← earlier, broader C-side harness suite (9 modules:
                        aead / bpacket / ed25519 / hmac_sha512 / hostkey /
                        kex / kex_c25519 / poly1305 / sha256 / sha512 /
                        x25519). Uses OpenBSD sha2.c for SHA.  Keep as-is.
triple_check/         ← newer, unified 3-way harness with one driver per
                        module + a top-level compare.py. Uses hand-written
                        SHA-512 (gen_tables.py derives H0/K from Newton
                        integer roots; no hand transcription).
                        c/main.c + python/verify.py + compare.py
```

Both directories coexist. Use `verify_c/` for the broader per-module harness
(especially when you need sha2.c-style incremental SHA-512 over a large
stream), and use `triple_check/<module>/` when you want a single, self-
contained, three-language byte-exact comparison.

Above those sit the per-loop gates, which are what "done" means for a loop:

```
cmd/<name>_test/          ← KAT driver, runs on 4 target x 2 mode unless the
                            dependency graph forces otherwise (say so in the
                            package comment when it does)
host/gen_*_vectors.py     ← KAT generator. Vectors come from Python, never from
                            transcribing our own encoder, or the suite proves
                            nothing.
host/*_oracle.py          ← reference implementation; refuses to emit anything
                            until it agrees with a second one (paramiko /
                            cryptography / a published RFC vector)
host/verify_loopNN.mjs    ← the gate: oracle agreement, KAT, real sshd, browser
                            Worker, and the earlier loops re-run
```

A gate is worth more than its check count. The checks that keep earning their
keep are the ones that can fail for a reason nobody had already ruled out.

### Adding triple-blind for a new module

For module `<m>`:

1. Pick the reference C source (preferably a stripped copy of the OpenSSH
   `<m>.c` placed in `triple_check/c/`) plus the same shim headers used
   for ed25519 (`config.h`, `includes.h`, `crypto_api.h`).
2. Write `triple_check/c/main_<m>.c` driver: minimal driver that calls
   the C functions on RFC/Rosenpass/OpenSSH KAT vectors, prints hex.
3. Write `triple_check/python/verify_<m>.py` using the corresponding
   Python library (`cryptography`, `hashlib`, `hmac`, etc.).
4. Update `triple_check/compare.py` to run all three: MoonBit test +
   C driver + Python ref, and assert byte-exact equality on the printed
   hex strings plus the published RFC KAT values.
5. Document the result in `<module>/REPORT.md` with the protocol/RFC
   number, KAT source, and the unified pass/fail per target.

### Acceptance criterion

For each crypto module:
- All three impls (MoonBit / C / Python) produce **byte-exact** outputs
  on the published KAT vectors.
- `moon test` passes 100% on native / wasm-gc / js.
- `moon check` shows 0 errors (warnings allowed only if pre-existing
  and unrelated to the module under test).

And one rule that the rest of this file keeps rediscovering the hard way:

> **A check that cannot fail is worse than no check.** Before believing any
> green line, ask what change would have turned it red. If nothing can, either
> delete it or fix the thing it was supposed to cover.

Three ways this repo got it wrong, all found by review rather than by a test:

- `moon test -p src/bpacket` — `-p` is not `moon test`'s package flag in this
  moon version (it takes a PATH), so it reported **0 tests**; and the assertion
  was written `passed === total && failed === '0'`, which `0/0` satisfies.
  The whole `src/bpacket` regression was therefore never running. Correct call:
  `moon test src/bpacket`, which immediately surfaced 13 real tests in
  `src/sha256`. A `total > 0` clause belongs in every such assertion.
- `check('counter continuity ...', text.includes('emit: PASS') && text.includes('wire:'))`
  — both conjuncts were already implied by the two checks above it. Rewritten
  to assert the *fixture* actually has multi-packet cases with pairwise-distinct
  packets, which is the precondition that makes the byte comparison a claim
  about counter continuity at all.
- A negative wire test whose *builder* used a different blob layout than the
  decoder under test: it kept passing, for the wrong reason.

### Loop #39: SFTP over a subsystem channel

`exec`, `pty-req`/`shell` and `window-change` all worked. `subsystem` -- the
third channel request type, and the one most deployments actually use -- did
not exist. The client could run a command, open a shell, and could not
transfer a file.

**The architectural decision, which is the reason this loop restructured
itself once.** The first draft put ~400 lines of SFTP in
`src/sshclient/sftp.mbt`. Adding the browser transport then meant writing the
same 400 lines again in `src/wtlive`, and a second copy of "when does a
READDIR end" is a second answer waiting to drift. So the protocol moved into
`src/sftp` as a transport-free state machine (`SftpSession`) and both drivers
became thin: ~120 lines each, and the only thing they are allowed to disagree
about is which function moves bytes.

The contract is four lines:

```moonbit
let s = SftpSession::new(ops)   // queues INIT
//   out = s.take_out()          // framed requests, for the channel
//   s.pump()                    // drain + advance
//   s.feed(channel_data_payload)// each inbound CHANNEL_DATA
// until s.done() or s.failed()
```

`pump` is called outside `feed` as well, on purpose: a reply may already be
sitting in the reassembly buffer while the socket has nothing left, and a
client that only pumps after a read ends up waiting forever for a packet it
already has.

**`subsystem` is want_reply=TRUE, and that is the whole point.**
`clientloop.c:2799-2811` sends it and then `client_expect_confirm(CONFIRM_CLOSE)`.
`env` is want_reply=FALSE and nothing ever answers it (RFC 4254 §6.4); the two
cannot share a rule. Waiting is what makes `ChanError::SubsystemRejected` /
`ExecError::SubsystemRejected` possible at all -- and it is deliberately *not*
folded into `ExecRejected`, because "there is no such subsystem" (usually a
typo: `sftp` vs `sftp-server`) and "the server refused this command" are
different diagnoses. `session.c:1945-1948` is the C that tells them apart.
Without the wait, a typo in `sshd_config` presents as "SFTP hangs after
connecting", which is the single most common SFTP deployment mistake.

**Two facts that only exist on the wire, and one of them nearly bit us.**

1. The reply numbers are `101 STATUS / 102 HANDLE / 103 DATA / 104 NAME /
   105 ATTRS`. The draft lists the *same five numbers sorted by name* --
   `101 DATA / 102 HANDLE / 103 NAME / 104 ATTRS / 105 STATUS` -- which reads
   naturally enough to be what an implementer writes from memory. A parser
   built on that ordering accepts every reply it is fed: a NAME reply parses
   as ATTRS, an ATTRS reply parses as NAME with a count of its first flag
   word. `host/sftp_capture.py` is what put the right order in the source, and
   `host/sftp_mutations.py` keeps it there by swapping the constants and
   requiring the KAT to go red.
2. `STATUS` carries a language tag after the message, so `expect_end` before
   reading it turns *every* STATUS into a parse failure -- including the
   `FX_EOF` that ends a read and the `SSH2_FX_NO_SUCH_FILE` a negative test
   expects. Same shape as VERSION's extension pairs: a parser that wants
   end-of-packet after the version number dies on the first byte a real
   server sends (six pairs on OpenSSH 8.0p1, more on newer ones -- so the
   count is *reported*, never asserted as a constant).

**End-of-read has two spellings.** A real server sends `STATUS(FX_EOF)`;
some send a zero-length `DATA`. Both are handled, and neither is confused with
a short chunk: a short chunk is NOT EOF, because treating one as EOF
truncates every file larger than a single read. The 200 KB fixture in the
gate exists for exactly this -- it takes many READs, many CHANNEL_DATA
packets, and at least one WINDOW_ADJUST back from the server.

**READDIR ends on `STATUS(FX_EOF)`, not on a short name list**, and the READ
offset accumulates over the whole file. Resetting it each round re-reads the
head of the file every time while the total length still looks plausible --
the worst kind of bug to find.

**The negative case is a status, not a transport error.**
`SSH2_FX_NO_SUCH_FILE` is a *successful* SFTP exchange: the request went out,
the server answered, the answer was code 2. `SftpOpResult::Failed(code, msg)`
carries it, so a routine negative test does not look like a broken client.

**Sizes are bounded before anything is sized from them.**
`SFTP_MAX_MSG_LENGTH` (256 KiB, `sftp-common.h:29`) is checked on the length
prefix itself, in the same order `sftp-client.c:195` does. A framing refusal
ends the session rather than only stopping packets from being handed out --
otherwise the driver waits for a reply that is never coming, and the symptom
is a hang rather than a refusal.

**The KAT has 14 session cases and 7 buffer cases.** All inbound bytes are a
real `internal-sftp` capture, with exactly one rewrite: the 4-byte request
id, because ids are client-chosen and pinning our numbering to paramiko's
would test the wrong thing. Two cases (`two_packets_one_feed`,
`second_packet_only_after_another_feed`) live at the `SftpInbuf` level rather
than the session level, because with one outstanding request there is no
causally possible session in which two replies arrive together -- writing it
as a session case would have demanded that the client ignore a reply it never
asked for.

19 mutations, all caught. `host/verify_loop39.mjs`: KAT on 4 backends x 2
modes byte-identical, the capture replayed, the mutations, a real
`internal-sftp` (realpath / listdir / read 11 B / read 200 KB / missing file),
the refused subsystem, and the browser Worker.

Run the gate with `node host/verify_loop39.mjs`.

Note: the Worker section skips with a message if Playwright's Chromium was
never downloaded (`npx playwright install chromium`). It is a *skip*, printed
in the summary -- silently reporting the browser path as verified is the one
outcome worse than a failure.

### Loop #40: the SFTP write side

Loop #39 could read. It could not write, which for an SFTP client is roughly
half the protocol -- a tool that only downloads is a different tool from one
that syncs.

**No new architecture.** Everything went into the existing `src/sftp` state
machine, because the split Loop #39 paid for is exactly the split this side
needs: `WRITE` / `SETSTAT` / `FSETSTAT` / `MKDIR` / `REMOVE` / `RMDIR` /
`RENAME` / `EXTENDED` are protocol, not transport, and `src/sshclient` and
`src/wtlive` stayed thin. `Rename` checks
`SftpSession::has_extension("posix-rename@openssh.com")` rather than counting
extensions, because the count is a property of the server and has no mapping to
"which capabilities".

**The offset is the whole loop.** `process_write` does
`lseek(fd, off, SEEK_SET)` before every write (`sftp-server.c:865-866`), so a
wrong offset is *not* a rejected request -- the server writes the bytes
somewhere else and answers `STATUS(OK)`. The file ends up with a plausible
length and the wrong contents, and every status code on the wire says it
worked. `written` is therefore a file offset advanced as each WRITE is
**queued**, not when it is acknowledged; waiting for the STATUS looks more
cautious and is not, because it re-sends the same chunk at the same offset
forever. The capture shows paramiko's offsets walking `0, 8192, 16384, ...`
and then **returning to 0** for the second file -- offsets are per file, so a
session-global counter is also wrong.

**Three things the C does not say, and the capture did.**

1. `FXP_RENAME` and `posix-rename@openssh.com` are different requests. The
   draft's RENAME is specified to fail when the target exists; the extension is
   `rename(2)` and replaces it. Confirmed against a target that was known to
   exist.
2. An unknown extension name is a clean `STATUS(SSH2_FX_OP_UNSUPPORTED=8)`,
   not a dropped channel. A client that treats it as fatal hangs against any
   server lacking the extension.
3. `SSH2_FXP_REMOVE` is 13 and `SSH2_FXP_RMDIR` is 15. Adjacent, and swapping
   them still produces a well-formed packet the server simply refuses.

**An empty payload sends zero WRITE requests**, not one empty WRITE. `TRUNC`
has already destroyed the old contents, and an empty WRITE comes back
`STATUS(OK)` -- so "create an empty file" and "write a file" would be
indistinguishable on the wire. A WRITE that *fails* still sends CLOSE: the OPEN
succeeded, so the server is holding a descriptor.

**Three bugs the KAT caught, all of them in code that looked finished.**

- `SftpVersionReply` gained `ext_names`, the field was added to the session --
  and nothing ever assigned it. Every `Rename` therefore took the v3 path and
  could not overwrite. It compiled, and it was wrong in the one way that only
  shows up against a real file.
- `send_write` never advanced `written`, so every chunk re-wrote offset 0.
- The driver grouped operations by flag rather than by command-line order, so
  `--sftp-mkdir d --sftp-write d/f` sent the write first. The comment above
  that code said "in command-line order" -- a comment/behavior split is worse
  than either one alone, because it makes the wrong order look intentional.
  `--sftp` now builds the op list while scanning argv.

**`--sftp-write` takes `<path>@<size>`, not two argv slots.** The port in this
driver is a *bare numeric* argument and `find_port` scans for the first thing
that parses as one, so a size in its own slot became the port and the run
reported `CONNECT_FAILED` -- which reads as a broken client. `@` rather than
`:` because Windows paths already contain colons.

**Two harness defects that made Loop #39's browser section vacuous.** It never
ran: the gate hung first (see below), and when forced through, G5 pointed the
Worker at a WebSocket port with **no relay behind it**. The Worker started,
never connected, and the symptom was a browser-shaped failure. `verify_loop39.mjs`
now starts `host/wt/ws_relay.py` like loop38 does; with that fixed, the browser
read path works too, and Loop #40's Worker writes 40000 bytes and reads the
same digest back as the native path.

**`startSshd` must not use `spawnSync`.** `sshd_setup.mjs` runs `sshd -D` in the
foreground and ends with `await new Promise(() => {})`, so it never returns.
`spawnSync` waits for that forever: the gate sat with no output and zero CPU
for 27 minutes, which looks like a slow run rather than a dead one. Async
`spawn` plus a port probe is the fix, and the probe is not optional either --
a fixed sleep is what made the sshd miss its window after the mutation pass
warmed `_build` back up cold.

**Windows has no POSIX permissions**, so `chmod` is recorded but never asserted
there: the capture shows mode `0o607` after a `chmod 0640`. Asserting it would
be theatre. Times *do* round-trip (`1700000000` / `1700000123`) and are.

**Verification.** 24 session cases + 7 buffer cases, 4 backends x 2 modes,
byte-identical. 30 mutations, all caught (11 new). The live run creates a
directory, writes 40000 bytes across several WRITEs, reads them back and
compares the SHA-256 against the same bytes computed independently in the gate,
renames, then **overwrites the renamed file through the extension and reads
that back** -- 11 bytes where 40000 used to be, which is what makes "accepted"
mean something. The Worker's 40000-byte digest matches the native one, which is
what the duplicated three-line payload rule is for: a Worker has no filesystem,
so the rule is repeated and the digest is the thing that would catch a drift.

### Build commands

```bash
# Loop #40: the SFTP write side (WRITE / SETSTAT / MKDIR / REMOVE / RMDIR /
# RENAME + posix-rename@openssh.com).  Starts its own sshd (18783), recaptures
# the write session, replays both KATs on 4 backends x 2 modes, runs the 30
# mutations, then drives the write script natively and in a Worker against the
# real server -- including the overwrite, which is proved by reading the
# replaced file back.
node host/verify_loop40.mjs
node host/verify_loop40.mjs --skip-regression

# Loop #39: SFTP over a subsystem channel. Starts its own sshd (18781),
# replays a captured internal-sftp through cmd/sftp_test on 4 backends x 2
# modes, runs the 19 mutations, then the same script natively and in a Worker
# against the real server
node host/verify_loop39.mjs

# Loop #38: host key algorithms (ssh-ed25519 + RFC 8332 rsa-sha2-*).
# Starts its own sshd with NO HostKeyAlgorithms pin, plus one pinned instance
# per algorithm so each dispatch is proved separately.
node host/verify_loop38.mjs
node host/verify_loop38.mjs --skip-regression

# Loop #32: the full browser gate -- G1 Worker, G2 byte stream, G3 SSH
# handshake against a real sshd, plus the Loop #30 crypto suites 4x2.
node host/verify_loop32.mjs
node host/verify_loop32.mjs --skip-regression   # browser stages only

# Loop #31: live-sshd gate (real OpenSSH on 127.0.0.1:22230, the MoonBit
# client, the exchange hash cross-checked twice, Loop #30 regressions)
node host/verify_loop31.mjs
node host/verify_loop31.mjs --keep-sshd     # leave the server up for poking

# Run all MoonBit tests
moon test                                   # defaults to native

# Rebuild C driver (hand-written SHA-512, no OpenSSH sha2.c)
cd triple_check/c
python gen_tables.py                        # regenerate tables.h
gcc -I. -c ed25519.c -o ed25519.o           # vendored OpenSSH ed25519.c
gcc -I. -c main.c -o main.o                 # driver
gcc main.o ed25519.o -o test_c.exe          # link

# Cross-check Python reference
cd triple_check/python
python verify.py

# One-shot triple-blind comparison (all 3 impls)
cd triple_check
python compare.py
```

### Pitfalls observed and fixed

- **`for ... else` in gen_tables.py**: the original prime sieve had
  `break` inside the `for` body, so the `else` clause never fired and
  the loop never produced primes. Fixed with an explicit `is_prime`
  flag.
- **`>> 31` on UInt64**: MoonBit UInt64 shift returns a 64-bit value, so
  `(x >> 31) & 1` gives a wrong bit position. Use `(x >> 63) & 1UL`
  instead. Affected: `fe_equal16`, `fe_ge16`, `sc_lt16`, `ge_equal_i8`.
- **`FixedArray::make(n, shared_val)` aliasing**: the inner value is
  shared by reference; struct constructors must initialize each element
  independently. The `src/test_nested/nested_test.mbt` directory is
  kept on disk (gitignored) as a diagnostic for this bug.
- **`#include "includes.h"` search path**: quoted includes always
  search the source file's directory first, so copying `ed25519.c` into
  `triple_check/c/` (next to the shim `includes.h`) is required to use
  the shim instead of the OpenSSH `includes.h` (which pulls in
  `<sys/socket.h>` and friends).
- **Empty-string SHA-512 self-test**: hashing `""` and comparing
  against `cf83e135...` transitively validates ALL 8 H0 and 80 K
  constants. Any single wrong constant changes the digest.
- **SSH transport exchange hash (Loop #31)**: RFC 4253 §8 lists the
  inputs informally and the natural reading is wrong. All eight fields
  are length-prefixed, K included, and I_C / I_S are the *complete*
  KEXINIT payload with the `0x14` type byte sitting **immediately after
  the length prefix**, not at the end. See `kex_gen_hash()` in
  `kexgen.c:47-96` and `kex_dh_compute_key()` in `kexdh.c:105` for the
  authoritative shape. Do not re-derive this from the RFC: run
  `python host/paramiko_oracle.py --port <p>`, which sweeps all 16
  prefix combinations against a live paramiko `session_id`.
- **`mpint_encode` already emits the u32 length prefix.** Wrapping its
  output in `write_ssh_string` again produces a string whose value
  starts with four zero bytes; a real server reads that as a far larger
  number and rejects the DH value as `>= p-1`.
- **SSH packet framing**: `packet_length` must be `4 (mod 8)` (the
  length field counts itself), the payload begins at offset 5 *within*
  the packet but at index 6 of the assembled buffer once the type byte
  is in place, and the payload length is
  `packet_length - padding_length - 2`.
- **`moon fmt` scope and CJK damage**: run it only over the packages the
  loop actually touched, then `git checkout --` the rest — it reformats
  unrelated legacy files.
  **The CJK half of this note did not reproduce and Loop #67 removed it.**
  It read: "`moon fmt` in write mode alters CJK comments (it turned
  `真实加密` into `真加密` in `src/sshclient/moon.pkg`)". On
  `moon 0.1.20261012` the damage is not there. Measured three ways, all
  before running write mode over anything: (1) the formatter's own output
  already sits in `_build/<target>/release/format/`, and all 366 CJK runs in
  `cmd/channel_test/main.mbt` are byte-identical between source and that
  output; (2) after formatting 12 files that needed it, all 373 CJK runs
  across them were unchanged; (3) after formatting the whole tree — 267
  files — `host/cjk_snapshot.py` compared all **12,840** CJK runs across 226
  files against a snapshot taken beforehand and found zero difference.
  The scope rule above stays, because the reformats are real; the CJK
  warning did not. `host/cjk_snapshot.py` is the standing guard: snapshot
  before any whole-tree format, `check` after, and it exits 1 if a single
  CJK run is lost or gained. What the old incident actually was is not
  recorded, and guessing is how a wrong rule survives for a dozen loops —
  the file it named no longer contains the string.
- **`moon check` summary goes to stderr** and exits 0 even with
  warnings, so a stdout-only capture sees an empty string. Read the
  error count out of the `N warnings, M errors` line across both
  streams, as `moonCheck()` in `host/verify_loop31.mjs` does.
- **Absolute artifact paths in `execSync`**: a bare `_build/...` is
  resolved by `cmd.exe` as a command name, not a path. Quote an
  absolute path instead.
- **`extern "js"` inline bodies: use the quoted IIFE form.** Write
  `= "((x) => ...)"`, not `#| (x) => ... |#`. In the `moon` version
  in use here the `#| ... |#` terminator is left in the emitted
  JavaScript, so every such FFI becomes a `SyntaxError` at load time
  in the browser. The quoted form is what `src/tcp/socket_js.mbt`
  already uses.
- **MoonBit has no `FixedArray` slice syntax.** `b[off..len]` is a
  parse error. Use a helper (`slice_bytes` in `src/sshclient/framing.mbt`).
- **A `suberror` cannot be pattern-matched.** Its constructors are not
  enum constructors. If a type must both be raised and matched for
  reporting, keep it a plain `pub(all) enum` and have the inner helpers
  return `Bool`/`Option` instead of raising -- which is also how
  Loop #31's blocking driver is structured.
- **`moonbitlang/async` does not support the wasm backends.** It covers
  native and js only. Anything awaiting a browser API is therefore
  `--target js` plus a Web Worker; the wasm artifacts cannot be the
  browser path. A `targets:` gate on a js-only module is what stops it
  leaking (the build simply fails for wasm, producing no artifact).
- **An `async fn main` that raises never reaches the Worker's completion
  hook.** Wrap the body and report through `wt_finish`, or the page
  only ever learns "timed out".
- **Chromium does not accept a locally-added certificate over QUIC.**
  It reports `QUIC_TLS_CERTIFICATE_UNKNOWN` for every override flag
  (`--ignore-certificate-errors`, `--ignore-certificate-errors-spki-list`
  with either the CA or leaf SPKI, dropping `--enable-automation`, and
  headed mode), while accepting the *same* certificate over plain HTTPS.
  WebTransport cannot be tested locally against a self-signed endpoint;
  use `ws://` (see `host/wt/ws_relay.py`) for the local end-to-end proof
  and keep WebTransport for endpoints with a publicly trusted
  certificate.
- **`page.evaluate` passes exactly one argument.** A Node-side variable
  referenced inside the browser function is simply undefined there, and
  the failure surfaces as a generic timeout. Put everything the browser
  needs inside the single config object.
- **aioquic 1.x: start a server with `serve()`, never a hand-rolled
  `create_datagram_endpoint`.** `QuicServer` is a `DatagramProtocol`
  that multiplexes connections off one socket; reusing a single instance
  leaves the packet loop with nothing to dispatch to, and the symptom is
  a silent server whose port still appears in `netstat`.
- **aioquic client: `wait_connected=False` sends nothing.** `connect()`
  calls `protocol.connect(addr, transmit=wait_connected)`, so the
  probe never puts an Initial on the wire and can only time out.
- **Generate the WebTransport test certificate idempotently.** The
  browser only trusts it because it was added to the Windows store, so
  regenerating the key each run invalidates that trust instantly.
  `host/wt/make_cert.py` reuses an existing pair unless `--rotate`.
- **Serve `chain.pem` (leaf + CA), not a bare self-signed leaf.**

### Loop #33: aes128-ctr + hmac-sha2-256 (encrypt-and-MAC)

Reaching the encrypted session turned up four protocol facts that are all
easy to get wrong and all fail silently. Each was read out of the OpenSSH C
source rather than inferred from the RFC.

- **The block size for `aes128-ctr` is 16, not 8.** `cipher.c:93` lists
  `{ "aes128-ctr", 16, 16, 0, 0, 0, EVP_aes_128_ctr }` and the second column
  is `block_size`. So padding must make `4 + packet_length` a multiple of
  **16** — i.e. `packet_length ≡ 12 (mod 16)` — while the plaintext phase
  used `≡ 4 (mod 8)`. A hard-coded 8 leaves every post-NEWKEYS packet
  misaligned and the server answers `padding error: need N block 16 mod M`.
  This is why `block_size_of` is a function of the mode and not a constant.
- **`hmac-sha2-256` is a full 32-byte MAC.** `mac.c:62` sets
  `truncatebits = 0`. Plenty of implementations truncate to 16 by mistake
  (conflating it with `hmac-sha1-96`); that simply will not interoperate.
  paramiko agrees — `transport.py` `_mac_info` gives it `size: 32`.
- **The CTR counter is per-connection, not per-packet.** `cipher.c:280-281`
  calls `aesctr_ivsetup` once at NEWKEYS and then `aesctr_encrypt_bytes`
  advances it for the life of the connection. Re-seeding from the IV for
  every packet still produces a byte-correct *first* packet, so the bug only
  shows on packet 2 — which is exactly why the KAT cases emit several packets
  back to back.
- **Non-EtM MACs cover the *decrypted* packet.** `packet.c:1749-1754` passes
  `incoming_packet`, which by then holds the full `4 + packet_length` bytes
  (first block from `packet.c:1687`, remainder appended at `packet.c:1738`).
  The MAC is appended *after* the ciphertext. Verifying before decrypting, or
  over the ciphertext, both produce a stream that decrypts to garbage with no
  error anywhere near the cause.
- **`kex->we_need` is one length for all six keys.** `kex.c:1141-1152`
  computes `max(enc.key_len, enc.block_size, enc.iv_len, mac.key_len)` and
  `kex.c:1155` derives A..F all at that length. For aes128-ctr +
  hmac-sha2-256 that is **32**, not the cipher's 16. The cipher is then
  handed only the prefix it wants (`head_bytes(.., 16)`); passing the full
  32-byte key aborts in `AesCtrMacCtx::new`. This is *not* a bug in the
  pre-existing `derive_keys`, which was already faithful.
- **Strict KEX is off unless the peer advertises it** (`kex.c:963-970`), and
  our proposal does not advertise `kex-strict-c-v00@openssh.com`. So the
  sequence number runs straight through NEWKEYS instead of resetting to 0
  (`packet.c:1376-1379`). Advertising it would change the Loop #31/#32
  transcript and invalidate the 509/753 assertions, so it is a
  transcript-stability choice; `SendCtx`/`RecvCtx` handle either outcome.
- **Sequence numbers must be tracked even in the plaintext phase.** Loop #31's
  hand-rolled packet helpers had no seqnr accounting, which was invisible while
  everything was plaintext — but seqnr feeds the MAC. Driving the whole
  handshake through `SendCtx`/`RecvCtx` fixes it and leaves the wire bytes
  identical (509/753), verified.
- **Packet reads must be exact, never chunked.** Once a packet is consumed the
  next read is for the following message, so a chunked reader blocks waiting for
  bytes nobody asked for. Past NEWKEYS the length is itself ciphertext, so ask
  for it first: `RecvCtx::wire_len_from_header` decrypts the 4-byte header from
  a counter snapshot without mutating state, and the caller then pulls exactly
  `packlen + authlen + maclen` more.
- **`await` is not MoonBit syntax.** Async calls are plain calls; writing
  `await f(x)` gives "The value identifier await is unbound" plus a parse
  error, which reads like a missing import rather than a bad keyword.
- **MoonBit's `String` indexer yields `UInt16`, not `Char`.** A hex parser
  declared as `fn hex_nibble(c : Char)` fails to type-check against `s[i]`.
- **paramiko 5.x has no `Cipher` class** — the framing moved into
  `Packetizer`. `write_all` (packet.py:348-386) calls `socket.send` and its
  bare `except Exception: n = -1` turns a typo in a mock socket into an
  `EOFError` three frames away. `Packetizer._build_packet` uses
  `3 + bsize - ((len(payload) + 8) % bsize)`, which is algebraically identical
  to `SendCtx::emit`'s rule — useful to know, since it is the cross-check.
- **The handshake is not reproducible across connections.** The client pins its
  DH exponent and KEXINIT cookie, but the *server* draws a fresh one per
  connection, so K, the exchange hash and `session_id` differ between any two
  runs. Only framing-level facts (byte counts, block alignment, field shapes)
  are comparable between the native and browser paths — do not assert hash
  equality there.

Run the gate with `node host/verify_loop33.mjs` (`--skip-regression` to skip
the crypto suites). It checks the packet layer against
`host/ssh_ctrhmac_oracle.py` — which refuses to emit vectors until its own
from-spec construction matches paramiko byte for byte, so MoonBit is the third
opinion rather than the first — then drives the native client and the browser
Worker against a real OpenSSH 8.0p1 sshd and requires `SERVICE_ACCEPTED` from
both, with identical byte counts (509/753 for the handshake, 573/817 with the
encrypted exchange).

### Loop #34: RFC 4252 section 7 publickey authentication

The client now proves who it is. A real OpenSSH 8.0p1 server looks the public
key up in `authorized_keys`, verifies the RFC 6979 ECDSA signature over the
RFC 4252 section 7 bytes, and answers `USERAUTH_SUCCESS` — first natively, then
from inside a browser Web Worker with zero native code and zero dependencies.

- **The ECDSA signature blob is two strings, not three fields:**

      string  key_type          "ecdsa-sha2-nistp256"
      string  signature_blob    (mpint r ‖ mpint s)

  This is the bug this loop spent most of its time on, and it is worth
  remembering because *every* local check passed while it was broken:
  `cryptography` verified the `(r, s)` over the exact bytes we sent, our own
  decoder round-tripped it, the KAT was generated from our own encoder and
  matched it, and the RFC 6979 values matched the published ones. Only a real
  server rejected it, with the least informative message in the protocol.

  The reason it hides so well is that an mpint's wire form *is* "length prefix
  + bytes". Drop the outer `string` and you still have `len ‖ r ‖ len ‖ s`, which
  a permissive reader will happily consume — just with the first 4 bytes
  swallowed as the length of `r`, and then no bytes left for `s`.

  Authority, in order of usefulness:
  - `ssh-ecdsa.c:431-432` — `sshbuf_get_cstring(b,&ktype) || sshbuf_froms(b,&sigbuf)`,
    then two `sshbuf_get_bignum2` reads out of `sigbuf`.
  - paramiko `ECDSAKey.sign_ssh_data` — `add_string(key_type)` then
    `add_string(self._sigencode(r, s))`, and `_sigencode` is the two mpints.
  - `src/hostkey/sig_verify.mbt:71-88`, which had it right all along because it
    verifies real host keys against a real server (Loop #31).

  **Lesson: when a blob layout is disputed, ask the implementation that has
  already been proven against a live server in this same repo, before adding
  another oracle.** `hostkey` was the answer and it was sitting one directory
  away.
- **`host/paramiko_blob_capture.py` is the tool that found it.** Patching
  paramiko's `AuthHandler._get_session_blob` dumps the bytes it *actually*
  signs. The first attempt patched `AuthHandler._finalize_pubkey_algorithm` and
  rebuilt the blob by hand — that produced a `pkblob` of 19 bytes (the key type
  only) and looked like a second, unrelated layout bug. A probe that reconstructs
  the blob instead of intercepting it will mislead you exactly when you can least
  afford it.
- **`ECDHSA_ERROR` never says which part was wrong.** OpenSSH's monitor path
  reports one line for both "that key is not in authorized_keys" and "that
  signature does not verify". `AuthError::AuthRejected` therefore carries the
  reason *plus* the signed bytes *plus* the signature, so a second implementation
  can replay the exact failure. Every hypothesis in the investigation below was
  ruled out by re-reading OpenSSH's C against our bytes — the only thing left was
  to compare against a working client.
- **The service name in `USERAUTH_REQUEST` is `ssh-connection`,** not
  `ssh-userauth` (the latter belongs to the preceding `SERVICE_REQUEST`).
  `auth2.c:302` takes it from the request itself, so the two are not
  interchangeable in any way that a live server will point at.
- **The public point Q is one SEC1 `string` (`0x04 ‖ X ‖ Y`),** not two
  coordinate strings and not an mpint. Getting this wrong produces a valid-looking
  key blob that no server will ever accept.
- **`cmd/userauth_test` depends on `src/userauth`, not `src/sshclient`.**
  `src/sshclient` reaches `src/tcp`, which is native-only, so a KAT built on it
  could only ever run on one backend. The section 7 assembly is pure byte work
  over `src/sshwire` and now runs on 4 target × 2 mode like everything else in
  this repo. The two five-line helpers it duplicates (`ascii`, `concat`) are the
  price of not dragging `@tcp` in — moving them into `src/sshwire` would touch
  every byte-exact baseline from Loops #31–#33 to save eight lines.
- **A negative wire test must build the blob in the layout you fixed.** When
  `decode_sig_blob` gained the wrapper, `build_sig` in `cmd/ecdsa_test` still
  produced three flat fields — so every "must be rejected" case kept passing, for
  the wrong reason: it failed at the parse layer, not on the defect it names.
  Silent, green, and worthless. `ecdsa_test`'s output hash moved with this fix
  (`0e3ec3f7e954bd98` → `d78cd820e9ea2317`); the harness re-baselined both
  `cmd/userauth_test`'s `mpint_pair_padded` parser and this one in the same commit.
- **P-256 r and s need a `0x00` sign pad about half the time.** The vector set
  covers 4 of 6 cases, and both sides must agree on the count — a suite that
  never exercises the pad tests only the easy half. Judge minimality by the
  rule, not by the first byte: a padded mpint *must* be followed by a byte with
  the high bit set.
- **A KAT generated from your own encoder cannot catch your own layout bug.**
  `verify_loop34.mjs` therefore re-derives the signed blob from the request
  actually put on the wire, exactly as `auth2-pubkey.c:207-213` rebuilds it, and
  compares byte for byte. That check is local, needs no server, and fails with a
  specific message — which is what turns the next occurrence of this bug class
  from a two-day investigation into a red line.

Run the gate with `node host/verify_loop34.mjs` (`--skip-regression` to skip the
Loop #32/#33 harnesses and the crypto baselines). It re-derives
`cmd/userauth_test/vectors.mbt` from `host/ecdsa_auth_oracle.py` and fails if the
committed copy has drifted, so the KAT cannot be satisfied by hand-editing it.

### Loop #33 review fixes

A review of Loop #33 turned up six items. Three were real defects, and the
other three were the same failure mode wearing different hats: a green check
that could not go red.

- **`recv_packet` collapsed every `PacketError` into `None`.** A MAC mismatch
  therefore looked identical to "the peer closed", so the only symptom on an
  encrypted channel was *waiting for SERVICE_ACCEPT and timing out* — a
  timeout that points at the wrong layer entirely. `recv_packet` and
  `wt_recv_plain_packet` now return `RecvOutcome { Packet, Closed, BadPacket }`
  and carry the `PacketError` label up through `LiveError::BadPacket(String)` /
  `SessionError::BadPacket` / `AuthError::BadPacket`. Both transports share the
  one enum and the one `packet_error_label`, so the browser path cannot invent a
  second name for the same fault.
- **`initial_kex` was never cleared.** `kex.c:567` does
  `kex->flags &= ~KEX_INITIAL` once the first key exchange is done; without it
  the flag stays true forever and every packet keeps evaluating a
  "is this wrap fatal?" branch whose answer stopped being right after NEWKEYS.
  Added `SendCtx/RecvCtx::end_initial_kex` + `in_initial_kex`, called right
  after `set_mode` in both paths, and `src/bpacket/packet_ctx_wbtest.mbt` pins
  the difference: same frame, `Failed(SeqnrWrapInitial)` before the call and a
  cleanly decoded packet after. Verified by mutation — making
  `end_initial_kex` a no-op turns 4 of the 25 tests red.
- **`key_head` printed key material.** It was the first 8 raw bytes of
  `enc_key_ctos` and the first 8 raw bytes of `mac_key_ctos`, hex-encoded —
  32 bytes of live session key into stdout and CI logs on every handshake,
  under a comment reading "does not print raw keys". Replaced with `key_tag`:
  `sha256(key)` truncated to 12 hex chars, `<enc>/<mac>`. Same diagnostic
  value (are the two directions different? did both paths derive the same
  keys?) with nothing recoverable. The harnesses now assert 12-hex halves and
  additionally check the two directions are *not* equal.
- **`head_bytes` / `hex_bytes_head` were duplicated** in `src/sshclient` and
  `src/wtlive`. They are now `pub` in `src/sshclient` and called from wtlive;
  a divergence in "how many leading bytes" would otherwise only bite the
  browser path, with the symptom "the server can't decrypt us".
- **`SentPacket.wire` documented only the AEAD shape** (`ct‖tag(16)`) and
  `emit`'s `pad_src` doc did not mention `MacEncrypt` at all. For the encrypt-
  and-MAC mode both are wrong in ways that read as plausible: the tag is 32
  bytes (`mac.c:62`, `truncatebits = 0` — and 16 is what chacha20-poly1305
  uses, so the wrong number looks right), and padding does come from `pad_src`
  even though the mode is not AEAD.
- **The counter-continuity check was tautological.** See the "cannot fail"
  rule above; it is now three checks, including that the vector set really
  contains multi-packet cases whose packets are pairwise distinct — without
  that, re-seeding the CTR counter per packet is byte-identical to correct
  behaviour on packet 1 and the whole property is untested.

Recomputed baselines: `src/bpacket/pkg.generated.mbti` catches up with Loop
#33's `AesCtrMacCtx` (it was stale because `moon info` aborts on three js-only
`cmd/wt_*` packages that report `Missing main function` under a native check —
generate it per package instead of project-wide).

### Loop #35: RFC 4254 connection layer (channels)

Loops #31-#34 proved we could open an encrypted session and say who we are.
Neither of them touched the connection layer, which is where SSH actually lives:
`ssh host cmd` opens a `session` channel, sends `exec`, and reads `CHANNEL_DATA`
until the peer sends `exit-status`. This loop does that against a real OpenSSH
8.0p1 server, natively and then inside a browser Web Worker.

**Where the protocol lives.** `src/channel` is a separate package with no
dependency on `src/sshwire` beyond the wire primitives and none at all on
`src/tcp`, for the same reason `src/userauth` was split out in Loop #34: a KAT
that can only run where a TCP stack exists is a quarter of the coverage this
repo insists on. Its core is `chan_step(state, msg_type, payload) ->
(new_state, actions, error?)` -- a pure state machine. The transport layers
(`src/sshclient/live.mbt` over TCP, `src/wtlive/live.mbt` over a WebSocket)
only move bytes. That is why "native and browser agree" does not rest on both
being written correctly: the protocol has exactly one implementation.

**Three bugs, all of the same shape.** Every one of them is locally
self-consistent, passes every check that does not require a big transfer or a
non-zero channel number, and is only visible to a real counterpart.

- `maybe_adjust` returned the **incoming** state on the no-adjust path, throwing
  away the window it had just decremented. `local_consumed` therefore never
  accumulated and not a single `WINDOW_ADJUST` was ever sent. Any output that
  fits in the 2 MiB window completes normally, which is every output anyone
  tries first. Found by replaying a 1.5 MiB transcript through the KAT.
- `maybe_adjust` read the amount off the window **after** `take_adjust` had zeroed
  `consumed`, so every `WINDOW_ADJUST` carried 0 bytes. The transfer still runs;
  the window simply never comes back.
- Inbound packets were matched against `remote_id`. RFC 4254 section 5.2 says the
  recipient field of an inbound packet names **our** channel. Both ids are 0 on a
  first channel, so this cannot be observed until a vector uses local=3 /
  remote=7. OpenSSH itself just resolves the id through `channel_by_id`
  (`channels.c:3474 channel_from_packet_id`) rather than committing to one side.

**Two deliberate divergences from OpenSSH**, both documented in place:

- `channel_input_extended_data` (`channels.c:3606`) does a bare
  `c->local_window -= data_len` and nothing else, while `channel_input_data`
  (`:3518-3523`) also does `c->local_consumed += win_len`. So in OpenSSH a peer
  that fills our window with nothing but stderr never gets a `WINDOW_ADJUST` and
  the transfer stalls. `chan_step` runs the same `consume()` on both streams: one
  extra `WINDOW_ADJUST` is always legal, a stall is not.
- A non-stderr extended-data code is dropped without touching window state,
  matching `channels.c:3585-3590`, which discards it before the string is even
  parsed.

**Oracle.** `host/channel_oracle.py` re-derives every value from the C
(`channels.h:231-232`, `channels.c:2440-2465`, `channels.c:3505-3523`,
`channels.c:3126-3135`, `session.c:2344-2347`) and cross-checks its
`CHANNEL_OPEN` / `exec` / `EOF` bytes against a **live paramiko session** before
emitting anything. That cross-check earned its place immediately: its
`CHANNEL_REQUEST` branch had been copy-pasted from the `CHANNEL_OPEN` branch and
parsed the recipient channel number as a string length, so every exec request
parsed to a zero-length request type and was silently skipped. "No disagreement
found" and "we never looked at the right packet" look identical from the outside.

`CHANNEL_EOF` is verified when paramiko emits it but not required -- paramiko
only sends it on the close path, and whether it appeared says nothing about our
layout. A check that goes red for unrelated timing reasons trains people to
ignore it.

**Mutation check.** `host/channel_mutations.py` puts each of the three bugs back
and requires `cmd/channel_test` to notice, then restores the file. A KAT that
stays green under the defects it was written for is not evidence of anything.

Run the gate with `node host/verify_loop35.mjs`. It re-derives
`cmd/channel_test/vectors.mbt` from the oracle and fails on drift, so the KAT
cannot be satisfied by hand-editing vectors; it runs the mutation check; it
compares six remote commands byte for byte against a local run of the same
programs; and it repeats all six inside a browser Web Worker.

One trap worth naming: the remote side is a Windows shell, so `echo` terminates
lines with CRLF. A hand-written `"hello\n"` reference is the wrong expectation and
sends you hunting a bug that is correct behaviour -- it did, once. The harness
reproduces every command locally instead of hard-coding expected bytes.

### Loop #36: interactive session (pty-req / shell / window-change)

Loop #35 ran commands over `exec`, the one-shot form of the connection layer.
An interactive shell is where the rest of RFC 4254 lives, and each piece has a
field that is wrong in a way the server tolerates:

- **`pty-req` puts columns before rows on the wire.** The client writes
  `sshpkt_put_u32(ws.ws_col)` first (`clientloop.c:2739`) and the server reads
  `sshpkt_get_u32(&s->col)` first (`session.c:1872`). Write them the other way
  round and you still get a perfectly valid pty with the dimensions transposed.
- **The terminal modes are wrapped in a `string`.** `ssh_tty_make_modes` does
  `sshbuf_put_u8(buf, TTY_OP_END)` then `sshpkt_put_stringb(ssh, buf)`
  (`ttymodes.c:331-332`), and `ssh_tty_parse_modes` opens with
  `sshpkt_get_string_direct` (`:352`). Leave the wrapper off and the server reads
  the four length bytes as an opcode -- and the pty still opens.
- **`TTY_OP_END` is 0** (`ttymodes.c:60`); `TTY_OP_ISPEED`/`TTY_OP_OSPEED` are
  128/129. paramiko sends an empty modes string, which is also legal
  (`ttymodes.c:354` returns early on `len == 0`) -- which is why the paramiko
  cross-check compares pty-req field by field rather than blob for blob.
- **`window-change` has `want_reply = FALSE` and no modes string.** The server
  reads four u32s and then `sshpkt_get_end` (`session.c:1847-1851`). Wait for a
  CHANNEL_SUCCESS there and you wait forever.
- **`exit-signal` is not `exit-status`.** When the process is killed the server
  sends `string name || boolean core || string language || string message`
  (RFC 4254 section 6.10). A client that only knows `exit-status` reports 255 with
  no explanation.

**A refused pty is not fatal.** OpenSSH clears `client_tty` and carries on
(`clientloop.c:2750`). `chan_step` therefore carries an `interactive` flag: in
that mode CHANNEL_FAILURE only increments a counter, while the `exec` path still
reports `ExecRejected`. The state machine does not track which request a reply
answers, so it cannot decide this -- and guessing wrong makes `ssh -T host`
unusable.

**Two bugs this loop's own tooling had, both from the same cause -- writing a
parser by copying a structurally different one:**

- The oracle's `exit-signal` transcript had a stray 8-byte blob between the
  language tag and the message. It had never been parsed by anything, because
  until now the client ignored `exit-signal` outright.
- The oracle read the signal name as a `u32`; it is a string, and reading the
  length prefix that way reported the signal as `"4"` for a request that said
  `"TERM"`. It also missed the `want_reply` byte, putting the length one byte
  late.

**One driver bug worth naming.** The first wait for CHANNEL_OPEN_CONFIRMATION
was written by reusing the helper that waits for CHANNEL_SUCCESS. The symptom is
not an error -- the server has already sent its confirmation and has nothing
more to say, and the read is blocking, so the client waits forever. Wrong wait
conditions in blocking code look like hangs, not like mistakes.

**Not claimed.** A pty banner from a Windows server carries the OS build number,
ANSI state and a prompt, so it is not reproducible byte for byte. G2/G3 check the
deterministic part -- the echoed command, the exit status, the byte counts, and
native-vs-browser equality -- while the bytes we *send* stay byte-exact against
the oracle and a live paramiko pty session. `host/channel_mutations.py` now
covers ten defects across both loops; every one of them turns the KAT red.

Run the gate with `node host/verify_loop36.mjs`.

### Loop #37: stdin flow control and the `env` request

Two RFC 4254 features every real `ssh` client uses and neither of the last two
loops touched. Both fail **silently**, which is the whole reason they need their
own loop:

- **Sending past the peer's window disconnects the connection** (RFC 4254
  section 5.2), but *under*-sending looks like success. The remote command still
  exits 0, the client still prints `EXEC_DONE`, and only the byte count
  disagrees.
- **`env` is never answered.** RFC 4254 section 6.4 says "No response is
  returned by the server", OpenSSH's client sends `channel_request_start(...,
  "env", 0)` (`clientloop.c:2706`), and paramiko's docstring calls the refusal
  "silent ... common client practice". Three sources agreeing means there is
  nothing on the wire to check -- the only oracle is the remote command looking
  at its own environment.

**The send-side clamp** (`channels.c:3085-3100`), transcribed exactly in shape:

```c
if (len > c->remote_window)     len = c->remote_window;
if (len > c->remote_maxpacket)  len = c->remote_maxpacket;
if (len == 0)                    return 0;
... send len bytes ...
sshbuf_consume(c->input, len);
c->remote_window -= len;
```

Clamp, not error. **A zero-length clamp is not a failure** -- it means the peer
has not made room yet, and the bytes stay in the buffer until a
CHANNEL_WINDOW_ADJUST arrives. `ChanState::stdin_take` returns the unsent tail
for exactly that reason. `stdin_action` is gone: one clamp, one place, and the
interactive shell path now goes through the same function instead of a second
encoding of the same rules.

**CHANNEL_EOF only after the buffer is empty.** `chan_ibuf_empty` returns
without sending when `sshbuf_len(c->input) != 0` (`nchan.c:130-134`). Sending it
early tells the peer the input is finished, and the remote command reads a
truncated stream *without complaining* -- harder to diagnose than a disconnect.
The `exec` path now sends EOF even with no stdin, which is what `ssh -n` does;
without it any command that reads stdin blocks forever, so the bug shows up as a
hang rather than as a wrong answer.

**`env` must go out before `exec`.** `session_input_channel_req` only dispatches
`"env"` while `c->type == SSH_CHANNEL_LARVAL` (`session.c:2175`); after `exec`
the request is dropped without a word, and want_reply is FALSE, so there is no
error either. Exactly two strings, then `sshpkt_get_end` (`session.c:2042-2044`)
-- a trailing field there is `sshpkt_fatal`, not something ignored.

**How the test proves it.** `sshd_setup.mjs` now names `LOOP37_TEST` and
`LOOP37_SECOND` in `AcceptEnv`, so one run covers both branches: the accepted
name arrives, the unlisted one is dropped, and the session completes either way.
For the bulk transfer the remote fixture reports the byte count *and* a SHA-256
of what landed, and `host/stdin_expect.py` computes that digest beforehand from
the same pattern the client uses -- so the comparison is between the far side and
an independent expectation, not between the client and itself. 3 MiB through the
2 MiB default window takes 96 packets and no disconnect.

**Two bugs found by the tooling, both worth naming:**

- `--exec` swallowed the rest of argv, so `--exec ... --env FOO=bar` handed the
  flags to the remote command. The remote ran fine and produced output; only the
  fact that the flags were also in the command string gave it away. Same class
  as the `--shell` bug in Loop #36.
- The KAT's stdin replay **rebuilt** the packets from the clamp, which was the
  point -- but it never checked the buffer that came back on the stall path, so
  the mutation "a stalled stdin went out in full" passed. The assertion that a
  `None` action returns the buffer untouched is now part of both replays.

**Mutation count:** sixteen across three loops, all caught.

Run the gate with `node host/verify_loop37.mjs`.

**Two lessons from Loop #39, both of which cost a red regression run.**

Adding a constructor to `ChanError` (`SubsystemRejected`) turned loop35, loop36
and loop37 red at once, with no change to any of their code. MoonBit treats a
non-exhaustive `match` on an enum as an error, which is the *right* default,
but the blast radius is every `describe(e : ChanError)`-style helper across
`cmd/` and `src/` -- five files, not one. When a loop adds a variant to a
shared error enum, grep for the enum name and fix every match in the same
commit; the regression suite is what found it, and it found it all three times
in a row, which is exactly as noisy as it is useful.

The second is quieter. `host/channel_mutations.py` anchors each mutation on a
literal source snippet, and this loop's edit to the 0x64 branch turned
`      if st.interactive {` into `  } else if st.interactive {` -- so one
mutation became a silent `SKIP` and loop35/36/37 all reported
`all mutations turn the KAT red` as failed while the KAT itself was perfectly
green. A mutation harness treats "the anchor is not where I left it" as a
failure, not a warning, and that is the right default: an anchor that moved
means either the code changed (so the mutation no longer describes anything)
or the harness went stale (so it is not testing what it claims). Either way
there is no reading of it under which it should be quietly skipped.

### Loop #38: real host key algorithms (`ssh-ed25519` + RFC 8332 RSA)

Thirty-seven loops of green, and the client could not talk to a stock
OpenSSH server. Not a subtle failure -- the handshake died outright:

```
client: NoAgreement
server: kex: host key algorithm: (no match)
        Unable to negotiate ... no matching host key type found.
        Their offer: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384
```

The cause was a test fixture, not a protocol gap. `host/sshd_setup.mjs` pinned
`HostKeyAlgorithms` to ECDSA, and `live_proposal()` reported only ECDSA, so the
two always agreed. A server holding the ed25519 and RSA keys that a default
install actually has offered nothing we would accept. The pin made an
incomplete client look complete, and it took a *probe server with the pin
removed* to see it.

**The three names, which is the whole content of RFC 8332.** For RSA:

| what | value |
|---|---|
| the key blob's type string | `ssh-rsa` |
| the negotiated algorithm name | `rsa-sha2-512` |
| the algorithm name inside the signature blob | `rsa-sha2-512` |

All three are in play and the first two legitimately differ. Writing the check
by analogy with `ssh-ed25519` -- "the signature name must equal the key type" --
rejects every RFC 8332 signature, and rejects it as `TypeMismatch`, pointing at
a name that looks perfectly fine. The real test is what
`ssh-rsa.c:526-535` says: the two names must each resolve to a digest, and
**the digests must be equal**. So `src/hostkey` grew
`rsa_digest_of_sigtype` (`:328-338`) and `rsa_digest_of_keyname`
(`:345-359`) as two separate functions rather than one -- collapsing "signature
type" and "key type" into a single table is precisely the mistake RFC 8332
exists to correct.

`ssh-rsa` is deliberately **absent** from the proposal. It maps to SHA-1
(`ssh-rsa.c:331`), which this project does not implement, and OpenSSH 8.8+
disables it by default. Advertising a name we cannot verify would move the
failure from negotiation time to verify time and blame an algorithm that was
never selected. Loop #38's G4 asserts the good version of that: a SHA-1-only
server is refused with `NoAgreement`, not accepted and then failed at the
signature check.

**What else changed.** `src/rsa` takes a digest parameter instead of being
SHA-256-only, and `rsa_verify_pkcs1_prefix` now enforces `RSA_PKCS1_MIN_FF = 8`
(`RFC 8017` §9.2) -- it had been more permissive than OpenSSL. The rule for
left-padding a signature shorter than the modulus (`ssh-rsa.c:549-560`, because
`sshbuf_put_bignum2` strips leading zeros) is transcribed explicitly rather
than left to `RSA_verify`. `agrees_with_alg` and `describe` live in
`src/hostkey`, not in the two drivers: RSA's answer differs structurally from
ed25519's and ECDSA's, and two copies of that rule drift. `live_proposal()`
now reports `ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384`
-- and the client's order is the preference outright (`kex.c:887-890`
`match_list(client, server)`, the rule RFC 4253 §7.1 states).

**A framing detail that a spec reading would have gotten wrong.** The algorithm
name in a signature blob is a length-prefixed `string`, not a NUL-terminated
`cstring` -- OpenSSH's `sshbuf_get_cstring` reads a length-prefixed string and
strips a trailing NUL, and both spellings accept the same bytes. This was not
believed but measured: `host/hostkey_capture.py` interposes on a real
handshake and takes the bytes at the point paramiko is about to verify them.

```
0000000b "ssh-ed25519"  00000040 <64 bytes>
0000000c "rsa-sha2-512" 00000100 <256 bytes>
```

Three of the KAT's vectors are those captures -- bytes an actual sshd put on
the wire over an exchange hash it actually computed. The rest are paramiko
blobs, and every case expected to be `Accepted` is verified raw by
`cryptography` 50.0 before being written out, so the KAT cannot agree that
garbage is valid. Negative expectations are declared per *layer*
(`agree` / `rsa` / `crypto`), because pinning the wrong layer's answer is
worse than pinning none: it keeps passing while the layer that matters is
broken.

**Two bugs the tooling found, one of them a real implementation defect:**

- `rsa_parse_pkcs1_prefix` counted the `0x00` separator as a padding byte, so a
  signature with seven `0xFF` instead of eight was accepted. It was *more*
  permissive than OpenSSL, in the direction that only shows up against a
  deliberately malformed signature. The mutation "count the 0x00 separator as a
  padding byte, which the fix removed" is in the harness and reproduces it.
- The test harness's `waitForLog` read `proc.stdout.data` from a poll loop
  without attaching a `data` handler. Without one the stream stays paused and
  the buffer is never filled, so it timed out on a child that was printing
  exactly the marker it was waiting for. Worth naming because it presented as
  "the sshd did not start" and sent the investigation at the server.

`hostkey_test`'s `t5[5]` was also red before this loop and for an unrelated
reason: `ecdsa-sha2-nistp256` with a name and no fields expects
`UnsupportedType`, but `sshkey.c:2031-2046` looks the name up in the impl table
*before* it tries to parse, so `InvalidFormat` is correct. The test was wrong,
not the code.

**Removing the pin moved four earlier harnesses, and that is the point.**
`verify_loop31/32/33/34` had inherited the ECDSA default silently: loop31
asserts `hostkey_alg: ecdsa-sha2-nistp256` and hand-verifies the server's
ECDSA signature over the exchange hash, and loops 32/33/34 carry transcript
byte counts (`509/753`, `573/817`) that are the sizes of *that* handshake. With
the pin gone they negotiated ed25519 and every constant moved. Each of them now
passes `--hostkey-algs ecdsa-sha2-nistp256` explicitly, which restores exactly
what they were written to test. Relaxing them to accept any algorithm would
have been the tempting move and the wrong one: the constants would have had to
be deleted rather than corrected, and loop31's hand-verified ECDSA signature is
the whole subject of that loop.

`verify_loop31`'s `ecdsa_test` baseline had been stale since Loop #34 (`6f8271b`
changed both `cmd/ecdsa_test` and `src/ecdsa` to add the RFC 6979 user-key
vectors, after the hash was frozen in Loop #31). It was re-baselined, with the
cause named in a comment -- worth recording because it presented as an ECDSA
regression and no ECDSA code had moved.

**Harness:** `cmd/hostkey_test`, 39 vectors (8 key blobs, 16 signatures, 12
PKCS#1 shapes, 3 real captures), green on all four backends in both modes with
byte-identical output. `host/hostkey_mutations.py` carries fourteen
mutations, all caught -- one of them can only be caught as a crash, since
removing the longer-than-modulus check makes the left-pad offset negative and
panics before any verdict is compared. `host/sshd_setup.mjs` grew
`--hostkey-algs` and `--name` so several pinned instances can run at once; the
pin is a test lever again, not a default.

Run the gate with `node host/verify_loop38.mjs`.

### Loop #41: Proton desktop shell (debug console, milestone 1)

`proton@0.3.4` is the GUI framework for a **manual fault-injection console**:
commands that drive `src/sftp`'s `SftpSession` directly -- malformed WRITEs,
wrong request ids, EXTENDED names no server has -- the branches a KAT against
a real well-behaved server never reaches. Not an SFTP file browser: the
browser-Worker gate already proves that path, and a second front end would
prove it again with more code.

**The boundary that keeps it safe: `src/` never imports `@proton`.** Only
`cmd/proton_gui` does. Proton is native-only (`supported-targets: "+native"`,
six packages in lockstep at 0.3.4), and a 0.x GUI framework must not become a
dependency of the 4-target KAT gates. The compiler enforces half of this
itself -- it warns when a package depends on Proton without declaring
`supported_targets` explicitly, which `cmd/proton_gui/moon.pkg` now does.

**The three prerequisites were already on the machine** (installed by the
`moonbit_static_analysis` project): `proton_cli 0.3.4` on PATH, the CEF
runtime in `~/.proton/store/win32-x64/cef-<sha256>-layout-1/`, and the
version-locked `cef_process.exe` helper in `~/.proton/helpers/win32-x64/0.3.4/`.
What was missing was only `moon add moonbit-community/proton@0.3.4` and the
runtime layout beside the built executable.

**What the executable wants at run time, relative to itself** -- derived from
the runtime's own error messages, which name each missing path in turn; this
is the complete list it asks for:

- the CEF **Release** set (`libcef.dll`, `chrome_elf.dll`, `libEGL.dll`,
  `libGLESv2.dll`, `d3dcompiler_47.dll`, `dxcompiler.dll`, `dxil.dll`,
  `vk_swiftshader.dll`, `vulkan-1.dll`, `icudtl.dat`, `resources.pak`,
  `chrome_100_percent.pak`, `chrome_200_percent.pak`,
  `v8_context_snapshot.bin`, `vk_swiftshader_icd.json`) in the exe's own
  directory. **Not `bin\`**: the first run put them in `bin\` because the
  runtime's earlier error text names `bin\libcef.dll`, and the result was
  `0xC0000135` (STATUS_DLL_NOT_FOUND) before `main()` -- the Windows loader
  resolves the import table before any MoonBit code runs, the exe's own
  directory is on the default search path and a `bin\` subdirectory is not,
  and the runtime's `bin\` convention is only its *later* check. The loader's
  rule wins.
- `cef_process.exe` (the subprocess helper, version-locked to the proton
  release) beside the exe.
- `Resources/` (the CEF pak/icu tree) beside the exe.

`host/proton_stage.mjs` does all three from the store, reading the CEF
archive's sha256 from
`.mooncakes/moonbit-community/proton/cef_requirements.generated.mjs` rather
than hard-coding it, so a proton bump takes the script along. Run it after
every `moon build` that removed `_build`:

```
node host/proton_stage.mjs
$env:PROTON_HEADLESS = "1"; _build\native\debug\build\cmd\proton_gui\proton_gui.exe   # smoke, no window
_build\native\debug\build\cmd\proton_gui\proton_gui.exe                               # the window
```

**Verified:** milestone 1 -- window opens (headless run stays alive consuming
CPU through the event loop; visible run opens the window). The 5-step
third-party check ran clean: `.mooncakes` populated, `moon tree` shows all six
packages at 0.3.4, and `src/sftp` checks green on all four targets with the KAT
still passing -- the native-only dependency pollutes nothing.

**Milestone 2 (done):** the command bridge. See below.

### Loop #41-M2: the fault-injection console

Milestone 1 proved a window opens. Milestone 2 gives it something to do: three
application commands bound through `.commands(...)` / `CommandRegistrar::bind`,
each driving `src/sftp`'s `SftpSession` over replies a well-behaved
`internal-sftp` never sends.

**Why a GUI and not another `cmd/sftp_test` case.** The Loop #39 KAT and the
Loop #40 live round trip both prove the happy path against real OpenSSH bytes.
Neither can reach "STATUS before VERSION", "a reply carrying someone else's
request id", "a length prefix over `SFTP_MAX_MSG_LENGTH`", or "an extension
advertised and then refused" -- OpenSSH does not emit those, so no capture
contains them. A fault injector is the only way to hold those branches, and
holding a branch by hand is a console's job. The console is a third *driver*
of the one `src/sftp` implementation, not a second implementation: no byte
assembly of its own, no parse rules of its own.

**The three commands** (`cmd/proton_gui/main.mbt`), each named by
`@proton_contract.command(...)`, each reachable as
`window.__MoonBit__.app.<name>(payload)`:

- `sftp_fault_list` -- the catalogue the page renders its buttons from
- `sftp_fault_run`  -- one scenario, full transcript
- `sftp_fault_all`  -- the whole suite verdict

**The signatures came from `pkg.generated.mbti`, never the README**, same rule
as every other third-party surface here:

```
pub fn[Request, Response] command(String) -> Command[Request, Response]
pub fn[Request : @json.FromJson, Response : ToJson]
    CommandRegistrar::bind(Self, Command[Request, Response],
        async (CommandContext, Request) -> Response) -> Unit raise
```

So a request type derives `FromJson`, a response type derives `ToJson`, and the
handler is `async` and takes the request context first. `moon check` reports
`unused_async` on all three handlers (none awaits; MoonBit would promote a
plain `fn` implicitly) -- the annotation is kept so the declared type still
says what the registrar asks for, with the reasoning in a comment at the
definitions.

**The transport name is derived, never written down.** An application route is
`app:<name>` (`ContractRoute::operation_name`), and the injected bridge
(`bridge_bootstrap.js`) exposes one property per granted op as
`__MoonBit__.app.<name>` -- so neither side assembles the string by hand.

**Ten scenarios, each aimed at a named branch of `src/sftp/session.mbt`:**
STATUS-before-VERSION ignored; wrong request id dropped, session still usable;
DATA where a WRITE expects STATUS (unexpected, handle still closed); EOF as a
WRITE answer (failure, never success); EXTENDED-vs-RENAME chosen by extension
*name* with six extensions advertised and the rename one absent; EXTENDED sent
when it *is* advertised; advertised-then-refused = `OP_UNSUPPORTED` result not a
dead session; over-max length prefix refused before anything is sized from it;
truncated ATTRS fatal; STATUS trailing byte fatal.

**The expectations come from a second implementation.**
`host/sftp_fault_oracle.py` is an independent SFTP client written from the draft
and OpenSSH's error branches with no reference to `src/sftp`. It refuses to
emit the vectors unless its own run of each scenario agrees with a hand-written
expectation. `host/gen_fault_vectors.py` transcribes that JSON into
`cmd/proton_gui/fault_vectors.mbt` (a generated file). This is the repo's
multiple-blind rule applied to fault injection: without it a scenario passes
the moment it agrees with itself.

**The blind check immediately paid for itself:** the oracle's first draft
called an over-max length prefix `framing: BadLength`; `src/sftp` reports
`framing: Unexpected`. The oracle was wrong -- in `src/sftp` `BadLength` is the
*cursor's* "a length field pointed past the end of the buffer" (`proto.mbt`),
a different failure with a different cause, while the framing check rejects a
length that is out of range before any buffer is sized from it. The oracle was
corrected and the distinction documented at both sites.

**The gate drives the real bridge, not the functions.**
`node host/verify_loop41.mjs` runs the oracle, builds, stages CEF, then opens a
**real window** with a CDP endpoint and evaluates
`window.__MoonBit__.app.sftp_fault_all({})` and
`...sftp_fault_run({name: ...})` *in the page*. Calling the MoonBit handler
directly would prove the scenarios and prove nothing about the bridge. The
two environment variables are the ones the source actually reads
(`facade_manifest.mbt`): `PROTON_MODE=dev` (which is what turns debug on) and
`PROTON_REMOTE_DEBUGGING_PORT` -- the port alone is not enough, because
`resolve_remote_debugging` returns Disabled unless debug > 0.

**Verified:** `ALL PASS (22 checks)` -- oracle self-consistency, build+stage,
CDP attach to the real document, `core.invokeOp` present, three granted ops,
both command shapes round-tripping JSON, and all ten scenarios byte-identical
to the oracle (requests, results, done/failed/reason). The extension *names*
are asserted, not just the count, since the names are what decide EXTENDED vs
RENAME.

**Three harness lessons from building it, all "impossible" verdicts:**

1. **`{}` not `null` for a fieldless request.** The registry decodes the
   payload with `@json.from_json(payload_json)` straight into the Request type
   (`core/op_registry.mbt`), and `EmptyRequest` is a fieldless *struct* -- it
   wants an object. `null` is valid JSON and still fails the struct decode, so
   the bridge reported "invalid payload for op app:sftp_fault_all". The page
   and the gate now send `{}`.

2. **Do not filter the CDP target by a guessed URL.** Two versions of the
   readiness check failed as a *timeout*, not as a wrong answer: one attached
   to CEF's `about:blank` placeholder (the bootstrap only runs on the real
   document, so there is no bridge on it), the next matched
   `url.startsWith("proton")` -- and the real URL is `https://proton.localhost/`.
   The wait condition is now the actual precondition: "a page where
   `__MoonBit__` exists and all three ops are functions".

3. **Compare rendered-to-rendered.** The JSON holds a result as a raw tuple
   (`["realpath", "/C:/Users/hp"]`); the bridge returns the rendered form
   `cmd/sftp_test` prints. Comparing them directly produced seven failures
   that looked like protocol disagreements -- `["changed"]` versus `["changed"]`
   is the same answer in two shapes. The gate now renders the JSON with the
   same rules, and -- because that makes a second port of one rule set, which
   is how ports drift -- cross-checks the port against the *generated*
   `fault_vectors.mbt`, so the duplication is an assertion rather than a fork.

5-step third-party check after adding `moonbit-community/proton_contract`:
`.mooncakes` populated; `moon tree` shows it at 0.3.4 in lockstep with the
other five; **`moon.mod` needed the direct edge** -- "the module is in the
global environment" is not "this module may import it", and moon says so
explicitly; `src/sftp` checks green on all four targets; the KAT still prints
`ALL PASS (24 session cases, 7 inbuf cases)`.

### Loop #69: a gate that dies at exit is not a pass, and a red step whose evidence was thrown away is not a bug report

GitHub run `39194939821` was the first run on the Windows runner to get past the
engine's own accounting, and it failed 18 of 47 steps. The interesting part is
not the 18. It is that **the log could not explain them.**

#### Defect 1: the engine keeps 12 lines, so a 928-second failure arrives as a fragment

`ci/ci.py` stored `lines[-12:]` per step and that was the whole record. Measured
on that run: `verify_loop45` burned **928.7s** and the surviving text ended at
`import paramiko`. Every follow-up question -- which fixture, did it build, was
the port taken -- needed a fact that had already been discarded, and the only
way to get it back was another 25-minute run.

This is **Loop #42's defect 3, one level up**. That loop fixed nested gates that
kept a 200-char summary and lost the rest; the fix was to write the failing
child's whole output to disk *at the moment of failure*. The CI engine has been
doing the same discarding ever since, and nobody noticed because a summary is
the right size for reading a green-ish run and the wrong size for reading a red
one.

A failing step now writes its complete stdout to `ci/artifacts/steps/<name>.log`
and `ci.json` carries a `full_log` key pointing at it. Passing steps write
nothing: an artifact full of green noise is an artifact nobody opens. The
workflow uploads the whole directory, not just `ci.json`.

The new self-check case is the one the defect is about -- a step that fails
*after* printing more than 12 lines, asserting the dropped **first** line is on
disk. Checking that a file exists would pass against a 12-line tail that happens
to be written. Engine self-check **24/24**.

#### Defect 2: two environment facts, both of which the workflow asserted were unnecessary

`ModuleNotFoundError: No module named 'paramiko'` and `'cryptography'` account
for ~11 of the 18. The Python MITM peers (`host/*.py`, `host/sftp_mitm.py`) are
not vendored and the runner's Python has neither.

The workflow carried a comment explaining why Playwright browsers were *not*
installed: "the gates that drive a real browser are peer-gates and do not run in
this tier". That reasoning is wrong in the same shape as the comment above it in
the same file -- it assumed a fact about the tier assignment instead of
measuring it. `verify_loop47` is in the **default** tier, reaches Playwright
unconditionally at startup, and takes a different code path when the binary is
absent:

```
Executable doesn't exist at ...\ms-playwright\chromium-1124\chrome-win\chrome.exe
SKIP  the Worker run
FAIL  harness  ReferenceError: Cannot access 'only' before initialization
```

Two lessons worth keeping. First, a comment justifying an omission is a claim
that can rot, and it rotted silently for two runs. Second, **the reason a
comment gave for skipping a step is not evidence that skipping was right** --
that is the whole reason this repository stopped curating lists and started
re-deriving them at runtime.

#### Defect 3: `host/sshd_setup.mjs` knew one developer's install prefix

```js
const SSHD_BIN = 'C:\\Program Files\\OpenSSH-Win64\\sshd.exe';
```

That is the portable Win32-OpenSSH build, installed on the machine these gates
were developed on. A GitHub `windows-latest` runner has the *inbox* Windows
feature instead, at `C:\Windows\System32\OpenSSH`. So every gate that needs a
server (loop31, 40, 47, 48, 50, 51, 54, 55, 62, 65, 66) died on a runner that
had sshd perfectly well.

It now probes three known locations and takes the first that exists, and when
none does it says so once, by name, before spawning anything -- instead of an
ENOENT from inside `spawn`, which reads as a bug in this file rather than as
"this machine has no sshd server".

**A hardcoded absolute path in a gate helper is a claim about the machine, and
the machine is not the repository.**

#### Defect 4: `verify_loop41` printed ALL PASS and then crashed

```
ALL PASS (29 checks)
node : Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), file src\win\async.c, line 76
EXIT=-1073740791
```

Reproduced locally at roughly **1 run in 4**; on run `39194939821` it is why
`verify_loop41.mjs` failed in 2.6s. The cause is a genuine race:
`cleanup()` called `child.kill()`, `cdp.close()` and `process.exit()` with
nothing awaited between them. `kill()` only *requests* termination and
`WebSocket.close()` only starts the closing handshake, so `process.exit()` tore
the loop down while libuv was mid-close on both handles.

`cleanup()` is now async and waits for the socket and the child to actually
close; the tail sets `process.exitCode` and lets the loop drain, with an
unref'd 10s timer as the escape hatch for a handle nobody remembered. Verified
**5/5 clean runs**, but the honest statement is that a race proved by 5 passes
is not proved -- what makes this more than a lucky streak is that the
`process.exit()` that was racing has been *removed*, not merely retried.

**No mutation was added for it, deliberately.** A mutation that reproduces a
1-in-4 race cannot be relied on to fail, and a mutation that cannot be relied on
to fail is worse than no mutation -- it sits in the count looking like coverage.
Same reasoning as Loop #68's deleted `MOON_COVE_REPORT_ENABLED` variant.

#### Still open

`verify_loop57/58/59` (ssh_config) failed on the runner with keywords reported
"not resolved" and one fixture's `IdentityFile` resolving to `/cli/key|/tmp/a`
instead of `/cli/key`. All three pass locally against
`OpenSSH_for_Windows_9.5p2`. `/tmp/a` is a value that exists in
`verify_c/sshconfig/syntax.conf` and in no other fixture, so the runner is
resolving a *different config* than the gate wrote. Not yet understood; the full
per-step output from defect 1 is what will settle it on the next run.

### Loop #70: the rule that was never in the repository, and the guard that was narrower than the failure

Run `39200128854` failed 10 of 47. Six of the ten had one cause, and the cause
was a rule this repository believed it had.

#### The finding: `core.autocrlf` lived in one developer's home directory

`verify_loop67` has guarded line endings since it was written. Its verdict on
the runner was:

```
FAIL  no source file is CRLF where the formatter emits LF
      CRLF files remain: cmd/aes_test/main.mbt, cmd/aes_test/moon.pkg,
      cmd/bench_cached/main.mbt, ... (essentially the whole tree)
```

The rule that should have prevented it was never in the repository. It was:

```
git config --global core.autocrlf false
git config --global core.eol lf
```

**A global git config does not travel with a clone.** Git for Windows defaults
to `autocrlf=true`, so `actions/checkout` on `windows-latest` wrote CRLF over
the entire tree while the developer got LF from the same commit. The gate that
exists to prevent this watched the whole time.

This is Loop #69's `SSHD_BIN` lesson one layer over, and the general form is
worth stating once: **a claim about the machine that is not written down in
the repository is not a rule -- it is a coincidence that happens to hold on
yours.**

#### Six gates, one line ending

| gate | what the run showed | why |
|---|---|---|
| loop67 | whole tree CRLF | the guard, reporting |
| loop57 | `values match ssh -G 0 keyword(s)`, all 8 cases | `src/sshconfig/parser.mbt` has **no `\r` handling anywhere**, so `Host *.example.com\r` matches nothing and the MoonBit side resolved **zero** keywords |
| loop58 | same, 8 of 13 cases | same resolver |
| loop56 | `SHA-1(b'')` failed, `b'abc'` passed | the empty input vector was the one carrying a stray `\r` |
| loop62 | `[7713 vs 7621 bytes]` | 92 bytes = 92 lines' worth of `\r` |
| loop66 | `only 0 entries carry a reason string` | the accept table broke on its reason field |

The loop57/58 shape is the one worth remembering: **the MoonBit side resolved
nothing while `ssh -G` -- C, and therefore tolerant -- answered everything.**
One side all-correct and one side all-empty is a shape only a line ending
produces, and it is worth naming that shape before spending an hour on config
precedence.

loop62 had a second-order effect worth recording: the generator writes in Python
text mode, so on Windows it **rewrote the committed file while asserting the
file was byte-for-byte reproducible**. The gate was modifying the thing it was
measuring.

#### What the fix is, and why it is not `text=auto`

`.gitattributes` pins `eol=lf` rather than relying on `text=auto`. `text=auto`
alone leaves the *checkout* conversion to `core.autocrlf` -- which is exactly
the setting that was wrong. Pinning `eol=lf` makes the working tree LF whatever
the machine's git believes.

`*.bat` is the deliberate exception, and not for looks:
`verify_c/build_poly1305.bat` contains `goto :check`, and cmd.exe label
resolution is not reliable in an LF-only batch file. Normalising those to LF
would have traded a class of CI failures for a class of local ones.

Renormalising then rewrote **9 blobs that were stored as CRLF** -- which is how
they got that way: they were never covered by loop67's guard, because that guard
only looked at `*.mbt, *.pkg, *.moon`. The diff is 4349 insertions and 4349
deletions and is **empty under `--ignore-cr-at-eol`**: the catastrophic-looking
whole-file rewrite that contains no change, which is precisely what loop67's own
comment describes.

#### A guard has to be at least as wide as the thing it guards

loop67's CRLF check was 342 files wide and the failure it exists to prevent
involved 765. It stayed green through all six gates it should have caught,
because every file that actually broke was a file it did not look at.

It now walks `git ls-files` with no extension filter, and **derives its
exceptions from `.gitattributes` rather than restating them**, so the two
cannot drift: add `*.foo text eol=crlf` and the guard learns by reading rather
than by being edited. 765 tracked files, 1 CRLF exception, 3 binary.

The first version of that matcher was wrong in an instructive way: it treated
the `*` in `*.wasm` as a **trailing** wildcard (`p.endsWith("*")`), which matches
nothing, so the check reported a `.wasm` file it had just been told to ignore.
Git attribute globs match by a **leading** star.

**Verified:** `loop70_mutations.py`, 2 CAUGHT / 0 MISSED.

- **M1** -- CRLF in `verify_c/ed25519_ref.c`. Must go red and name the file.
  This is the mutation that *justifies the widening*: the old guard was blind
  to it by construction.
- **M2** -- LF in `verify_c/build_poly1305.bat`. Must stay **green**. Without
  it, an exception list that matches everything would pass a test that only
  proves the guard is on.

#### The evidence chain has a hole at every layer that summarises a child

Loop #69 fixed the engine, which keeps 12 lines. Then run `39200128854` showed
the same disease one level down, in three places at once:

```
verify_loop41          FAIL moon build  Error: failed to run build for target Native
                       -- and not one line of the compiler's complaint
verify_loop55          BUILD FAILED / The system cannot find the path specified.
                       -- the kept line is the batch's own echo, not cl's error
probe_sshd_leak        the sshd never came up -- sshd's own stderr was discarded
                       by `inner.stderr.on('data', () => {})`
```

`host/keep_output.mjs` makes the fix a one-call change: the summary still
prints, the full transcript goes to `.loop70/<label>.log`. Wired into those
three call sites.

Note what loop41's failure actually was: the build died in **3.0 seconds**, so
it could not have been a compile error. Loop #69's libuv race was real and is
reproduced locally at ~1 in 4, but **it is not what CI hit** -- CI hit a build
that fails immediately. Two different defects; reporting only the local one
would have been reporting the one that could not explain the run.

#### Still open, and deliberately not fixed here

- **loop55** -- `The system cannot find the path specified.` Root cause found
  and it is not CRLF: all **9** `verify_c/build_*.bat` scripts begin with
  `set GCC=D:\llvm-mingw\llvm-mingw-20260602-ucrt-x86_64\bin\gcc.exe`. A second
  instance of the hardcoded-machine-path defect, in nine files at once. Loop
  #69 fixed one such path and proved nothing about the other eight.
- **loop41** -- the native build of `cmd/proton_gui`, unexplained until the
  transcript survives.
- **loop65** -- sshd still will not start on the runner; now the starter's own
  stderr survives to say why.
- **loop53** -- `missing .loop53/ca`, a generated fixture that is not there.
- **11 of 44 gates never run on CI at all** (`PEER_GATES`). A quarter of the
  suite is skipped by design, and "skipped by design" is exactly the shape that
  nobody looks at again.

#### Run `39204915519`: 10 failures became 5, and the fix had a hole in it

The CRLF half is **verified on CI, not just locally**. Of the ten failures,
`verify_loop57`, `58`, `62`, `66` and `67` are green. Those were five of the six
CRLF casualties; the sixth, `verify_loop56`, turned out not to be CRLF at all
(its file was already LF; it was taking the first eight lines of a failing
script instead of the last -- see below).

What is left is `41`, `53`, `55`, `56`, `65`.

**The evidence fix did not work, because of where it wrote.** `keep_output.mjs`
put the transcripts in `.loop70/`, and the workflow uploaded `ci/artifacts/`
only. So on the runner the transcripts were produced and then destroyed with
the VM -- which is the exact failure Loop #69 was written to end, reintroduced
one layer down by the layer that was supposed to fix it. The upload path now
names `.loop70/` too.

**`verify_loop56` took the HEAD of a failing subprocess's output.**

```js
bad("python reference", py.text.trim().split("\n").slice(0, 8)...)
```

On the runner that printed eight `pass S1 ... == hashlib` lines out of a script
that then failed. The traceback is always at the end. This is Loop #69's
12-line tail inverted -- there the error was pushed out by volume, here it is
pushed out by choosing the wrong end -- and it now goes through `keep()`.

No mutation was added for either of these two, for the reason Loop #70 already
set out: there is no injection point that makes `knownhosts_python_ref.py` fail
on demand, and a mutation that cannot be relied on to fail is worse than none.

### Loop #71: nine copies of one path, and a rule I wrote down without measuring it

Loop #69 fixed `SSHD_BIN`, one hardcoded machine path. It could not claim that
fixed the class, because the class is "a path that exists on one machine and
is asserted as if it existed on all of them". This loop finds the rest, and
then tries to make the question stop needing to be asked.

#### Nine `build_*.bat`, all with one developer's gcc

```bat
set GCC=D:\llvm-mingw\llvm-mingw-20260602-ucrt-x86_64\bin\gcc.exe
```

On the runner that expands to a path that is not there, and the only line the
gate could show was the batch's own echo:

```
BUILD FAILED
The system cannot find the path specified.
```

All nine now resolve the way `build_poly1305.bat` **already did** -- `where
gcc`, then `where clang`, then fail by name. Which is the point: this was not a
new convention being invented, it was a convention that had been in the
repository the whole time in one file out of nine, and the other eight had not
heard of it.

Measured: `cmd /c build_aead.bat` prints `using gcc`, builds, runs, exits 0.

#### The rule I wrote down without measuring it

Loop #70 added this to `.gitattributes`:

```
*.bat text eol=crlf
```

justified by "cmd.exe label resolution is not reliable in an LF-only batch
file". That claim was assumed. The repository contradicted it immediately:
all nine `.bat` files were already stored as LF, `build_poly1305.bat` already
contained `goto :check`, and it worked.

Loop #71 put a `goto :cc_ready` block into eight more of them, which forced
the question to be asked, and the answer was: **it works**. So the exception
was removed.

Leaving it would have been worse than having been wrong in the first place.
**An exception list is a place the CRLF guard stops looking.** A `.bat` entry
with a false reason is nine files with a permanent blind spot, justified by a
sentence nobody re-reads. That is the same habit this loop exists to end:
writing an assumption down and then treating the writing-down as the proof.

#### `verify_loop71.mjs`: is there another one?

The question Loop #69 could not answer. It does not keep a list of what has
been fixed -- a list goes stale, and a stale list is worse than none. It
**derives** the set of tracked files still containing a machine-specific
absolute path and refuses to pass while that set is non-empty.

Result when it first ran: **45 hits in 16 files.** Loop #71 fixed all sixteen.

| what | files | how |
|---|---|---|
| hardcoded repo root `E:\src\moon\openssh_moonbit` | 9 | derived from `__file__` |
| `verify_e2e.mjs` chromium: user **and** browser revision | 1 | read `LOCALAPPDATA`, list `chromium-*`, newest first |
| `verify_loop60.mjs` OpenSSH-C: already a probe | 1 | declared, not changed |
| `verify_loop39.mjs` realpath `/C:/Users/hp` | 1 | compared against this machine's `USERPROFILE` |
| `sftp_fault_oracle.py` synthesised `/C:/Users/hp` | 1 | declared: synthesised payload, chosen for its shape |
| `cmd/sftp_test/vectors.mbt`, 26 captured paths | 1 | declared: captured wire bytes, byte-compared against an oracle |
| `setup-moonbit/action.yml` `C:\Users\runneradmin\.moon\bin` | 1 | `$env:USERPROFILE\.moon\bin` |

The last one deserves a line of its own. It worked because GitHub's Windows
runner account happens to be named `runneradmin` -- the single most
implementation-detail thing about a runner, and exactly the kind of fact that
changes without warning.

**`verify_loop39` got stronger, not just portable.** The old assertion was
"the realpath equals this developer's home". paramiko's `normalize('.')`
resolves the *process's own* home, so the honest expectation is not a literal
at all. It is now "whatever this machine's home is, in the shape sftp converts
it to" -- and an unset `USERPROFILE` shows up as a mismatch with both sides
printed, rather than as a silent pass on someone else's computer.

**The two exemptions are not laziness.** `vectors.mbt` holds request bytes
captured from a live OpenSSH 8.0p1 `internal-sftp` session, compared
byte-for-byte against an independently written oracle. Rewriting those paths
would not make the vectors portable; it would make the comparison
meaningless. And `sftp_fault_oracle.py`'s value is *synthesised* -- the client
receives it and echoes it back, both sides in one file, so it cannot drift. It
is a placeholder exactly like `does-not-exist.bin` next to it.

Exemptions are declared in the file that needs them, with a reason, and a bare
marker with no reason **fails**.

#### The gate's own bugs, all found by its own tests

Four, and every one of them would have made the gate worse than useless:

1. `https://example.com` contains `s:/`, which matched `[A-Za-z]:[\\/]`
   exactly -- so the gate flagged a machine path in front of **every URL in the
   repository**. Fixed with a lookbehind.
2. `'/C:/' + home` is a *prefix*, not a path, and matched because zero
   characters after the separator were acceptable. Fixed by requiring one.
3. `stripComments` deleted multi-line block comments, so line indices drifted
   and the "refusing to guess" guard fired on **622 of 765 files**. Fixed by
   blanking comment characters and keeping their newlines.
4. The first exemption heuristic tried to *infer* "probe list" from the text
   ("is this an array element?", "does the file mention `where`?") and its own
   exclusion test failed on the very case it was written to allow. Replaced
   with a marker that has to state its reason.

A gate that cries wolf on its own header is a gate that gets switched off, and
a heuristic that misclassifies a file that is already correct makes its
silence untrustworthy. The exclusion tests exist for that, and they are the
only reason these were caught before CI.

The exemption window is not a taste decision either. It was 4, then 8, and
each time the gate complained about a file Loop #69 had already fixed. It is
now **measured against the tree** and asserted: "the widest legitimate
exemption needs 10 lines, the window is 12."

**Verified:** `9/9`, 768 files scanned, 0 hits. `loop71_mutations.py`,
**3 CAUGHT / 0 MISSED**:

- **M1** a hardcoded gcc path returns to `build_aead.bat` -- must go red and
  name the file. This is the exact shape that made loop55 fail on CI, put back
  where it was found.
- **M2** a bare `machine-path-exempt` with no reason -- must go red. The
  escape hatch used as a mute button.
- **M3** a justified probe list -- must stay **green**. Without it, "passes
  everything" is equally consistent with "flags everything", and M1 and M2
  would prove nothing about the steady state.

M2 reported MISSED the first time, and the reason was in the harness rather
than the rule: the scratch file was never `git add --intent-to-add`ed, so
`git ls-files` did not list it and the gate was never asked. **A mutation that
fails to set up its own preconditions is not evidence about the thing under
test.**

#### Two findings this loop did not fix

- **`gen_hostkey_test.py` and `gen_kexflow_test.py` no longer reproduce their
  committed outputs.** Running them and then `moon fmt` -- exactly what
  loop56's drift check does -- produces a diff that *deletes a hand-written
  comment* explaining that a peer may offer MAC names the client cannot run,
  which is Loop #60's invariant in prose. The generated output also drops the
  `@kexflow.` qualification. The files were restored rather than committed.
  `gen_knownhosts_test.py` is honest: byte-identical after formatting.
  So the drift check exists for one of three generators. **This is worth its
  own loop**: the fix is to teach the generators to emit what the hand-edits
  added, or to move those comments somewhere a generator cannot eat.
- **loop41, 53, 56, 65 are still unfixed on CI.** `.loop70/` reached the
  runner this time (`include-hidden-files: true`; before that,
  `upload-artifact@v4` skips dot-prefixed paths by default and
  `if-no-files-found: warn` stayed quiet because `ci/artifacts/` matched), so
  the next run should finally carry the transcripts.

### Loop #72: three runner prerequisites, and a gate that was measuring its own documentation

Run `39218394411` failed 5 of 48. One of the five was
`verify_loop71.mjs` -- the gate Loop #71 shipped, written specifically to
prevent a class of defect, failing at a class of defect. That is the headline.

#### What the evidence finally said

Loop #71 made `.loop70/` reachable (`include-hidden-files: true`), so for the
first time the transcripts survived the runner. Every one of the remaining
failures became a specific fact instead of a shape:

| gate | the fact |
|---|---|
| loop55 | **green** -- the nine `where gcc` fixes work |
| loop41 | `cl.exe ... -IC:/Users/runneradmin/.proton/store/win32-x64/cef-169847f3...-layout-1/sdk` then `fatal error C1083: Cannot open include file: 'include/capi/cef_browser_capi.h'` |
| loop56 | `UnicodeEncodeError: 'charmap' codec can't encode character '\u2260'` at `knownhosts_python_ref.py:605` |
| loop65 | the inner transcript was 65 bytes: `STARTER: port never opened`, stderr empty |
| loop71 | `EXEMPT_WINDOW is 12 but someexemption in the tree needs 31 lines` -- no file named |

#### 1. loop56 died printing `!=`

Twenty-nine self-checks passed, then the thirtieth took the process down: the
check name contains a not-equal sign, stdout is cp1252 on a Windows runner,
and cp1252 has no U+2260. Nothing about known_hosts was wrong. **The console's
code page had the last word on whether a self-check counted as a pass.**

Fixed in two places, deliberately:

- `verify_c/knownhosts_python_ref.py` reconfigures its own stdout to UTF-8
  with `errors='replace'`. The `replace` is the load-bearing half: with it, a
  stray character in a future check name degrades to `?` in the log instead of
  turning 29-of-29 into a crash on the 30th. **A reference implementation that
  dies while REPORTING its result is reporting the console, not the protocol.**
- the workflow sets `PYTHONIOENCODING=utf-8` for the whole tier, which covers
  the other eight Python references rather than the one that was observed.

Proven by running it with `PYTHONIOENCODING=cp1252` forced: exit 0. The
reconfigure overrides the hostile console rather than trusting the caller.

This is the third time this Windows console-encoding trap has appeared in this
project, in three different layers. The first two are recorded in Loop #42.

#### 2. `verify_loop71` was measuring itself

The failure said an exemption needed 31 lines and named no file. Two defects,
and the first is the reason the second took a run to find.

**The message could not name its own subject.** That is the exact defect
Loop #70 fixed in `verify_loop41` -- a failure whose detail does not say which
file -- reintroduced two loops later, in a gate written to prevent it.
`windowNeededFor` now returns `{file, needed}` and the assert names both the
file and the distance.

**Once it could name itself, it named itself.** The gate contains the strings
it looks for: its exclusion fixtures hold `'C:\\Program Files\\OpenSSH-Win64'`
and a bare `machine-path-exempt`, so the marker regex matched the gate's own
header comment and the lookahead then found a drive letter 59 lines below, in a
test case. On the CI checkout the same arithmetic read 31; locally it read 10
earlier in the loop and 59 later, purely because I had added test cases in
between. **Two numbers, same bug, and the difference was my own editing.**

Fixed three ways, each of which was necessary:

1. the marker regex is anchored to the start of a comment token, so prose that
   merely *mentions* the marker is not a marker;
2. `SELF_EXCLUDED` is a **named** list with a reason attached -- the gate
   itself, and `loop71_mutations.py`, whose M1 plants a hardcoded gcc path in
   order to prove the gate can fail. A gate's fixtures must contain what the
   gate hunts for, or the exclusion tests cannot be written;
3. **the exclusions are printed on every run, with their reasons, and a
   listed-but-absent file fails the gate.** A silently-skipped file is how a
   gate quietly stops working; adding to this list is a reviewable act with a
   stated justification, which is the entire difference between it and a
   whitelist someone added to turn the build green.

Anchoring alone did not fix it: the next run immediately flagged
`host/loop71_mutations.py`, which is the same problem one level out.

#### 3. The third "obviously already installed" prerequisite

`moon update` fetches the mooncake. It does not fetch CEF. On this machine the
CEF store exists because **another project** put it there -- AGENTS.md records
that the prerequisites came from `moonbit_static_analysis`, not from this
repository -- so the workflow step was written from a machine that had been
pre-provisioned by something outside it.

paramiko, then Playwright, then CEF: three runner prerequisites in three loops,
each one "obviously already there" and each one not there. The CI environment
is a machine nobody has set up, and the only reliable way to know what it needs
is to let a run fail and read what it said.

The command is `proton_cli cef setup`, read from `proton_cli cef --help` rather
than guessed. There is no `--dry-run`, so it runs only in CI, never locally.

**And the first version of that step was wrong in a way worth recording,
because it is the same mistake this file keeps making.** It asserted that
`proton_cli.exe` ships with the MoonBit CLI and lives in
`$env:USERPROFILE\.moon\bin`, and failed the workflow if the file was not
there. Run `39230209722` answered in one second:

```
Write-Error: proton_cli.exe not found at C:\Users\runneradmin\.moon\bin\proton_cli.exe
  -- it ships with the MoonBit CLI install.
```

The error message repeated the assumption as its own justification. That is the
shape to watch for: a check whose complaint is a restatement of the thing it
never verified.

What the toolchain actually does, each part read rather than remembered:

- `https://cli.moonbitlang.com/install/powershell.ps1` fetches
  `moonbit-latest.zip` and `moonbit-windows-x86_64-dev.zip` and extracts them
  into `.moon`. Neither archive contains `proton_cli.exe`. `moon --help` has no
  `proton` subcommand. **The Proton CLI is not part of the MoonBit CLI
  distribution.**
- It is a **registry package**. `moon view moonbit-community/proton_cli` ->
  `0.5.0`, repository `github.com/moonbit-community/proton/tree/main/cli`.
- The published Proton README says
  `moon install --path cli --bin target\proton-tools`. That line is wrong:
  `moon install --help` has no `--path`. The real signature is a positional
  `SOURCE` (`user/module/pkg[@version]`) plus `--bin DIR`. Copying the README
  would have failed on the runner for a different reason and cost another run.
- `justjavac/proton_cli` -- the name in that README -- is **deprecated**;
  `moon view` says so and names `moonbit-community/proton_cli` as the
  replacement.

So the step installs it, and does not name the file it expects:

```
moon install "moonbit-community/proton_cli@0.3.4" --bin "$env:USERPROFILE\.moon\bin"
```

**Pinned, and the pin is load-bearing.** `proton_cli cef requirements` on 0.3.4
prints:

```json
{"proton_version":"0.3.4","platform":"win32-x64",
 "cef_archive":"cef_binary_150.0.19+gcf60f42+chromium-150.0.7871.252_windows64_minimal",
 "cef_sha256":"169847f3d000ded924c619e4d2d042ca3c44d2a5a0398dfdf521c70d34739761",
 "layout_version":1}
```

`169847f3` is the sha in the original C1083 failure text. A floating
`@latest` would install 0.5.0, which requires a different CEF archive, and the
CLI and the build would then disagree about which CEF this is -- the same "an
untrue declaration" shape that Loop #68 and Loop #66 both had to chase. The pin
is not taste; it is the only thing that keeps the two halves agreeing.

Then the step verifies the outcome instead of trusting the exit code: it re-reads
`cef requirements`, reconstructs the layout path from what the tool said, and
fails if `sdk\include\capi\cef_browser_capi.h` is not there. A green
`cef setup` that installed the wrong archive would otherwise become a C1083 four
steps away in a different file.

The binary's own name is discovered with `Get-ChildItem -Filter 'proton*.exe'`
rather than written down, because the README calls it `proton` and the file that
appears is `proton_cli.exe`. Naming it would be a guess about a filename, in the
one step whose entire subject is a toolchain component that was not where the
previous version said it was.

#### 4. The evidence chain had a fourth hole

`sshd_setup.mjs` prints exactly why it could not start. The transcript held:

```
exit 1
--- stdout ---
STARTER: port never opened
--- stderr ---
```

Empty. The culprit was `stdio: 'ignore'` in `probe_sshd_starter.mjs`, copied
from `verify_loop40` "to be faithful". It was faithful to one thing nobody
wanted: Loop #69's `no sshd.exe in any of: ...` was being discarded one layer
further down, by a file whose entire job is to explain why.

Capturing the child's streams does not change what is measured. The leak
depends on `detached: false` and `child.unref()`; `stdio` decides who READS the
output, not whether the sshd survives its parent. So this is not a deviation
from the reproduction -- it is the reproduction, with the explanation attached.

Forwarded rather than buffered, deliberately: a pipe nobody reads fills and
blocks the child, which would turn "sshd said something" into "sshd hung", a
second and much worse lie.

**Four loops, four layers, one habit.** Loop #69 (engine keeps 12 lines), #70
(`.loop70/` outside the upload path), #71 (dotfiles skipped by the uploader),
#72 (`stdio: 'ignore'` in the probe). Each time the fix was correct and the
plumbing ate it, and each time the failure was invisible because the thing
doing the hiding was the thing reporting the symptom.

**Verified locally:** loop56 41/41, loop65 25/25, loop71 9/9.
`loop71_mutations.py` re-run after the exclusion changes: **3 CAUGHT / 0
MISSED** -- M1 plants into `build_aead.bat`, which is not excluded, so the new
exclusion list did not accidentally blind the mutation that proves the gate
works.

#### And two defects this loop's own change introduced, found while committing it

Neither was caught by a gate, which is the point of writing them down.

**The tally was printed before the thing it tallies.** The exclusion block --
the one that pushes a FAIL when an excluded file has stopped existing -- sat
*below* the `loop71: 9/9 checks passed` line. On the day an excluded file is
deleted, the run prints the count, then prints the exclusion list with `GONE`
next to it, then prints a FAIL, then exits 1. Every line is true and the first
one is the lie a reader sees first. Anything that can add a result has to run
before the number that counts results; the block moved above it.

**A helper written for behaviour that was implemented somewhere else.**
`excludedFilesIn()` was added alongside the exclusion change with a comment
describing exactly what the block below it already did, and nothing called it.
Dead code carrying a comment that explains live code is worse than no comment:
the next reader has two places to look and no way to tell which one runs.

Both of these are the same species as the four above them -- a report that is
accurate about itself being wrong about something else.

### Loop #68: the last red row was two untrue declarations, and a third failure that was this repository's own build cache

`test-coverage` had been red for about a dozen loops. Loop #67 pinned the
mechanism -- `moon coverage analyze` has no `--target`, so it builds the whole
workspace for the DEFAULT target, and a js-gated `main.mbt` is not there -- and
recorded it as structural. The structural part was true and is still true. What
was on top of it was not.

There were three things stacked here, and the third was the expensive one,
because for most of this loop it looked like a property of the toolchain:

1. **Seven `cmd/` executables under-declared their target**, and
   `cmd/ssh_live` declared nothing at all while building on native only. Both
   are untrue statements about the repository, and both are fixed below.
2. **`moon coverage analyze` has no `--target`.** Real, structural, and
   unchanged. It is why a workspace-wide walk at the default target is the thing
   that surfaces the other two.
3. **A stale instrumented `_build`.** This one produced
   `conflicting trace metadata` for three packages and an OCaml assertion
   failure, neither of which had anything to do with the code. It is also what
   made steps 4 and 5 of the recipe below look mandatory when they are not, and
   it survived three refuted hypotheses and a lot of confident writing before
   the mutations caught it.

#### Two declarations were untrue, and `moon coverage analyze` was the instrument that caught them

The combine step walks every package in the module. Seven executables gated
their only source file with

```moonbit
options(
  targets: { "main.mbt": [ "js" ] },
)
```

which is a **file** filter, not a package declaration: on every other target the
package still exists, it just has no `main.mbt` left, and the compiler answers
`[4067] Missing main function in the main package`.

And `cmd/ssh_live` declared **nothing at all**, while building on native only.
That one was never a gate artefact -- seven real errors, every one of them true:

| target | `moon check -p cmd/ssh_live` |
|---|---|
| native | 0 errors |
| js | 8 |
| wasm | 7 |
| wasm-gc | 9 |

`cmd/ssh_live` consumes `src/khfile` and `src/tcp`, both native-only, so
`@khfile.append_terminated` and `@khfile.AppendResult` do not exist anywhere else.
Every gate had missed it because the gates only ever asked whether a package
builds on the target it was built for.

The fix is the form `cmd/proton_gui` and `cmd/sftp_mitm` already used:

```moonbit
options(
  supported_targets: "+js",
)
```

Measured, not assumed: a package that declares `supported_targets` and is asked
for a target it does not support **refuses**, exiting non-zero with **zero
diagnostics** -- a declared impossibility rather than a surprise. Neither
`proton_gui` nor `sftp_mitm` ever appeared in the combine run's output. The
controlled proof was converting `cmd/wt_ssh` alone: its `[4067]` disappeared
while the other six stayed.

**The per-file `targets:` form is still correct under `src/`, and this loop did
not touch it.** `src/khstore/moon.pkg` and `src/khfile/moon.pkg` say why: a
package-level declaration would block downstream consumers, so a wasm-wanting
consumer fails loudly at its own compile instead of silently inside the library.
`cmd/` packages are leaves -- nothing imports them -- so the reason does not
apply and only the honesty does. `verify_loop68.mjs` asserts both halves, so the
library rule cannot be quietly relaxed later.

`host/patch_target_decl.py` applies the conversion and then **checks every
package against all four targets** instead of trusting its own edit. Ten
packages declare a target; all ten build on exactly that one.

#### The recipe is one command, and both obvious additions turn out to be unnecessary

**`moon clean` first. That is the whole recipe.** It is worth saying why,
because each of the two steps people reach for next looks load-bearing and is
not, and each of them cost this loop real time before the mutations caught on.

1. **`moon clean`.** The dirty state it removes produces *two* errors that read
   like toolchain limitations: `conflicting trace metadata` for three packages'
   worth of "this can never be reported", and an OCaml assertion failure. Both
   are the same cause. Wiping `_build` fixes both -- see the next section.
   `moon coverage clean` does **not** substitute for it: that removes the dump
   files (28 of which had accumulated here) and leaves the conflict in place.
2. **`MOON_COVE_REPORT_ENABLED=1`.** **Not needed.** `moon coverage --help`
   advertises it, and the default OCaml `moon_cove_report` does die on an
   assertion inside `output_no_intermediate` (`moon_cove_report.ml:220291`) --
   against a dirty `_build`. Against a clean one it exits 0 and prints the same
   report: `src/kexflow`, 73 `<-- UNCOVERED` markers against `Total: 73`, in 15
   seconds, which is the same report the wasm reporter produced for that
   package. (No speed claim is made here: the two were timed in different build
   states, and comparing them would be exactly the kind of measurement this
   section is about not inventing.) The env var was a workaround for a symptom
   of the thing above.
3. **~~`moon coverage clean` between packages.~~ Not needed.** `moon clean` has
   already done everything it does. Deleting it changes nothing measurable.

`moon clean` is the reason `host/cov_report.py` exists at all: `ci/qa.py` cannot
set an environment variable (`_run_argv` inlines the environment) and a bare
command line cannot run one thing and then another, so the qa row is a script.
`host/cov_probe.py` and section C of the gate do the same clean for the same
reason.

#### What it measures -- and the one measurement in this loop that was wrong

15 of the 17 `src` directories holding a test driver produce a real,
source-annotated report: **463 uncovered lines** measured in total, every report
cross-checked so that the number of `<-- UNCOVERED` markers on the annotated
source equals the `Total:` the reporter claims. A number on its own would not
notice a dropped or duplicated line.

The two that do not are both explained, and neither is a toolchain limit:

- `src/khfile` -- `no coverage source data`. Its only test file is gated to
  native (`targets: { "store.mbt": ["native"], "store_test.mbt": ["native"] }`,
  for the library reason above), and `moon coverage analyze` runs at the
  DEFAULT target with no `--target` flag to change that. So its tests are never
  compiled by the command that wants to report on them. This is the honest
  residue of the missing flag, and it is the only package in the tree it costs.
- `src/test_nested` -- the same message, for a boring reason: it has no
  `moon.pkg` at all. It is a fixture directory holding one `nested_test.mbt`,
  not a package.

**A third entry in the earlier, longer list was this loop's own build cache.**
For most of this loop the answer was 13 of 17: `src/bpacket` and `src/hmac`
failed with

```
error: conflicting trace metadata for file id '.../src/bpacket$chacha_api'
```

which reads exactly like a toolchain limitation, and two plausible mechanisms
were tested and refuted on the way -- "a package with two test drivers" (nine of
the reportable packages have both a blackbox and a whitebox driver) and "a file
id present in more than one dump" (`src/aead` and `src/sha256` have every key
in more than one dump and report cleanly). The thing that finally broke it was
not an experiment at all. In the harness's **first draft**, three mutations --
one deleting a `moon coverage clean`, one dropping an environment variable, one
changing a package list -- reported **the same single FAIL line**:
`newly reportable: src/bpacket,src/hmac`. Three unrelated mutations cannot
produce one identical unrelated failure. The gate was not catching them; it was
failing for an environmental reason on every run and the mutations were riding
on it. (The first-draft M3/M4/M5 are not the M3/M4/M5 in the shipped file --
that is the point, and the reason is in the harness docstring.)

Confirmed three ways, in this order:

1. A sandbox, which has no `_build` at all, reports both packages fine.
2. `moon clean` in the working tree, then the same command: `src/bpacket`
   exits 0 with `Total: 66 uncovered line(s) in 11 file(s)`, in 31 seconds.
3. Reproducing the suspected cause *fails* to reproduce it: a standalone
   `moon test --enable-coverage -p src/bpacket --target native` followed by
   `moon coverage clean` and a re-analyse still reports cleanly, so the stale
   thing is not the dumps and not the extra test run.

`moon coverage clean` removes the dump files and leaves the conflict exactly
where it was. Only `moon clean` clears it. So `host/cov_report.py`,
`host/cov_probe.py` and section C of the gate all begin with `moon clean`, and
that line is what makes the committed `host/cov_reportable.json` a statement
about the repository instead of a statement about whoever ran it last.

`host/cov_conflict.py` exists so the next person does not have to re-derive this
from scratch: it reports, for every file id carried by more than one dump, which
dumps hold it and how their counters differ.

#### The gate derives the answer instead of listing it

`host/verify_loop68.mjs` keeps **no** list of which packages should be
reportable. It re-runs the toolchain over every `src` package with a test driver
and compares the result against the committed `host/cov_reportable.json` **in
both directions**. A package that silently becomes unreportable fails, and so
does one that silently becomes reportable -- the second is Loop #66's accept
table lesson: a gate that only notices new problems is a gate whose evidence has
stopped being checked.

Section A2 is the check that closes the hole the rest of section A leaves. The
declared-package matrix only inspects packages that already declare something, so
deleting `cmd/ssh_live`'s declaration would just drop it off the list. A2 asks
the workspace-wide question instead -- `moon check` at the default target must
report **zero `Error: [NNNN]` lines** -- and that is the very observation that
found the bug. It is asserted on the error count and *not* on the exit code: a
package that correctly refuses an unsupported target exits non-zero with no
diagnostics at all, so an exit-code assertion would be demanding the workspace
build on the target it was told it cannot support. This is Loop #67's
`evidence_targets` lesson wearing a different hat -- silence is the healthy state
here, and a package that failed to compile must never be read as a clean one.

`host/loop68_mutations.py` runs 7 mutations, each one a **reversal of a fix this
loop shipped** rather than a synthetic defect: the per-file gate restored, the
`ssh_live` declaration deleted, a declaration pointed at the wrong target, the
library-side gate that this loop deliberately left alone removed, the qa command
aimed at the one package whose tests can never be covered, and the committed
evidence edited in each of the two directions. The question a mutation answers
is never "can this gate see an arbitrary bug" but "would it have seen the thing
that was actually wrong here".

**Result: `mutations=7 CAUGHT=7 MISSED=0 BUILD-BROKEN=0`.**

**The mutations earned their keep twice, and both times by failing.**

The first time, in the harness's first draft, M3, M4 and M5 -- a clean call, an
environment variable and a package list, nothing to do with one another --
reported **the same single FAIL line**:
`newly reportable: src/bpacket,src/hmac`. Three unrelated mutations cannot
produce one identical unrelated failure, so the gate was not catching them; it
was failing for an environmental reason on every run and the mutations were
riding on it. Without looking at *which* check fired, M3 through M7 would have
been recorded as five comfortable CAUGHTs and a stale `_build` would have
shipped as a permanent claim about the toolchain.

The second time, two mutations came back **MISSED** and both were right to.
Deleting the per-package `moon coverage clean`, and separately dropping
`MOON_COVE_REPORT_ENABLED=1`, each changed nothing -- because `moon clean` has
already done the work of both. Those two were written, run, judged and then
**deleted from the set**, and the reason is recorded in the harness rather than
quietly dropped. A mutation that provably cannot fail is worse than no
mutation: it sits in the count looking like coverage of the recipe and it trains
the reader to trust a number that means nothing.

#### Two gates of older loops needed updating, and neither update was optional

Making the row green was the easy half. Two older gates then went red, and both
had been written to assert something that is no longer true. The interesting
question is not that they went red -- it is which direction they were wrong in.

**`verify_loop67.mjs` asserted that the evidence must name
`combine_coverages`** -- the OCaml function inside the reporter whose source line
had been read in Loop #67 to find the failure. Loop #68 fixed the blocker, the
evidence stopped quoting that function, and the gate went red on a row that is
now GREEN. That is a stale assertion, not a regression, and the right fix was to
assert the part of the story that has not changed (the row must still say the
combine walks the whole workspace at the default target) rather than to quote the
old prose back. Asserting the name of a function inside someone else's
implementation would have meant the fix had to keep naming it forever.

Then the same check failed a second time, on a claim that was present and
correct. `ci/qa.py` builds each evidence block by concatenating adjacent string
literals, so the **source** reads

```python
"...has no "
"--target, and src/test_nested..."
```

and a literal search for `no --target` in the source text misses, because the two
halves are separated by `" "`. The check was reading the spelling of the
evidence rather than the value, and it had only been passing by luck of where the
prose happened to wrap. It now joins the literals the way Python does before
looking for anything. Same rule as everywhere else in this file: assert the
property, never the formatting of the source that happens to spell it.

**`verify_loop65.mjs` failed for real, and not because of anything this loop
changed.** Its sshd-leak probe waited a flat `setTimeout(1500)` after the owner
process exited, then asked once whether the port was still bound. Under a full
CI run that guess was wrong:

```
FAIL  the probe cleans up after itself  [self-cleanup by this probe: FAILED, port still bound]
```

Standalone, minutes later, the same gate passed 25/25 with no sshd process left
behind. A check that fails under load and passes when idle is a flaky check, and
`moon clean` -- which Loop #68 puts at the head of the coverage recipe, making
every run start cold -- is exactly the kind of load that exposes one. The probe
now asks the question that matters: has the port been free *continuously* for a
settling window, rather than was it free at one instant after a guessed delay.
Three consecutive standalone runs: 25/25.

Two lessons, both about what a green gate is made of. A gate can be red for a
reason that has nothing to do with the code it inspects, and the way to tell is
to run it alone -- a failure that disappears when you stop running everything
else is a timing bug until proven otherwise. And a gate whose failure text names
no file is a gate that will cost an hour next time; `host/cov_report.py` now also
writes its reason to **stderr**, because the CI engine keeps only the last 12
lines of output and a coverage table is longer than that, which is exactly how an
earlier run of this loop showed a table of successes and the bare words
"exit 1" with no indication of what had gone wrong.

### Loop #73: a failure that named its own source file, and the two situations it could not tell apart

Loop #72's four fixes verified green one by one. The full local CI then came
back 47/48 with the single failure in `verify_loop68.mjs` -- a gate from four
loops earlier, on a code path Loop #72 never touches. It is worth separating
that off from #72 and looking at on its own, because it is the same shape of
defect this project has now hit three times: **a catch-all that cannot say
which of two very different things happened.**

#### What the run said

```
reportable: 14/17
  not reportable: src/aead  --  Called from Moon_cove_report in file "moon_cove_report.ml", line 223726, characters 2-9
FAIL  committed reportable set matches what the toolchain does now
      -- no longer reportable: src/aead
```

and then, in the very next section, on the very same tree:

```
D. PASS  host/cov_report.py -- the qa command -- exits 0  --  15/15 packages reported
```

Both cannot be right about `src/aead`. Standalone it passed 36/36, and so did
`--only loop66,loop67,loop68`. It needs the full 22-65 warm-up and a loaded
machine, which is to say it is not reproducible on demand -- the hardest kind
of failure to argue about and the easiest kind to write down wrongly.

#### The reason on that line was the reporter's own `main` frame

`moon coverage analyze -p src/khfile`, on a clean `_build`, prints:

```
Fatal error: exception Failure("Error: No coverage source data found, maybe you
forgot to run `moon test` with `--enable-coverage`, or the package name
`src/khfile` is incorrect?\n")
Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
Called from Moon_cove_report.Coverage_collection.combine_coverages in file "moon_cove_report.ml", line 223261, ...
Called from Moon_cove_report.main in file "moon_cove_report.ml", line 223617, ...
Called from Moon_cove_report in file "moon_cove_report.ml", line 223726, characters 2-9
```

Both `host/cov_report.py` and section C of the gate took the **last non-blank
line** as the reason. That line is `moon_cove_report` calling itself. It is the
same string for every failure the reporter can raise, so it carried exactly
zero information, and it was printed next to a package whose failure is a real,
permanent property of the repository.

That matters here specifically because **the transient failure has the same
shape as the permanent one.** The committed evidence records
`src/khfile` and `src/test_nested` as un-coverable for a real reason -- their
only test drivers are gated to `native`, and `coverage analyze` has no
`--target`, so there is nothing to instrument. On the failing run `src/aead`
reported no coverage source data too. Same message. Different cause: one is a
fact about a package, the other is an instrumented build that did not
complete on that particular pass.

So a signature test would not have separated them, and a "retry" that
classified by signature would have been worse than nothing. **The
discriminator is persistence, not wording.**

#### Two changes, in both places the derivation is written

There are two copies of this logic -- `host/cov_report.py` (the qa command) and
section C of `verify_loop68.mjs` (which re-derives independently, on purpose,
so the gate is not just re-reading the script's own answer). Both got the same
two changes.

1. **The reason is read from the failure payload**, not the tail of the
   output. `src/khfile` now prints `Error: No coverage source data found, ...`
   instead of a line number in the toolchain's own source. Fallback is still
   the tail, so an unrecognised failure shape stays visible rather than
   swallowed.
2. **One retry before concluding.** ~3s for the two packages that fail for
   real, and a one-off build failure goes back to being the transient it was.
   A package that only reports on the second attempt is *named in the output*
   (`recovered on retry: ...`), not healed silently -- the fact that made the
   gate red belongs in the log one level up as well.

#### And an assertion, because the fix was otherwise untested

Both edits are invisible to a green run: on a good day the gate passes either
way. So section C now asserts **the reason is readable** -- no not-reportable
package may report a line starting with `Called from ` or `Raised at `. That
is a deterministic property of the two packages that legitimately cannot be
covered, and it is the mutation target.

`host/loop68_mutations.py` **M8** deletes the extraction lines from the gate
and must come back CAUGHT. It mutates the gate rather than the tree, which is
normally off limits -- the rule from Loop #71 is that a gate is excluded from
its own scan, because it contains the strings it looks for. This is the case
where exclusion is not available: the defect is *in the scanning code*, so a
check that the scanning code is doing its job is the only thing that can catch
it.

#### What was not mutated, and why

The retry cannot be mutation-tested honestly. The failure it defends against
is rare enough that a sandbox run with the retry deleted would come back
clean -- a MISSED by definition, and a MISSED that only shows up on a busy
machine is worse than no mutation, because it trains the reader to trust a
number that means nothing. `host/cov_report.py` carries the same two changes
and has no mutation of its own for a structural reason worth writing down:
its default target list is the committed reportable set, and every package in
that set reports, so it never prints a not-reportable reason for anything to be
wrong about. Its `--derive` and `--all` paths are the ones section C exercises
directly.

There is also a duplication I chose not to remove. One implementation would be
better -- `verify_loop68.mjs` re-deriving in JavaScript what `cov_report.py`
already derives in Python is exactly the "protocol implemented twice" problem
this repository argues against everywhere else. It survives here because
section C's independence from the script's own answer is the whole reason the
comparison can fail, and collapsing them would make the gate agree with itself
by construction. That is debt with a name, not debt to hide.

### Loop #67: a twelve-loop-old warning was wrong, and the tool that measured it was wrong in a worse way

Loop #66 closed the static-analysis row. This one closes format-check and
benchmark, disproves a standing instruction, and finds a real regression that
Loop #66 shipped. The regression is the reason to read this section twice.

#### The CJK warning was false, and it was costing us the fix

AGENTS.md carried this rule for a dozen loops:

> `moon fmt` in write mode corrupts CJK comments (`真实加密` -> `真加密`)

It was the stated reason `format-check` could never be made green -- "run with
`--check` ONLY". It does not reproduce on `moon 0.1.20261012`. Measured three
ways, and the first one needed no write mode at all:

1. **The formatter's own output is already on disk.** `moon fmt --check` writes
   what it *would* write to `_build/<target>/release/format/`. All 366 CJK runs
   in `cmd/channel_test/main.mbt` are byte-identical between source and that
   output. This is the decisive test and it is free.
2. After formatting the 10 files `--check` named, all 373 CJK runs across them
   were unchanged.
3. After formatting the whole tree -- 267 files -- `host/cjk_snapshot.py`
   compared **12,840** CJK runs across 226 files against a snapshot taken
   beforehand. Zero difference.

The rule is deleted, and the guard that replaces it is stronger than the rule
was: `host/cjk_snapshot.py save|check` snapshots CJK *content* and fails if a
run is lost or changed inside a file that still exists. It fired once during
this loop -- on `src/wtlive/live.mbt`, because a dead function and its Chinese
doc comment were deleted on purpose -- which is the proof that it is measuring
something real. `verify_loop67.mjs` runs it.

The incident itself is not recorded, and guessing is how a wrong rule outlives
a dozen loops. The file it named no longer contains the string.

#### `moon fmt --check` reports a partial set, like `moon check`

Before formatting, `--check` named 10 files. Formatting them made it name **20
more, with no overlap**. Same command, same tree, and the second batch was
always there. This is the Loop #66 finding wearing a different hat: a single
measurement pass is a floor, not a total. Both tools report what they reached,
not what exists.

Of the 10 it named first, **2 were line-ending-only** -- a CRLF source against
an LF formatter, byte-identical after normalising. The diff renders as a
whole-file delete-and-readd, which reads like a catastrophe and contains no
change at all. `verify_loop67.mjs` now asserts that every tracked `.mbt`,
`.pkg` and `.moon` file is LF.

#### Loop #66 shipped a compile error, and only a js build found it

Loop #66 renamed `AuthReport.method` -> `auth_method` because `method` is a
reserved keyword, and updated `cmd/wt_ssh/main.mbt` to read `r.auth_method`.
But `cmd/wt_ssh`'s `r` is a `src/wtlive.WtAuthReport` -- the WebTransport twin
of the type, not the type itself. Loop #66 renamed one twin and edited the
consumer of the other.

`moon check cmd/wt_ssh` on the default target does not see it: the file is
gated to js. `moon check --target js` does, and so does `moon build`. It
surfaced in this loop as `verify_loop46.mjs` failing with "failed when building
project" -- the first time the whole-workspace CI had run since.

Two lessons, and the second is the expensive one:

1. Parallel types must be renamed together. `WtAuthReport` got the same
   treatment, and its `reserved_keyword` warning had been invisible for the same
   reason the error was.
2. **The collector reported that broken package as CLEAN.** Its
   `_is_hard_error` tested `msg.startswith("Error")`, and the message is
   `The type ... has no field auth_method.` -- no prefix. Loop #66's fixpoint
   of "3 remaining warnings" was therefore a statement about packages that
   happened to build. Fixed to key on the diagnostic's shape
   (`Warning (<kind>):` or not), which is the only thing that actually
   discriminates -- `level` cannot, because `--deny-warn` reports warnings as
   `"level": "error"` too.

#### The same mistake one level up: judging a package from one target

With the error detector fixed, the collector immediately reported **five
packages that "failed to build"** -- and every one of them was fine. They are
js-only executables with `options(targets: { "main.mbt": ["js"] })`; checked on
the default target they have no main and fail [4067]. `cmd/probe_async_wall`
was the real defect hiding in that list: its `main.mbt` is `extern "js"` end to
end and **its `moon.pkg` never declared the gate at all**, so it was a js-only
package pretending to be universal.

So the collector now reads `moon.pkg` and checks a package on all four targets
when it declares gating, on the default target when it does not, and only
gathers diagnostics from targets that built -- a target that failed produces
cascade noise, which is exactly how `cmd/wt_ssh` once produced a wall of
`test_unqualified_package`. Fixing all of that turned "3 warnings" into 4 real
sites across 3 files, all of them justified:

- `cmd/proton_gui` x3 `unused_async` -- `CommandRegistrar::bind` declares its
  handler type as `async fn`, so a handler is async whether or not its body
  awaits. `main.mbt:69` says so in the source. The warning is about the body;
  the requirement is about the type.
- `src/khfile` x1 `unused_package` -- Loop #66's entry, kept.

And a controlled experiment settled a disagreement between the two loops.
`src/wtlive` also imported `moonbitlang/async`, unused by the same test.
Loop #66's evidence says such an import must stay; Loop #67 deleted it and
measured: `moon check --target js` and `moon build cmd/wt_ssh --target js` are
both green without it. **Same warning, same package shape, opposite answers** --
because `src/khfile` has `async test` (whose expansion consumes the import) and
`src/wtlive` has only `async fn` (which does not). Both entries now carry that
distinction in their evidence.

#### benchmark: the row had never measured anything

`moon bench --target native` with no `-p` benchmarks the *current* package, so
the row inherited the whole workspace and died on the js-only Worker mains.
Scoped to `-p src/bigint`, the real reason surfaced: the repository contained
**zero** benchmark blocks, and `moon bench` on a package with none exits **0**
while printing `Total tests: 0, passed: 0, failed: 0` and `Warning: no test
entry found`. An exit-code-only check would have reported a PASS having measured
nothing. `verify_loop67.mjs` asserts on that text.

`src/bigint/bigint_bench.mbt` now carries five. A MoonBit benchmark is a
**test block taking a `@bench.T`**, not a `bench "..." { }` block -- `bench` is
not a keyword in that position, and `ignore(x)` and `let _ = x` both fail to
parse inside one. `b.keep()` is what stops the optimiser deleting the
computation. Measured here:

| benchmark | time (mean ± σ) |
|---|---|
| `mod_pow` 2048-bit e=65537, schoolbook | 4.86 ms ± 52 µs |
| `mod_pow_auto`, cached Montgomery ctx | **173.96 µs ± 2.23 µs** |
| `mod_mul` 2048-bit | 237.80 ns ± 2.34 ns |
| `mpint_encode` 2048-bit | 329.05 ns ± 2.40 ns |
| bytes round trip | 486.26 ns ± 2.21 ns |

The 28x gap is Loop #29's optimisation finally quantified instead of asserted.
The modulus is RFC 3526 group 14, written as a derivation (`2^2048 - 1` is 255
bytes of `0xFF` and `0xFF`, and `189 = 0xBC`, so subtracting puts `0x43` last)
rather than 256 pasted bytes that nothing here could check.

#### The first full CI run found three more, and two of them were self-inflicted

Closing format-check meant formatting 267 files, and formatting is exactly the
kind of change that breaks gates which were asserting on things nobody thought
to re-derive. Three failures, all from that one action:

1. **`src/bigint/bigint_bench.mbt` shipped five warnings.** `@bench.T` is a
   core package, and core packages are no longer implicitly in scope. It reports
   as `core_package_not_imported`, a **deprecation rather than an error** --
   which is why the benchmarks still ran and the number still came out. A gate
   that only ran the benchmarks would never have noticed.
2. **`verify_loop56.mjs` failed on a 276-byte "drift".** Its two generated files
   are compared byte for byte, so formatting one turned a content check into a
   wrapping check. Worse, the gate *writes* the generator's output back in
   place, so the unformatted file it left behind turned `moon fmt --check` red
   **two steps later in the same run** -- one byte-for-byte assertion turned one
   green row into two red ones. The fix is to run `moon fmt` on the generated
   files before comparing, so the check measures what it exists to measure
   (did the content change) and formatting stays format-check's business. The
   failure message now says "after formatting, so this is a content change and
   not a wrapping one", which is the difference between an action and a shrug.
3. **`verify_loop66` and `verify_loop67` went red on the new file** -- the same
   five warnings, caught by the accept-table equality, which is what it is for.

The generalisable part: **turning on a gate you had been carrying as "known
defect" is its own change**, and it will find things that were always there and
that no gate was looking at. The benchmark file is the clean example -- it was
written to be correct, ran correctly, printed real numbers, and was still wrong
in a way only the accept table could name.


#### Mutations, and one that was filed in the wrong place

`host/loop67_mutations.py`, six mutations. The first run came back
**4 CAUGHT / 2 MISSED / 1 BUILD-BROKEN**, and all three of the wrong-looking
ones were worth more than a pass would have been:

- **M1 was BUILD-BROKEN, and it should not have been.** It prepended a junk
  line to a source file to create a CRLF defect, which also made the package
  fail to compile -- so it tested the compiler, not the CRLF check, even though
  the gate did catch it. It now converts the file's line endings instead, which
  is the defect without the breakage. *A mutation that cannot build has not
  tested the gate*, and reporting it as a pass would have been the lie.
- **M7 errored on a stale anchor** because I had edited `cjk_snapshot.py`
  under it. A harness whose anchors silently rot stops testing anything, so it
  fails loudly and the anchor is fixed rather than the mutation dropped.
- **M5 MISSED, and the gate deserved it.** It re-added `src/wtlive`'s dead
  `moonbitlang/async` import -- and the only check in the repository that
  notices a stray unused import is the accept-table equality inside
  `verify_loop66.mjs`, which `verify_loop67.mjs` invokes with `--skip-live` so
  that a mutation run stays affordable. So the mutation sat exactly where the
  check it attacks was switched off.

  It moved to `host/loop66_mutations.py` as **M9**, beside the check, and runs
  there with `live=True`. **A mutation belongs beside the check that catches
  it, not beside the loop that introduced the defect** -- which is a different
  statement from "put it in the same file as the code it breaks".


#### The mutation that was right about the gate, twice

M9 re-adds `src/wtlive`'s dead `moonbitlang/async` import and expects the
accept-table equality to reject it. It did not -- and it was right twice, which
is rarer and more useful than being right once.

The first MISSED was cheap to explain and was a placement error: M9 sat in
`loop67_mutations.py`, whose gate calls Loop #66's with `--skip-live` to keep a
mutation run affordable, and that flag skips exactly the accept-table check it
attacks. Moved to `loop66_mutations.py` beside the check.

The second MISSED was a **real hole in the collector**, found only because the
mutation was not deleted and the gate was not explained away:

- The site *was* reported. `collect_one("src/wtlive", target="js")` returns
  `('src\\wtlive\\moon.pkg', '2')` as an `unused_package`.
- But `unused_package_all_targets` returned the **empty set**, and empty means
  "classified as a false positive and filtered out".

The intersection runs over all four targets. `src/wtlive` gates both of its
files to js, so on native it builds with **zero active files** and reports
nothing at all -- and an empty set intersected with anything is empty.
**A target where a package has no files is silence, not evidence.**

That fix then exposed two more, both of the same family:

- **Bare `moon check` does not default to native.** `cmd/proton_gui` is
  `supported_targets: "+native"`, so checking it with no `--target` produced no
  diagnostics, and the collector would have called a package with three real
  warnings clean. The collector had been consulting "whatever the default is" --
  now it consults `targets:`, then `supported_targets:`, and otherwise **all
  four targets**.
- **The `targets:` parser only captured the first element of each list.** With
  `[ "wasm", "wasm-gc" ]` it returned `{wasm}`, so `src/tcp` was being
  intersected over three targets instead of four -- and an intersection over
  fewer targets is one that can hide a real dead import. Caught by printing
  what each package resolved to rather than by reasoning about it.

With the hole closed, one more genuinely dead import appeared that three rounds
of "is this a false positive?" had been waving through: **`cmd/wt_ssh`'s
`moonbitlang/async/js_async`**. Deleted after `moon check --target js` and
`moon build cmd/wt_ssh --target js` both came back clean without it. Nothing in
this repository noticed it for a dozen loops, because every layer above the
compiler was answering the question it had been asked rather than the question
that was true.

The mutation harness earned its keep here in a way a passing run could not:
**a mutation that cannot fail is more dangerous than no mutation at all**, and
three of this loop's four were failures that had to be read before they could
be fixed.


#### Still red

`test-coverage`. `moon coverage analyze` has **no `--target` flag**, only
`--target-dir`, and `-p` does not limit the scan -- `combine_coverages` builds
every package for the default target, so the two js-only Worker mains fail
[4067]. An attempt to declare them differently (`options(is_main: [...])`) was
reverted after the key turned out to take a boolean, and `git diff` confirmed
the revert before moving on. This is recorded, not worked around.

The release gate stays shut and no tag was cut. `ci/release.py` refusing while a
tier is red is the correct outcome, and it is not a formality: it was exercised
in exactly that mode both this loop and the last.

Where the matrix ended up, for the record. `python ci/ci.py --tiers
env,build,gates,qa`: **57/58 steps in 762.9 s**, and of the twelve runnable QA
categories **11 pass**. That is 8/12 at the start of Loop #66, 9/12 after it,
and 11/12 now:

| row | Loop #66 | Loop #67 |
|---|---|---|
| static-analysis | red (one package) | **pass**, 22.4 s |
| format-check | red | **pass**, 0.1 s |
| benchmark | red | **pass**, 5.0 s |
| test-coverage | red | red, structural |

#### A note on editing, because it cost more time than any of this

The `edit` tool failed to match multi-line blocks in this repository -- AGENTS.md,
ci/qa.py, cmd/flow_kat/main.mbt, collect_warnings.py, src/khfile/moon.pkg --
on invisible byte differences alone, repeatedly. `host/patch_span.py` locates a
span by two unique ASCII lines and rewrites between them, with a uniqueness check
so a drifted file fails loudly. The one trap worth naming: `}` is not a unique
end marker in MoonBit, `cmd/flow_kat/main.mbt` has 74 of them, hence the
`until:` form.


### Loop #66: the warnings were hiding each other, and the collector was hiding the warnings

Loop #66 set out to turn the four red qa rows green. It closed one of them and
found, on the way, that the tool used to measure the others had been lying in a
way that made every earlier count wrong.

#### The headline: `moon check --deny-warn` is not a set of warnings, it is a snapshot

The first measurement said the tree had 15 warning sites. It actually had 318.
Then 62. Then 12. Then 3. Nothing was added to the tree between those numbers --
the *same* command was reporting fewer things each time, because fixing one kind
of diagnostic made another kind visible.

`src/hostkey` is the clean example. While `cert.mbt` still contained one
`deprecated` call, `moon check src/hostkey --deny-warn` reported exactly that
call and nothing else. Fixing it -- changing `.substring(start=0, end=n)` to
`n[:len].to_owned()` -- made **105** `test_unqualified_package` warnings appear
in the same package, in the same command, with no file touched except the one
that had just been fixed. Three consecutive runs on the repaired tree returned
105, 105 and 105, so the result is stable; it is just *not* stable against the
act of fixing something else.

The operational consequence is the part worth keeping: **a static-analysis gate
built on one measurement pass cannot work here, and a number read off a single
pass is a floor rather than a total.** The loop measured, fixed, re-measured and
repeated until one full pass produced no new sites. That fixpoint is 3.

#### Two independent reasons an import can look unused, and only one of them is fixable

`unused_package` fired on 19 sites. They split cleanly, and the split is the
useful part:

| Cause | Example | Verdict |
|---|---|---|
| Files gated per target | `src/wt`, `src/khstore`, `src/khfile`, `cmd/wt_probe`, `cmd/knownhosts_kat` | false positive |
| Consumed by a compiler expansion | `src/khfile`'s `moonbitlang/async` | false positive |
| Genuinely dead | `src/tcp`'s `moonbitlang/core/bytes` | removed |

The first is handled **derived, not by allowlist**. `options(targets: {...})`
leaves an import with no textual reference whenever the files that use it are
gated away, so `host/collect_warnings.py` intersects `unused_package` across all
four targets and keeps only what fires everywhere. That alone removed 15 sites,
and it has teeth: the real `src/tcp` case fires on all four and was caught by it.

The second is the one the intersection **cannot** reach, and finding that is the
loop's sharpest result. `moonbitlang/async` is consumed by the compiler's
`async test` expansion, which emits a call to `@moonbitlang/async.run_async_main`
-- generated code, so no source line references the package. It looks unused on
*every* target, and the gate would otherwise tell the next reader to delete a
line whose deletion produces eight hard errors, one per `async test` block,
reproducing verbatim the message the package comment had predicted. The gate
therefore asserts the import is **present**, and the comment now says "do not
clean it up". The lesson generalises: *an intersection over configurations cannot
detect a consumer that is not in the source text at all.*

#### What was removed

- `src/tcp`: `moonbitlang/core/bytes`. `Bytes` is prelude, so four files using
  the type never needed the import.
- `src/sshclient`: `src/tcp`. This is Loop #64's payoff, finally visible as a
  deleted line -- the Transport impl moved to the transport side and took the last
  `@tcp.` reference with it, so the dependency arrow the loop argued about is
  gone rather than merely pointing the other way.
- `cmd/main`, `cmd/ssh_full`: three dead imports.
- Dead code: `eq_at`, `bytes_to_ascii_string`, `ascii_bytes`, `byte_to_hex`,
  the whole `PfCursor` reader, the write-only `in_section`, a `key_kat256_dbg`
  that was byte-identical to the `key_kat256` below it, and `HASH_LEN` /
  `HASH_MAGIC`.
- 19 deprecated `.substring(start=A, end=B)` calls rewritten to `[A:B].to_owned()`.
  Two of the intermediate forms compile-fail rather than misbehave, which is
  what made it safe to try: a bare `s[:n]` is a `StringView` where a `String` is
  wanted, and `.to_string()` *on a StringView* is itself deprecated. Only
  `.to_owned()` satisfies both.
- `AuthReport.method` → `auth_method`, because the word is reserved. The printed
  label stays `method:` -- that is RFC 4252's term, and `verify_loop34` asserts
  on it. Renaming the field but not the label is the whole point: the toolchain
  objected to an identifier, not to the protocol vocabulary.

#### Two instruments that were themselves wrong

`host/collect_warnings.py` keyed results as `path -> {line: kind}`, so two
warnings on one line silently collapsed into one, and a package that **failed to
build** reported as clean because its cascade noise was filtered out. Both are
fixed, and a broken package now exits 2 with its name on stderr, because "cannot
tell" and "clean" are different answers.

Separately, the first reading of the collector's own output was wrong before the
collector was: `python host/collect_warnings.py 2>&1 | Out-String` on
PowerShell 5.1 interleaves stderr into stdout and destroyed a whole file's entry
mid-JSON. The `files=9 sites=15` in this loop's notes is that artefact, not a
measurement. Native redirection writes UTF-16 (0xFF BOM), so the working forms
are `cmd /c "python ... > out.json"` or reading with `encoding="utf-16"`.
**When a tool reports a count, verify the collector before believing the number**
-- the third time this repository has been bitten by it.

#### Gate and mutations

`host/verify_loop66.mjs`, 14 checks, exit 0. Two are negative assertions
(`src/khfile` must still import `moonbitlang/async`; `in_section` must still be
*read* by the second function in `parser.mbt`, even though the dead copy is
gone), one re-runs the collector live and asserts the reported set **equals** the
accept table -- so a new warning fails and a fixed one fails too. The gate caught
two of its own bugs while being written: it asserted `in_section` was absent
file-wide when a second function legitimately reads it, and it used `require` in
an ESM module. A gate that fails on correct code is still doing its job.

`host/loop66_mutations.py`: **7 CAUGHT, 0 MISSED, 1 BUILD-BROKEN** over 8
mutations. M3 is the deliberate shape from Loop #65 -- deleting
`src/khfile`'s `moonbitlang/async` **is** the fix a future reader will attempt,
and the gate must reject it. M5 is recorded as BUILD-BROKEN because the mutation
does not compile: a mutation caught by the compiler has not tested the gate.

#### Still red, and why

`ci/qa.py`'s `static-analysis-sast-code` row now runs the gate instead of
`moon check --deny-warn`. The other three rows are untouched and still red:

- **test-coverage** -- `moon coverage analyze` has **no `--target` flag**, only
  `--target-dir`, and `-p` does not limit the scan: `combine_coverages` builds
  every package for the default target, so the two js-only Worker entry points
  (`cmd/wt_probe`, `cmd/wt_ssh`) fail [4067] "Missing main function". An attempt
  to declare them differently (`options(is_main: [...])`) was reverted -- the key
  takes a boolean, and `git diff` confirmed the revert before moving on.
- **benchmark** -- needs real `*_bench.mbt` files; the repo has none, and the
  zero-work guard is what stops the row reporting a green that measured nothing.
- **format-check** -- `moon fmt --check` wanted to re-wrap KAT byte arrays.
  **Solved in Loop #67**, which also disproved the CJK warning this line used to
  carry: `moon fmt` over the whole tree leaves all 12,840 CJK runs across 226
  files byte-identical. `moon fmt --check` now exits 0.

The release gate therefore stays shut and no tag was cut, which is the correct
outcome and not a formality: `ci/release.py` refuses when a tier is red, and it
was exercised in exactly that mode.


### Loop #65: verify_loop40 leaks the server it starts, and a fixed port makes that bite

`verify_loop40.mjs` starts a real OpenSSH server and **cannot stop it**.
`startSshd()` (line 147) spawns `node host/sshd_setup.mjs`, calls
`child.unref()`, polls until the port answers, and returns a boolean — the
handle is discarded and never stored. `sshd_setup.mjs:210` parks on
`await new Promise(() => {})`: `sshd -D` runs in the foreground forever and no
SIGTERM/SIGINT handler is installed. The only `kill()` in the whole gate is
`relay.kill()` (line 556), a different process. So on every run, successful or
not, an sshd is orphaned on `SSHD_PORT = 18783` — a **hard-coded literal**, so
the second run collides with the first.

That is the shape behind `verify_loop49` passing standalone and failing inside
a suite run. It is the kind of order-dependent failure that gets relabelled
"flaky" and then lived with forever.

Reading the code shows there is no owner; it does **not** show that the process
survives. `host/probe_sshd_leak.mjs` measures it, in two processes on purpose:
the inner one reproduces loop40's `spawn` + `unref` + dropped handle verbatim
and exits normally, exactly as a gate that finished — or was killed — would;
the outer one then polls the port. If it still answers, the server outlived its
only owner. In a single process that measurement would be void, because the
inner process would still be alive. The outer probe cleans up after itself,
which is precisely what loop40 lacks.

```
LEAK CONFIRMED: the port still answers after the owner exited.
self-cleanup by this probe: ok, port released
```

`verify_loop65.mjs` 25/25. Mutations **6 CAUGHT / 0 MISSED**. M1 is worth
reading twice: giving loop40 an sshd kill *is* the fix being argued for, and
the gate goes red when it appears — the gate asserts the leak exists, so a real
fix must be accompanied by a decision about what the gate should then say.

#### The classification mistake, corrected

Loop #64 wrote `PEER_GATES` as `verify_loop31..39` and left loop40 in the
default tier, where it costs ~44 minutes and turns the run red for reasons
unrelated to the code under test. That was Loop #64's error, not a judgement
call. The set is now `31..40, 49`, each entry carrying the measurement that put
it there. Default tier: **44 steps**; the eleven excluded gates are named on
every run.

#### A note on restoring bytes

Two separate incidents this loop, both mine:

- `git show … | Out-String` turned a 2-line change into a 717-line diff.
  PowerShell rewrites line endings and appends a newline. Use `git show` piped
  to a binary write.
- A restore-from-HEAD script then reverted the loop's own uncommitted work along
  with the temporary mutation, and the gate noticed before I did.
  **Restore-by-HEAD is only safe on files with no legitimate uncommitted
  changes.** Restore by re-applying the exact change instead.

#### A gate that took four attempts to specify

The provenance check on `PEER_GATES` — "the set must carry the measurement that
justifies it" — was too weak three times in a row, and each time a mutation that
should have failed it passed:

1. A mutation that appended a misleading comment and deleted nothing. The gate
   was right to pass; **the mutation was broken**, which is worse than no
   mutation because it looks like a hole.
2. Deleting one line of the block — "measured" also appears on Loop #64's
   paragraph about 31–39.
3. Deleting the block's header — the detail lines still name `loop40`.

Deleting the whole nine-line block fails it (23/25). The spec that works names
the two gates specifically. Three broken mutations are recorded in
`host/loop65_mutations.py` rather than deleted: **a mutation that cannot fail is
more dangerous than no mutation at all.**

### Loop #64: a transport seam, a measured wall, and a CI that can say no

`src/sshclient/live.mbt` and `src/sftp.mbt` named `@tcp.TcpConn` in 25
signatures. `@tcp` is **our own** package (`src/tcp`, a plain Winsock binding) —
not `moonbitlang/core/tcp` — so the protocol layer and one transport were the
same thing at the type level. There was no way to say "run the same handshake
over a WebSocket", and no way to *prove* two transports equivalent because only
one existed.

`src/transport` supplies the seam. Three methods, because that is all
`sshclient` calls: SSH is strict request/response, so `read_exact` is the only
read primitive that matters and no partial-read notion leaks upward.

```
pub(open) trait Transport {
  fn wire_send(Self, FixedArray[Byte]) -> Bool
  fn wire_read_exact(Self, Int) -> FixedArray[Byte]?
  fn wire_close(Self) -> Unit
}
```

The `Transport for @tcp.TcpConn` impl lives in `src/transport`, not in
`src/tcp`. The dependency arrow points one way and `src/tcp` is unmodified: if
the socket binding learned about the trait, the "seam" would be a cycle wearing
a trait's clothes. `verify_loop64.mjs` asserts both directions.

**The wall, measured rather than argued.** `cmd/probe_async_wall` puts a byte
into a JS-visible slot from a `setTimeout` callback — the stand-in for
`WebSocket.onmessage` — and asks whether a *synchronous* `fn` can ever see it:

```
sync : STARVED after 5000000 spins -- synchronous code never yields
async: GOT 0x5a
```

Both arms are driven by the same `setTimeout` scheduling, because if they
differed the comparison would prove nothing; `verify_loop64.mjs` asserts that.
**Consequence, and it is the real finding of this loop:** `src/sshclient` is
synchronous, a browser WebSocket can only be read by awaiting, and in MoonBit
only an `async fn` can await. So running the verified handshake in a browser is
not "write a WebSocket bridge" — it requires converting the whole SSH layer to
`async fn`. Loop #63's conclusion is narrowed, not overturned: the wasm target
cannot do it; the js target can, but only asynchronously.

Verification: `verify_loop64.mjs` 31/31. Mutations: **4 CAUGHT / 0 MISSED /
2 BUILD-BROKEN** (the two broken ones are compile errors, so the gate never
judged them and they are not evidence).

`verify_loop63.mjs` asserted `live.mbt` contains `@tcp.TcpConn` — a literal that
this loop supersedes. It was replaced by the stronger statement it was standing
in for: scan every `impl Transport for` in the repo and assert the set is
exactly `["@tcp.TcpConn"]`. A second implementation is exactly what would let a
browser transport in, and nothing else in that gate would notice. Loop #64's own
mutation M6 found the first attempt was too weak — it only guarded one end of
the arrow — and that is now asserted too.

#### Local CI, and three gates that were red for reasons nobody had noticed

`ci/ci.py` is the engine; `.github/workflows/ci.yml` is a thin shell that calls
it. The step list lives in **one** place on purpose: a YAML copy of 40 gates
drifts within a couple of loops, and the failure mode is silent — CI goes green
because it stopped running the new gate.

The engine exists because a hand-written loop got it wrong inside one session:
PowerShell 5.1 evaluates `.Count` on a *scalar* as `$null`, so a run with one
failing gate printed `11 - $null = 11`, i.e. **"11/11 PASS" while the process
exited 1**. A summary that can disagree with the exit status is not a summary.
`--self-check` therefore tests the engine's own accounting, including that one.

Three red gates surfaced immediately, all pre-existing (reproduced on a clean
`git worktree` of `59145fb`):

1. **`verify_loop24.mjs`, red since Loop #57.** It asserted
   `cmd/sshconfig_test` prints `fnmatch_pass: 23/23`. Loop #57 *deleted* that
   block — the count was hardcoded, so the binary printed 23/23 whether or not
   the arithmetic held — and moved the cases into `src/sshconfig/sshconfig_test.mbt`
   as a table that asserts instead of printing. The gate was never updated. It
   now asserts the *absence* of the hardcoded line and the *presence* of the
   table.
2. **`verify_loop30.mjs`, KAT mismatch vs Python — and the MoonBit side was
   right.** An independent RFC 4251/5656 parser decided it:
   MoonBit's blob parses and consumes all 101 bytes; the expected file does not
   parse at all. `gen_ecdsa_driver.py`'s `sig_blob` omitted the outer
   `string signature_blob` length, and `render`'s `format(v, "X")` dropped
   leading zeros, producing a 95-character hex string where a 48-byte value needs
   96. Both fixed; the generator is now idempotent (`cmd/ecdsa_test/main.mbt`
   regenerates byte-identical to HEAD).
3. **The generator was a landmine.** Loop #34 had fixed `build_sig` *by hand*
   in `cmd/ecdsa_test/main.mbt`, left a comment predicting exactly this bug, and
   never fixed the generator. Regenerating silently reverted it. The generator
   now emits the correct layout with the original Chinese comment preserved
   byte-for-byte.

All three are the same disease: **one fact stored twice, one copy edited.**
Keep the generator authoritative and make regeneration idempotent, or a future
loop will repeat this.

#### Mutations run in a sandbox, because `finally` is not a safety net

Mutation harnesses restore the tree in a `finally`, which does not run when the
process is killed — and `subprocess.run(timeout=...)` kills. This already
happened: `verify_loop40` was interrupted at 44 minutes and left
`src/channel/channel.mbt` with the `env` name/value pair swapped. The tree was
restored byte-exactly (via `git show` + a binary write; `git show | Out-String`
turns a 2-line change into a 717-line diff, and `git checkout --` is forbidden).

`ci/sandbox.py` runs the mutations tier against a throwaway `git worktree` with
the current uncommitted state applied on top, so the tree that matters is never
written to.

#### QA matrix: 20 categories, each with evidence

`ci/qa.py` classifies 20 QA categories as `implemented` / `not_available` /
`needs_external`. Every `not_available` carries the probe that proves it, and
the matrix is printed in full — omitting a category is the failure mode to
avoid. Notable: **Gherkin does exist** (`moonrockz/gherkin@0.5.1`); it is
unavailable *here* only because `moon.mod` declares neither it nor `cucumber`,
and adding dependencies is out of scope. Also merged rather than shipped twice:
`static-code-check` into static-analysis, `contract-test` into
api-interface-contract — this project has been bitten three times by two copies
of one fact. Two commands that exit 0 while testing nothing were caught and are
guarded: `moon bench cmd/bench_cached` and `moon test -p src/channel` both
report "Total tests: 0".

`python ci/ci.py --tiers qa` currently reports **8/12 pass, 4 fail**
(`format-check`, `moon check --deny-warn` with 114 `test_unqualified_package`,
`moon coverage analyze` with no data, `moon bench` hitting `extern "wasm"` on
native). Not hidden. ~~`moon fmt --check` failing is expected and must not be
"fixed" by running `moon fmt`: that corrupts CJK comments
(`真实加密` → `真加密`).~~ **Superseded by Loop #67**, which measured the CJK
claim three ways and found no damage on `moon 0.1.20261012` — 12,840 runs
across 226 files, byte-identical after a whole-tree format. The format-check
row is now green. The other three rows moved as follows: the static-analysis row
went green in Loop #66 (8/12 → 9/12); `moon coverage analyze` and `moon bench`
are still red, for the reasons recorded under Loop #66 and Loop #67.

#### Release gate

`ci/release.py`. **No tag while the local CI is not fully green — including when
the owner asks directly.** The gate does not know who is asking; the tag is
produced by `git tag` from `next_tag()`, never hand-typed. `next_tag` moves only
the trailing number (`v0.1.0` -> `v0.1.1`), preserving zero padding, and refuses
rather than guessing when there is nothing to move. Gitee may be pushed at any
time; GitHub only after a green run and a tag. Tiers excluded from the tag
decision (`peer-gates`, `mutations`) are printed at the moment the decision is
made, not hidden.

**Both halves of that rule now have a remote, as of 2026-10-19.** This file
previously said the GitHub half was "policy with nothing to act on yet"; that is
no longer true and the note was removed rather than left to mislead:

| remote | URL | role |
|---|---|---|
| `origin` | `git@gitee.com:ren-yongxiang/moonbit_openssh.git` | day-to-day storage |
| `github` | `git@github.com:riantr/moonbit_openssh.git` | version/release updates |

The Gitee repository was renamed from `moonbit-openssh` to `moonbit_openssh` and
re-created empty, so this is a move rather than a second origin -- one remote per
host, and `origin` still means "the one you push to normally". The rename is why
the old path 404s now: `git ls-remote` on it fails with `404 not found`, which is
worth knowing before anyone concludes the SSH key broke.

The GitHub rule is unchanged and still has teeth: a green run is necessary but
not sufficient. `v0.1.1` was computable the moment qa reached 12/12, and pushing
it to GitHub still required the tag to exist first.

A self-check case caught a contradiction here: this file originally promised to
refuse a date-shaped tag like `release-2026-10`, while the implementation
incremented it. The implementation matched the owner's rule ("only the last
digit moves"), so the *promise* was corrected, not the code.

#### Left open: verify_loop41 fails in the suite and passes alone

The default tier is **43/44**, with one red: `verify_loop41.mjs` exits
`3221226505` (`0xC0000409`, a native abort) inside a suite run, while running
it standalone passes — three times in a row, 29 checks each. It is not flaky
on its own, so something else in the suite affects it.

**Whether this predates Loop #65 is NOT established.** The evidence leans that
way — this loop changed only `ci/ci.py` (the peer-gate set and the mutations
sandbox) plus new files under `host/`, touched nothing in `src/` or `cmd/`,
and loop41 shares no state with loop40 — but leaning is not proving, and the
attempt to prove it failed three times: a `git worktree` is a plain checkout,
so it has no `node_modules`, and `verify_loop41.mjs` imports the npm `ws`
package. Every control run therefore died with `ERR_MODULE_NOT_FOUND` before
reaching any assertion. The experiment needs `npm install ws` in the worktree
first; until then this is an open question, not a result.

#### Also learned this loop

- MoonBit type parameters go **before** the name: `fn[T] f`, not `fn f[T]`.
  This was got wrong three times during the migration.
- `src/tcp` has a `moon.pkg` warning about `moonbitlang/core/bytes` being unused
  — pre-existing, harmless.
- `[System.IO.File]` with a relative path resolves against the *process* CWD,
  not `Set-Location`, so an encoding check reported `INVALID-UTF8` for files it
  had never read. Always use absolute paths there.

### Loop #63: the browser path has never run, and on this toolchain it cannot

Loops #60, #61 and #62 each found a thing that looked tested and was not — a
proposal naming an algorithm it cannot run, a function with a swapped argument
order, a gate that trusted its own emitter. This is the same defect at the
largest scale in the tree, and it concerns the reason this project exists.

**The claim.** `docs/socket/loop23-summary.md` records Loop #23 as "PASS (with
caveat)", `host/verify_loop23.mjs` is titled as a verification of
`cmd/ssh_full_ws`, and across Loops #23–#33 the browser path is described as
byte-exact verified. The goal — SSH from a browser — rests on it.

**What is true, in four pieces.**

- **`src/sshclient/live.mbt` is the only code that performs a real, verified
  handshake, and it is bound to `@tcp.TcpConn`.** It does not import
  `src/ws_socket`. That is native TCP, and it *is* genuinely verified: Loops
  #54–#59 run it against a real peer.
- **`cmd/ssh_full_ws` compiles and does not do a handshake.** It reads the
  server's KEXINIT and KEXDH_REPLY into `let _ =` — discarded — never
  negotiates, never parses a host key, never verifies a signature, never derives
  a session key, and continues in plaintext after NEWKEYS. Its `read_n` calls
  take lengths computed by `make_server_*_reply().length()`: the peer is a
  hardcoded byte blob, and the client knows in advance how long each answer is.
  That is the shape of a scripted replay, not of a protocol.
- **`verify_loop23.mjs` runs no MoonBit code.** Both sides are JavaScript — a
  Node WebSocket client against a Node mock server, with hand-written algorithm
  lists standing in for the client's. Its own header says the MoonBit side was
  checked by compilation only and points at `verify_loop22.mjs`, a `MockSocket`
  path that is not a socket.
- **`host/node_host_wasm.mjs`, the host that would run the wasm, has never
  run.** Zero callers. And it had an `await` inside a non-async function, so
  the file could not even be parsed — `moon build` never loads it and nothing
  ever noticed. Its `ws_recv_into` throws on a short buffer, with a comment
  conceding that blocking is unsupported and MoonBit has no retry.

**Why it cannot be fixed by restructuring the client.** wasm-gc exports exactly
one symbol, `_start`. There is no way for a host to re-enter the module between
reads, so a synchronous `Socket::read_n` inside a wasm frame can never yield to
the event loop that a WebSocket's `onmessage` needs. `cmd/probe_export` exists
to make that falsifiable rather than a claim in a comment: a plain `pub fn`,
built and inspected, **does not appear in the export table**. If MoonBit ever
grows an export mechanism, section A of the gate fails and this reasoning has
to be revisited — which is exactly why it is a gate and not a paragraph.

The escape that does work is `--target js`, which shares `src/` and supports
async I/O. That is the next piece of work; this loop establishes what is true
today so it starts from facts.

**What was fixed here.** The `await` bug, so the file parses. Not the blocking
limitation — `ws_wait_for_bytes` is now `async` and correctly documented, but
`ws_recv_into` still refuses to block, and the gate asserts both that refusal
and the absence of callers, so nobody reads the file as a working path.

**Three gate defects, all mine, and one of them nearly inverted the finding.**

- The syntax check ran `node --check node_host_wasm.mjs` with `cwd` at the repo
  root. The file is in `host/`, so Node reported a missing-module error that
  reads exactly like a syntax error. **Asking Node to parse a file that is not
  there is not a parse.**
- The "discarded reads" regex used `[^)]*`, so it truncated at the inner `)` of
  `make_server_kexinit_reply().length()` and concluded the reads were *not*
  scripted — the opposite of the finding. **A regex that cannot count its own
  parentheses will confidently agree with anything.**
- The caller scan matched this gate's own header comment and reported
  `verify_loop63.mjs` as a caller. It now excludes itself and strips comments
  before matching, because a comment runs nothing.

**Mutation D was my error, not the gate's.** The first version wired a "caller"
in by appending a comment naming the host — and the gate reported MISSED,
correctly, since it strips comments. A mutation that does not change behaviour
cannot test a behaviour check. Rewritten as a real `execSync` spawn, it is
caught.

**Results.** `verify_loop63.mjs` 23/23, `loop63_mutations.py` 5 CAUGHT /
1 EQUIVALENT / 0 MISSED. Loops #53–#62 unchanged.

**What this loop does not do.** It does not build a browser client. It states,
with evidence, that the browser client does not exist yet — that MoonBit does
real SSH over native TCP, and compiles to wasm, and that the two have never been
joined. The next honest step is the transport abstraction that would join them,
or the `--target js` route that sidesteps the blocking read entirely.

### Loop #62: `flow_on_reply` completes a real handshake, and the three bugs were in my vectors

Loop #61 ended by naming what it had *not* proved. Quoting itself:

> `flow_on_reply` has no caller and no end-to-end test. Argument order and the
> derived length are pinned, but "this function can complete a handshake" is not
> yet a claim anything here can support.

This is that claim, with a vector set behind it.

**Result: 7/7, and the client code changed not at all.** That is the headline,
and it needs stating plainly because the opposite would have been easier to
write. `flow_on_reply` was correct once Loop #61 fixed it. What was missing was
the ability to *know* that — and the three defects I spent most of this loop
chasing were all in my own vector generator. `from_blob` reporting
`InvalidFormat` was **right**; the blob I handed it was malformed.

**The vectors are two-blind.** `host/gen_flow62_vectors.py` implements the server
half independently: X25519 and Ed25519 from Python's `cryptography`, and the
exchange-hash layout transcribed from kexgen.c:67-82 rather than copied from
`src/kexc25519/exchange_hash.mbt`. H and the signature are each computed twice by
code sharing nothing with the tree. The generator's own RFC 7748 implementation
is cross-checked against `cryptography` — they agree on every seed, and if they
did not, the generator would not be independent at all.

**The three generator bugs, and how each was found.** None by re-reading RFC
4253; all three by a probe, because a gate that cannot say *why* a case failed
is a gate you end up debugging by hand:

1. **K_S was `type ‖ pubkey`** — missing the key's own length prefix.
   `from_blob` said `InvalidFormat` and it was correct.
   Probe: `FLOW_PROBE <id> from_blob=<...> ks_len=<n>`, gated on the length being
   51 so a truncated blob cannot pass as "parsed".
2. **I_C was a copy of I_S.** The exchange hash covers both, so the signature
   could never verify. Probe: `FLOW_H <id> h=<hex>`, diffed against the `h =`
   line the generator wrote. A hash mismatch is unambiguous — exactly one side
   has the layout wrong, and this says which. Both now agree byte for byte.
3. **The signature blob had an extra length prefix** around the algorithm name.

I also spent two attempts "fixing" the signature framing by reasoning from memory
before re-reading `HkCursor::get_cstring`, which settles it: the algorithm name
*is* a length-prefixed string, because `get_cstring` is built on `get_string`.
The project's own rule — constants and formats come from sources, never from
recall — has a cost, and this is what the cost looks like.

**V7 is the case that matters.** The server signs an exchange hash computed over
a *different* Q_S than the one it transmits: a substituted server public key, the
classic active attack on curve25519 ECDH. The client recomputes H from its own
view and rejects it. The vector file records both `h` and `h_signed`, so the gap
between them is visible in the file rather than only in a failure message.

**What the mutations actually proved: 3 CAUGHT / 2 MISSED / 1 EQUIVALENT.** The
two MISSED are the most useful output, and they are limits of the gate, not
defects in it:

- **Hardcoding the derivation length to 64 again is invisible here.** Correct
  for chacha20-poly1305, which is the only cipher every vector negotiates. A
  chachapoly-only vector set structurally cannot see it. Loop #61's gate catches
  it by reading the source, which is the honest division of labour: **a vector
  set tests behaviour; a source check tests an invariant about code shape.**
  Closing this properly means an `aes128-ctr` vector, the day the browser path
  can carry a non-AEAD cipher.
- **Removing the `session_id == H` assertion is invisible by construction.** The
  emitter reports a variant name, and both a correct and a wrong session id
  produce `Established`. Making it observable is a change to the harness.

The caught one worth naming is **C: skip host key verification entirely.** A
client that never checks the signature reports `Established` for V1/V2 and
`SignatureInvalid` for V5/V7 — the *same* verdicts as a correct client, because a
broken signature and an unchecked one look identical from outside. V5 and V7
catch it. **That is what makes the negative cases worth having.**

Getting C to compile took three attempts, and the first two were caught by the
**compiler**, which proves nothing about the gate; the script now says so in
those words. MoonBit rejects a multi-line argument list in a `let` binding that
it accepts inside `match`, so the working mutation keeps the original statement
shape and changes one arm.

**Two harness defects, both mine.**

- The drift check used `git status --porcelain`, which reports `??` for a new
  uncommitted file — so it failed every run for a reason that had nothing to do
  with reproducibility. **A drift check that cannot tell "changed" from
  "untracked" is not a drift check.** It compares bytes before and after.
- The generated vector file was not in the mutation snapshot. The gate
  regenerates it as its first step, so a generator mutation rewrote it on disk
  and the *next* mutation started dirty. Not theoretical: mutation F was
  reported CAUGHT purely because E had left a wrong expectation behind, when F
  should be EQUIVALENT.

**Tooling, self-inflicted.** Twice more this loop, PowerShell `python -c` with
multi-line `\n` inside single-quoted strings mangled the replacement text, so
the anchor matched already-corrupted content and reported a syntax error from a
line I had never written. Restored with `git checkout --` on a file I was
mutating on purpose. The rule stands: script files go through the file tools.

**Results.** `verify_loop62.mjs` 35/35, `flow_kat` 7/7, three distinct verdicts
across the set. `loop53`–`loop61` unchanged. `moon test src/kexflow` 15/15,
`src/hostkey` 25/25, `src/bpacket` 25/25.

**What this loop does not cover.** `cmd/ssh_full_ws` still calls `flow_start` and
stops; nothing runs the browser path end to end over a socket. What is now
proven is that `flow_on_reply` turns a real, independently signed REPLY into the
right verdict — the framing around it is still untested.

### Loop #61: the kex and host key axes, and the function that had never been run

Loop #60 left kex and hostkey out of scope and said so. This closes that, and
the reason it was left out is where the real defect turned out to be.

**`flow_on_reply` could never succeed.** It called
`derive_keys(shared_mpint, h, we_need)`. The signature is
`derive_keys(hash, shared_secret_mpint, we_need)`, and `derive_single`
concatenates `K ‖ H ‖ letter ‖ session_id` (RFC 4253 §7.2), so the call site had
the two operands swapped: K1 was computed as HASH(H ‖ K ‖ letter ‖ H), and
`session_id` came back as the shared secret. The `session_id == h` assertion two
lines below therefore failed every single time, and reported
`Failed(ProtocolError)` — "the peer's bytes are malformed" — for a bug that is
entirely ours. `cmd/sshclient/live.mbt` calls the same function the other way
round, and that path is validated against a real sshd, which is what makes the
disagreement decidable.

Nothing caught it because **the function has no caller**. `cmd/ssh_full_ws`
calls `flow_start` and stops. A function that has never run cannot have been
tested, and the other two defects were sitting in the same unlit room:

- **`FLOW_WE_NEED = 64` hardcoded.** Right for chacha20-poly1305, silently the
  wrong length for anything else — which is how an unrunnable cipher could still
  produce a *successful* `Established`. Now derived from
  `@bpacket.transport_params`.
- **"We cannot answer this algorithm" was reported as `ProtocolError`.** Two
  new variants, `AlgorithmNotRunnable` and `CipherNotRunnable`, kept separate
  because the owner differs: the first is fixed by changing a proposal, the
  second by adding to `src/bpacket`. The tree had already made this split once,
  for `@cert-authority`, precisely because reporting it as `HostKeyMismatch`
  walks the user into `--kh-tofu`.

**The argument swap is now pinned by a test, not by reading code.** Both
parameters are `FixedArray[Byte]`, so MoonBit cannot see a swap — a compile
error would have been the cheapest possible defence and does not exist. `t12`
asserts that `session_id` is the hash argument and that `K‖H` and `H‖K` derive
different keys.

**What I suspected and found clean, before writing anything.** I expected the
host key list to be the real problem — a client advertising RSA and ECDSA host
keys it cannot verify would be a genuine security defect. It is not:
`HostKey::verify` does ed25519 and ECDSA, and `verify_with_alg` adds the RSA
path (Loop #38) precisely because RFC 8332 means the negotiated name is not the
blob's type string. All five names are backed. Recorded because "I checked and
it was fine" is a result, and because the next person should not redo it.

I also expected `cmd/ssh_full_ws` to carry a hand-copied proposal literal
still naming the EtM MAC Loop #60 removed. It does not — it calls
`Proposal::default_client(false)`, and its `make_server_kexinit_reply` is a mock
*server*, exempt by design. Two of my three suspicions this loop were wrong,
and both were caught by reading the source instead of the grep hit.

**Two false positives, and what they were really telling me.** The first honest
run reported `default_client/strict=true` and `live_proposal_with_certs=true` as
over-promising. Both wrong, and the reasons matter:

- `kex-strict-c-v00@openssh.com` **is not a key exchange**. OpenSSH appends it
  in `kex_proposal_populate_entries` to signal strict-KEX, and `ssh -Q kex`
  lists twelve algorithms that do not include it. Treating it as unimplemented
  makes the gate demand the marker's removal — and the fix anyone reaches for
  under that pressure is to drop it and turn off strict KEX. **A gate that
  demands a security property be deleted is a security regression wearing the
  costume of a failing test.**
- `ssh-ed25519-cert-v01@openssh.com` is gated by **policy**, not by
  implementation: Loop #53 parses and validates certificate structure but
  deliberately refuses certificates as host keys. `ssh -Q key-plain` and
  `ssh -Q key-cert` are two disjoint lists, which is the authority saying
  exactly this.

So a name list is not a uniform list of algorithms. The emitter now has four
verdicts — `ok`, `NO-PATH`, `MARKER`, `POLICY-GATED` — and the gate asserts the
classification rather than the binary, so a checker that answered `ok` for both
would fail.

**Gate defects found, all of them mine.** Four, and one of them a repeat:

- The check used `ssh -Q key-plain` for all five host key names and failed on
  `rsa-sha2-256` / `rsa-sha2-512`. It was right to fail: those are *signature*
  algorithm names (RFC 8332), not key types, and `key-plain` lists `ssh-rsa`.
  I made the RFC 8332 conflation in the very checker that exists to prevent it.
  The category is `ssh -Q key-sig`.
- `verdictFull === undefined` against a `null` initialiser — **the exact same
  bug Loop #60 made with `verdict_stoc`**, five confident wrong failures. Same
  gate-author, consecutive loops, same defect class: the process needs a rule,
  not just the fix. In these emitters every optional field starts `null`, so the
  test is `!field`, never `=== undefined`.
- The source-text checks read my own explanatory comments. The comment
  documenting the swap contains `derive_keys(hash, shared_secret_mpint, ...)`,
  and the one documenting `FLOW_WE_NEED` says "`FLOW_WE_NEED` was 64" — three
  confident failures caused by the gate reading its own documentation. **A
  comment explaining a bug will always contain the bug's text**, so every
  textual gate now runs on comment-stripped source.
- Mutation B **slipped through**: `expect(...flowBody.includes("@bpacket.transport_params"))`
  was satisfied by a leftover mention while the length was hardcoded. That is the
  hollow-check shape again, and the mutation is now `let we_need : Int = 64`
  with the mention removed, caught by asserting the *assignment* — seeded from
  `we_key`, raised by `we_mac`, never bound to a numeric literal.

**Results.** `verify_loop61.mjs` 62/62, `loop61_mutations.py` 5 CAUGHT /
1 EQUIVALENT / 0 MISSED. `verify_loop60.mjs` unchanged at 73/73 and `loop53`–
`loop59` still ALL PASS. `moon test src/kexflow` 15/15, `src/hostkey` 25/25,
`src/sshconfig` 10/10, `src/knownhosts` 49/49, `src/bpacket` 25/25.
`src/kexflow` and `src/hostkey` check clean on all four targets.

The equivalent mutant is `flow_on_reply`'s new cipher guard short-circuited to
`&& false`: unobservable today because every client proposal offers only
chacha20-poly1305, so an unrunnable cipher is never negotiated. Dead defence
now; live the moment a second cipher enters a proposal.

**Still open, and named so it is not mistaken for done.** `flow_on_reply` has
no caller and no end-to-end test — a real handshake vector through the browser
path would be the next thing worth building. Argument order and the derived
length are pinned, but "this function can complete a handshake" is not yet a
claim anything here can support.

### Loop #60: a client proposal may only name algorithms the packet transport can run

The invariant is one line. Writing it down is most of the work.

**What `src/bpacket` can actually run.** `Mode` has three constructors
(`packet_ctx.mbt:34-38`), so there are exactly two encrypted transports behind
them:

| cipher | `Mode` | files |
|---|---|---|
| `chacha20-poly1305@openssh.com` | `Aead` | `chacha_*.mbt` + `poly1305_*.mbt` |
| `aes128-ctr` | `MacEncrypt` | `aes_ctr_mac.mbt` |

and exactly one MAC the `MacEncrypt` branch can compute: `hmac-sha2-256`.
`packet_ctx.mbt:32` already said EtM is unimplemented; this loop makes that
statement enforceable instead of documentary.

**Defect 1 — `kexflow::default_client` advertised an algorithm it cannot run.**
Its MAC list led with `hmac-sha2-256-etm@openssh.com`. Nothing had ever failed,
because that proposal's cipher is an AEAD and an AEAD never computes the MAC:
the over-promise was harmless *by coincidence*, and the coincidence is invisible
to every test that exists. It is not a near-miss of a name either — `mac.c:62`
and `mac.c:72` are two different rows with `etm=0` and `etm=1`, so EtM is a
different algorithm, not a spelling variant of the one we implement. The list is
now `hmac-sha2-256`.

The reason a coincidence is not a property is worth spelling out: change one
line of `enc_ctos` to `aes128-ctr` and `negotiate` hands back the EtM name,
because `pf_match_list` scans *our* list first. The client would then have
agreed to an algorithm it cannot run, in a handshake it just completed.

**Defect 2 — `we_need_for` was a second, looser parameter table.**
`sshclient/live.mbt` accepted four ciphers and five MACs, and the caller then
truncated the derived key to 16 bytes and built an `AesCtrMacCtx` regardless of
what came back. A proposal naming `aes256-ctr` would have run **aes128-ctr with
the first 16 bytes of a 256-bit key**, and reported nothing. Latent — no live
proposal offered it — but it failed *open*, and it was one line from live.
`we_need_for` now delegates to `@bpacket.transport_params`, which aborts on
anything without a `Mode` branch, and the `16`s are gone from `live.mbt`:
they come from the table now.

`live.mbt` also gained a routing guard. That path builds a `MacEncrypt` context
and nothing else, so an AEAD agreement would need the `ChachaPolyCtx` branch and
has to fail loudly instead of being fed into the wrong constructor.

**Scope is deliberately asymmetric.** A *client* proposal is checked. A *server*
proposal is not: negotiation takes the intersection, so a peer may name anything
and the handshake still lands on something we can run. `host/verify_loop23.mjs`'s
six-cipher list is a **server** proposal and is exempt — that was worth stating
because it looks exactly like the thing this loop forbids.

The gate proves the exemption still holds, rather than merely not contradicting
it: `cmd/proposal_kat` emits a deliberately-broken peer fixture (two names with
no packet layer) and the gate asserts it is still `scope=server` and still
unjudged. A gate that had quietly widened into "reject every name we do not
implement" would pass a much simpler test and break connectivity against real
sshd for no safety gain.

**The third truth source is deleted, not trimmed.** `src/kex_names` had four
unused `*_default()` functions naming 6 ciphers and 6 MACs — a third place to
learn algorithm names from, and the part that would most invite the same bug
back. They are gone; the name↔enum mapping stays, because that is a spelling
table and makes no claim about what executes. The GCM ciphers are the sharp
case: `src/aes` really does implement AES-GCM, so "the name resolves" and "the
transport runs it" look identical from the outside.

**Numbers come from outside this tree.** Every parameter is cross-checked
against OpenSSH's own tables in the C reference tree, not transcribed:
`cipher.c:93` / `:105` for `block_size`/`key_len`/`iv_len`/`auth_len`, and
`mac.c:62` for the MAC. `cipher_ivlen` (cipher.c:170-178) is why chacha20's
`iv_len` is 0 and aes128-ctr's is 16 — the same column, two different answers.
Names are cross-checked against `ssh -Q cipher` / `ssh -Q mac`.

That last cross-check earns its keep by including the name we *removed*. If
`hmac-sha2-256-etm@openssh.com` were not a genuine OpenSSH MAC, deleting it
would be a typo fix rather than a policy fix, and the two deserve different
confidence.

**Seven gate failures on first run, all of them real.** Worth recording because
four were self-inflicted and two were the *correct* kind of catch:

- `verdict_stoc` was initialised to `null` and compared against `undefined`:
  five confident wrong failures out of a parser that was working.
- The gate compared OpenSSH's `auth_len` against our `mac_key_len` slot. Two
  different quantities; the accessor for the right one simply did not exist.
- That gap then let `authlen_for` ship a wrong answer: it returned 32 for
  aes128-ctr, where OpenSSH's `auth_len` is **0** and the 32-byte MAC lives in
  `mac_len`. The C cross-check caught it on the next run. "Looks right" and
  "is right" are separate properties, and only the outside authority had the
  second one.
- One check asserted a test *name* appeared in `moon test` output. moon prints
  names only for failures, so it could never pass — and looked exactly like a
  real assertion. This is the same shape as Loop #59's regex that matched
  nothing.

**The gate does not trust the emitter.** `proposal_kat` tags each name
`ok` / `NO-PATH`, but the gate keeps its own copy of the runnable set and
recomputes. Trusting the label would mean the same package evaluating the same
predicate twice — both sides agree, both are wrong, mutation B would pass. That
check exists because mutation B is the one most likely to be written by someone
who "just wanted it to work".

**Results.** `verify_loop60.mjs` 73/73, `loop60_mutations.py` 5 CAUGHT /
1 EQUIVALENT / 0 MISSED. Gate `loop53`–`loop59` all still ALL PASS;
`moon test src/kexflow` 14/14, `src/sshconfig` 10/10, `src/knownhosts` 49/49,
`src/bpacket` 25/25. `src/bpacket` and `src/kexflow` check clean on all four
targets (native / js / wasm / wasm-gc).

`cmd/ssh_live` does **not** build for js / wasm / wasm-gc, and did not before
this loop either: Loop #54 gave `--kh-file` real disk writes through
`moonbitlang/async/fs`, which is native-only. Noted so nobody reads the failure
as a Loop #60 regression.

**The equivalent mutant is the interesting one.** Short-circuiting the new
cipher routing guard to `&& false` changes nothing observable, because
`live_proposal` offers only `aes128-ctr` and the guard never fires. That is a
correct classification, not a gap in the gate: the guard is dead defence on
today's inputs and starts mattering the moment a second cipher becomes
negotiable. Reported as a finding rather than quietly excluded.

**What this loop does not cover.** The invariant is enforced over cipher and
MAC only. `kex_algs` and `hostkey_algs` have the same shape of problem — a
client naming an unimplemented kex would fail the same way — and are tagged
`kind=info` in the emitter so `NO-PATH` always means "over-promising on the
transport". Widening the gate to kex and hostkey is a separate decision with a
real connectivity cost, and it is not silently bundled in here.

**Tooling note, self-inflicted.** A PowerShell one-liner intended to add return
type annotations resolved its path against the *PowerShell* working directory
rather than the process one, and `WriteAllText` truncated
`cmd/proposal_kat/main.mbt` to 0 bytes. The project rule against PowerShell file
editing already covers this; the new datum is that the failure is **silent and
destructive** rather than an error, and `git status` is the only thing that
showed the scope was limited to one new file. Recovered by rewriting the file.

### Loop #59: the client dials what the config says, and pins under the name the user typed

Loop #58 made `cmd/ssh_live` *print* its resolved connection parameters and
checked those against `ssh -G`. Printing the right thing and connecting to the
right thing are different claims, and only the first one had been proven. A
`HostName` that resolves correctly in the dump while the socket still goes to
`127.0.0.1` would have passed every check in Loop #58.

So this loop runs the client against a real SSH peer -- `host/sftp_mitm.py`, the
one Loop #54 uses -- with **no port argument at all**. If it authenticates, the
host and the port came out of the config file, because there is nowhere else for
them to have come from.

#### `HostName` decides where to connect. It does not decide what to pin under.

This was the one thing worth getting right, and it is worth stating because the
wrong answer is invisible. `add_host_to_hostfile(filename, host, key, store_hash)`
takes exactly **one** host, and `write_host_entry(f, host, NULL, ...)` passes
`ip = NULL` (hostfile.c:542 / :476) -- `HostName` never enters the key. Pinning
under the resolved name means the next connection *by alias* looks up a name that
is not in the file, so every connection looks like a first connection and TOFU
fires forever. That failure never errors; it just never remembers.

`--kh-host` therefore now defaults to `--target`, not to a hardcoded `127.0.0.1`.
The gate asserts the *absence* of a `127.0.0.1` line, not just the presence of
the alias line, because a client that wrote both would pass the first check.

#### The `find_user` re-parse that Loop #54 had already declared dead

`run_exec` and `run_shell` each called `find_user(@env.args())` themselves. That
is precisely the "both sides ask the question separately" drift Loop #54 removed
from the known_hosts path -- and it had a consequence Loop #58 could not see:
the user resolved from the config never reached either function. `main` now
computes the user once, alongside host and port, and passes it down; both
functions lost their private `argv` re-parse.

Six `TcpConn::connect("127.0.0.1", port)` call sites became
`connect(host, port)`. Loop #54's own precedent is "they just take one more
parameter", so this is threading rather than a refactor into a session struct.

#### What step 1 does **not** prove

The fixture's `HostName` is `127.0.0.1` and the client's fallback is also
`127.0.0.1`, so step 1 cannot distinguish "dialed the configured host" from
"dialed the default". The **port** is what proves the config drove the dial: it
is absent from argv entirely. The host half is covered by `--config-effective`
against `ssh -G` (Loop #58), and the alias-keying rule is covered by mutation A.
A hostname that resolves differently from `127.0.0.1` would have made the check
*look* stronger than it is; it is written down instead.

#### A gate defect worth the two runs it cost

The known_hosts checks first spelled the key type as `ssh-`. The peer presents
`ecdsa-sha2-nistp256`, so:

- "pin is keyed by the alias" **failed against a correct file**, and
- "pin is NOT keyed by the resolved HostName" **passed vacuously**.

A regex that never matches anything is indistinguishable from a regex proving an
absence, so the second check was decoration that read as evidence. Both now match
`\S+`. The gate also dumps the file's contents on failure -- Loop #40's rule that
the failure and its evidence land together -- because "no line keyed by
loop59-pin" costs a re-run with a debug print to diagnose, and there were three
plausible explanations.

#### Mutations: 3 CAUGHT, 1 EQUIVALENT

| | mutation | caught by |
|---|---|---|
| A | pin keyed by the resolved `HostName` | both keying checks, with the file dumped |
| B | the port from the config is ignored | step 1 cannot connect |
| C | the user from the config is ignored | step 1's reported user |
| D | gate stops checking `--proposal` | EQUIVALENT |

#### Process discipline

Loop #53's rule, kept because it is the reason a failure stays a failure: the
peers are killed and `.loop59` removed in a `finally`, so a failure part-way
through cannot leave a peer listening that the *next* gate connects to.

### Loop #58: ssh_config on the client's path, and the rule that decides whether it is usable

Loop #57 ended with `src/sshconfig` proven correct against `ssh -G` and still
called by nothing. That is not a resting state. It is the exact condition the
first-block-only bug survived in for thirty loops: correct-looking code with no
caller rots the way wrong code does, because nothing ever exercises it.

So this loop wires it into `cmd/ssh_live` and checks the thing that decides
whether the feature is worth having at all -- **precedence**.

#### The rule

OpenSSH takes the first value obtained for each keyword, and the command line is
read before any file:

```
--user / -o Key=Value   >   the config file   >   the client's built-in default
```

Checked, not assumed: `ssh -G -F fallback.conf -o User=cliu -o Port=2200 web1`
answers `user cliu`, `port 2200` -- the command line wins over a file that sets
both, and also over a file that sets neither.

If the file were consulted only when the caller said nothing, then anyone with a
config file could never override it from the command line, which is the everyday
case. That is why `-o` is here rather than deferred.

**The whole chain is computed once, in `cfg_resolve`.** `--proposal` already
existed for the same reason (Loop #38): "the connection succeeded" does not show
*which* configuration was used, so there has to be an offline path that prints the
answer. `--config-effective` is that path, and it returns before anything dials.

The `--user` step is asserted **against the client's own rule, not against
`ssh -G`**, because `ssh -G` has no `--user`. It is labelled as such in the gate
output so nobody later reads it as a cross-check. That gap was in the first draft
of this loop: `--config-effective` originally showed only `-o` and the file, so
the top of the chain was claimed but unobservable.

#### Two rules again, and the second is still the one that matters

1. **VALUE** -- every keyword the client resolved must equal `ssh -G`'s answer.
2. **COMPLETENESS** -- every keyword the config or the overrides *moved* must be
   resolved. The moved set comes from diffing `ssh -G` with and without the
   fixture, so OpenSSH decides what counts as changed.

Rule 1 alone passes a client that resolves nothing. Mutation B (ignore `--config`
entirely) is caught **only** by rule 2:

```
FAIL  case cascade.conf db1.prod.example.com answers everything the config changes
      not resolved: hostname, user, port, identityfile
```

`ssh -G` also prints every compiled-in default, so comparing all four keywords
unconditionally would be asking the client to invent `port 22` and seven default
`IdentityFile` paths. The first draft of the gate did exactly that and produced
six confident, wrong failures.

#### `IdentityFile` ordering

`-o IdentityFile=` is the first value obtained, and `IdentityFile` accumulates, so
the override **precedes** the file's entries rather than replacing the list. The
gate compares the ordered `|`-joined list for this reason: mutation C produces
the same *set* in the wrong order, and a membership check would have called that
correct.

#### `find_port` learned about arguments that take a value

`find_port` scans argv for the first all-digits token. `--target 2222` and
`-o Port=2220` put a digits-only string in argv for a reason unrelated to the
port, and the scan would happily dial the wrong one. It now skips the token after
`--target`, `-o` and `-F`. This was not a bug before this loop -- there were no
such arguments -- and it would have become one the moment the feature landed.

**Nothing moves without `--config`.** Every `ConnConfig` field is empty unless a
file was given, and `main` substitutes only non-empty ones. Every existing gate
passes no `--config` and dials `127.0.0.1:22222`, so none of them can have moved;
`--proposal` is asserted byte-identical in the gate as the concrete form of that
claim.

#### Mutations: 4 CAUGHT, 1 EQUIVALENT

| | mutation | caught by |
|---|---|---|
| A | `-o` loses to the file | value rule (4 cases) |
| B | `--config` ignored entirely | **completeness rule only** |
| C | `-o IdentityFile` appended last | value rule, by ordering |
| D | `--user` loses to `-o` | the `--user` assertion |
| F | gate stops checking the no-config run | EQUIVALENT |

C was first written as "replace the list" and was caught by a **compile error**,
not by an assertion -- `Array::remove_at` does not exist in this MoonBit version.
A mutation caught by a broken compiler is not evidence, so it was rewritten as an
append-last mutation that compiles, and the CAUGHT it produces is the ordered
comparison doing its job.

#### Still not done

`cmd/ssh_live` dials `127.0.0.1:22222` by construction; it is a test client
against a local sshd, not a general SSH CLI. `HostName`/`User`/`Port`/`IdentityFile`
are now resolved and printable, but the resolved `hostname` is **not** yet the
dial target -- wiring that means this client stops being a fixed-target harness,
which is a larger change than a config flag and is left for its own loop.
`Match`, `Include` and quoting remain unimplemented, as in Loop #57.

### Loop #57: ssh_config resolution, diffed against OpenSSH's own `ssh -G`

This loop did not start by auditing `ssh_config`. It started by measuring which
`src/` packages have **no production importer** -- after Loop #56 left a survey
script behind. Four qualify: `kex_names`, `sshconfig`, `test_nested`, `wt_socket`.

**The survey's first answer was wrong, and that mattered.** The first run counted
another `src/` package as a *test* reference rather than a library reference, and
reported seven "dead" packages including `aes`, `bpacket`, `sha512` and
`kexc25519`. All four are live -- `src/kexflow/moon.pkg` imports `kexc25519`.
Building a loop on that number would have been building on a miscount. The lesson
is the one Loop #40 already wrote down about nested gates: a classifier that is
silently wrong is worse than no classifier, because it produces a confident
number.

#### What was actually wrong

`src/sshconfig` is not merely unused. `match_host_option` **searched only the
first matching `Host` block**:

```
Host web1
  User deploy
Host *
  Port 2222
```

`ssh -G web1` answers `user deploy` **and** `port 2222`. The old code answered
`deploy` and, for `Port`, "no such option". `Host *` at the end of a file is the
single most common thing in every `~/.ssh/config` on earth. It was never noticed
because nothing called it -- and because its only test checked a config where the
keyword happened to be in the first matching block.

Three more parser bugs fell out of checking against the authority rather than the
spec: options **before** the first `Host` were accumulated into a pattern-less
section and then **dropped**; `Keyword=Value` became a keyword literally named
`Port=2202`; and a trailing `# comment` stayed in the value.

#### The rules, each confirmed before it was written down

Nothing here was written from memory. Every line was settled by running
`ssh -G` on OpenSSH_for_Windows_9.5p2:

1. **All** matching `Host` blocks participate, in file order -- not just the first.
2. Single-valued keywords keep the **first** value obtained.
3. Multi-valued keywords **accumulate**. `IdentityFile` is one: two matching
   `Host x` blocks both survive. This is why arity is per-keyword. A resolver that
   treats everything as first-wins silently drops a key; one that treats
   everything as accumulate turns `User` into a list. Both fail quietly.
4. Options before the first `Host` apply unconditionally, and win over the rest.
5. One match on a `!` pattern discards **the whole block**, positive patterns
   included. It is not "that one pattern is skipped".
6. Keywords are case-insensitive (`readconf.c` uses `strcasecmp`).
7. `Host` patterns are matched case-**sensitively**. `ssh_config(5)` is ambiguous
   here, so it was checked rather than assumed: `Host Web1` does not match `web1`.

The last two are the kind of pair that is easy to get backwards and impossible to
guess from the prose, which is the argument for having an executable authority.

#### The gate: two rules, and the second is the one that matters

`host/verify_loop57.mjs`, 21 checks, two-sided on purpose. Loop #55 needed three
sides because its authority was a published constant two implementations could
both misread. Here the authority **executes**, so a third leg could only agree
with one of the two.

1. **VALUE** -- every keyword MoonBit resolves must equal `ssh -G`'s answer.
2. **COMPLETENESS** -- every keyword where the fixture *changed* OpenSSH's answer
   relative to an empty config must be resolved by MoonBit too.

Rule 1 alone passes a resolver that silently drops half the file, because a
resolver that answers nothing has no wrong answers. Rule 2 is what turns "I found
User" into "I found Port too, two blocks down". Mutation A restores the original
bug and is caught **only** by rule 2:

```
FAIL  case fallback.conf web1 answers every keyword the fixture changes
      not resolved: port, serveraliveinterval
```

The changed-keyword set comes from diffing `ssh -G -F <fixture>` against
`ssh -G -F empty.conf`, so OpenSSH decides what counts as changed rather than this
gate. That is what lets completeness be checked without hardcoding a list of
keywords the fixtures happen to set.

#### The fnmatch test that was wrong twice, and hid itself

`cmd/sshconfig_test` counted passing `if` conditions and printed them against a
**hardcoded** `fnmatch_total = 23`, then exited 0 either way. The block holds 25
conditions, so it printed `23/23` -- green-looking arithmetic that could not be.

Two of its expectations were wrong, both verified with `ssh -G`:

- `fnmatch("a*b*c", "abdc")` -- it asserted **no** match. OpenSSH matches: `a` +
  `""` + `b` + `"d"` + `c` is exactly the pattern.
- `fnmatch("*.ngs.fi", "ngs.fi")` -- it asserted a match. OpenSSH does not match:
  `*` can match the empty string, but `.ngs.fi` still has to match `ngs.fi`
  afterwards, and the lengths differ.

Both errors claimed *more* matching than glob gives. **The implementation was
right and the test was wrong, twice** -- so the fix was to delete the block rather
than repair it: the same 25 expectations now live once, as a table, in
`src/sshconfig/sshconfig_test.mbt` t10, where a mismatch is counted and asserted
and a failure names the case. A second copy is what let the two drift in the first
place; the copy that drifted was the one a human read.

This also fixes `moon test src/sshconfig`, which reported **`Total tests: 0`** --
Loop #24 wrote its checks as a printing command, so the package looked exercised
and was not. It now has 10.

#### Mutations: 5 CAUGHT, 1 EQUIVALENT

| | mutation | caught by |
|---|---|---|
| A | first matching block only (the original bug) | completeness rule |
| B | `!` pattern ignored instead of vetoing its block | value rule |
| C | keyword lookup case-sensitive | value rule (`user=deploy\|fallback`) |
| D | pre-`Host` options dropped again | completeness rule |
| E | `IdentityFile` stops accumulating | **`moon test`, not the gate** |
| F | gate stops checking case coverage | EQUIVALENT |

E is reported the way it happened. The fixtures give one `IdentityFile` each, so
the gate cannot see its accumulation; only `t7_multivalued_keywords_accumulate`
does. Saying otherwise would have meant inventing a fixture the loop did not
build.

F is a finding: no emitter skips a case on this tree, so the coverage assertion is
not observable. The claim is bounded to these inputs.

#### Not done

`Match`, `Include`, quoting and escapes are not implemented, and `#` unconditionally
starts a comment, so an `IdentityFile` containing `#` is truncated. Written down
rather than papered over. The package is still **not wired into any client** --
`cmd/ssh_live` does not read a config file. That is the next step, and the reason
this loop fixed the resolver before wiring it: the bug was worth finding either
way, but wiring a wrong resolver into a client would have made the user's
connections fail in a way that is very hard to read back to this.

### Loop #56: known_hosts, three sides -- and the two references that had fallen behind

The known_hosts chain in `verify_c/` is the oldest in the repository and, until this
loop, nothing ran any of it automatically:

```
knownhosts_python_ref.py   42 self-checks against hashlib / hmac
      |                    -> writes _knownhosts_ref_out.txt   (the vector file)
      v
gen_knownhosts_test.py     sanity-checks against FIPS 180-4 and RFC 2202
                           -> emits src/knownhosts/knownhosts_test.mbt
                           -> emits verify_c/_knownhosts_kat.h
      |
      v
knownhosts_harness.c       28 assertions, built by build_knownhosts.bat
```

`knownhosts_test.mbt` asserting against vectors that the generator wrote from a file
that Python wrote is a closed loop: a mistake anywhere inside it is invisible to it.
**Two things are done here that nothing did before.**

**One: the sides emit verdicts, not just bytes.** The new `cmd/knownhosts_kat` and
the Python reference both print the *decision* each reaches for every vector --
`0=Ok 1=Mismatch 2=Unknown 3=Invalid 4=CertAuthority` -- in the vector file's own
`key = value` shape, so `host/verify_loop56.mjs` can line them up by name. The point
is that a disagreement about what a pinning rule **means** shows up here; a
disagreement about SHA-1 arithmetic is not the interesting one, and that has
published constants.

**Two: drift is an assertion.** The two generated files are compared byte for byte
against what the generator produces right now. They were regenerated once by hand
and then left alone, and a generator change nobody re-ran would otherwise sit there
looking fine.

#### The finding: two references still had the Loop #51/#53 fail-open

Only `src/knownhosts` had the fix. `knownhosts_harness.c` and
`knownhosts_python_ref.py` were both still on the Loop #14 rule, where a
`@cert-authority` entry takes part in last-match-wins. Comparing a CA entry's blob
against the presented host key is meaningless -- it holds the **CA's** public key,
not this host's -- and **equal is fail-open**: a peer presenting the CA's own key
as its host key used to be accepted. The vector set predated the fix, so **neither
reference side had a single CA vector to notice**. Loop #51 fixed the bug and
Loop #53 wrote down why; nobody noticed that fixing it in one place out of three is
not a fix. Both sides are corrected here, `HOST_CERT_AUTHORITY = 4` is added to both,
and C1-C3 pin it:

| case | what it is | expected |
|---|---|---|
| C1 | CA entry covers the host, no direct entry | `4` CertAuthority |
| C2 | direct entry **and** CA entry for the same host | `0` Ok -- the direct one speaks |
| C3 | presenting the CA entry's **own** key | `4`, never `0` |

C3 is the load-bearing one: it is the case that returned `Ok` before the fix.

`CertAuthority` is not `Unknown` and the difference is operational, not cosmetic:
"nobody has pinned this host" means *add a line*, "pinned via a CA and we do not
verify certificates" means *get a new CA or re-sign*. Both refuse; they must not
report the same thing. `check_host_key_strict` deliberately does **not** upgrade
`CertAuthority` to `InvalidEntry` -- that would merge it with "the entry is broken".

#### The case table is not uniform, and that is the trap

The vectors do not spell themselves out by id. V2 is a wildcard match *of V1's line*
and has no line of its own; V3/V6/V7 present `V1_blob_hex`, not their own
`V*_blob_hex`; V7 is the strict path; V10 is two cases sharing one expected value;
V8 is marker parsing and has no verdict at all. The first version of the emitter
derived every key name as `<id>_knownhosts_line` / `<id>_presented_blob_hex`, which
fed an **empty entry list** into four cases -- and `parse_file` on nothing returns
no entries, which is a real verdict, `Unknown`, so those cases *passed*. That is the
whole failure mode this loop is about, and it is now a hard abort:
`assert_full_coverage` fails if the vector file carries an `_expected_status` that no
row claims.

That guard earned its keep immediately, on the author: the suffix length was written
as 15 instead of 16, so `V1_expected_status` sliced down to `V1_`, and the guard
reported "V1 has no row in the case table" -- an error that looks correct and is
not. The suffix is a named constant now.

**C2 is two known_hosts lines.** They were first written as one `key = value` whose
value contained a newline, which quietly breaks the vector file itself: it is
line-oriented, and both `pairs()` in the MoonBit emitter and `parse_kv` in Python
read a second key out of a value that does not exist. It is two keys now
(`C2_knownhosts_line`, `C2_knownhosts_line_ca`) and the generator splits them into
`C2_KH_LINE` / `C2_KH_LINE_CA` for the C harness, whose `parse_kh_line` takes one
line at a time.

#### The gate, and four things it caught in its own first run

`host/verify_loop56.mjs`, 41 checks. It refuses to overwrite a key it has already
parsed, and it checks the **key sets** match before comparing values -- a case that
exists on one side only does not error, it just stops being checked.

- `V10_expected_status` was printed once per sub-case. A duplicate key, correctly
  refused. The emitters now print it once, and the gate compares each sub-case to it.
- The `*_strict_got_status` row was a duplicate wearing a different prefix: V7 *is*
  the strict case. Both sides dropped it.
- `^\s*fail\b` was case-sensitive and the harness prints `FAIL` in caps, so the
  counter was always zero -- dead code shaped like a working second opinion. The
  `Total:` line was doing the real work.
- `build_knownhosts.bat` had CJK in `REM` comments. cmd reads a `.bat` in the OEM
  code page, so the multibyte comment was split into byte sequences cmd then tried
  to **execute**: the build still succeeded, but three `'...' is not recognized as
  an internal or external command` lines landed in the middle of the output. That
  noise is what made a real 24/28 regression read as a build break. The comments are
  ASCII now, with a note saying why, and the script deletes the previous `.exe`
  before compiling (the `build_ed25519.bat` rule from Loop #55).

#### Coverage the emitters cannot supply between them

Both emitters have `assert_full_coverage`, but two implementations that are wrong in
the same way check each other perfectly. Delete the C3 row from **both** tables and
their key sets stay identical while one case quietly stops being decided at all.
The gate therefore reads `_knownhosts_ref_out.txt` itself -- the one artifact neither
emitter gets to curate -- and fails if any `*_expected_status` in it has no verdict.
`host/loop56_mutations.py` mutation E deletes the row from both tables *and* switches
the emitter's guard off, and the gate's own check is what catches it.

**Representation, not semantics.** Python's `marker` is the raw token (`@revoked`)
and its two internal callers compare against `'@revoked'`; C's `kh_entry_t.marker`
and MoonBit's `Marker` enum both carry the bare name. Three sides first met here and
disagreed -- on representation, not on what a marker means -- so it is normalized at
the emitter boundary rather than by rewriting the Python reference's internals.

#### What the C side can and cannot contribute

`knownhosts_harness.c` asserts `s == V*_STATUS`, so it yields a boolean, not a
verdict. MoonBit and Python are compared **by value**; C is compared on whether it
agreed with the pinned number. That asymmetry is the harness's, not the gate's, and
it is written down rather than papered over.

#### Mutations: 5 CAUGHT, 1 EQUIVALENT

| | mutation | verdict |
|---|---|---|
| A | MoonBit lets CA entries back into last-match-wins | CAUGHT (C1/C2/C3 + 12 unit failures) |
| B | the C harness stops treating a CA entry as "not a pin" | CAUGHT (24/28, four named assertions) |
| C | the Python reference does the same | CAUGHT (three case disagreements) |
| D | a generated file is hand-edited | CAUGHT by the drift check |
| E | the C3 row is deleted from both tables, guard off | CAUGHT by the vector-file coverage check |
| F | the gate's `parseKeyed` drops its `=` line guard | **EQUIVALENT** |

F is a finding, not a failure: no line either emitter prints begins with `=`, so the
guard cannot be observed here. The claim is bounded -- *on these outputs* -- and the
distinction from `MISSED` is a verdict rather than a comment, because `MISSED` is an
accusation and conflating the two makes both useless.

**The mutation harness had a bug, and it is worth recording because it produced a
confident wrong answer.** Its first version wrote each edit from the pristine text,
so for a mutation with two edits to the *same* file the later one silently undid the
earlier. Mutation E therefore never deleted the C3 row from `main.mbt` at all -- it
only disabled the coverage guard, and it reported a crisp `CAUGHT` about a key-set
mismatch that had nothing to do with what it claimed to test. Reading the current
file content per edit fixes it. `python host/loop56_mutations.py E` now runs one
mutation by label prefix, which is what made the discrepancy findable at all: the
same mutation in isolation behaved differently from the same mutation in sequence.

**Workspace note, not a project fact:** the `edit` tool in this workspace could not
round-trip CJK inside `old_string` and reported "could not find the exact text" on
lines that were present and unchanged. One attempt to fix a stray `")` that way
wrote that line back as **invalid UTF-8**, which Python then refused to parse and
which `edit` could still not match -- the one repair had to go through a script.
Use **ASCII-only anchors** in `edit`, and in the mutation script too: an anchor that
fails to match on an encoding round-trip reports `NOBUILD`, which reads as "nothing
proven" rather than "the script is broken".

### Loop #55: a second pair of eyes, runnable

`verify_c/` has held nine C harnesses and seven Python references since the
early loops. Every one was run by hand and the result went into a document.
**Nothing ran them again.** `scripts/compare_kat.mjs` exists and works; nothing
invokes it. The nine `build_*.bat` scripts are named in `docs/` and nowhere
else. A `git grep` for `build_ed25519` outside `verify_c/` hits only
documentation.

That is worth stating plainly because it is the same shape Loop #53 was written
against: a fixture and a verifier sharing one mistake. Ed25519, AEAD and the
binary packet layer are the three places where a wrong answer is **silent** -- a
verifier that accepts a forged signature, an AEAD that accepts tampered
ciphertext, a length prefix off by four -- and all three were being checked only
against constants this repository also wrote.

**What runs now.** `host/verify_loop55.mjs`, three seconds, and it compares
*values* rather than counting lines:

| side | what it is |
|---|---|
| MoonBit | `src/ed25519` via the new `cmd/ed25519_kat` |
| C | OpenSSH's original `ed25519.c` (`verify_c/ed25519_harness.c`) |
| Python | `cryptography`, libsodium/OpenSSL-backed (`verify_c/ed25519_python_ref.py`) |

Each side prints the vectors in a different shape, so the gate parses each into
a map keyed by vector name and compares `pk` and `sig` across all three. A
shared text format would have been cosmetic and would have broken the first time
one side's banner changed.

**A published authority is not a second opinion, so all three are checked
against each other as well as against RFC 8032.** Two implementations agreeing
with a standard is evidence. Two implementations agreeing with each other
because both were written from the same misreading is not, and nothing here can
rule that out -- which is exactly why the malleability check is asserted
separately instead of being folded into the byte comparison.

**The negative cases are the load-bearing part, and getting them right took a
mutation.** `s == L` (malleability), a tampered message and a wrong key change
no positive vector at all. A verifier that accepts a malleable signature agrees
with all three sides on every RFC 8032 vector and is still exploitable, so a
gate that only compared the vectors would report ALL PASS.

**The first mutation run proved the opposite of what was assumed here, and the
harness was at fault.** `MISSED -- the gate still reported ALL PASS` for "disable
the range check". The malleability vector was built with `s = L`, and L's top
byte is `0xed`, so `sig[63] & 0xE0 != 0` rejected it at the **first** check --
the range check was never reached. The test had been passing for a reason that
had nothing to do with malleability.

The real attack is `s + L`, not `L`: a second valid signature over the same
message. `s + L < 2L < 2^253`, so its top byte is under `0x20` -- both the
high-bits check and the S-range bit check pass, and the *only* thing that can
reject it is the range check. That is the vector that tests the thing. It also
carries its own self-check: if `s + L` overflowed 32 bytes it would have wrapped
back into range and stopped being malleable, so the emitter prints the carry and
the gate requires it to be clear. A test that quietly stops testing itself is
worse than no test.

The original signature is re-verified in the same block as the control. Without
it, "the malleable one was rejected" could just mean `verify` rejects everything.

**One mutation here turned out to be an equivalent mutant, and that is recorded
as its own verdict rather than as `MISSED`.** Disabling `sc_is_in_range_bytes`
does not change what this client accepts: `s + L` is still rejected. Asking
Python settled why -- `cryptography`, which is OpenSSL/libsodium-backed and
shares no code with this repository, **also rejects `s + L`** (`InvalidSignature`).
So the rejection is a property of the format, not of one line here, and the range
check is defence in depth rather than the sole guard.

`MISSED` is an accusation and `EQUIVALENT` is a finding; conflating them makes
both useless, which is why `loop55_mutations.py` grew a fifth verdict. The
concrete claim is bounded and stated that way: **equivalent with respect to the
vectors this gate tests.** A vector that separated them does not exist yet, and
inventing one would mean hand-rolling a signature no other implementation
accepts -- the thing Loop #53 twice declined to do.

The mutation that *does* prove the negative cases are load-bearing is dropping
the final `pack(P) == R` comparison instead. No positive vector changes; a
forged signature becomes accepted, and the tampered-message, wrong-key and
malleability checks are the only things that see it.

**The C harness's own verdict is asked before anything is compared with it.**
If the reference says FAIL, "MoonBit matched it" is not good news, and a gate
that only compared values would print a cheerful match.

**`build_ed25519.bat` had `%%` in a `REM` line**, so cmd expanded it and every
run printed `'%' is not recognized` before the build. Harmless -- and it trained
everyone to ignore noise in the output of the one script a gate shells out to.
The script now also **deletes the previous `.exe` before building**: a stale
binary that still passes is the Loop #47 failure exactly, one level down.

**AEAD and bpacket are regressions only, and the gate says so.** Their C and
Python sides use *independently generated* case sets -- `C1a` versus `S1a` --
so there is nothing to line up and no shared vector file to compare against. The
gate checks that both harnesses still build and pass, which catches a harness
that stopped compiling, and says in its own header that this is not a substitute
for a three-way comparison. Claiming more than that would be the kind of
overclaim this loop exists to remove.

**The gate's first run caught a bug in the gate.** The Python reference prints
its RFC vectors and *then* a "Tampered Message Rejection" section that also has a
`sig =` line; the parser kept `current = "Test 3"` and silently overwrote the
signature, so the gate reported "Python disagrees with C and MoonBit" and pointed
at the reference. It is now wrong twice over on purpose: a `=====` banner ends the
section, and a key that already exists raises instead of overwriting. A parser
that can silently replace a value it already has will, given any reference with
more than one section, report a confident wrong answer -- which is the same shape
as the bug the loop exists to catch, one level up.

**`hx()` is written out again rather than shared with `src/aead`.** The two never
parse the same input -- RFC 8032 constants here, RFC 8439 constants there -- so
sharing a parser would make "both sides mis-read the same character" happen once
instead of twice, which is the failure being hunted.

**Verified:** `verify_loop55` `ALL PASS (17 checks)`, 3 seconds.
`host/loop55_mutations.py` 3 CAUGHT / 0 MISSED / 0 NOBUILD / 0 CRASH, where the
three mutations are "a signature bit is wrong" (caught by the comparison and by
`moon test`), "s == L is accepted" (caught only by the negative case, which is
the point), and "the MoonBit side prints nothing" (caught because a comparison
with a missing side must fail rather than pass vacuously).
`moon test src/ed25519` 23/23 unchanged.

**What it does not retire.** Six of the nine harnesses -- hostkey, kexflow,
knownhosts, kex, kex_c25519, and the SHA-2 / HMAC / poly1305 / x25519 ones --
still run only by hand. Each needs a MoonBit-side emitter in its reference's
format before it can be compared the way ed25519 now is, and that is one loop
each.

### Loop #54: the pin that outlives the process

Loop #52 made TOFU remember, in a browser. The native client kept **printing**
the line: `--kh-tofu` produced text, a human copied it into `known_hosts`, and
the pin lived exactly as long as the terminal they had open. That is the same
defect Loop #52's own title names, on the other transport -- and after Loop #53
it got worse, because the hint on a rejected certificate tells the user to add
a `@cert-authority` line by hand while the tool that could write the file does
not exist natively.

**"This moon version has no file IO" was out of date.** Loop #48 wrote that and
it was true then. `moonbitlang/async/fs` is in `.mooncakes` with a native stub
(`stub.c`, `dir.c`, `watch_windows.c`) and the whole surface this needs: `exists`,
`read_file`, `write_file`, `rename`, `remove`.

**`write_file(append=true)` truncates unless you also change `create_mode`.**
This is the footgun worth knowing about, and it is silent:

```
create_mode defaults to CreateOrTruncate
append     defaults to false
```

Those two defaults are safe *together*. Pass `append=true` alone and the file is
truncated and then one line is appended to nothing -- no error, no log, and the
next connection reports the host as unpinned, which reads as "TOFU forgot
again" wearing a completely different cause. `OpenOrCreate` is the mode that
makes append mean append, and `store_test.mbt` asserts the *property* (existing
entries survive) rather than the mechanism, so the test still holds if the
implementation is rewritten.

**Append, not read-modify-write.** Both preserve existing content, so the gate
asserts the property and not the choice. Append is narrower: a read-modify-write
can lose a concurrent writer's entry outright, while an append can only fail to
add its own. There is no lock, and that is a decision rather than an omission --
concurrent writers can still race, and it is written down instead of implied.

**A torn append costs the line being added and nothing else, and that was
checked rather than assumed.** `parse_file` skips a line it cannot parse, so a
fragment is ignored rather than read as a wrong key -- the failure that would
actually matter, because a half-written entry that *did* parse would report a
mismatch against a host nobody changed.

**The gate's isolation is a separate process, which is stronger than Loop
#52's fresh page.** Nothing carries over between the two runs except the file on
disk -- no module variable, no Worker, no open connection. "The client
remembered" and "the client is still holding the first connection's state" are
indistinguishable from inside one process; a new process makes them different
facts.

**What step 1 asserts past "a line appeared" is the part that is easy to get
wrong.** The file already holds a comment, an unrelated direct entry and an
`@revoked` line. A write-back that rewrites instead of appending destroys all
three, and the *next* connection still authenticates on the new host -- so the
damage stays invisible until the day somebody relies on a pin they already had.
"Exactly one line added" does not catch it either: truncate-then-append also adds
exactly one line. Only the three preservation assertions do.

**Reading the file is a decision input, not just a write target**, so step 4
pins a key that is *not* the presented one and requires `HostkeyMismatch` with
zero authentication attempts. A `--kh-file` that was only ever written would pass
every other step of this gate.

**The write-failure case is its own step because the failure this shape invites
is the exact one Loop #52 had to fix on the browser side**: print `accepted`,
quietly drop the pin. And the notice has to separate two different failures --
the credentials already went out, so the connection succeeded; what failed is
the *remembering*. Reporting it as a connection failure tells the user something
was refused, and reporting it as success tells them they are pinned.

**`main` became async; nothing else did.** Reading a file is async, and
`kh_policy` had six call sites each re-parsing `argv`. The fix is to resolve once
in `main` and pass a `KhConfig` down, so the `run_*` functions stayed **sync**
and each gained one parameter. The alternative -- making each caller async --
would have put the read six times and reintroduced the read/write drift that
`KhConfig` exists to remove. It also puts `--kh-file` resolution *after* the
`--proposal` early return, so that path stays a pure offline dump.

**`has_line` was extracted rather than written twice.** `append_line` already
contained the "is this line already here" loop, and the file path needs the same
predicate against different storage. `append_line` now goes through
`to_line` + `has_line`, which also removes the inline field-order duplication
its own comment complained about.

**A read that fails forces strict on, and that is the only safe reading.**
A user who cannot read their own trust anchors must never be accepted *because*
they could not read them -- that translates "storage is broken" into "trust
whatever is offered". `Missing` and `Unreadable` are separated in the transcript
so the user learns their file has a problem, while the *trust decision* treats
both as "no pin here" and refuses.

**`src/khfile` does not depend on `src/knownhosts`, deliberately.** Row format
belongs to the format layer and the dependency runs *that* way: the format
package is used by the platform package, not the reverse. The first draft had
`khfile` call `has_line` and it was removed -- one fewer edge that can drift.

**Deleted `src/knownhosts_store`**, 19 lines of Loop #19 `extern "wasm"`
scaffolding with zero importers. The repo-root `moon check --target native` is
*still* red afterwards, but for a different and correct reason: `src/ws_socket`,
`src/wt_socket` and the `cmd/wt_*` executables are js/wasm-only live packages.
Per-package checking is the right granularity in a repository with per-target
packages; a root-wide native check cannot be green here and chasing it would
mean deleting working code.

**Verified:** `verify_loop54` `ALL PASS (16 checks)` -- five steps, every one a
separate `cmd/ssh_live` process against its own man in the middle.
`host/loop54_mutations.py` 3 CAUGHT / 0 MISSED / 0 NOBUILD / 0 CRASH.
`moon test src/khfile --target native` 8/8. No regression: `moon test
src/knownhosts`, `verify_loop41` 29, `verify_loop47` 19, `verify_loop52` 9,
`verify_loop53` 26.

### Loop #53: `@cert-authority` becomes a real trust anchor

Loop #51 turned the fail-*open* off and stopped there: a `@cert-authority` line
was parsed, noticed, and refused, but nothing was ever verified against it. That
is the right answer for a client that cannot verify certificates -- and it makes
the standard deployment impossible. Puppet, Chef and Ansible all ship SSH host
certificates signed by a CA; a client that refuses every certificate is a client
that cannot be pointed at a fleet those tools manage.

So this loop makes the CA entry the thing it is named after: a **trust anchor**.
The certificate is accepted when the pinned CA signed it, it is inside its
validity window, and it names this host.

**The hard part was not the cryptography -- it was four facts about the blob that
I had wrong, and all four fail silently.**

| what I would have written from memory | what the bytes say |
|---|---|
| `cert type`: 1 = host, 2 = user | **`USER = 1`, `HOST = 2`** |
| inner key field carries its type name | **bare public key material**, no type name (32 bytes for ed25519) |
| `principals` is a comma-separated ASCII list | **one string**, holding length-prefixed substrings back to back (`00 00 00 10 host.example.com`) |
| `signed_data` = `nonce..reserved` (192 bytes) | **`blob[0 : len - 4 - len(sig)]`** (247 bytes), including the type name *and* the signature-key field |

Getting the type constants backwards does not "support one more certificate" --
it treats a certificate issued **to alice** as proof of a **host's** identity. The
two have different principal semantics and a different meaning entirely. The
values here came from signing one certificate with and without `ssh-keygen -h`,
reading the type field out of the blob, and cross-checking against what
`ssh-keygen -L` prints.

**The `signed_data` one is the reason this loop needed an independent oracle.**
The 192-byte reading is off by 55 bytes, and an ed25519 verifier given the wrong
message does not raise -- it returns "invalid signature". Every self-made vector
would therefore have been checked by a *broken* verifier and come out red for the
right-looking reason, or, once the fixture was signed by the same broken
implementation, come out green. The fixtures cannot catch it, because the
fixtures and the verifier would share the same mistake.

So `host/cert_signed_data_oracle.mjs` does not trust the layout: it takes the
blob's **every contiguous slice** and asks OpenSSL whether any of them verifies.
Exactly one does, and it is the 247-byte one. The oracle self-checks against a
self-signed vector before it will say anything (`host/cert_oracle_selfcheck.mjs`)
-- an oracle that is itself unverified is how a wrong answer gets promoted to a
spec.

**The signature check runs before every semantic check.** Every field in the
certificate is attacker-supplied until the CA signature verifies, so reading
`cert_type` first is feeding peer bytes into a branch. Written as a
non-negotiable rule with the reason next to it, because reordering it "for a
better error message" breaks nothing that any test would catch: each individual
check stays green.

**Six conditions, and `--kh-tofu` is not an exception to any of them.** There is
no case where a certificate is accepted without a pinned CA. A certificate with
no local anchor is indistinguishable from one a man in the middle invented, and
TOFU cannot help: there is no single key to remember, there is a CA to trust.

**Direct pins still beat CA entries, certificates included.** A known_hosts with
both a direct pin and a CA anchor, presented with a valid certificate, is a
`Mismatch` -- not "certificates are unsupported". Loop #51's priority rule
exists so a genuine key change is not laundered into an unimplemented-feature
error.

**`CertAuthority` and `CertUntrusted` are different failures with opposite
remedies.** The first means "an anchor is configured and this certificate does
not match it" (re-sign, or the CA changed). The second means "no anchor exists
at all" (add one line). Both refuse; telling the user to go hunting for a man in
the middle when the fix is one config line is the wrong answer either way. This
is also why `PinVerdict::CertAuthority` was renamed to `CertRejected(String)` --
its meaning changed under Loop #51, and a same-named constructor in two enums
does not compile.

**The clock is injected, and the default is fail-closed.** `KnownHostsPolicy::now`
defaults to `0`, which is "not yet valid" -- i.e. reject. The failure mode for
forgetting to pass a clock is a refusal, never an acceptance. And it must be
injected rather than read: the gate re-runs "an expired certificate must be
refused" forever, and a wall clock would make that assertion permanently true
after the day it was written. The drivers pass `@env.now() / 1000`; the unit was
measured against Python's `time.time()`, not assumed. An extern `Date.now()`
version was written first and deleted -- one less FFI boundary, and Loop #52 had
already paid for the bugs on that boundary.

**The certificate algorithm is advertised only when an anchor exists.** OpenSSH
offers `ssh-ed25519-cert-v01@openssh.com` unconditionally. Offering it
unconditionally is not a security gain here, and it would move the KEXINIT
baseline in `verify_loop41` / `verify_loop45` byte for byte. This is a
deliberate deviation, marked as one in the source, so the next person to
"complete" it reads the argument first.

**The gate refuses for the right reason, and that is the assertion.** Two
outcomes that look like failures are the *strong* outcomes: with no anchor
configured, the client never offers the certificate algorithm, so the peer has
nothing to negotiate and the handshake dies at **agreement** -- the client never
reaches a pinning decision at all, let alone sends credentials. Asserting
`HostkeyUnknown` there would demand the weaker behaviour and read a correct run
as a failure. Each refusal additionally asserts the leaf name, that the hint
names the actual remedy, that `auth_attempts == 0`, and that the peer really had
a host key configured -- absent must never be read as zero.

**Two of the awkward decisions are not guesses -- they are `hostfile.c`.**

- **The CA is found by issuer, and the first match wins.** `hostfile.c:377`
  handles `want_cert` by comparing `k->cert->signature_key` against each entry's
  key and `break`ing on the first hit with the comment "A matching CA exists".
  That is byte equality against the **issuer**, not last-match-wins, and it is
  what `find_ca_entry` does. Last-match-wins is the rule for the *direct* key
  path precisely because a bare key line is a claim about a host; a certificate
  names exactly one issuer, so there is nothing to order.
- **Revoking a CA kills every certificate it cut, host-scoped or not.**
  `hostfile.c:321-330` sweeps every `MRK_REVOKE` entry globally and, for a
  certificate, compares against `k->cert->signature_key` as well as the key
  itself. The `revoked-ca` case in the gate exists because that second
  comparison is easy to leave out, and leaving it out means a revoked CA keeps
  working forever.

**An untested half, recorded rather than glossed.** `ssh-keygen` refuses to sign
a certificate with no principals ("Empty principal name"), so the other half of
"an empty principal list is valid for every principal" -- the accepting side --
has no fixture. Only the parsing side of `parse_principals` is covered. A
fixture minted by hand-rolling the signing would need a second implementation of
certificate issuance, which is exactly the thing this loop avoided.

**Four harness lessons, all of them failures that pointed somewhere else:**

1. **A MITM serves exactly one connection** (`listen(1)`, a single `accept`). The
   first version of the browser half reused the peer's the native client had just
   consumed, so the browser run reported `NoServerIdent` -- a transport symptom
   for a harness bug. Every transport now gets its own man in the middle.

2. **Check that the man in the middle is alive.** `freePort()` closes a listener
   and hands the number back, and the OS may give it to something else, or
   paramiko may exit on it. Against a dead peer the transcript says nothing and
   the client says `NoServerIdent`. Loop #52 already wrote this check; loop53
   wrote a new `startMitm` and left it out, and then spent three hypotheses
   ruling out the certificate code.

3. **Browser gates must never run concurrently.** Each spawns Chromium, a static
   server and a WS bridge. One gate's `moon clean` deleted another gate's
   freshly built `_build` mid-run, and the result was a failure that read like a
   protocol bug.

4. **A gate that does not exit is a gate whose results cannot be attributed.**
   `serve()` leaves an HTTP server listening and `chromium.launch()` leaves a
   browser open; `openPage(..., { freshStorage: true })` opens a context per case
   that outlives its page. The gate printed its verdict and then sat there
   forever, so the shell never returned and an **orphaned gate from the previous
   run stayed on the machine**, holding ports and racing the next one. That is
   how two `verify_loop53.mjs` processes ended up writing the same
   `.loop53/*.json` at once -- and one mutation verdict was read from a
   transcript the other gate had overwritten. Closing the server, the browser
   and each context dropped the runtime from over four minutes to 111 seconds as
   well.

The fourth lesson has a corollary worth stating on its own: **`task_stop` is not
a substitute for a restore.** Killing the mutation runner mid-flight skipped its
`finally`, leaving the tree mutated, and the next gate run faithfully reported
the mutation as a failure. Nothing about that output was wrong -- it was a
correct verdict about the wrong tree.

**Verified:** `verify_loop53` `ALL PASS (26 checks)` -- 11 cases, each driven by
both `cmd/ssh_live --auth` over TCP and `cmd/wt_ssh` in a browser Worker.
`host/loop53_mutations.py` 3 CAUGHT / 0 MISSED / 0 NOBUILD / 0 CRASH.
`moon test src/hostkey` 25/25, `moon test src/knownhosts` 49/49. No regression:
`verify_loop41` 29 (the KEXINIT byte baseline, unmoved -- the conditional
advertisement does its job), `verify_loop45` 51, `verify_loop46` 53,
`verify_loop47` 19, `verify_loop52` 9.

### Loop #52: a pin that survives the page going away

Loops #49/#50 made the *decision* right and the *rendering* right, and then
printed the line. Printing is not remembering: the gate caught stdout and fed
the line back by hand, while a browser user has nobody to do that. So `--kh-tofu`
on Tuesday means unpinned again on Wednesday -- the exact state TOFU exists to
remove and `accept-new` is not allowed to leave. The pin lived exactly as long as
the test that produced it.

New `src/khstore` (js-only) plus `host/wt/moonbit_khs.js`, following the shape
`src/wt` already established: "what a line looks like" stays in `src/knownhosts`
and is shared by both transports; "where it goes" is the platform's. The stored
value is the **line**, not a structured object, so a browser user who exports it
gets text they can paste into `~/.ssh/known_hosts` -- a richer structure would
need a conversion step, and conversion is where format bugs live (Loop #49's
marker-loss bug was exactly that).

**Four real obstacles, all found by running it rather than reasoning about it.**

1. **A Web Worker has no `localStorage`.** The first version wrote to it. Not a
   policy or a permission -- simply absent: `globalThis.localStorage` is
   `undefined` inside a Worker, so the property access throws and no `try` around
   the call rescues it. IndexedDB is the only origin-scoped storage a Worker has,
   and the only one that makes sense here. What made this findable rather than a
   silent no-op is that the failure was **reported**: every connection printed
   `tofu: NOT stored`, and the driver says it in words rather than letting a user
   believe they are pinned.
2. **No string literals inside an `extern "js"` body.** MoonBit has no
   single-quoted string (`'` is a lexing error, U+0027), so `""` inside a
   double-quoted body must be written `\"` -- and the compiler emits that
   right-hand side as a literal, backslash and all. The generated JavaScript
   contains `?? \"\"`, a SyntaxError, and the module dies at `importScripts` with
   an **empty transcript**, so the failure looks like a harness problem rather
   than a code problem. `src/wt/ffi.mbt` escaped this by accident: none of its
   bodies needs a string. Same family, opposite end -- it recorded inline
   `#| ... |#` leaking its own terminator.
3. **No `Option` across the FFI boundary.** `getItem`'s `null` looks like it
   should arrive as `None` and does not: the generated code tests
   `=== undefined` and treats `null` as `Some(null)`, so the `Some` arm
   dereferences null and the error surfaces far from the cause. The extern now
   answers "was there anything" and the value travels in a second call.
4. **Awaiting is `@js_async.Promise::wait(...)`, not an `await` keyword.**
   `await f(x)` parses `await` as an unbound identifier. Only a parse error, so
   the only kind of confusion that costs nothing.

**A fifth one, and it is the harness contract rather than the language.** Every
mode in `cmd/wt_ssh` ends with its own `wt_finish(...)`, because the Worker
harness takes "finished" from MoonBit through `__wt_finish` rather than guessing
when `importScripts` returned. `kh_forget` shipped once without it: the mode
printed `forget: 127.0.0.1` correctly and then hung, so the gate saw a bare
timeout with a *complete and correct* transcript. That failure reads as a slow
machine, not as a missing signal. **A new mode that returns early must signal.**
The gate now reports that case by name rather than as a timeout.

**`moon check src/khstore` said "no work to do" right after a failed run**,
because the failed attempt had already populated the cache. Force a rebuild
(`moon build`) when a check seems to have skipped your change.

**The gate's isolation is the design, not a detail.** The obvious version passes
for the wrong reason: if step 2 runs in the same page, it cannot distinguish "the
store worked" from "nothing changed and the browser is still holding the first
connection's state". So every step runs in a fresh Page inside a **shared
BrowserContext** -- a new page, new globals, new Worker, no leftovers, and the
same origin-scoped storage. That required changing `host/wt_browser.mjs`'s
`openPage`, which had used `browser.newPage()` and therefore opened a fresh
*context* every call: right for Loop #48/49/51, which wanted total isolation, and
wrong here, where the whole claim is that the pin outlives the page. Getting that
backwards reports a working store as a broken one.

Five cases, and three of them exist to stop the store from being merely a cache:

| case | flags | expected |
|---|---|---|
| 0 | nothing stored, nothing pinned | refuse, `HostkeyUnknown` |
| 1 | `kh_tofu` | authenticate, and the browser really holds the pin |
| 2 | **none at all**, new page | authenticate, from the stored pin |
| 3 | the stored host presents a different key | refuse, `HostkeyMismatch` |
| 4 | `kh_forget`, then connect | forget does not connect; then refuse as `Unknown` |

Case 4 is two steps on purpose, and that is what is under test. `kh_forget`
forgets and **stops** -- it does not go on to accept whatever the peer presents.
One step that does both is how a "remove this pin" button becomes a silent
accept, which is the fail-open Loop #51 closed. And a forgotten host must come
back as `Unknown`, not `Mismatch`: a store that cannot tell "not pinned" from
"the key changed" cries wolf about a legitimate rotation, and its users learn to
click through.

**Step 4a asserts the absence of a file, not the contents of one.** "Forgetting
must not also connect" is checked as `existsSync(transcript) === false`, because
the man in the middle writes its transcript when a connection happens and writes
nothing otherwise. The first version read the transcript and asserted
`auth_attempts == 0` -- and `.loop52/` is not cleaned between runs, so it read a
file left by a *previous* run and reported an authentication attempt that never
happened. A failure with no cause behind it is the worst kind to chase, and it
took an isolated run of `kh_forget` (which showed no connection, and no file at
all) to see that the client was right and the gate was not. The scratch directory
is now wiped at startup for the same reason, so the property holds on the first
run and not just the hundredth. **Step 4a passes `kh_tofu` as well, and that combination took four attempts to
find.** Removing `kh_forget`'s `return` -- the obvious mutation -- turns out to
be *safe*: the pin has just been forgotten, so the connection that follows reads
an empty store and is refused anyway. The mutation also has to remove the
`wt_finish` **call**, because the harness takes "finished" from that call: with
the signal still there the mode announced completion before performing the
authentication it was supposed to perform, and the gate correctly read a clean
forget. A mutation that produces the right answer for a reason that has nothing
to do with the mutation is indistinguishable, from the outside, from a gate with
a hole. So 4a asks for both `kh_forget` and `kh_tofu` and asserts that neither
credential leaves nor any authentication is attempted.

**Sharing the context cost a real regression, and that is the interesting part.**
Making storage survive meant `openPage` had to stop using `browser.newPage()`,
which opens a fresh *context* every call. The first regression run then failed
**Loop #48**, whose `unpinned` case had been relying on "a new context means a
clean slate" -- and it failed by *authenticating*, because a pin left behind by an
earlier case in the same run was still there. That is the worst way for this gate
to fail: the case named "nothing is pinned" passed by being pinned.

So `openPage` takes `{ freshStorage: true }`, and every gate that is not about
storage persistence now asks for it explicitly. Only `verify_loop52` shares. The
default stays shared so that a future gate testing persistence inherits the right
behaviour rather than having to discover it, and the opt-out is one visible word
at the call site. `verify_loop46` needed it for a second reason: it passes
`kh_tofu`, and a leftover pin from an earlier case can change whether a fault
vector is even reached -- which is the part that gate measures.

**The gate asks the browser, not the client.** The first version of step 1
asserted the `tofu: stored` line -- and mutation A *is* `let stored = true`. The
self-report agreed with itself and passed, so a client that stored nothing would
have been reported as having stored. The gate now reads the same IndexedDB from
its own side, twice: that a pin exists, and that it carries the key the peer was
shown. A pin filed under the right host with the wrong key would authenticate on
the next connection only by luck, and "only by luck" is exactly what TOFU is.

Writing that check immediately failed for the wrong reason: the first version
looked up the bare host name, while `src/khstore` files pins under
`moonbit.ssh.known_hosts/<host>`. Step 2 was *passing* throughout, which is what
said the pin was really there and the lookup was wrong -- two checks that
disagree is a signal worth reading before believing either. The key is now
duplicated into the gate **on purpose**: if `storage_key` ever changes, the
lookup returns null and step 1 fails loudly instead of quietly agreeing with a
store that moved.

**Four failed mutations, and the fourth one is the lesson.** Getting C to mean
"kh_forget forgets and then carries on" took four attempts, each failing in a way
that looked like a different problem:

1. the anchor spelled out a Chinese comment, which drifts when someone edits it;
2. the anchor shrank to `wt_finish(true, "done")\n    return` -- which appears
   **five times** in `main.mbt`, because every mode ends the same way. So
   `str.replace` rewrote all five and the mutation silently became "every mode
   carries on". At the one path the gate measures, behaviour was unchanged, so it
   reported **MISSED** -- pointing at the gate;
3. a one-line anchor plus an inserted statement, which changes no control flow at
   all, so the `return` was still there;
4. removing the `return` but keeping `wt_finish(true, "done")` -- the subtle one.
   The harness takes "finished" from that call, so the mode announced completion
   **before** the authentication it was supposed to perform, and the gate
   correctly read a clean forget.

The fourth is worth keeping. **A mutation that produces the right answer for a
reason that has nothing to do with the mutation is indistinguishable, from the
outside, from a gate with a hole** -- nothing in `MISSED` says which it was.

Every one of these produces a confident verdict about a mutation that was not the
one described. All four mutation drivers now assert `src.count(frm) == 1` and
report **NOBUILD** otherwise -- nothing was proven, and MISSED would be a lie.

**Adding a status line is a protocol change, and it broke two gates downstream.**
Loop #52 inserts `tofu: stored` / `tofu: NOT stored` between the existing
`tofu: accepted-unpinned` and the entry itself. `verify_loop49` and
`verify_loop50` both parse that output to recover the written line, and both had
their own filter listing only the one marker they knew about -- so each silently
picked up `stored` as if it were a known_hosts line. Same failure both times: a
byte-for-byte comparison between transports reporting a mismatch, and a
reconnect refused because the "line" was the word `stored`.

Two gates, one cause, found twice, which is what it costs for a parsed protocol to
have a marker list living in two places. It now lives in **one**
(`host/tofu_transcript.mjs`), used by all three gates, and it recognises the entry
**structurally** as well -- a `known_hosts` line has at least two
whitespace-separated fields, and no status line does. So a future status line
breaks the parse only if somebody forgets a file that already has a fallback.

The general rule: a driver and a gate are two independent implementations of "what
this output means", and neither is documentation for the other.

**Browser gates do not run concurrently with anything.** Every one of them
launches Chromium, a static server, and a WebSocket bridge, and they pick ports
with `freePort()`. Two at once produce failures that read like protocol bugs --
`no outcome from the Worker`, `http=404` for the MoonBit module, `did not
authenticate: ""` -- none of which says "two gates shared the machine". Discovered
by running a mutation driver and a regression sweep at the same time during this
loop and having to throw both sets of results away. Run them one at a time.

**Verified:** `ALL PASS (9 checks)` on `verify_loop52`, and `loop52_mutations`
reports `3 CAUGHT, 0 MISSED`. No regression on `verify_loop46` 53 / `47` 19 /
`48` 15 / `49` 11 / `50` 13 / `51` 17.
`verify_loop47` 19 / `48` 15 / `49` 11 / `50` 13 / `51` 17.

### Loop #51: `@cert-authority` is not a host key pin

Loop #50 made refusing the default. This closes a hole that default made
reachable, and it was found by reading what a marker *means* rather than what it
parses as -- Loop #49 had just taught `render` to preserve `@cert-authority`, and
nobody had asked what the matcher did with it.

**It did nothing.** `Marker::Revoked` is consulted in `check.mbt`; `Marker::CertAuthority`
was never read anywhere in the decision path. `entry_matches_spec` ignores the
marker, so a `@cert-authority` line was an ordinary trust entry. Measured with a
throwaway probe before fixing anything:

```
direct pin (the control)       AUTHENTICATED    auth_attempts=1
@cert-authority, same blob     AUTHENTICATED    auth_attempts=1   <-- fail-open
@revoked, same blob            refused  HostkeyMismatch  auth_attempts=0
```

`@cert-authority host K` says *trust this host only when it presents a certificate
signed by K*. This client does not validate host certificates. So the entry is a
question we cannot answer, and **both** obvious ways to answer it are wrong, in
opposite directions:

- treat it as a direct pin -> fail open when the blobs coincide (the hole above);
- treat it as a mismatch -> fail closed, but accuse a man in the middle who does
  not exist. `HOST_CHANGED`'s documented remedy is "add the key" or "type yes",
  which here means reaching for `--kh-tofu`.

That second one is why this is more than a missing check. **A client that cries
wolf about an ordinary CA deployment trains its user to disable the protection**,
and Loop #50's entire argument was that turning protection off should cost a
deliberate keystroke. The bug was finding a way around the keystroke.

`@cert-authority` is common in real `~/.ssh/known_hosts` -- it is how a Puppet /
Chef / Ansible CA gets pinned -- so both halves of this are reachable in
ordinary use.

**The fix is a separate match path, not a special case.** `find_last_match_v2`
became `find_last_direct_match_v2`, which excludes `@cert-authority` outright,
plus `has_cert_authority_match` to tell "nobody pinned this" apart from "pinned
via a CA, which we cannot answer". `HostStatus` / `PinVerdict` / `PinFailure` each
gain `CertAuthority`, and both adapters plus `src/kexflow` translate it into their
own error (`HostkeyCertAuthority` / `HostKeyCertAuthority`). Three states that
must not be confused, each with a different remedy:

| verdict | says | the user's next move |
|---|---|---|
| `Mismatch` | someone is lying | rotate the key, investigate |
| `Unknown` | nobody pinned this host | add a pin |
| `CertAuthority` | this client cannot answer | use a different tool, or pin the host key directly |

Two precedence rules, both asserted because both directions are wrong:

- **A direct entry wins over a CA entry**, so a *real* key change on a host that
  has both still screams. If the CA entry won, a genuine compromise would be
  laundered into "this client doesn't do certificates" -- strictly worse than
  the reverse.
- **`@revoked` still bites first**, because its scan is global and by design
  ignores host matching. A key that is both revoked and CA-referenced reported as
  `CertAuthority` would turn an unambiguous revocation into a feature gap.

**`--kh-tofu` does not open this one.** It is easy to read "accept what you haven't
seen" as permission to accept this, and it would restore exactly the downgrade
being removed -- through a switch that looks entirely reasonable.

**Gate: `ALL PASS (15 checks)` over five cases on both transports**, plus 38
known_hosts unit tests. `ca-other-blob` is the case that looks like a pass and is
not: refusing is correct there, but refusing *for the wrong reason* is the whole
damage, so the leaf name is compared and not just the outcome. A gate that checked
only yes/no would have shipped the accusation.

**The name is not the whole fix, so the gate checks the sentence too.** Loop
#51's argument is that the name decides what the user does next, and an
unfamiliar label in a log changes nothing -- the user still walks the path they
walked last time. Both drivers therefore print a `hint:` line *after* the
machine-readable `error:` line, and every refused case in the gate asserts both
that the hint exists and that it mentions what that case is about: `revoked` must
say "man in the middle", `ca-*` must say "certificate", `unpinned` must say "no
key pinned". Without that, deleting `print_pin_hint` turns every gate green again
while quietly putting the autopilot back, and the three hints could converge into
one paragraph with every leaf name still correct.

```
error: transport:handshake:HostkeyCertAuthority
hint: 127.0.0.1 is pinned via a @cert-authority entry, and this client does not
      validate host certificates. This is not a man in the middle: pin the host
      key directly (ssh-keyscan -t ecdsa 127.0.0.1), or use --kh-tofu and know
      that the pin will break when the host renews its certificate.
```

**Verified:** `ALL PASS (17 checks)` on `verify_loop51` over six cases on both
transports, plus 38 known_hosts unit tests. `ca-other-blob` is the case that looks
like a pass and is not: refusing is correct there, but refusing *for the wrong
reason* is the whole damage, so the leaf name is compared and not just the
outcome. A gate that checked only yes/no would have shipped the accusation.

**Two traps in the tree that are not regressions.** Both cost time during this
loop; neither was introduced by it.

1. **`moon check --target native` at the repo root fails**, and did before this
   loop. `src/knownhosts_store` is a Loop #19-era host-shim scaffold using
   `extern "wasm"`, last touched in `3a23d8c`, **imported by nobody**, with no
   `targets:` gate in its `moon.pkg` to keep it off the native backend (the
   pattern exists elsewhere -- see Loop #37). Check the packages you touched, or
   the known-hosts dependents specifically (`src/knownhosts`, `src/kexflow`,
   `src/sshclient`, `src/wtlive`, `cmd/ssh_live`, `cmd/wt_ssh`, `cmd/sftp_mitm`);
   do not read a red root-level check as a regression. It is also, incidentally,
   where a real store would go if the write-back ever stops being a printed line.

2. **The committed `pkg.generated.mbti` files are stale.** `src/knownhosts`'s was
   last written in `3a23d8c` (Loop #17-#21) and does not contain
   `KnownHostsPolicy`, `decide`, `PinFailure` or `append_line` -- everything from
   Loop #48 on. Moon does not regenerate them in place here, and there are no
   fresh copies under `_build`. Most of them date to the initial commit. So **do
   not read a `pkg.generated.mbti` in this repo as the package's API surface**;
   read the `.mbt` files. This bit during this loop: the stale `knownhosts` mbti
   already contained a `CertAuthority`, which is `Marker::CertAuthority` from
   Loop #14, and it briefly looked like evidence that Loop #51's new status was
   already there. The "read the real `pkg.generated.mbti`" rule in the
   third-party-package checklist is about `.mooncakes`, where moon *does*
   generate a current one; it does not apply here.

**Mutation check: `host/loop51_mutations.py`** -- A drops the exclusion (the
fail-open returns), B downgrades the answer to `Unknown` (the accusation
returns), C makes `src/wtlive` discard the verdict. All three caught.

A is the informative one, because it reproduces **both halves of the original
bug at once**: `ca-same-blob` and `tofu-ca` go back to `AUTHENTICATED`, and
`ca-other-blob` goes back to `HostkeyMismatch`. That is the pre-fix behaviour,
side by side, in one run.

B turned up something the gate's cases had not made explicit: **the TOFU hole
does not need the marker filter removed.** Downgrading the CA answer to `Unknown`
is enough, because `Unknown` under `--kh-tofu` is "accept". So
"accept-new must not re-open this" is a property of the *verdict being distinct*,
not of the exclusion in `find_last_direct_match_v2` -- two independent mechanisms,
and asserting only one of them would have left the other untested.

### Loop #50: the default is the refusal

Loop #48 made pinning real. Loop #49 made it write back. Neither changed the
**default**, which stayed where #48 left it: pin nothing, connect anyway. That is
the shape OpenSSH has spent twenty years defaulting away from, and it is where
every forgotten configuration file lands silently. This loop puts the default on
the safe side: **nothing configured means refuse**, and accepting a new key
becomes something you have to type (`--kh-tofu` / `kh_tofu`, the equivalent of
`StrictHostKeyChecking=accept-new`).

The shape is half the argument. In the safe default the unsafe thing costs one
flag; in the old one, the safe thing cost a file **and** a flag. One fewer
configuration item is one fewer thing to get wrong. For the same reason
`--kh-strict` was **deleted** rather than flipped: once refusing is the default,
a switch named "strict" points the opposite way from every other switch, and of
two oppositely-named switches one will never be read.

**What actually went wrong, three times over.** The first three attempts at this
were correct code. `moon check` passed. And a client with nothing configured kept
authenticating. The cause was one line in `KnownHostsPolicy::verify`:

```moonbit
if self.entries.length() == 0 { return Skip }
```

`Skip` was a verdict meaning "nothing was configured, so nothing was compared",
and `decide` read it as *no objection*. So under `strict`, "you configured
nothing" was reported as "everything checked out". `check_host_key` already
returns `Unknown` for an empty entry list -- that early return was swallowing it.
Fixing it was to **delete the state**: `Skip` is gone from `PinVerdict`, because
"forgot to configure" and "configured, nothing matched" are the same behaviour
with opposite answers under strict, and a field that conflates them is a field a
default can fall into. The only way to not pin is now `skip()` (`strict = false`),
which reaches the same verdict through the **same code** rather than a bypass.

**A fail-open default is structurally invisible to end-to-end tests.** The peer
does not care what our default is; it will happily accept userauth from a client
that should never have sent it. Nothing in a gate that only checks "did the right
thing happen" can see the difference. So `host/verify_loop50.mjs` is built around
*differences*, not absolute outcomes:

| case | flags | expected |
|---|---|---|
| a | none at all | refuse `HostkeyUnknown`, 0 auth attempts |
| b | a + exactly one switch | authenticate, report a line to write back |
| c | b's written-back line, **no** switch | authenticate |
| d | `--kh-strict` (deleted in #50) | still refuse |

`c` is the payoff: once the key is written back, the unsafe switch is not needed
again. If it were, `accept-new` would be a permanent downgrade rather than a
one-time decision and "remember it" would be a lie. `d` is there because a deleted
flag is not automatically an inert one, and "we removed it" is a claim rather than
a measurement.

**The refusal is asserted three ways, and only the third is new.** The error name
could be anything, and `auth_attempts == 0` could hold for an unrelated reason
(peer hung, wrong port, dead bridge). What makes it *this* layer's doing is that
the man in the middle still recorded a host key blob: the exchange completed
signature verification and we refused a peer whose key we had just proven it
holds. A peer that never presented a key also shows zero auth attempts -- and
would be refusing for a reason that has nothing to do with pinning.

**Both the rule and the call sites collapsed to one copy.** `allows` (the Bool
version) had no callers at all while both adapters hand-rolled the same decision;
that is three copies of one rule, and a default changed in one of them. Loop #50
deletes `allows` and leaves `decide` as the only entry point -- adapters now only
translate the failure into their own error type. The stale anchor in
`host/loop48_mutations.py` had to move with it, which is itself the lesson: an
anchor that no longer matches reports `SKIP`, and a `SKIP` is indistinguishable
from a gate with nothing left to catch.

**Harness lessons:**

* **`moon build` reported "no work to do" while the source had changed.** It cost
  real time, because the resulting binary behaves exactly like a correct build of
  an older default. `moon clean` fixed it. The mutation driver now cleans before
  every run: a mutation that fails to show up because nothing was rebuilt reads as
  `MISSED`, which points at the gate rather than at the tree.
* `kh_host` now defaults to `127.0.0.1` in both drivers, via one helper each
  (`kh_host_name` / `cfg_kh_host`). Two call sites asking "which host do we look
  up" independently is how the write-back ends up writing a name the next
  connection will not query -- and `HostkeyUnknown("")` is a refusal that says
  nothing actionable.
* A unit test, not just a gate, is the right regression net for a default. The
  assertion `from_text("", host, 0, true).decide(blob) == Some(Unknown(...))` runs
  in milliseconds and covers precisely the branch that never executes.

**Mutation check: `3 CAUGHT, 0 MISSED`.** `host/loop50_mutations.py` mutates the
default three ways, all the same bug in different clothes -- the default quietly
stops refusing:

| | mutated | caught by |
|---|---|---|
| A | `cmd/ssh_live`: `strict` no longer derived from `--kh-tofu` | native only |
| B | `decide` ignores `self.strict` on `Unknown` | both transports **and** the unit test |
| C | `cmd/wt_ssh`: default policy built non-strict | browser only |

B is the one that matters. A and C are a wrong constant at a call site and read
as such in a diff; B is the rule itself losing the property while every caller
still passes the right arguments -- exactly the shape of Loop #50's original bug.
That the unit test catches it too is the point of having added one: the rule is
shared, so a rule-level regression has to show up in both transports, and a gate
that only ran end to end would have paid two browser launches to learn the same
thing.

**Two real defects in the mutation driver itself, both found by running it.**
Restoring the tree only in `finally` meant each mutation started from the
*previous* one's leftovers, so C -- which touches `cmd/wt_ssh` alone -- reported
the **native** client failing too. Every mutation was still CAUGHT, so the
tally looked perfect while the attribution was fiction; and a mutation reported
against a client it never touched invents a dependency edge that sends the next
person looking for it in `moon.pkg`. The same bug was in
`host/loop48_mutations.py`. Second, the per-transport breakdown matched
`"native "` against labels that begin `"FAIL native "`, so it had never printed
once -- dead reporting that looked like "nothing was caught by either client".

**Gates adjusted rather than re-tuned:** `verify_loop47` now passes `--kh-tofu`,
which makes it *stronger* -- willing to accept any self-consistent key, the only
thing left stopping a forgery is signature verification. `verify_loop48`'s
`no-policy` case became `unpinned` and now expects a refusal: the case used to be
written down as a **passing** case precisely so the gap stayed visible, and
flipping it is how the gap's closure gets re-checked every run instead of claimed
once. `verify_loop45` (`cmd/sftp_mitm` passes `skip()` explicitly at a call site)
and `verify_loop46`/`verify_loop49` were unaffected.

**Verified:** `ALL PASS (13 checks)` on `verify_loop50` plus 32 known_hosts unit
tests, `verify_loop48` 15, `verify_loop47` 19, `verify_loop45` 51, `verify_loop46`
53, `verify_loop41` 29, no regression.

### Loop #49: TOFU has to actually remember

Loop #48 added the comparison. This closes the half that makes the policy TOFU
rather than just "trust anything": **trust on first *use***. Accepting an
unpinned host is half a policy. If nothing is written back, "use" never happened
-- the next connection is again a fresh credential-free acceptance, and so is
the one after that. The client never becomes harder to fool, only slower.

**The write-back is rendered in `src/knownhosts` and printed by the driver.**
`render.mbt` holds the rendering (`render`, `append_line`, `to_line`) and nothing
else; no filesystem is touched, because this moon version's core has no
file-reading API and `src/wt` is js-only where a browser has no filesystem at
all. So "what a line looks like" has one implementation that both transports
share, and "where it goes" is the driver's business -- a known_hosts file natively,
localStorage in a browser. The gate captures the printed line and feeds it back
in.

**The sequence is the point, and step 3 is what makes step 2 mean something:**

1. no known_hosts at all, an honest peer -> authenticate, and the client reports
   the key it just accepted
2. that text fed back in, **the same** peer -> authenticate, and it is now a match
3. that text fed back in, a peer with a **different real key** -> refuse

Step 3 is what catches a write-back that produced text matching nothing: TOFU
would be indistinguishable from never having pinned at all, and step 2 alone
passes in that case. The mismatching peer is a *self-consistent* one with the
wrong key -- a forged one would fail earlier for an unrelated reason.

**Two real bugs the round-trip property caught, both invisible end to end:**

* **`render` dropped the `@revoked` / `@cert-authority` marker.** A revocation
  record written back becomes an ordinary **trust** record -- the opposite
  direction -- and it still parses, so nothing anywhere reports an error. This is
  the worst class of write-back damage and the end-to-end sequence cannot see it,
  because nothing in the sequence writes a marker. Hence a dedicated assertion.
* **`render` did not emit a trailing newline**, so "read back out byte for byte"
  did not close: every line differed by one `\n`.

Both came from writing the property down first and testing it against real data.
**The test constants are real SSH wire blobs, not placeholders** -- a made-up
base64 string parses to zero entries, and a `0 != 1` failure reads like "the
rendering is broken" when only the fixture was never a key. Same shape as Loop
#43's `hex_to_bytes` lesson: a bad fixture produces a failure that points at the
rule.

**Two harness lessons, and one of them is a good assumption I got wrong:**

* `println` can wrap the base64 across lines, so a single-line regex truncates
  the key and the gate then reports "the written line does not carry the key the
  peer presented" -- pointing at the driver, which was right. The line is also
  printed *after* `tofu: accepted-unpinned`, so a first-match read returns the
  status marker as content, and a last-match read swallows the rest of the
  transcript.
* **A repeated TOFU on reconnect is correct, not a failure.** Writing back again
  on every accepted connection is what keeps the file current when a host
  legitimately rotates its key. The first draft of this gate treated it as "the
  first write-back was not remembered" and failed on correct behaviour; the
  distinction that actually matters is in step 3.
* The man in the middle writes its transcript when its session thread returns, so
  a read placed before the client has connected gets an empty file. Both step 1
  and step 3 had this; step 1 happened to pass, which is not a reason to leave it.

**Verified:** `ALL PASS (11 checks)` plus 24 known_hosts unit tests. Both
transports write a byte-identical line, so a browser user and a native user end
up with the same known_hosts for the same server. `verify_loop48` 15,
`verify_loop47` 19, `verify_loop41` 29, no regression.

### Loop #48: host key pinning, in the live client

Loop #47 proved the client refuses a peer's key exchange when the exchange does
not hold up. Both of its forgeries are **inconsistent**: the blob does not
prove the signature. What they cannot reach is the attack that matters in
practice -- a man in the middle with its own key and its own perfectly valid
signature. That exchange is entirely self-consistent, so every signature check
passes. Only comparing the presented key against the expected one stops it.

**And the live client was not doing that at all.** `src/kexflow` carries the
rule (`check_host_key_strict`), and both live adapters implement their own
handshake without going through kexflow -- so on the client that actually
connects, host key pinning had never executed. The rule existed, was
unit-tested, and was unreachable. Reading "the rule is written" as "the rule
runs" is the specific mistake this loop closes.

**The rule stayed in one place.** `KnownHostsPolicy` / `PinVerdict` live in
`src/knownhosts`, next to `agrees_with_alg`'s reasoning and for the same reason:
a rule copied into two transport adapters is a rule that eventually exists in
one of them only. The adapters each translate the verdict into their own error
variant and nothing else -- `HostkeyMismatch(String)` and `HostkeyUnknown(String)`
in both, which Loop #44's anchors then hold together.

**`Skip` and `Accept` are different verdicts on purpose.** "Checked and
consistent" and "never checked" collapse to the same value in a Bool, and a log
that says everything was verified would be lying. Keeping them apart is what
lets a caller -- and a gate -- tell them apart.

**Five cases per client, and the set is the point.** One man in the middle,
presenting one self-consistent key, told different things about what to expect:

| case | what the client is told | expected |
|---|---|---|
| match | pin the key actually sent | authenticate |
| mismatch | pin a different key | refuse, send nothing |
| unknown-strict | pin another host, strict | refuse, send nothing |
| unknown-tofu | pin another host, non-strict | authenticate |
| no-policy | nothing at all | authenticate |

The last two look like failures and are not. They are here to pin down the
policy actually in force -- **pinning is opt-in, and an unpinned host is
accepted**. OpenSSH's default is the opposite. Writing that down as *passing*
cases is what keeps the gap visible instead of quietly closed by somebody
assuming it had been handled.

**The matching case's known_hosts line is built from the transcript, not from a
file in the repo.** The man in the middle reports the blob it presented
(`hostkey_blob_b64`), so the line that should match is derived from what the
peer actually sent. A pinned file would go stale the moment the key was
regenerated, and the stale file reads as a mismatch -- which looks like a
protocol bug and is a fixture problem.

**known_hosts arrives as text, not as a path, and that was forced.** This moon
version's core has no file-reading API (`@env` is argv / env / time), nothing in
the repo reads files, and `src/wt` is js-only where a browser has no filesystem
at all. A "read the known_hosts file" option that only works natively would
split the two adapters into different behaviours -- the exact drift this repo
keeps paying for. Text works in both, and it is what a browser application
actually has. Both drivers call one `KnownHostsPolicy::from_text`.

**A policy that parses to nothing is refused, not skipped.** `--known-hosts-text`
with zero parsed entries would otherwise become a silent `Skip`, which is the
worst possible outcome: a check that looks like it ran and did not.

**Two mutations, both caught.** Reporting a mismatch as a match, and discarding
the verdict in `src/sshclient`, both turn the gate red. Only the browser half of
the second is left standing on purpose -- the point of a shared rule is that one
adapter can be mutated without the other covering for it.

**The mutation driver undoes itself, and that is not optional.** It snapshots
every file it touches and restores from the snapshot. The first version was
debugged by hand with `git checkout -- src/sshclient/live.mbt`, which -- because
the loop's own uncommitted work sat in that same file -- silently undid the work
too. The loss was invisible: the file still compiled. The same mistake then
recurred on a second file, and for a while the driver reported the browser half
failing under a mutation that only touches the native adapter. That result was
impossible, and the cause was not a hidden dependency between the adapters but a
tree that was not what it was believed to be. **A mutation is never undone with
git unless it was committed first**, and when a result is impossible, suspect the
tree before suspecting the code.

**Verified:** `ALL PASS (15 checks)`. `verify_loop47` 19, `verify_loop46` 53,
`verify_loop45` 51, `verify_loop41` 29, no regression.

### Loop #47: a peer that lies about its host key

Every handshake test in this repo had talked to a peer that told the truth.
Loop #38 pinned the host key algorithms against a real sshd; Loops #34-#40 and
#43-#46 all completed handshakes against a man in the middle whose host key was
correct. So `HostkeyInvalid` and `SignatureInvalid` were **defined in both
transport adapters and driven by nothing** -- reachable only by a peer whose key
exchange does not hold up. That is the most security-relevant gap left in the
client, and it took a wrapper object to close.

**One wrapper, no cryptography of our own.** paramiko builds both halves of
`KEXDH_REPLY` from a single object -- `kex_ecdh_nist.py` reads
`get_server_key().asbytes()` for the blob and `get_server_key().sign_ssh_data()`
for the signature -- so `LyingHostKey` splits them: `asbytes()` returns key A,
`sign_ssh_data()` signs with key B. Both keys are real paramiko keys and both
signatures are made by paramiko; the only thing invented is *which* of them
answers which half.

**Two forgeries, because they are different rules on different branches:**

| MITM flag | the lie | the branch it must reach |
|---|---|---|
| `--lie-hostkey` | blob A, signed by B | `SignatureInvalid` |
| `--lie-hostkey-type NAME` | a real blob announced as another type | `HostkeyInvalid` |

Driving only one leaves the other untested, and they are not interchangeable:
the client checks the type *before* the signature, so `--lie-hostkey-type` never
reaches the signature check at all.

**The assertion is not "the client reports an error" -- it is that no
credentials left.** An implementation that logs an error and authenticates
anyway has leaked the thing the error was about. So the man in the middle counts
the authentication attempts it is asked to approve, and the gate asserts that
count is zero, along with zero channel requests. It approves everything by
design (Loop #45's decision), so it cannot notice a client that should not have
arrived -- it has to be told. The counts are written into the transcript before
anything can fail, so "zero" is a measured `0` and never a missing key.

**`--auth` is the mode to drive on purpose**: its success condition *is* reaching
authentication, so a verification hole shows up as the run succeeding where it
must fail.

**A control run is not optional.** Three clients that refused everything would
satisfy every check above, so each client also runs against an honest man in
the middle and must authenticate. The refusals and the control are one
measurement from two ends.

**Three clients answer the same question, and the third is not ours:** paramiko
(`host/hostkey_witness.py`, a real client that was written by somebody else, so
the expectation is not "whatever MoonBit does"), `cmd/ssh_live --auth` over TCP,
and `cmd/wt_ssh` (`auth: 1`) in a browser Worker over WebSocket. The error name
is compared by its **leaf** -- `cmd/ssh_live` renders
`transport:handshake:SignatureInvalid` and `cmd/wt_ssh` renders
`handshake:SignatureInvalid`; the prefixes are two renderings of where it
surfaced, and the leaf is the part the rule produced. Both transports must agree
on the leaf.

**Two mutations, and the second one found a defect in the gate itself.**
Never rejecting a bad ECDSA signature, and always agreeing with the negotiated
algorithm name, both fail the gate -- and the second fails as a *branch
fall-through* (`HostkeyInvalid` becomes `SignatureInvalid`) while the security
property still holds, which is the argument for asserting both.

The first mutation also exposed the reason this loop needed its own gate rather
than an extension of `verify_loop45.mjs`: `verify_loop47.mjs` originally built
only `cmd/ssh_live --target native`, so the browser half ran a `wt_ssh.js` left
over from whenever it was last built and **kept passing** against mutated
source. A gate that can report PASS for a tree it did not compile converts a
caught regression into a silent one -- and the browser half is the half this loop
exists to cover. Both halves are now rebuilt on every run.

**The browser plumbing is shared, not copied.** `host/wt_browser.mjs` holds the
HTTP server, the page, the Worker driver and the Worker's `Event` rendering that
`verify_loop46.mjs` and `verify_loop47.mjs` both need. Two copies of a *rule*
is the duplication this repo keeps paying for (see Loops #41/#45); there is no
reason to start paying for it in the plumbing too.

**Verified:** `ALL PASS (19 checks)`. `verify_loop46` 53, `verify_loop41` 29,
`verify_loop45` 51, no regression.

### Loop #46: the same vectors, in a browser Worker

Loop #45 left exactly one adapter undriven. `src/sshclient` had a man in the
middle in front of it; `src/wtlive` did not, and the stated reason was that
`src/wt` speaks **WebTransport**, which needs a publicly trusted certificate --
Chromium rejects a locally-added one on the QUIC path with
`QUIC_TLS_CERTIFICATE_UNKNOWN` no matter which override flag is set.

**The reason was half right, and the useful half was in `src/wt`.** It picks its
transport from the URL: `ws://` opens a `WebSocketStream`, anything else opens
WebTransport (`host/wt/moonbit_wt.js`). A `ws://` URL carries exactly the same
bytes, so everything above the transport is exercised identically -- no change
to `src/`, no new cryptography, and the WebTransport limitation stops being a
limit on what can be *tested* rather than on what can be *shipped*.

```
browser Worker (MoonBit js, src/wtlive) --WebSocket--> wt_mitm_bridge --TCP--> sftp_mitm.py
```

`host/wt_mitm_bridge.mjs` is `host/wt/ws_relay.py` with a different upstream,
which is deliberate: the relay is already proven against a real sshd, so the
browser half is not a new thing being trusted for the first time. It forwards
bytes and **parses nothing** -- no SSH, no reassembly, no counting. Any of those
would be a second implementation of something that already has one, and a place
for a transcript to be quietly wrong in a way the gate could not see.

**The rendering is `cmd/wt_ssh`'s own, and the gate undoes it instead of
forcing it to match.** `wt_print_sftp_op` prints `op0: REALPATH` plus
`op0_hex: ...` rather than `cmd/ssh_live`'s single rendered line, because its
alignment with `ssh_live` line for line *is* Loop #39 G5's assertion. Changing it
to make this gate simpler would have deleted the thing the earlier gate
measures, so the third gate parses the multi-line form back into the shape the
other two compare. That is a different trade from `verify_loop41` and
`verify_loop45`, which each ported the renderer: those compare rendered strings
to rendered strings, this one compares parsed fields, so the duplication is
smaller and there is nothing to cross-check against a generated table.

**Hex case is a rendering choice, not a protocol fact, and the two drivers make
opposite ones.** `cmd/wt_ssh` prints through `@ecdsa.bytes_to_hex` (uppercase);
`cmd/sftp_mitm` has its own `to_hex` (lowercase). `wt_ssh` is the one that is
right -- `wt_dump_prefix` is deliberately aligned with `cmd/ssh_live` -- so the
gate folds case on the **hex fields only**. Folding the whole rendered string
would also hide a case change in `realpath=` itself.

**Requests are compared by count, not by bytes.** In the TCP run the framing is
the client's, so the concatenated stream is comparable; a browser's WebSocket
chunks it however it likes. Counting still catches the failure that matters --
a client that never sends its requests, or sends the wrong number.

**Four harness lessons, every one of them a failure that pointed somewhere
else:**

1. **`worker error: [object Event]` was a 404, twice over.** `serve()` called
   `readFile`, which was never imported, so *every* static request raised a
   `ReferenceError` and answered 404 -- the page, the Worker script, everything.
   A Worker's `onerror` for a script that never loaded receives a DOM `Event`
   with no `.message`, no `.filename`, and `String(ev)` is the literal
   `"[object Event]"`, so the cause was nowhere in the output. Two changes make
   that class of failure impossible to hide again: the Event's fields are copied
   into a plain object and rendered by name, and the page records every
   `response >= 400` and every `requestfailed`, so a missing asset is a visible
   `404 <url>` instead of an opaque Event.

2. **`page.evaluate` carries no Node scope.** The formatting helper was defined
   beside the gate and referenced inside the evaluated function, so the page
   raised `ReferenceError: describeEvent is not defined` -- while the gate went
   on to report a *worker* failure, one layer away from the actual cause. The
   browser side now copies fields out and Node formats them; no `eval` of a
   stringified function.

3. **The gate hung up on the MITM before it finished writing.** `sftp_mitm.py`
   records its transcript when the session thread returns, and three scenarios
   were reported as `the man in the middle recorded nothing` -- which reads as
   a protocol failure. It was a race: the child was killed the instant the
   Worker's result arrived. The order is the dependency's order -- close the
   bridge, the MITM sees the socket end, the thread returns, the transcript is
   written -- and only then is a kill still needed.

4. **A wrong field name reads as a protocol divergence.** The parser asked for
   `op0_path_hex`; `wt_print_sftp_op` prints `op<i>_hex` for the bytes and
   `op<i>_path` for the length. The failure was
   `got ["realpath=undefined"] want ["realpath=2f"]`, which is indistinguishable
   from `src/wtlive` returning something else.

**Verified:** `ALL PASS (53 checks)` -- the same 10 scenarios x 5 cut points
`verify_loop45` runs, every one of them a real SSH handshake, but driven from a
browser Worker over WebSocket. The bytes above the transport are now proven
identical across both adapters: a window rule changed in one file, or a pump
forgotten in the other, shows up here as a transcript that differs from
expectations `verify_loop45` already proved.

**What it does not retire.** The WebTransport path itself is still untested
locally -- that needs a publicly trusted certificate, not a flag -- so what is
proven is everything above the transport, on the WebSocket carrier.

### Loop #45: the fault vectors over a real socket (the MITM)

Loop #44 stated the limit plainly: `run_sftp_session` is private in both
adapters and starts from a post-authentication session state, so **no
malformed byte could reach a transport adapter**. This removes that limit.

**`host/sftp_mitm.py` is paramiko in _server_ mode.** Key exchange, cipher
setup, NEWKEYS and userauth are a real SSH implementation doing real crypto --
none of it re-derived, none of it trusted. What it does *not* do is speak
SFTP: once the client asks for the `sftp` subsystem, it acknowledges the
request and writes a scenario's bytes straight onto the channel. There is no
`SFTPServer` anywhere in the file, and no code path that could grow one by
accident -- the peer is wrong on purpose.

It accepts **any** public key. That is a decision, not an oversight: the thing
under test is what the client does with SFTP bytes *after* authentication, and
a key check would be testing `src/userauth`, which Loop #34 and the live sshd
gate already cover.

`cmd/sftp_mitm` is the other end: a real TCP connection, a real handshake, the
real `live_sftp`. Native by necessity -- `live_sftp` takes a `@tcp.TcpConn`.

**The expectation does not change**, and that is the whole claim: the SFTP
layer cannot tell whether the bytes came from a real `internal-sftp`, a fake
peer in-process, or a man in the middle over a socket. Same vector table, same
oracle, same cut points.

**Two transcripts are compared, against different things on purpose.** The
client's own report (version / results / done-or-failed, plus the
`Protocol(<reason>)` string a failed session reports) against the expectations;
and *the bytes the MITM saw the client send* against the expected request
frames. The second is the one that would catch a transport that mangled what
it sent -- a window clamp that over-sends, a subsystem request that leaves
before the confirmation -- and the client's own report cannot see that, because
a client has no idea what went out before the channel closed.

**Three harness lessons, all of them wrong-looking failures:**

1. **CRLF silently turns a match into no match.** The gate reported
   `results: got []` for scenarios that were demonstrably producing the right
   answer when run by hand. In a JavaScript regular expression `.` does not
   match `\r` -- it is a line terminator, alongside `\n` -- so
   `^op\d+: (.*)$` without the `m` flag can never match a CRLF line, and the
   failure is **no match**, not a wrong value. An empty list reads as "this
   scenario produced nothing", which points at the SFTP layer. `verify_loop39`
   has normalized CRLF since Loop #38; the rule travels with the repo, not with
   whichever file happened to remember it.

2. **Comparing a raw tuple to a rendered string, a second time.** The oracle
   stores a result as `["realpath", "/C:/Users/hp"]`; the client prints
   `realpath=2f433a2f55736572732f6870`. `verify_loop41` made this exact
   mistake and fixed it; `verify_loop45` made it again, because it is a new
   file with a new author and the shape looks obviously compatible until it
   does not. The fix is the same, and the cross-check against the *generated*
   `cmd/sftp_mitm/vectors.mbt` is what keeps the second port honest.

3. **The MITM must re-frame correctly or every transcript differs for the
   wrong reason.** Re-assembling the client's requests re-attaches the length
   prefix, and the length does **not** count itself
   (`put_u32(mlen, sshbuf_len(m))`, sftp-client.c:160-161). Writing
   `len(body) + 4` produced transcripts that differed from the expectations by
   exactly four -- a difference with nothing to do with the fault being
   injected, and one that would have been reported as a transport bug.

**Verified:** `ALL PASS (51 checks)` -- 10 scenarios x 5 cut points, every one
of them a real TCP connection, a real key exchange and a real userauth against
the man in the middle. Three of the ten end in `Failed`, and their
`Protocol(<reason>)` strings are compared rather than merely logged, so the
path from a malformed reply to a reportable outcome is checked end to end.

**It is a separate gate** (`node host/verify_loop45.mjs`), not a step inside
`verify_loop41.mjs`, because it is by far the slowest thing in the repo: 50
sessions, each a full handshake. Folding it into the fast gate would make
every iteration pay for it.

**What it retires.** `host/verify_transport_parity.py` (Loop #44) exists
because nothing could reach an adapter. Now `src/sshclient` can be driven
directly. `src/wtlive` could not -- it needs WebTransport, not TCP -- so at this
point the parity gate still carried the browser half alone. Loop #46 put the
same vectors in front of `src/wtlive` over a WebSocket carrier, which closes
that; the parity anchors are now checked against real coverage on both sides.

### Loop #44: keeping the two transport adapters in step

**What could not be tested then, and no longer cannot.**
`run_sftp_session` is private in
both `src/sshclient/sftp.mbt` and `src/wtlive/sftp.mbt`, and both take a
*post-authentication* session state as their entry point. So the only way to
hand either adapter's loop a malformed reply is to speak enough of the SSH
handshake to get there -- a MITM server implementing the server side of kex and
userauth. Until Loop #45 built that, **no malformed byte could reach a
transport adapter**, and any claim that the fault vectors covered the
transports would have been false. They cover `SftpSession` and `ChanState`,
which is where Loop #43 drew the line.

**So the anchors below are a stopgap, not a permanent answer.** Once the MITM
drives both adapters, this gate can retire; until it does, it is what stands
between a one-sided edit and a divergence nobody would notice.

That leaves the actual risk: two files, two edit sites, and a rule that exists
in both. Loop #39's G5 proves the browser side works against a real
`internal-sftp`; Loop #43 proves the state machine and the channel layer hold
under ten malformed replies. **Neither can catch "someone changed the window
rule in one file and not the other"** -- the happy path never fills the
window, and the fault vectors never reach either adapter's loop.

**Why anchors and not a diff.** A normalized diff of the two files is ~145
lines of *legitimate* difference: the auth entry points genuinely differ
(native takes a `subsystem` parameter and gets its state from
`live_auth_with_state`; wtlive hardcodes `"sftp"` and gets it from
`wt_auth_into`), one is sync and one is async, and the send/receive calls have
different names. Such a check fires on every correct edit and gets muted on
the next one.

`host/verify_transport_parity.py` instead pins the smaller claim: **each of
fifteen load-bearing statements must still be present in both files.** It only
goes red when a rule is actually removed, each anchor names the decision rather
than a line number, and the anchors are *statements* -- deleting the comment
that explains a rule does not satisfy it. Verified by deleting
`if stuck && rest.length() > 0 {` from the wtlive copy: the gate reported
exactly that one rule and named the file.

The fifteen: wait for OPEN_CONFIRMATION; wait for CHANNEL_SUCCESS on the
subsystem; the subsystem request itself; requests through the peer's window; a
full window pumps before giving up; a bound on rounds; a bound on the clamp
spin; an unparsable CHANNEL_DATA is an error; the parsed payload reaches the
session; the session is pumped every round; only 0x5e carries data; the
session's failure reason is surfaced; EOF on the clean path; both byte
counters.

**The last one is annotated, not just listed.** `st.counters.recv` counts the
*encrypted stream from the server* and carries WINDOW_ADJUST timing, which is
load-sensitive -- Loop #42 defect 4 exists because `verify_loop36` compared it
cross-transport. The anchor requires the counter to be *reported* in both
files while the exclusion stays a cross-transport rule; the reason sits next
to the anchor so the next person to "fix" loop36 finds the argument.

### Loop #43: the same fault vectors through the channel layer

Loop #41-M2 fed malformed bytes straight into `SftpSession::feed`. That proves
the state machine. It says nothing about the layer below it, and the layer
below is where the risk actually lives:

- `ChanState::stdin_take` clamps each outbound packet to
  `min(remote_window, remote_max_packet)` (RFC 4254 §5.2), so a request is
  routinely split across several CHANNEL_DATA.
- the CHANNEL_DATA boundary is **not** an SFTP packet boundary -- that is the
  entire reason `src/sftp/stream.mbt` exists.
- `src/sshclient/sftp.mbt` and `src/wtlive/sftp.mbt` are two near-identical
  files. Deliberately (they hold no protocol), but still two files.

**`cmd/sftp_fault` is a fake peer.** It answers CHANNEL_OPEN_CONFIRMATION and
CHANNEL_SUCCESS, delivers each vector's payload as CHANNEL_DATA **re-sliced at
four cut points** (1, 3, 7, 64 bytes), and reads our requests back out of the
CHANNEL_DATA the client framed them into -- reassembled through `SftpInbuf` and
re-framed with `sftp_frame`, because `drain` hands back bodies while the
vectors record whole frames.

**The invariant under test is the one `stream.mbt` exists to hold:**

> the CHANNEL_DATA cut point must not change the answer

Each chopped run is asserted against the whole-payload answer *and* the
expectation, not just the expectation -- comparing a chopped run to the
chopped expectation would let a shared error pass twice. The oracle
(`host/sftp_fault_oracle.py`) proves the same invariant independently before
it will emit the vectors at all.

**Verified:** `ALL PASS (50/50 runs, 10 scenarios x 5 cut points)` on all four
backends with the same verdict, and byte-identical between js debug and
release. 5 mutations all caught (`host/sftp_fault_mutations.py`).

**Two driver bugs this found, both of which pass the un-sliced case:**

1. **Never feeding the session.** `chan_step` advances the *channel*; handing
   the payload to the state machine is the driver's job (`pump_once` does it
   right after the step). A driver that only steps the channel leaves the
   session waiting for a reply that arrived. Symptom: every scenario hangs at
   VERSION with exactly one request emitted -- INIT.
2. **Comparing bodies to frames.** `SftpInbuf::drain` consumes the length
   prefix and never returns it, so the peer reported `0100000003` where the
   expectation said `000000050100000003`. The fix is to re-frame with
   `sftp_frame`, which is the one function that owns framing.

Both are now mutation cases, so they cannot come back quietly.

**One mutation was deliberately dropped rather than left failing.** "Consume
the bytes of a refused packet anyway" changes `take()` on a path that returns
`None` immediately afterwards (`self.failed` latches), so nothing this gate
observes can move -- dropping four bytes no one reads is not a difference. It
is not a hole in the gate: `cmd/sftp_test` already asserts it, as
`length_over_max_refused` with `expect_pending: 13`. Listing it here would
have produced a MISSED that said nothing about `cmd/sftp_fault`.

**The mutation script distinguishes four verdicts,** because conflating them
is how a mutation list quietly stops meaning anything: `NOBUILD` (the mutated
source did not compile -- nothing was proven either way, and calling it
MISSED would point at the gate), `CRASH` (it compiled and blew up -- caught,
because a gate that cannot survive the mutation still noticed it), `CAUGHT`
(a named check went FAIL), and `MISSED` (it ran and everything still passed).
The first draft had only two, and the "forget `want` after a short feed"
mutation arrived as `PanicError` -- which under a two-valued scheme is
indistinguishable from "no output at all", and would have been reported as a
gate hole.

### Loop #42: three harness defects behind one impossible verdict

`verify_loop40`'s regression reported `FAIL loop39 still passes` with the
detail line `ALL PASS (44 checks)` -- a gate that passed everything and
failed anyway. Three defects were stacked under that one line, and none of
them was in the code any loop tests.

**1. A shadowed variable that only exploded on success.**
`verify_loop39.mjs`'s G2 declared `const skipped = <SKIP-line count>` inside
`main()`, shadowing the global `skipped` **array** (line 61) with a Number
for the whole function. The ending's `for (const s of skipped)` then threw
`TypeError: skipped is not iterable` -- but only on the ALL-PASS path,
because the failure path returns 1 without ever touching it. So loop39
printed ALL PASS and exited 1; every run with a real failure had shown a
clean FAILURES summary, which is what made the verdict look impossible.
Renaming the counter `skippedCount` is the whole fix.

**2. A mutation batch that died mid-run with no traceback.** The nested runs
also showed loop37 at `46/47` with `5 caught, 0 missed` -- five CAUGHT lines
and then silence, no MISSED, no SKIP, nothing. `channel_mutations.py`'s
`run_kat()` used `text=True` with no explicit encoding, so moon's output was
decoded with the locale codec (cp936 here); one box-drawing character the
compiler prints on a cold-build diagnostic path raised
`UnicodeDecodeError` inside the batch loop, the `finally` restored the
sources, and the child died with its stdout buffer unflushed -- leaving
exactly the five lines that had made it out. Single runs on a warm `_build`
printed pure ASCII and could not reproduce it, which is why it looked like a
timing flake. The fix is three independent belts: `encoding="utf-8",
errors="replace"` (the decode can never raise), `flush=True` on every batch
line (what is printed is delivered), and an explicit 64 MiB `maxBuffer` on
the spawnSync side (the 1 MiB default is one cold build away from killing
the child for a different reason).

**3. Nested failures that discarded their own evidence.** loop38 captured
each child gate's full output and kept only a 200-char summary; loop39 kept
400 chars; the gate file kept one line. Diagnosing defect 2 required three
level-deep re-runs on a warm machine and a hope. Both `verify_loop38.mjs`
and `verify_loop40.mjs` now write each failed child's complete output to
`.loop38/last_<label>.log` / `.loop40/last_loopN.log` (gitignored,
overwritten each run) at the moment the failure is detected -- the failure
and its evidence land together, and one run is enough.

**4. An assertion on the wrong half of the stream.** With 1-3 fixed, the
next full nested run exposed a fourth defect that had been hiding behind
them: `verify_loop36.mjs` asserted `total_recv_bytes` cross-transport --
the **encrypted stream from the server**, which carries WINDOW_ADJUST
timing. Under nested load the server answers a window-consuming shell with
one extra 80-byte adjust (correct behavior), and the gate read it as a
transport bug. The Loop #40 gate excludes `total_*_bytes` from
cross-transport comparison for exactly this reason; loop36 predates that
rule. It now keeps `total_sent_bytes` -- the half that is ours and is
byte-exact -- and drops the recv side, with the rationale in a comment.

**Method note, because it is what found defect 1.** The impossibility
("ALL PASS and failed anyway") was chased by treating the two halves as two
different bugs -- which they were: defect 3 made the evidence invisible,
defect 2 supplied the flaky red, and defect 1 turned the green path red too.
Defect 4 only surfaced once 1-3 stopped flaking. Each fix was verified
against the next full nested run, not against a warm single run -- a warm
single run is what made defect 2 invisible for weeks.


### Loop #74: three CI failures that had nothing to do with each other, and one that was not a failure at all

Run `39236194074` was the first CI run carrying all three of Loop #74's fixes.
It came back with 46/49 and three red gates: `loop53`, `loop56`, `loop71`.
They share no code. Reading them as one story would have been wrong, and the
useful part of this loop is that each one turned out to be a *different kind*
of defect -- and that the third one was caused by the fix that preceded it.

#### loop71: the new files broke the rule the new gate enforces

`verify_loop71.mjs` checks that no tracked file asserts a machine-specific
absolute path. Loop #74 added two files that both hardcoded
`C:\Program Files\OpenSSH` as a probe list -- and the gate correctly
reported them:

```
FAIL  no tracked file asserts a machine-specific absolute path
    6 hit(s) in 2 file(s):
        host/gen_loop53_fixtures.mjs:113  C:\\Program   (3 hit(s))
        host/verify_loop74.mjs:89         C:\\Program   (3 hit(s))
```

The fix is the one `sshd_setup.mjs` already demonstrates: a probe list is a
*candidate* list, and it has to say so. Both files now carry the same
`machine-path-exempt:` marker with the same reason, and the candidate list is
the same three entries `sshd_setup.mjs` probes. `verify_loop71.mjs` -> 9/9.

Worth noting: the gate had been green for a loop and a half while the
repository was growing files that violated it. The gate was not wrong to be
green -- it only sees what is committed. It went red the moment the
violating files were committed, which is exactly what a gate is for.

#### loop53: the generator signed the wrong key

`verify_loop53.mjs` came back 24/26, with `user-cert` failing in both
transports:

```
FAIL  user-cert [native]  error="transport:handshake:SignatureInvalid" want leaf HostkeyCertAuthority
```

The contract says the client must refuse a USER certificate *as a host
identity*, and name that as the reason. Instead the handshake died earlier,
in the signature check, with a completely unrelated error. **A gate that
fails for the wrong reason is worse than a missing gate**, because it sends
the reader after the wrong bug.

The cause was in the fixture generator added in Loop #74, not in the client.
`host/gen_loop53_fixtures.mjs` had one `sign()` that took the CA and the
output path, and hardcoded the *subject*:

```js
args.push(path.join(DIR, "host.pub"));   // every certificate, always
```

But the user certificate has to be issued over `userhost.pub`, because the
MITM in `verify_loop53.mjs` signs the handshake with the `userhost` private
key and the client verifies that signature against the certificate's **inner
key**. With the inner key being `host.pub`, the signature check fails first
and the certificate-type check -- the one the case exists to exercise -- is
never reached.

Measured against the original 2026-10-13 fixture set to be sure of the
shape, with a throwaway decoder that reported each certificate's inner key
and the public key it matched:

```
usercert-in-cert.pub     type=1(user) inner<- userhost.pub
host-good-cert.pub       type=2(host) inner<- host.pub
```

So `sign()` now takes the subject as a parameter, and the generator **checks
its own output**: it parses each certificate blob the way OpenSSH lays it
out and asserts the type, the inner key, the principals and the signing CA.
A generator that can only report "the files exist" ships a wrong fixture set
just as happily as a right one, and the wrong one costs a CI run to discover.

`host/loop53_fixture_mutations.py` swaps the USER certificate for the HOST
one and requires the generator to notice -- and to name the file and the
property. It does.

The principals were aligned with the committed fixture set at the same time
(`other.example.com` / `alice` rather than the `10.0.0.9` / `testuser` this
generator had invented), and `user-cert-cert.pub` -- the
`NON_HOST_PRINCIPAL_CERT` source that `host/cert_gen_fixture.py` reads -- is
now generated too. Two sources of truth for the same certificates is still
a gap, but a gap between two *generators* is smaller than a gap between a
generator and one machine's leftovers.

`verify_loop53.mjs` -> 26/26.

#### loop56: the C harness was reading uninitialised stack memory

`verify_loop56.mjs` came back 36/41, and the C harness reported **12 of 28**
assertions failed. The same source passed 28/28 on the developer machine.

That is the shape of a memory bug, and the interesting part is *which* memory.
`verify_c/knownhosts_harness.c` decoded base64 like this:

```c
char padded[1024];
memcpy(padded, s, slen);
int r = slen % 4;
if (r != 0) { while (strlen(padded) % 4 != 0) padded[strlen(padded)] = '='; }
padded[strlen(padded)] = '\0';
```

Two undefined behaviours in three lines:

1. `padded` is never NUL-terminated after the `memcpy`, so the first
   `strlen(padded)` reads past `slen` into whatever the stack held.
2. The padding loop measures the string with `strlen` *after* overwriting
   the terminator it just measured, so each iteration can walk further into
   the uninitialised region.

The trigger is precise. An ed25519 public key blob is exactly 68 base64
characters, and `68 % 4 == 0`, so the `if` branch was skipped and the
decoder went straight to the unterminated `strlen`. Every ed25519-key
assertion in the harness was reading uninitialised memory. The vectors whose
length is not a multiple of four went down the padding branch, where
`strlen` hit a copied-in zero within `slen`, and they were green all along
-- which is why the failure looked selective.

**This was never a compiler difference.** It was undefined behaviour, and
the two compilers simply left different bytes on the stack. The way to prove
that, rather than argue about it, is to make the compiler poison the stack
on purpose:

```
clang -O2 -ftrivial-auto-var-init=pattern -o kh_poison.exe knownhosts_harness.c -lm
```

Before the fix that build gives **12/28**, and the 12 that fail are exactly
the 12 that failed on CI. The reproduction does not depend on any particular
compiler, which is the point: it is a measurement of the defect rather than
of the environment.

The fix terminates the buffer right after the `memcpy`, and computes the
padding count arithmetically instead of re-measuring it:

```c
padded[slen] = '\0';
int r = slen % 4;
if (r != 0) {
    int pad = 4 - r;
    if (slen + pad >= (int)sizeof(padded)) return -1;
    for (int k = 0; k < pad; k++) padded[slen + k] = '=';
    padded[slen + pad] = '\0';
}
```

The overflow guard is new too: the old `slen >= sizeof(padded)` check
protected the `memcpy` but not the padding, which could write three bytes
past the end.

A second instance of the same class was hiding behind the first: the hashed
host vector (V4) has a 27-character salt, which is `27 % 4 == 3`, so it took
the padding branch -- and that branch was the one that overwrote its own
terminator. With the terminator fixed but the padding still measured by
`strlen`, the poisoned build still failed V4, with the 27-byte input inflated
to 1024 bytes. Both halves had to be fixed.

**And a third defect, found by asking a question the gate was not asking.**
The boundary check that came with the fix -- "does the decoder still agree
with Python's `base64.b64decode` for every input length?" -- turned up that
the decoder emits **three bytes for every group of four sextets**, whatever
the group's real content was. OpenSSH's `b64_pton` emits `sextets * 6 / 8`
bytes, so a 27-character nopad string is 20 bytes there and 21 bytes here.

One call site compensated for that (`if (salt_n == 21) salt_n = 20;` in
`match_hashed_host`). The other did **not**: `parse_kh_line` took the
decoder's length verbatim as `key_blob_len`, so a public key blob whose
base64 length is not a multiple of four would make this harness believe the
peer presented a different key -- a Mismatch where the correct answer is Ok.
Every current fixture happens to be 68 characters (51 bytes, exact), so the
latent defect had never fired.

That is the worst shape a defect can have in a *reference implementation*: it
is wrong only on inputs the fixtures do not contain, and when it does fire it
reports the **tested** code as broken. The decoder now emits
`sextets * 6 / 8` bytes, the truncation patch is gone (the length is
asserted instead), and the C harness has its own assertion for the byte
count of every residue modulo four -- `""`, 1, 2, 3, 4, 5, 6, 7, the 27-char
salt and the 68-char key blob.

`host/verify_loop75.mjs` is the permanent guard. It rebuilds the harness
with `-ftrivial-auto-var-init=pattern` and requires the *same* number of
passing assertions as the normal build, plus five source-level assertions
that the buffer is terminated, the padding is computed, the byte count
follows the sextets, and the truncation patch is gone. A build that only
ever runs on a stack that happens to be zero cannot tell a correct decoder
from a lucky one.

`host/loop75_mutations.py` proves the guard is not vacuous: it reverts each
of the three halves of the fix in turn and requires the poisoned build to go
red. All three are **CAUGHT**:

```
CAUGHT  M1  (the original decoder, unterminated buffer and strlen-measured padding) -- poisoned build gave 12/29
CAUGHT  M2  (the buffer is never NUL-terminated after the memcpy)                 -- poisoned build gave 12/29
CAUGHT  M3  (the decoder always emits three bytes per quad)                        -- poisoned build gave 27/29
```

M1 and M2 reproduce the same 12/29 that CI saw. M3 fails the new base64
length assertion instead, which is the point of that assertion.

#### The pattern across all three

Three failures, three different kinds, and one shared property: **each one
was invisible to the environment it was born in.**

- loop71's violation was committed by a fix that landed in the same loop.
- loop53's bug was in the generator that fix added, and the original
  fixture set that the generator was supposed to reproduce had the right
  shape -- the generator was checked against nothing.
- loop56's bug had been in the C harness since Loop #13, green on every
  developer machine, red on every CI runner, and the reason was a byte of
  stack memory.

The last one is the expensive kind. It took until a runner with a different
compiler happened to land in a different stack layout, and the fix is not
"the C harness" but **a gate that poisons the stack on purpose**. The
general rule this loop adds: a gate that runs in one environment and passes
there has not been shown to be correct, it has been shown to be lucky.

### Pushing to GitHub when the git front door is down

`github.com`'s git front door intermittently resets the connection on this
machine. Measured on 2026-10-20, three shapes in a row:

```
fatal: unable to access 'https://github.com/riantr/moonbit_openssh.git/':
  Connection timed out after 300002 milliseconds
fatal: unable to access 'https://github.com/riantr/moonbit_openssh.git/':
  Recv failure: Connection was reset
fatal: unable to access 'https://github.com/riantr/moonbit_openssh.git/':
  Failed to connect to github.com port 443 after 21038 ms
```

`api.github.com` stays reachable the whole time. So the two remotes need
different treatment: **Gitee pushes straight away** (it is a different host
and it does not have this problem), and GitHub needs a retry with backoff.
Three attempts with a growing backoff was enough that day; the third
succeeded.

**The API cannot be used as a substitute for the push, and the reason is
worth writing down**, because the obvious workaround is wrong in a way that
does not show up until much later.

The GitHub REST API can create a commit directly:
`POST /repos/{owner}/{repo}/git/commits` with a tree and a message. It
works, and it produced a commit with **the same tree SHA**
(`111f637d4dad247de53b58d5436db7c5667f341f`) and the same parent -- so the
content was byte-identical. But the commit SHA came out different:

```
local  5f006e24006e111a2bdac21b196eb8a092c2724e
api    940e8cc91da8ccd4063365de9fd704f4cd189bb1
```

The cause is that **the API normalises commit timestamps to UTC**, while
this repository's commits carry a `+0800` offset:

```
author RiantR <RiantR@local> 1792463809 +0800
```

Two commits with the same tree, the same parent and the same message but
different timestamps are two different commits. Pushing the API's version
would leave Gitee and GitHub holding **two different histories for one set
of changes**, and the next ordinary `git push` to GitHub would then be
rejected as non-fast-forward and would need `--force`. That is a much worse
outcome than waiting for the front door to come back.

So the rule is: **retry the git protocol; do not reconstruct the commit
through the API.** If a push ever does have to be reconstructed that way,
the local branch has to be reset to the remote's commit in the same
operation -- never the other way round, and never with one remote left
behind.

A related trap while measuring this: `git log --format=%B` appends a
trailing newline that the raw commit object does not have (the object's
message ends with `\n` but `%B` adds its own), so the message the API
stored was 6130 bytes against the local object's 6131. Reconstructing the
commit from `%B` therefore cannot match either, for a second reason.
`git cat-file commit HEAD` is the honest way to look at the bytes.

**Re-confirmed on 2026-10-21, and this time as a script that refuses to
lie.** The front door was down again (four attempts, ~21 seconds each, all
"Failed to connect to github.com port 443"), so the API route was tried
again -- but with the comparison built in as a *gate*, not a hope: every
changed blob is uploaded and the SHA the API returns is compared with the
one the local git already computed for that content; the tree is created
and compared with the local tree SHA; the commit is created and compared
with the local commit SHA. The ref is moved **only if all three match**.

The result is a cleaner version of the same finding:

```
20 file(s) differ
  have  AGENTS.md
  upload host/channel_oracle.py (sha verified)
  ... 18 more, every blob SHA verified
api tree sha   d3cf6a9db66e39586bdcbe6c656eaf0d12d95814
tree matches the local tree
api commit sha 35564c3a8dbadf1b33b3f87943e2ee1176761a17
COMMIT SHA MISMATCH: api=35564c3a... local=4da747cc... -- ref not touched
```

Every blob and the whole tree matched, and the commit still did not, and
the reason is the same one as before, visible in the commit the API
returned:

```
author    RiantR <RiantR@local> 2026-10-20T09:17:33Z     <- API: normalised to UTC
author    RiantR <RiantR@local> 1792545453 +0800          <- local
```

So the API route is closed for this repository, now with a measurement
rather than an argument. The script is worth keeping for the shape of it:
**compare the SHAs at every level, and refuse the final step unless they
all match.** A tool that reconstructs a commit and then hopes it is
equivalent is the thing this rule exists to prevent.

And the push itself, once the front door came back, was an ordinary
`git push` -- the fifth attempt, with a growing backoff. No `--force`, no
API, no divergent history: both remotes ended on the same commit, with
`git ls-remote` reporting identical `refs/heads` and `refs/tags`.

---

## Loop #76: direct-tcpip -- the client half of a local port forward

### What was missing

`ssh -L 8080:db:5432` is, at the protocol level, one thing: the client opens
a channel of type `direct-tcpip` and asks the **server** to connect to
`db:5432`; after that the channel carries the TCP connection's bytes
(RFC 4254 section 7.2). This repository had none of it. `src/kexflow` and
`src/sshclient` could not even name the channel type, and `src/channel` knew
only about `session` channels.

It is the client half of a whole OpenSSH subsystem. The other half --
`forwarded-tcpip`, the server-initiated direction that `ssh -R` uses -- is
still missing, and so is the local listener that turns a connection into a
`direct-tcpip` request. What this loop adds is the protocol layer of the
first: the request, the relay, and the two failure modes.

### The bytes are the contract, so they are compared against another implementation

`cmd/forward_kat` prints this client's `CHANNEL_OPEN "direct-tcpip"` payload
for four cases; `host/gen_forward_vectors.py` prints the same payloads built
with **paramiko's own encoder** (`paramiko.message.Message`). The gate
requires them to be equal, byte for byte.

Comparing our encoder with our encoder would prove nothing, and the server
is *tolerant* about the fields it does not use -- an originator it cannot
parse, for instance. A layout that is right where it matters and wrong where
it does not would pass every end-to-end test and still be a wrong wire
format. Pinning the whole payload is what catches that, and the four cases
are chosen to cover the layout's edges (an IPv6 literal, the largest port, a
long destination name) rather than to be pretty.

The end-to-end evidence is layered, and each layer is a different party:

| layer | who | what it proves |
|---|---|---|
| B | paramiko's encoder | the bytes are the protocol's bytes |
| C | a real OpenSSH 8.0p1 server | the server read our request and connected where we asked |
| C2 | the target itself | the bytes survived the round trip, split across four packets |
| D | the server's log | the server decoded our destination and originator |
| E | paramiko, live | a second implementation gets the same answer from the same server |
| F, G | the two failure modes | the failures are told apart, and neither is reported as a success |

### The failure that the protocol does not report

This is the part worth remembering.

OpenSSH's server connects to the target **asynchronously**. The server's own
log, from a run against this client:

```
debug1: server_input_channel_open: ctype direct-tcpip rchan 0 win 2097152 max 32768
debug1: server_request_direct_tcpip: originator 127.0.0.1 port 0, target 127.0.0.1 port 24099
debug1: connect_next: host 127.0.0.1 ([127.0.0.1]:24099) in progress, fd=9
debug1: server_input_channel_open: confirm direct-tcpip
debug3: finish_connect - ERROR: async io completed with error: 10061, io:0000028B46AE8440
```

The confirmation goes out **first**; the failure of the connect happens
afterwards. So there is no `CHANNEL_OPEN_FAILURE` to read: the channel opens,
and then it closes, having moved nothing. The protocol carries no signal
that distinguishes "the server could not reach the target" from "the target
accepted the connection and closed it immediately".

The first version of this code assumed the failure *was* reported -- the
comment said so, and the comment was wrong. The negative test caught it
immediately: forwarding to a port nobody was listening on printed
`result: FORWARD_DONE` with zero bytes. That is the "failed open" shape
this repository keeps having to undo.

What OpenSSH's own client does with the same situation is worth measuring
rather than guessing: `ssh -W 127.0.0.1:<dead port>` against the same server
exits **0**, with empty stdout and empty stderr. It does not report the
failure either.

So this client reports a third result, `FORWARD_NO_DATA`, which describes
the **observation** and not a guessed cause:

```
result: FORWARD_NO_DATA
note: the channel opened and closed without one byte coming back
note: the usual cause is that the server could not reach the
note: target; the protocol cannot tell that apart from a target
note: that accepted the connection and closed it immediately.
```

The word "failure" is deliberately absent from the result name, because we
do not know the cause. It is also not `FORWARD_DONE`, because `DONE` means
"bytes came back". The rule -- what counts as a successful forward -- lives
in exactly one place, `src/sshclient/forward.mbt`, because the native and
the browser path both have to agree on it.

The other failure mode *is* reported by the protocol, and it arrives by a
completely different route: a server that refuses to forward at all answers
`CHANNEL_OPEN_FAILURE` with reason 1 (`SSH_OPEN_ADMINISTRATIVELY_PROHIBITED`).
`host/sshd_setup.mjs` grew a `--no-forward` lever for it, for the same
reason `--hostkey-algs` exists: a server configuration that is a *test*
condition should be a lever, not the default.

### The client half is not the whole feature

What is here: the request, the relay, the window handling, the failures.
What is not: the local listener that turns an incoming TCP connection into a
`direct-tcpip` request (that is `ssh -L`'s other half, and it is socket
plumbing, not protocol), and the `forwarded-tcpip` direction that `ssh -R`
uses, which the **server** initiates. The browser path has no forwarding at
all yet, and `src/wtlive` will need the same shared state machine -- which
is why the protocol half went into `src/channel` and not into the native
driver.

### The gate

`host/verify_loop76.mjs`, 41 checks. Two of them need an OpenSSH **server**,
and no gate in the default CI tier has ever needed one -- every gate that
does is in the peer-gates tier, which CI does not run -- so whether the
runner has an `sshd` at all was unproven until the first CI run of this
gate answered it (it does, and the answer is in the next section). The
gate therefore runs the paramiko comparison everywhere, and **skips
loudly** the parts that need a server when there is none. A machine that
cannot run a check has not run it, and saying otherwise is the failure
this repository keeps having to undo.

`host/loop76_mutations.py`: six mutations, all CAUGHT. The one worth
naming is M4 -- making `FORWARD_NO_DATA` report as a success -- because that
is the exact defect the first version of this code shipped, and the gate
that catches it is the one that was written after the defect was found.

### Gate plumbing

`host/echo_server.mjs` is a TCP echo target that also reports what it
received (`ECHO <bytes> <sha256>`), so a payload the gate does not know by
heart -- the 100000-byte one that needs four packets -- can still be checked
end to end: the target says what it got, the client says what it got back,
and the two digests have to match. The maximum-packet clamp is only
exercised by a payload larger than one packet, which is why that case
exists.

### The gate that was green on one machine

The first GitHub Actions run of this gate (39377509698) failed at 17 of 34
checks, and every failure had the same shape: the client could not
authenticate.

    FAIL  the forward runs  -- result: FORWARD_FAILED
    FAIL  the paramiko oracle runs  -- AuthenticationException: Authentication failed.

Two different implementations, the same server, the same key, the same
rejection. The cause was not in the forwarding code at all. The gate asked
for a **user** -- and it asked for one specific developer's account:

    [String(port), "--kh-tofu", "--kh-host", "127.0.0.1", "--user", "hp", ...extra]

GitHub Actions runs as `runneradmin`. There is no `hp` account on that
machine, so the server had no account to authenticate and said no. The
client reports that as `AuthRejected`, and the gate's red box pointed at
the forwarding code.

Three things are worth keeping from this.

**The machine is not the repository.** This is the same rule as the
machine-path rule Loop #69 wrote `host/verify_loop71.mjs` for, applied to
an account name instead of a path, and it needed the same treatment: the
account is DERIVED, never written down. `host/ssh_user.mjs` and
`host/ssh_user.py` are the single source of it -- `USERNAME`/`USER`/
`LOGNAME`, then `os.userInfo()` / `getpass.getuser()`. Every gate that
opens a real OpenSSH server (loop34 to loop40, and this one) and every
tool that connects to one (`sftp_capture.py`, `sftp_write_capture.py`,
`forward_oracle.py`, `channel_oracle.py`, `paramiko_blob_capture.py`,
`pubkey_probe.py`, `hostkey_capture.py`) now names the account this
machine runs as.

**A gate that fails has to say why.** The client's word for "the server
said no" is `AuthRejected`, which says nothing about *why*. The reason was
in the server's log, one layer down:

    Accepted publickey for <user> from 127.0.0.1 port 56134 ssh2: ECDSA SHA256:hfuNWmjIYvsBGZ6dpCLTTAEa5LxbZABRHHVoynAxFlo

So the gate now prints the server's own account of it -- the userauth and
publickey lines -- whenever a forward or the oracle does not complete. A
red gate that names the reason is a measurement; a red gate that says
"AuthRejected" is a rumour. Two of the checks added here are about that
too: the `authorized_keys` file is read back and parsed (key type, curve
name, and an uncompressed P-256 point, not merely "the writer exited 0"),
and the server's own configuration is checked for accepting that key type.
The client signs with one type, the file offers one, and the server allows
one; when they disagree the server says "no" and the reason is invisible
from the client's side.

**A green that yesterday's file can satisfy is not a green.** The oracle
writes its result to `.loop76/oracle.json`. When the oracle failed on one
run, the file from the PREVIOUS run was still there, and the two checks
that read it -- "the oracle transferred the same number of bytes" and "the
oracle's bytes have the same digest as ours" -- passed on it. The gate
now deletes the file before the oracle runs, and the oracle records the
server and the target it was pointed at, so a result from another run is
visible instead of being read as a fresh one.

One more measurement, made while testing the fix with a second account on
this machine (`USERNAME=Administrator`): the server accepted the public key
for that account --

    Accepted publickey for Administrator from 127.0.0.1 port 56134 ssh2: ECDSA SHA256:hfuNWmjIYvsBGZ6dpCLTTAEa5LxbZABRHHVoynAxFlo

-- and then could not start the session:

    fork of unprivileged child failed

That is a property of Win32-OpenSSH running as a plain process rather than
as a service: it can only create a session child for the account it itself
runs as. It is not a client defect, and it does not arise on CI, where the
server and the account are the same `runneradmin`. It is recorded here
because it is the reason a cross-account test cannot be run to the end on
a developer machine, and the honest form of that is "authentication is
proved, session creation is not testable here" rather than a claim that
the whole thing works.

The configuration was made version-robust in the same pass, because the
runner's server is the inbox one (9.x) and this machine's is 8.0p1. The
user-key algorithm option was renamed in OpenSSH 8.5
(`PubkeyAcceptedKeyTypes` became `PubkeyAcceptedAlgorithms`), so
`host/sshd_setup.mjs` no longer guesses a spelling: it writes a candidate
configuration and validates it with `sshd -t` on the binary that is
actually going to run, and tries the next spelling if the server refuses
this one. The gate then reports which spelling the server accepted.
The authorized_keys path is listed in both spellings for the same reason --
sshd tries each entry in turn, and a path one Windows build reads as a path
the other does not would fail the whole gate with a rejection that says
nothing about the path.

### The generated vectors, and a check that could not pass

Running the peer-gates tier for the first time in a while turned up a check
that had never been able to pass, in two gates that are not in the CI tier
(loop34 and loop35). Both of them regenerate their known-answer vectors and
require the committed copy to be unchanged:

    const gen = spawnSync('python', ['host/gen_userauth_vectors.py'], ...);
    const diff = spawnSync('git', ['diff', '--stat', '--', 'cmd/userauth_test/vectors.mbt'], ...);
    check('committed vectors still match the oracle', (diff.stdout || '').trim() === '', ...);

The intent is right -- a hand-edited vector would otherwise turn the KAT into
a tautology. The comparison is what could not work. The committed file has
been through the formatter (the repository is formatter-clean; `moon fmt
--check` over the whole tree is a gate), while the generator's output had
not, and the two differ by exactly the formatter's line wrapping:

    -      "sid0", "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",
    +      "sid0",
    +      "a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf",

Every constant in both files is identical -- only the layout differs -- so
the check was comparing a formatted file with an unformatted one and
reporting the difference as "the vectors are stale". Worse, the gate
regenerates **in place**, so the unformatted copy was left in the working
tree, and every later `git diff` in the repository was non-empty because of
it.

The fix is in the generator, because the generator is what is wrong: the
file it writes is a source file in a formatter-clean repository, so it has
to produce what the formatter produces. `host/gen_userauth_vectors.py` and
`host/gen_channel_vectors.py` now run `moon fmt` on their own output
before reporting it, and the header's "Regenerate with: ..." becomes true
of the file's formatting as well as of its contents.

Measured after the change:

    python host/gen_userauth_vectors.py
    wrote cmd\userauth_test\vectors.mbt (6 cases, 9798 bytes)
    git diff --stat cmd/userauth_test/vectors.mbt   ->   (empty)

    python host/gen_channel_vectors.py
    wrote ...\cmd\channel_test\vectors.mbt (55332 bytes on disk, 9 session vectors)
    git diff --stat cmd/channel_test/vectors.mbt    ->   (empty)

The byte comparison the gate wanted now holds, and the working tree stays
clean when the gate regenerates.

One more pre-existing defect in the same area, found in the same run:
`verify_loop31.mjs` read the error count out of `moon check`'s "N warnings,
M errors" summary and treated the summary's **absence** as an error. A
package whose check is already up to date prints "no work to do" instead, so
a successfully checked package was reported as failing -- a false red that
appears only on a machine with a warm build cache, and a green that appears
on a fresh checkout. The exit status is the reliable signal in both cases;
verify_loop32 and verify_loop33 already work that way, and this copy had not
been brought along.

## The peer tier, run again for the first time since Loop #50

`ci/ci.py` keeps a measured list of gates that need something this repository
cannot provide for itself -- a live SSH peer and/or a browser Worker:

    PEER_GATES = frozenset("verify_loop%d.mjs" % n
                            for n in (31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 49))

They are excluded from the default tier **by design** (they take hours), which
is exactly why they rot: between Loop #50 and this pass, six loops changed
something every one of those gates depends on -- the host-key default (#50),
the account the gates authenticate as (#76), the known-hosts store (#52/#54),
the target-specific drivers (#63/#64/#68), and the formatter (#67). A gate
that has not been run since the thing it measures changed is not a green
gate. It is a gate that has not been run.

Running them one at a time (never two at once -- they fight over ports and
over the build directory) turned up six classes of defect. Not one of them was
in the protocol.

### A default changed underneath the gates

Loop #50 made **refusing an unpinned host** the default. The gates in this
tier were written before that and were never updated, so every one of them
that opened a real server was turned away before it could be judged:

    FAIL  result: ESTABLISHED
          | result: FAILED
          | error: HostkeyUnknown

That is a failure about pinning, reported as a failure about the thing each
gate exists to test. The fix is the same in every gate:

    // native
    const PIN_ARGS = ['--kh-tofu', '--kh-host', '127.0.0.1'];
    // browser
    kh_tofu: '1',
    kh_host: '127.0.0.1',

`--kh-tofu` is the explicit "accept this key" (`accept-new`). Nothing is
written to disk: the write-back only happens when `--kh-file` is given, and
these drivers are given neither, so the developer's own `known_hosts` is never
touched.

**A Windows shell has no empty-string argument.** The first version of this
passed `--known-hosts-text ''` as well, because that is how the native driver's
own doc describes "do not pin this time". `run()` hands its argument to a
shell, and the shell delivers the two characters `''` -- a *non-empty*
known_hosts text, which parses to zero entries, which the client refuses with
"known_hosts parsed to nothing". A gate that quotes its own arguments wrongly
fails in a way that reads like a client bug. Where an argument can be empty,
the argument list travels as an argv array (`spawnSync`), not as a command
string.

### The account, again

The same rule as the machine-path rule (Loop #69) applied to an account name:
**derive it, never write it down**. `host/ssh_user.mjs` and `host/ssh_user.py`
are the single source. loop32 and loop33 were not even passing a user -- they
relied on `cmd/wt_ssh`'s built-in default, which is the literal `"hp"`.

### A missing store backend, and a product bug it was hiding

`cmd/wt_ssh` reads the known-hosts **store** on every connection when no
`known_hosts` text was given (`cfg_kh_policy` calls `@khstore.load`). The
browser harness only loaded the store's backend when a gate passed
`khsShimUrl`, and **no gate did** -- so every browser run died with

    TypeError: Cannot read properties of undefined (reading 'load')

before it could say anything about SSH.

The fix is in one place rather than in eleven: `host/wt/worker.js` now
defaults the store's shim to the one that sits next to it. A gate that wants to
measure "there is no store at all" passes an explicit empty string, which is a
different thing from "I did not think about it".

**And the product was wrong underneath.** `src/khstore` says, in its own
comment, "**Never throw.** Every failure is a value." It meant that for a
store that *fails*. It did not mean it for a store that is not *there*: the
extern bodies went straight to `globalThis.__moonbit_khs`, so the first
property access raised a TypeError -- synchronously, outside any promise
chain. And `save` returned a hardcoded `true`, which made `cmd/wt_ssh`'s
`tofu: NOT stored` line **unreachable**: a store that refused the write
(private mode, quota, enterprise policy) was reported to the user as a store
that took it, and the whole point of Loop #52's message was to say the
difference.

Both are fixed in the store, and the shim now resolves rather than rejects
when IndexedDB refuses to open -- a refused write is an answer ("no"), not an
exception. `verify_loop52.mjs` grew a fifth step for it: with the store
removed, the connection must still succeed, and the client must say the pin
was not stored.

### A gate that could not fail

`verify_loop31.mjs` decided whether a build had succeeded by looking for the
string `error` in moon's output. moon says:

    Error: failed to run build for target Js
    Caused by:
      Package 'riantr/moonbit_openssh/cmd/ssh_live' does not support target
      backend 'js'. Supported backends: [native]

Capital `E`. A case-sensitive search for `error` does not match it, so **a
build that failed was reported as a build that succeeded** -- and the three
checks below it then read `_build/wasm/.../cmd/ssh_live/ssh_live.wasm`, a file
left over from before Loop #68 made the driver native-only. A stale artifact
was being measured as if it were the current one.

Since Loop #68 the honest expectation is inverted: `cmd/ssh_live` must be
**refused** by js/wasm/wasm-gc, and the refusal has to name the backend. The
property Loop #31 wanted to state -- "the browser path has no socket" -- is
now measured where it is true, on the artifact that actually runs in a
browser: `cmd/wt_ssh`'s js bundle must not contain `mb_tcp_connect` (the
native entry point into `src/tcp/winsock.c`) and must contain `__moonbit_wt`
(the byte-stream shim the browser side talks to).

### Two mutation anchors that stopped matching

`host/channel_mutations.py` and `host/sftp_mutations.py` keep the text they
mutate as a literal anchor. Loop #67 ran `moon fmt` over the tree, and the
formatter changed some of those literals -- a trailing comma after
`{ ..st, window: w, }`, the `if` in `ChanState::report` split across four
lines instead of one, `Int` becoming `Int32` in the SFTP constants, and the
`put_type`/`put_u32i` pair split onto two lines. The harness counts an anchor
that does not resolve as **not caught**:

    SKIP  drop the window when no adjust is due -- anchor count {'exec.mbt': 0, 'channel.mbt': 0}
    SKIP  make exit-status report 0 instead of the SSH 255 fallback -- anchor count {...}
    FAIL all three window/id bugs turn the KAT red  14 caught, 2 missed

So loop35, loop36 and loop39 were red, and the red pointed at the KAT instead
of at the anchor. A mutation whose anchor has drifted is not a mutation at all
-- and the harness's own rule ("an anchor that appears more than once is
NOBUILD, not MISSED") is the same instinct: a mutation that proves nothing
must not be counted as a verdict about the code.

The anchors are now the text that is in the file, and the mutated text keeps
the same shape, because a mutation that changes the layout as well as the
behaviour would be measuring two things at once. All sixteen channel
mutations and all thirty SFTP mutations turn the KAT red again.

**The check that makes the drift visible is worth keeping:** before running
the mutations, resolve every anchor and require it to match **exactly one**
file, exactly once. That turns "the KAT is not sensitive" into "this text is
no longer in the source", which is a different question with a different fix.

### `moon fmt` only formats files that are inside a package

This is a toolchain fact that cost an afternoon, and it explains three
separate symptoms.

`moon fmt <file>` exits 0, prints nothing, and changes **nothing** when the
file does not belong to a package of the current module. It does not fail and
it does not warn. So:

  * `host/gen_sftp_vectors.py --out .loop40/whatever.mbt` produces an
    **unformatted** file, while the same generator writing
    `cmd/sftp_test/vectors.mbt` produces a formatted one. Loop #40 compared
    those two byte for byte and could never pass: the difference was 1290
    bytes of the formatter's line wrapping, and nothing about the vectors.
  * The committed `cmd/sftp_test/vectors.mbt` carries a
    `machine-path-exempt-file` block (the repository-wide convention from
    Loop #69/#71: a file that legitimately contains a machine-specific
    absolute path has to say so, and say why, *in the file*). The generator
    overwrites the whole file, so that block has to be **emitted by the
    generator** -- a hand-written header is lost the first time anybody
    regenerates, and then Loop #71 flags the file and Loop #39's staleness
    check can never pass either.
  * A scratch file placed in a package directory under a `_`-prefixed name is
    **not** ignored by the build: it produces a duplicate-declaration error.
    (A subdirectory with its own `moon.pkg` *is* ignored by the parent
    package -- but `moon fmt` will not touch it either.)

So the rules that follow:

  * a generator that writes a source file must write it **inside a package**,
    so the formatter applies, and must run `moon fmt` on it afterwards;
  * a gate that compares a committed file with a regenerated one must
    regenerate **at the package's own path** and restore the original bytes
    afterwards, rather than generating to a scratch path outside every
    package. Loop #40 now does that, and restores in a `finally` -- a gate
    that leaves a generated source file rewritten is a gate that can turn a
    later run green.

### A message that reads as a path, and a gate that names its exclusions

The three vector generators now report a formatter failure like this:

    sys.stderr.write("moon fmt failed on %s:\n%s\n%s\n" ...

`host/verify_loop71.mjs` reads the `s:` followed by a backslash as drive `s`
and the start of a path -- so a message that contains **no path at all** was
reported as a machine claim:

    FAIL  no tracked file asserts a machine-specific absolute path
          host/gen_channel_vectors.py:45  s:\n%s\n%s\n   (1 hit(s))

The gate is right to be strict, and this repository's habit is that **code
adapts to the linter, not the other way round** -- a gate that quietly skips
files is how a gate quietly stops working. So the message changed ("moon fmt
failed on the file %s\n...") and the detector was left alone.

The same pass found a second thing, and it is the more interesting one.
`host/gen_sftp_vectors.py` has to *emit* the `machine-path-exempt-file` header
that the generated vectors need (the captured bytes name the machine that
recorded them). The gate's whole-file form matches that marker **anywhere in
a file**, including inside a string literal -- so the generator inherited the
exemption by accident, invisibly, and a future machine path added to the
generator would not have been caught.

An accident is not an entry. It is now a named entry in the gate's own
`SELF_EXCLUDED` list, with the reason attached, and the reason is the one
that has to keep being true: the generator's exemption is for the marker text
it *emits*, and it contains no machine path of its own.

### What the peer tier looks like now

Measured on this machine, one gate at a time:

| gate | before | after |
|---|---|---|
| loop31 | 26/40 | 40/40 |
| loop32 | 48/54 | 54/54 |
| loop33 | 25/35 | 35/35 |
| loop34 | 38/44 | 50/50 |
| loop35 | 38/39 | 39/39 |
| loop36 | 37/39 | 39/39 |
| loop37 | 51/52 | 52/52 |
| loop38 | 32/33 | 33/33 |
| loop39 | 37/44 | 44/44 |
| loop40 | 41/42 | 42/42 |
| loop49 | 10/11 | 11/11 |
| loop52 | 9/9 | 10/10 (step 5 added) |

The rule this adds: **a gate that has not been run since the thing it
measures changed is not a green gate.** The peer tier is excluded from CI for
a reason -- it needs a live peer and a browser -- but "excluded" and "never
run again" are different states, and only one of them is a decision.

**Run them one at a time.** The peer gates fight over ports and over the build
directory, and running two of them at once made one of them fourteen times
slower and produced six node crashes that looked like gate failures. That is
the same rule as the mutations tier running in a throwaway worktree, for the
same reason.

**The nested regression chains are exponential.** loop39's regression section
runs loop31..loop38, and each of *those* has a regression section of its own.
It terminates, and it is the reason a single peer gate can take an hour --
which is also why the batch that was supposed to run three gates hit the
one-hour ceiling in the middle of loop40's chain. `verify_loop40.mjs` has a
`--skip-regression` flag for exactly this: the chain was already run gate by
gate, and re-running it inside every gate is what turns "slow" into "cannot
finish".

## Loop #78: forwarded-tcpip -- the server half of a remote port forward

### What was missing

`ssh -R 9000:db:5432 host` is, at the protocol level, two things:

1. the client asks the **server** to listen on a port (the "tcpip-forward"
   global request, RFC 4254 section 7.1), and
2. when somebody connects to that port, the **server** opens a
   "forwarded-tcpip" channel back to the client (RFC 4254 section 7.2), and
   the client relays the bytes to its own local target.

This repository had none of it. `src/channel` could not name the channel
type, and `chan_step` had **no branch for an inbound CHANNEL_OPEN at all**:
message 0x5a fell into the catch-all `_ =>` and was dropped. The symptom of
that is the worst kind -- "the server opened a channel and it never
appeared" -- because every other part of the connection looks perfectly
healthy.

Loop #76 added the mirror image of this (`direct-tcpip`, the client half of
`ssh -L`). This loop adds the other half, and the two are mirror images all
the way down: the *same* CHANNEL_OPEN_CONFIRMATION, the same window rules,
the same EOF/CLOSE dance, but with the channel numbers running the other way.

### Three things only a real server can settle

RFC 4254 section 7.1 and 7.2 leave three questions open, and all three of
them are the kind where reading the specification and reading the code give
different answers.

**1. The reply to "tcpip-forward" does not always carry a port.** The RFC
says the reply carries the allocated port; OpenSSH's server puts a u32 in the
reply only `if (allocated_listen_port != 0)`, and that variable is filled in
only when the client asked for port 0. So:

| the client asked for | the reply payload is |
|---|---|
| port 0 | a u32 -- the port the server allocated |
| a specific port | **empty** |

Measured against a real Win32-OpenSSH 8.0p1 server, by
`host/remote_fwd_capture.py` (which drives the server through paramiko and
prints the raw bytes):

```
client asked for port 0     -> reply payload = 00 00 fb 51   (u32 64337)
client asked for port 23456 -> reply payload = (empty)
```

A parser that reads a u32 out of that reply unconditionally reads past the
end of the message when the client named the port itself -- on a real server
that is a malformed packet, not a missing field. The gate runs **both**
shapes end to end, because only the second one can catch that.

**2. The port inside a forwarded-tcpip open is the port the server was
LISTENING on**, not the ephemeral port of the connection it accepted. The
same capture, with the open decoded field by field:

```
0000000f "forwarded-tcpip"
00000002 sender channel = 2
00200000 initial window = 2097152
00008000 maximum packet = 32768
00000000 host = ""            (the listen address we asked for)
0000fe59 port = 65113         (the port the server was LISTENING on)
00000009 originator ip = "127.0.0.1"
0000fe5a originator port = 65114
```

This is not a detail. OpenSSH's own client matches an incoming
forwarded-tcpip against its configured forwards by exactly that number
(`open_listen_match_tcpip` compares it with the port the client asked to
listen on), so a client that reads the other number refuses every channel
it is sent.

And the number is easy to get wrong by reading it the obvious way. The
OpenSSH server puts `get_local_port(c->sock)` into that field -- the local
port of the socket it has just accepted -- and "an accepted socket has an
ephemeral port" is the natural assumption and it is **wrong**: an accepted
socket keeps the *listener's* local endpoint, so `getsockname()` on it
answers with the listening port. The 8.0p1 server on this machine and the
9.9 and 10.4 sources therefore agree, and the agreement is not obvious --
it is the kind of thing that reads as a contradiction until you look at what
`getsockname` returns for an accepted socket.

The rule this loop follows: **when the source and the server seem to
disagree, the server is the specification** -- and when they seem to
disagree, work out *why* before believing that they do. The measured bytes
are in `host/gen_remote_fwd_vectors.py` as vector P1, and they are the bytes
of a real server, not bytes this repository invented.

**3. The server does not know the client's local target.** The "tcpip-forward"
request carries the *bind* address and the port, and nothing else: the
"connect to db:5432" half of `ssh -R` lives only in the client's own
configuration. So the local target has to be given to the driver
(`dest_host` / `dest_port`), and the fields inside the forwarded-tcpip open
are only good for **checking** that the channel is the one we asked for --
which is what this client does, and what OpenSSH's client does.

### The channel state machine grew a second role

`ChanState` now knows whether the channel was opened by us or by the peer.
That is not bookkeeping, it is the difference between two opposite flows
sharing one state machine:

| | we opened it | the peer opened it |
|---|---|---|
| who sends CHANNEL_OPEN | us | the peer |
| who sends CHANNEL_OPEN_CONFIRMATION | the peer | us |
| the channel number in the confirmation | the peer's | ours |
| `remote_id` | the peer's | the peer's |
| `local_channel` | ours | ours |

The existing `local_channel` / `remote_id` convention carries over unchanged
-- the inbound DATA's recipient is *our* number in both cases -- so the
window rules, the EOF and CLOSE handling, and the `stdin_take` clamping all
work for a peer-opened channel without being touched. What did change:

* `chan_step` grew a 0x5a branch. It **records** the open and returns no
  action: whether to accept the channel is a policy decision, and the policy
  belongs to the driver. `confirm_open_action` and `refuse_open_action` are
  the two answers, and the driver picks one.
* A CHANNEL_OPEN arriving on a channel *we* opened is now
  `Malformed("unexpected_open")` instead of being silently dropped. It used
  to fall into the catch-all, which is how a peer-initiated channel could
  vanish without a word.
* `ChanState::take_stdout` exists because a relay has to **drain** the
  inbound buffer as it goes. `exec` and `direct-tcpip` can afford to keep
  everything until the end; a relay cannot, because the far end is waiting
  for the bytes we are holding. `stdout_len` stays the *cumulative* count
  across drains -- otherwise "we drained it" and "we never received
  anything" would look the same.
* `ChanState::close_action` exists because EOF and CLOSE are two different
  things.  What it does **not** do is rescue a hang: the first draft of this
  section claimed that OpenSSH will not send its CLOSE until it has
  received ours, so "send EOF and stop" leaves the connection hanging with
  the symptom "the connection is still there, and it never ends".
  **That claim was wrong**, and wrong in the way only a measurement catches
  -- it was read off the source and never tested.  What the server actually
  does, from its own log (the sshd this loop starts):

      channel 2: read<=0          the proxied socket reached EOF
      channel 2: send eof         the server's CHANNEL_EOF
      receive packet: type 97     our CHANNEL_CLOSE
      channel 2: send close       the server's CHANNEL_CLOSE

  So the server sends its EOF because **its** socket ended -- not in answer
  to anything we sent -- and its CLOSE is triggered by **either** our EOF or
  our CLOSE.  Two consequences, both measured: sending EOF without CLOSE
  does *not* hang (the state machine answers the peer's CLOSE with one of
  its own), and sending CLOSE without EOF leaves the peer never told that
  our input direction had ended.

### The relay is not full duplex, and saying so is part of the work

MoonBit has no threads. Two blocking reads cannot happen at the same time --
whichever goes first starves the other -- so the relay reads the local end
**only right after writing to it**, and reads the SSH end in between. A local
target that does not answer stalls the relay.

That is a real limitation and it is stated in the code, not hidden. The
accurate description is: *the local end is read right after it is written to;
bytes that arrive on the SSH end in the meantime wait in the socket buffer
and are not lost, but they are deferred.* A genuinely full-duplex relay
needs both ends to be pollable, which means the SSH transport has to be able
to say "nothing has arrived yet" -- that is a different loop, and it is
listed in the gaps below.

### stdout is block-buffered, so the mid-flight line has to go to stderr

The client has to tell the gate which port the server granted, and it has to
do it **while it is still running** -- the gate is the party that connects
to that port, and the relay has not started yet.

`println` writes to stdout, and stdout is block-buffered when it is a pipe.
So the line sat in the buffer, the client went on to block in "wait for the
server to open a channel", and the gate sat there waiting for a line that
would only be flushed when the process exited -- which was never, because
the gate was the one who had to make the connection that would let the
client finish. A deadlock with a plausible-looking cause.

`eprintln` is not buffered, so the granted port goes to **stderr**, under a
different key (`granted_port:`, not `listen_port:`) so that a script reading
the two streams together cannot confuse the mid-flight line with the final
report.

### What the gate proves

`host/verify_loop78.mjs`, 59 checks:

| layer | who | what it proves |
|---|---|---|
| B | paramiko's encoder and decoder | the bytes are the protocol's bytes (11 vectors) |
| B | a real server's captured bytes | the forwarded-tcpip layout, field for field |
| C1 | a real OpenSSH 8.0p1 server | the server granted a port and opened the channel |
| C1 | the probe at the far end | the bytes survive the relay, in **both** directions |
| C1 | the local target's own digest | what actually arrived at the far end of the relay |
| C1 | the server's log | the server opened a "forwarded-tcpip" channel, on that port |
| C2 | a real OpenSSH 8.0p1 server | the reply with **no** port in it is handled |
| D | a server with `AllowTcpForwarding no` | the refusal is reported, and the client does not hang |

The end-to-end case is a genuine round trip and not a one-way pipe: the
client writes a payload into the local target, the target echoes it, the
echo comes back over the channel to the probe; then the probe sends bytes of
its own, the client relays them to the local target, and the target's echo
comes back the same way. The local target's own `ECHO <bytes> <sha256>`
line is the far end's independent account of what it received -- the
client's counters say what the client *believed* it moved, and only the
target's digest says what arrived.

`host/loop78_mutations.py` mutates eight ways this code could plausibly be
wrong -- swapping the two channel numbers in the confirmation, asking for no
reply, reading an empty reply as port 0, answering the server's open with a
failure, dropping the bytes the channel delivered, addressing the EOF to our
own channel instead of the peer's, never sending our EOF, and reading the
originator port where the listen port belongs -- and requires each of them to
turn a named gate check red. A mutation that does not compile is reported as
INVALID, because a build failure is not evidence about the gate.

A mutation that **cannot** fail is not evidence either, and this loop found
one: "never send our CLOSE" leaves the gate completely green, because the
state machine answers the peer's CLOSE with a CLOSE of its own, so the
client finishes exactly as before. It was replaced by "never send our EOF",
which is caught by the one check that looks at what we actually sent.

Each mutation was also run **on its own** before the batch, because the
author's expectation and the measurement disagreed once. Addressing the EOF
to our own channel was expected to hang the client (the reasoning was the
wrong claim above); measured, the relay still works and the client exits 0,
but the server takes our EOF for the end of a different channel, tears the
connection down underneath the relay, and the client reports
`REMOTE_FORWARD_FAILED` instead of a finished forward. The mutation is
real and the gate catches it -- but under a different name than the one it
was written for, and a mutation script that only accepts its own guess
would have called that a miss and pointed at the gate instead of at the
expectation.

`host/loop78_mutations.py --only N` runs a single mutation, which is how
that disagreement was settled without re-running the whole batch.

### The local run was killed mid-way, and it was not the code

The local `python ci/ci.py --tiers env,build,gates` -- the same three tiers
the CI job runs -- died part-way through on 2026-10-22. `verify_loop46.mjs`
was killed after 196.8s (exit `0x40010004`), and then **every** gate after
it died in about 0.1s with `0xC0000409` and no output at all: no header, no
check, nothing. The engine itself was still alive, because it is the
parent.

What it is not: a defect in those gates. Each of them passes when it is run
on its own -- loop46 is 53 checks ALL PASS, loop47 is 19 checks ALL PASS --
and the gates before the break (9, 22 through 45) all passed in the same
run. The machine was carrying an unrelated multi-process job at the time,
and the CI runner -- a clean VM with nothing else on it -- runs the same
three tiers in 20.4 minutes.

So the fact worth keeping is not a theory about why the process died. It is
this: **a gate that dies with no output at all has usually not run**, and the
cheap way to tell the difference between "the code is broken" and "the
machine stopped cooperating" is to run the gate **on its own**. The gates
were re-run in small batches with a per-gate timeout, which is also the
practical way to get a green local run on a busy machine: a batch of eight
gates with a timeout each cannot be taken down by the first one that hangs.

The CI job runs `--tiers env,build,gates` and **not** the mutations tier, so
the eight mutations of this loop do not lengthen it.

### The CJK snapshot has to be regenerated when a loop writes Chinese

`verify_loop67.mjs` compares the CJK content of every `.mbt` / `.moon` /
`.pkg` file against a committed snapshot, and it fails when a file that is
present in both has gained or lost a CJK run. The guard exists to catch a
formatter that eats Chinese characters, and it cannot tell "the formatter
ate it" from "a human wrote a new comment" -- it is not built to, and a
human writing a new comment is the common case.

So: **a loop that adds or edits Chinese comments must regenerate the
snapshot** (`python host/cjk_snapshot.py save .cjk_snapshot.json`) and
commit it. Three existing files changed here (`cmd/ssh_live/main.mbt`,
`src/channel/channel.mbt`, `src/channel/exec.mbt`); the three new ones
(`src/channel/globalreq.mbt`, `src/sshclient/remotefwd.mbt`,
`cmd/remote_fwd_kat/main.mbt`) were only reported as NOTEs, which is the
guard saying "a file I have never seen" rather than a failure.

This cost a CI round trip. The first push of this loop reached the runner
with the old snapshot, and `verify_loop67.mjs` was the **only** one of the
52 steps that went red -- everything else, including this loop's own gate,
was green. The report is in `ci/artifacts/steps/verify_loop67.mjs.log`, and
the fix is one command. The order matters too: regenerate the snapshot
**after** the last edit to a Chinese comment, and after `moon fmt`, because
a snapshot taken in between is a snapshot of a tree that does not exist.

### A gate that went red for a reason that had nothing to do with the code

`verify_loop49.mjs` (a peer gate) failed twice in a row on this machine:

```
FAIL  known_hosts round trip  spawn failed: spawnSync cmd ETIMEDOUT
```

with every other check in the gate green. The obvious reading is that the
known_hosts round trip broke. It had not: the command it runs,
`moon test src\knownhosts`, finishes in 0.7s by hand and prints
"Total tests: 49, passed: 49, failed: 0".

The cause was one character of the timeout. Node's `spawnSync` timeout is in
**milliseconds**, and the call said `timeout: 900` -- nine tenths of a
second. `moon test` has to compile the test driver, so it takes a second or
two, and the check was killed before it could report anything. The same
command in `verify_loop50.mjs` and `verify_loop51.mjs` says `900000`, and
every other spawn in the tree says 30000 / 60000 / 90000 / 120000 /
180000 / 300000 / 900000. loop49 was the only three-digit one, and it was
the only one that failed.

The unit is what made it invisible: **900 milliseconds is a plausible-looking
number**, and the failure message does not say "milliseconds" -- it says
`ETIMEDOUT`, which reads like the toolchain was unreachable rather than
like a deadline that was too short for the work. It is fixed
(`timeout: 900000`), and the gate is green: 11/11.

The general rule this suggests, and the one worth keeping: **a gate that
fails with a timeout has to be re-run by hand before it is believed.**
A timeout says the deadline was hit, not that the work was wrong, and the
two are indistinguishable from the failure message alone.

### The gaps this loop does not close

* **No full-duplex relay.** See above: the local end is read right after it
  is written to.
* **No local listener.** `ssh -L` means "listen locally, and for each
  connection open a direct-tcpip channel". The listener is still missing;
  Loop #76 built the channel half. -- **closed by Loop #79**, see below.
* **No browser path.** `src/wtlive` drives the same protocol over a
  WebSocket, and a peer-initiated channel has to be handled there too. The
  protocol layer is shared (`src/channel`), so the browser side needs a
  driver, not a second implementation.
* **No `cancel-tcpip-forward`.** The request exists in the protocol and the
  constant is in `src/channel/globalreq.mbt`; nothing sends it yet. --
  **closed by Loop #81**, see below.

---

## Loop #79: the local listener -- the other half of `ssh -L`

### What was missing

`ssh -L 9000:db:5432 host` is two things:

1. the client **listens** on a local port, and
2. every connection that arrives on that port becomes one "direct-tcpip"
   channel to the server (RFC 4254 section 7), and the bytes are relayed to
   and from the server's target.

Loop #76 built the channel half. Nothing listened: there was no `listen()`
anywhere in the repository, so a client could open a direct-tcpip channel but
there was no way for a local program to reach one. Loop #78 built the mirror
image (`ssh -R`: the server opens the channel, the client relays to its own
target).

This loop adds the listener (`src/tcp`), the relay that drives it
(`src/sshclient/locallisten.mbt`), the command-line mode
(`cmd/ssh_live --local-forward`) and the gate.

### The listener is its own type, and it is in `src/tcp`

A listening socket and a connected socket have different contracts -- the
same reason `ByteStream` is a separate trait from `Transport` (Loop #78) --
so `TcpListener` is a separate type with `listen` / `port` / `accept` /
`close`.

`accept` takes a deadline and reports **three** outcomes, not two:
`Accepted(conn, peer_ip, peer_port)`, `Timeout` ("nobody yet") and `Failed`
("the listener is broken"). Collapsing the last two into a single `None`
makes a listener that cannot be stopped look like a listener that is merely
idle, and the relay has to tell those apart: "nobody is using this forward"
and "the forward is broken" call for different actions.

The relay does not mention `TcpListener` at all. `src/sshclient` does not
depend on `src/tcp` (Loop #64 removed that arrow on purpose, and loop64's
gate asserts that the repository has exactly one `impl Transport for`), so
the listener arrives as an injected closure:

    accept : () -> AcceptResult[连接]

`AcceptResult` has the same three cases as `AcceptOutcome`, for the same
reason: `NoConnection` means "ask again", `Failed` means "stop".

### Three defects in the socket layer that had to be fixed first

1. **`mb_tcp_close` called `WSACleanup()` on every close.** A Winsock
   process calls `WSACleanup()` once, at the end. Calling it on every socket
   close tears the process's Winsock state down while other sockets are
   still open -- and a local forward has three sockets at once (the
   listener, the SSH connection, the accepted connection). The socket count
   is now tracked, and the cleanup happens when the last one goes.
2. **`Bytes::from_array` copies.** The buffer C writes into is the `Bytes`,
   not the `FixedArray` that was handed to it. Reading the bound port back
   out of the `FixedArray` returns the zeros it was created with -- which is
   how the first version of this loop reported "port 0" for a listener that
   was working perfectly. The trap is already documented in
   `TcpConn::recv_some`; it is now documented twice, because it was paid for
   twice.
3. **The accepted connection's peer address is read back out of the `Bytes`
   too**, for the same reason.

### The relay's shape: strictly alternating, and why

MoonBit has no threads, and two blocking reads starve each other, so the
relay runs one direction per round:

1. send whatever is owed (`pending`),
2. read the local end, send it into the channel,
3. read the channel, write it to the local end.

Step 3 has to come after step 2 for the same reason Loop #78's relay reads
the local end after writing to it: the local end of an `ssh -L` is usually
the party that speaks **first** (request/response protocols: HTTP, a
database, SSH itself), and a reply that sits in the channel while we block
on the local socket is a deadlock.

The known boundary, stated in the code rather than hidden: a target that
**speaks first** (an SMTP banner, say) stalls the relay in step 2, because
the local end stays quiet and we wait for it. A real `ssh -L` selects on
both ends; that needs a pollable transport, which is listed in the gaps.

### "A read that did not fill the buffer means there is no more"

Step 2 reads up to 32 KiB. A **short** read means the socket has nothing
more for now, so the round moves on to the channel. A **full** read means
there probably is more, so it reads again and sends again.

This is not an optimisation; it is the difference between "small transfers
work" and "large transfers finish". The SSH channel window is 2 MiB, and the
peer's `WINDOW_ADJUST` is **batched** (OpenSSH tops the window up once the
peer has consumed half of it). If the relay sent 32 KiB and then went back
to wait for a packet, it would wait for an adjust that only comes after the
peer has consumed 1 MiB -- and it would never get there, because it was not
sending any more. Both sides wait for the other: the transfer stops after
32 KiB and looks like a hang.

### The `rest` that `stdin_take` returns is not "the part we did not send"

`stdin_take` **clips** the payload to the channel window and returns the
rest. The rest is "the part we have not sent **yet**". Dropping it is
silent data loss: the client believes it forwarded everything, the far end
received less, and nothing anywhere reports an error.

**Loop #78's relay dropped it.** The symptom was "a big transfer is quietly
corrupted": the bytes that do not fit in the window are the ones that
disappear, and the client looks perfectly healthy. This loop fixed that
relay as well, and the new relay keeps the remainder in a `pending` buffer
until the window opens again.

Both relays now also count the bytes they re-send. The count used to be
taken when the bytes were **read**, which only counts the part the channel
accepted at that moment; the clipped remainder is counted when it is
actually sent. Forgetting the second half produces a report that is
*smaller* than the truth on a transfer that worked -- nothing is broken,
only counted wrong, which is the kind of defect that hides for years.

### What the gate proves

`host/verify_loop79.mjs`, 55 checks:

* **A. The code builds** (`cmd/ssh_live`, `cmd/listen_kat`).
* **B. The listener works with no SSH server anywhere near it.** It binds,
  reports the port it actually got, accepts a connection, and sees the
  peer's **real** address and port. This section runs on every machine,
  including one with no OpenSSH installed.
* **C1. A real OpenSSH server forwards for us.** A probe connects to the
  port the client is listening on; the bytes go both ways; the counters
  agree; the echo target's own digest agrees; and the server's log names
  the probe's real ephemeral port as the originator -- the number Loop #76
  could only put a zero in.
* **C2. Two local connections over ONE ssh session.** The server logged two
  channels with two different numbers, and one authentication.
* **D. More bytes than the channel window holds.** Four megabytes through a
  2 MiB window, with the far end deliberately **not reading** until the
  gate lets it -- a target that reads as fast as it can would never close
  the window, and the case would prove nothing. The far end's byte count
  and digest have to match exactly.
* **E. A server that refuses to forward says so** (`AllowTcpForwarding no`
  -> `OpenFailed`), and does not hang.
* **F. Nobody connects is told apart from a broken listener**
  (`NoConnection`, not a hang).

`host/loop79_mutations.py` turns nine of those checks red on purpose: the
clipped bytes dropped, a made-up originator, a port that is not read back
off the socket, a made-up peer port, a reused channel number, the channel's
bytes dropped on the floor, a `WINDOW_ADJUST` that does not reopen the
window, the re-sent bytes not counted, and an EOF that is never sent.

### The gaps this loop does not close

* **No full-duplex relay.** The local end is read only between the channel
  reads (see above). A target that speaks first stalls it.
* **No concurrent connections.** One connection is forwarded at a time, and
  the next is not accepted until the current one finishes. Real `ssh -L`
  handles many at once; that needs either threads or a pollable transport.
* **No browser path.** A browser has no listening socket, so the browser
  build of this feature would be the other direction (the page asks the
  server to connect out). The protocol half is shared.
* **No `cancel-tcpip-forward`.** Still not sent. -- **closed by Loop #81**,
  see below.
* **The `ssh -R` relay still reads the local end only right after writing
  to it.** That direction needs the opposite discipline (the local target
  is the one that answers), so the two relays deliberately differ. The
  `pending` fix applies to both.

---

## Loop #79, follow-up: the gates that guessed how long a peer takes to start

The push of Loop #79 made CI red -- `verify_loop45.mjs`, and nothing else.
The new gate passed, every other gate passed, and the failing one had
passed on the previous run with the same code.

    FAIL  status_before_version  client could not connect

Nothing in Loop #79 touched the SFTP fault-injection path, so the reading
that suggests itself -- "the loop broke the SFTP client" -- was wrong
before it was checked. Checked: the same gate, on the same tree, passes
locally, 51/51.

The cause was a fixed sleep. `verify_loop45.mjs` started the MITM
(`host/sftp_mitm.py`, paramiko in server mode) and then waited

    await sleep(1500);

before letting the client connect. That is a guess about how long "start
python, import paramiko, bind a port" takes, and on a loaded runner the
guess loses: the client's `connect()` is refused, and the failure reads
like a protocol difference rather than like a race.

The detail that identifies it: **the failure always lands on the same
gate**. The MITM gates run in numeric order and loop45 is the first of
them, so it is the one that pays for the interpreter's cold start; every
later gate reuses the warm page cache and passes. A defect that reproduces
on exactly one gate, on the gate that happens to run first, is a
scheduling race and not a protocol difference.

The fix is the one `verify_loop46.mjs` already used for the WebSocket
bridge: wait for the process to SAY it is ready.

* `host/sftp_mitm.py` prints `listening on 127.0.0.1:<port>` on **stderr**
  as soon as the socket is bound (stderr, because stdout carries the JSON
  transcript and the gates parse its last line).
* `host/mitm_ready.mjs` waits for that line.
* Every MITM gate (45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 59) now waits
  for it instead of sleeping.

The port cannot be probed instead: `sftp_mitm.py` serves exactly one
connection, so a probe would consume the accept the gate is waiting for.

Verified locally after the change: loop45 51/51, loop47 19/19, loop59 7/7.

### The rule this makes explicit

**A gate must not guess how long a peer takes to start.** A sleep is a
guess, and a guess that loses produces a failure that looks like a
protocol difference. When a gate fails with "the client could not
connect", the first thing to ask is whether the peer was ready yet -- and
the answer has to come from the peer saying so, not from a number in the
gate.

---

## Loop #80: the SSH agent -- a key the client never sees

### What was missing

Every publickey authentication in this repository so far had the private key
**in the client**: `cmd/ssh_live`'s `test_auth_key()` hands the raw `d` to
`live_auth`, which signs the RFC 4252 section 7 bytes with it. That is fine
for a test key that is published in RFC 6979 A.2.5 and only ever used against
a throwaway sshd, and it is exactly what a production client must not do:
the private key has to be somewhere the client cannot read, or "the client
never has the key" is a claim about the process rather than about the
architecture.

`ssh-agent` is the standard answer. The agent holds the keys; the client
asks it two things -- *which keys do you have?* and *sign this* -- over a
local transport.

This loop adds the agent protocol (`src/agent`), the authentication path that
uses it (`src/sshclient/agentauth.mbt`), a command-line mode
(`cmd/ssh_live --agent <host>::<port>`), a mock agent (`host/agent_mock.py`),
an independent reference for the wire format (`host/agent_oracle.py`) and the
gate.

### The protocol, pinned from OpenSSH's source

Everything in `src/agent` was read out of `authfd.c` / `authfd.h`, not out of
a tutorial:

* **The framing** is `uint32 length` + `byte type` + payload, where the
  length counts the type byte and the payload but **not itself**. That is
  `ssh_request_reply` (authfd.c:137) exactly: it writes `POKE_U32(buf, len)`
  with `len = sshbuf_len(request)`, and the request already holds the type
  byte.
* **The message numbers** are `SSH2_AGENTC_REQUEST_IDENTITIES` 11,
  `SSH2_AGENT_IDENTITIES_ANSWER` 12, `SSH2_AGENTC_SIGN_REQUEST` 13,
  `SSH2_AGENT_SIGN_RESPONSE` 14, `SSH2_AGENT_FAILURE` 30 (authfd.h).
* **The payloads** are from `deserialise_identity2` and `ssh_agent_sign`:
  * `IDENTITIES_ANSWER`: `uint32 count`, then `count` times
    `string key blob` + `string comment`;
  * `SIGN_REQUEST`: `string key blob` + `string data` + `uint32 flags`;
  * `SIGN_RESPONSE`: `string signature`.

### The channel is a struct of closures, not a trait

The first attempt was a trait:

    pub(open) trait AgentChannel {
      fn agent_write(Self, FixedArray[Byte]) -> Bool
      fn agent_read_exact(Self, Int32) -> FixedArray[Byte]?
      fn agent_close(Self) -> Unit
    }

with `pub impl @agent.AgentChannel for @tcp.TcpConn` in `src/transport`. It
does not compile:

    Error: [4061] ... cannot implement a foreign trait for a foreign type

MoonBit will not let one package implement a trait, declared in another
package, for a type, declared in a third package. The repository's rule is
that every `pub impl` lives in the package that declares the trait -- so a
trait-based agent channel would have had to live in `src/tcp`, and
`src/agent` would have had to depend on `src/tcp` to reach it. That is the
arrow Loop #64 removed, and putting it back for a convenience is exactly the
kind of trade this repository does not make.

So `AgentChannel` is a **struct of three closures**:

    pub(all) struct AgentChannel {
      write : (FixedArray[Byte]) -> Bool
      read_exact : (Int32) -> FixedArray[Byte]?
      close : () -> Unit
    }

and the driver wraps a socket into it. Two consequences worth writing down:

* `src/agent` is still a leaf package (it depends on `src/sshwire` only), and
  `src/sshclient` gains `src/agent` without regaining `src/tcp`.
* A closure-typed field is called as `(c.write)(data)`, not `c.write(data)` --
  the compiler says `Type AgentChannel has no method write` and points at the
  parenthesised form. (`fn { ... }` is not a closure literal; it is
  `fn() { ... }`.)

### The probe comes first, and that is observable

RFC 4252 section 7 lets the client ask "may I use this key?" before it
signs anything: the same request with the boolean set to **FALSE** and no
signature field. The server answers `SSH_MSG_USERAUTH_PK_OK` (60) if it
accepts the public key, and `USERAUTH_FAILURE` if it does not.

Two reasons to do it that way:

* **Do not disturb the agent for a key the server is going to refuse.** A real
  agent may ask the user to confirm (touch the key's fingerprint). A
  confirmation prompt for a key that was always going to be rejected is pure
  harassment.
* **"The key is wrong" and "the signature is wrong" are the same sentence to
  the server.** Both come back as `FAILURE`. Only the probe separates them.

The second reason is the one with a testable consequence, and the test is
uncomfortable for the obvious implementation: **a successful run cannot show
that the probe happened.** A successful run signs exactly once whether or not
the client probed first. So the gate runs a *second* agent, holding a key the
server does not accept, and asserts that this agent was **never asked to
sign** -- the mock's sign counter has to be zero. A client that signed before
probing shows one.

That is why `host/agent_mock.py` counts, and why the gate reads the count
rather than the transcript.

### The signature is carried, not recomputed

The agent's `SIGN_RESPONSE` payload is `string signature`, and the signature
inside it is already the **SSH-shaped blob** -- the same shape the publickey
request's `string signature` field carries. So the client puts it in
**unchanged**. It does not parse it, does not re-encode it, and does not
re-sign.

This is worth a note about OpenSSH's own encoding, because it is a place
where "reasonable" and "right" differ. OpenSSH builds an ECDSA signature blob
as

    string  "ecdsa-sha2-nistp256"
    string  ( mpint r || mpint s )

and `sshbuf_put_bignum2` writes a **u32 length prefix** before the body
(`regress/unittests/sshbuf/test_sshbuf_getput_crypto.c`: `sshbuf_put_bignum2`
leaves `sizeof(expbn1) + 4` bytes, and the first four are the length). So the
inner string is `u32||r || u32||s`, **not** `r || s`. RFC 5656 section 3.1.2
writes it as "mpint r, mpint s", and an SSH mpint *is* length-prefixed, so the
two readings agree -- but a reader who takes "mpint" to mean "the raw body"
produces a blob that is 8 bytes short, and the server answers "publickey ...
signature unverified", which is indistinguishable from "that key is not in
authorized_keys".

### The bounds are checked before anything is allocated

Every length in this protocol is given by the peer:

| what | who gives it | the limit | where it is checked |
|---|---|---|---|
| reply length | the agent | `MAX_AGENT_REPLY_LEN` = 256 KiB | `agent_exchange`, before the read |
| identity count | the agent | `MAX_AGENT_IDENTITIES` = 2048 | `agent_parse_identities`, before the loop |
| string length | the agent | the rest of the payload | `ag_read_string`, before the copy |

The reply length is the dangerous one: it is a u32, and taking it at face
value lets one bad agent ask the client for 4 GiB. The check is *before* the
read, not after.

`cmd/agent_kat` measures all of this rather than asserting it in prose: it
feeds the parser a channel that claims a 1 MiB reply, one that claims zero
bytes, an identity list of 2049 entries, a truncated identity and a truncated
signature, and prints `PASS`/`FAIL` for each. The identity-count case is
built with **real** entries, because a count that is simply a lie makes both
a bounded and an unbounded parser fail for the same reason -- and a test that
cannot tell the two apart is not a test.

### What the gate proves

`host/verify_loop80.mjs`, 66 checks (57 in the three sections below, 9 in the
regression section at the end):

* **G1. The wire format, byte for byte, against an independent
  implementation.** `host/agent_oracle.py` writes the same bytes from
  OpenSSH's `authfd.c`; `cmd/agent_kat` writes them from `src/agent`. Every
  hex line has to match, and the KAT has to produce the same bytes on **4
  targets x 2 modes** (the protocol is pure byte assembly -- no socket
  anywhere -- so it has to come out identical everywhere).
* **G2. A real OpenSSH 8.0p1 server accepts a signature the agent
  produced.** The mock agent holds the RFC 6979 A.2.5 key; the server's
  `authorized_keys` holds its public half. The client probes, the server
  answers `PK_OK`, the agent signs, the server answers `USERAUTH_SUCCESS`.
  The blobs are then judged **here**, not by the server: the request is
  parsed under the RFC 4252 layout, the signed blob is rebuilt the way
  OpenSSH rebuilds it and compared byte for byte, and the signature is
  verified over exactly the bytes we claim with `cryptography` -- an
  implementation that shares no code with this repository.
* **G3. The probe comes first.** A second agent holds a key the server does
  not accept. The client has to report `ProbeRejected`, and that agent's sign
  counter has to stay at **zero**.

`host/loop80_mutations.py` turns twelve of those checks red on purpose: a
frame length that counts itself, a sign request with the fields swapped, an
identity answer with the fields swapped, an identity parser that reads them
the other way round, a reply-length limit that is not enforced, an
identity-count limit that is not enforced, a probe that claims a signature
follows, a probe without the public key, a signed blob without the session
identifier, an agent asked to sign the wrong bytes, a signature not taken out
of its string, and a client that signs before it probes.

### The gaps this loop does not close

* **No named pipe, no unix domain socket.** The real agent on Windows is at
  `\\.\pipe\openssh-ssh-agent` and on unix at a unix domain socket. This loop
  uses a TCP mock, which is legitimate because the protocol does not care what
  carries it -- but the real transport is not implemented yet.
* **No browser path.** A browser has no local agent at all. The protocol is
  the reusable part; the carrier is a separate problem.
* **Only ECDSA P-256 identities are exercised.** The parser is
  key-type-agnostic (the algorithm name is read out of the blob), but no other
  key type has been through it.
* **No agent lifecycle.** No `ssh-add`, no key confirmation, no `SSH_AGENTC_*`
  messages beyond the two this loop uses.

---

## Loop #81: cancel-tcpip-forward -- the request that undoes a forward

### What was missing

`ssh -R 9000:db:5432 host` is three things at the protocol level, and this
repository had two of them:

1. the client asks the **server** to listen on a port (the "tcpip-forward"
   global request, RFC 4254 section 7.1) -- **Loop #78**,
2. somebody connects to that port and the server opens a "forwarded-tcpip"
   channel back to the client, and the client relays it to its own target --
   **Loop #78**,
3. the client no longer wants the forward and **cancels** it (the
   "cancel-tcpip-forward" global request, same section) -- **nothing**.

`src/channel/globalreq.mbt` had the request name as a constant and no code
sent it. AGENTS.md listed it as an open gap in two places.

### The cancel is harder than the request, and the reason is not the RFC

The request payload is self-describing: name, want_reply, address, port.
The cancel payload is `string name` + `boolean want_reply` + `string
address` + `uint32 port`, and the last two fields have to **match the
request it cancels** -- with the rules set by the server, not by the RFC.

Read off OpenSSH 10.4 (`channels.c`, `serverloop.c`):

* the address is compared with `strcmp(c->path, host)` -- byte for byte --
  and `c->path` is the address string **exactly as the request carried it**
  (`c->path = xstrdup(host)`). "The same address" means the same bytes, not
  the same meaning: another spelling, another case, or a missing
  normalisation is a cancel that silently matches nothing.
* the port is compared against `c->listening_port`, which is the port **the
  server allocated**. Cancelling with the port we asked for (0) matches no
  listener at all.

So the inputs of the cancel are not "what the user wants to undo" but the
**result of the request**: the port the server answered with, plus the
address that went out. Only a client that made that request has them. That
is why the API here is a *ladder* -- request, then cancel -- and not two
independent calls.

### want_reply=0 is the shape OpenSSH itself uses

OpenSSH's own client sends the cancel with **want_reply = 0**:

    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */

and the server answers only when want_reply is set (the `if (want_reply) {`
at the end of `server_input_global_request`). With want_reply=0 the server
sends **nothing at all**, so a client that waits for an answer waits for
ever. That is the easiest way to get this protocol wrong, and it is not
visible in a successful transcript: "no error" and "the cancel worked" look
identical.

The way out is to make the silent cancel *provable* by a second request. The
server processes the packets of one connection in order, so:

    cancel(P, want_reply=0)   ->  no reply at all
    cancel(P, want_reply=1)   ->  REQUEST_FAILURE

The second answer is only FAILURE if the first cancel really closed the
listener. Had the first one been dropped or malformed, the listener would
still be there and the second cancel would answer SUCCESS. The ladder gives
the silent form a deterministic verdict instead of "no complaints".

The same ladder works the other way round: cancel(P, want_reply=1) answers
SUCCESS (the server found the listener and closed it), and a second one
answers FAILURE (there is nothing left to cancel).

### The bind address is normalised before it goes out

OpenSSH's client runs the address through `channel_rfwd_bind_host` before
sending the request: "" and "*" both become the empty string, which means
"any local address". Since the cancel is matched against the address that
was **stored**, the cancel has to carry the same normalised string -- so the
normalisation happens on the request side, once, in
`@channel.rfwd_bind_host`.

### What was built

* `src/channel/globalreq.mbt`:
  `cancel_tcpip_forward_request_payload(listen_host, listen_port,
  want_reply)` and `rfwd_bind_host(listen_host)`.
* `src/sshclient/cancelfwd.mbt`: `live_forward_cancel_ladder` -- one
  authenticated connection that asks for the forward, waits for the granted
  port, calls back with it (so the caller can look at that port **before**
  the cancel), and then sends one cancel per step of the ladder, reporting
  each one separately. `ForwardCancelOutcome::{Done, Failed}` with
  `ForwardCancelError::{AuthFailed, ForwardRefused, SendFailed, Closed,
  BadPacket, NoReply}`.
* `cmd/cancel_fwd_kat`: the payloads, byte for byte.
* `cmd/ssh_live --forward-cancel <host>:<port>` and
  `--forward-cancel-no-reply <host>:<port>`: the two ladders.
* `host/gen_cancel_fwd_vectors.py`: the same payloads, built by paramiko's
  own encoder.

### What the gate proves

`host/verify_loop81.mjs`, 43 checks (1 build, 17 wire format, 18 against a real
server, 3 regression, 4 of the 18 that are about the server's own log):

* **G0. The client builds.** The gate runs a *prebuilt* binary, so a change
  to the protocol layer would not reach it unless the binary is rebuilt
  first. Without that build the mutation harness would happily "prove" that
  a broken payload still passes, because the broken payload was never in the
  binary.
* **G1. The bytes are paramiko's bytes.** `cmd/cancel_fwd_kat` prints the
  payloads; `host/gen_cancel_fwd_vectors.py` prints the same ones from
  paramiko's `Message` encoder. Every line has to match, and the KAT has to
  produce the same bytes on **4 targets x 2 modes** (the payloads are pure
  byte assembly -- no socket anywhere -- so they have to come out identical
  everywhere). On top of that the gate checks the **relation** the request
  exists for: the tail of the cancel (address + port) has to be the *same
  bytes* as the tail of the request it cancels. That relation is invisible
  if each payload is only compared against a third party.
* **G2. A real OpenSSH server cancels the forward.**
  * the port the server allocated was listening before the cancel and
    refuses connections after it -- measured while the SSH connection is
    still alive, because a closed connection tears the listener down anyway
    and would make the measurement meaningless;
  * the first cancel is answered SUCCESS, the second FAILURE;
  * the silent variant: the first cancel gets no answer at all, and the
    second one is answered FAILURE -- which is what proves the first one
    worked;
  * the server's **own** log: `cancel-tcpip-forward addr 127.0.0.1 port
    <granted>` (the granted port, never 0), `rtype cancel-tcpip-forward
    want_reply 0` and `want_reply 1`, and
    `channel_cancel_rport_listener_tcpip: close channel` -- the server's own
    cancel path running, which the client cannot forge.

`host/loop81_mutations.py` turns ten of those checks red on purpose: the
cancel sent under the *tcpip-forward* name, a cancel that always asks for a
reply, an inverted want_reply byte, the cancel with the port before the
address, an unnormalised "*" bind address, a forward request that asks for
no reply, a cancel that carries the requested port instead of the granted
one, REQUEST_FAILURE read as success, a silent cancel reported as answered,
and a ladder that sends only its first cancel.

### The gaps this loop does not close

* **Only the remote forward can be cancelled.** `ssh -L` has a
  "cancel-local-forward" in the same family; the client closes its own
  listener instead, and this loop did not touch that path.
* **No browser path.** A browser cannot listen on a port at all, so the
  cancel of a *remote* forward is the part that survives there -- but
  nothing drives it from `src/wtlive` yet.
* **The relay is still not full-duplex.** Unchanged from Loop #78: the local
  end is read right after it is written to.
* **The cancel does not verify the target went away.** It closes the
  listener; what happens to a connection that was already accepted is the
  server's business.

## Loop #82: ssh-keyscan -- the host key, without authenticating

### What was missing

There was no way to ask a server for its keys without connecting *as a user*.
The only path to a host key in this repository was the client path, and the
client path authenticates. So the question "what keys does this host have,
and is it the one I expect?" could only be answered by handing credentials to
that host first -- which is exactly the thing you want to decide *before* you
trust it.

The second half was narrower but just as real: `KnownHostEntry::to_line` could
render `host keytype base64(blob)`, but nothing produced the **hosts field**
the way OpenSSH's ssh-keyscan does. That field is not "the host name" -- it is
`put_host_port(host, port)` lower-cased, and the two rules in it are the rules
`misc.c` implements.

### The protocol, pinned from OpenSSH's source

* `ssh-keyscan.c`, `keygrab_ssh2`: the scan **only does the key exchange**.
  The comment in that function says it runs "until an error occurs or until
  the `key_print_wrapper()` callback sets `c_done`", and then it disconnects.
  It never sends `SSH_MSG_SERVICE_REQUEST` and never sends
  `SSH_MSG_USERAUTH_REQUEST`.
* `ssh-keyscan.c`, `keygrab_ssh2`: **one connection per key type.** The
  function sets `myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]` to a single
  algorithm per attempt, because a key exchange negotiates exactly one host
  key.
* `ssh-keyscan.c`, `keyprint_one`: `put_host_port(host, port)`, then
  `lowercase(hostport)`, then `sshkey_write` -- and `sshkey_write` prints the
  type name **inside the key blob**.
* `misc.c`, `put_host_port`: port 0 or 22 -> the host as typed; anything else
  -> `[host]:port`. The brackets are what keep an IPv6 literal from swallowing
  the port.
* `misc.c`, `lowercase`: ASCII upper-case letters fold, nothing else moves.

### The name in the line is not the name that was negotiated

This is the one that is easy to get wrong, and the server's own log is what
settles it. Measured against a real `sshd`:

```
server log:   debug1: kex: host key algorithm: rsa-sha2-512
known_hosts:  [127.0.0.1]:22302 ssh-rsa AAAAB3NzaC1yc2E...
```

RFC 8332 is the reason the two differ: the blob says `ssh-rsa`, the
negotiated algorithm is `rsa-sha2-512`. OpenSSH writes the blob's name
(`sshkey_write`), and OpenSSH also *reads* a known_hosts line by the blob's
name -- so a line that says `rsa-sha2-512` is a line OpenSSH would not match
against the key it just saw.

The gate asserts both halves in two different places, because they are two
different facts: the **server's log** names the negotiated algorithm, and the
**line** names the blob's type.

### One connection per key type, and each one gets its own key

The gate reads the server's log **straight after this client's scan and before
any other client has touched the server**, so the slice belongs to the scan
alone. Measured:

```
the scan opened exactly one connection per key type
  -- 3 key exchanges: rsa-sha2-512,ecdsa-sha2-nistp256,ssh-ed25519
```

Three connections, three different keys, in OpenSSH's type order. One
connection proposing all three types would negotiate one key and print one
line -- and the mutation harness has that mutation in it.

### What was built

* `src/sshclient/keyscan.mbt` -- `live_keyscan`: the handshake and nothing
  else. It uses `KnownHostsPolicy::skip()`, which is **not** a bypass: it is
  "no entries, and not strict", so it goes through the same decision code as
  an ordinary client's allow branch. A side channel around that code would be
  the shape where "the default fell through to the side channel".
* `src/sshclient/live.mbt` -- `live_proposal_with_hostkey` (a proposal that
  names one host key algorithm) and `handshake_to_session_with_proposal` (the
  handshake, with the proposal as an argument). The scan and the ordinary
  client share **one** handshake; they differ by one argument.
* `src/knownhosts/render.mbt` -- `host_field` (`put_host_port`), `lowercase_ascii`
  (`lowercase`), and `keyscan_host_field`, the composition of the two. The
  composition is a function because "who lower-cases?" has to have one answer:
  split across the driver and the library, dropping it changes nothing that a
  test can see.
* `cmd/ssh_keyscan` -- the tool. `-p port`, `-t type`, the default type list
  in OpenSSH's order (rsa, ecdsa, ed25519). The known_hosts lines go to
  **stdout**; the `# host:port SSH-2.0-...` comment goes to **stderr**, which
  is what both installed OpenSSH builds do.
* `cmd/keyscan_kat` + `host/gen_keyscan_vectors.py` -- the two rules and their
  composition, as cases, against a Python transcription of `misc.c`.

### The oracle is the real tool, not a second implementation

The comparison is against **OpenSSH's own `ssh-keyscan`**, running against the
same server, on this machine: both installed builds (the portable 8.0p1 under
`Program Files`, and the inbox 9.x under `System32`). Its known_hosts lines
have to be the **same lines, byte for byte**, and so does the
`# host:port ...` note.

That is deliberately *not* a re-implementation. A second implementation of
`put_host_port` would agree with the first one for the same reason two copies
of the same mistake agree. The installed binaries cannot agree with our bug
by construction.

### The real tool's output order is not a contract, and finding that out cost a red run

The first version of the gate compared the two stdouts **as one byte string**,
order included. It passed, twice -- and then failed, on a third run, with the
two outputs visibly identical in the first 120 characters and different after
that.

The difference was the *order*:

```
ours  line0 = ssh-rsa              theirs line0 = ecdsa-sha2-nistp256
ours  line1 = ecdsa-sha2-nistp256  theirs line1 = ssh-rsa
```

and `ssh-keyscan.c` says why. The tool opens **all** of its connections at
once -- `conprocess`/`conread`/`congreet` over a `select()` loop, one
connection per key type -- and prints each key from the key-exchange
completion callback (`key_print_wrapper` -> `keyprint_one`). So its output
order is the order the handshakes **finished**, which is timing, not
specification. On this machine the 8.0p1 build printed ecdsa before rsa on
one run and rsa before ecdsa on the next.

A gate that compares something neither tool promises is not a strict gate; it
is a coin flip that happens to be green most of the time. So the comparison
is now over the **set of lines**, each byte for byte, and this client's own
order is asserted as the separate claim it is: it is sequential, so it always
prints in the order it requested the types in (rsa, ecdsa, ed25519 -- the
order of OpenSSH's own `keytypes` array, `KT_MIN..KT_MAX`).

### The note line's stream is not a contract either

The same reasoning applies one level down. The tool's "# host:port
SSH-2.0-..." note is a separate thing from the known_hosts lines, and **which
stream it lands on is a version detail of the real tool**: the installed 8.0p1
and 9.x builds put it on stderr, while OpenSSH 10.4's `congreet` writes it to
`stdout` (`fprintf(stdout, "%c %s:%d %s\n", ...)`). Comparing whole streams
would compare that detail as if it were the contract.

So the gate compares the known_hosts lines as a set, and compares the note
**wherever the tool put it**. This client's own layout -- known_hosts on
stdout, note on stderr -- is a claim of ours, and it is asserted separately.

What the two builds do **not** agree on is the default type list: 9.x also
scans the FIDO and ML-DSA types, so its stderr carries five comment lines
where 8.0p1's carries three. Its **stdout** carries the same three lines,
because the server does not have the other two keys -- and stdout is the
contract.

### What the gate proves

`host/verify_loop82.mjs`, 43 checks (2 build, 15 line rules, 16 against the real
tool and a real server, 6 about the server's own log, 4 regression):

* **G0. The code builds.** The gate runs a *prebuilt* binary, so a change to
  the protocol layer would not reach it unless the binary was rebuilt first.
* **G1. The line rules, byte for byte.** `cmd/keyscan_kat` prints the rules;
  `host/gen_keyscan_vectors.py` prints the same cases from a Python
  transcription of `put_host_port` and `lowercase`. Every line has to match,
  and the KAT has to produce the same bytes on **4 targets x 2 modes**.
* **G2. The output is the real tool's output.** The same known_hosts lines,
  byte for byte, as each installed `ssh-keyscan` (order apart, and the note
  wherever the tool puts it -- see above); the `-t ed25519` line and note
  identical too; the server's log showing one connection per key type with
  three different negotiated algorithms.
* **G3. The scan never authenticates.** The **server's own log** must contain
  no `userauth` for the scan -- and, to make that zero mean something, the
  gate then authenticates for real against the same server and shows the log
  *does* record userauth when a client really does it. A zero that would be
  zero anyway is not a measurement.

The gate also counts `SSH_MSG_SERVICE_REQUEST` packets in the server's log.
Asking for the `ssh-userauth` service sends no credentials, so "no userauth"
alone would not notice it -- but it is the step right before credentials go,
and a scan that took it would be one refactor away from taking the next one
too. That count is **conditional on a positive control**: the same marker must
appear for the client that does authenticate, or the check reports itself as
skipped rather than passing vacuously on a server that logs nothing.

`host/loop82_mutations.py` turns twelve of those checks red on purpose: the
line written with the negotiated algorithm name instead of the blob's type
name, the hosts field without its brackets, port 22 not treated as the default
port, port 0 not treated as the default port, the host name not lower-cased,
the composition skipping the lower-casing, the line with its fields in the
wrong order, all key types proposed in one connection, the key types scanned
in the wrong order, ed25519 preferred for every connection, the scan asking
for the `ssh-userauth` service as well, and the comment line naming the wrong
thing.

### The gaps this loop does not close

* **Host names do not resolve.** The native socket layer connects with
  `inet_pton(AF_INET)`, so it accepts **IPv4 literals only** -- `ssh-keyscan
  example.com` does not work, and neither does `ssh user@host`. This is
  pre-existing and project-wide, not something this loop introduced, but it is
  the first loop whose tool is *useless without* it. Measured, same server,
  same argument: ours prints `result: CONNECT_FAILED LOCALHOST:22303`, the
  real 8.0p1 prints `write (LOCALHOST): Connection refused` -- the real tool
  resolves the name and gets refused on the first address it tries (`::1`),
  ours never resolves it at all. This is the next thing to fix, and it belongs
  to `src/tcp`, not to the key scan.
* **The lower-casing cannot be observed end to end.** The only host this
  client can reach is a numeric literal, which has no letters to fold. The
  rule is therefore pinned as cases (`KEYFIELD K1..K3`, against the Python
  transcription) rather than by the byte comparison. It closes when host names
  resolve.
* **No exit code.** `core` and `async` have no `exit()`, and `moon.mod` is
  frozen, so the driver reports through `result:` lines instead. OpenSSH
  returns `found_one ? 0 : 1`; this tool currently exits 0 even when it found
  nothing, so a script cannot tell success from failure.
* **No `-H`** (write the host name hashed), and no `-F`/`-f` file options.
* **No FIDO and no ML-DSA.** OpenSSH 10.4's default type list includes them.
  This client does not scan them, because it cannot verify them, and writing
  an unverified key into known_hosts is worse than not writing it. The names
  that were dropped are all *after* the ones that were kept, so the key the
  server picks is the same one OpenSSH picks.
* **No IPv6.** The socket layer is AF_INET only, so `::1` is not reachable
  even though the line format for it (`[::1]:2222`) is pinned by a case.
* **The client's own TOFU path still writes the bare host name** for a
  non-standard port, unlike this tool's `put_host_port`. That is pre-existing
  behaviour; changing it would move the expected output of gates that already
  pass, so it is left for the loop that owns the TOFU path.

## Loop #83: host names resolve -- the transport stops being IPv4-only

### What was missing

`ssh user@example.com` and `ssh-keyscan example.com` are how anybody actually
uses an SSH client, and this repository could do neither. `src/tcp` connected
with `inet_pton(AF_INET)`, so it accepted **IPv4 literals only**: a name was
never turned into an address, and the connection never left the machine.

Loop #82's own gap ledger named this as the next thing to fix, and named it
precisely: "Host names do not resolve ... it belongs to `src/tcp`, not to the
key scan". So this loop is in `src/tcp`, and the key scan is where the
evidence comes from.

### The protocol, pinned from OpenSSH's source

* `ssh.c:resolve_host` -- `getaddrinfo(name, port, &hints)` with
  `hints.ai_family = AF_UNSPEC` (or `options.address_family`) and
  `hints.ai_socktype = SOCK_STREAM`. It returns a **list** of addresses, not
  one. `AI_CANONNAME` only when a CNAME was asked for.
* `sshconnect.c:ssh_connect_direct` -- the client's own connect loop: "Loop
  through addresses for this host, and try each one in sequence until the
  connection succeeds". Each address gets its own socket and its own timeout;
  a failure closes that socket and moves on to the next one.
* `misc.c:timeout_connect` -- a non-blocking connect, a wait for the socket,
  and then `getsockopt(SO_ERROR)`: `optval != 0` means the connect failed.

Two details that are easy to miss, and that the implementation follows:

* the timeout is **per address** -- `ssh_connect_direct` does
  `*timeout_ms = saved_timeout_ms` before *every* address it tries, so a name
  that resolves to three addresses gets three times the budget;
* a timeout of zero or less means "no deadline", and `timeout_connect` then
  does a plain blocking `connect()`.

### Windows does not report a refused connect the way POSIX does

This is the part that could not be written by analogy, so it was measured
(`.loop83/measure_socket.py`):

```
a non-blocking connect to a closed port:  connect_ex -> 10035 (in progress)
  t =  250 ms  readable=False writable=False except=False  SO_ERROR=0
  t = 2000 ms  readable=False writable=False except=False  SO_ERROR=0
  t = 2250 ms  readable=False writable=False except=True   SO_ERROR=10061
```

Two consequences, and both of them are in the implementation:

1. **A refused connect lands in the EXCEPT set, not in the write set.** On
   POSIX a failed connect makes `poll`/`select` report `POLLOUT`, and the
   reason is in `SO_ERROR`. On Windows the socket goes into the except set.
   An implementation that waits only for writability would sit there until
   the deadline on *every* refused connection, and never learn that the
   connection had already failed.
2. **The refusal is not visible straight away.** For about two seconds the
   socket is in neither set and `SO_ERROR` is still zero. A blocking connect
   to the same port takes about 2.0 s and returns `WSAECONNREFUSED`, so the
   two paths agree on the timing and differ only in who reports it.

So the implementation watches the write set **and** the except set, and reads
`SO_ERROR` *while* it waits rather than only after `select()` returns.

### The refusal latency depends on the socket, and that decides what can be tested

The same refusal, measured two ways on this machine:

```
a plain Winsock socket (ours, and Python's)   the refusal shows up after ~2.0 s
node's socket (libuv)                          the refusal shows up after ~0.001 s
```

Both numbers are real, and they are not measuring the same thing: node
creates its sockets with `WSA_FLAG_OVERLAPPED`, and an overlapped socket is
told about the failed connect through its completion path, which is prompt. A
plain socket does not see the error until the connect attempt has expired.

This mattered because the gate **calibrates itself**. A deadline shorter than
the refusal latency cannot see the refusal, so it has to report a timeout
instead -- and that difference is the only evidence that the deadline is
doing anything at all. The first version of the gate calibrated with node,
measured 2 ms, concluded "a timeout and a refusal are the same thing here",
and **skipped three checks** -- on a machine where the distinction plainly
exists. The calibration now runs `host/refusal_latency.py`, which measures it
with a plain socket, the way the implementation measures it.

The lesson is the one this repository keeps meeting: **a calibration has to
be taken with the same mechanism the thing under test uses**, or it calibrates
nothing. The first version of the gate was not wrong in what it asserted; it
was wrong in what it was able to assert -- and it said so loudly rather than
quietly, which is the only reason the hole was found.

### The deadline has to be measured against the clock, not accounted for

This one was found by GitHub Actions and not by the machine it was written on,
which is the whole point of the sentence.

The connect's deadline was **accounted for**: the wait loop added up the time
it had *asked* `select()` to wait for, and compared that total with the
budget. That is not the same thing as measuring how long the wait really
took. A wait comes back late whenever the machine is loaded, so an accounted
budget is spent at a fraction of the rate the clock runs.

On the idle machine where it was written, the two accounts agreed and the
gate was green. On the CI runner they did not: a `select()` asked to wait
100 ms took 276 ms, so a one-second budget ran out after 2.8 seconds, and the
two addresses a name resolved to took 5.5 seconds between them -- *later than
the refusal the deadline was supposed to beat*. The gate noticed, because it
compares the deadline-limited run against the run that waits out the refusal:

```
the deadline was honoured -- it finished before the refusal arrived
  on the runner:  5522 ms vs 4084 ms   FAIL
  here:           2042 ms vs 4093 ms   PASS
```

The fix is `GetTickCount64()`: the budget is charged against the wall clock,
in one place (`mb_budget_left`), so that "the deadline is measured against the
clock" is a single thing the mutation check can point at rather than
something spread across a loop.

Two things came out of it:

* **The wait slice went from 100 ms to 500 ms.** The slice is only a
  granularity limit -- `select()` returns the moment the socket is ready --
  so it decides how often the deadline is re-checked, not how long the wait
  lasts. A long slice means fewer `select()` calls, and a loaded machine
  makes each of those calls late, which is exactly what used to stretch the
  budget.
* **The gate's absolute bound is derived from the number of addresses.** The
  budget is per *address* (OpenSSH resets it before every address it tries),
  so a name that resolves to three addresses gets three budgets. A bound
  written for one address would fail on a name that resolves to more -- and
  the number of addresses is not the same on every machine, so it is read
  out of the run rather than assumed. The bound is deliberately loose; the
  two checks around it are the ones with teeth. The label says the deadline
  was honoured, and the comparison says it was honoured *earlier* than
  waiting out the refusal would have been.

The lesson is the one this repository keeps meeting, in a new shape: **a
deadline that is only *accounted for* is correct exactly as long as the
machine is idle.** Timing code that is never run under load is timing code
that has not been tested -- and the only place it got tested was a CI
runner that was busy with something else.

### What OpenSSH's own tools do with a name, measured

Against the same server, the same port and the same name, on this machine:

```
the real ssh client (9.x), -vv:
    debug1: Connecting to localhost [::1] port 60560.
    debug1: connect to address ::1 port 60560: Connection refused
    debug1: Connecting to localhost [127.0.0.1] port 60560.
    debug1: Connection established.

the real ssh-keyscan (8.0p1 and 9.x):
    write (localhost): Connection refused
```

So the two OpenSSH tools **differ**, and the difference is in their source:

* `sshconnect.c:ssh_connect_direct` loops over the addresses, and the real
  client therefore reaches the server through the second address. This
  client does the same thing, and the gate compares the two address lists
  element by element.
* `ssh-keyscan.c:tcpconnect` is a **different** function with a different
  shape: it breaks out of the address loop as soon as a `connect()` returns
  `EINPROGRESS`, handing the socket straight to the `select()` loop. A
  refusal that arrives *after* that hand-off is therefore never retried on
  the next address, and the scan dies at the banner write with
  `write (<host>): Connection refused`.

That difference is deliberate on OpenSSH's side and is **not** reproduced
here: this client resolves and tries every address, like OpenSSH's client
does. A scan of `localhost` therefore succeeds here and fails in OpenSSH's
own ssh-keyscan.

The gate **pins** that difference rather than leaving it in prose, because a
difference that is only written down is a difference the next loop will
"fix" by making this client match the weaker one. So the real ssh-keyscan is
run against the same name on the same server, and:

* when it produces known_hosts lines, they have to be **our** lines, byte for
  byte (the same claim Loop #82 makes for a numeric host, extended to names);
* when it produces none -- which is what both installed builds do here --
  its own message has to say why, because a tool that fails silently is a
  tool whose failure nobody can act on. Measured: `write (localhost):
  Connection refused`.

(The loop-82 gap ledger said "the real tool resolves the name and gets refused
on the first address it tries (`::1`)". That was measured against
**ssh-keyscan**, and it is right about ssh-keyscan. It is not right about
OpenSSH's `ssh` client, which falls back to the second address -- as the
transcript above shows.)

### What was built

* `src/tcp/winsock.c` -- `mb_tcp_connect_ex`: `getaddrinfo` with
  `AF_UNSPEC`/`SOCK_STREAM`, the address list in the resolver's order, and a
  per-address non-blocking connect with a deadline. It writes a **report**
  back: how many addresses the name resolved to, which one was reached, what
  happened to each of the others, and the system's own error code. The report
  layout is written out byte by byte in that file, because it crosses a
  language boundary where both sides have to agree on it exactly.
* `src/tcp/socket_common.mbt` -- `TcpFailure` (`ResolveFailed`,
  `ConnectFailed(code)`, `ConnectTimeout`), `ConnectReport`, and
  `TcpConn::connect_with_timeout(host, port, timeout_ms)`.
  `TcpConn::connect(host, port)` keeps its old shape and now resolves too --
  it is the same call with no deadline, which is what OpenSSH does when no
  `ConnectTimeout` is given.
* `cmd/ssh_keyscan` -- `-T <seconds>` (OpenSSH's flag, and OpenSSH's rule
  that a zero timeout is invalid) and `-v`, which prints the resolution and
  what happened to each address. `-v` is silent by default, because
  OpenSSH's ssh-keyscan prints no addresses either.
* `host/refusal_latency.py` -- the calibration oracle: how long a refused
  connection takes to become visible, measured with a **plain** socket, the
  way the implementation measures it. It is a separate file rather than a
  few lines inside the gate because it is the one measurement whose method
  matters, and it has to be readable on its own.

### The failures are three different names

```
result: RESOLVE_FAILED  no-such-host.invalid:22302   (the name does not resolve)
result: CONNECT_FAILED  localhost:22302               (it does not listen)  error: 10061
result: CONNECT_TIMEOUT localhost:22302               (the deadline ran out)
```

The same closed port produces two different labels depending on whether the
deadline was long enough to see the refusal -- which is what makes the
deadline itself testable, and what a single "connect failed" would have
hidden.

### What the gate proves

`host/verify_loop83.mjs`, 50 checks (45 of its own, 5 regression -- the gates
of Loop #78 to #82):

* **G0. The code builds**, for native and for the whole tree (the js and wasm
  backends answer for the browser targets, so the resolution code is shared
  and has to type-check everywhere).
* **G1. A name reaches the server.** The same scan by name and by number must
  produce the same three keys -- only the hosts field differs -- and the
  **server's own log** must show three more connections, all of them from
  127.0.0.1. A name in upper case is lower-cased in the hosts field and
  keeps its case in the note, which is how Loop #82's "the lower-casing
  cannot be observed end to end" gap closes: a numeric literal has no letters
  to fold, and a name has letters.
* **G1b. Every address is tried, in order.** Every resolved address was
  tried, exactly one of them was reached, and the address that was reached
  is the one the tool reports.
* **G2. The failures are told apart.** A name that does not resolve says
  `RESOLVE_FAILED` and fails fast; a refused connection says
  `CONNECT_FAILED` and carries the system's own code (10061); a deadline
  shorter than the refusal says `CONNECT_TIMEOUT`; and a zero timeout is a
  usage error, as it is in OpenSSH.
* **G3. The same addresses as OpenSSH's own client.** The oracle is OpenSSH's
  `ssh -vv`, whose debug output names every address it tries. The lists have
  to agree element by element, and the client has to have reached the server
  -- otherwise the comparison would be vacuous.
* **G3b. The real ssh-keyscan, on the same name.** When it produces keys,
  they have to be our keys, byte for byte; when it produces none, its own
  message has to say why. See above -- this is the check that pins the
  documented difference between the two OpenSSH tools.
* **G4. The numeric path did not move.** A number still resolves to itself,
  is still reached on the first try, and is still fast.

### The claims that are about this machine, and the ones that are about the code

"localhost" is not a fixed fact. On this machine it resolves to `::1` first
and `127.0.0.1` second -- but that comes from the Windows DNS client, not
from the hosts file: the hosts file here has its localhost lines commented
out ("localhost name resolution is handled within DNS itself"). A machine
whose resolver handed back only `127.0.0.1` would be just as correct, and a
gate that insisted on `::1` would be red on it for saying something true.

So the gate runs OpenSSH's own client **first**, and its answer decides which
claims are about this machine and which are about the code. The portable
claim -- "we pick the same addresses, in the same order, as OpenSSH's own
client" -- is asserted unconditionally. The claims about the particular pair
(`::1` first, `127.0.0.1` second, the first refused and the second
connected) are asserted only when the oracle shows that pair, and are
**skipped loudly** otherwise. A gate that hard-codes a machine's resolver
answer is a gate that will be red on somebody else's machine for no reason.

The timing claims are machine claims too, and they are handled the same way.
A deadline shorter than the refusal latency can only report a timeout if the
refusal really is that slow here, so the gate **measures** the latency first
(`host/refusal_latency.py`, with the same kind of socket the implementation
uses) and skips the deadline checks loudly when the machine is too fast for
the distinction to exist. What is left is the part that is about the code: a
deadline has to make the wait *shorter*, and it has to be measured against the
clock rather than accounted for -- the defect GitHub Actions found, and the
one an idle machine cannot see.


`host/loop83_mutations.py` turns twelve of those checks red on purpose: IPv6
addresses dropped from the resolved list, only the first address tried, the
addresses tried in the opposite order, the port lost during the resolution,
a refused connect never noticed, the error code of a failed connect lost, the
address that was reached misreported, a name that does not resolve reported
as a connect failure, a timeout reported as a connect failure, the deadline
the caller asked for ignored, a timeout of zero accepted, and the deadline
charged against something other than the wall clock.

The last one is the mutation for the defect GitHub Actions found, and it
works the way that defect worked: it charges the budget at a third of the
rate the clock runs, so the deadline arrives *later* than it should -- late
enough that the refusal is seen first, and the run reports a refusal where
the caller asked for a timeout.

### One of the mutations was equivalent, and that is worth knowing

The first list had a mutation that removed **only** the watch on `select()`'s
except set -- and it did not turn anything red. The reason is that this code
notices a refused connect **twice**, independently: the socket shows up in the
except set, and `SO_ERROR` is also polled while the wait goes on. Both report
the refusal at the same moment (measured: ~2.0 s for both), so either one
alone is enough.

That is not a hole in the gate; it is a redundancy in the implementation, and
it is worth recording rather than hiding: the mutation now removes **both**
mechanisms at once, and that one does turn the gate red. A mutation that
cannot fail is not evidence, and an equivalent mutant is not a defect -- but
it is a fact about the code, and the fact is that the refusal is noticed even
if one of the two ways of noticing it is removed.

### A mutation run that is killed leaves the tree mutated

The mutation runner restores the tree in a `finally` block -- which a killed
process never reaches. Stopping one mid-batch (here, because its anchor had
drifted and the run was going to be repeated anyway) left `src/tcp/winsock.c`
holding a mutation, and the next build compiled it as if it were the code.

The runner now writes the pristine state to disk before it changes anything
and a run that finds its predecessor's leftovers puts them back before it
starts, loudly. The lesson is the general one: **a checker that mutates the
tree under test has to survive being stopped**, and "it restores in a
`finally`" is not the same as "it restores".

### The gaps this loop does not close

* **The client's own failure label is still flat.** `cmd/ssh_live` says
  `result: CONNECT_FAILED` for every way a connect can fail, while
  `cmd/ssh_keyscan` now says which one it was. `ssh_live` **gains** name
  resolution from this loop -- its `TcpConn::connect` resolves now -- but its
  label was not split, because that label is asserted by gates from earlier
  loops and moving it changes those gates' expectations rather than this
  loop's subject. It belongs to the loop that owns the client's own output.
* **No `ConnectTimeout` for the ordinary client.** `TcpConn::connect` has no
  deadline (0 means "no deadline", like OpenSSH with no `ConnectTimeout`), and
  `cmd/ssh_live` does not expose one. The transport can do it; the driver
  does not ask for it yet.
* **The deadline is per address, and OpenSSH's ssh-keyscan makes it global.**
  The per-address budget is OpenSSH's *client* arrangement
  (`ssh_connect_direct` resets the timeout before every address), and that is
  what the transport does. But `ssh-keyscan.c` has one `timeout = 5` for the
  whole scan, so `-T 5` here can mean five seconds *per address* -- fifteen
  for a name with three addresses. The two tools answer the same question
  with different budgets, and a user who expects ssh-keyscan's behaviour
  waits longer here than there.
* **No canonical name.** OpenSSH's `resolve_canonicalize` can replace the
  host with its canonical name (and follow CNAMEs) when
  `CanonicalizeHostname` is set. This client resolves and connects, but keeps
  the name as it was typed -- which is also what the known_hosts line has to
  carry.
* **No `AddressFamily` option.** `AF_UNSPEC` is fixed, so both stacks are
  always tried. OpenSSH lets the user pick one.
* **The browser path still cannot resolve.** `src/tcp`'s js and wasm backends
  are stubs that report failure, and the browser transport is `src/wtlive`'s
  WebTransport, which resolves inside the browser. Nothing here changes that.
* **Loop #82's "no IPv6" gap is now closed.** It said "the socket layer is
  AF_INET only, so `::1` is not reachable". `::1` is reachable now, and
  `localhost` resolves to it first -- it is simply refused on this machine,
  because the test server listens on 127.0.0.1 only.
* **Loop #82's "the lower-casing cannot be observed end to end" gap is now
  closed.** A name in upper case is scanned by name, the known_hosts line
  comes out lower-cased, and the note keeps the case it was typed in.

---

## Loop #84: the client has a random source -- the secrets stop being constants

### What was missing

Before this loop the client had **no entropy at all**.  Two values that should
never be the same twice were the same every single time:

* the KEXINIT cookie was the fixed 16-byte array `A0 A1 .. AF`
  (`sshclient.fixed_cookie`);
* the Diffie-Hellman private exponent was a fixed 32-byte constant
  (`5A17C39E .. 87B1E`), and **three drivers each carried their own copy of
  it** -- `cmd/ssh_live`, `cmd/ssh_keyscan` and `cmd/wt_ssh`.

Two consequences, and the second one is the serious one:

1. every transcript this client produced started with the same sixteen bytes;
2. a DH exchange with a known private exponent has **no forward secrecy at
   all**.  The shared secret is `f^x mod p` for an `x` that is in the source
   code, so anybody with the repository can recompute it from a recorded
   exchange.  The whole point of a DH key exchange is that `x` is secret.

### The practice, pinned from OpenSSH's source

* `kex.c:598` -- `arc4random_buf(cookie, KEX_COOKIE_LEN)`
* `kexc25519.c:54` -- `arc4random_buf(key, CURVE25519_SIZE)`
* `dh.c:303` -- `DH_generate_key(dh)`, which is OpenSSL, whose randomness
  comes from the platform
* `dh.c:300` -- `DH_set_length(dh, MINIMUM(need * 2, pbits - 1))`
* `kexdh.c:67` -- `dh_gen_key(kex->dh, kex->we_need * 8)`

OpenSSH draws both from the platform CSPRNG and never reuses either.  The
doubling in `dh.c:300` is there because Pollard rho and the big-step/little-step
attacks are O(sqrt(n)), and the length it ends up with is what OpenSSL's
`BN_priv_rand(..., BN_RAND_TOP_ONE, BN_RAND_TOP_ONE, ...)` then fills in: the
top TWO bits set, so the key really has the length that was asked for, and the
bottom bit set, so the key is odd.

### `src/rng`: one platform call per request, no state, no seed

The new package is a thin wrapper and nothing else:

* **native** -- `BCryptGenRandom(NULL, buf, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG)`.
  A NULL algorithm handle asks for the primary provider, which is the same
  generator the system uses for its own keys.
* **js** -- the Web Crypto API's `crypto.getRandomValues`.  It refuses a view
  longer than 65536 bytes, so a long request is filled in chunks, and
  `subarray` gives a view on the SAME buffer so the chunks land where the
  first one would have.  Measured, not assumed: a MoonBit `Bytes` reaches JS
  as a `Uint8Array`, and `getRandomValues` fills it in place.
* **wasm** -- **there is no entropy source**, so the backend says so.

It holds no state and no seed, and it makes one platform call per request,
exactly like `arc4random_buf`.  A seeded generator whose seed lives in the
binary is not a CSPRNG, and a package whose whole job is to be one is not the
place where that mistake should hide.

### A failure is reported, and never papered over with zeros

`bytes(n)` aborts when the platform call fails.  OpenSSH's `arc4random_buf`
aborts too, and the reason is the same: a caller handed zeros would use them
as a secret, and **a zero key is not a key**.

This is the one claim in this loop that nothing about the *successful* path
can check, so it is checked from the outside -- see "A unit test cannot watch
an abort" below.

### The exponent: 2047 bits, the top two bits set, odd

`src/kexdh/privkey.mbt` draws `pbits - 1` bits -- 2047 for group 14 -- which
is the largest length the group allows and is the length OpenSSH ends up with
for the largest `need`.

* Why `pbits - 1` rather than `pbits`: the exponent has to be smaller than
  the prime, and the prime has `pbits` bits, so a value with `pbits - 1` bits
  is below 2^(pbits-1) and therefore below the prime.  That is a GUARANTEE,
  not a rejection loop, so the distribution of the exponent is not skewed by
  filtering.
* Why the top two bits and the low bit: OpenSSL's `BN_RAND_TOP_ONE` twice and
  once, which is what makes Pollard rho cost O(sqrt(n)) over the whole
  exponent rather than half of it.

The difference from OpenSSH's rule (`MINIMUM(need * 2, pbits - 1)`) is that
this client does not know `we_need` before it negotiates, and takes the
maximum instead.  The maximum is never weaker than OpenSSH's rule; it costs a
few hundred extra squarings in a modexp that takes milliseconds.

### The one exception, and why it exists

The cookie is **always** random: nothing needs it to be reproducible, because
the transcript oracle reads it off the wire.

The exponent has **one** documented exception.  `host/transcript_check.py`
recomputes the exchange hash in Python from the bytes on the wire, and to do
that it needs the shared secret, and to get the shared secret it needs the
client's private exponent -- which it cannot learn from the wire, because
recovering it from `e = g^x mod p` is the discrete logarithm.  So the oracle
asks for the known exponent by name:

* `cmd/ssh_live --fixed-kex`
* `cmd/wt_ssh` with `cfg("fixed_kex") == "1"`

That is a testing premise, not a production one: a client that used the fixed
exponent in anger would have no forward secrecy, which is the very thing this
loop exists to remove.  `host/verify_loop31.mjs` now passes
`--client-arg=--fixed-kex` to the oracle, which it has to -- without that the
oracle computes an exchange hash over a secret it does not have.

### What the wire actually carries (measured)

The DH public value `e = g^x mod p` goes on the wire as an SSH mpint, and its
**length is not constant**.  Measured over 20000 draws:

```
257 bytes   49.80 %
256 bytes   50.01 %
255 bytes    0.19 %
```

(The first guess -- that `e` would always be 256 bytes -- was wrong, and the
number theory behind it was wrong too: the QR subgroup's elements are spread
over the whole of `[1, p-1]`, not over the top half of it.)  It does not
matter for the byte counts the gates pin: SSH's padding rounds every packet
up to a multiple of the cipher block size, and all three lengths land on the
same padded total, so `sent_bytes: 541` and `recv_bytes: 737` are stable.

### How the gate checks randomness without checking randomness

A gate cannot check randomness by looking at it -- that is what randomness is.
What it can check is the contract a CSPRNG *wrapper* can be wrong about, and
the observable difference between two runs:

| claim | how it is checked |
|---|---|
| the length asked for is the length delivered | `src/rng`'s five contract tests |
| two calls are not the same bytes | the same tests, and `cmd/rng_probe` |
| the output is not all zeros | the same tests |
| the WHOLE buffer was written | the SECOND HALF is not all zeros |
| the cookie is fresh | two connections, two cookies, off the wire |
| the exponent is fresh | two connections, two `e`, off the wire |
| neither is the old constant | the same, against a value computed in Python |
| the escape hatch still reproduces the old value | byte-for-byte equality with `pow(g, FIXED_X, p)` computed in Python |
| the browser draws entropy too | a real Chromium Web Worker |
| the target with no entropy source says so | a wasm build that PANICS |

The oracle is `host/loop84_peek.py`: a MITM tee in front of a real sshd, with
the SSH packet parser **imported** from `host/transcript_check.py` rather
than copied, so the two cannot drift apart.  It prints the client's cookie and
`e`, and the value the OLD constant exponent would have produced -- computed
in Python from the group 14 prime, not read out of the repository.

### A test file has to be gated by the target its contract can hold on

The first version of `src/rng`'s test file was compiled on every target, and
the wasm run failed 4/4 -- correctly, because the wasm backend has no entropy
source and the draw aborts.  That was the right behaviour and the wrong
shape: it made `moon test src/rng` red on the default target, and the default
target is **not** native (`moon test src/rng` failed while
`moon test src/rng --target native` passed).

So the test files are gated per target, the same way the backends are:

* `src/rng/rng_test.mbt` -- the five contract tests, compiled on native and js;
* `src/rng/rng_wasm_wbtest.mbt` -- one test, compiled on wasm and wasm-gc: the
  backend reports failure, and it did not touch the buffer on its way to
  failing.

A **white-box** test (`*_wbtest.mbt`) is what can see a private function: a
black-box test file is compiled into its own package and can only see `pub`
items, so `mb_rng_fill` was "unbound" until the file was renamed.

### The SHAPING has to be separable from the DRAW, or the test cannot be instrumented

The exponent's contract is about its SIZE and its SHAPE -- 2047 bits, the top
two set, odd -- and the first version of the test asserted it on a real draw,
which means the test needed an entropy source, which means the test file had
to be compiled only where there is one.

That is where the coverage tool stopped talking about `src/kexdh`.
`moon coverage analyze` has no `--target` flag, so it runs at the DEFAULT
target, and a package whose only test driver does not compile there produces

```
error: coverage runtime data does not match the selected source files
```

-- which is a package that has tests and can no longer be measured.  The
refreshing of `host/cov_reportable.json` put `src/kexdh` in the
not-reportable list, and it would have stayed there for a reason that was
entirely this loop's own doing.

So the SHAPING is separated from the DRAW:

* `private_exponent_bytes(pbits)` -- how many bytes a group of `pbits` bits
  draws from;
* `exponent_from_bytes(bytes)` -- the pure shaping: the top byte's high bit
  cleared, the top two bits below it set, the bottom byte's low bit set;
* `dh_private_exponent(pbits)` -- draw, then shape.

The shape is then testable on FIXED bytes, with no entropy source at all, so
the test file compiles and passes on every target -- native, js, wasm and
wasm-gc -- and the coverage tool can instrument the package again.

The general lesson: **a test that needs an entropy source is a test that
cannot be instrumented at the default target**, and the way out is not to
gate the test file but to split the function so that the part worth asserting
does not need the random part.

### A unit test cannot watch an abort, so the abort is watched from outside

Nothing in a MoonBit test can observe an `abort` from the inside.  So the
"the failure stops the client" half of the contract is observed from the
outside, by a wasm build of `cmd/wasm_rng_probe` run under
`host/node_host.mjs`:

```
wasm_rng_probe: start
Runtime error: unreachable          <- exit code 3
```

The gate requires exit code 3 and **no** second line.  A build that turned the
failure into bytes would print `wasm_rng_probe: got 32` and exit 0, and the
gate would see it.

### The assertion that was pointed the wrong way

The mutation suite found a real defect in the gate itself, and it is worth
writing down because the mistake is a natural one.

The contract test for "the whole buffer was written" compared the two halves
of a 4096-byte draw and required them to be **different**, and its comment
said: "an implementation that filled only the first half would leave two
identical halves".  **That is false.**  A half-filled buffer has a RANDOM
first half and a ZERO second half, and those two are different -- so the
assertion passed on exactly the implementation it was supposed to catch.

The mutation "only half of the requested buffer is filled" was MISSED, and the
fix is the other direction: the **second half must not be all zeros**.  An
implementation that filled only the first half leaves the second half exactly
as it found it, and a real CSPRNG output's second half is all zeros with
probability 2^-16384.

The general lesson is the one this repository keeps learning: **a structural
assertion has to be checked against the mistake it is supposed to catch.**
Comparing the two halves catches "the buffer holds one constant"; it does not
catch "the buffer holds half of one".  Both assertions are now there, and they
say which mistake each one is for.

### A mutation run that is killed leaves the tree mutated (again)

This happened a second time in this loop, and the backup mechanism that
Loop #83 added is what stopped it from becoming a mystery.

The mutation runner was stopped in the middle of the batch (its anchor for the
"the exponent may be even" mutation had drifted, and the run was going to be
repeated anyway).  The runner restores the tree in a `finally` block, which a
killed process never reaches, so `src/kexdh/privkey.mbt` was left holding the
mutation `bytes[nbytes - 1] = (last & 0xFEUL).to_byte()` -- an exponent that
may be even.

The symptom was not a compile error.  It was `moon test src/kexdh` reporting
`3/4 passed` on a test that had passed a minute earlier, with the failing
test named `the_private_exponent_is_odd` -- which is exactly the mutation
that had been left behind.  The runner's next start printed

```
RESTORED  a previous run was interrupted; put back: src\rng\api.mbt, ...
```

and the tree was whole again.

Two things are worth saying about that:

* **the mechanism worked**, and it worked from a plain `import` of the
  runner's own `restore_leftovers()` -- it is a function with a job, not a
  habit;
* **the symptom pointed straight at the cause.**  "The oddness test fails" is
  not a mystery when the mutation that makes the exponent even is the last
  thing that ran.  A structural test that names the property it protects is
  also a test that names the defect when the property is broken.

### The mutation suite, in full

| # | the defect | the check that catches it |
|---|---|---|
| 0 | the wrapper returns a constant instead of the platform's bytes | two draws are not the same bytes |
| 1 | a platform failure becomes zeros instead of stopping the client | the wasm draw PANICS instead of returning bytes |
| 2 | only half of the requested buffer is filled | the WHOLE 4096-byte buffer was written |
| 3 | the native backend always reports failure | native: every contract test passes |
| 4 | the js backend fills the buffer with a constant | js: every contract test passes |
| 5 | the wasm backend pretends to have an entropy source | wasm: the one test that can hold there passes |
| 6 | the private exponent is half the group's size | the exponent keeps the group's size and shape |
| 7 | the private exponent does not have its top two bits set | the exponent keeps the group's size and shape |
| 8 | the private exponent may be even | the exponent keeps the group's size and shape |
| 9 | the client falls back to the fixed DH exponent | the two DH public values are different |
| 10 | the client falls back to the fixed KEXINIT cookie | the two cookies are different |
| 11 | `--fixed-kex` is accepted and ignored | the fixed-KEX DH public value is the old constant's |

All twelve turn the gate red.

### The mutation anchors drifted, and that is what the anchor rule is for

The first run of the suite reported ten CAUGHT and two SKIPped, and the two
SKIPs were **not** defects in the code -- they were anchors that had
drifted:

* the wasm backend's anchor was written with semicolons (`ignore(buf);`)
  and MoonBit has none (`ignore(buf)`);
* the `--fixed-kex` anchor was written with parentheses around the condition
  (`if (argv[i] == "--fixed-kex")`) and MoonBit has none either
  (`if argv[i] == "--fixed-kex"`).

A drifted anchor is reported as SKIP and counted as "not caught", and that is
exactly right: a mutation that cannot be applied proves nothing about the
gate, and counting it as caught would be a lie about the gate's teeth.  The
fix is to copy the anchor **out of the file**, not to write it from memory.

And `moon fmt` moved them a second time: it rewrites `if (x != 0) {` into
`if x != 0 {`, so an anchor that contains the parenthesised form stops
matching as soon as the file is formatted.  The rule this repository already
has -- **run `moon fmt` first, then re-check the anchors** -- is not a
formality; it is the only thing that catches this, and it caught it twice in
this loop.

### The formatter has an opinion about doc comments, and it is not yours

`///|` on *every* line of a paragraph is read by `moon fmt` as the start of a
new doc-comment block on every line, and the formatter then separates them
with blank lines -- a wall of one-line paragraphs.  The repository's
canonical form is:

```
///|
/// Multi-precision unsigned natural (limbs little-endian, limbs[0] = LSB)
pub struct BigNat {
```

i.e. the `|` marker alone on the first line, and the body as plain `///`
lines with no blank lines between them.  Writing the comment in that form
from the start avoids the round trip entirely.

### A new package with tests is a red gate until the coverage evidence is refreshed

`host/verify_loop68.mjs` re-derives the set of packages the toolchain can
produce a coverage report for, and compares it against the committed
measurement in `host/cov_reportable.json`.  A package that BECOMES
reportable is a red gate until that file is refreshed -- and `src/rng` became
one in this loop, because it has test files.

The refresh is

```
python host/cov_probe.py --json host/cov_reportable.json
```

and it has to be that script rather than a hand edit.  The file is a
MEASUREMENT: a row in it says "a run of this script produced a report for
this package".  Editing the list by hand would make the file claim something
that was never measured, which is the same class of failure as the committed
one, in the other direction.

### The gaps this loop does not close

* **The wasm targets have no entropy source at all.**  The client cannot run
  there: the browser path is the js target, where the Web Crypto API is
  there, and the wasm targets are compile-only in this repository.  A real
  wasm deployment would need the host to provide an entropy import, and
  nothing here provides one.
* **curve25519 is not implemented.**  OpenSSH's modern default is
  `curve25519-sha256` (`kexc25519.c:54`), and this client still negotiates
  `diffie-hellman-group14-sha256` only.  The exponent rule in
  `src/kexdh/privkey.mbt` is the DH one and does not carry over.
* **The exponent length rule differs from OpenSSH's.**  This client takes the
  group's maximum; OpenSSH takes `MINIMUM(need * 2, pbits - 1)`, where `need`
  is known only after the negotiation.  The maximum is never weaker, and it
  is a few hundred extra squarings.
* **`src/rng` is used for exactly two things so far**: the KEXINIT cookie and
  the DH private exponent.  Everything else the client derives -- the session
  id, the exchange hash, the traffic keys -- comes from the shared secret, so
  it inherits the randomness of the exponent.  A future ed25519 key, a
  hostbased salt or a password challenge would need `src/rng` too.
* **`--fixed-kex` is on `cmd/ssh_live` only.**  `cmd/wt_ssh` has the same
  escape hatch (`cfg("fixed_kex")`), and no gate sets it: the browser path
  has no oracle that needs a known exponent.
* **No `ssh-keygen`.**  The client can USE a key, but there is nothing here
  that generates one, and a generated key needs `src/rng` as well.
* **`src/rng` has no audit of what it does NOT cover.**  A package that is
  "the random source" tends to accumulate callers, and every one of them
  should be checked for "is this actually a secret".  There is no such list
  yet.

---

## Loop #85: ssh-keygen -- the client can MAKE a key

### What was missing

Loop #84 closed a gap it named in its own list: "**No `ssh-keygen`.**  The
client can USE a key, but there is nothing here that generates one."

That is a bigger gap than it looks.  A client that can only be handed a key is
a client that cannot be used by anybody who does not already have one, and the
file that holds a key is a **published format** -- so the thing that is missing
is not only a command but a second implementation of OpenSSH's file format,
written by nobody, checked by nobody.

Two things made it possible to do it right:

* `src/rng` (Loop #84) is the entropy source a key needs.  A key is a secret,
  and a secret needs somewhere to come from that is not a constant in the
  source code.
* OpenSSH itself is on this machine, in two builds.  So the oracle for "is
  this file the file OpenSSH writes" is not another implementation of the same
  idea -- it is **the program that everybody else has to read**.

### The format, pinned from OpenSSH's source

`openssh-key-v1`, the format OpenSSH has written since 7.8:

```
"openssh-key-v1\0"        15 bytes
cstring  ciphername      "none"
cstring  kdfname         "none"
string   kdfoptions      empty
uint32   number of keys  1
string   publickey blob  51 bytes
string   encrypted       144 bytes
```

and inside the last field:

```
uint32   check           the same random word, twice
uint32   check
string   "ssh-ed25519"
string   <32 bytes of public key>
string   <64 bytes of secret key>
string   <the comment>
padding  1, 2, 3, ...    up to the cipher's block size
```

The sources:

* `sshkey.c:72` -- `AUTH_MAGIC` is `"openssh-key-v1"`, and it is written with
  `sizeof(AUTH_MAGIC)`, so **the NUL terminator is part of the bytes on the
  wire**.  Fifteen bytes, not fourteen.
* `sshkey.c:2832` -- `sshkey_private_to_blob2`; the header fields are at
  `sshkey.c:2891-2898` and the check words, the key, the comment and the
  padding at `sshkey.c:2903-2918` (the padding is `++i & 0xff`, i.e. 1, 2, 3,
  ... in order).
* `sshkey.c:2935-2937` -- the PEM assembly.
* `sshbuf-misc.c:128` -- `sshbuf_dtob64` with `wrap=1`, which breaks the line
  after every **70** characters; `sshbuf-misc.c:222` removes the padding for
  the `authorized_keys` form.
* `ssh-ed25519.c:81-88` -- `ssh_ed25519_generate` calls
  `crypto_sign_ed25519_keypair`, and the secret key is **64 bytes**: the
  32-byte seed followed by the 32-byte public key.  That is `ED25519_SK_SZ`,
  and it is the same layout RFC 8032 uses for the expanded secret key -- so
  `src/ed25519`'s `keypair_from_seed` already returns exactly what the file
  wants, and nothing has to be re-derived.
* `authfile.c:82` -- `sshkey_perm_ok`, which is why the permissions below are
  not a nicety.

### A `cstring` and a `string` are the SAME wire form

This is the trap in the format, and it is worth writing down because the
natural reading is wrong:

> a `cstring` in OpenSSH means "a string whose contents contain no NUL" --
> it does **NOT** mean "a NUL-terminated string".

Both are a uint32 length followed by the bytes.  Reading "cstring" as
"NUL-terminated" puts one extra byte after every string field, and the file
comes out 244 bytes instead of 242 and **no reader accepts it** -- not
OpenSSH's, not ours.

The file is 242 bytes, and the arithmetic says so before a single byte is
written:

```
15 (magic) + 8 ("none") + 8 ("none") + 4 (empty options) + 4 (one key)
  + (4 + 51) (public blob) + (4 + 144) (private block) = 242
```

where 51 = 15 + 36 for `ssh-ed25519` plus the 32-byte key, and 144 is the
private block padded up to the "none" cipher's block size of 8.

### The three packages

* **`src/keyfile`** -- the format, and nothing else.  It knows how to write a
  file, how to read one back, and how to derive a key pair from a seed.  It
  draws nothing on its own except through `src/rng`.
* **`src/keyperm`** -- making the file private.  On Windows there are no POSIX
  mode bits, so the mode is the ACL, and the ACL has to be replaced rather
  than inherited.
* **`cmd/ssh_keygen`** -- the driver.  `-f`, `-t`, `-C`, `-N`, `-q`.

The split is deliberate: the format is pure and testable byte for byte on
every target, while the drawing lives in `generate_ed25519` and is exercised
by the gate instead.

### A passphrase is refused, not ignored

`-N secret` is an **error**, and no file is written.

A tool that accepts `-N secret` and writes an UNENCRYPTED key is a way to lose
a secret quietly, and the whole point of this file is that the secret really is
protected.  The same reasoning applies to the private key that is already
there: it is written with `CreateNew`, so an existing key is **never silently
replaced**.

Both refusals are checked by the gate, and the second one is checked by the
bytes on disk rather than by a message, because a message is what a tool prints
on its way to doing the thing anyway.

### Making the file private on Windows (six attempts, and what each one cost)

A file created on Windows inherits the ACL of its directory, and in an ordinary
user directory that ACL lets "Authenticated Users" read it.  OpenSSH then
refuses the key with "Permissions for '...' are too open", so **a key file that
is not private is not a key file**.

The attempts, in order, because the failures are the interesting part:

1. `SetEntriesInAclW` + `EXPLICIT_ACCESS_W` -- **crash**.
2. `SetEntriesInAclA` + `EXPLICIT_ACCESS` -- **crash** as well.
3. The root cause of both: the owner SID was taken with
   `GetSecurityDescriptorOwner` from the **self-relative** security descriptor
   that `GetNamedSecurityInfoW` returns.  In a self-relative descriptor the
   owner pointer is an *offset into the descriptor*, not a separate allocation,
   and handing it to an API that frees it corrupts the heap.  The fix is
   `GetNamedSecurityInfoW`'s **owner output parameter**, which is the API's own
   correctly-scoped pointer.
4. `SetSecurityInfo` with a self-relative DACL -- returns **-5**: the two
   forms are not interchangeable.
5. `MakeAbsoluteSecurityDescriptor` -- **LNK2019**: it is not in `advapi32`.
6. What works: `ConvertStringSecurityDescriptorToSecurityDescriptorW` to build
   the whole descriptor from an **SDDL** string, and `SetFileSecurityW` to
   install it.  The SDDL's `P` is what protects the DACL from inheriting the
   parent's permissions back:

   ```
   D:P(A;;FA;;;<owner sid>)
   ```

   The SDDL is used because the alternative -- assembling the
   `ACL_REVISION` / `ACCESS_ALLOWED_ACE` bytes by hand -- is exactly the kind
   of thing that reads past the end of a SID and crashes, and a crash in a
   function whose job is to protect a secret is a bad way to spend an
   afternoon.

`PROTECTED_DACL_INHERIT` is spelled out as `0x80000000` in `keyperm.c`, because
the SDK header that declares it is not reachable from this build; the value is
fixed by the API.

**The failure is reported.**  `src/keyperm` returns a negative stage code and
the driver says so and stops.  On the js and wasm targets there is no way to
protect a file, so `protect` returns -1 there rather than pretending.

### The gate's oracle is OpenSSH itself

`host/verify_loop85.mjs` is the first gate in this repository whose judge is
not another implementation of the same idea but the real thing:

| section | what it checks |
|---|---|
| G0 | `src/keyfile` compiles and its tests pass on native, js, wasm and wasm-gc |
| G0b | a real `ssh-keygen` exists (both builds, when both are here) |
| G1 | our file has the shape OpenSSH's writer produces: the same magic, the same field lengths, the same 242 bytes, and our private file embeds the public key from our own `.pub` |
| G2 | OpenSSH reads our private key and derives **the public key we wrote** |
| G3 | the private key file is private: OpenSSH does not complain, and the ACL says so on its own |
| G4 | the tool refuses a passphrase, refuses another key type, and refuses to overwrite an existing key |
| G5 | two keys are different, and the public key in the file is the public key of the secret key in the file |

The two-way check in G2 is the one that matters: `ssh-keygen -y -f <our
private>` has to succeed **and** print the public key that is in our `.pub`
file, byte for byte.  That is two claims in one: the file is parseable by
OpenSSH, and the key it holds is the key we say it is.

### The first run of the gate found four defects, and all four were in the gate

The gate's first run was red in twelve places -- the four test-assertion
checks (one per target), the seven shape checks that compare our file with a
reference file, and the fingerprint check -- and **every one of the failures
was a bug in the gate rather than in the code**.  After the first three fixes
it was 53/55, and the two that were left were the last two defects.  They
are worth writing down, because the first two are the kind of thing that
looks like a failure of the thing being tested.

1. **The test-output regex had the wrong groups.**  `moon test` prints
   `Total tests: 8, passed: 8, failed: 0`, and the regex
   `Total tests:\s*(\d+),\s*passed:\s*(\d+),\s*failed:\s*(\d+)` gives
   **m[1] = total, m[2] = passed, m[3] = failed**.  The code compared **m[2]**
   (which is `passed`) against 0 and **m[1]** (which is `total`) against `> 0`,
   so all four targets FAILED while the detail line printed "8/8 passed".
2. **`-N '""'` is not an empty passphrase on Windows.**  OpenSSH took the two
   quote characters *as* the passphrase and wrote an **aes256-ctr + bcrypt**
   file of 274 bytes -- a completely different format from the one under test,
   and seven of the shape checks failed because of it.  The call has to be a
   **real empty argument**, and the repository already had the precedent
   (`host/gen_loop53_fixtures.mjs:136-138`: "-N '' has to be a real empty
   argument").
3. **The fingerprint helper read the wrong field.**  `fingerprint()` took
   `r.status` from the object `keygen()` returns -- and that object has
   `code`, not `status` -- so the exit code was `undefined`, the check failed,
   and the fingerprint next to it was **correct**.
4. **A structural check was comparing bytes where only lengths are
   comparable.**  "our blob's key count and public blob have the same length"
   compared the bytes of the range that holds the public key blob -- and the
   two files are made by **different writers with different seeds**, so their
   public keys differ by construction and that comparison could never pass.
   It now compares the length fields, and a stronger check was added next to
   it: the public key blob **inside** our private file has to be the public key
   in our own `.pub` file.  If those two disagreed, the file would be saying
   two things at once.

The general lesson is the one this repository keeps learning: **a gate that
fails is a gate that has to be read before the code is touched.**  Three of
the four failures were in the instrument, and a gate that reports a failure
without being read is worth exactly nothing.

### The mutation suite, in full

| # | the defect | the check that catches it |
|---|---|---|
| 0 | the magic loses its NUL terminator | our blob starts with the same magic |
| 1 | the cipher name claims the key is encrypted | src/keyfile's tests pass on native |
| 2 | the two check words are not the same word | src/keyfile's tests pass on native |
| 3 | the private block stores the public key instead of the secret key | our blob is 242 bytes |
| 4 | the padding bytes are not 1, 2, 3, ... | src/keyfile's tests pass on native |
| 5 | the base64 is wrapped at 64 columns instead of 70 | we wrap the base64 at 70 columns |
| 6 | the base64 padding is not stripped | the fingerprint OpenSSH prints is the one our tool printed |
| 7 | the fingerprint is computed over the seed instead of the public key | the fingerprint OpenSSH prints is the one our tool printed |
| 8 | the reader compares the two check words the wrong way round | src/keyfile's tests pass on native |
| 9 | the reader takes the public half of the secret key for the seed | src/keyfile's tests pass on native |
| 10 | the ACL is never installed, but the caller is told it was | the private key file is readable by its owner only |
| 11 | the DACL also grants Authenticated Users | the private key file is readable by its owner only |
| 12 | the driver says the passphrase is unsupported and writes the key anyway | no private key was written for the refused passphrase |
| 13 | the driver overwrites an existing private key | the existing private key was left alone |

All fourteen turn the gate red.

Number 12 is the dangerous one, and it is the reason the gate checks the
**bytes on disk** rather than the refusal message: a driver that prints "a
passphrase is not supported" and then writes the key anyway is exactly the
failure this loop exists to prevent, with an extra sentence in front of it.

### Two of the mutations were EQUIVALENT, and one of them was pointing the wrong way

The first run of the suite was 12 CAUGHT and 2 MISSED, and **neither of the
two misses was a defect in the code**.

**The first miss was an equivalent mutation.**  "the `.pub` line keeps the
base64 padding" cannot fail, and the reason is arithmetic: an ed25519 public
key blob is **51 bytes** (15 for the key type, 4 + 32 for the key), 51 is a
multiple of 3, and so its base64 **never has a `=` in it at all**.  There is
nothing to strip on that line, for this key type.  The padding rule bites
somewhere else -- the fingerprint, whose SHA-256 is 32 bytes, and 32 is *not*
a multiple of 3 -- so the mutation moved there, and the gate had to be
tightened to catch it: the fingerprint regex used to stop at the `=`, so a
fingerprint with its padding still compared equal to one without.

**The second miss was pointing the wrong way.**  The mutation inverted the
`if (!SetFileSecurityW(...))`, and the inversion does the opposite of what
the label said: the ACL **was** installed, and the caller was told it had
**failed**.  It was caught -- by "our ssh_keygen wrote a .pub file", because
the driver stops before writing it -- but not by the check that was named.
The dangerous direction is the other one: the call never happens and the
caller is told it did.  That version is caught by the ACL check and by
OpenSSH itself, and neither of them can see the other one.

The general lesson is the one this repository already has, in a new place:
**a mutation that cannot fail is not evidence, and a mutation that fails for
the wrong reason is not the mutation you meant to write.**  The first one is
found by the runner (it reports MISSED); the second one is only found by
reading what the gate said the failure was -- which is why the runner prints
the FAIL lines under a MISSED mutation.

### The unit test vector is OpenSSH's own file

The bytes in `src/keyfile/keyfile_test.mbt` are not hand-made.  They are what
a real `ssh-keygen -t ed25519` produced, read back field by field, so the
test asserts that **the file this repository writes is the file OpenSSH
writes**.

The seed is fixed (`19ef1c43...e374e9`), so the key is fixed, so the file is
fixed, and the assertion is one hex string of 484 characters -- 242 bytes --
that a reader can check by eye against the layout above.  The test needs no
entropy source, so it compiles and passes on all four targets, which is what
keeps `src/keyfile` reportable by the coverage tool.

### The gaps this loop does not close

* **No encrypted private keys.**  A file with a passphrase has
  `ciphername != "none"` and a real KDF, and this repository does not implement
  `bcrypt_pbkdf` or AES-CTR.  The reader says `Unsupported` for such a file,
  which is the honest answer: the file is fine, this reader does not do that
  part of it.  The writer refuses to produce one.
* **One key type.**  `ed25519` only.  RSA, ECDSA, the FIDO/SK types and
  ML-DSA are all refused by name.
* **`cmd/ssh_keygen` only makes keys.**  OpenSSH's `ssh-keygen` also has `-y`
  (print the public key of a private key), `-l` (print a fingerprint) and `-b`
  (print the public key blob).  The reader in `src/keyfile` can do the first
  two; the driver does not expose them yet.
* **`src/keyperm` is Windows-only.**  On a POSIX system the exclusive create
  mode is what makes the file private, and there is no ACL to set.
* **`src/rng` has a third kind of caller now.**  The seed and the check word
  come from it, and both are secrets in the sense that matters: a repeated
  seed is a repeated key, and a repeated check word makes two key files look
  alike.
* **`ssh-add` and `ssh-copy-id` are still missing**, so the key this loop
  makes still has to be carried around by hand.

### A stub that ignores its argument is a SAST finding, not a style question

`src/keyperm`'s stub has to have the same signature as the native half, so
it takes a `path` it cannot act on -- there is no file system on the browser
to protect.  The first version wrote:

```moonbit
pub fn protect(path : String) -> Int32 {
  -1
}
```

and the Loop #66 SAST gate caught it: `unused_value` at
`src/keyperm/keyperm_stub.mbt:12`.  The fix is the convention the repository
already has (`src/rng/rng_wasm.mbt` does the same thing for the same
reason):

```moonbit
pub fn protect(path : String) -> Int32 {
  ignore(path)
  -1
}
```

The point is not the warning.  The point is that **a gate which is red for a
reason you do not understand is a gate you cannot trust**, and this one had
been green in every run before Loop #85 -- because nothing had added a
package with a stub until now.  The warning was not about `keyperm`; it was
about the fact that the gate had never been asked this question.

### The mutation anchors drifted again, and `moon fmt` is the reason

`moon fmt` moved three of the fourteen anchors, in exactly the ways it moved
Loop #84's:

* it rewrapped the magic's byte array onto **one** line, so the anchor that
  ended in `0x76, 0x31, 0x00,` no longer matched;
* it put the `println`'s argument on **its own** line, so a two-line anchor
  became a five-line one;
* it pulled the `create_mode` argument up onto the call's line.

The fix is the rule this repository already has -- **copy the anchor out of
the file, do not write it from memory** -- and the check that the anchors
are still unique has to run AFTER `moon fmt`, not before it.

### The gates tier was a TREE, and it had 1m36s of headroom left

Loop #85's own run was green -- GitHub run 40995593926, `success`, 58m33s --
and the `gates` job inside it took **58m24s against a 60-minute cap**.  One
more loop would have taken it over, and the failure would have been a job
timeout: a red step with a name and no reason.

The cause was not the work.  Five gates -- loop81 through loop85 -- each run a
"regression" section that re-runs the gates before them, and the members were
spawned **without** `--skip-regression`, so each member ran its own chain as
well:

```
loop85 -> loop84 -> loop83 -> loop82 -> loop81 -> loop80
          -> loop83 -> ...                    -> loop79
```

That is not a chain, it is a tree, and the local CI's own timings show what
it costs:

| gate | time in the CI tier |
|---|---|
| `verify_loop78.mjs` | 8.2 s |
| `verify_loop79.mjs` | 23.4 s |
| `verify_loop80.mjs` | 48.7 s |
| `verify_loop81.mjs` | 85.5 s |
| `verify_loop82.mjs` | 176.9 s |
| `verify_loop83.mjs` | 391.1 s |
| `verify_loop84.mjs` | 644.3 s |
| `verify_loop85.mjs` | **1181.6 s** |

Nearly half the tier, in one gate.  The fix is one argument: spawn the
members **with** `--skip-regression`, so the chain is one level deep.

**Nothing is lost, and it is worth being precise about why**, because the
obvious objection is "the nested run is there to catch something":

* every member of every chain is **also** a gate the CI engine runs directly
  (`ci/ci.py --tiers gates` runs every `host/verify_loop*.mjs` that is not a
  peer gate), so nothing stops being checked;
* the reason the nested run exists -- a gate that leaves state behind that
  breaks an EARLIER gate -- is **preserved**: the members still run AFTER the
  parent gate has finished its own work.  What goes away is only the
  re-checking of the members' own members, which is the same work the engine
  does anyway.

And this was **not a new idea**: `verify_loop36.mjs:409`, `37:499` and
`38:401` have always spawned their nested scripts with `--skip-regression`.
The gates tier never learned the convention from them.

`host/patch_nested_regression.py` makes the change, with `--check` to report
and `--apply` to write.  The `gates` job's cap went from 60 to 90 minutes at
the same time -- the cap's job is to turn "the runner hung" into a red step
with a name, not to be a target -- and it is a bound, not a prediction.

---

## Loop #86: the key can be ENCRYPTED -- `bcrypt_pbkdf` and AES-256-CTR

### What was missing

Loop #85 made the client able to MAKE a key, and it **refused** a passphrase.
The refusal was not laziness; it was the honest answer to a question this
repository could not yet answer.  There was no `bcrypt_pbkdf` here, and a
tool that accepts `-N secret` and writes an UNENCRYPTED key is a way to lose
a secret quietly.

So Loop #86 adds the missing pieces:

| package | what it is |
|---|---|
| `src/blowfish` | the cipher: the pi constants, the Feistel function, both key schedules, the keystream reader |
| `src/bcrypt_pbkdf` | OpenSSH's KDF: the bcrypt hash and the PBKDF2-shaped derivation around it |
| `src/keyfile` (grown) | the encrypted half of `openssh-key-v1`: the KDF options, the cipher, and a reader that needs a passphrase |

and `cmd/ssh_keygen` stops refusing and starts encrypting.

### The constants are pi, and that is checkable

Blowfish's P-array and S-boxes are the hexadecimal expansion of the
fractional part of pi.  That is a property of the **algorithm**, not of any
one implementation -- OpenBSD's `blowfish.c` says so in a comment and so does
the original Blowfish paper.

So the constants are not "whatever OpenSSH's C file says".  They are pi, and
that can be CHECKED.  `host/blowfish_pi.py` does two independent things and
compares them:

1. it reads the 1042 words out of OpenSSH's `openbsd-compat/blowfish.c`;
2. it computes pi to 8336 hex digits with mpmath and takes the digits from
   **there**.

```
$ python host/blowfish_pi.py --check
OK  1042 words agree with pi (computed to 8336 hex digits)
    P[0]=0x243f6a88 P[17]=0x8979fb1b
    S[0][0]=0xd1310ba6 S[3][255]=0x3ac372e6
```

If the two agree, the constants are pi -- which is a much stronger claim than
"the file and our port agree", because it does not depend on OpenSSH being
right.

**Two traps in the extraction, both paid for in full:**

* the C struct is `u_int32_t S[4][256]` FIRST and `u_int32_t P[18]` SECOND,
  because that is the layout; pi's order is the P-array first and the
  S-boxes after it.  Reading the file as if it were in pi's order compares
  the **wrong words**;
* hex -> decimal precision is a factor of **1.2041**, not its reciprocal
  (0.302), and a digit-at-a-time `x *= 16` loop accumulates rounding until
  the digits come out as zeros -- measured: the loop gave zeros from word
  265 on.  The fractional part has to be scaled by `16**8336` and truncated
  **once**.

### The cursor: the one thing that is easy to get wrong

`Blowfish_stream2word` hands back a *cursor*, and the cursor is a position
in the **key** stream that is then reused as a position in the **salt**
stream.  Where it is reset is the caller's business, and the C's answer is
surprising in both directions:

```c
	j = 0;                              /* the key phase   */
	for (i = 0; i < BLF_N + 2; i++)
		c->P[i] = c->P[i] ^ Blowfish_stream2word(key, keybytes, &j);

	j = 0;                              /* the salt phase  */
	for (i = 0; i < BLF_N + 2; i += 2) { ... }

	for (i = 0; i < 4; i++) {            /* the S-box phase */
		for (k = 0; k < 256; k += 2) { ... }   /* j is NOT reset */
	}
```

The cursor **is** reset between the key phase and the salt phase, and is
**not** reset before the S-boxes -- so the S-boxes are salted with the salt
starting at **offset 8**, not at offset 0.  A port that "tidies up" the
cursor produces a key schedule that is subtly wrong and never matches
anything, with no error message anywhere: just a key that does not open.

There is a second subtlety in the same function: the cursor it returns can
be **equal to the length of the buffer**.  The wrap happens when a byte is
READ, not when the word is finished, so a word that ends on the last byte
hands back the buffer's length and the next call wraps it.  Normalising it
(`j % n`) reads the same bytes and is not the same function, because the
cursor is a visible output.  The C harness prints it, the test asserts it,
and the mutation suite flips it.

### The KDF is not PBKDF2, and the difference is the point

OpenSSH's own comment on `bcrypt_pbkdf` says why the output is scattered:

> One modification from official pbkdf2.  Instead of outputting key material
> linearly, we mix it.  pbkdf2 has a known weakness where if one uses it to
> generate (e.g.) 512 bits of key material for use as two 256 bit keys, an
> attacker can merely run once through the outer loop, but the user always
> runs it twice.  Shuffling output bytes requires computing the entirety of
> the key material to assemble any subkey.

So byte `i` of a block goes to `i * stride + (count - 1)` of the key, not to
`i`.  A KDF that scatters linearly is still a KDF, still produces a
well-formed file, and is still read back correctly -- it is just the weakness
OpenSSH removed, and nothing about the file says so.  It is mutation #8.

The rest of the construction, for the record:

* the passphrase is collapsed with SHA-512 **once**, at the start;
* the salt is hashed together with a **big-endian** counter;
* the bcrypt hash is: one salted expansion (`expand_state`), then **64**
  rounds of an unsalted expansion (`expand0_state`), each round with the
  salt hash and then with the password hash, and then **64** encryptions of
  a 32-byte magic string;
* the magic string is `"OxychromaticBlowfishSwatDynamite"` -- exactly 32
  bytes, so it is exactly eight whole words and needs no terminator;
* the eight words go out **little-endian**.

### The KDF options: the salt comes FIRST

```c
	if ((r = sshbuf_put_string(kdf, salt, SALT_LEN)) != 0 ||
	    (r = sshbuf_put_u32(kdf, rounds)) != 0)
```

`kdfoptions` is a **length-prefixed salt** and then a **plain four-byte
word**, in that order -- and OpenSSH's reader agrees
(`sshbuf_get_string` then `sshbuf_get_u32`).  It is easy to assume the
other order, and the assumption produces a file of exactly the right SIZE
and exactly the wrong CONTENT, which no reader accepts.

`SALT_LEN` is 16 and `DEFAULT_ROUNDS` is 24, and a real `ssh-keygen` writes
both.  The gate checks that our file has the same numbers.

### The passphrase is BYTES, not characters

OpenSSH hashes the passphrase as a C string: `strlen(passphrase)` bytes of
it, and no terminator.  What matters is therefore the bytes, and a
passphrase that is not ASCII has to be encoded the same way on both sides.

UTF-8 is that encoding here, via `@encoding/utf8.encode`.  The tempting
shortcut -- taking the low byte of each character -- is right for ASCII and
silently wrong for everything else, and a passphrase that derives a
different key on the two sides is a passphrase the user cannot get past.

MoonBit's `String::length()` counts **characters**, not bytes, and
`String::to_bytes()` is deprecated and returns **UTF-16LE** (six bytes for
`"aé中"`, where UTF-8 is also six but they are not the same six).  The
deprecation notice points at `@encoding/utf8.encode`, which is right.

### The reader has FOUR answers, and they are four different things

Loop #85's reader had three.  It has four now, and the new one is the one
that matters most in practice:

| answer | when |
|---|---|
| `Ed25519` | the file was opened and it is a key |
| `Malformed` | the file is not a key file at all |
| `Unsupported` | the file is a key file this reader cannot open -- another key type, another cipher, or an encrypted file read with no passphrase |
| `WrongPassphrase` | the file WAS deciphered and the check words did not match |

`WrongPassphrase` is not the same as `Malformed`: the file is perfectly
good, the reader simply was not given the key it needs.  The check words
are the mechanism -- they are the same word twice, and a wrong passphrase
makes the two of them differ.  **There is no MAC**; the check words are the
tag.

The reader also checks that the public key in the envelope is the public key
of the secret key in the file, which OpenSSH does too (`sshkey.c:3214`).

### The oracle is OpenSSH's OWN C code

`verify_c/blowfish_ref.c` and `verify_c/bcrypt_pbkdf_ref.c` are OpenSSH's
`openbsd-compat/blowfish.c` and `openbsd-compat/bcrypt_pbkdf.c`, copied here
with **three include lines and one `#define` changed** and nothing else.
`host/blowfish_ref.py --check` proves that the copies still match the
source, and the SHA-512 they need is OpenBSD's real `sha2.c`, which was
already in this repository.

```
verify_c/blowfish_shim.h   the three things OpenSSH's headers would have:
                           the u_int* typedefs, blf_ctx (copied verbatim
                           out of OpenSSH's own blf.h), and four libc shims
verify_c/blowfish_harness.c  picks the inputs and prints the answers
verify_c/build_blowfish.bat  the tenth build script, with the same
                           compiler-resolution rule as the other nine
```

The harness prints the vectors and `host/blowfish_kat.py --check` proves
that the constants the MoonBit tests assert are those vectors.

### No hex string in this loop was typed by hand, and three were

The first draft of `src/blowfish/blowfish_test.mbt` had **three** wrong
constants, and every one of them was a hand-transcription error:

* a 144-character hex string split in the wrong place, so the expected
  P-array was off by one **word**;
* the same, again, in the unsalted schedule;
* a key that counted **up** from 255 where the C harness's key counts
  **down** from 255.

All three looked like implementation bugs and all three were the test's
fault.  The fix was not "be more careful"; it was to stop typing:

* `host/blowfish_kat.py --check` reads the C harness's output and checks
  every constant the committed tests assert **against it** -- the
  direction that catches mistakes.  It found all three;
* `host/openssh_key_vector.py` reads a REAL OpenSSH private key file and
  prints its fields, which is where the unit test's vector comes from.

A vector that is off by one word looks exactly like a vector that is right.
That is worth a tool.

### The gate's other oracle is OpenSSH itself

A file format is a contract with the program everybody else has to read, and
only the program can say whether the contract is kept.  The gate does both
directions:

* **OpenSSH writes, we read.**  A real `ssh-keygen -t ed25519 -N "..."`
  file is embedded in `src/keyfile/keyfile_test.mbt` -- the whole file, base64
  and all -- and the test opens it with its passphrase and gets back the key
  that is in it.
* **We write, OpenSSH reads.**  The gate makes an encrypted key with our
  tool and then has the real `ssh-keygen` open it.

**The non-interactive trick.**  `ssh-keygen -y` asks for the passphrase on
the terminal, and a gate has no terminal.  `ssh-keygen -p -P <pass> -N ""`
does the same job without one: it opens the file with the passphrase given
on the command line and writes it back with an empty passphrase, and if the
passphrase was wrong it says `incorrect passphrase supplied to decrypt
private key` and leaves the file alone.  The file is then read with
`ssh-keygen -y`, which needs no passphrase.

**The argument array has to be exact.**  An empty passphrase is an empty
string and has to survive as one.  PowerShell drops an empty argument
entirely, and then `ssh-keygen -N "" -f file` reads the `-f` as the
passphrase and complains about "too many arguments".  `spawnSync` has no
shell, so the array is what the program sees -- which is why the gate is
Node and not PowerShell.

**The copy needs its ACL fixed.**  OpenSSH REFUSES a private key file that
other users can read, and it says so.  A plain file copy on Windows
inherits the **directory's** ACL, so the probe copy has to be given the
same treatment the original got (`icacls /inheritance:r /grant:r`).

### The round count in the file is FOUR BYTES, and it is untrusted input

This one was found by the mutation suite rather than by reading the code, and
it is worth the whole story.

The mutation "the KDF options put the rounds before the salt" swapped two
lines in the **writer**.  The file it produced was the right SIZE and the
wrong CONTENT -- and the **reader** read the salt out of the first four
bytes and the round count out of the next four, which gave it a round count
of **0x00010203 = 66051**.  `bcrypt_pbkdf` does not mind a round count of
66051: it does 66051 bcrypt hashes, each of which is about 67,000 Blowfish
block encryptions, and that is a computation measured in **hours**.

The mutation suite did not report "the mutation was missed".  It **hung**,
with `keyfile.blackbox_test` burning CPU, and it took three processes to
kill by hand.

The fix is not a faster KDF.  The fix is that **the round count in the file
is not obeyed**:

| | |
|---|---|
| OpenSSH's `ssh-keygen -a` | accepts 1 .. `INT_MAX` (`ssh-keygen.c:3503`) |
| OpenSSH's reader | takes whatever the file says (`sshkey.c:3110`) and hands it straight to the KDF |
| here | `MAX_ROUNDS` = 256, in `src/keyfile`, on both sides |

A private key file is untrusted input: it arrives over the network, out of a
tarball, in the mail.  A reader that obeys the round count in the file is a
reader that can be made to stop.

**256 is a measured number.**  One bcrypt round costs about forty
milliseconds in this implementation, so the cap is a little over ten seconds
of work; the same derivation in OpenSSH's C is a hundred times faster, so a
number that is absurd here is merely slow there.  The cap is set for THIS
implementation, which is the one that has to finish.

**The cap is in the file layer, not in the KDF.**  `src/bcrypt_pbkdf` is a
faithful port and keeps OpenSSH's own rule (one round or more); the cap
lives in `src/keyfile`, where the number comes from a file or from a
person.  Two places check it -- the reader and the derivation -- because
the reader's check is the one that sees a file and the derivation's is what
stands between a number from anywhere and a computation that never finishes.

**The driver's `-a` is capped too, and the number is capped as it is
read.**  A count of thirty digits does not fit in an `Int32`, and an `Int32`
that wraps around lands on a small number that looks perfectly legal:
`4294967320` is `2^32 + 24`, and without the check it would be written into
the file as **24**.  The gate checks that exact number.

### The comment is TEXT, and text has an encoding

The comment in a private key file is text.  The writer wrote it one byte per
character -- `out[i] = s[i].to_byte()` -- which is right for ASCII and
silently wrong for everything else, because it keeps one byte and throws the
rest of the encoding away.  A comment of one accented letter went into the
file as one byte and came back as a different character.

The reader had the matching bug in the other direction: it decoded bytes one
at a time into characters, which is Latin-1, and it could not read UTF-8 at
all.

Both are fixed by using UTF-8 on both sides -- `@utf8.encode` on the way out
and `@utf8.decode_lossy` on the way in -- and the test is a comment outside
ASCII that has to come back exactly as it went in, on the plain path and on
the encrypted path.

**Two fields had to stop going through `String` altogether.**  The KDF
options and the public key blob in the envelope are BINARY: the salt is
sixteen bytes of `arc4random` and the public key is 32 bytes of curve
point.  They were being read as strings and converted back byte by byte,
which happened to be lossless -- but only because the reader's decode was
Latin-1.  Fix the decode and those two fields would have been mangled, so
they are read as bytes now, which is what they are.  **A field that is bytes
and a field that is text are different things and should not go through the
same function.**

**One thing this does not fix, and cannot.**  OpenSSH stores the comment as
the raw bytes it was given, and on a Windows console those bytes are in the
console's code page, not UTF-8.  A comment OpenSSH wrote on a non-UTF-8
locale comes back with replacement characters -- the file still opens, and
the key is still right.  The decode is lossy on purpose.

### A gate that hangs is worse than a gate that is wrong, and so is a gate that dies

There are two ways a gate can stop talking, and **both of them happened
in this loop**.

**It can hang.**  The gate's `moon()` helper called `spawnSync` with no
timeout, so it waited for the child for as long as the child wanted to
run.  When the round-count bug was live, the gate waited for hours and
reported nothing at all.

**It can die.**  The mutation "the driver writes an unencrypted key when
given a passphrase" came back MISSED -- and the gate was not wrong, it
was **DEAD**.  The mutated driver writes a file whose KDF options are
empty, and the gate's `parseKdfOptions` read a four-byte length out of
an empty buffer, which throws.  The gate stopped at that line and
printed nothing more, and the mutation suite read the absence of a FAIL
line as "the gate did not notice" -- when in fact the gate had stopped
running at all.

So two rules, and the second is the general one:

* every `spawnSync` in a gate needs a timeout, and **a timeout has to be
  a FAILURE with a reason**, not a silent skip: "the test never finished"
  is a failure of the test, and a red gate with no reason is a rumour --
  the reader has no way to tell "the round trip broke" from "the
  toolchain did not run";
* **the gate itself must not be able to die quietly.**  `main()` is
  wrapped, so an exception anywhere in it is reported in the same
  PASS/FAIL vocabulary as everything else, with the reason, and the
  process exits non-zero.  **"Nothing" is not a verdict.**

And the reader of a gate has to be able to tell the two apart: "the gate
says no" is a FAIL line, "the gate stopped" is a *missing* line, and only
the first one is evidence.  A mutation that is MISSED has to be
investigated before it is believed -- the first question is not "is the
gate right?" but "did the gate run?".

### After editing a file, look at `git diff` for comment churn

The doc comments on disk are `///` lines: a standalone `///|` is the header
of a block, a standalone `///` is a separator inside one, and the text lines
are `/// text`.  **The reading tool renders a `///` block as `///|` lines
with blank lines between them**, and a file that is written back from that
rendering keeps the rendering.

Editing `src/keyfile/parse.mbt` that way rewrote about three hundred lines
of the Loop #85 documentation and buried the change under a wall of
comments that say nothing about it.  `src/keyfile/blob.mbt` came out clean,
which is the confusing part: the churn depends on how the file was written
back, not on what was changed.

So the rule is not "use this tool" but **"look at the diff"**.  After
editing, `git diff` has to show the change and not the neighbourhood.  When
it shows the neighbourhood, the fix is a one-off script that applies the
inverse transform -- `///| text` back to `/// text`, the in-block blank lines
back out, and a standalone `///|` back to `///` unless it starts a block --
and then the diff shows the change again.

The repository has both styles in it, so nothing breaks either way; a
reviewer just cannot see the change through three hundred lines of
reshuffled prose.

### The mutation suite grew to 21

Five more mutations came out of the two fixes above:

| mutation | what it proves |
|---|---|
| the round cap is smaller than the round count OpenSSH writes | the cap is not so small that it refuses ordinary files |
| the reader does not cap the round count | the reader's half of the cap is load-bearing |
| the derivation does not cap the round count | the derivation's half is load-bearing too |
| the comment is written one byte per character | the writer's half of the encoding |
| the reader decodes the comment one byte at a time | the reader's half |

**The hostile round count in the tests is `MAX_ROUNDS + 1`, not two
billion.**  The cap is one comparison, so a count of 257 proves it as well as
a count of two billion does -- and if the cap were ever removed the test
would take a few seconds and FAIL, where a count of two billion would make
it hang.  A test that hangs when the defect is present is worse than a test
that fails.

### The gaps this loop does not close

* **`cmd/ssh_keygen` still only makes keys.**  It does not read them: the
  reader in `src/keyfile` can do `-y` and `-l`, and the driver does not
  expose them.  This is the next obvious gap and it is what the client's
  `ssh` needs.
* **One key type, one cipher, one KDF.**  `ed25519` only; `aes256-ctr` and
  `bcrypt` only.  OpenSSH also writes `aes256-gcm@openssh.com` with
  `bcrypt`, and `chacha20-poly1305@openssh.com`.
* **`-a` is accepted but the rounds are not a secret.**  A passphrase
  derived in 24 rounds is 24 rounds of work; OpenSSH's own default, and
  nothing here argues with it.  The count is capped at 256, because the
  count is read out of a file as often as it is typed on a command line,
  and a file is untrusted input.
* **The passphrase is on the command line**, which is what OpenSSH does and
  is visible to anybody who can read the process list.
* **`ssh-add` and `ssh-copy-id` are still missing**, so a key that is now
  encrypted has to be carried around and typed by hand.
* **The KDF is slow on purpose.**  One bcrypt hash is about 67,000 Blowfish
  block encryptions; a 24-round derivation is about 1.6 million.  That is the
  price of the KDF, and it is why the tests use 4 rounds and the real files
  use 24.

---

### The OpenSSH tree is a PROBE, not a path

`verify_loop71` refused this loop's two new scripts for naming one
developer's OpenSSH checkout, and it was right.  A path written into code
is a promise that the code works on the machine it was written on, and the
promise does not travel to a clone.

The location now lives in one file, `host/openssh_src.py`:

```python
# machine-path-exempt: each entry below is a CANDIDATE location, probed in
# order until one exists.  ...
CANDIDATES = [
    r"E:\src\moon\openssh-C",
    r"C:\src\openssh-C",
]
```

`OPENSSH_SRC` comes first and overrides the list, which is the only way to
point at a tree on a path nobody guessed.  When no candidate exists the
failure names **every** one of them, because "the tree is not here" is not
an explanation and "the tree is not here, and here is everywhere I looked"
is.

**"The tree is not here" is an EXIT CODE (3), not an error string.**
The gate that asks the question has to be able to tell "I could not check
this here" from "the check failed".  A caller that recognises absence by
matching text is one edit away from reporting a real mismatch as a skip --
and a skip that is reported as a pass is worse than a failure, because it
is invisible.

The same rule settled the other gate this loop turned red.
`verify_loop85` asserted that a passphrase is REFUSED; that was Loop #85's
contract and Loop #86 changed the contract on purpose, because the KDF
exists now.  When a contract moves, the gate moves with it, and the new
claim has to be a **stronger** one:

| | Loop #85 said | Loop #86 says |
|---|---|---|
| the passphrase | is refused | is honoured |
| the file | is not written | is written |
| the cipher name | -- | `aes256-ctr` |
| the KDF name | -- | `bcrypt` |
| OpenSSH without the passphrase | -- | cannot open it (exit 255) |

The last row is the one that matters.  A file that says `aes256-ctr` and
opens anyway would be worse than one that says `none`, because the user
has been told it is protected.

### The toolchain moved under us, and CI installs `latest`

moon was upgraded from `0.1.20261012` to `0.1.20261102` **by another
process on this machine**, not by this repository: the upgrade showed up
as `moon.exe` vanishing from `~/.moon/bin` while a `moon upgrade` process
was running, and every gate that needed the toolchain from that moment
on failed in 0.3 s with

    'moon' is not recognized as an internal or external command

Four gates went red that way (`verify_loop68`, `76`, `78`, `79`).  None of
them was a defect: they were the toolchain being replaced underneath a
run.  The first thing to ask about a sudden `0.3 s` failure of several
gates is **whether the gate ran at all**, not whether the gate is right.

Two real consequences did come out of it, and both are permanent:

#### 1. The derive syntax moved

`} derive(Eq)` (a suffix on the closing brace) is now `#derive(Eq)` on
the line ABOVE the declaration:

```moonbit
#derive(Eq)
pub(all) enum Marker {
  None
  CertAuthority
  Revoked
}
```

Only two files in this repository used the old form --
`src/knownhosts/entry.mbt` (2 sites) and `cmd/proton_gui/contract.mbt`
(4 sites) -- and `moon fmt` rewrote exactly those two files and nothing
else in the tree.  That is the measurement that keeps this small: the
formatter's diff IS the scope of the migration, so the scope did not have
to be guessed.

`moon fmt --check` is a **qa-tier category**, and the CI installs moon
with the default `version: latest`.  So a syntax change upstream breaks
this repository's CI even though nobody touched the source: the runner
picks up the new toolchain and the old spelling no longer parses.  This
is the same lesson as the CRLF rule in `.gitattributes` -- a claim about
the machine is not a rule, and "the toolchain stays where it was" is a
claim, not a pin.

The `pub extend Marker with Eq::{equal, not_equal)` lines survive the
migration untouched, and so does the reason they exist: the promoted
`Eq::{equal, not_equal}` methods are deprecated, and naming them keeps
the call sites honest (Loop #66).

#### 2. The toolchain writes an interface file for EVERY package

`moon 0.1.20261012` wrote `pkg.generated.mbti` only for the packages
`moon info` had been asked for, which is why this repository tracked 23
of them and `.gitignore` named the two exceptions.  `0.1.20261102` writes
one for **every** package on **every** build: 74 files on disk, 51 of
them untracked.

Two measurements decided what to do with them:

* **They are stable across targets.**  Built for native, js, wasm and
  wasm-gc in turn, `src/sha256`, `src/keyfile`, `src/sshclient` and
  `src/wtlive` each produce a byte-identical file.  The two `.gitignore`
  exceptions existed because "the generated interface drifts with the
  target" -- that reason no longer reproduces, so the exceptions are
  gone rather than kept for their shape.  A rule whose stated reason has
  stopped being true is a rule that stops being reviewed.
* **They embed constant VALUES, not only types.**  `moon info` writes
  `pub const CAPTURE_FIXTURE : String = "E:/src/moon/openssh_moonbit/.loop39/sftp"`
  into `cmd/sftp_test/pkg.generated.mbti` -- a machine path, in a
  tracked file, from Loop #39.  That is why the untracked ones are
  ignored rather than committed: an interface file is not an authored
  claim, and committing 51 of them would commit 51 chances to write one
  machine's directory into the repository.

So `.gitignore` now carries ONE rule (`**/pkg.generated.mbti`) instead of
two named exceptions.  A `.gitignore` does not untrack a file that is
already tracked, so the 23 interfaces this repository does track stay
tracked, and `git status` is clean again.

#### The 23 tracked interfaces were STALE, and now they are not

Refreshing them with the current toolchain added **114 declarations**
and removed **none**.  `src/aead/pkg.generated.mbti` was an EMPTY file
in the repository -- the package's entire interface, 24 declarations,
was simply not in the committed copy.  `src/hostkey` was missing 39,
`src/sftp` 14, `src/kexflow` 10, `src/bpacket` 12, `src/knownhosts` 11.

Nothing in the source had changed to cause that; the files were written
by an older toolchain and never refreshed afterwards, so they were
**claims about the interface that were no longer true**.  The toolchain
also re-spells `Int` and `UInt` as `Int32` and `UInt32` -- the same
types, since MoonBit's `Int` is 32 bits -- which is a spelling change
and not an API change, and the refresh was checked for exactly that:
114 declarations added, 0 removed, 0 changed names.

---

## Loop #86, follow-up: a gate must not guess how long a peer takes to FINISH either

Loop #79's follow-up fixed the *startup* half of this: a gate that waits a
fixed number of milliseconds for a peer to come up loses the race on a
loaded machine, and the loss reads like a protocol difference.  The
shutdown half was never fixed, and it is the same mistake.

`verify_loop54.mjs` and `verify_loop59.mjs` stopped their peers with

    await sleep(2500);
    if (m.proc.exitCode === null && m.proc.signalCode === null) m.proc.kill();

`host/sftp_mitm.py` writes its transcript only AFTER its session thread
returns -- `worker.join(timeout=120)` first, and in a control run
`t.join(5)` before that -- so 2.5 s is a guess about a peer's shutdown,
and the guess loses the same way the startup guess loses.  What the losing
run produced was this:

    FAIL  remembered  authenticated but the peer saw null attempts

`.loop54/s2.json` was **zero bytes**.  The peer was killed mid-write, the
gate read an empty file, `JSON.parse("")` threw, `readJson` returned
null, and the gate printed "null attempts" -- a statement about the
*client's* authentication that was entirely an artefact of the gate
having killed its own peer.  A gate that reports the subject under test as
broken because it raced its own harness is worse than a gate that simply
fails, because it sends the next reader to the wrong module.

The fix is the mirror image of Loop #79's: wait for the peer to SAY it is
done.  `host/wt_browser.mjs` already had the helper, and seven sibling
gates (47--53) already used it:

    import { exitedWithin } from "./wt_browser.mjs";
    ...
    if (!(await exitedWithin(m.proc, 30000))) m.proc.kill();

The child's exit IS the signal that the transcript is on disk: the file is
written and closed before `main()` returns.  The 30 s window is not
arbitrary -- the peer is entitled to its own `t.join(5)` before it
writes, so the window has to be comfortably wider than that, and the
`kill()` is only the backstop for a peer that never leaves at all.  The
local `sleep` helper went with it: a dead `sleep` in a gate reads as
"there is still a sleep somewhere in here", which is exactly the
impression the change was meant to remove.

**The assertion did not get weaker.**  `auth_attempts` must still be
exactly 1, and the "remembered" step still has to authenticate from the
file alone in a fresh process, with no `--kh-tofu` and no printed line.
What changed is only how the gate waits: it observes the peer's exit
instead of guessing at a duration.

Measured after the change: loop54 16/16 on three consecutive runs, loop59
7/7 on two.

### The rule this makes explicit

**A gate must not guess how long a peer takes to start, and it must not
guess how long it takes to finish.**  Both guesses lose on a loaded
machine, and both lose the same way: the symptom gets reported against
the subject under test.  When a gate fails with a value that came out of
a file the harness owns -- "null attempts", "no transcript", "the client
saw nothing" -- the first thing to ask is whether the harness killed its
own peer too early, and the answer has to come from the peer's exit
status, not from a number in the gate.

---

## Loop #86, follow-up: the CI cache restored the toolchain and undid the install

Pushing the Loop #86 follow-up made GitHub Actions red.  Not in the gates:
in a **setup step**, before a single gate ran.

    Write-Error: moon install moonbit-community/proton_cli@0.3.4 exited -1
    Error: Failed when discovering packages
    Caused by:
        Unable to read `moon.pkg` for module
        'moonbitlang/core@0.10.16+b1a0e846e (stdlib)' package
        'async/external_loop_integration' at path
        'C:\Users\runneradmin\.moon\lib\core\async\external_loop_integration',
        error: Conditional imports are not yet supported by the build system.

The first question about a red CI that says nothing about this repository's
code is whether the toolchain that ran is the toolchain that was installed.
Here it was not, and the log said so if you read it in the right order:

    07:41:25  Set up MoonBit      moon 0.1.20261104, stdlib core 0.10.20
    07:41:52  Set up MoonBit      "moon 0.1.20261104 (940aa18 2026-11-04)"
    07:41:58  Cache MoonBit deps  Cache hit, ~116 MB
    07:42:06  Cache MoonBit deps  "Cache restored successfully"
    07:42:12  Provision the CEF   moon install fails

The setup step printed `moon 0.1.20261104` -- the toolchain it had just
installed.  Four seconds later the cache restored `~/.moon` from the
2026-10-30 run, which is **moon 0.1.20261012 and core 0.10.16+b1a0e846e**,
and the job carried on with those.  The version in the log was a statement
about the install; the version that ran was a different one, and nothing in
the workflow said so.

`core 0.10.16+b1a0e846e` is the standard library that belongs to moon
0.1.20261012.  That standard library's
`async/external_loop_integration/moon.pkg` has conditional imports
(`import { ... } for "test"`, under `#cfg(target="native")`), and the
0.1.20261012 build system cannot read those -- so `moon install`, which
discovers packages before it does anything else, died on a standard library
package it was never going to install.

### What was checked, and how the diagnosis was reached

The failure text names three versions, and the first reading of it is that
the toolchain is simply broken upstream.  It is not, and the way to know is
to rebuild the runner's state locally instead of reasoning about it:

* The install script (`cli.moonbitlang.com/install/powershell.ps1`) fetches
  the CLI from `binaries/$Version/` and the standard library from
  `cores/core-$Version.zip` -- so the core is pinned to the same `$Version`
  as the CLI, and `$Version` is `latest` by default.
* `cores/core-latest.zip` carries **core 0.10.20+65efd5b93**, which is
  the same version the runner's own compiler reported
  (`moonc v0.10.20+65efd5b93`).  The runner was running core **0.10.16**,
  which is not that.
* In an isolated `MOON_HOME` -- the same download, the same
  `moon update`, the same `moon install` -- the core stayed at 0.10.20 and
  `moon install` got **past** package discovery, failing only on a missing
  `bigint.mi` bundle artifact that the install script's own
  `moon.exe bundle` step creates.  The installer had not run that step in
  the reproduction; nothing about core 0.10.20 was broken.
* The `Cache MoonBit dependencies` step logged `Cache hit for:
  moonbit-Windows-3161bb9...`, `Cache Size: ~116 MB`, `Cache restored
  successfully`, `Cache restored from key: moonbit-Windows-3161bb9...` --
  at 07:41:58, i.e. after the install and before the failure.

So the cache was the thing that made the runner disagree with itself.

### The fix

`~/.moon` **is** the toolchain: moon.exe, moonc, the native backend and the
bundled standard library.  Caching it means a run can restore an older moon
than the one it just installed, and an older moon and an older standard
library do not agree about file formats.  The cache now holds `.mooncakes`
only -- the downloaded third-party packages, which is the expensive part;
the toolchain is downloaded unconditionally by the setup step either way, so
caching it saved nothing and cost a wrong toolchain.

The cache step also moved **before** "Set up MoonBit".  With the toolchain
out of the cache the order no longer matters, but a cache that runs after an
installer is a cache that can shadow the installer, and the ordering that
makes that impossible is worth having.

And the CEF step now prints `moon version --all` **in the step that uses
it**.  The setup step prints the version it installed; a step that names
the version it ran is a step whose failures can be read.

### The rule this makes explicit

**A cache that overlaps an installer must not be able to outlive it, and a
version printed by one step is not evidence about another.**  Both halves
were true here and together they made a four-second gap invisible: the log
named one toolchain and the job used another.

This is the fourth time in this repository that the plumbing ate a correct
fix -- Loop #69's twelve lines, Loop #70's `.loop70/` outside the upload
path, the artifact uploader's dotfile rule, and now the cache.  The shape
is always the same: the thing that was supposed to make the work cheaper
or more reliable is the thing that silently undid it, and it undid it in a
way that looked like a defect in the subject.

---

## Loop #87: ssh-keygen can READ a key -- `-l`, `-y`, `-P`, `-E`

Loop #85 made this repository able to MAKE a key and Loop #86 made it able
to ENCRYPT one.  Loop #87 makes it able to READ one:

    ssh-keygen -l -f <key>       the fingerprint
    ssh-keygen -y -f <key>       the public key
    ssh-keygen -y -P <pass> -f <key>    the public key of an encrypted one
    ssh-keygen -l -E <hash> -f <key>    the fingerprint in another hash

### The judge is the real tool, and the comparison is byte for byte

The gate (`host/verify_loop87.mjs`) runs the REAL `ssh-keygen` and this
tool with the SAME arguments and compares **the exit status, stdout and
stderr, byte for byte**.  Byte for byte, and not "the same information":

* **stdout** including the line ending.  OpenSSH writes CRLF on Windows
  and so does this tool.
* **stderr**, which is stricter than it sounds.  OpenSSH runs every
  message through `strnvis` with `VIS_SAFE|VIS_OCTAL` (log.c:69), so a
  path in an error message has its backslashes **doubled**:

        ssh-keygen: E:\\src\\moon\\nope: No such file or directory

  A tool that prints single backslashes there is a tool whose error
  output can never be compared with OpenSSH's byte for byte, and the day
  somebody needs that comparison is the day it has to be exact.
* **the exit status**, which is **255** for every failure.

### The rules, read out of the real tool

The rules below were measured, not guessed.  The script that measured them
is `.loop87/probe_truth.py`, and the transcript it produces is the reason
each of these is here:

* **`-l` on a PRIVATE key file asks for the PUBLIC key first**
  (authfile.c:269).  The `.pub` file beside it decides the fingerprint
  AND the comment, and the passphrase is never needed.
* **A `.pub` FILE whose line has no comment is given the FILE's NAME as
  its comment** (authfile.c:238, `strdup(*cp ? cp : filename)`).  So
  `ssh-keygen -l -f key` can print the path where `ssh-keygen -l -f
  key.pub` prints `no comment` -- for the same key, in the same second.
* **A `.pub` LINE whose comment is empty, or whose comment starts with
  `#`, is given NO comment** (ssh-keygen.c:989).  That is a DIFFERENT rule
  in a DIFFERENT place, and the two disagree.
* **`no comment` and an EMPTY comment are different strings, and the
  difference is a space**: one space and two.

        256 SHA256:... no comment (ED25519)
        256 SHA256:...  (ED25519)

* **`-l` on an ENCRYPTED key needs no passphrase at all**: the public blob
  of an `openssh-key-v1` file is in the clear.  The COMMENT of that key
  is in the enciphered block, so it cannot be read, and OpenSSH prints
  `no comment` for it.
* **`-y` always opens the PRIVATE file**, so it needs the passphrase for
  an encrypted one.
* **The two failure messages are different messages**: `-l` on a missing
  file says `ssh-keygen: <path>: No such file or directory` and `-y` says
  `<path>: No such file or directory`, with no program name in the second
  one.  The reason is in the source: one format string names the program
  and the other does not.

### The one divergence, stated rather than hidden

**`-E md5` is REFUSED.**  OpenSSH supports it and this repository has no
MD5, so the honest answer is a refusal rather than a fingerprint in the
wrong form:

    $ ssh_keygen -l -E md5 -f key
    ssh_keygen: only -E sha256 is supported, not md5

An algorithm that NEITHER tool knows (`-E bogus`) gets OpenSSH's own
words, byte for byte:

    Invalid hash algorithm "bogus"

The distinction matters: "this tool cannot print that fingerprint" and
"that algorithm does not exist" are different claims, and only the second
one is OpenSSH's to make.

### Three mistakes that the byte comparison caught, and a rule for each

The first version of this loop was wrong in three ways, and every one of
them was invisible to a test that checked "does it produce a
fingerprint":

1. **`print` does not exist in MoonBit.**  There is `println` and
   `eprintln`, and no `print`; a program that wants to write a line
   without a trailing newline has to cut the newline off itself.  The
   compiler said so (`The value identifier print is unbound`) and the
   fix was to add `public_line_text` to `src/keyfile` -- the FILE text
   ends with a newline and the printed LINE does not.

2. **The type of a key line was read with the wrong function.**  The
   parser wanted "where does the key type END", and used the function
   that answers "where does the next word START".  The two are
   interchangeable in a reader that only cares about the position of
   the blob, and they are not interchangeable here: the type came out
   as the empty string, so every line was "not ed25519", and the tool
   said "is not a public key file" about a perfectly good key.  The
   blob had the same disease: read with `skip_blanks` instead of
   `end_of_word`, the base64 came out as the empty string.

   **A position in a line is either the start of a word or the end of
   one, and asking for the wrong one gives a plausible number.**  Both
   of these were found by the byte comparison and by nothing else.

3. **A MoonBit program CAN choose its exit status.**  Loop #86's gate
   says in a comment that "MoonBit's `main` has no way to set an exit
   status", and that comment was wrong: `moonbitlang/core/env` has
   `exit(Int32)`, and `@env.exit(255)` sets the status exactly.
   `abort` is the other thing -- it raises a failure, and the status
   that comes out of that is the runtime's, not the program's.

   **A tool that fails with 0 is a tool whose failure a script cannot
   see**, and a tool that says why on stdout is a tool whose output
   cannot be told apart from a key.  So: the errors go to stderr and
   the status is 255, which is what OpenSSH does.

### Where the rules live

The rules live in `src/` and the driver translates them:

* `src/keyfile/public.mbt` -- `parse_public_line`, `fingerprint_line`,
  `fingerprint_of_blob`, `public_of_private_file`,
  `private_file_is_encrypted`.
* `src/keyfile/log.mbt` -- `escape_log_text`, OpenSSH's `strnvis`.
* `src/keyfile/pair.mbt` -- `public_line_text`.
* `cmd/ssh_keygen/main.mbt` -- the dispatch, and the messages.

**The parser reports the FACT and the caller applies the RULE.**  The
parser says "the comment in this line is `x`" or "this line has no
comment"; it never says "so the comment is the file name".  That is
because OpenSSH has two rules and they disagree, and a package that
picked one of them would be wrong half the time.

### The gate, the mutations, and the tests

* `host/verify_loop87.mjs` -- 56 checks, in seven sections: the
  toolchain, the real OpenSSH being present, the byte-for-byte
  comparison, the two-way round trip, the failures, the digest option,
  and the rules visible in the output.
* `host/loop87_mutations.py` -- 17 mutations, each naming the check that
  has to go red because of it.  The check name is matched as a WHOLE
  LINE, not as a prefix: the gate has checks called "-l on a private key"
  and "-l on a private key whose comment is empty", and a prefix match
  would call the second one a hit for the first.
* `src/keyfile/public_test.mbt` -- 15 tests.  The fingerprint vector in
  them was computed independently and then CHECKED AGAINST THE REAL
  TOOL:

        $ ssh-keygen -l -f k.pub
        256 SHA256:VvxuUNEw8QPYQxk4kv+N/5t0DKHxwyE4iYP0soz3a34 e2e@loop87 (ED25519)

### The rules this makes explicit

* **A byte comparison is a stronger judge than a test that asks a
  question.**  All three mistakes above passed every unit test that
  existed at the time and failed the byte comparison immediately.

* **`repr()` of bytes doubles the backslashes, and so does `vis`.**  The
  transcript of a `repr()` cannot tell ONE backslash from TWO, so the
  first reading of the error output was wrong -- and the fix for it was
  to print the hex and the backslash RUNS, not to read the transcript
  harder.  (On the same note: PowerShell renders a native command's
  stderr as an error record and doubles the backslashes there too.  The
  exact bytes of a Windows tool are read with Python's `subprocess`.)

* **A position in a line is either the start of a word or the end of
  one, and asking for the wrong one gives a plausible number.**

* **Two rules in the same program that disagree are not a bug in the
  reader; they are a fact about the thing being read.**  The reader's
  job is to report the fact and let the caller choose the rule.

---

## Loop #88: ssh-keygen can REWRITE a key -- `-p` and `-c`

Loop #85 made this repository able to MAKE a key, Loop #86 gave the file
a passphrase, and Loop #87 made it able to READ one.  What was left was
the middle of the story:

    ssh-keygen -p -N <new> -f <key>       a new passphrase
    ssh-keygen -c -C <new> -f <key>       a new comment

A key file that can be read but not written again is a key file that can
be created once and then never changed -- and changing a key file is
what those two options are for.

### The rules, read out of the real tool

Every rule below was MEASURED, not guessed.  The scripts that measured
them are `.loop88/probe_truth.py`, `.loop88/probe_more.py` and
`.loop88/probe_three.py`, and `.loop88/compare_keygen88.py` is what
holds this tool to them -- **byte for byte, the exit status, stdout and
stderr, against the real `ssh-keygen`**.

* **`-p` prints `Key has comment '<comment>'` BEFORE it writes
  anything**, and `Your identification has been saved with the new
  passphrase.` after it.  The comment of a key with no comment is an
  EMPTY comment and not an absent one, so the line reads
  `Key has comment ''`.

* **`-c` prints `Old comment: <comment>`** -- and then exactly one of

      Comment '<new>' applied
      Comment removed            (the new comment is empty)
      No change to comment       (the comment is already the one asked
                                  for -- and then NOTHING is written)

  An empty comment still prints: the line is `Old comment: ` with a
  space and nothing after it.  And `-c -C ""` on a key that has no
  comment is **not** a change: the two comments are equal, so the file
  is left alone.

* **`-p` does NOT touch the `.pub` file.  `-c` rewrites it** with the
  new comment, and writes it even when it was not there before.

* **Changing the comment does NOT change the passphrase.**  An
  encrypted key is still encrypted with the same passphrase afterwards.

* **An empty new passphrase takes the passphrase OFF the key**: the
  file comes out unencrypted, and opens afterwards with no passphrase at
  all.

* **The EMPTY passphrase is tried FIRST.**  So `-p -P whatever` on a key
  with no passphrase works, and the `-P` is never looked at.

* **`-c` takes the CURRENT passphrase from `-P`, or from `-N` when there
  is no `-P`** (ssh-keygen.c:1506).  That is OpenSSH's order and it is a
  quirk worth naming: `-N` means "the new passphrase" in `-p` and "the
  current passphrase" in `-c`.

* **The two failure messages are DIFFERENT messages.**  `-p` says

      Failed to load key <path>: incorrect passphrase supplied to decrypt private key

  and `-c` says

      Cannot load private key "<path>": incorrect passphrase supplied to decrypt private key

  One has no quotes around the path and the other has them, and the
  reason is in the source: one format string and the other
  (ssh-keygen.c:1397 and ssh-keygen.c:1515).

* **A file that is not there says so without the program name in front
  of it**: `<path>: No such file or directory`.

### The thing the output does NOT say

**The stdout of a rewrite says almost nothing about the file it
wrote.**  "Your identification has been saved with the new passphrase."
is the same line whether the salt was drawn afresh or not, whether the
round count is 24 or 1, whether the comment was written into the file
at all, and whether the file is enciphered or not.

So the gate does not only compare the output.  It looks at the FILE:

| what | where in the file | why it matters |
|---|---|---|
| the salt | 16 bytes at offset 47 | the same salt and the same passphrase derive the same key, so a file that reuses its salt is a file whose OLD passphrase is still worth something |
| the KDF round count | a big-endian word at offset 63 | it is the cost of guessing the passphrase; the default is 24 |
| the cipher name | the string at offset 15 | it says whether the private block is enciphered at all |
| the check word | 4 bytes at offset 98 of an UNENCRYPTED file | it is the tag that says "this file was deciphered with the passphrase it thinks it was" |

**Two rewrites of the same key have to differ**, and that is a check
the output cannot make.  OpenSSH draws the salt and the check word
afresh every time it writes a file (`arc4random_buf(salt, SALT_LEN)`
and `check = arc4random()` in `sshkey_private_to_blob2`), and so does
this.

**The round count of a rewrite is the DEFAULT, not the one the old file
had.**  OpenSSH's `ssh-keygen` has ONE global `rounds`, which is 0
unless `-a` was given, and `sshkey_private_to_blob2` turns a 0 into
`DEFAULT_ROUNDS` (24).  So a file written with `-a 100` comes back with
24 rounds after a `-p`.

### Nothing here asks a question

OpenSSH asks for the old passphrase, for the new one and for the new
comment on the **TERMINAL** -- and with no terminal it does not fail,
it **BLOCKS**.  Measured: `ssh-keygen -p -P "" -f key` with an empty
stdin did not return in 120 seconds, and the probe had to be killed.

So this tool refuses, and says which option is missing:

    $ ssh_keygen -p -f key
    ssh_keygen: give the new passphrase with -N

**A tool that waits for an answer that is not coming is a tool that
hangs**, and a tool that hangs is worse than a tool that refuses.

**And a GATE that runs the real tool must never put it in a position
to ask.**  This one did, and it cost an afternoon: the gate ran the
real `ssh-keygen -y` against a key that the code under test was
supposed to have de-enciphered -- and when the code was broken (which
is what a mutation run does on purpose) the key was still enciphered,
so the real tool asked for the passphrase **on the terminal** and sat
there.  The gate hung, the mutation run hung with it, and a hung
`ssh-keygen` outlived the timeout that was supposed to kill it.

Every call now gives the passphrase, so the tool is never in a
position to ask:

    ssh-keygen -y -P "" -f key

An enciphered file is then refused with a sentence, and an
unenciphered one is opened as before -- the passphrase is ignored
when there is nothing to decipher.

**A gate has to be safe against the code it is testing being broken.**
That is the whole point of a mutation run: the gate is asked to deal
with a tree that does not work, and a gate that can be hung by a
broken tree is a gate that cannot measure anything.

### The divergences, stated rather than hidden

* **`-p` and `-c` together**: OpenSSH prints the sentence and then its
  whole usage text, and exits with **1**.  This tool prints the
  sentence -- `Can only have one of -p and -c.` -- and exits with 1,
  and does **not** print OpenSSH's usage: that text is OpenSSH's, it
  changes from one release to the next, and a tool that prints another
  tool's usage text is a tool that lies about what it can do.

* **This tool does not check the Windows ACL of a file it reads.**  The
  real tool refuses a file with wide permissions before it looks at the
  contents, so on such a file it says what is wrong with the
  permissions; this one says what is wrong with the file.

* **This repository has ed25519 only**, so a rewrite of an RSA key is
  refused rather than done.

* **A rewritten file is made private again.**  OpenSSH writes with
  `umask(077)`, which only affects a file that is CREATED, so a file
  that was already there keeps the mode it had.  This repository is
  stricter on purpose -- see `src/keyperm` -- and a key file that other
  users can read is not a key file.

### Where the rules live

The rules live in `src/` and the driver translates them:

* `src/keyfile/rewrite.mbt` -- `private_file_text_with_passphrase`
  (an empty passphrase means an UNENCRYPTED file, and the salt and the
  check word are drawn afresh) and `comment_is_unchanged`.
* `src/keyfile/pair.mbt` -- `random_check_word`.
* `cmd/ssh_keygen/main.mbt` -- the dispatch, the two modes, and the
  messages.

**The driver asks `src/keyfile` the question and translates the
answer.**  It does not decide what a rewritten file looks like.

### The gate, the mutations, and the tests

* `host/verify_loop88.mjs` -- **106 checks**, in nine sections: the
  toolchain, the real OpenSSH being present, the byte-for-byte
  comparison (18 cases), the two-way round trip, the failures, the
  rules visible in the output, what the FILE says (which the output
  does not), the divergences, and the rules living in `src/`.

  **Both tools are pointed at the SAME file, one after the other, and
  the file is restored between the two runs.**  That matters for a
  rewrite in a way it did not for a read: a rewrite CHANGES the file,
  so the two tools cannot be pointed at two different copies without
  changing what is being compared -- the path is IN the message, and
  two files with two names have two messages.

* `host/loop88_mutations.py` -- **16 mutations**, each naming the check
  that has to go red because of it.  The check name is matched as a
  WHOLE LINE, not as a prefix.

* `src/keyfile/rewrite_test.mbt` and `src/keyfile/rewrite_rng_test.mbt`
  -- 9 tests.  **They are split by target**, because a rewrite draws a
  salt and a check word and drawing them needs an entropy source, and
  the wasm targets have none (`src/rng` says so on purpose).  The split
  is the same one `src/rng` makes for its own tests: without it,
  `moon test src/keyfile` on wasm would be a red run -- and a red run
  that means "there is no entropy here", not "the code is wrong".

### Two anchors that had drifted, and one test that could not fail

**A mutation whose anchor has drifted cannot be measured**, and the
mutation script counts it as "not caught".  So a drifted anchor is a
hole in the evidence that looks like coverage.  A scan of every
mutation script in the repository (`.loop88/scan_anchors.py`) found two
in Loop #85's, both of them left over from Loops #86 and #87:

* "the fingerprint is computed over the seed instead of the public key"
  pointed at the two lines of `fingerprint_text` that Loop #87 moved
  into `fingerprint_of_blob`.  The anchor follows the code.

* "the driver says the passphrase is unsupported and writes the key
  anyway" pointed at a REFUSAL that Loop #86 removed, because Loop #86
  gave the file a passphrase and there was nothing left to refuse.  It
  was rewritten to stand for a rule that is still there: the driver
  checks the protection the right way round.

**A test that cannot fail is not a test.**  Loop #85's test "the
encrypted file names the cipher and the KDF" ended with an assertion
that the enciphered block's length is a whole number of AES blocks --
and read that length from offset **74**, which is the low byte of the
public blob's length field and not the block's length at all.  The
assertion was true by accident: the byte it read was `0x33`, and
`0x33000000` is a multiple of 16.  The offset is **126**, and the
assertion now means what it says.

### The gate was reading the comment out of the WRONG FILE

Three of the sixteen mutations went through a green gate, and all three
were the same mistake -- **the gate read the comment out of the `.pub`
file**:

    ssh-keygen -l -f <private key>    prints the comment of the .pub FILE
    ssh-keygen -y -f <private key>    prints the comment of the PRIVATE BLOCK

`-l` goes through `sshkey_try_load_public` (authfile.c:238), which
tries `<key>.pub` first and uses it when it is there.  `-y` opens the
private key itself and prints the comment that is inside it.

**A `-p` does not touch the `.pub` file, so a `-l` cannot see anything a
`-p` wrote.**  A rewrite that dropped the comment out of the private
block left the `.pub` file exactly as it was, and the gate said PASS.
The same is true of `-c`: it writes the two files from two different
lines of the driver, so a `-c` that changed only the `.pub` file would
have looked right as well.

Measured, not assumed -- a key whose `.pub` file was rewritten by hand
with another comment:

    $ ssh-keygen -l -f k          # 256 SHA256:... public@probe (ED25519)
    $ ssh-keygen -y -f k          # ssh-ed25519 AAAA... private@probe

So the checks that ask about a comment after a rewrite ask with `-y`:

    ssh-keygen -y -P <the new passphrase> -f <key>

**A check that reads a different file from the one the code writes is
not a weak check -- it is a check of nothing.**  It passes, always, and
it looks like it is watching.  The three mutations it hid were not
subtle defects: one dropped the comment out of an enciphered rewrite,
one wrote the private file with the old comment, and one wrote the
file somewhere else entirely.

### The check name is matched WHOLE LINE, and that is not pedantry

Two of the three remaining mutations were reported as "not caught" for a
reason that had nothing to do with the code under test: the mutation
named a check that the gate does not have.

    the gate has:    the re-enciphered key is REALLY enciphered
    the mutation had: a re-enciphered key is REALLY enciphered

One word.  The matcher is a whole-line regular expression on purpose
(the gate has checks whose names start with one another's), so a name
that differs by one word does not match, and a mutation that names a
check that does not exist can never be caught.

**A mutation that names a check that does not exist is a hole that
looks like coverage**, exactly like a drifted anchor.  The check name
has to be COPIED OUT of the gate, and when the gate and the mutation
list are edited apart, the two drift.  There is now a script for that
(`.loop88/check_names88.py`) that reads the mutation list with `ast`
-- a regular expression over the source text gets the names wrong,
because half of them contain an apostrophe -- and compares them with
the names the gate actually printed.

### The rules this makes explicit

* **The output of a command is not the file it produced.**  A rewrite
  says the same three lines whether it wrote the right file or the
  wrong one.  A gate that only compares the output calls a rewrite
  that wrote an UNENCRYPTED key when it was asked to encipher one
  correct -- and so does a test that only asks "did it print the
  sentence?".

* **A file that is rewritten in place has to be READ first, and the
  two halves of the old file are not the same thing.**  The passphrase
  is in the enciphered block and the public key is in the clear; a
  rewrite that took the comment from the `.pub` file would put a
  comment in the file that was never there.

* **A tool that asks a question needs a terminal.**  Measured: the
  real tool BLOCKS without one.  The honest answer for a tool that has
  no terminal is to refuse and say what is missing.

* **A rule that is checked by a byte comparison is a rule that cannot
  drift quietly.**  Every one of the rules above was read out of the
  real tool by running it, not by reading its source and hoping.

* **A gate has to read the file the code WRITES.**  The `.pub` file and
  the private block hold the same comment right up until a rewrite
  makes them differ -- and then a check that reads the other one is a
  check of nothing.  This one cost three mutations.

## Loop #89: the SSH agent -- `ssh_agent` and `ssh_add`

Loop #80 wrote the client half of the SSH agent protocol (`src/agent`: ask
for the identity list, ask for a signature, parse the answers).  What was
missing was the other half -- the side that **holds** the keys -- and the
transport that can carry it on this platform.

    ssh_agent [--socket <pipe>] [--key <file> ...]   a daemon that holds keys
    ssh_add   [-l] [-L] [-d] [-D] [-q] [file ...]

### The transport is a NAMED PIPE, and that is not a choice

`SSH_AUTH_SOCK` on this machine is a **named pipe** (`\\.\pipe\...`), and
the real client refuses anything else without even connecting:

    $ SSH_AUTH_SOCK=127.0.0.1:1234 ssh-add -l
    Error connecting to agent: No such file or directory

The literal string `SSH_AUTH_SOCK=\\.\\pipe\\openssh-ssh-agent` is inside
the installed `ssh-add.exe`, and the installed `ssh-agent.exe` is a
**Windows service**: it says `unable to start ssh-agent service, error
:1058` and exits, and the service itself is disabled on this machine
(`sc start ssh-agent` -> `StartService FAILED 1058`).

So the judge available here is the real **client**, not the real **agent**.
That is worth saying out loud, because it decides what the gate can
claim:

* the real client is the judge for **what goes on the wire** and for
  **what the sentences and the exit statuses are**;
* the real agent is NOT available, so **the server's decisions are
  pinned by OpenSSH's rules** (`ssh-agent.c`) and by the real client's
  rendering of them -- not by a second implementation to compare with.

`src/agentpipe` is the transport: a C-FFI layer over `CreateNamedPipeW` /
`CreateFileW` / `ConnectNamedPipe` / `ReadFile` / `WriteFile`.  It is
**native only**, and the js/wasm targets get a stub that refuses
everything -- a stub that pretended to have a pipe would fail later, in
the middle of a request, with a message about the AGENT rather than about
the PLATFORM.

### The protocol is ASYMMETRIC, and that is the whole trap

Every shape below was measured by running the real `ssh-add` against a
stub agent that printed the bytes it sent
(`.loop89/probe_add_proto.py`):

    ADD_IDENTITY      (17)  135 bytes, NO outer length prefix
                         00 00 00 0b "ssh-ed25519"
                         00 00 00 20 <32 bytes of public key>
                         00 00 00 40 <64 bytes of private key>
                         00 00 00 0c probe@loop89

    REMOVE_IDENTITY   (18)   55 bytes, WITH an outer length prefix
                         00 00 00 33 <the 51-byte public key blob>

    REQUEST_IDENTITIES(11)   no payload
    REMOVE_ALL        (19)   no payload -- and the client ALSO sends the
                              v1 message (9), whose error is ignored

The asymmetry is not a typo.  The add path serializes the key field by
field (`sshkey_private_serialize`: the type name, the public key, the
private key), while the remove path writes one blob (`sshkey_puts`, which
is `sshbuf_put_string(blob)` -- **one more length prefix**).

A server that reads both the same way gets exactly one of them right, and
the one it gets wrong is the one that **works against a mock agent** --
which is the worst place to find out.

`IDENTITIES_ANSWER` is `u32 count` and then per identity **TWO** strings:
the key blob and the comment.  The first attempt sent one string per
identity, and the real tool answered `incomplete message`.

### The sentences and the exit statuses, measured

    ssh-add -l        (empty agent)   stdout "The agent has no identities."   exit 1
    ssh-add <file>                    stderr "Identity added: <path> (<comment>)"   exit 0
    ssh-add -l        (one key)       stdout "256 SHA256:<fp> <comment> (ED25519)"  exit 0
    ssh-add -L        (one key)       stdout "<pubkey line>"   exit 0
    ssh-add -d <file>                 stderr "Identity removed: <path> ED25519 (<comment>)"  exit 0
    ssh-add -D                        stderr "All identities removed."   exit 0
    (no agent)                        stderr "Error connecting to agent: No such file or directory"   exit 2
    (agent refuses)                   stderr "Could not add identity \"<path>\": agent refused operation"   exit 1

**Which stream a sentence goes to is part of the contract.**  "The agent
has no identities." is a `printf` in OpenSSH -- STDOUT -- and the exit
status is still 1.  "All identities removed." is `fprintf(stderr, ...)`.

**`-L` prints the public key line and then a SPACE and the comment.**  The
space is unconditional: OpenSSH prints the key line, then prints
`" " + comment`.  The `.pub` FILE has no trailing space when the comment
is empty, but `ssh-add -L` does.  The two are different things.

### The gate: `host/verify_loop89.mjs` (81 checks)

The gate has six parts, and each part judges something different:

* **G0** -- the tree compiles and the unit tests pass.
* **G2** -- **our client vs the real client, byte for byte**: the same
  sequence of operations, each client against **its own** agent, and the
  exit status, stdout and stderr compared byte for byte.
* **G3** -- the round trip: the real client lists and removes a key that
  our agent is holding.
* **G4** -- **the wire**: a stub agent records the request FRAMES the two
  clients put on the pipe, and the two frames are compared byte for byte.
  This is the only thing that can tell a protocol SHAPE from a sentence.
* **G5** -- **the server's decisions, rendered by the real client**.
* **G6** -- the agent can be given a key at startup (`--key`).
* **G7** -- the options this tool REFUSES, and why (see below).

### The blind spot in G2, and how G5 closes it

G2 has a hole, and it is worth naming it.

In G2 **both** clients talk to **our** agent.  So when the AGENT decides
something, both clients see the same decision and print the same thing --
and the comparison cannot tell whether that decision was RIGHT.  A server
that accepted a duplicate key would make both clients print "Identity
added", and the two would agree perfectly about a wrong answer.

**The mutations found this, not the author.**  Three of the twenty-one
mutations pass every output comparison in G2:

* the agent accepts a duplicate key;
* removing all from an empty agent fails;
* the identity list drops the comment.

G5 closes it by asking the **real client** a question whose answer only
the server can give, and checking the answer against OpenSSH's rules
(`process_add_identity` refuses a duplicate key; removing all the keys
succeeds even when there are none):

    adding a new key          -> SUCCESS
    adding the same key again -> FAILURE      <- OpenSSH refuses a duplicate
    removing a key it has not -> FAILURE
    removing all its keys     -> SUCCESS, even when it had none
    the comment it gives back -> the comment it was given
    the public key line       -> the key file's line

The sentences in G5 are measured; the DECISIONS are OpenSSH's rules.  The
gate says so, in the gate.

### The mutations: `host/loop89_mutations.py` (23, all CAUGHT)

Twenty-three mutations, each one a way this code could plausibly be wrong,
each one naming the gate check that has to go red because of it.

**Three of them caught the gate rather than the code**, and that is what
they were for:

* **the agent accepts a duplicate key** -- INVISIBLE to G2 (both clients
  talk to our agent), caught by G5.
* **removing all from an empty agent fails** -- invisible to G2 for the
  same reason, caught by G5.
* **the identity list drops the comment** -- invisible to G2, caught by
  the new G5 check that reads what the agent HOLDS.

Two more are about the **interface**, not the wire:

* **the client treats `-s` as an unknown option** and **the client calls
  a real unimplemented option an unknown one** -- both turn a fact about
  THIS TOOL into a fact about the USER.  Caught by G7.

And one of them caught the **mutation runner itself**:

* **the anchor counter keyed by basename.**  Two of the files under test
  are called `main.mbt` -- `cmd/ssh_add/main.mbt` and
  `cmd/ssh_agent/main.mbt` -- and a dict keyed by the basename has the
  second one overwrite the first.  Every anchor that lives in
  `cmd/ssh_add` came back as a **SKIP**, and a SKIP is counted as "not
  caught": eight mutations silently never ran.  The same collision was in
  the **backup**, and that one was worse -- restoring it would have put
  `cmd/ssh_agent`'s content into `cmd/ssh_add`, silently corrupting the
  tree.  Both are keyed by the PATH now.

### A CANCELLED mutation run leaves the tree mutated

The runner writes the whole file set before every mutation and restores
it in a `finally`.  **A run that is CANCELLED does not reach its
`finally`.**  That happened here: the batch was cancelled while it was
on mutation #14, and `src/keyfile/blob.mbt` was left with that mutation
applied -- which silently removed a space from the `ssh-add -L` output
and turned two gate checks red **for a reason that had nothing to do with
the code**.

The backup is on disk precisely so that this can be undone from outside
the process that wrote it, so there is now a `--restore` mode, and a
`.loop89/check_pristine89.py` that says whether the tree is what it was
before the mutations started.

**A cancelled run is not a failed run: it is a run whose measurement is
worthless AND whose tree is now wrong.**  Both halves have to be dealt
with.

### The guarded way to run mutations, and the unguarded way

The failure above was made POSSIBLE by how the run was started.  The
engine (`ci/ci.py`) already knew about this shape of accident:

    ci/ci.py --tiers mutations      # runs each harness in a throwaway
                                    # `git worktree` sandbox, so the tree
                                    # that matters is never written to

That is why the sandbox exists (Loop #40's interrupted run left
`src/channel/channel.mbt` with a swapped name/value pair).  **Running
`host/loop89_mutations.py` directly skips the sandbox and writes into the
working tree** -- which is the unguarded path, and the one that left the
space out of the `-L` line here.

Two habits come out of it, and both are cheap:

* run mutation batches through `ci/ci.py --tiers mutations`, not directly;
* when a direct run has to be interrupted anyway, run
  `python host/loop89_mutations.py --restore` before trusting anything
  else, and confirm with `.loop89/check_pristine89.py` -- **the gate
  catching it is the LAST line of defence, and it cost a full gate run
  to find out.**

### An option letter that already means something

The first version of this loop gave BOTH tools short options, and both
were wrong, because the tools are named after OpenSSH tools whose options
already exist:

    ssh-agent -s     "print sh-style env commands"   not "which socket"
    ssh-agent -a     "bind to this address"          not "load this key"
    ssh-add   -s     "add keys from a PKCS#11 card"  not "which socket"

`ssh_add -s <pipe>` meant "the agent is here".  Measured against the real
tool with OUR agent running, so the connection succeeds and the provider
is actually reached (`.loop89/probe_dash_s2.py`):

* `ssh-add -s <provider>` **BLOCKS**.  It wants a PIN, asks on the
  terminal, and with no terminal it waits -- killed at 6 s with **no
  output at all**, the same shape as `ssh-keygen -p` in Loop #88.
* `ssh-add -s` with no argument: `option requires an argument -- s`, and
  its own usage text says `ssh-add -s pkcs11`.
* `ssh-add -e <provider>`: `Could not remove card "<path>": agent
  refused operation`, exit 1.

So a tool that takes `-s` and means something else has done the worst
thing available: **`ssh-add -s pkcs11` typed at it SUCCEEDS as a no-op**,
and the user is told the card was added.

Three behaviours are possible for an option a tool does not implement,
and only one is honest:

1. take the letter and give it a different meaning -- silently wrong;
2. say "unknown option" -- a lie about the INTERFACE, since it is a real
   OpenSSH option;
3. say what the option MEANS and that this tool does not do it.

This loop now does (3), and G7 pins it:

    $ ssh_add -s provider
    ssh_add: -s is for a PKCS#11 smartcard, which this tool does not support
    (exit 1, and it does not hang)

`ssh_agent` went further and dropped short options ENTIRELY:

    $ ssh_agent -s x
    ssh_agent: no short options: every ssh-agent short option already means something else
    usage: ssh_agent [--socket <pipe>] [--key <file> ...]

and the client has no socket option at all, because **`SSH_AUTH_SOCK` is
how a client finds an agent** -- the literal string
`SSH_AUTH_SOCK=\\.\pipe\\openssh-ssh-agent` is inside the real
`ssh-add.exe`.

### What this loop is really about

* **The rules live in `src/`, and the driver only translates.**  The
  protocol lives in `src/agent` and `src/agentserver`; the file format
  lives in `src/keyfile`; `cmd/ssh_agent` owns the pipe and the loop over
  connections, and `cmd/ssh_add` owns the sentences.  Neither driver
  decides what a request MEANS.

* **A server that says "success" to something it did not do is worse
  than a server that says no.**  `AGENT_FAILURE` is a legal answer, and
  the CLIENT decides what it means -- that is why `agent_add_identity`
  returns `Bool?` and not a `Bool`: `None` is "the connection is gone",
  `Some(false)` is "the agent refused", and those two are different
  things.

* **The key's two halves have to be the same key.**  The agent checks
  that when a key is added, not when it is used: signing with a mismatched
  pair produces a signature the client cannot verify, and the client sees
  a mysterious authentication failure.  Finding it at ADD time is much
  cheaper and much clearer.

* **A comparison between two things that are both yours cannot check
  your server.**  That is the G2 hole, and it is worth remembering for
  every other "ours vs theirs" gate in this repository: when both sides
  are the code under test, the comparison checks the CLIENT and says
  nothing about the SERVER.

* **The real tool is the judge, and the real tool is not always
  available.**  Here the real CLIENT was available and the real AGENT was
  not -- and the honest thing is to say which is which, rather than to
  write a gate that quietly claims more than it checked.

* **A named pipe's two ends have to be in two processes.**  The client
  BLOCKS in `CreateFile` until the server calls `ConnectNamedPipe`, and
  the server BLOCKS in `ConnectNamedPipe` until a client connects -- and
  MoonBit's `async` is a single-threaded cooperative scheduler, so a
  blocking C call in it blocks the whole program.  So the round trip is
  **not** a unit test here: it is tested in the gate, which runs the
  agent and the client as two processes, which is how the real tools use
  it anyway.  The unit test covers the parts a single process CAN
  check -- and those are exactly the parts where a wrong answer is a
  hang.

## Loop #90: `scp` -- and `-D` as the cheapest honest oracle

`scp` since OpenSSH 9.0 speaks SFTP, so this loop is `src/sftpdrive` (an
interactive client: one request, look at the answer, decide) plus
`src/scp` (the rules and a copy engine written over an abstract local
filesystem) plus `cmd/scp`.  `src/subproc` exists because of the oracle
below.

**`scp -D <program>` runs the named program and speaks SFTP over its
stdio.**  Pointed at the local `OpenSSH-Win64\sftp-server.exe` that is a
full-duplex copy with **no network, no sshd and no key material** -- the
cheapest comparison this repository has, and the reason this loop could be
gated byte for byte at all.  Three traps, all measured:

  * **A single-letter host is a DRIVE LETTER.**  `scp a.txt h:/out.txt`
    answers `The system cannot find the drive specified.` -- `is_remote()`
    on the Windows port refuses `X:` as a host.  Use a multi-character
    name.
  * **An absolute remote path ESCAPES the working tree.**  `realpath("/")`
    on the Windows server answers exactly `/`, i.e. the current drive's
    root.  Every remote path in the bed is relative, and scp and the
    server share one cwd.
  * `-D` passes the path as one argv element, so a path with a space works.

**The sentences come from the STATUS CODE, not from the peer's text.**  For
a missing file the local server sends `No such file` while the real tool
prints `No such file or directory` (`ENOENT`'s text).  `SSH_FX_FAILURE`
keeps the peer's own `Failure`.  A client that passes the peer's message
through is wrong on the first row and right on the second, which is the
worst kind of wrong.

**Every failure is one line or two, and the split is not symmetric.**
Upload: `dest open "x": ...` **then** `failed to upload file a to b`.  A
top-level download: `open local "x": ...` and **nothing else**.  Inside a
recursive download: `open local "x": ...` then
`Download of file <absolute> to <y> failed`, once per child, and the walk
**keeps going**.  Getting these symmetric is the natural mistake.

**A multi-source destination is treated differently on the two sides.**  A
local target that is missing or is a file is refused through `perror`
(`local/out: No such file or directory`, **no `argv[0]: ` prefix**, exit 1)
and nothing is copied; a **remote** target is `mkdir`'ed -- and a refusal
there is `fatal()` at **255**.  And the mkdir happens **per source, after
that source has been stat'ed**: two sources that do not exist leave no
directory behind.  This loop's first version created it in a pre-flight and
the gate caught the leftover empty directory.

**`-p` preserves DIRECTORY times too, on both sides**, and a directory's
time is written **after** its children -- writing a child moves the
parent's mtime.

**`eprintln` text-translates the whole string.**  Measured:
`eprintln("A\nB")` emits `A\r\nB\r\n`.  That cannot express the `-P`
refusal, whose embedded newline the real tool writes raw and which is
captured as `bad port "0"\n\r\n` -- so the driver builds its bytes and
writes them through a raw fd (`mb_scp_emit`), with `text_crlf` doing the
conversion once.

### Two lessons about gates, both from this loop

**A gate can be green and empty.**  The first version of
`host/verify_loop90.mjs` rebuilt the fixture before *each* side, which
erased the files the scenario was about: 17 of 20 comparisons were two
identical failures "passing".  The gate now builds the fixture once per
side and carries a **non-vacuity** assertion -- a transfer must leave a
named file on the real side, a refusal must have printed something.

**A mutation's verdict order matters.**  `host/loop90_mutations.py` first
treated a failing unit test as "did not build", which mislabelled six good
mutations as INVALID: a mutation aimed at a rule the unit tests already pin
turns the tests red *and* the gate red, and the verdict went to whichever
marker matched first.  Consult the **named gate check** first, then the
build check, then call it missed.  Result: 10 mutations, 10 caught, 0
missed.

## Loop #91: the private key FILE, and `scp` over a real sshd

Loop #90's two declared gaps, one of them closed.  The gap was: a real `scp`
signs with a private key **file**, and `src/keyfile` could read only
ed25519.  So this loop is `src/keyfile` (an ECDSA reader) plus
`src/sshclient` (an interactive subsystem link) plus `cmd/scp`'s SSH leg.

**`live_auth` already signed ECDSA P-256.**  `live.mbt:1228` builds the
`userauth` request with `@ecdsa.Curve::p256()` and a scalar the caller
supplies; nothing about the client needed teaching.  What was missing was
that the scalar lived in a test constant rather than in a file.  Measuring
this first is what kept the loop small.

### Two beliefs this loop measured and found wrong

Both were in this repository, and neither could be seen before ECDSA
existed, because **an ed25519 public blob is 51 bytes -- a whole multiple of
three -- so its base64 has no `=` to strip and no way to notice.**

  * **The `authorized_keys` line KEEPS its base64 padding.**  `encode.mbt`
    said OpenSSH strips it (citing `sshbuf_dtourlb64`) and called
    `strip_padding`.  Measured: a P-256 blob is 104 bytes and
    `ssh-keygen -y` prints `...YJk/dc=`, and the `.pub` file the tool wrote
    at key creation holds the `= ` too.  The strip remains correct for
    **fingerprints** (`SHA256:` really is 43 characters for a 32-byte
    digest) -- two different rules, not an inconsistency.
  * **`ssh-keygen -y` output ends with CRLF and carries exactly ONE
    newline.**  `encode_public_line_of` returns the FILE form, so passing
    it to `println` produced two.  Caught only by comparing bytes; a trimmed
    comparison would have called it equal.

### The ECDSA private block, and the three traps

`type | curve_id | Q | d | comment | padding` -- the trap is that ed25519
has no `curve_id`, so a reader that copies the ed25519 shape reads
`nistp256`(8) as the point and the point(65) as the scalar.  Both lengths
look plausible and nothing fails until a signature is wrong.  That is what
the first walk did.

  * **`d` is an `mpint`.**  A scalar whose top bit is set carries a leading
    `00`.  Measured fixtures: P-256 ordinary `d` = 32 bytes, P-384 `d` = 49
    with `00`, P-256-above-2^255 `d` = 33 with `00`.
  * **P-521's `d` is 66 bytes and starts with `01`** -- a real bit of a
    521-bit number, not a sign byte, so the strip must not fire on it.  Its
    point is 133 bytes (521 bits is 66 bytes with seven bits unused), and a
    reader that rounds to 64 rejects every P-521 key.
  * **P-521's padding is EMPTY**, because its block happens to be a whole
    number of 8-byte words.  A reader that insists on at least one padding
    byte rejects every fifth P-521 key.

The three curve names `nistp256` / `nistp384` / `nistp521` are the **same
length**, so they must be compared as strings, never by width.

### The interactive link (`src/sshclient/link.mbt`)

The same four steps `run_sftp_session` takes, stopping after the subsystem
confirmation and handing back `write`/`read`, because `scp` must read an
answer before choosing the next request.  Two things that are easy to get
wrong:

  * **A write may have to read.**  `stdin_take` clamps to the peer's window;
    when it is exhausted the only way forward is to receive, and data that
    arrives during a write must be **buffered**, not dropped.
  * **End of stream is an empty array, not an error** -- that is the
    contract `src/sftpdrive` already reads.

`live_auth_curve_with_state` splits the curve out of the auth path: the
curve is a property of the KEY FILE.  A P-384 key that signs as P-256 is
refused by the server as the wrong key type, which reads like an
authorization failure and is not one.

### What the bed cost, measured

  * **A private sshd spawned as a plain (non-elevated) user works on this
    machine.**  That was the real risk -- Win32-OpenSSH normally runs as a
    service in order to impersonate the login user -- and `sshd -D -e -f
    <conf>` serves the user that started it.
  * **Absolute remote paths work with both tools**: `hp@host:/E:/.../x`.
    The bed's "remote" side is a directory on this machine, so a relative
    remote path would resolve against the login user's home and the gate
    would write outside its own bed.
  * **PowerShell cannot pipe a script into `sftp -b -`**: the pipe prepends
    a UTF-8 BOM and the client answers `Invalid command`.  Write a batch
    FILE.
  * The gate keeps the sshd directory and `known_hosts` **outside** the bed
    it wipes between cases.  The first version put them inside and every
    comparison failed with `kex_exchange_identification: read: Connection
    reset` -- a deleted host key, reading like a protocol problem.

### The weakness the gate had, and how it was found

Section A compares `ssh-keygen -y`, whose output is built from the public
**point**.  So a reader that takes the wrong bytes out of `d` prints the
right line and passes every `-y` check: **the scalar is only observable in a
signature.**  Same for the curve.  The gate therefore signs two real copies,
one with the top-bit-set key and one with the P-384 key, and a wrong scalar
or a wrong curve turns THOSE red.  Without them, mutations #0 and #1 would
have been MISSED while every `-y` check stayed green.

`host/verify_loop91.mjs`: 23/23.  `host/loop91_mutations.py`: 6 mutations,
6 caught, 0 missed, 0 invalid, 0 skipped.

The standing gates after this loop, all green:

    loop67   8/8     (CJK snapshot re-saved; the diff is only this loop's
                      intentional additions -- 248 files, 17629 runs)
    loop68  57/57
    loop71   9/9     (949 files scanned, 0 machine-path hits)
    loop90  41/41
    loop91  23/23

**loop71 was red at Loop #90's own commit and nobody knew**: `4fe5544`
checked out into a worktree and run there reports 8/9, with
`verify_loop90.mjs` asserting `C:\Windows\System32\OpenSSH\scp.exe`.  Both
gates now declare a candidate list and probe it -- per binary, in the order
each loop's measurements were taken with, because a machine holding both
OpenSSH installations must resolve to what the measurements used or a green
gate stops meaning what it meant.  Note the marker's limit: `EXEMPT_WINDOW`
is 12 lines, and the failure says the file and the distance ("13 line(s)
below its machine-path-exempt marker"), which is why it was a one-read fix.


### `moon check --deny-warn` reports unused values per FILE, resolves per PACKAGE

`src/keyfile` had two `unused_value` errors at HEAD (`test_seed`,
`blob_of`), verified at HEAD in a worktree so they were not new.  They are
not dead: `rewrite_rng_test.mbt` calls them.  A test helper defined in one
file and called only from a sibling is reported unused, while helpers also
called in their own file (`hex_of`, `slice`, `u32_at`) are not.  The fix is
to move a helper into the file that uses it -- not to delete working code
because a warning named it.

## Loop #92: `sftp-server` -- the server half of SFTP

`src/sftp` is the client: it builds requests and parses replies.  This loop
built the **mirror** -- `src/sftpserver` parses requests and builds replies --
and `cmd/sftp_server` is the driver that speaks it over standard input and
output.  That is the same program `sshd` runs for the `sftp` subsystem, and
the same one `scp -D <program>` runs to speak SFTP over a pipe.

**The wire format keeps ONE implementation.**  The cursor, the string
encoders, the attrs encoder and the framing are all `src/sftp`'s; this
package adds only the direction that did not exist.  The same argument
`src/sftpdrive` made one layer up.

The rules live in `src/sftpserver` and the filesystem behind them is an
**interface** (`ServerFs`, a bundle of fifteen function values), the same
move `src/scp` made with `LocalFs`.  So the state machine can be asked for
things a real disk cannot be asked for -- a directory with 250 entries, a
read-only file, a path that is not there -- and every answer can be
compared against the bytes the real server sent for the same situation.
`src/sftpserver/*_test.mbt` does that on **all four targets**: 42 tests,
green on native, js, wasm and wasm-gc.

### The oracle: the real `sftp-server.exe`, byte for byte

`host/verify_loop92.mjs` sends the SAME requests to two servers -- the real
`sftp-server.exe` on this machine and ours -- and compares the replies
**byte for byte**, plus the tree that is left on the disk.  Comparing two
servers against each other is the only way to see the differences that
matter: a reply can be "correct" in isolation and still differ from the one
a real client is written against.

Two things about the bed are load-bearing:

  * **The times are pinned.**  A STAT reply carries the file's access time,
    and the first server to read the file can change it -- which would make
    the second server's answer differ for a reason that has nothing to do
    with behaviour.  Every file AND every directory is stamped with the
    same instant before EACH server runs.  The directories are stamped last
    and bottom up, because writing a file inside a directory changes that
    directory's own time.
  * **Every case opens with INIT.**  The real server waits for it before it
    answers anything at all, so a case that started with a STAT would see
    the real server answer nothing -- which is correct behaviour and would
    look like a difference in every later reply.

### What was measured, and what it cost to get wrong

| the fact | the number | where it came from |
|---|---|---|
| VERSION carries six extensions, not eleven | 179 bytes | `probe2.py` |
| the STATUS sentences are a closed set | seven | `probe3.py`, `probe6.py`, `probe10.py` |
| a handle is a SLOT, not a counter | 0, 1, then 0 again | `probe8.py` |
| a listing is cut into batches of a hundred | 100, 100, 50 | `probe8.py` |
| an enumeration ends with STATUS EOF, not an empty NAME | 1 | `probe_out.txt` |
| a READ never returns more than 65536 bytes | 65536 | `probe3.py` |
| an unknown request TYPE gets NO reply | silence | `probe3.py` |
| an unknown EXTENSION is refused | 8 | `probe3.py` |
| the date column changes form at an age of 15768000 s | half a year | `probe5.py` |
| the size column is `%8llu` and GROWS | 123456789 shifts the date | `probe2.py` |
| a directory's size is the filesystem's own number | 0, 0, 4096, 24576 | `probe_dirsize2.py` |

The date rule was checked against **all 23 recorded longname lines** before
it was written down (`.loop92/longname_rule.py` replays them and compares),
so what went into the code is the rule and not one lucky example.

### The four defects the gate found

They are the reason the gate exists, and none of them would have been found
by a unit test that only checked its own ideas.

  1. **The `longname` had SEVEN spaces too few** between the group column
     and the size.  Every listing differed by seven characters per line.
     The layout is `mode(10) + "    1" + " -        -" + EIGHT spaces +
     size(%8llu) + " " + date(12) + " " + name`, and the eight spaces are
     the gap the `ls -l` layout leaves for a group column wide enough to
     hold a name.

  2. **The permission word's "other" field is the access control list's.**
     A writable file answers `0o100600` under the temp directory and
     `0o100607` under `E:\` -- the same file, and the difference is exactly
     the "other" field.  `.loop92/probe_acl2.py` grants ONE ACE per
     directory and reads the number back:

         | the ACL says | the "other" field |
         |---|---|
         | `Everyone:(M)` | 7 |
         | `Everyone:(GR,GE)` | 5 |
         | `Authenticated Users:(M)` | 7 |
         | `Authenticated Users:(GR,GE)` | 5 |
         | `BUILTIN\Users:(M)` | 0 |
         | `BUILTIN\Users:(RX)` | 0 |
         | nothing | 0 |

     Two things are worth noticing: the rights that count are the GENERIC
     ones (an ACE granted the specific `(RX)` moved nothing), and only the
     two classes that stand for EVERYBODY count -- not the groups the user
     happens to be in.  A read-only file has the write bit taken off the
     ACL's answer.  `localfs.c` reads the ACL with
     `GetNamedSecurityInfoW` and `advapi32`; `FSTAT` does **not** consult
     it (it repeats the owner's bits into the group and other columns, and
     answers `0o100666` in both directories).

  3. **A directory's size is the FILESYSTEM's number, and it is not a
     constant.**  Measured with the real server, a directory with 0, 1, 16
     and 120 entries answers 0, 0, 4096 and 24576 -- the NTFS index, in
     4096-byte clusters.  An early note in this loop said "a directory is
     4096", because the one directory it happened to measure had 16
     entries in it.  The rule is "whatever the platform says", and the
     platform's number is what `GetFileAttributesExW` already returns.

  4. **`localfs.c` had never been compiled.**  `moon check` does NOT build
     the native stub -- only `moon test` and `moon build` do -- so a file
     with a struct type that does not exist (`WIN32_FILE_ATTRIBUTE_DATA`
     has no `cFileName`) and an uninitialised pointer in it sat there
     green.  **A package that has C in it must be built, not checked.**

Two more things the gate turned up that are worth keeping in mind:

  * **The session must not invent handle numbers.**  The first version
    allocated a slot of its own and ignored the filesystem's number, which
    meant the reply could say one number and the table look up another.
    The handle number IS the filesystem's, and the session records what it
    was given.
  * **The protocol requires INIT first.**  A server that answers a STAT
    without it is answering a question nobody asked.

### The gate, the mutations, and the tests

`host/verify_loop92.mjs` is **30 checks**.  `host/loop92_mutations.py` is
**12 mutations**, and each one has to turn a NAMED check red: the name is
matched as a whole line, and the named check is consulted before anything
else, so a mutation that breaks the build is INVALID rather than MISSED.

`src/sftpserver/*_test.mbt` is **42 tests**, green on native, js, wasm and
wasm-gc.  The tests pin the rules; the gate proves the rules are the real
server's rules; the mutations prove the gate can tell the difference.

### The mutation that found the gate's own hole

The first run of the mutations had TEN of them, and one of the ten did NOT
turn the gate red.  That one was worth more than the nine that did.

The mutation changed the permission word FSTAT reports for a **read-only**
file -- 33060 instead of 33024 -- and the gate stayed green.  The reason is
that no case FSTATed a read-only file: every one of them opened `a.txt`,
which is writable.  The rule had two branches and the gate had only ever
asked about one of them.

The same hole was in the STAT case, which asked about a writable file only.
So the read-only base (33024 against 33152) was unasked, and so was the
rule that takes the write bit off the ACL's answer for a read-only file
(`other_bits & 5`).

Two cases were added -- a STAT of the read-only file and an FSTAT of it --
and two more mutations with them, aimed at exactly the branches that had no
cover.  The list is twelve now, and all twelve are caught.  **A gate that
cannot fail is not a gate**, and this one could not fail until somebody
asked it the question it had no answer to.

### The standing gates caught three things this loop did not

Loop #92 added a package, and the gates that already existed had opinions
about it.  All three findings are the kind that no unit test can make:

  * **loop67**: `src/sftpserver/localfs.c` was in the working tree with
    CRLF.  The repository's rule is LF -- `* text=auto eol=lf` in
    `.gitattributes` -- and the gate reads every tracked file, with no
    extension filter, because a CRLF file reads as a whole-file
    delete-and-re-add diff.  The committed content was already LF; only the
    working copy was not.  **The commit was right and the tree was wrong**,
    which is the shape of defect that a `git status` will not show you.

  * **loop71**: two files named a machine path.  One was a comment that
    mentioned the drive the bed sits on; the other was a test that pins the
    server's path SPELLING (`/C:/...`, a slash before the drive letter).
    The spelling is the protocol's, not this machine's, so it was assembled
    from pieces rather than written out -- the shape is kept and the claim
    is not.

  * **loop68**: `host/cov_reportable.json` is a committed measurement of
    which packages the toolchain can produce a coverage report for, and a
    package with tests is one the toolchain *can* instrument.  A new
    package with tests therefore makes that file stale the moment it lands,
    and the gate re-derives the set and compares.  The file is regenerated,
    not edited by hand: `python host/cov_probe.py --json
    host/cov_reportable.json`.

    Regenerating it turned up a second staleness the gate could not see:
    the gate compares the **set** of reportable packages, and every package
    in the set was in the set before, so it said nothing.  The file also
    carries each package's row -- how many uncovered lines, how many files,
    which test files -- and `src/keyfile`'s row was left over from before
    Loop #91 added five test files to it (58 uncovered lines in 5 files,
    where the toolchain now measures 111 in 8).  **A gate that compares a
    set cannot notice that a row inside it moved.**

The rule that comes out of this: **a package is not finished when its own
tests are green.**  It is finished when the gates that already existed
still say so.

### The rules in one place

`src/sftpserver/proto.mbt` is the wire format, `session.mbt` is the rules
(which request produces which reply), `longname.mbt` is the `ls -l` line,
and `localfs.c` is the only platform code.  `cmd/sftp_server` decides
nothing: it frames requests off standard input and writes the replies back,
and it is native only because it reads and writes a file descriptor.

`posix-rename@openssh.com` is implemented because the real server
implements it -- and it REPLACES the target, which the draft's `FXP_RENAME`
refuses to do (`4 Failure` for the same pair of files).  The other five
extensions the real server advertises are not implemented, and an
extension this server does not know answers `8 Operation unsupported`,
which is a different thing from an unknown request TYPE, which gets no
reply at all.

## Loop #93: `sshd` -- the server half of SSH

`src/sshclient` is the client: it dials out, it proposes, it verifies the other
side's signature.  This loop built the **mirror** -- `src/sshd` listens, it
answers, it is the one whose host key gets signed -- and `cmd/sshd` is the
driver that accepts a socket and runs the state machine.

The slice is the whole handshake up to a **publickey authentication**:

    1. the identification exchange,
    2. the key exchange, in the SERVER role,
    3. the switch to the encrypted transport,
    4. `ssh-userauth` service negotiation,
    5. the `publickey` method, with the client's signature verified.

The connection protocol -- channels, `exec`, `shell`, `subsystem` -- is the
NEXT loop.  It is not a detail that was skipped: it is a different protocol
(RFC 4254) whose every rule is expressed in terms of a session that has to
exist first.  What this loop owes the peer in the meantime is a refusal it can
read, and that refusal is checked byte for byte (see below).

### The oracle: the real `ssh.exe`, and its own words

A server is not right because it agrees with us -- it is right when a real
client believes it.  So the oracle here is the OpenSSH client on this
machine, and the verdict is **the client's own sentence**:

    Authenticated to 127.0.0.1 ([127.0.0.1]:22321) using "publickey".

That one line says the client verified our host key's signature over the
exchange hash, switched to the encrypted transport, negotiated `ssh-userauth`,
and checked the signature over the session identifier.  Every one of those is
a thing the server has to get right, and the gate reads the client's sentence
rather than the server's opinion of itself.

The failure modes this catches are the ones a self-check cannot: **a reply
that is well formed but framed wrongly is refused by the peer**, and the peer
says so.  Two of the three defects below were exactly that.

### What was measured, and how

`host/ssh_recorder.py` is a recording TCP proxy.  Put in front of a real
`sshd -D`, it records the plaintext part of a session -- everything up to
NEWKEYS -- and that is the whole of what a server has to get byte-for-byte
right before anything is encrypted.  It is deliberately dumb: it forwards
bytes and writes them down, because a proxy that understood SSH would be a
second implementation of SSH, and its understanding would be the thing under
test.

| the fact | the number | where it came from |
|---|---|---|
| the real sshd proposes group14 + ed25519 + aes128-ctr + hmac-sha2-256 | one set | the recorder in front of a real `sshd -D` |
| the real sshd does **not** offer strict-kex | absent | the same capture |
| `KEX_ECDH_REPLY` is three strings | `string(K_S) string(Q_S) string(sig)` | the same capture |
| `K_S` is `string("ssh-ed25519") + string(pub32)` | 51 bytes | the same capture |
| the signature field is `string(string(alg) + string(sig64))` | **87 bytes on the wire** | the same capture |
| the signature blob is `string("ssh-ed25519") + string(64)` | 83 bytes | the same capture |
| `Q_S` is an mpint, leading zero included | 4 + N | the same capture |
| the client's `CHANNEL_OPEN` is **four** fields | 23 bytes | our server, with the real client |
| there is **no** `string sender channel` in `CHANNEL_OPEN` | absent | the same |
| `CHANNEL_OPEN_FAILURE` is **four** fields | `u32 u32 string string` | RFC 4254 §5.4, and the client's own answer |

The algorithms are not a preference: they are what the real `sshd` and the
real client negotiated, and they are what this repository's own client
already speaks, so the server's transcript can be compared field by field
with the real server's.  `curve25519-sha256` would also work -- the
primitives are in the tree (`src/kexc25519`) -- but choosing it would mean the
comparison could no longer be made, and a comparison that cannot be made is a
claim that cannot be checked.

The server's proposal lives in `src/kexflow` (`Proposal::default_server`),
not in `src/sshd`: the proposal is the KEX's own business, and a server that
had to import the client's proposal would put the two halves of one protocol
in two packages that cannot see each other's tables.

### The three defects the real client found

None of them would have been found by a unit test that only checked its own
ideas, because in all three the server produced a **perfectly well-formed
message that the peer refused to read**.

  1. **The signature field was missing one layer of `string`.**  The reply's
     third field is a string whose CONTENT is the signature blob, so the blob
     is wrapped in a string ONE more time.  Written unwrapped, the bytes were
     the same 83 bytes of content with a different framing -- `u32(11)
     "ssh-ed25519" || u32(64) || sig` instead of `u32(83) || u32(11)
     "ssh-ed25519" || u32(64) || sig`.  The peer read an **11-byte
     "signature"**, found 68 bytes it did not expect, and said
     `unexpected bytes remain after decoding`.  It never sent NEWKEYS, so the
     server's own failure was `no_newkeys` -- a symptom that pointed at the
     wrong place entirely.

  2. **The `CHANNEL_OPEN` was read with one `string` too many.**  The payload
     is four fields -- `string type || u32 sender channel || u32 window ||
     u32 max packet` -- and there is **no** `string sender channel` between
     the type and the number.  Reading one took the **window size** for the
     channel number, so the refusal was addressed to channel 2097152 and the
     client answered `open failure packet referred to nonexistent channel
     2097152`.  The repository's own client (`src/channel`, which talks to
     the real sshd every day) builds the same four fields; the RFC's fifth
     field is not what the implementations send.

  3. **The `CHANNEL_OPEN_FAILURE` left out the language tag.**  The payload is
     `uint32 recipient || uint32 reason || string description || string
     language tag` -- FOUR fields.  Three leave the peer reading the next
     packet's bytes as the tag.

The first of the three is the reason `host/verify_loop93.mjs` also records
the handshake and checks the **shape** of the reply against the shape the
real sshd was measured to send: a whole-handshake verdict cannot say WHICH
message was wrong.

### The two holes the mutation suite found

The first run of the thirteen mutations caught **eleven**.  The two it did not
catch were worth more than the eleven it did, because both of them were holes
in the GATE -- a check that could not fail, and a rule the gate could not see.

  1. **"The client verified our host key" could not fail.**  The check
     looked for the client's `Server host key: ssh-ed25519 SHA256:...` line.
     But OpenSSH prints that line **before** it verifies the signature over
     the exchange hash, so a server that signs nothing at all still produced
     the line, and the check stayed green while the client was aborting with
     `incorrect signature`.  The check now also asserts that the client did
     **not** say `incorrect signature` -- the client's own sentence, measured
     with the signature zeroed, not guessed.

  2. **The authorized-keys rule was written TWICE.**  The probe
     (`key_is_authorized`) and the signed request (`verify_publickey`) each
     had their own comparison of the key blob against the list.  The real
     client ALWAYS sends the probe first, so breaking only the signed
     request's comparison left the probe's refusal standing, and breaking
     only the probe's comparison left the signed request's refusal standing.
     **Neither half of the rule was visible to the gate.**  The rule is
     written once now -- `key_authorized` -- and called from both, and the
     mutation that breaks it turns the gate red.

The second one is the general shape: **a rule that is written twice is a rule
that can be broken in a way nobody notices**, and the mutation suite is
exactly the place where that shows up.  The first one is the other shape: **a
check that greps for a line the peer prints BEFORE the thing it claims to
check has been checked.**

### The rules in one place

`src/sshd/kexserver.mbt` is the key exchange in the server role,
`authserver.mbt` is the `publickey` method and the authorized keys, `wire.mbt`
is moving packets, and `server.mbt` is the state machine that decides what
happens in what order.  `cmd/sshd` decides nothing about SSH: it listens,
reads the host key and the authorized keys, and hands the connection over.

Three rules were worth writing down because they are easy to get backwards:

  * **The two directions are the client's names with the roles swapped.**
    What the server SENDS uses the `stoc` key and what it RECEIVES uses the
    `ctos` key.  Getting that backwards does not fail loudly -- it decrypts
    the peer's stream into noise and the MAC does not verify, which reads as
    "the peer sent garbage".
  * **The authorized keys are consulted BEFORE the signature is looked at.**
    The other order turns "you do not have access" into "your signature is
    bad", which is a different and misleading answer -- and it does wasted
    work on every unauthorized key.
  * **A key with OPTIONS in `authorized_keys` is REFUSED.**  This server does
    not implement `command=` or `no-pty`, and a key whose restrictions it
    will not enforce is a key whose restrictions are silently dropped.

### The gate, the mutations, and the tests

`host/verify_loop93.mjs` is **28 checks**.  `host/loop93_mutations.py` is
**13 mutations**, and each one has to turn a NAMED check red: the name is
matched as a whole line, and the named check is consulted before anything
else, so a mutation that breaks the build is INVALID rather than MISSED.
Three of the thirteen are the defects above, reproduced exactly.

`src/sshd/sshd_test.mbt` is **15 tests**, green on native, js, wasm and
wasm-gc.  The framing ones are written against the bytes the real sshd was
measured to send -- the reply's signature field is 83 bytes and the blob
inside it has no trailing bytes, the channel number is the sender channel and
not the window size.

### The CI was red before this loop, and the reason was a warning on stderr

The GitHub Actions run on Loop #92's commit (`16183b3`) was **red**: 59 of 66
steps, with seven gates failing.  None of them was caused by Loop #93 -- they
were red already -- and the reason is worth writing down, because it is the
third time this repository has been broken by a claim about a machine instead
of a claim about the code.

**1. A build warning went into the output a hash was computed over.**
`host/verify_loop80.mjs` pins the output of seven `moon run` programs by
sha256, and its `moon()` helper hashes `stdout + stderr` together.  `moon`
writes its warnings to **stderr**, and Loop #90 added `cmd/scp`, whose
`moon.pkg` imports `src/scp` -- the same name as the package itself.  moon
answers that with

    Warning: Duplicate alias `scp` at "...\cmd\scp\moon.pkg".

so the warning text went into the hash.  **All seven baselines stopped
matching.**  Measured, to be sure of the direction: the stdout alone hashes
to exactly the recorded baseline (`1bbbc364fb3d5e51` for `u128_test`), and
stdout+stderr does not.  The fix is the alias:

    import { "riantr/moonbit_openssh/src/scp" @scplib, ... }

and `cmd/sshd` does the same with `@sshdsrv`, because `src/sshd` has the same
name as `cmd/sshd`.  **A package that imports a package with its own name
makes moon warn on every build in the workspace**, and the warning is on
stderr, so any gate that hashes a command's combined output inherits it.
Loop #80, 82, 83, 84 and 85 were all red for this one reason.

**2. A gate read files that nothing in the repository made.**
`host/verify_loop91.mjs` reads four private key fixtures from `.loop91/`.
They were made by hand, by a probe script that was never committed, and
`.loop*/` is gitignored -- so the gate was green on the machine that wrote
it and **crashed with ENOENT** on a fresh clone.  The fixtures are now made
by `host/loop91_fixtures.py`, which is in the repository, and the gate calls
it.  The `mpint/k0` fixture needs a P-256 key whose scalar is **above
2^255**, so the script SEARCHES for one (measured: 3 keys on this machine;
the bound is 60) rather than assuming one exists.  And the gate does not
take the script's word for it: it parses the private key itself, with a
second implementation of the OPENSSH PRIVATE KEY format, and asserts the
scalar is 33 bytes starting `00`.  A gate that believes the maker is a gate
that believes a comment.

**3. A gate compared bytes that belong to the server's version.**
`host/verify_loop92.mjs` compares our SFTP server with the real
`sftp-server.exe` reply by reply, byte for byte -- and **every case starts
with an INIT**, so reply 0 of every case is the INIT reply.  The INIT
reply's extension list is not the protocol's; it is the server's, and it
changes with the server's version.  Measured with the real tool on two
machines:

| the real server | bytes | the extension list |
|---|---|---|
| OpenSSH 7.9p1 (this machine) | 179 | `statvfs` "2", `fstatvfs` "2" |
| the inbox Windows OpenSSH (the runner) | 250 | `statvfs` "2", and `limits`, `expand-path`, `copy-data`, `home-directory` |

One difference -- the extension list -- turned **every** case red on the
runner, and none of it is our bug: it is a newer OpenSSH.  The INIT reply
is now judged by RULES: the protocol version is the same, every extension
we IMPLEMENT is one the real server also declares, and every extension we
declare is in our contract.  The rules and their evidence are in
`host/loop92_init_rule.mjs` and `host/loop92_init_replies.json` -- **both
sets of real bytes are in the repository**, so the rule is checked against
both machines' OpenSSH on every run -- and three negative controls say the
rule can still go red (drop an implemented extension, change the version,
implement something the peer lacks).  The rule is deliberately
one-directional: the real server declaring extensions we do not have is not
our bug, and a server is not obliged to have what a newer peer has.

The general shape is the same one Loop #69 found in
`host/sshd_setup.mjs`: **a claim about the machine is not a rule.**  Three
versions of it, three fixes, and the fix each time is to put the machine's
part into the repository -- the alias, the fixture script, the two sets of
INIT bytes.

### And the fixture that was made by hand hid a real bug for two loops

The fixture script is not only a fix for the ENOENT.  Making the keys
**fresh on every run** turned a fixture that had been pinned to one lucky
key into a generator, and the generator found a defect that the pinned
fixture had been hiding for two loops.

`src/keyfile` checked the ECDSA scalar's length like this:

    if d.length() > ecdsa_scalar_max(curve) || d.length() == 0 ||
       d.length() < ecdsa_scalar_max(curve) - 1

and `ecdsa_scalar_max` is `point_width / 2 + 1`, so for P-521 it accepted
**66 or 67** bytes and nothing else.  But an `mpint` is stored minimally:
leading zeros are stripped, and a `00` is put back only when the top bit
of the first byte is set.  P-521's order starts `01`, so a scalar below
2^520 has a `00` as the first byte of its 66-byte form -- that `00` is not
a sign byte (the number is positive), so it is stripped, and the file
stores **65** bytes.  The reader called such a file malformed.

| curve | the number | the stored length can be | the reader accepted |
|---|---|---|---|
| P-256 | 32 bytes | 32 | 32 |
| P-384 | 48 bytes | 48 | 48 |
| P-521 | 66 bytes | **65**, 66, 67 | 66, 67 |

So the reader refused **one ECDSA key in 256** -- the ones whose scalar's
top byte came out zero -- and the real `ssh-keygen -y` read every one of
them.  The check is now `1 .. width` bytes, with the upper bound still
there, because a scalar longer than the curve's width is not a scalar of
that curve; a TRUNCATED file is caught by the check words and the
padding, which are what say whether the block is a whole one.

Two things are worth saying about how it was found:

* **The pinned fixture was the reason it survived.**  The hand-made
  `.loop91/k521` was one of the other 255, so the gate was green and the
  reader was wrong, and both were true at the same time.  A fixture that
  is regenerated is a fixture that cannot keep its luck.
* **The new test was mutation-checked.**  Putting the old check back
  makes `a_p521_scalar_of_65_bytes_reads_and_the_line_is_the_one_openssh_prints`
  fail by name -- so the test has cover, rather than merely passing.

The fix is in `src/keyfile/ecdsa.mbt`, the test in
`src/keyfile/ecdsa_test.mbt` (57 tests, green on all four targets), and
the shape is written down in `ecdsa_scalar_width`'s doc comment, because
"the scalar's length is a range and not a number" is the kind of rule
that is re-derived wrongly otherwise.

### The rule that comes out of all three

**A gate must measure the thing it claims, on the machine it runs on, and
nothing else.**  Each of the three failures above was a gate that measured
something adjacent:

| the gate measured | what it claimed |
|---|---|
| a hash of `stdout + stderr` | "the program's output has not changed" |
| "the file exists" | "the fixture is the one the case is about" |
| the INIT reply, byte for byte | "our server agrees with the real one" |
| the scalar's length, as one number | "this is an ECDSA scalar" |

The fix in each case is to make the measurement narrower and the evidence
wider:

* hash **stdout only**, because stderr belongs to the toolchain, not to the
  program -- and put the toolchain's own warnings out of the way (the
  alias) rather than filtering them out of the hash, because a filter is
  another rule that can be wrong;
* have the gate **make** its fixture, and **parse it itself** to check it
  is the shape the case is about, because a gate that trusts the maker
  trusts a comment;
* judge the reply by **rules that are about us** (the protocol version; the
  extensions we implement) rather than by bytes that belong to the peer's
  version, and keep the peer's bytes **in the repository** so the rule is
  checked against every machine's OpenSSH rather than only this one's;
* accept the **whole range** a value can have -- a scalar's length is
  `1 .. width`, not one number -- and make the fixture **fresh**, because
  a pinned fixture is a fixture that can keep its luck.

The last one has a rule inside it that is easy to get backwards: **the real
server having extensions we do not have is not our bug.**  A server is not
obliged to have what a newer version of the peer has, and the newest
OpenSSH replaced four extensions with two.  The rule is deliberately
one-directional, and the negative controls in `host/loop92_init_rule.mjs`
say so.

## Loop #94: `sshd` -- the connection protocol, and the message numbers that were wrong

Loop #93 finished the handshake.  What was left between a logged-in client
and a command is RFC 4254: the session channel, the `exec` request, the
command's two output streams, its exit status and the close.

### The slice

`src/sshd/channelserver.mbt` is the server's half of RFC 4254.  It accepts
one session channel, runs the command the peer asks for, and reports what
happened.  The driver (`cmd/sshd`) supplies a `CommandRunner` -- a function
that runs a command -- because starting a process is native-only work and
`src/sshd` builds on all four backends.  That is the same shape
`src/sftpserver`'s `ServerFs` uses for the filesystem.

### Three witnesses, because one of them lies

The real `sshd` on this machine (`C:\Program Files\OpenSSH-Win64\sshd.exe`,
OpenSSH_for_Windows_8.0) was measured three ways: its own DEBUG3 log, the
real client's `-vvv` log, and paramiko -- an independent implementation --
reading the same bytes.

The client's log line

    channel 0: open confirm rwindow 0 rmax 32768

says the window is ZERO.  It is not: paramiko read the same
CHANNEL_OPEN_CONFIRMATION and says the window is **2097152**.  The client
prints the window it has AVAILABLE, not the window the server offered, so
that line is a witness about the client.  Believing it would have produced a
server that grants the peer nothing, and the peer would have said nothing
about it -- it would simply have stopped sending.

The server's DEBUG3 log names every packet it sends, and it is the record
of the order:

    send packet: type 91    (CHANNEL_OPEN_CONFIRMATION)
    send packet: type 99    (CHANNEL_SUCCESS, the answer to "exec")
    send packet: type 96    (CHANNEL_EOF)
    send packet: type 98    (CHANNEL_REQUEST "exit-status")
    send packet: type 97    (CHANNEL_CLOSE)

Two things in that list are easy to get wrong, and both were measured:

* **the EOF comes BEFORE the exit-status.**  The exit status is a
  CHANNEL_REQUEST, not a byte of stdout, and the real server sends it after
  closing its own output direction.  A client that waits for the exit status
  before reading the data deadlocks.
* **the exit-status request carries `want_reply = FALSE`.**  The server
  tells the client the status and does not wait for an answer.

The real client also sends two GLOBAL_REQUESTs (`no-more-sessions@openssh.com`
and `hostkeys-00@openssh.com`, both `want_reply = FALSE`) before the exec.
The real server answers neither, and so does this one: a server that
answered would put a packet in the peer's stream that the peer is not
expecting.

### The command is `cmd.exe /c "<command>"`, and the quotes are load-bearing

The real server's log says:

    spawn_argv[0]: "c:\windows\system32\cmd.exe" /c "cmd /c echo loop94-stdout"

The command string is ONE argument, wrapped in quotes.  cmd.exe's rule for
the argument of `/c` is: if the first character is a quote, strip it and
remove the LAST quote character on the command line.  So

    cmd /c "cmd /c echo hello"

echoes `hello"` -- with a trailing quote -- and **that quote is in the bytes
the client receives**.  It is not decoration, and it is why the comparison
against the real server has to be byte for byte.

### The dead end: `> out 2> err` on the command line

The obvious way to separate a command's stdout from its stderr is to
redirect them to two files.  It does not work here, and the reason is the
same quote rule: with the redirections on the command line, the LAST quote
on the line is the one closing `err`, so the whole tail becomes the command
and `echo` prints it.  Measured (`.loop94/cmdline_probe.py`):

    cmdline: cmd.exe /c "cmd /c echo loop94-stdout" > "...o.bin" 2> "...e.bin"
    piped out=b'loop94-stdout" > "...\\o.bin" 2> "...\\e.bin\r\n'

The separation has to happen in the **handles**, which is what the third
pipe in `src/subproc` is for.

### `src/subproc` grew a third pipe

`src/subproc` had stdout on a pipe and stderr *inherited* -- which is right
for `scp -D`, where a configuration error is worth seeing on the terminal,
and wrong for a server that has to report the two streams separately.

The addition is a third pipe plus the machinery to read two pipes without
deadlocking: a child that fills the stderr pipe (64 KB) while the parent is
blocked reading stdout stops writing, and the parent never gets to the
stderr it was waiting for.  So the parent waits on **both** pipes and the
process at once (`mb_subproc_wait_any`), and reads only what is there.

There is also a deadline, and it is not the same thing as a per-wait
timeout: a per-wait timeout bounds how long the parent waits for the NEXT
thing, not how long the child may run -- a command that writes a byte every
millisecond would never be interrupted by one.  The deadline (`GetTickCount64`
on the C side) is what says "this command has had its turn".

### The message numbers in `src/sshwire` were wrong, and no test could see it

`src/sshwire/msg.mbt` numbered the connection protocol like this:

    CHANNEL_DATA      0x5e
    CHANNEL_EOF       0x5f     <- wrong
    CHANNEL_CLOSE     0x60     <- wrong
    CHANNEL_REQUEST   0x62

-- that is, it skipped `SSH_MSG_CHANNEL_EXTENDED_DATA` (0x5f) and shifted EOF
and CLOSE down by one.  RFC 4254 §5.1 and the real server both say EOF is
96 and CLOSE is 97, and the real server's log says so in as many words
("send packet: type 96", "send packet: type 97").

**Why it stayed wrong for so long:** every test that used those constants
also BUILT packets with them.  `src/sshclient/client.mbt` is a mock server,
and it sent its EOF as 0x5f; the test then checked that the packet it
received was "an EOF" by comparing against the same constant.  A mock and
the code that checks the mock agree with each other by construction.

The real client was never affected: `src/channel` does not use that table at
all, it uses the literal bytes (0x5e / 0x60 / 0x61), which is why it talks
to the real server correctly every day.  So the table was a SECOND copy of a
rule that already existed, and the copy was the one that was wrong.  The
same shape as Loop #92's INIT comparison and Loop #60's `we_need_for`: a
second copy of a rule is where the bug lives.

### The gates that caught this loop's own work

Three standing gates went red while this loop was in progress, and each one
was measuring something adjacent to the change:

| the gate measured | what it claimed | what was true |
|---|---|---|
| `src/sshclient/live.mbt` contains `@bpacket.transport_params` | "the cipher rule is in `src/bpacket`" | the rule had MOVED to `src/bpacket` -- the gate measured an address, not a property |
| the accept table of warning sites | "no new warnings" | two of the new functions were never called, and an unused function is a warning |
| the coverage report | "these packages are reportable" | the coverage probe ran while this file was half-edited, so the tests did not build |

The first one is the interesting one, and it is the third time this
repository has been broken by measuring a place instead of a thing.  The
gate now checks BOTH ends of the delegation chain: that `src/bpacket`'s
`we_need_for` reads the parameter table and names no cipher literal, and
that the client's function delegates to it.

The second one had an honest fix that is worth naming: the warning accept
table is keyed by `file:line`, so "adding the warning to the table" would
have made the gate green while leaving two dead functions in the tree.  The
functions were deleted instead -- `subproc_avail_raw` and
`subproc_exited_raw` were written for a design that the deadline replaced.

The third one was self-inflicted and is recorded as such: the gate was run
while `src/subproc` was mid-edit.  The lesson is the one this file already
carries twice -- **do not edit the tree while a gate that builds the tree is
running** -- and it is here because it happened anyway.

### Two defects that only the real client could find

Both were in the code that looked finished, and both produced output that
was *the right shape*:

  1. **The right length, all zeros.**  `Proc::read_into` read through
     `Bytes::from_array(buf)`, which COPIES -- so C filled the copy and the
     caller's array kept the zeros it was made with.  The client received
     sixteen zero bytes for `echo loop94-stdout`.  A check on the LENGTH
     passes; only a check on the BYTES catches it.

  2. **A close that was really a reset.**  The server sent its
     CHANNEL_CLOSE and closed the socket immediately.  The client's
     answering CLOSE was still in flight, so the close became a TCP RESET,
     and the reset discarded the exit status that had just been sent.  The
     client said `Connection reset` and exited 255 -- while the server's own
     report said `exit_status: 0 / stdout_bytes: 16`.  Both halves were
     telling the truth about different things.

The second one is why the channel phase now DRAINS until the peer's CLOSE
arrives, and why `ServerReport` carries `peer_closed`: a boolean that is
only true when the drain ran is what makes the drain testable, because on a
fast loopback connection the RESET itself is not reliably observable.

### A gate that measured its own harness

`verify_loop94.mjs` ran the real client with `spawnSync` while the server
under test was a `spawn`ed child whose stdout was read with events.
`spawnSync` blocks the event loop, so those events could not be delivered
until the client was done -- and by then the gate had already concluded that
the server never reported the command.  Three checks failed against a server
whose report was correct.

The fix is `spawn` plus `await`, and the shape of the mistake is worth
keeping: **a gate that uses a blocking call next to an asynchronous subject
is measuring its own harness.**

The mutation suite then caught the same class of error from the other side.
Its first version searched the whole gate output for the word `error` to
decide a mutation was INVALID, which made three VALID mutations look
invalid -- because a failing unit test prints `Error:`, and that is the
mutation being CAUGHT, not the tree failing to build.  The rule this file
already states is the fix: **look for the named check first; the build
result is one specific check, not a word anywhere in the output.**  After
that, two more mutations had to name `the src/sshd unit tests pass` as their
target, because the unit tests -- not the end-to-end comparison -- are what
actually catch an inverted window constant and a swapped recipient/sender.

## The rest of the tool set -- what is done, and what is not

The goal for this repository is the whole OpenSSH tool set in MoonBit.
That is worth stating as a list rather than an impression, because "the
client works" and "the repository is finished" are very different claims.

**Done, and proven against a real peer or a real tool:**

    ssh          ssh_live (native) / wt_ssh (browser) / ssh_full
    ssh-keygen   make (Loop #85), encipher (Loop #86), read (Loop #87),
                 rewrite -p/-c (Loop #88)
    ssh-agent    Loop #89 -- and the REAL ssh-add talks to it
    ssh-add      Loop #89
    ssh-keyscan  cmd/ssh_keyscan
    sftp         the client, against internal-sftp
    scp          Loop #90 -- upload, download, -r, -p, local-to-local and
                 remote-to-remote, byte-comparable via `-D` (see below).
                 Loop #91 -- the SSH leg, over a real sshd, with an ECDSA
                 key file read by `src/keyfile`
    sftp-server  Loop #92 -- `src/sftpserver` plus `cmd/sftp_server`,
                 byte-comparable against the real `sftp-server.exe` on
                 every request shape (see below)
    sshd         Loop #93 -- `src/sshd` plus `cmd/sshd`: the handshake and
                 a publickey authentication, against the REAL `ssh.exe`,
                 which says `Authenticated to ... using "publickey"` (see
                 below).  The connection layer is the next loop.
    port forward the CLIENT half: direct-tcpip

**Not started.**  These are the honest remainder, and each one needs a
different kind of judgement about what "proven" means:

    sshd, the rest  the connection layer (channels, `exec`, `shell`,
                    `subsystem`), the other userauth methods, the
                    `sshd-session`/`sshd-auth` split, and the rekey.
                    Testable against the real `ssh` client, one loop at a
                    time -- Loop #93 did the handshake and `publickey`.
    ssh-copy-id     small.  Upstream is a shell script; the judgement
                    call is whether a MoonBit version should mirror its
                    sentences or just its effects.
    ssh-keysign     small but niche -- the host-based-auth delegate, and
                    it needs hostbased auth to be worth testing at all.

**Deliberately not planned:**

    ssh-pkcs11-helper   a smartcard.  `ssh-add -s/-e/-S` is refused with
                        a sentence rather than silently redefined
                        (see the option-letter section above), and a
                        helper would be the same claim in a bigger bin.
    ssh-sk-helper       FIDO/U2F.  Needs the hardware to mean anything,
                        and a stub that "succeeds" would be worse than
                        the refusal.

The order worth taking is `scp`, then `sftp-server`, then `sshd` -- each
one is testable against a real counterpart with the machinery this
repository already has, and `sshd` is the only one that is really
several loops.  The first two are done; `sshd` is under way, and its
handshake is proven against the real client.

## Loop #95: the module identity, and the two records that must agree

This loop had no protocol in it.  It renamed the module, fixed the README,
and put the mooncakes.io release inside CI -- and along the way it found
one corruption that a search-and-replace was about to cause, one gate that
a search could not see, and one pin that had been describing Loop #20
since Loop #20.

### The rename is one token, and the token has two homes

The module moved from its repository-shaped name to `riantr/moonbit_openssh`
-- publisher/package, which is what the registry needs and what a user
types.  That is 111 tracked files and 263 occurrences: 54 `moon.pkg`
import edges, `moon.mod`'s `name`, the checked-in `pkg.generated.mbti`
files, four functional Python tools (`host/collect_warnings.py`'s accept
table is keyed by package path, `host/cov_conflict.py` matches a package
prefix, two mutation harnesses anchor on `moon.pkg` text), and the prose.

The rename was done as a whole-token byte substitution over
`git ls-files`, which is safe for a reason worth writing down:
replacement offsets are the failure mode of *positional* edits, and a
whole-token substitution has no positions.  Completeness is then asked as
a separate question -- `git grep -l` over the whole tracked tree -- rather
than inferred from the edit's own report.

### The completeness check that reported complete while a gate was red

The `git grep -l -F` above came back clean, and two gates failed anyway:

    loop64:  FAIL  src/transport imports src/tcp
    loop65:  FAIL  verify_loop64 still passes   (nested)

The cause is a form of the old path that a plain-text search cannot see.
`host/verify_loop64.mjs` spelled the module path inside **RegExp
literals**, where every separator is escaped:

    /openssh\/<old package>\/src\/tcp/

Backslash-slash is not backslash-slash to `git grep -F "publisher/package"`:
the bytes differ, so the "is the rename complete" question was answered
about the *plain* form only, and the answer was true and useless at the
same time.

Two fixes, both worth keeping:

* `host/verify_loop64.mjs` now READS the module name from `moon.mod`
  instead of hardcoding it into two regexes.  A rename can no longer make
  this gate red at all, which is better than a rename that remembers to
  edit the gate.
* `ci/publish.py` greps **three** spellings of the old path -- plain,
  escaped-separator (JS regex), and doubled-escape (JS string holding a
  path) -- each assembled from parts so the check cannot match itself.
  The negative case is what proved the point: the first, single-form
  version of this very check had *reported the rename complete* while
  loop64 was red.

The remaining occurrences of the bare project name are filesystem
records: the repository directory itself is not renamed, so comments
citing a `E:\...\<old-name>\...` path still name a real place.  Those are
left alone; a comment about where the checkout lives is not a module
claim.  Two empty `moon new` scaffold files at the root were renamed with
the package (`<old-name>_test.mbt` -> the new package's name), because a
blackbox test file's name is the package's name and the package follows
the module.

### The gate that caught my own docstring

The publication gate's own documentation tripped `host/verify_loop71.mjs`:

    FAIL  no tracked file asserts a machine-specific absolute path
    1 hit(s) in 1 file(s):
        ci/publish.py:236  ...   Package to \\?\E:\..._build\publish\...

Writing down what `moon package --list` prints meant writing down a path, and
a path with a drive letter is a claim that every machine has it.  The gate is
right and the paragraph was wrong: it now says `Package to ` followed by the
Windows extended-length prefix and the artefact's own absolute path, names
why the drive letter is withheld, and keeps the fact that matters (the last
line is an artefact, not a file to publish).

Two things worth keeping from this:

* `.md` is blanked by that gate whole, for a good reason -- but a **docstring
  in a `.py` file is not blanked**, and it is just as much prose. The gate
  scans code, so documentation that lives in code is scanned as code.
* The loop had already written down that a gate "knowing something is wrong
  without saying what" is the expensive failure. This one said exactly what
  and where, in the first four lines, which is why the fix took one edit.

The release run that found it had 43 of 54 gates green and was stopped rather
than finished: a failed step means the release gate WILL refuse the tag, so
the remaining 25 minutes could not change the outcome.

### A search-and-replace inside the wasm would have corrupted it


`host/main.wasm` is a checked-in artefact of `cmd/main` (see the README's
*Known gaps*), and it contains the module name in the `name` custom
section behind a LEB128 length prefix.  The bytes, before the rename:

    2E 04 6e 61 6d 65 00 27 26 <38 bytes: the old module name>/cmd/main@0.1.0

`0x26` is 38: the length of the old name, which is 38 bytes.  The new name
is 37.  Substituting the bytes and leaving the prefix alone makes the
section read one byte past the end of the string -- and
`WebAssembly.validate` does not reliably report that, because a custom
section is allowed to contain arbitrary bytes.

So the artefact was rebuilt from source instead
(`moon build --target wasm-gc --release cmd/main`), and the result was
checked three ways: the section table walks to exactly EOF, the name now
sits behind `0x25` (37) with a run length of 37, and
`WebAssembly.validate` returns true.  The lesson is not "wasm is
special": it is that a checked-in binary with a length-prefixed string is
not a text file that happens to be unreadable.

### The pin that was measuring Loop #20

`host/browser_test.mjs` asserts the demo's output byte for byte, and it
expected `kexinit_len: 241` and `client_sent_total: 507`.  The rebuilt
artefact produced `181` and `443`.  Both numbers are load-bearing, so the
question was which one was current.

It was not the pin.  `moon run cmd/main --target native` -- no wasm
involved -- also prints 181/443, and `node host/verify.mjs` compares all
four targets in both modes against each other and found **one** hash,
`69c1f46b5e554b4d`, for all eight.  The cause is 60 bytes of KEXINIT:
Loop #60 added `src/kexflow/runnable.mbt`, which keeps the proposal to
algorithms the packet transport can actually run, so several algorithm
names left the proposal.  The pin had been describing a state of the
source that no longer existed since Loop #20 -- nothing ran the test, so
nothing said so.

Two consequences are recorded rather than absorbed:

* `host/outputs.json` is a **generated** file -- `host/verify.mjs` rewrites
  it on every run, and it had not been regenerated since that loop.  It is
  refreshed here, not edited.
* The historical documents under `docs/socket/loop1*-summary.md` keep
  their 241/507.  They are measurements of the day they were written;
  rewriting history to match today would make them worthless.

### A gate that failed on its own cleanup

The third release run reached **85/86 steps** and stopped on one:

    FAIL  verify_loop92.mjs   exit 1   72.0s

Inside it, all 30 protocol checks PASSED.  The failure was the last line of the
bed teardown:

    Error: EPERM, Permission denied: \\?\...\.loop92\gate92
        at Object.rmSync (node:fs)   <- freshBed()

Windows keeps a directory handle alive for a moment after the process holding
it exits, so `rmSync` on the freshly-used bed loses the race against the child
that just died.  It passed locally and on the earlier gates-only run because
that machine was idler.

`rmTreeSync` now retries EPERM/EBUSY with backoff (8 tries, 120 ms x n) and
still throws on the last one, with a message naming the likely cause.  Retrying
a cleanup is not the same as retrying an assertion: the failure is not
swallowed, only the window is widened.  Green locally afterwards: 38 passed,
0 failed.

The point worth keeping: **the release gate did its job.**  A failed step meant
`v0.1.2` was NOT created, and the run's own output says so:

    REFUSED: 1 step(s) failed: verify_loop92.mjs
    no tag was created. This holds even when asked for explicitly

A run that had reported green here would have tagged a tree whose own gate was
red 30 seconds earlier.

### The two records


A git tag and a mooncakes.io version are two records of one claim: "this
tree is the tested state".  Nothing in either toolchain compares them, so
`version = "0.1.2"` next to a `v0.1.3` tag would publish a version that
names no commit.  Three pieces now hold that:

* `ci/publish.py --check` -- offline and credential-free.  It asserts the
  file set `moon package` would ship contains `moon.mod` and the sources
  and contains nothing under `_build/`, `.loop*/`, `ci/artifacts/` or
  `.mooncakes/`; that `name`, `description`, `repository`, `license`,
  `keywords` and `readme` are all present (description, repository and
  keywords were **empty** before this row existed -- license was the one
  field already set -- and `moon publish` warns about none of them); that
  no tracked file still names the pre-rename module path;
  and that the version is `X.Y.Z`.
* `ci/release.py`'s `assert_version_matches_tag` -- a pure function, so
  the engine self-check can prove all four of its cases without a
  repository.  The release gate calls it **before** the tag exists,
  because after the tag a disagreement can only be recorded as a mistake.
* `ci.py --publish` -- reachable only together with `--tag`, i.e. only
  through a green run that created the tag.  It does not skip when logged
  out.

### `moon whoami` exits 0 while saying it does not know who you are

    Logged in, but username is unavailable. Please run `moon login` again.

Exit code 0.  A `returncode == 0` check would call that authenticated and
then fail at publish time.  So the decision is made on the text, and
`--publish` refuses loudly with the one command a human must run, because
a release that silently did not publish is the outcome a reader is least
able to notice.

### What `moon package --list` actually does

Measured, because most of these contradict the obvious reading, and two of
them were gotten wrong on the way:

* **the file manifest goes to STDERR, and stdout is EMPTY** -- 0 bytes while
  stderr carries the whole report.  The first reader of this command parsed
  stdout, got zero entries, exit code 0, and called it "nothing to publish".
  `ci/publish.py` now pins the rule with a fixture and a negative control
  (`parse_manifest`), because a parsing rule that cannot be tested is how the
  empty manifest got shipped;
* the same stderr stream also carries `moon check`'s diagnostics, since the
  command runs the check first: a `Running moon check ...` preamble,
  `Warning: [0029]` blocks drawn with box characters, blank lines.  An entry
  is therefore recognised by shape -- non-empty, no whitespace, no
  box-drawing character -- which measured against one real output separates
  953 entries from 137 diagnostic lines.  Box fragments need their own rule,
  because `───╯` contains no whitespace at all;
* the **last** line is not an entry.  It is `Package to ` followed by the
  Windows extended-length path prefix and the artefact's own absolute path,
  ending in `riantr-moonbit_openssh-<version>.zip` -- the artefact and the
  machine's directory layout, not something being published.  No drive letter
  is written down here on purpose: `host/verify_loop71.mjs` fails a tracked
  file that asserts a machine-specific absolute path, and a docstring in a
  `.py` file is a tracked file.  That gate caught the previous wording, with
  the file and line;
* it runs `moon check` first, so it is much heavier than "list some files";
* `--dry-run` is **not implemented** for `package` ("dry-run is not
  implemented for package", exit 1) -- it is implemented for `publish`;
* `--frozen` is not cosmetic: without it the command syncs dependencies
  first, and a probe was killed by a 600 s timeout before it printed
  anything.

It also exits **0** on this repository even though `moon check --target
native` at the root is red (the js/wasm-only live packages).  Packaging
does not build the packages that do not publish, so those are not the same
question.

### The gate that caught its own prose

`check_rename_is_complete` greps the tracked tree for the old module path,
and `ci/publish.py` is in that tree.  Written as a literal, the check
matched itself and failed always -- which it did, on the first run, and
the failure was the useful kind: it also flagged a QA evidence string that
had reintroduced the token it was describing.  The token is now assembled
from parts (`"openssh" + "/" + "openssh_" + "moonbit"`), so the check is
still exact and has nothing to find.

### Numbers

    rename                     111 files, 263 occurrences, 0 left
    engine self-check          24/24 -> 35/35 cases
    QA matrix rows             20 -> 21 (`packaging`)
    packaging manifest         954 entries (374 .mbt), parsed from stderr
    browser demo artefact      34,536 bytes, WebAssembly.validate true
    8-way target agreement     one hash, 69c1f46b5e554b4d

## Loop #96: two gates that were measuring the runner

The GitHub mirror had been three loops stale, so the first run on the renamed
module (run **44039917227**, 2026-11-17, `windows-latest`) was really a report
about Loop #92 dressed as a report about Loop #95. It went **7 red gates ->
2**.  The five that healed without being touched are the interesting part:

    loop80, loop82, loop83, loop84, loop85, loop91   now green
    loop92, loop94                                   still red

`loop91` was fixed by #93 itself (`host/loop91_fixtures.py` regenerates the
ECDSA fixtures the gate used to find lying around).  `loop83`/`loop84`/
`loop85` only ever failed by cascading `loop82 harness still green 35/36`.
And `loop80`/`loop82` -- which #93-#95 never edited -- went green because of
the **`cmd/scp` duplicate-alias warning** that #93 fixed with `@scplib`: those
two gates hash `moon run`'s combined stdout+stderr, and a workspace warning
carrying an absolute path (`\\?\D:\a\...\cmd\scp\moon.pkg`) had been entering
every hash.  A cold runner printed it; a warm developer tree did not.  That is
the same defect as the ones below, seen one layer up: **the judgement included
the toolchain, not just the program.**

### The cap that belongs to each server, not to the protocol

`loop92`'s case "a READ never returns more than 65536 bytes" compares our
reply with the real `sftp-server.exe`'s, byte for byte.  On the runner:

    reply 2   real ...0001 9000...   = 102400 bytes   (OpenSSH 8.0)
              ours ...0001 0000...   =  65536 bytes   (our own cap)

Both numbers are each server's own choice, and this machine's OpenSSH 9.5
caps at 65536 too -- which is exactly why the equality check had been passing
here for months: **the gate was asserting that every machine runs the same
OpenSSH build.**  The case now owns reply 2 through a `judge` hook: ours must
be exactly 65536, both replies must be DATA for id 36, both payloads must be
prefixes of the same file, and the peer's cap is printed as a measurement
instead of being demanded.  Every other reply is still byte equality.

### A server that refuses the key measured nothing

`loop94` reported "the committed recording and the live measurement differ".
What the live measurement actually contained was six commands that all exited
**255** with `Permission denied (publickey,password).` -- the runner's Windows
OpenSSH is an older build and refused our nistp256 test key.  The gate turned
"could not authenticate" into "our bytes moved", which is a claim about our
code supported by no measurement at all.

The file already had the right contract, and the gate already honoured it:
`host/loop94_oracle.py` documents exit **3** as "no usable real sshd here, the
caller may skip", and `verify_loop94.mjs` prints `skip` for it.  `measure()`
raised that only when `sshd.exe` was *absent*, never when it started and
refused.  It now raises it when every command exited 255 and every stderr says
"permission denied".

Negative control, because a skip path that cannot fire is not a fix:
`.loop95/negctl_loop94.py` plants an **RSA** user key (the shared
`sshd_setup.mjs` pins accepted user-key algorithms to ECDSA), reproducing the
runner's condition on a machine that can otherwise authenticate:

    planted an RSA user key (the pinned real sshd accepts ECDSA only)
    oracle exit: 3
      SKIP: the real sshd here refuses the test key, so nothing was measured:
      hp@127.0.0.1: Permission denied (publickey,password,keyboard-interactive).
    negative control: PASS -- the skip path fires

The positive path is unchanged: `loop94` still runs **49/49** here, taking the
strict comparison, because this machine authenticates.  A machine that *can*
drive the real server still gets the strict comparison; a machine that cannot
now says so instead of accusing the recording.

The same docstring also emitted `SyntaxWarning: invalid escape sequence '\s'`
on every run (it quotes `<windows>\system32\cmd.exe`); that backslash is now
escaped.  Noise in a runner log is a place where a real warning can hide.

### Numbers

    GitHub run 44039917227    7 red gates -> 2
    loop92 after the fix      38 passed, 0 failed
                              measured: our cap 65536, the real server's 65536
    loop94 after the fix      49/49
    loop94 negative control   exit 3, SKIP (refused key, reproduced)
    files touched             host/verify_loop92.mjs, host/loop94_oracle.py

## Loop #97: the tag trigger that was not there, and the frozen assumption

Publishing 0.1.3 from CI took three attempts, and each failed for a different
reason that no local green run could have found:

1. **The secret carried a BOM.** It was written with
   `Get-Content -Raw ... | gh secret set`, and PowerShell put a UTF-8 BOM in
   front of the JSON.  The runner then said

       the secret is neither the login JSON nor a bare token:
       Unexpected character encountered while parsing value: ﻿.

   The FILE has no BOM -- measured: first bytes are `7B 0A 20 20` (`{\n  `) --
   so the BOM came from the pipe, not from `moon login`.  Writing the bytes
   from Python (`subprocess.run(..., input=data)`) removed it.  A secret is a
   byte string; a shell pipeline is not a byte-preserving channel.
2. **`on.push` had `branches: ["**"]` and no `tags:`.**  A tag push matches
   neither filter, so the workflow never ran and the publish job's
   `if: startsWith(github.ref, 'refs/tags/v')` was never evaluated.  The tag
   reached GitHub and produced no run at all.
3. **`--frozen` on a fresh runner.**  `ci/publish.py`'s dry run passed
   `--frozen`, and the runner answered

       Failed to sync dependencies: `frozen` is set, so the build system cannot
       change the modules directory, but new modules need to be installed

   `--frozen` encodes "the `.mooncakes` of a developer machine, already synced
   by every prior build".  The publish job runs `moon update` and nothing else,
   so that history does not exist there.  The flag is gone from `dry_run()`;
   what the dry run exists to check is the REGISTRY, not the freeze.

What the failures nevertheless proved, on the runner (run 44059001768):

    token length: 32 characters
    wrote C:\Users\runneradmin\.moon\credentials.json (116 bytes)
    moon whoami: Logged in as riantr
    This run's tag is the one moon.mod names      success

So the credential path and the tag/version invariant are real.  Only the
trigger and the dependency assumption were wrong.

**Decision (the owner's):** bump to **0.1.4** and let the rebuilt chain publish
that, rather than publishing 0.1.3 locally or through a branch dispatch.
**0.1.3 is therefore a tag that exists and was never released** -- recorded
here so nobody wonders later, and so nobody "fixes" it by moving the tag.

Changes: `push.tags: ["v*"]`; `gates` and `release-gate` skip tag pushes, so a
tag push runs only `publish`; `dry_run()` no longer passes `--frozen`.

### The rule this loop adds

**A workflow that publishes on a tag must be tested by a tag push, not by a
dispatch.** `workflow_dispatch --ref v0.1.3` makes `github.ref` equal
`refs/tags/v0.1.3`, so the job's `if` is satisfied and the job runs -- while
the trigger that would fire in production (`on.push.tags`) still does not
exist.  Dispatch is how the missing trigger stayed invisible through two
attempts.

### Numbers

    attempts before the trigger was found   2 dispatches
    runner proof of the credential          whoami: Logged in as riantr
    secret bytes                            116 (32-character token)
    runner-minutes saved per tag push       ~45 (gates skipped)
    0.1.3                                   tagged, never published

## Loop #98: the compiler moved, and a third-party dependency broke

GitHub run 44065649338 (the branch push of Loop #97) went red in three gates --
**loop41, loop66, loop68** -- with one cause.

The evidence, in the order it was found:

* **The same source failed on one machine and not the other.**  The runner's
  kept build transcript names the file and the line:
  `.mooncakes/tonyfettes/xlog/entry.mbt:35:25` -- `Type Level has no method
  to_string` -- with the hint "impl cannot be invoked directly as method unless
  explicitly promoted via `extend`".  The very same xlog version compiles here.
* **The compiler was not the same.**  The runner printed
  `moon 0.1.20261117 (eb64713 2026-11-17)`; this machine has
  `moon 0.1.20261102 (ea07287 2026-11-02)`.  The CI installs `version: latest`,
  so **the compiler moves between runs**.
* **The failure was not ours.**  `xlog` is a TRANSITIVE dependency of `proton`
  and is used only by `cmd/proton_gui`.  No package under `src/` imports it.
* **The broken version is the one the dependency asks for.**  `proton 0.3.4`
  requires `tonyfettes/xlog@0.4.2`, and 0.4.2 calls `impl`-defined methods
  directly.

### The compiler cannot be pinned, and the measurement says so

The obvious remedy -- pin the compiler -- is not available:

* `https://cli.moonbitlang.com/binaries/<version>/moonbit-windows-x86_64.zip`
  answers **403** for every concrete version (probed 0.1.20261102, 0.1.20261117,
  both with and without a `v` prefix, and both the binary and the core).  Only
  the channels exist: `binaries/latest/...` answers 200/206.  The installer's
  `$Version` is therefore a CHANNEL, not a version.
* `github.com/moonbitlang/core` has **no releases and no tags**, so there is no
  versioned archive to install from either.
* The install script has no fallback: a missing version is `Install Failed`,
  exit 1.  A pin would be loud -- but there is nothing to pin TO.

So the compiler floats, and the dependencies are ours to pin.

### The upstream fix, which is also the right one

**proton 0.9.1, published the same day, depends on xlog 0.5.1** -- and xlog 0.5.1
adds `extends.mbt`:

    pub extend Level  with Show::{to_string, output}
    pub extend Entry  with Show::{to_string, output}
    pub extend Entry  with ToJson::{to_json}

The call sites are unchanged (`self.level.to_string()` is still there); what
changed is that the trait methods are now **promoted**, which is what the new
compiler asks for and what the old one also accepts.  So xlog 0.5.1 compiles
under BOTH compilers -- measured here on 0.1.20261102 (`moon check
cmd/proton_gui --target native`: 0 errors) and on the runner by the next CI
run.  `moon.mod` therefore gains one direct edge:

    "tonyfettes/xlog@0.5.1",

which is what raises it: MoonBit's resolver takes the **highest** version
requested anywhere in the graph.  proton stays at 0.3.4, so the CEF archive and
its sha256 in the CI are untouched.

### The pin that was not a pin

The same measurement found a second thing.  `moon.mod` declared
`moonbitlang/async@0.22.2`, and every build used **0.22.4** -- proton's
requirement, because the resolver takes the maximum.  The declaration was a
claim the build did not honour, and it is the version the *published* module
would state.  It now says 0.22.4, the version actually used.  The resolution
does not change; the record does.

### A green run that does not say what it ran on

`ci.json` recorded every env step as `"ok"`, so two runs could not be compared:
when the compiler moved on 2026-11-17 and three gates went red, the artifact
could not show what had changed.  The env steps now carry the version they
report -- the first line of `moon version --all` -- so the artifact names the
compiler that produced the verdict.  Same argument as the committed loop94
recording, one level up: a measurement that cannot be re-grounded is a claim
about the machine.

### The publish path checks, it does not build

Measured from the first publication attempt (run 44059001768), whose dry run
printed exactly this before failing:

    publishing riantr/moonbit_openssh 0.1.3 as Logged in as riantr
    Running moon check ...
    Error: Failed to calculate build plan
    moon check failed

So `moon publish --dry-run` type-checks the module; it does not compile it.
That matters because `cmd/proton_gui` needs the Proton CEF runtime to BUILD,
and the publish job does not provision it -- and does not need to, because a
package is a zip of sources (954 files, 374 of them `.mbt`), not of binaries.
A check does not compile the C stubs, so the missing CEF cannot bite here.

### Numbers

    GitHub run 44065649338     3 red gates, 1 cause
    runner compiler             moon 0.1.20261117 (2026-11-17)
    this machine                moon 0.1.20261102 (2026-11-02)
    xlog 0.4.2 errors           6, in 3 files (entry.mbt, log.mbt, writer.mbt)
    xlog 0.5.1                  adds extends.mbt; compiles on both compilers
    moon.mod                    + tonyfettes/xlog@0.5.1
                                async 0.22.2 -> 0.22.4 (the version in use)
    local check                 cmd/proton_gui: 0 errors
    loop41 / loop66 / loop68    green locally with the new resolution


## Loop #99: the compiler moved again -- two diagnostics, and the toolchain that matches CI

GitHub run 44255552480 (commit `d7678c8`) went red in ONE gate: **loop66**,
the static-analysis gate.  72 of 73 steps passed, so the Loop #98 dependency
fix did its job -- loop41 and loop68, the other two victims of the xlog 0.4.2
breakage, are green under the runner's compiler.

What loop66 said:

    new warnings not in the accept table:
      cmd/proton_gui/moon.pkg:24, src/hostkey/cert_test.mbt:19

The gate reports `file:line`, and the artifact did not carry the warning
TEXT.  An accept-table entry has to be evidence-backed, so the text had to be
measured, which meant the compiler CI uses had to be obtained.

### Getting the compiler CI uses, without destroying the one we had

A version cannot be installed: `cli.moonbitlang.com/binaries/<version>/...`
answers **403** for every version-shaped path, for the binary and for the
core alike, and the channels that exist are `latest` and `nightly` (both
206) while `beta`, `2026-11-17` and `20261117` are 403.  The version already
on this machine can never be fetched again, so it was **not** overwritten:
the `latest` toolchain was installed into a SECOND `MOON_HOME`
(`E:\src\moon\_moon_latest`), side by side.

It is the same build the runner had.  The archive's `Last-Modified` is
`Tue, 17 Nov 2026 09:51:12 GMT` -- the same file the runner downloaded at
07:00 UTC on the 18th -- and:

    moon version --all -> moon 0.1.20261117 (eb64713 2026-11-17)
                     -> moonc v0.10.21+06da1ed44 (2026-11-16)

which is byte-for-byte the version the cloud run recorded in `ci.json`
("moon 0.1.20261117 (eb64713 2026-11-17)").  **`Last-Modified` on the
channel archive is the version's identity**, because the version string
itself cannot be requested.

### The two diagnostics

1. `cmd/proton_gui/moon.pkg:24:3-24:26`
   `Warning (unused_package): Unused package 'moonbitlang/core/json'`

   The package imported `moonbitlang/core/json` for the
   `#derive(ToJson, FromJson)` attributes in `contract.mbt`.  The new
   compiler does not count the derive as a consumer, because the PRELUDE now
   carries the json package (`moonbitlang/core/prelude` imports
   `moonbitlang/core/json`), so the traits resolve without the explicit
   edge.  The import is genuinely redundant; the fix is to remove it -- the
   same shape as Loop #66's removal of `moonbitlang/core/bytes` from
   `src/tcp`.  Measured after the removal: the derives still resolve, and
   the package's only remaining diagnostics are the three `unused_async`
   entries the accept table already carries.

2. `src/hostkey/cert_test.mbt:19:10-19:20`
   `Warning (deprecated): Use `Bytes::make(len, b'\x00')` instead`

   `Bytes::new(0)` is deprecated in the new core.  It was the only occurrence
   of `Bytes::new(` in the whole tree, so the repair is the whole of it.
   `Bytes::make(len : Int32, init : Byte)` exists in BOTH cores
   (`builtin/intrinsics.mbt:1568` in the old one), so the source is not tied
   to the newer compiler.

Both are fixed in the source rather than accepted: an accept-table entry is
for a warning that CANNOT be removed (a compiler limitation, an `async fn`
whose declared type demands it), and these two are ordinary dead weight.

### `moon check` does not run a package's prebuild script

Measured with an isolated probe package that declares the same option
`moonbit-community/proton` declares in its module manifest
(`options("--moonbit-unstable-prebuild": "build.mjs")`), whose `build.mjs`
appends a marker line every time it is invoked:

    moon check                  -> NO marker   (2 tasks ran)
    moon check --target native  -> NO marker   (2 tasks ran)
    moon build --target native  -> MARKER present

The prebuild script belongs to the BUILD plan, not the CHECK plan.  That
matters because `cmd/proton_gui`'s dependency `proton` resolves the Proton
CEF SDK layout under `~/.proton/store` in that script, and the publish job
does not provision the CEF layout (only the gates job does).  Since
`moon publish` runs a CHECK over the module -- measured on run 44059001768,
where the publish job's own output was "Running moon check ..." -- the
publish job does not need the CEF, and the workflow needed no CEF step and
the release needed no extra cloud round to prove it.

A second thing the probe taught: the prebuild script receives the whole
environment in its JSON payload (`{"env": {...}, "paths": {...}}`), so a
build script must never print that payload into a CI log.

### The rule this loop leaves behind

**The local compiler must be the compiler CI runs.**  Everything in this loop
was expensive only because it was measured on the wrong compiler: the cloud
run is the first place where the new diagnostics appeared, and the fix could
not be written until a compiler that produces them existed on this machine.
Two changes make the next occurrence cheap:

  * the local toolchain is now the same build as CI's, and it is installed
    side by side with the previous one instead of overwriting it;
  * `ci/ci.py` records the toolchain version in `ci.json` (Loop #98), so two
    runs can be compared instead of merely counted.

### The tag that was signed for a tree that failed in the cloud

The tenth release round signed `v0.1.4` at `d7678c8` -- correctly, by the
local gate: the local CI was green, and the release gate refuses to tag
unless every step that ran passed.  The CLOUD then showed that tree to be
broken under the runner's compiler, which is a fact the local round could not
know.  `v0.1.4` had never left this machine (it is not on Gitee, not on
GitHub, not on mooncakes.io), so it was deleted and re-signed on the fixed
tree rather than being pushed as a broken release or left behind as a second
"tagged but never published" tombstone like `v0.1.3`.

A tag that has been pushed anywhere is not moved again.  A tag that exists
only in one working copy, and names a tree the cloud rejected, is a
work-in-progress number, not a published state.

### Numbers

    GitHub run 44255552480      1 red gate (loop66), 72/73 steps passed
    runner compiler             moon 0.1.20261117 (eb64713 2026-11-17)
    local compiler, new         moon 0.1.20261117 (eb64713 2026-11-17)  <- E:\src\moon\_moon_latest
    local compiler, kept        moon 0.1.20261102 (2026-11-02)          <- C:\Users\hp\.moon (not overwritten)
    new diagnostic 1            unused_package 'moonbitlang/core/json' (proton_gui/moon.pkg:24)
    new diagnostic 2            deprecated Bytes::new -> Bytes::make (hostkey/cert_test.mbt:19)
    local check                 cmd/proton_gui: 3 accepted warnings; src/hostkey: 0
    loop66 under the new compiler   14/14, "4 reported sites, equal to the 4-entry accept table"
