// SPDX-License-Identifier: Apache-2.0
//
// handoff-verify.mjs: an offline verifier for Handoff v0 record exports (SPEC r8.1a), in dependency-free JavaScript.
// It runs in Node (tested on Node 24) and in a browser. It is a line-by-line port of the Python reference implementation
// (refimpl/handoff: canon.py, crypto.py, event.py, state.py, keys.py, log.py, head.py, erase.py, verify.py, cli.py).
//
//   node handoff-verify.mjs verify RECORD.json --keys keys.json [--json]     (the section 13 command line)
//   node handoff-verify.mjs conformance <fixtures URL or directory>           (the section 15 fixtures)
//
// - Canonical JSON: the G5 profile parser and the RFC 8785 serialiser of canon.py.
// - Unicode: every rule that depends on character data (NFC, lower-casing, digits, printable) uses Unicode 15.0, the
//   version of the reference's Python 3.12. A code point unassigned in Unicode 15.0 is treated as the reference
//   treats it: an inert starter with no decomposition, no case mapping and no digit value. An engine whose own data
//   is older than 15.0 gets ERROR (ENGINE_UNICODE), never a verdict.
// - SHA-256, SHA-512 and HMAC-SHA256: implemented here, synchronously, so the whole verifier is one synchronous call.
// - Ed25519: strict verification in pure JavaScript with BigInt (RFC 8032 section 5.1.7 plus the checks of crypto.py:
//   canonical A and R, A and R not small-order and in the prime-order subgroup, S < L). No platform Ed25519 is used.
// - Merkle trees: RFC 9162 section 2.1 inclusion and consistency proofs, the sorted tip tree (log.py, head.py).
// - Verdicts: ACCEPT, REJECT, DETECT and ERROR, exactly as verify.py decides them.
//
// The verify path reads only the bytes it is given. It opens no socket and reads no clock. Only the conformance runner
// loads files (from the directory or URL it is given), and the Node command line reads and writes local files.
// A signature proves that a key signed some bytes. It does not prove that what those bytes say is true.

// ================================================================ bytes, hex, base64, UTF-8

const TE = new TextEncoder();
export const utf8 = (s) => TE.encode(s);
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);

// Python's s.encode("utf-8", "surrogatepass"): a lone surrogate becomes its 3-byte form (ED A0..BF xx), which the
// UTF-8 check then refuses at that byte, as the reference does. TextEncoder would silently turn it into U+FFFD.
export function utf8Pass(s) {
  if (!LONE_SURROGATE_RE.test(s)) return TE.encode(s);
  const out = [];
  for (let i = 0; i < s.length; i++) {
    const c = s.charCodeAt(i);
    if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
      const d = s.charCodeAt(i + 1);
      if (d >= 0xdc00 && d <= 0xdfff) {
        const cp = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
        out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
        i++;
        continue;
      }
    }
    if (c < 0x80) out.push(c);
    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
    else out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
  }
  return new Uint8Array(out);
}

// Input bytes at the API boundary: a Uint8Array as it is; an ArrayBuffer (what file.arrayBuffer() gives in a browser)
// or any typed-array view or DataView as a Uint8Array over the same bytes; a string as its surrogatepass UTF-8.
// Anything else is a usage error, so no size, BOM or UTF-8 check can be skipped by the type of the input.
export function asBytes(v, what) {
  if (v instanceof Uint8Array) return v;
  if (typeof v === "string") return utf8Pass(v);
  const tag = Object.prototype.toString.call(v);
  if (tag === "[object ArrayBuffer]" || tag === "[object SharedArrayBuffer]") return new Uint8Array(v);
  if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
  throw new InputError(`${what} must be bytes (a Uint8Array, an ArrayBuffer or a typed-array view) or a string`, "USAGE");
}

export function concat(...parts) {
  let n = 0;
  for (const p of parts) n += p.length;
  const out = new Uint8Array(n);
  let o = 0;
  for (const p of parts) {
    out.set(p, o);
    o += p.length;
  }
  return out;
}

const HEXCH = "0123456789abcdef";
export function toHex(b) {
  let s = "";
  for (let i = 0; i < b.length; i++) s += HEXCH[b[i] >> 4] + HEXCH[b[i] & 15];
  return s;
}

export function fromHex(s) {
  // Python bytes.fromhex on an already validated string (pairs of hex digits; spaces between pairs are skipped).
  s = String(s).replace(/ /g, "");
  if (s.length % 2 || /[^0-9a-fA-F]/.test(s)) throw new TypeError("non-hexadecimal number found in fromhex() arg");
  const out = new Uint8Array(s.length / 2);
  for (let i = 0; i < out.length; i++) out[i] = parseInt(s.substr(2 * i, 2), 16);
  return out;
}

export function bytesEq(a, b) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  return true;
}

function cmpBytes(a, b) {
  const n = Math.min(a.length, b.length);
  for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
  return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
}

const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64REV = (() => {
  const r = new Int16Array(128).fill(-1);
  for (let i = 0; i < 64; i++) r[B64.charCodeAt(i)] = i;
  return r;
})();

export function b64decode(s) {
  // Python base64.b64decode(s, validate=True): only the base64 alphabet, correct padding.
  if (typeof s !== "string" || s.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(s)) {
    throw new TypeError("invalid base64 input");
  }
  const pad = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0;
  const n = (s.length / 4) * 3 - pad;
  const out = new Uint8Array(n);
  let o = 0;
  for (let i = 0; i < s.length; i += 4) {
    const a = B64REV[s.charCodeAt(i)], b = B64REV[s.charCodeAt(i + 1)];
    const c = s[i + 2] === "=" ? 0 : B64REV[s.charCodeAt(i + 2)];
    const d = s[i + 3] === "=" ? 0 : B64REV[s.charCodeAt(i + 3)];
    const v = (a << 18) | (b << 12) | (c << 6) | d;
    if (o < n) out[o++] = (v >> 16) & 255;
    if (o < n) out[o++] = (v >> 8) & 255;
    if (o < n) out[o++] = v & 255;
  }
  return out;
}

export function b64encode(b) {
  let s = "";
  for (let i = 0; i < b.length; i += 3) {
    const v = (b[i] << 16) | ((i + 1 < b.length ? b[i + 1] : 0) << 8) | (i + 2 < b.length ? b[i + 2] : 0);
    s += B64[(v >> 18) & 63] + B64[(v >> 12) & 63];
    s += i + 1 < b.length ? B64[(v >> 6) & 63] : "=";
    s += i + 2 < b.length ? B64[v & 63] : "=";
  }
  return s;
}

// Position of the first invalid UTF-8 sequence (as Python's UnicodeDecodeError.start), or -1.
function utf8InvalidAt(d) {
  const n = d.length;
  let i = 0;
  while (i < n) {
    const b = d[i];
    if (b < 0x80) {
      i++;
      continue;
    }
    let need, lo = 0x80, hi = 0xbf;
    if (b >= 0xc2 && b <= 0xdf) need = 1;
    else if (b >= 0xe0 && b <= 0xef) {
      need = 2;
      if (b === 0xe0) lo = 0xa0;
      if (b === 0xed) hi = 0x9f;
    } else if (b >= 0xf0 && b <= 0xf4) {
      need = 3;
      if (b === 0xf0) lo = 0x90;
      if (b === 0xf4) hi = 0x8f;
    } else return i;
    if (i + 1 >= n || d[i + 1] < lo || d[i + 1] > hi) return i;
    for (let k = 2; k <= need; k++) if (i + k >= n || d[i + k] < 0x80 || d[i + k] > 0xbf) return i;
    i += need + 1;
  }
  return -1;
}

export function utf8Decode(d) {
  const bad = utf8InvalidAt(d);
  if (bad >= 0) throw new TypeError("invalid UTF-8 at byte " + bad);
  return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(d);
}

// Code-point helpers (Python counts and slices strings by code point; JavaScript by UTF-16 unit).
function cpLen(s) {
  let n = s.length;
  for (let i = 0; i < s.length - 1; i++) {
    const c = s.charCodeAt(i);
    if (c >= 0xd800 && c <= 0xdbff) {
      const d = s.charCodeAt(i + 1);
      if (d >= 0xdc00 && d <= 0xdfff) {
        n--;
        i++;
      }
    }
  }
  return n;
}
const cpCount = (s, i) => cpLen(s.slice(0, i));
const cpSlice = (s, n) => Array.from(s).slice(0, n).join("");
function cpAt(s, i) {
  const cp = s.codePointAt(i);
  return String.fromCodePoint(cp);
}

// ================================================================ Unicode 15.0 (the reference's character data)

// Code points assigned in Unicode 15.0 (General_Category other than Cn), generated from Python 3.12.3 unicodedata
// 15.0.0. Each item is "gap.length-1" in hex: the gap from the end of the previous range, then the range length minus 1.
const U15_ASSIGNED = "0.377,2.5,4.6,1.0,1.13,1.18c,1.25,2.31,2.2,1.36,8.1a,4.5,b.10d,1.3b,2.64,e.3a,2.30,2.e,1.1b,2.0,1.a,5.1e,1.1,6.eb,1.7,2.1,2.15,1.6,1.0,3.3,2.8,2.1,2.3,8.0,4.1,1.4,2.18,2.2,1.5,4.1,2.15,1.6,1.1,1.1,1.1,2.0,1.4,4.1,2.2,3.0,7.3,1.0,7.10,a.2,1.8,1.2,1.15,1.6,1.1,1.4,2.9,1.2,1.2,2.0,f.3,2.b,7.6,1.2,1.7,2.1,2.15,1.6,1.1,1.4,2.8,2.1,2.2,7.2,4.1,1.4,2.11,a.1,1.5,3.2,1.3,3.1,1.0,1.1,3.1,3.2,3.b,4.4,3.2,1.3,2.0,6.0,e.14,5.c,1.2,1.16,1.f,2.8,1.2,1.3,7.1,1.2,2.0,2.3,2.9,7.15,1.2,1.16,1.9,1.4,2.8,1.2,1.3,7.1,6.1,1.3,2.9,1.2,c.c,1.2,1.32,1.2,1.5,4.f,2.19,1.2,1.11,3.17,1.8,1.0,2.6,3.0,4.5,1.0,1.7,6.9,2.2,c.39,4.1c,25.1,1.0,1.4,1.17,1.0,1.16,2.4,1.0,1.6,1.9,2.3,20.47,1.23,4.26,1.23,1.e,1.c,25.c5,1.0,5.0,2.178,1.3,2.6,1.0,1.3,2.28,1.3,2.20,1.3,2.6,1.0,1.3,2.e,1.38,1.3,2.42,2.1f,3.19,6.55,2.5,2.29c,3.58,7.15,9.17,9.13,c.c,1.2,1.1,c.5d,2.9,6.9,6.19,6.58,7.2a,5.45,a.1e,1.b,4.b,4.0,3.29,2.4,b.2b,4.19,6.a,3.3d,2.40,1.1c,2.a,6.9,6.d,2.1e,31.4c,3.2e,1.73,8.3b,3.e,3.3b,7.2a,2.a,8.2a,5.215,2.5,2.25,2.5,2.7,1.0,1.0,1.0,1.1e,2.34,1.e,1.d,2.5,1.12,2.2,1.8,1.64,1.b,2.1a,1.c,3.20,f.20,f.8b,4.296,19.a,15.713,2.1f,1.15c,5.2c,1.0,5.0,2.37,7.1,e.17,9.6,1.6,1.6,1.6,1.6,1.6,1.6,1.6,1.7d,22.19,1.58,c.d5,1a.b,4.3f,1.55,2.66,5.2a,1.5d,1.53,c.2e,1.726c,3.36,9.15b,14.b7,8.ca,5.1,1.0,1.4,18.3a,3.9,6.37,8.45,8.b,6.73,b.1d,3.4d,1.a,4.20,1.36,9.d,2.9,2.66,18.1b,a.5,2.5,2.5,9.6,1.6,1.3b,4.7d,2.9,6.2ba3,c.16,4.30,4.226d,2.69,26.6,c.4,5.19,1.4,1.0,1.1,1.1,1.7c,10.1bc,2.35,7.0,20.29,6.32,1.12,1.3,4.4,1.86,2.0,1.bd,3.5,2.5,2.5,2.2,3.6,1.6,a.4,2.b,1.19,1.12,1.1,1.e,2.d,22.7a,5.2,4.2c,3.57,1.c,3.0,2f.2d,82.1c,3.30,f.1b,4.23,9.1d,5.2a,5.1d,1.24,4.d,2a.9d,2.9,6.23,4.23,4.27,8.33,b.b,1.e,1.6,1.1,1.a,1.e,1.6,1.1,43.136,9.15,a.7,18.5,1.29,1.8,45.5,2.0,1.2b,1.1,3.0,2.16,1.47,8.8,30.12,1.1,5.20,3.1a,5.0,40.37,4.13,2.31,1.1,5.7,1.2,1.1c,2.2,4.9,7.8,7.3f,20.26,4.b,9.35,3.1c,2.1a,5.19,7.3,c.6,50.48,37.32,d.32,7.2d,8.9,126.1e,1.29,1.2,2.1,4b.2a,8.29,16.19,26.1b,14.16,9.4d,4.23,9.43,a.0,2.18,7.9,6.34,1.11,8.26,9.5f,1.13,b.11,1.2e,3e.6,1.0,1.3,1.e,1.a,6.3a,5.9,6.3,1.7,2.1,2.15,1.6,1.1,1.4,1.9,2.1,2.2,2.0,6.0,5.6,2.6,3.4,8b.5b,1.4,1e.47,8.9,a6.35,2.25,22.44,b.9,6.c,13.39,6.9,36.1a,2.e,4.16,b9.3b,64.52,c.7,2.0,2.7,1.1,1.1d,1.1,2.b,9.9,46.7,2.2d,2.a,1b.47,8.52,d.48,7.9,f6.8,1.2c,1.d,a.1c,3.1f,2.15,1.d,49.6,1.1,1.2b,3.0,1.1,1.8,8.9,6.5,1.1,1.24,1.1,1.5,7.9,136.18,7.10,1.28,3.1b,56.0,f.31,d.39a,66.6e,1.4,b.c3,a4c.62,d.455,faa.246,21b9.238,7.1e,1.9,4.50,1.9,6.1d,2.5,a.45,a.9,1.6,1.14,5.12,2b0.5a,65.4a,4.38,7.10,40.4,b.1,e.17f7,8.4d5,2a.8,22e7.3,1.6,1.1,1.122,f.0,1d.2,2.0,e.3,8.18b,904.6a,5.c,3.8,7.9,2.7,125c.2d,2.16,9.73,3c.f5,a.26,2.c1,15.45,7a.13,c.13,c.56,9.18,87.54,1.46,1.1,2.0,2.1,2.3,1.b,1.0,1.6,1.40,1.3,2.7,1.6,1.1b,1.3,1.4,1.0,3.6,1.153,2.123,2.2bd,f.4,1.e,450.1e,6.5,d5.6,1.10,2.6,1.1,1.4,5.3d,21.0,70.2c,3.d,2.9,4.1,140.1e,11.39,5.0,1d0.29,2e6.6,1.3,1.1,1.e,1.c4,2.f,29.4b,4.9,4.1,311.43,4c.3c,c2.3,1.1a,1.1,1.0,2.0,1.9,1.3,1.0,1.0,6.0,4.0,1.0,1.0,1.2,1.1,1.0,2.0,1.0,1.0,1.0,1.0,1.1,1.0,2.3,1.6,1.3,1.3,1.0,1.9,1.10,5.2,1.4,1.10,34.1,10e.2b,4.63,c.e,2.e,1.e,1.24,a.ad,38.1c,d.2b,4.8,7.1,e.5,9a.3d7,4.10,3.c,3.76,4.5e,6.b,4.0,f.b,4.37,8.9,6.27,8.1d,2.1,4e.153,c.d,2.c,3.8,7.2d,1.6,8.d,4.8,7.8,7.92,1.36,25.9,406.a6df,20.1039,6.dd,2.1681,e.1d30,c1f.21d,5e2.134a,5.105f,adc51.0,1e.5f,80.ef,fe10.fffd,2.fffd";
let u15Ranges = null;
function u15Table() {
  if (u15Ranges === null) {
    const items = U15_ASSIGNED.split(",");
    u15Ranges = new Uint32Array(items.length * 2);
    let prev = 0;
    items.forEach((it, k) => {
      const [g, l] = it.split(".");
      const s = prev + parseInt(g, 16), e = s + parseInt(l, 16);
      u15Ranges[2 * k] = s;
      u15Ranges[2 * k + 1] = e;
      prev = e + 1;
    });
  }
  return u15Ranges;
}
// True if cp is assigned in Unicode 15.0.
export function assigned15(cp) {
  const t = u15Table();
  let lo = 0, hi = t.length / 2 - 1;
  while (lo <= hi) {
    const mid = (lo + hi) >> 1;
    if (cp < t[2 * mid]) hi = mid - 1;
    else if (cp > t[2 * mid + 1]) lo = mid + 1;
    else return true;
  }
  return false;
}
// Apply fn to each maximal run of code points assigned in Unicode 15.0; leave every other code point as it is. Under
// Unicode 15.0 such a code point is a starter with no decomposition, no composition and no case mapping, so it
// splits the string into parts that normalise and case-map independently. Within a run, Unicode's normalization
// stability policy makes any engine at Unicode 15.0 or later give the 15.0 result.
function by15(s, fn) {
  let out = "", run = "";
  for (const ch of s) {
    if (assigned15(ch.codePointAt(0))) run += ch;
    else {
      if (run) out += fn(run);
      run = "";
      out += ch;
    }
  }
  return run ? out + fn(run) : out;
}
export const nfc15 = (s) => by15(s, (r) => r.normalize("NFC"));
export const lower15 = (s) => by15(s, (r) => r.toLowerCase());
// The engine's own normalization data must be Unicode 15.0 or later: U+10EFD (added in 15.0, combining class 220)
// must be ordered before U+0301 (class 230). An older engine cannot reproduce the reference and gets ERROR.
let engineOk = null;
export function engineUnicodeOk() {
  if (engineOk === null) {
    try {
      engineOk = "á\u{10efd}".normalize("NFD") === "a\u{10efd}́" && "é".normalize("NFC") === "é" &&
        "İ".toLowerCase() === "i̇";
    } catch (e) {
      engineOk = false;
    }
  }
  return engineOk;
}

// ================================================================ Python-compatible text helpers

function isPrintableCp(cp) {
  if (cp === 0x20) return true;
  if (!assigned15(cp)) return false;
  const ch = String.fromCodePoint(cp);
  return !/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}\p{Zs}]/u.test(ch);
}

function pyStrRepr(s) {
  const q = s.includes("'") && !s.includes('"') ? '"' : "'";
  let out = q;
  for (const ch of s) {
    const cp = ch.codePointAt(0);
    if (ch === q || ch === "\\") out += "\\" + ch;
    else if (ch === "\t") out += "\\t";
    else if (ch === "\n") out += "\\n";
    else if (ch === "\r") out += "\\r";
    else if (cp < 0x20 || cp === 0x7f) out += "\\x" + cp.toString(16).padStart(2, "0");
    else if (cp < 0x7f) out += ch;
    else if (isPrintableCp(cp)) out += ch;
    else if (cp <= 0xff) out += "\\x" + cp.toString(16).padStart(2, "0");
    else if (cp <= 0xffff) out += "\\u" + cp.toString(16).padStart(4, "0");
    else out += "\\U" + cp.toString(16).padStart(8, "0");
  }
  return out + q;
}

export function pyRepr(v) {
  if (v === null || v === undefined) return "None";
  if (v === true) return "True";
  if (v === false) return "False";
  if (typeof v === "number") return String(v);
  if (typeof v === "string") return pyStrRepr(v);
  if (Array.isArray(v)) return "[" + v.map(pyRepr).join(", ") + "]";
  if (typeof v === "object") return "{" + Object.keys(v).map((k) => pyStrRepr(k) + ": " + pyRepr(v[k])).join(", ") + "}";
  return String(v);
}

// Python str.strip() whitespace (str.isspace).
const PY_WS = new Set([0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x85, 0xa0, 0x1680, 0x2000, 0x2001,
  0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000]);
function pyStrip(s) {
  let a = 0, b = s.length;
  while (a < b && PY_WS.has(s.charCodeAt(a))) a++;
  while (b > a && PY_WS.has(s.charCodeAt(b - 1))) b--;
  return s.slice(a, b);
}

// Python json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=True).
export function pyJsonDumps(v) {
  if (v === null || v === undefined) return "null";
  if (v === true) return "true";
  if (v === false) return "false";
  if (typeof v === "number") return String(v);
  if (typeof v === "string") {
    let out = '"';
    for (let i = 0; i < v.length; i++) {
      const c = v.charCodeAt(i);
      if (c === 0x22) out += '\\"';
      else if (c === 0x5c) out += "\\\\";
      else if (c === 0x0a) out += "\\n";
      else if (c === 0x0d) out += "\\r";
      else if (c === 0x09) out += "\\t";
      else if (c === 0x08) out += "\\b";
      else if (c === 0x0c) out += "\\f";
      else if (c < 0x20 || c > 0x7e) out += "\\u" + c.toString(16).padStart(4, "0");
      else out += v[i];
    }
    return out + '"';
  }
  if (Array.isArray(v)) return "[" + v.map(pyJsonDumps).join(",") + "]";
  const keys = Object.keys(v).sort(cmpCodePoints);
  return "{" + keys.map((k) => pyJsonDumps(k) + ":" + pyJsonDumps(v[k])).join(",") + "}";
}

function cmpCodePoints(a, b) {
  const x = Array.from(a), y = Array.from(b);
  const n = Math.min(x.length, y.length);
  for (let i = 0; i < n; i++) {
    const p = x[i].codePointAt(0), q = y[i].codePointAt(0);
    if (p !== q) return p < q ? -1 : 1;
  }
  return x.length - y.length;
}

// Python == over JSON values (True == 1 and False == 0, as in Python).
function pyEq(a, b) {
  if (a === null || a === undefined) return b === null || b === undefined;
  if (b === null || b === undefined) return false;
  const na = typeof a === "boolean" ? Number(a) : a, nb = typeof b === "boolean" ? Number(b) : b;
  if (typeof na === "number" && typeof nb === "number") return na === nb;
  if (typeof a !== typeof b) return false;
  if (typeof a !== "object") return a === b;
  if (Array.isArray(a) !== Array.isArray(b)) return false;
  if (Array.isArray(a)) return a.length === b.length && a.every((x, i) => pyEq(x, b[i]));
  const ka = Object.keys(a), kb = Object.keys(b);
  return ka.length === kb.length && ka.every((k) => hasOwn(b, k) && pyEq(a[k], b[k]));
}

const isDict = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Uint8Array);
const isInt = (v) => typeof v === "number" && Number.isInteger(v);
const isNat = (v) => isInt(v) && v >= 0;
const keySetEq = (o, keys) => {
  const k = Object.keys(o);
  return k.length === keys.length && keys.every((x) => hasOwn(o, x));
};
const setdefault = (o, k, v) => {
  if (!hasOwn(o, k)) o[k] = v;
  return o[k];
};
const get = (o, k) => (hasOwn(o, k) && o[k] !== undefined ? o[k] : null);

// ================================================================ errors

class HandoffError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
  }
  toString() {
    return this.code + ": " + this.message;
  }
}
export class CanonError extends HandoffError { }
export class CryptoError extends HandoffError { }
export class EventError extends HandoffError { }
export class ProofError extends HandoffError { }
export class HeadError extends HandoffError { }
export class KeysError extends HandoffError { }
export class TransitionError extends HandoffError {
  constructor(code, message, seq = null) {
    super(code, message);
    this.seq = seq;
  }
}
export class InputError extends Error {
  constructor(message, code = "USAGE") {
    super(message);
    this.code = code;
  }
  toString() {
    return this.message;
  }
}

// ================================================================ SHA-256, SHA-512, HMAC (constants derived, not typed)

function primes(n) {
  const out = [];
  for (let k = 2; out.length < n; k++) if (out.every((p) => k % p)) out.push(k);
  return out;
}
function iroot(n, r) {
  // floor(n ** (1/r)) for BigInt n >= 0, by Newton's method from above
  if (n < 2n) return n;
  let x = 1n << BigInt(Math.ceil(n.toString(2).length / r) + 1);
  for (;;) {
    const y = ((BigInt(r) - 1n) * x + n / x ** BigInt(r - 1)) / BigInt(r);
    if (y >= x) return x;
    x = y;
  }
}
const PR80 = primes(80);
const K256 = Uint32Array.from(PR80.slice(0, 64), (p) => Number(iroot(BigInt(p) << 96n, 3) & 0xffffffffn));
const H256 = Uint32Array.from(PR80.slice(0, 8), (p) => Number(iroot(BigInt(p) << 64n, 2) & 0xffffffffn));
const M64 = (1n << 64n) - 1n;
const K512 = PR80.map((p) => iroot(BigInt(p) << 192n, 3) & M64);
const H512 = PR80.slice(0, 8).map((p) => iroot(BigInt(p) << 128n, 2) & M64);

function mdPad(data, blockLen, lenBytes) {
  const l = data.length;
  const total = Math.ceil((l + 1 + lenBytes) / blockLen) * blockLen;
  const buf = new Uint8Array(total);
  buf.set(data);
  buf[l] = 0x80;
  let bits = BigInt(l) * 8n;
  for (let i = total - 1; bits > 0n; i--) {
    buf[i] = Number(bits & 255n);
    bits >>= 8n;
  }
  return buf;
}

export function sha256(data) {
  const buf = mdPad(data, 64, 8);
  const h = Uint32Array.from(H256);
  const w = new Uint32Array(64);
  const rotr = (x, n) => (x >>> n) | (x << (32 - n));
  for (let off = 0; off < buf.length; off += 64) {
    for (let t = 0; t < 16; t++) {
      const j = off + 4 * t;
      w[t] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3];
    }
    for (let t = 16; t < 64; t++) {
      const a = w[t - 15], b = w[t - 2];
      const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
      const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
      w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;
    }
    let [a, b, c, d, e, f, g, hh] = h;
    for (let t = 0; t < 64; t++) {
      const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
      const ch = (e & f) ^ (~e & g);
      const t1 = (hh + S1 + ch + K256[t] + w[t]) | 0;
      const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
      const mj = (a & b) ^ (a & c) ^ (b & c);
      const t2 = (S0 + mj) | 0;
      hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
    }
    h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
  }
  const out = new Uint8Array(32);
  for (let i = 0; i < 8; i++) {
    out[4 * i] = h[i] >>> 24; out[4 * i + 1] = (h[i] >>> 16) & 255; out[4 * i + 2] = (h[i] >>> 8) & 255; out[4 * i + 3] = h[i] & 255;
  }
  return out;
}

export function sha512(data) {
  const buf = mdPad(data, 128, 16);
  const h = H512.slice();
  const rotr = (x, n) => ((x >> n) | (x << (64n - n))) & M64;
  const w = new Array(80);
  for (let off = 0; off < buf.length; off += 128) {
    for (let t = 0; t < 16; t++) {
      let v = 0n;
      for (let k = 0; k < 8; k++) v = (v << 8n) | BigInt(buf[off + 8 * t + k]);
      w[t] = v;
    }
    for (let t = 16; t < 80; t++) {
      const s0 = rotr(w[t - 15], 1n) ^ rotr(w[t - 15], 8n) ^ (w[t - 15] >> 7n);
      const s1 = rotr(w[t - 2], 19n) ^ rotr(w[t - 2], 61n) ^ (w[t - 2] >> 6n);
      w[t] = (w[t - 16] + s0 + w[t - 7] + s1) & M64;
    }
    let [a, b, c, d, e, f, g, hh] = h;
    for (let t = 0; t < 80; t++) {
      const S1 = rotr(e, 14n) ^ rotr(e, 18n) ^ rotr(e, 41n);
      const ch = (e & f) ^ (~e & M64 & g);
      const t1 = (hh + S1 + ch + K512[t] + w[t]) & M64;
      const S0 = rotr(a, 28n) ^ rotr(a, 34n) ^ rotr(a, 39n);
      const mj = (a & b) ^ (a & c) ^ (b & c);
      const t2 = (S0 + mj) & M64;
      hh = g; g = f; f = e; e = (d + t1) & M64; d = c; c = b; b = a; a = (t1 + t2) & M64;
    }
    const v = [a, b, c, d, e, f, g, hh];
    for (let i = 0; i < 8; i++) h[i] = (h[i] + v[i]) & M64;
  }
  const out = new Uint8Array(64);
  for (let i = 0; i < 8; i++) for (let k = 0; k < 8; k++) out[8 * i + k] = Number((h[i] >> BigInt(56 - 8 * k)) & 255n);
  return out;
}

export function hmacSha256(key, msg) {
  let k = key.length > 64 ? sha256(key) : key;
  const k0 = new Uint8Array(64);
  k0.set(k);
  const ip = k0.map((x) => x ^ 0x36), op = k0.map((x) => x ^ 0x5c);
  return sha256(concat(op, sha256(concat(ip, msg))));
}

// ================================================================ canon.py: canonical JSON (G5 profile, RFC 8785)

const MAX_SAFE_INT = 2 ** 53 - 1;
const KEY_RE = /^[a-z][a-z0-9_]{0,31}$/;
const BANNED_RE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069\u200b\u200c\u200d\u2060\ufeff]/;
const LONE_SURROGATE_RE = /[\ud800-\udbff](?![\udc00-\udfff])|(?:^|[^\ud800-\udbff])[\udc00-\udfff]/;

class Limits {
  constructor(maxBytes, maxDepth, maxMembers, maxItems, maxStringBytes = 4096) {
    Object.assign(this, { maxBytes, maxDepth, maxMembers, maxItems, maxStringBytes });
  }
}
export const EVENT_LIMITS = new Limits(16 * 1024, 8, 64, 64);
export const EXPORT_LIMITS = new Limits(16 * 1024 * 1024, 11, 64, 1000);
export const SIDE_LIMITS = new Limits(1024 * 1024, 8, 64, 1000);

function checkString(s, lim = EVENT_LIMITS) {
  if (LONE_SURROGATE_RE.test(s)) throw new CanonError("STR_LONE_SURROGATE", "string holds a lone surrogate");
  const n = utf8(s).length;
  if (n > lim.maxStringBytes) {
    throw new CanonError("LIMIT_STRING", `string of ${n} UTF-8 bytes exceeds ${lim.maxStringBytes}`);
  }
  const m = BANNED_RE.exec(s);
  if (m) {
    throw new CanonError("STR_BANNED_CHAR", "banned code point U+" + m[0].charCodeAt(0).toString(16).toUpperCase().padStart(4, "0"));
  }
  if (nfc15(s) !== s) throw new CanonError("STR_NOT_NFC", "string is not in NFC");
}

function checkKey(k) {
  if (!KEY_RE.test(k)) throw new CanonError("KEY_FORM", `key ${pyRepr(cpSlice(k, 40))} is not ASCII [a-z][a-z0-9_]{0,31}`);
}

function checkInt(n) {
  if (!(-MAX_SAFE_INT <= n && n <= MAX_SAFE_INT)) throw new CanonError("NUM_RANGE", "integer outside +/-(2^53 - 1)");
}

const ESC = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
// Python's str.isdigit() beyond General_Category Nd (Numeric_Type Digit), from Python 3.12.3 unicodedata 15.0.0.
const PY_DIGIT_EXTRA = /[\u00b2-\u00b3\u00b9\u1369-\u1371\u19da\u2070\u2074-\u2079\u2080-\u2089\u2460-\u2468\u2474-\u247c\u2488-\u2490\u24ea\u24f5-\u24fd\u24ff\u2776-\u277e\u2780-\u2788\u278a-\u2792\u{10a40}-\u{10a43}\u{10e60}-\u{10e68}\u{11052}-\u{1105a}\u{1f100}-\u{1f10a}]/u;

class Parser {
  constructor(text, lim) {
    this.s = text;
    this.i = 0;
    this.n = text.length;
    this.lim = lim;
  }
  err(code, msg) {
    throw new CanonError(code, `${msg} (at char ${cpCount(this.s, this.i)})`);
  }
  ws() {
    const s = this.s;
    let i = this.i;
    while (i < this.n) {
      const c = s.charCodeAt(i);
      if (c === 32 || c === 9 || c === 10 || c === 13) i++;
      else break;
    }
    this.i = i;
  }
  value(depth) {
    this.ws();
    if (this.i >= this.n) this.err("JSON_SYNTAX", "unexpected end of input");
    const c = this.s[this.i];
    if (c === "{") return this.obj(depth + 1);
    if (c === "[") return this.arr(depth + 1);
    if (c === '"') return this.string(false);
    const ch = cpAt(this.s, this.i);
    if (c === "-" || ((/\p{Nd}/u.test(ch) || PY_DIGIT_EXTRA.test(ch)) && assigned15(ch.codePointAt(0)))) return this.number();
    for (const [lit, val] of [["true", true], ["false", false], ["null", null]]) {
      if (this.s.startsWith(lit, this.i)) {
        if (val === null) this.err("JSON_NULL", "null is not allowed (an absent member is written by omitting it)");
        this.i += lit.length;
        return val;
      }
    }
    for (const bad of ["NaN", "Infinity", "-Infinity"]) {
      if (this.s.startsWith(bad, this.i)) this.err("JSON_NAN_INF", `${bad} is not JSON`);
    }
    this.err("JSON_SYNTAX", `unexpected character ${pyRepr(ch)}`);
  }
  obj(depth) {
    if (depth > this.lim.maxDepth) this.err("LIMIT_DEPTH", `nesting deeper than ${this.lim.maxDepth}`);
    this.i++;
    const out = Object.create(null);
    let count = 0;
    this.ws();
    if (this.i < this.n && this.s[this.i] === "}") {
      this.i++;
      return out;
    }
    for (;;) {
      this.ws();
      if (this.i >= this.n || this.s[this.i] !== '"') this.err("JSON_SYNTAX", "expected a key");
      const k = this.string(true);
      if (hasOwn(out, k)) this.err("JSON_DUP_KEY", `duplicate key ${pyRepr(cpSlice(k, 40))}`);
      if (count >= this.lim.maxMembers) this.err("LIMIT_MEMBERS", `object has more than ${this.lim.maxMembers} members`);
      this.ws();
      if (this.i >= this.n || this.s[this.i] !== ":") this.err("JSON_SYNTAX", "expected ':'");
      this.i++;
      out[k] = this.value(depth);
      count++;
      this.ws();
      if (this.i < this.n && this.s[this.i] === ",") {
        this.i++;
        continue;
      }
      if (this.i < this.n && this.s[this.i] === "}") {
        this.i++;
        return out;
      }
      this.err("JSON_SYNTAX", "expected ',' or '}'");
    }
  }
  arr(depth) {
    if (depth > this.lim.maxDepth) this.err("LIMIT_DEPTH", `nesting deeper than ${this.lim.maxDepth}`);
    this.i++;
    const out = [];
    this.ws();
    if (this.i < this.n && this.s[this.i] === "]") {
      this.i++;
      return out;
    }
    for (;;) {
      if (out.length >= this.lim.maxItems) this.err("LIMIT_ITEMS", `array has more than ${this.lim.maxItems} items`);
      out.push(this.value(depth));
      this.ws();
      if (this.i < this.n && this.s[this.i] === ",") {
        this.i++;
        continue;
      }
      if (this.i < this.n && this.s[this.i] === "]") {
        this.i++;
        return out;
      }
      this.err("JSON_SYNTAX", "expected ',' or ']'");
    }
  }
  string(isKey) {
    const s = this.s;
    const PLAIN = /[^"\\\u0000-\u001f]*/y;
    this.i++;
    const parts = [];
    let budget = this.lim.maxStringBytes;
    for (;;) {
      PLAIN.lastIndex = this.i;
      const m = PLAIN.exec(s);
      const chunk = m[0];
      if (chunk) {
        parts.push(chunk);
        budget -= cpLen(chunk);
        if (budget < -3 * this.lim.maxStringBytes) this.err("LIMIT_STRING", "string too long");
      }
      this.i = m.index + chunk.length;
      if (this.i >= this.n) this.err("JSON_SYNTAX", "unterminated string");
      const c = s[this.i];
      if (c === '"') {
        this.i++;
        break;
      }
      if (c === "\\") {
        const e = s.substring(this.i + 1, this.i + 2);
        if (hasOwn(ESC, e)) {
          parts.push(ESC[e]);
          this.i += 2;
        } else if (e === "u") {
          let cp = this.hex4(this.i + 2);
          this.i += 6;
          if (cp >= 0xd800 && cp <= 0xdbff) {
            if (s.substring(this.i, this.i + 2) !== "\\u") this.err("STR_LONE_SURROGATE", "high surrogate without a low surrogate");
            const lo = this.hex4(this.i + 2);
            if (!(lo >= 0xdc00 && lo <= 0xdfff)) this.err("STR_LONE_SURROGATE", "high surrogate without a low surrogate");
            this.i += 6;
            cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00);
          } else if (cp >= 0xdc00 && cp <= 0xdfff) {
            this.err("STR_LONE_SURROGATE", "lone low surrogate");
          }
          parts.push(String.fromCodePoint(cp));
        } else {
          this.err("JSON_SYNTAX", "bad escape");
        }
      } else {
        this.err("JSON_CONTROL_CHAR", "raw control character in string");
      }
    }
    const out = parts.join("");
    if (isKey) checkKey(out);
    else checkString(out, this.lim);
    return out;
  }
  hex4(j) {
    const h = this.s.substring(j, j + 4);
    if (!/^[0-9a-fA-F]{4}$/.test(h)) this.err("JSON_SYNTAX", "bad \\u escape");
    return parseInt(h, 16);
  }
  number() {
    const NUM = /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/y;
    NUM.lastIndex = this.i;
    const m = NUM.exec(this.s);
    if (!m) {
      if (this.s.startsWith("-Infinity", this.i)) this.err("JSON_NAN_INF", "-Infinity is not JSON");
      this.err("JSON_SYNTAX", "bad number");
    }
    const tok = m[0];
    this.i = m.index + tok.length;
    if (m[2] || m[3]) this.err("NUM_NOT_INTEGER", `fraction or exponent in ${pyRepr(tok.slice(0, 40))}`);
    if (tok === "-0") this.err("NUM_NEG_ZERO", "-0 is not allowed");
    if (tok.replace(/^-+/, "").length > 16) this.err("NUM_RANGE", "integer outside +/-(2^53 - 1)");
    const big = BigInt(tok);
    if (big < -BigInt(MAX_SAFE_INT) || big > BigInt(MAX_SAFE_INT)) checkInt(Infinity);
    return Number(tok);
  }
}

export function canonLoads(data, lim = EXPORT_LIMITS) {
  if (!(data instanceof Uint8Array)) data = asBytes(data, "the input");
  if (data.length > lim.maxBytes) throw new CanonError("LIMIT_SIZE", `input of ${data.length} bytes exceeds ${lim.maxBytes}`);
  if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
    throw new CanonError("JSON_BOM", "a UTF-8 BOM is not allowed");
  }
  const bad = utf8InvalidAt(data);
  if (bad >= 0) throw new CanonError("JSON_BAD_UTF8", `invalid UTF-8 at byte ${bad}`);
  const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(data);
  const p = new Parser(text, lim);
  const v = p.value(0);
  p.ws();
  if (p.i !== p.n) p.err("JSON_SYNTAX", "trailing data");
  return v;
}

function quote(s) {
  let out = '"';
  for (let i = 0; i < s.length; i++) {
    const ch = s[i], c = s.charCodeAt(i);
    if (ch === '"') out += '\\"';
    else if (ch === "\\") out += "\\\\";
    else if (c === 8) out += "\\b";
    else if (c === 12) out += "\\f";
    else if (c === 10) out += "\\n";
    else if (c === 13) out += "\\r";
    else if (c === 9) out += "\\t";
    else if (c < 0x20) out += "\\u" + c.toString(16).padStart(4, "0");
    else out += ch;
  }
  return out + '"';
}

function dumpInto(v, lim, depth, out) {
  if (v === null || v === undefined) throw new CanonError("JSON_NULL", "null has no form in the profile");
  if (v === true) out.push("true");
  else if (v === false) out.push("false");
  else if (typeof v === "number") {
    if (!Number.isInteger(v)) throw new CanonError("NUM_NOT_INTEGER", "floats are not allowed in the profile");
    checkInt(v);
    out.push(String(v));
  } else if (typeof v === "string") {
    checkString(v, lim);
    out.push(quote(v));
  } else if (Array.isArray(v)) {
    if (depth + 1 > lim.maxDepth) throw new CanonError("LIMIT_DEPTH", `nesting deeper than ${lim.maxDepth}`);
    if (v.length > lim.maxItems) throw new CanonError("LIMIT_ITEMS", `array has more than ${lim.maxItems} items`);
    out.push("[");
    v.forEach((item, i) => {
      if (i) out.push(",");
      dumpInto(item, lim, depth + 1, out);
    });
    out.push("]");
  } else if (isDict(v)) {
    const keys = Object.keys(v).filter((k) => v[k] !== null && v[k] !== undefined);
    if (depth + 1 > lim.maxDepth) throw new CanonError("LIMIT_DEPTH", `nesting deeper than ${lim.maxDepth}`);
    if (keys.length > lim.maxMembers) throw new CanonError("LIMIT_MEMBERS", `object has more than ${lim.maxMembers} members`);
    keys.sort(); // RFC 8785 section 3.2.3: UTF-16 code units, which is JavaScript's default string order
    out.push("{");
    keys.forEach((k, i) => {
      checkKey(k);
      if (i) out.push(",");
      out.push(quote(k));
      out.push(":");
      dumpInto(v[k], lim, depth + 1, out);
    });
    out.push("}");
  } else {
    throw new CanonError("JSON_TYPE", `type ${typeof v} has no JSON form`);
  }
}

// Canonical text; its UTF-8 bytes are the canonical bytes.
export function canonDumpsText(v, lim = EVENT_LIMITS) {
  const out = [];
  dumpInto(v, lim, 0, out);
  const s = out.join("");
  const n = utf8(s).length;
  if (n > lim.maxBytes) throw new CanonError("LIMIT_SIZE", `canonical form of ${n} bytes exceeds ${lim.maxBytes}`);
  return s;
}
export const canonDumps = (v, lim = EVENT_LIMITS) => utf8(canonDumpsText(v, lim));
export const C = (v) => canonDumps(v, EVENT_LIMITS);

// ================================================================ crypto.py: hashes, domain tags, strict Ed25519

export const FORMAT = "handoff/v0";
const HEX32_RE = /^[0-9a-f]{32}$/;
const HEX64_RE = /^[0-9a-f]{64}$/;
const HEX128_RE = /^[0-9a-f]{128}$/;
const isHex = (v, rx) => typeof v === "string" && rx.test(v);

export const DT = (name) => concat(utf8("weio-handoff/v0/" + name), new Uint8Array([0]));
export const H = (...parts) => sha256(concat(...parts));
export const keyId = (pub) => toHex(H(DT("key"), pub).slice(0, 16));

const P = 2n ** 255n - 19n;
const L = 2n ** 252n + 27742317777372353535851937790883648493n;
const md = (a) => {
  const r = a % P;
  return r < 0n ? r + P : r;
};
function powmod(b, e, m) {
  let r = 1n;
  b %= m;
  if (b < 0n) b += m;
  while (e > 0n) {
    if (e & 1n) r = (r * b) % m;
    b = (b * b) % m;
    e >>= 1n;
  }
  return r;
}
const inv = (x) => powmod(x, P - 2n, P);
const D = md(-121665n * inv(121666n));
const D2 = md(2n * D);
const SQRT_M1 = powmod(2n, (P - 1n) / 4n, P);

function leToBig(b) {
  let n = 0n;
  for (let i = b.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(b[i]);
  return n;
}

function decodePoint(b, what) {
  if (b.length !== 32) throw new CryptoError("ED_BAD_LENGTH", `${what} is not 32 bytes`);
  const n = leToBig(b);
  const sign = n >> 255n;
  const y = n & ((1n << 255n) - 1n);
  if (y >= P) throw new CryptoError("ED_NONCANONICAL_" + what, `${what} encodes y >= p`);
  const u = md(y * y - 1n);
  const v = md(D * y * y + 1n);
  let x = md(u * powmod(v, 3n, P) * powmod(u * powmod(v, 7n, P), (P - 5n) / 8n, P));
  const vx2 = md(v * x * x);
  if (vx2 === u) {
    // x is a square root
  } else if (vx2 === md(-u)) {
    x = md(x * SQRT_M1);
  } else {
    throw new CryptoError("ED_NOT_ON_CURVE_" + what, `${what} is not a curve point`);
  }
  if (x === 0n && sign === 1n) throw new CryptoError("ED_NONCANONICAL_" + what, `${what} encodes x = 0 with the sign bit set`);
  if ((x & 1n) !== sign) x = P - x;
  return [x, y];
}

// Extended coordinates (X, Y, Z, T), x = X/Z, y = Y/Z, xy = T/Z; the unified addition of crypto.py's _eadd.
const ext = ([x, y]) => [x, y, 1n, md(x * y)];
const IDENT = [0n, 1n, 1n, 0n];
function eadd(p1, p2) {
  const [X1, Y1, Z1, T1] = p1, [X2, Y2, Z2, T2] = p2;
  const a = md((Y1 - X1) * (Y2 - X2));
  const b = md((Y1 + X1) * (Y2 + X2));
  const c = md(D2 * T1 * T2);
  const d = md(2n * Z1 * Z2);
  const e = b - a, f = d - c, g = d + c, h = b + a;
  return [md(e * f), md(g * h), md(f * g), md(e * h)];
}
const isIdentity = (p) => md(p[0]) === 0n && md(p[1] - p[2]) === 0n;
function emul(k, pt) {
  let acc = IDENT, q = pt;
  while (k > 0n) {
    if (k & 1n) acc = eadd(acc, q);
    q = eadd(q, q);
    k >>= 1n;
  }
  return acc;
}
const isSmallOrder = (pt) => isIdentity(emul(8n, ext(pt)));
const inPrimeSubgroup = (pt) => isIdentity(emul(L, ext(pt)));
function encodePoint(p) {
  const zi = inv(p[2]);
  const x = md(p[0] * zi), y = md(p[1] * zi);
  let n = y | ((x & 1n) << 255n);
  const out = new Uint8Array(32);
  for (let i = 0; i < 32; i++) {
    out[i] = Number(n & 255n);
    n >>= 8n;
  }
  return out;
}
const BASE = [15112221349535400772501151409588531511454012693041857206046113283949847762202n,
  46316835694926478169428394003475163141307993866256225615783033603165251855960n];

const pubCache = new Map();
export function checkPublicKey(pub) {
  const k = toHex(pub);
  let r = pubCache.get(k);
  if (r === undefined) {
    r = null;
    try {
      const pt = decodePoint(pub, "A");
      if (isSmallOrder(pt)) throw new CryptoError("ED_SMALL_ORDER_A", "public key is a small-order point");
      if (!inPrimeSubgroup(pt)) throw new CryptoError("ED_TORSION_A", "public key has a torsion component (mixed order)");
      r = { pt };
    } catch (e) {
      if (!(e instanceof CryptoError)) throw e;
      r = { err: [e.code, e.message] };
    }
    if (pubCache.size > 4096) pubCache.clear();
    pubCache.set(k, r);
  }
  if (r.err) throw new CryptoError(r.err[0], r.err[1]);
  return r.pt;
}

function checkSignatureForm(sig) {
  if (sig.length !== 64) throw new CryptoError("ED_BAD_LENGTH", "signature is not 64 bytes");
  const rpt = decodePoint(sig.slice(0, 32), "R");
  if (isSmallOrder(rpt)) throw new CryptoError("ED_SMALL_ORDER_R", "R is a small-order point");
  if (!inPrimeSubgroup(rpt)) throw new CryptoError("ED_TORSION_R", "R has a torsion component (mixed order)");
  const s = leToBig(sig.slice(32));
  if (s >= L) throw new CryptoError("ED_S_NOT_REDUCED", "S >= L (malleated signature)");
  return s;
}

// Strict Ed25519 (crypto.verify): our checks first, then the RFC 8032 equation [S]B = R + [k]A, checked as
// encode([S]B - [k]A) == R, the cofactorless check OpenSSL makes. Throws CryptoError on any failure.
export function ed25519Verify(pub, sig, msg) {
  const A = checkPublicKey(pub);
  const s = checkSignatureForm(sig);
  const k = leToBig(sha512(concat(sig.slice(0, 32), pub, msg))) % L;
  const negA = ext([md(-A[0]), A[1]]);
  // Straus: [s]B + [k](-A) with shared doublings
  const B = ext(BASE), BA = eadd(B, negA);
  let acc = IDENT;
  for (let i = 255; i >= 0; i--) {
    acc = eadd(acc, acc);
    const bs = (s >> BigInt(i)) & 1n, bk = (k >> BigInt(i)) & 1n;
    if (bs && bk) acc = eadd(acc, BA);
    else if (bs) acc = eadd(acc, B);
    else if (bk) acc = eadd(acc, negA);
  }
  if (!bytesEq(encodePoint(acc), sig.slice(0, 32))) throw new CryptoError("ED_BAD_SIGNATURE", "signature does not verify");
}

export function sigInput(kind, objCanonicalBytes) {
  if (!["sig-event", "sig-agent", "sig-head", "sig-key"].includes(kind)) throw new Error("unknown signature kind");
  return concat(DT(kind), H(objCanonicalBytes));
}

export const normalizeEmail = (addr) => lower15(nfc15(pyStrip(addr)));
export function partyDigest(kRec, value) {
  if (!(kRec instanceof Uint8Array) || kRec.length !== 32) throw new Error("k_rec must be 32 bytes");
  return toHex(hmacSha256(kRec, utf8(value)));
}
export const emailDigest = (kRec, addr) => partyDigest(kRec, normalizeEmail(addr));

// ================================================================ keys.py: the G6 key history

const KEY_ENTRY_KEYS = ["key_id", "alg", "pubkey", "valid_from_head", "retired_after_head", "revoked_from_head", "reason",
  "endorsed_by", "endorsement"];
const OPTIONAL_ENTRY_KEYS = ["retired_after_head", "revoked_from_head", "reason", "endorsed_by"];

function kneed(cond, code, msg) {
  if (!cond) throw new KeysError(code, msg);
}
const optInt = (v, what) => kneed(v === null || isNat(v), "KEYS_FORM", `${what} must be null or an integer >= 0`);

function inflateKeyEntry(e) {
  if (isDict(e)) for (const k of OPTIONAL_ENTRY_KEYS) setdefault(e, k, null);
  return e;
}
function inflateKeysDoc(doc) {
  if (isDict(doc) && Array.isArray(get(doc, "entries"))) for (const e of doc.entries) inflateKeyEntry(e);
  return doc;
}

function checkEntryForm(e) {
  kneed(isDict(e) && keySetEq(e, KEY_ENTRY_KEYS), "KEYS_FORM", "key entry has the wrong fields");
  kneed(isHex(e.key_id, HEX32_RE), "KEYS_FORM", "key_id form");
  kneed(e.alg === "ed25519", "KEYS_FORM", "alg must be ed25519");
  kneed(isHex(e.pubkey, HEX64_RE), "KEYS_FORM", "pubkey form");
  kneed(isNat(e.valid_from_head), "KEYS_FORM", "valid_from_head form");
  optInt(e.retired_after_head, "retired_after_head");
  optInt(e.revoked_from_head, "revoked_from_head");
  kneed([null, "rotation", "compromise"].includes(e.reason), "KEYS_FORM", "reason form");
  kneed(e.endorsed_by === null || isHex(e.endorsed_by, HEX32_RE), "KEYS_FORM", "endorsed_by form");
  kneed(isHex(e.endorsement, HEX128_RE), "KEYS_FORM", "endorsement form");
  kneed(keyId(fromHex(e.pubkey)) === e.key_id, "KEYS_FORM", "key_id is not derived from pubkey");
}

function entrySignedBytes(e) {
  const body = {};
  for (const k of Object.keys(e)) if (k !== "endorsement") body[k] = e[k];
  return sigInput("sig-key", C(body));
}

export class KeyHistory {
  constructor(entries) {
    this.entries = entries;
    this.state = new Map();
    this.intro = new Map();
    this.validate();
  }
  static fromDoc(doc) {
    kneed(isDict(doc) && keySetEq(doc, ["format", "entries"]), "KEYS_FORM", "keys.json form");
    kneed(doc.format === FORMAT, "KEYS_FORM", "keys.json format is not handoff/v0");
    kneed(Array.isArray(doc.entries) && doc.entries.length > 0, "KEYS_FORM", "keys.json has no entries");
    return new KeyHistory(doc.entries);
  }
  static fromBytes(raw) {
    let doc;
    try {
      doc = canonLoads(raw, SIDE_LIMITS);
    } catch (e) {
      if (!(e instanceof CanonError)) throw e;
      throw new KeysError("KEYS_FORM", "keys.json refused by the canonical parser: " + e.message);
    }
    return KeyHistory.fromDoc(inflateKeysDoc(doc));
  }
  validate() {
    this.entries.forEach((e, i) => {
      checkEntryForm(e);
      try {
        checkPublicKey(fromHex(e.pubkey));
      } catch (ce) {
        if (!(ce instanceof CryptoError)) throw ce;
        throw new KeysError("KEYS_BAD_KEY", `entry ${i}: ${ce.code}`);
      }
      const kid = e.key_id;
      const prev = this.state.has(kid) ? this.state.get(kid) : null;
      let signer;
      if (i === 0) {
        kneed(e.endorsed_by === null, "KEYS_ENDORSEMENT", "entry 0 must be self-signed");
        signer = e.pubkey;
      } else {
        const end = e.endorsed_by;
        kneed(this.state.has(end), "KEYS_ENDORSEMENT", `entry ${i} endorsed by an unknown key`);
        kneed(this.state.get(end).revoked_from_head === null, "KEYS_ENDORSEMENT", `entry ${i} endorsed by a revoked key`);
        const isRevocation = e.revoked_from_head !== null && (prev === null || prev.revoked_from_head === null);
        if (isRevocation) kneed(end !== kid, "KEYS_ENDORSEMENT", "a revocation is endorsed by another key");
        kneed(this.state.get(end).retired_after_head === null || isRevocation, "KEYS_ENDORSEMENT",
          `entry ${i} endorsed by a retired key (a retired key may endorse only a revocation)`);
        signer = this.state.get(end).pubkey;
      }
      try {
        ed25519Verify(fromHex(signer), fromHex(e.endorsement), entrySignedBytes(e));
      } catch (ce) {
        if (!(ce instanceof CryptoError)) throw ce;
        throw new KeysError("KEYS_ENDORSEMENT", `entry ${i} endorsement fails (${ce.code})`);
      }
      if (prev === null) {
        kneed(e.retired_after_head === null && e.revoked_from_head === null && e.reason === null, "KEYS_FORM",
          "an introducing entry carries no retirement or revocation");
        if (i > 0) {
          let mx = -Infinity;
          for (const st of this.state.values()) if (st.valid_from_head > mx) mx = st.valid_from_head;
          kneed(e.valid_from_head >= mx, "KEYS_FORM", "a new key cannot start before an earlier key");
        }
        this.intro.set(kid, e);
      } else {
        kneed(e.pubkey === prev.pubkey && e.valid_from_head === prev.valid_from_head, "KEYS_FORM",
          "an update must keep pubkey and valid_from_head");
        for (const f of ["retired_after_head", "revoked_from_head"]) {
          kneed(prev[f] === null || prev[f] === e[f], "KEYS_FORM", `${f} cannot change once set`);
        }
        if (e.retired_after_head !== null) kneed(e.retired_after_head >= e.valid_from_head, "KEYS_FORM", "retired before valid");
        kneed(e.reason === (e.revoked_from_head !== null ? "compromise" : "rotation"), "KEYS_FORM",
          "reason must be compromise for a revocation, else rotation");
      }
      this.state.set(kid, e);
    });
    for (const [kid, intro] of this.intro) {
      const m = intro.valid_from_head;
      if (intro === this.entries[0] || m === 0) continue;
      for (const [pid, p] of this.state) {
        if (pid === kid || p.revoked_from_head !== null || p.valid_from_head >= m) continue;
        if (p.retired_after_head !== null && m - 1 <= p.retired_after_head && p.retired_after_head < m + 1) {
          throw new KeysError("KEYS_OVERLAP", `key ${pid} retires after head ${p.retired_after_head}, before the 2-head overlap with ` +
            `key ${kid} (valid from head ${m}) ends`);
        }
      }
    }
  }
  known(kid) {
    return this.state.has(kid);
  }
  validAt(kid, n) {
    const e = this.state.get(kid);
    if (e === undefined) return false;
    if (n < e.valid_from_head) return false;
    if (e.retired_after_head !== null && n > e.retired_after_head) return false;
    if (e.revoked_from_head !== null && n >= e.revoked_from_head) return false;
    return true;
  }
  requiredSigners(n) {
    return [...this.state.keys()].filter((k) => this.validAt(k, n)).sort();
  }
  pubkey(kid) {
    return fromHex(this.state.get(kid).pubkey);
  }
  compromised(kid) {
    const e = this.state.get(kid);
    return e !== undefined && e.revoked_from_head !== null;
  }
  toDoc() {
    return { format: FORMAT, entries: this.entries };
  }
}

// ================================================================ log.py: RFC 9162 Merkle proofs and the tip tree

const MAX_PATH = 64;
const EMPTY_ROOT = sha256(new Uint8Array(0));
const leafHash = (leafInput) => H(new Uint8Array([0]), leafInput);
const nodeHash = (l, r) => H(new Uint8Array([1]), l, r);

function parsePath(path) {
  if (!Array.isArray(path)) throw new ProofError("PROOF_MALFORMED", "proof path is not a list");
  if (path.length > MAX_PATH) throw new ProofError("PROOF_TOO_LONG", `proof path of ${path.length} nodes exceeds ${MAX_PATH}`);
  return path.map((p) => {
    if (!isHex(p, HEX64_RE)) throw new ProofError("PROOF_MALFORMED", "proof node is not 64 lowercase hex");
    return fromHex(p);
  });
}

// Tree sizes and indices are < 2^53, so they are handled as BigInt for the bit arithmetic of RFC 9162.
function verifyInclusion(leafIndex, treeSize, leafH, path, root) {
  if (path.length > MAX_PATH) throw new ProofError("PROOF_TOO_LONG", "proof path too long");
  if (!(0 <= leafIndex && leafIndex < treeSize)) {
    throw new ProofError("PROOF_INDEX", `leaf index ${leafIndex} not below tree size ${treeSize}`);
  }
  let fn = BigInt(leafIndex), sn = BigInt(treeSize) - 1n, r = leafH;
  for (const p of path) {
    if (sn === 0n) throw new ProofError("PROOF_INCLUSION", "inclusion path too long for the tree");
    if (fn & 1n || fn === sn) {
      r = nodeHash(p, r);
      if (!(fn & 1n)) {
        while (!(fn & 1n || fn === 0n)) {
          fn >>= 1n;
          sn >>= 1n;
        }
      }
    } else {
      r = nodeHash(r, p);
    }
    fn >>= 1n;
    sn >>= 1n;
  }
  if (sn !== 0n || !bytesEq(r, root)) throw new ProofError("PROOF_INCLUSION", "inclusion proof does not reach the head's root");
}

function verifyConsistency(first, second, firstRoot, secondRoot, path) {
  if (path.length > MAX_PATH) throw new ProofError("PROOF_TOO_LONG", "proof path too long");
  if (first > second) throw new ProofError("PROOF_CONSISTENCY", "first size exceeds second size");
  if (first === second) {
    if (path.length || !bytesEq(firstRoot, secondRoot)) {
      throw new ProofError("PROOF_CONSISTENCY", "equal sizes must have equal roots and an empty proof");
    }
    return;
  }
  if (first === 0) {
    if (path.length || !bytesEq(firstRoot, EMPTY_ROOT)) throw new ProofError("PROOF_CONSISTENCY", "a proof from the empty tree is empty");
    return;
  }
  if (!path.length) throw new ProofError("PROOF_CONSISTENCY", "empty consistency proof");
  const f = BigInt(first);
  if ((f & (f - 1n)) === 0n) path = [firstRoot, ...path];
  let fn = f - 1n, sn = BigInt(second) - 1n;
  while (fn & 1n) {
    fn >>= 1n;
    sn >>= 1n;
  }
  let fr = path[0], sr = path[0];
  for (const c of path.slice(1)) {
    if (sn === 0n) throw new ProofError("PROOF_CONSISTENCY", "consistency path too long");
    if (fn & 1n || fn === sn) {
      fr = nodeHash(c, fr);
      sr = nodeHash(c, sr);
      if (!(fn & 1n)) {
        while (!(fn & 1n || fn === 0n)) {
          fn >>= 1n;
          sn >>= 1n;
        }
      }
    } else {
      sr = nodeHash(sr, c);
    }
    fn >>= 1n;
    sn >>= 1n;
  }
  if (!bytesEq(fr, firstRoot) || !bytesEq(sr, secondRoot) || sn !== 0n) {
    throw new ProofError("PROOF_CONSISTENCY", "consistency proof does not link the two roots");
  }
}

function u64(n) {
  const out = new Uint8Array(8);
  let v = BigInt(n);
  for (let i = 7; i >= 0; i--) {
    out[i] = Number(v & 255n);
    v >>= 8n;
  }
  return out;
}
const eventLeafInput = (tag, seq, evHash) => concat(DT("leaf"), tag, u64(seq), evHash);
const tipLeafInput = (tag, lastSeq, lastEventHash, logIndex) => concat(DT("tip"), tag, u64(lastSeq), lastEventHash, u64(logIndex));

function verifyTipMember(tag, tip, index, path, tipCount, tipRoot) {
  if (!bytesEq(tip[0], tag)) throw new ProofError("TIP_WRONG_RECORD", "tip leaf is for another record");
  verifyInclusion(index, tipCount, leafHash(tipLeafInput(...tip)), path, tipRoot);
}

function verifyTipAbsent(tag, left, right, tipCount, tipRoot) {
  if (tipCount === 0) {
    if (left !== null || right !== null || !bytesEq(tipRoot, EMPTY_ROOT)) {
      throw new ProofError("TIP_ABSENCE", "an empty tip tree has no neighbours");
    }
    return;
  }
  if (left === null && right === null) throw new ProofError("TIP_ABSENCE", "no neighbour given");
  if (left !== null) {
    verifyInclusion(left.index, tipCount, leafHash(tipLeafInput(...left.tip)), left.path, tipRoot);
    if (!(cmpBytes(left.tip[0], tag) < 0)) throw new ProofError("TIP_ABSENCE", "left neighbour does not sort before the record");
  }
  if (right !== null) {
    verifyInclusion(right.index, tipCount, leafHash(tipLeafInput(...right.tip)), right.path, tipRoot);
    if (!(cmpBytes(tag, right.tip[0]) < 0)) throw new ProofError("TIP_ABSENCE", "right neighbour does not sort after the record");
  }
  if (left !== null && right !== null) {
    if (right.index !== left.index + 1) throw new ProofError("TIP_ABSENCE", "neighbours are not adjacent");
  } else if (left === null) {
    if (right.index !== 0) throw new ProofError("TIP_ABSENCE", "lower edge must be leaf 0");
  } else if (left.index !== tipCount - 1) {
    throw new ProofError("TIP_ABSENCE", "upper edge must be the last leaf");
  }
}

// ================================================================ event.py: the envelope, bodies and signed bytes

const TYPES = ["COMMIT", "CONFIRM", "DELIVER", "ACCEPT", "REJECT", "AMEND", "REVERSE", "DISPUTE", "WITHDRAW", "ERASE"];
const ACTORS = ["P", "C", "W"];
const METHODS = ["email_token", "ed25519", "server"];
const ENVELOPE_KEYS = ["format", "record_id", "seq", "prev_hash", "type", "actor", "at", "body", "auth", "server_key_id"];
const AUTH_KEYS = ["method", "token_nonce", "token_expires", "agent_key_id"];
const TIME_RE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/;
const NAME_MAX_CHARS = 80;
const EVIDENCE_KINDS = ["file_sha256", "link", "note_digest", "payment_ref"];
const ERASE_FIELDS = ["email", "note"];
const ERASE_REASONS = ["request", "retention"];

function daysFromCivil(y, m, d) {
  y -= m <= 2 ? 1 : 0;
  const era = Math.floor(y / 400);
  const yoe = y - era * 400;
  const doy = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5) + d - 1;
  const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
  return era * 146097 + doe - 719468;
}

// G5 times: YYYY-MM-DDTHH:MM:SSZ only. Returns POSIX seconds (UTC), as calendar.timegm(time.strptime(...)).
export function parseTime(s) {
  if (typeof s !== "string" || !TIME_RE.test(s)) throw new EventError("TIME_FORM", `time ${pyRepr(s)} is not YYYY-MM-DDTHH:MM:SSZ`);
  if (parseInt(s.slice(17, 19), 10) > 59) throw new EventError("TIME_FORM", `time ${pyRepr(s)} has no leap or overflow seconds in handoff/v0`);
  const y = +s.slice(0, 4), mo = +s.slice(5, 7), d = +s.slice(8, 10), h = +s.slice(11, 13), mi = +s.slice(14, 16), se = +s.slice(17, 19);
  const leap = (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
  const dim = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (y < 1 || mo < 1 || mo > 12 || d < 1 || d > dim[mo - 1] || h > 23 || mi > 59) {
    throw new EventError("TIME_FORM", `time ${pyRepr(s)} is not a valid date`);
  }
  return daysFromCivil(y, mo, d) * 86400 + h * 3600 + mi * 60 + se;
}

export const genesis = (recordId) => toHex(H(DT("genesis"), utf8(FORMAT), new Uint8Array([0]), fromHex(recordId)));
export const recordTag = (recordId) => H(DT("tag"), fromHex(recordId));
export const eventHash = (event) => H(DT("event"), C(event));

function eneed(cond, code, message) {
  if (!cond) throw new EventError(code, message);
}
const ehex = (v, rx, what) => eneed(isHex(v, rx), "FIELD_FORM", `${what} has the wrong form`);
function ekeys(obj, required, optional, what) {
  eneed(isDict(obj), "FIELD_FORM", `${what} is not an object`);
  const ks = Object.keys(obj);
  const missing = required.filter((k) => !hasOwn(obj, k)).sort();
  const extra = ks.filter((k) => !required.includes(k) && !optional.includes(k)).sort();
  eneed(!missing.length, "FIELD_MISSING", `${what} lacks ${missing.join(", ")}`);
  eneed(!extra.length, "FIELD_UNKNOWN", `${what} has unknown field(s) ${extra.join(", ")}`);
}
const eint = (v, what, lo = 0) => eneed(isInt(v) && v >= lo, "FIELD_FORM", `${what} is not an integer >= ${lo}`);

function checkParty(p, what) {
  ekeys(p, ["digest"], ["agent_key", "name"], what);
  ehex(p.digest, HEX64_RE, what + ".digest");
  if (get(p, "agent_key") !== null) ehex(p.agent_key, HEX64_RE, what + ".agent_key");
  if (hasOwn(p, "name")) {
    eneed(typeof p.name === "string" && cpLen(p.name) > 0 && cpLen(p.name) <= NAME_MAX_CHARS, "FIELD_FORM",
      `${what}.name must be 1-${NAME_MAX_CHARS} characters`);
  }
}
function note(body, what) {
  if (hasOwn(body, "note_digest")) ehex(body.note_digest, HEX64_RE, what + ".note_digest");
}

function checkBody(etype, body, method) {
  const pd = method === "email_token" ? ["party_digest"] : [];
  if (etype === "COMMIT") {
    ekeys(body, ["terms_digest", "parties", ...pd], ["confirm_by", "oasf_ref"], "COMMIT.body");
    ehex(body.terms_digest, HEX64_RE, "terms_digest");
    ekeys(body.parties, ["p", "c"], [], "COMMIT.body.parties");
    checkParty(body.parties.p, "parties.p");
    checkParty(body.parties.c, "parties.c");
    if (hasOwn(body, "confirm_by")) parseTime(body.confirm_by);
    if (hasOwn(body, "oasf_ref")) {
      eneed(typeof body.oasf_ref === "string" && cpLen(body.oasf_ref) > 0 && cpLen(body.oasf_ref) <= 256, "FIELD_FORM",
        "oasf_ref must be 1-256 characters");
    }
  } else if (etype === "CONFIRM") {
    ekeys(body, ["ref", "terms_digest", ...pd], [], "CONFIRM.body");
    ehex(body.ref, HEX64_RE, "ref");
    ehex(body.terms_digest, HEX64_RE, "terms_digest");
  } else if (etype === "DELIVER") {
    ekeys(body, ["terms_digest", "evidence", ...pd], ["note_digest"], "DELIVER.body");
    ehex(body.terms_digest, HEX64_RE, "terms_digest");
    note(body, "DELIVER.body");
    const ev = body.evidence;
    eneed(Array.isArray(ev) && ev.length >= 1 && ev.length <= 16, "FIELD_FORM", "evidence must hold 1-16 items");
    ev.forEach((item, i) => {
      ekeys(item, ["kind", "value"], [], `evidence[${i}]`);
      eneed(EVIDENCE_KINDS.includes(item.kind), "FIELD_FORM", `evidence[${i}].kind is unknown`);
      const v = item.value;
      if (item.kind === "file_sha256" || item.kind === "note_digest") ehex(v, HEX64_RE, `evidence[${i}].value`);
      else if (item.kind === "link") {
        eneed(typeof v === "string" && v.startsWith("https://") && cpLen(v) <= 2048, "FIELD_FORM",
          `evidence[${i}].value must be an https link`);
      } else {
        eneed(typeof v === "string" && cpLen(v) > 0 && cpLen(v) <= 256, "FIELD_FORM", `evidence[${i}].value too long`);
      }
    });
  } else if (etype === "ACCEPT" || etype === "REJECT" || etype === "DISPUTE") {
    ekeys(body, ["ref", ...pd], ["note_digest"], etype + ".body");
    ehex(body.ref, HEX64_RE, "ref");
    note(body, etype + ".body");
  } else if (etype === "AMEND") {
    ekeys(body, ["terms_digest", ...pd], ["note_digest"], "AMEND.body");
    ehex(body.terms_digest, HEX64_RE, "terms_digest");
    note(body, "AMEND.body");
  } else if (etype === "REVERSE") {
    ekeys(body, ["ref", "terms_digest", ...pd], ["note_digest"], "REVERSE.body");
    ehex(body.ref, HEX64_RE, "ref");
    ehex(body.terms_digest, HEX64_RE, "terms_digest");
    note(body, "REVERSE.body");
  } else if (etype === "WITHDRAW") {
    ekeys(body, [...pd], ["note_digest"], "WITHDRAW.body");
    note(body, "WITHDRAW.body");
  } else if (etype === "ERASE") {
    ekeys(body, ["role", "fields", "reason"], [], "ERASE.body");
    eneed(body.role === "P" || body.role === "C", "FIELD_FORM", "ERASE.body.role must be P or C");
    const f = body.fields;
    eneed(Array.isArray(f) && f.every((x) => typeof x === "string") && f.length >= 1 && f.length <= ERASE_FIELDS.length &&
      new Set(f).size === f.length && f.every((x) => ERASE_FIELDS.includes(x)), "FIELD_FORM", "ERASE.body.fields must name email or note");
    eneed(ERASE_REASONS.includes(body.reason), "FIELD_FORM", "ERASE.body.reason must be request or retention");
  }
  if (pd.length && etype !== "ERASE") ehex(body.party_digest, HEX64_RE, "party_digest");
}

export function checkEvent(event) {
  eneed(isDict(event), "FIELD_FORM", "event is not an object");
  canonDumpsText(event, EVENT_LIMITS);
  ekeys(event, ENVELOPE_KEYS, [], "event");
  eneed(event.format === FORMAT, "FORMAT", "format is not handoff/v0");
  ehex(event.record_id, HEX32_RE, "record_id");
  eint(event.seq, "seq");
  ehex(event.prev_hash, HEX64_RE, "prev_hash");
  eneed(TYPES.includes(event.type), "FIELD_FORM", "unknown event type");
  eneed(ACTORS.includes(event.actor), "FIELD_FORM", "actor must be P, C or W");
  parseTime(event.at);
  ehex(event.server_key_id, HEX32_RE, "server_key_id");
  const auth = event.auth;
  ekeys(auth, AUTH_KEYS, [], "auth");
  eneed(METHODS.includes(auth.method), "AUTH_METHOD", `auth.method ${pyRepr(auth.method)} is not email_token, ed25519 or server`);
  const m = auth.method;
  if (m === "email_token") {
    ehex(auth.token_nonce, HEX32_RE, "auth.token_nonce");
    parseTime(auth.token_expires);
    eneed(auth.agent_key_id === null, "AUTH_FORM", "email_token carries no agent_key_id");
  } else if (m === "ed25519") {
    eneed(auth.token_nonce === null && auth.token_expires === null, "AUTH_FORM", "ed25519 carries no token fields");
    ehex(auth.agent_key_id, HEX32_RE, "auth.agent_key_id");
  } else {
    eneed(auth.token_nonce === null && auth.token_expires === null && auth.agent_key_id === null, "AUTH_FORM",
      "server auth carries no token or agent fields");
  }
  checkBody(event.type, event.body, m);
}

function checkSigs(sigs) {
  eneed(Array.isArray(sigs), "SIGS_FORM", "sigs is not a list");
  eneed(sigs.length >= 1 && sigs.length <= 2, "LIMIT_SIGS", `an event carries S_w and at most one S_a (${sigs.length} given)`);
  let w = null, a = null;
  for (const s of sigs) {
    ekeys(s, ["role", "key_id", "sig"], [], "sig");
    ehex(s.key_id, HEX32_RE, "sig.key_id");
    ehex(s.sig, HEX128_RE, "sig.sig");
    if (s.role === "w") {
      eneed(w === null, "LIMIT_SIGS", "two server signatures");
      w = s;
    } else if (s.role === "a") {
      eneed(a === null, "LIMIT_SIGS", "two agent signatures");
      a = s;
    } else {
      throw new EventError("SIGS_FORM", "sig.role must be w or a");
    }
  }
  eneed(w !== null, "SIG_W_MISSING", "no server signature S_w");
  return [w, a];
}

const signedBytes = (event, kind = "sig-event") => sigInput(kind, C(event));

// ================================================================ state.py: the G1 table and rules R1-R6

const [PROPOSED, AGREED, DELIVERED, ACCEPTED, REJECTED, REVERSED, WITHDRAWN] =
  ["PROPOSED", "AGREED", "DELIVERED", "ACCEPTED", "REJECTED", "REVERSED", "WITHDRAWN"];
const TERMINAL = [REVERSED, WITHDRAWN];

class RecordState {
  constructor() {
    this.record_id = null;
    this.n = 0;
    this.last_hash = null;
    this.last_at = null;
    this.state = null;
    this.pending = null;
    this.disputed = 0;
    this.erased = new Map();
    this.terms = null;
    this.parties = null;
    this.confirm_by = null;
    this.nonces = new Set();
    this.hashes = [];
    this.latest_deliver = null;
    this.accept_hash = null;
    this.delivered = 0;
    this.accepted = false;
  }
  summary() {
    return {
      state: this.state, events: this.n,
      pending: this.pending === null ? null : { kind: this.pending.kind, by: this.pending.actor, seq: this.pending.seq },
      disputed: this.disputed,
    };
  }
}

function tfail(code, message, seq) {
  throw new TransitionError(code, message, seq);
}

function checkLink(st, event) {
  const seq = event.seq;
  if (st.n === 0) {
    if (event.prev_hash !== genesis(event.record_id)) tfail("CHAIN_GENESIS", "seq 0 prev_hash is not the genesis value for its record_id", seq);
    return;
  }
  if (event.record_id !== st.record_id) tfail("RECORD_ID_MISMATCH", "record_id differs from seq 0's", seq);
  if (event.prev_hash !== st.last_hash) tfail("CHAIN_PREV_HASH", "prev_hash is not H(previous event)", seq);
}

function checkAuth(st, event, sigA, parties) {
  const { seq, actor, auth, body } = event;
  const method = auth.method;
  if (actor === "W") {
    if (method !== "server") tfail("R2_ACTOR", "a W event must use auth.method server", seq);
    if (sigA !== null) tfail("R4_SIG_A_UNEXPECTED", "a server event carries no agent signature", seq);
    return;
  }
  if (method === "server") tfail("R2_ACTOR", "auth.method server is only for actor W", seq);
  const party = parties[actor];
  const agentKey = get(party, "agent_key");
  if (method === "ed25519") {
    if (agentKey === null) tfail("R4_NO_AGENT_KEY", `role ${actor} committed no agent key`, seq);
    if (auth.agent_key_id !== keyId(fromHex(agentKey))) tfail("R4_AGENT_KEY_MISMATCH", `agent_key_id is not the key role ${actor} committed`, seq);
    if (sigA === null) tfail("R4_SIG_A_MISSING", "ed25519 method without S_a", seq);
  }
  if (sigA !== null) {
    if (agentKey === null) tfail("R4_SIG_A_INVALID", `S_a present but role ${actor} committed no agent key`, seq);
    if (sigA.key_id !== keyId(fromHex(agentKey))) tfail("R4_SIG_A_INVALID", "S_a key_id is not the committed agent key", seq);
    try {
      ed25519Verify(fromHex(agentKey), fromHex(sigA.sig), signedBytes(event, "sig-agent"));
    } catch (e) {
      if (!(e instanceof CryptoError)) throw e;
      tfail("R4_SIG_A_INVALID", `S_a fails strict verification (${e.code})`, seq);
    }
  }
  if (method === "email_token") {
    if (st.nonces.has(auth.token_nonce)) tfail("R4_NONCE_REUSED", "email token nonce already used in this record", seq);
    if (body.party_digest !== party.digest) tfail("R4_PARTY_DIGEST", `party_digest is not role ${actor}'s digest in COMMIT`, seq);
    if (parseTime(event.at) > parseTime(auth.token_expires)) tfail("R4_TOKEN_EXPIRED", "event is after the token's expiry", seq);
  }
}

function applyEvent(st, event, sigA = null) {
  checkEvent(event);
  const { seq, type: etype, actor, body } = event;
  if (seq !== st.n) tfail("R1_SEQ", `seq ${seq} where ${st.n} was expected`, seq);
  if (st.n === 0 && etype !== "COMMIT") tfail("R1_FIRST_NOT_COMMIT", "seq 0 must be COMMIT", seq);
  checkLink(st, event);
  if ((etype === "ERASE") !== (actor === "W")) tfail("R2_ACTOR", `${etype} may not be written by ${actor}`, seq);
  if (st.erased.has(actor)) tfail("R3_ERASED_ACTOR", `role ${actor} was erased at seq ${st.erased.get(actor)}`, seq);
  const at = parseTime(event.at);
  if (st.last_at !== null && at < st.last_at) tfail("R5_TIME_ORDER", "at is earlier than the previous event's at", seq);
  let parties = st.parties;
  if (etype === "COMMIT" && seq === 0) {
    parties = { P: body.parties.p, C: body.parties.c };
    for (const role of ["P", "C"]) {
      const k = get(parties[role], "agent_key");
      if (k !== null) {
        try {
          checkPublicKey(fromHex(k));
        } catch (e) {
          if (!(e instanceof CryptoError)) throw e;
          tfail("COMMIT_BAD_AGENT_KEY", `role ${role} agent key refused (${e.code})`, seq);
        }
      }
    }
  }
  checkAuth(st, event, sigA, parties);
  const h = toHex(eventHash(event));
  transition(st, event, h, parties);
  if (seq === 0) st.record_id = event.record_id;
  if (event.auth.method === "email_token") st.nonces.add(event.auth.token_nonce);
  st.n += 1;
  st.last_hash = h;
  st.last_at = at;
  st.hashes.push(h);
  return st;
}

function transition(st, event, h, parties) {
  const { seq, type: t, actor: a, body: b } = event;
  const s = st.state;
  if (t === "COMMIT") {
    if (seq !== 0) tfail("R6_ILLEGAL", "COMMIT is only legal at seq 0", seq);
    if (parties.P.digest === parties.C.digest) tfail("COMMIT_SELF_DEALING", "P's and C's party digests are equal (V50)", seq);
    st.parties = parties;
    st.confirm_by = get(b, "confirm_by");
    st.state = PROPOSED;
    st.pending = { kind: "COMMIT", hash: h, actor: a, terms_digest: b.terms_digest, seq };
    return;
  }
  if (t === "ERASE") {
    if (!st.erased.has(b.role)) st.erased.set(b.role, seq);
    return;
  }
  if (TERMINAL.includes(s) && t !== "DISPUTE") tfail("G1_TERMINAL", `${s} is terminal; only DISPUTE or ERASE may follow`, seq);
  if (t === "CONFIRM") {
    const p = st.pending;
    if (p === null) tfail("CONFIRM_NOTHING_PENDING", "no proposal awaits confirmation", seq);
    if (p.kind === "AMEND" && s === DELIVERED) tfail("CONFIRM_WHILE_DELIVERED", "decide the open delivery before confirming an AMEND (A1)", seq);
    if (a === p.actor) tfail("CONFIRM_SELF", "CONFIRM must come from the role that did not propose (A2)", seq);
    if (b.ref !== p.hash) tfail("CONFIRM_REF", "CONFIRM.ref is not H(the pending proposal) (A5)", seq);
    if (b.terms_digest !== p.terms_digest) tfail("CONFIRM_TERMS", "CONFIRM.terms_digest differs from the proposal's (A3)", seq);
    if (p.kind === "COMMIT") {
      if (st.confirm_by !== null && parseTime(event.at) > parseTime(st.confirm_by)) tfail("CONFIRM_LATE", "CONFIRM.at is after COMMIT.confirm_by", seq);
      st.state = AGREED;
      st.terms = p.terms_digest;
      st.pending = null;
    } else if (p.kind === "AMEND") {
      if (s !== AGREED && s !== REJECTED) tfail("R6_ILLEGAL", `CONFIRM of an AMEND in ${s}`, seq);
      st.state = AGREED;
      st.terms = p.terms_digest;
      st.pending = null;
    } else {
      if (s !== ACCEPTED) tfail("R6_ILLEGAL", `CONFIRM of a REVERSE in ${s}`, seq);
      st.state = REVERSED;
      st.pending = null;
    }
    return;
  }
  if (t === "WITHDRAW") {
    if (s === ACCEPTED || st.accepted) tfail("G1_ACCEPTED_CLOSED", "WITHDRAW after an ACCEPT; new work is a new record", seq);
    if (![PROPOSED, AGREED, DELIVERED, REJECTED].includes(s)) tfail("R6_ILLEGAL", `WITHDRAW in ${s}`, seq);
    st.state = WITHDRAWN;
    st.pending = null;
    return;
  }
  if (t === "DELIVER") {
    if (a !== "P") tfail("G1_WRONG_ROLE", "only P may DELIVER (V47)", seq);
    if (s === ACCEPTED) tfail("G1_ACCEPTED_CLOSED", "DELIVER after ACCEPT; new work is a new record", seq);
    if (s === PROPOSED) tfail("G1_NOT_AGREED", "DELIVER before both sides confirmed the COMMIT (V49)", seq);
    if (s !== AGREED && s !== REJECTED) tfail("R6_ILLEGAL", `DELIVER in ${s} (one open delivery at a time)`, seq);
    if (b.terms_digest !== st.terms) tfail("DELIVER_TERMS", "DELIVER.terms_digest is not the current confirmed terms", seq);
    if (st.pending !== null && st.pending.kind === "AMEND") tfail("DELIVER_PENDING_AMEND", "an AMEND awaits confirmation", seq);
    st.state = DELIVERED;
    st.latest_deliver = h;
    st.delivered += 1;
    return;
  }
  if (t === "ACCEPT" || t === "REJECT") {
    if (a !== "C") tfail("G1_WRONG_ROLE", `only C may ${t} (V47)`, seq);
    if (s !== DELIVERED) tfail("R6_ILLEGAL", `${t} in ${s} (no undecided delivery)`, seq);
    if (b.ref !== st.latest_deliver) tfail("REF_NOT_LATEST_DELIVER", `${t}.ref is not H(the latest DELIVER)`, seq);
    if (t === "ACCEPT") {
      st.state = ACCEPTED;
      st.accepted = true;
      st.accept_hash = h;
    } else {
      st.state = REJECTED;
    }
    return;
  }
  if (t === "AMEND") {
    if (s === ACCEPTED) tfail("G1_ACCEPTED_CLOSED", "AMEND after ACCEPT; new work is a new record", seq);
    if (![AGREED, DELIVERED, REJECTED].includes(s)) tfail("R6_ILLEGAL", `AMEND in ${s}`, seq);
    if (b.terms_digest === st.terms) tfail("AMEND_SAME_TERMS", "AMEND must carry new terms", seq);
    st.pending = { kind: "AMEND", hash: h, actor: a, terms_digest: b.terms_digest, seq };
    return;
  }
  if (t === "REVERSE") {
    if (!st.accepted) tfail("REVERSE_NO_ACCEPT", "REVERSE with no prior ACCEPT (V45)", seq);
    if (s !== ACCEPTED) tfail("R6_ILLEGAL", `REVERSE in ${s}`, seq);
    if (b.ref !== st.accept_hash) tfail("REVERSE_REF", "REVERSE.ref is not H(the ACCEPT)", seq);
    if (b.terms_digest !== st.terms) tfail("REVERSE_TERMS", "REVERSE.terms_digest is not the current terms", seq);
    st.pending = { kind: "REVERSE", hash: h, actor: a, terms_digest: b.terms_digest, seq };
    return;
  }
  if (t === "DISPUTE") {
    if (s === WITHDRAWN && st.delivered === 0) tfail("DISPUTE_NO_DELIVER", "DISPUTE after WITHDRAW with no DELIVER (A4)", seq);
    if (![DELIVERED, REJECTED, ACCEPTED, REVERSED, WITHDRAWN].includes(s)) tfail("R6_ILLEGAL", `DISPUTE in ${s}`, seq);
    if (!st.hashes.includes(b.ref)) tfail("DISPUTE_REF", "DISPUTE.ref names no earlier event", seq);
    st.disputed += 1;
    return;
  }
  tfail("R6_ILLEGAL", `${t} in ${s} is not in the G1 table`, seq);
}

// ================================================================ head.py: signed heads, the chain, witness rules

const HEAD_KEYS = ["format", "n", "date", "tree_size", "log_root", "tip_root", "tip_count", "prev_head", "published_at",
  "server_key_id", "next_key"];
const DATE_RE = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
const HEAD_GENESIS = toHex(H(DT("genesis-head"), utf8(FORMAT)));

function hneed(cond, code, msg) {
  if (!cond) throw new HeadError(code, msg);
}

function checkHead(h) {
  hneed(isDict(h) && keySetEq(h, HEAD_KEYS), "HEAD_FORM", "head has the wrong fields");
  canonDumpsText(h, EVENT_LIMITS);
  hneed(h.format === FORMAT, "HEAD_FORM", "head format is not handoff/v0");
  for (const f of ["n", "tree_size", "tip_count"]) hneed(isNat(h[f]), "HEAD_FORM", `head.${f} must be an integer >= 0`);
  hneed(typeof h.date === "string" && DATE_RE.test(h.date), "HEAD_FORM", "head.date form");
  parseTime(h.date + "T00:00:00Z");
  parseTime(h.published_at);
  for (const f of ["log_root", "tip_root", "prev_head"]) hneed(isHex(h[f], HEX64_RE), "HEAD_FORM", `head.${f} form`);
  hneed(isHex(h.server_key_id, HEX32_RE), "HEAD_FORM", "server_key_id");
  if (h.next_key !== null) {
    try {
      checkEntryForm(h.next_key);
    } catch (e) {
      if (!(e instanceof KeysError)) throw e;
      throw new HeadError("HEAD_FORM", "next_key: " + e.message);
    }
  }
  if (h.n === 0) hneed(h.prev_head === HEAD_GENESIS, "HEAD_FORM", "head 0 must carry the head genesis as prev_head");
}

const headHash = (h) => H(DT("head"), C(h));
const headBytes = (h) => canonDumpsText(h, EVENT_LIMITS); // the canonical text stands for the canonical bytes

function checkHeadEntry(entry, allowTip = false) {
  const allowed = ["head", "sigs", "consistency", ...(allowTip ? ["tip"] : [])];
  hneed(isDict(entry) && hasOwn(entry, "head") && hasOwn(entry, "sigs") && Object.keys(entry).every((k) => allowed.includes(k)),
    "HEAD_FORM", "head entry has the wrong fields");
  checkHead(entry.head);
  const sigs = entry.sigs;
  hneed(Array.isArray(sigs) && sigs.length >= 1 && sigs.length <= 4, "HEAD_FORM", "a head carries 1-4 signatures");
  const seen = new Set();
  for (const s of sigs) {
    hneed(isDict(s) && keySetEq(s, ["key_id", "sig"]), "HEAD_FORM", "head signature form");
    hneed(isHex(s.key_id, HEX32_RE), "HEAD_FORM", "head sig key_id");
    hneed(isHex(s.sig, HEX128_RE), "HEAD_FORM", "head sig form");
    hneed(!seen.has(s.key_id), "HEAD_FORM", "two signatures by one key");
    seen.add(s.key_id);
  }
  const c = get(entry, "consistency");
  if (c !== null) parsePath(c);
}

function verifyHeadSigs(entry, kh) {
  const h = entry.head;
  const n = h.n;
  const msg = sigInput("sig-head", C(h));
  const required = kh.requiredSigners(n);
  hneed(required.length > 0, "HEAD_KEY_WINDOW", `no key in the history is valid at head ${n}`);
  const got = new Set();
  for (const s of entry.sigs) {
    const kid = s.key_id;
    hneed(kh.known(kid), "HEAD_UNKNOWN_KEY", `head ${n} signed by a key not in the key history (V12)`);
    hneed(kh.validAt(kid, n), "HEAD_KEY_WINDOW", `head ${n} signed by key ${kid} outside its window (V19)`);
    try {
      ed25519Verify(kh.pubkey(kid), fromHex(s.sig), msg);
    } catch (e) {
      if (!(e instanceof CryptoError)) throw e;
      throw new HeadError("HEAD_SIG_INVALID", `head ${n} signature by ${kid} fails (${e.code})`);
    }
    got.add(kid);
  }
  const missing = required.filter((k) => !got.has(k));
  hneed(!missing.length, "HEAD_SIG_MISSING", `head ${n} lacks the signature of ${missing.join(", ")} (overlap needs both keys)`);
  hneed(required.includes(h.server_key_id), "HEAD_KEY_WINDOW", `head ${n} server_key_id is not a valid key`);
  if (h.next_key !== null) {
    const nk = h.next_key;
    const intro = kh.intro.has(nk.key_id) ? kh.intro.get(nk.key_id) : null;
    hneed(intro !== null && canonDumpsText(intro) === canonDumpsText(nk), "HEAD_NEXT_KEY",
      `head ${n} announces a key that is not in the key history`);
    hneed(nk.valid_from_head === n + 1, "HEAD_NEXT_KEY", `next_key must start at head ${n + 1}`);
  }
}

function checkAnnouncements(entriesByN, kh) {
  for (const [kid, intro] of kh.intro) {
    if (intro === kh.entries[0]) continue;
    const m = intro.valid_from_head;
    const prev = entriesByN.get(m - 1);
    if (prev !== undefined) {
      const nk = prev.head.next_key;
      hneed(nk !== null && nk.key_id === kid, "HEAD_NEXT_KEY", `head ${m - 1} does not announce key ${kid}`);
    }
  }
}

function hfinding(level, code, message, evidence = null) {
  const f = { level, code, seq: null, message };
  if (evidence !== null) f.evidence = evidence;
  return f;
}
const evOf = (entry) => ({ head: entry.head, sigs: entry.sigs });

function checkChain(entries, source) {
  const out = [];
  for (let i = 0; i + 1 < entries.length; i++) {
    const a = entries[i], b = entries[i + 1];
    const ha = a.head, hb = b.head;
    if (hb.n !== ha.n + 1) {
      out.push(hfinding("detect", "HEAD_GAP", `${source}: head ${hb.n} follows head ${ha.n} with no proof chain (G4 d)`, [evOf(a), evOf(b)]));
      continue;
    }
    if (hb.tree_size < ha.tree_size) {
      out.push(hfinding("detect", "HEAD_SIZE_DECREASE", `${source}: tree_size decreases from head ${ha.n} to ${hb.n} (G4 d)`, [evOf(a), evOf(b)]));
      continue;
    }
    if (hb.prev_head !== toHex(headHash(ha))) {
      out.push(hfinding("detect", "HEAD_PREV_LINK", `${source}: head ${hb.n} prev_head is not H(head ${ha.n})`, [evOf(a), evOf(b)]));
    }
    if (hb.date <= ha.date) {
      out.push(hfinding("detect", "HEAD_DATE", `${source}: head ${hb.n} date does not follow head ${ha.n}'s (one head per UTC date)`, [evOf(a), evOf(b)]));
    }
    if (hb.published_at < ha.published_at) {
      out.push(hfinding("detect", "HEAD_TIME_ORDER", `${source}: head ${hb.n} published before head ${ha.n}`, [evOf(a), evOf(b)]));
    }
    const proof = get(b, "consistency");
    try {
      if (proof === null) throw new ProofError("PROOF_CONSISTENCY", "no consistency proof supplied");
      verifyConsistency(ha.tree_size, hb.tree_size, fromHex(ha.log_root), fromHex(hb.log_root), parsePath(proof));
    } catch (e) {
      if (!(e instanceof ProofError)) throw e;
      out.push(hfinding("detect", "HEAD_CONSISTENCY", `${source}: head ${hb.n} is not consistent with head ${ha.n} (${e.message}; G4 c)`, [evOf(a), evOf(b)]));
    }
  }
  return out;
}

function equivocation(groups) {
  const out = [];
  const byN = new Map(), byDate = new Map();
  for (const [src, e] of groups) {
    const h = e.head;
    for (const [table, key, kind] of [[byN, h.n, "n"], [byDate, h.date, "date"]]) {
      const other = table.get(key);
      if (other === undefined) table.set(key, [src, e]);
      else if (headBytes(other[1].head) !== headBytes(h)) {
        const f = hfinding("detect", "HEAD_EQUIVOCATION",
          `two validly signed heads with the same ${kind} ${key} differ (${other[0]} vs ${src}; G4 a)`, [evOf(other[1]), evOf(e)]);
        if (!out.some((x) => x.code === "HEAD_EQUIVOCATION" && pyEq(x.evidence, f.evidence))) out.push(f);
      }
    }
  }
  return out;
}

function rollback(anchorEntry, witnessEntries) {
  let best = null;
  for (const [src, e] of witnessEntries) if (best === null || e.head.tree_size > best[1].head.tree_size) best = [src, e];
  if (best !== null && anchorEntry.head.tree_size < best[1].head.tree_size) {
    return [hfinding("detect", "HEAD_ROLLBACK",
      `the export's latest head ${anchorEntry.head.n} (tree_size ${anchorEntry.head.tree_size}) is older than known head ` +
      `${best[1].head.n} (tree_size ${best[1].head.tree_size}, from ${best[0]}; G4 b). Later events for this record may be ` +
      "hidden: verify a fresh export.", [evOf(anchorEntry), evOf(best[1])])];
  }
  return [];
}

// ================================================================ erase.py: status lines for erased roles

function eraseStatusLines(st) {
  return [...st.erased.keys()].sort().map((role) => {
    const s = st.erased.get(role);
    return `party ${role}: the server recorded an erasure at seq ${s}. The protocol requires the server to delete this ` +
      "role's address, notes and k_rec from its table and its backups (SPEC 5.7, 12). This verifier cannot " +
      `observe that deletion. Copies exported before seq ${s}, and the signed record itself (digests, any party ` +
      "name), are not recalled.";
  });
}

// ================================================================ verify.py: the export verifier

const EXPORT_KEYS = ["format", "kind", "record_id", "events", "heads", "tip", "keys", "plaintext"];
const ENTRY_KEYS = ["event", "sigs", "log_index", "inclusion"];
const CONFIRM_ANCHOR_TOLERANCE = 24 * 3600;
const isHandoffError = (e) => e instanceof HandoffError;

export const DETECT_CLASS = {
  HEAD_EQUIVOCATION: "conflict", HEAD_SIZE_DECREASE: "conflict", HEAD_PREV_LINK: "conflict",
  HEAD_DATE: "conflict", HEAD_TIME_ORDER: "conflict", HEAD_FORK_SAME_SIZE: "conflict",
  TIP_BACKWARDS: "conflict", TIP_FORK: "conflict",
  HEAD_ROLLBACK: "freshness",
  TIP_AHEAD_TRUNCATED: "completeness",
  HEAD_UNANCHORED: "anchoring", EVENT_KEY_REVOKED: "anchoring", KEY_COMPROMISED_UNWITNESSED: "anchoring",
  CONFIRM_ANCHOR_LATE: "anchoring",
};
const detectClass = (code) => {
  if (!hasOwn(DETECT_CLASS, code)) throw new Error("no evidence class for " + code);
  return DETECT_CLASS[code];
};

export class Report {
  constructor() {
    this.findings = [];
    this.time_bounds = [];
  }
  add(level, code, message, seq = null, evidence = null) {
    const f = { level, code, seq, message };
    if (level === "detect") f.class = detectClass(code);
    if (evidence !== null) f.evidence = evidence;
    this.findings.push(f);
  }
  reject(code, message, seq = null, evidence = null) {
    this.add("reject", code, message, seq, evidence);
  }
  codes(level = null) {
    return this.findings.filter((f) => level === null || f.level === level).map((f) => f.code);
  }
  get result() {
    const levels = new Set(this.findings.map((f) => f.level));
    if (levels.has("reject")) return "REJECT";
    if (levels.has("detect")) return "DETECT";
    if (levels.has("error")) return "ERROR";
    return "ACCEPT";
  }
  toJSON() {
    return { result: this.result, findings: this.findings, time_bounds: this.time_bounds };
  }
}

const codeOf = (e) => (e && e.code !== undefined ? e.code : "ERROR");
const msgOf = (e) => (e && e.message !== undefined ? e.message : String(e));

function tipTuple(leaf) {
  if (!(isDict(leaf) && keySetEq(leaf, ["record_tag", "last_seq", "event_hash", "log_index"]))) {
    throw new ProofError("TIP_FORM", "tip leaf has the wrong fields");
  }
  for (const f of ["record_tag", "event_hash"]) if (!isHex(leaf[f], HEX64_RE)) throw new ProofError("TIP_FORM", `tip leaf ${f} form`);
  for (const f of ["last_seq", "log_index"]) if (!isNat(leaf[f])) throw new ProofError("TIP_FORM", `tip leaf ${f} form`);
  return [fromHex(leaf.record_tag), leaf.last_seq, fromHex(leaf.event_hash), leaf.log_index];
}

function neighbour(nb) {
  if (nb === null) return null;
  if (!(isDict(nb) && keySetEq(nb, ["index", "leaf", "path"]))) throw new ProofError("TIP_FORM", "tip neighbour has the wrong fields");
  if (!isNat(nb.index)) throw new ProofError("TIP_FORM", "tip neighbour index form");
  const index = nb.index, tip = tipTuple(nb.leaf), path = parsePath(nb.path);
  return { index, tip, path };
}

function verifyTip(tip, tag, headObj) {
  if (!isDict(tip) || !hasOwn(tip, "head_n") || Object.keys(tip).length !== 2 || !(hasOwn(tip, "member") || hasOwn(tip, "absent"))) {
    throw new ProofError("TIP_FORM", "tip must be {head_n, member} or {head_n, absent}");
  }
  // §8.3: head_n must be an integer (a boolean is not, though Python has True == 1) equal to the anchor's n.
  if (!isInt(tip.head_n) || tip.head_n !== headObj.n) throw new ProofError("TIP_HEAD", "the tip proof is not against the latest head");
  const root = fromHex(headObj.tip_root), count = headObj.tip_count;
  if (hasOwn(tip, "member")) {
    const m = tip.member;
    if (!(isDict(m) && keySetEq(m, ["index", "leaf", "path"]))) throw new ProofError("TIP_FORM", "tip member has the wrong fields");
    const t = tipTuple(m.leaf);
    if (!isNat(m.index)) throw new ProofError("TIP_FORM", "tip member index form (int >= 0, r7 gap 1)");
    const path = parsePath(m.path);
    verifyTipMember(tag, t, m.index, path, count, root);
    return ["member", t];
  }
  const a = tip.absent;
  if (!(isDict(a) && keySetEq(a, ["left", "right"]))) throw new ProofError("TIP_FORM", "tip absent has the wrong fields");
  const left = neighbour(a.left), right = neighbour(a.right);
  verifyTipAbsent(tag, left, right, count, root);
  return ["absent", null];
}

function inflateHeadEntry(entry) {
  if (isDict(entry)) {
    setdefault(entry, "consistency", null);
    const h = get(entry, "head");
    if (isDict(h)) {
      setdefault(h, "next_key", null);
      if (isDict(h.next_key)) inflateKeyEntry(h.next_key);
    }
  }
  return entry;
}

function inflateExport(doc) {
  if (!isDict(doc)) return doc;
  for (const k of ["tip", "keys", "plaintext"]) setdefault(doc, k, null);
  if (Array.isArray(get(doc, "events"))) {
    for (const en of doc.events) {
      if (!isDict(en)) continue;
      setdefault(en, "log_index", null);
      setdefault(en, "inclusion", null);
      const ev = get(en, "event");
      if (isDict(ev) && isDict(get(ev, "auth"))) for (const k of ["token_nonce", "token_expires", "agent_key_id"]) setdefault(ev.auth, k, null);
    }
  }
  if (Array.isArray(get(doc, "heads"))) for (const e of doc.heads) inflateHeadEntry(e);
  const tip = doc.tip;
  if (isDict(tip) && isDict(get(tip, "absent"))) {
    setdefault(tip.absent, "left", null);
    setdefault(tip.absent, "right", null);
  }
  inflateKeysDoc(doc.keys);
  return doc;
}

// The first word of each letter's Unicode character name, as verify.py's _scripts() takes it. JavaScript has no
// character names, so this maps the Unicode Script property to that word; a few name families are special-cased.
const SCRIPTS = ["Latin", "Greek", "Cyrillic", "Armenian", "Hebrew", "Arabic", "Syriac", "Thaana", "Nko", "Samaritan",
  "Mandaic", "Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Oriya", "Tamil", "Telugu", "Kannada", "Malayalam", "Sinhala",
  "Thai", "Lao", "Tibetan", "Myanmar", "Georgian", "Hangul", "Ethiopic", "Cherokee", "Canadian_Aboriginal", "Ogham", "Runic",
  "Tagalog", "Hanunoo", "Buhid", "Tagbanwa", "Khmer", "Mongolian", "Limbu", "Tai_Le", "New_Tai_Lue", "Buginese", "Tai_Tham",
  "Balinese", "Sundanese", "Batak", "Lepcha", "Ol_Chiki", "Glagolitic", "Tifinagh", "Coptic", "Hiragana", "Katakana",
  "Bopomofo", "Han", "Yi", "Lisu", "Vai", "Bamum", "Syloti_Nagri", "Phags_Pa", "Saurashtra", "Kayah_Li", "Rejang", "Javanese",
  "Cham", "Tai_Viet", "Meetei_Mayek", "Gothic", "Old_Italic", "Deseret", "Shavian", "Osmanya", "Adlam", "Vithkuqi"];
let scriptRes = null;
function scriptWord(ch) {
  const cp = ch.codePointAt(0);
  if (cp === 0xaa) return "FEMININE";
  if (cp === 0xba) return "MASCULINE";
  if (cp === 0xb5) return "MICRO";
  if ((cp >= 0xff21 && cp <= 0xff3a) || (cp >= 0xff41 && cp <= 0xff5a)) return "FULLWIDTH";
  if (cp >= 0xff61 && cp <= 0xffdc) return "HALFWIDTH";
  if (cp >= 0x1d400 && cp <= 0x1d7ff) return "MATHEMATICAL";
  if (cp >= 0x2100 && cp <= 0x214f) return "LETTERLIKE";
  if (/\p{Lm}/u.test(ch) && cp >= 0x2b0 && cp <= 0x2ff) return "MODIFIER";
  if (scriptRes === null) {
    scriptRes = [];
    for (const s of SCRIPTS) {
      try {
        scriptRes.push([s, new RegExp(`\\p{Script=${s}}`, "u")]);
      } catch (e) {
        // a script this engine does not know
      }
    }
  }
  for (const [s, rx] of scriptRes) {
    if (rx.test(ch)) return s === "Han" ? "CJK" : s.split("_")[0].toUpperCase();
  }
  return "UNKNOWN";
}
function scriptsOf(name) {
  const out = new Set();
  for (const ch of name) if (/\p{L}/u.test(ch)) out.add(scriptWord(ch));
  return out;
}

function loadHeadEntries(rawList, kh, source, rep, allowTip = false) {
  const out = [];
  rawList.forEach((item, i) => {
    let entry;
    try {
      entry = item instanceof Uint8Array || typeof item === "string" ? inflateHeadEntry(canonLoads(item, SIDE_LIMITS)) : item;
      checkHeadEntry(entry, allowTip);
      verifyHeadSigs(entry, kh);
    } catch (e) {
      if (!isHandoffError(e)) throw e;
      rep.add("warning", "WITNESS_HEAD_IGNORED", `${source} item ${i} ignored: ${msgOf(e)} (${codeOf(e)})`);
      return;
    }
    out.push(entry);
  });
  return out;
}

// verifyExport(exportBytes, {keysBytes, knownLines, mirrorHeads, mirrorKeys, requireAnchored, localCaps})
// knownLines: array of byte lines (JSONL); mirrorHeads: array of byte files (null = no mirror); *Keys: keys.json bytes;
// localCaps: optional {export_bytes: n}. Returns {report, extra}; throws InputError for a problem with the inputs
// other than the export (the CLI's ERROR, exit 3).
export function verifyExport(exportBytes, opts = {}) {
  if (opts === null || typeof opts !== "object") throw new InputError("options must be an object", "USAGE");
  exportBytes = asBytes(exportBytes, "the export");
  const list = (v, what) => {
    if (v === null || v === undefined) return null;
    if (!Array.isArray(v)) throw new InputError(`${what} must be an array of byte strings`, "USAGE");
    return v.map((x, i) => asBytes(x, `${what} item ${i}`));
  };
  const one = (v, what) => (v === null || v === undefined ? null : asBytes(v, what));
  const keysBytes = one(opts.keysBytes, "keysBytes"), knownLines = list(opts.knownLines, "knownLines");
  const mirrorHeads = list(opts.mirrorHeads, "mirrorHeads"), mirrorKeys = one(opts.mirrorKeys, "mirrorKeys");
  const requireAnchored = !!opts.requireAnchored, localCaps = opts.localCaps ?? null;
  if (!engineUnicodeOk()) {
    throw new InputError("this JavaScript engine's Unicode data is older than Unicode 15.0, so it cannot reproduce the " +
      "reference's character rules; use a current browser or Node 24", "ENGINE_UNICODE");
  }
  if (requireAnchored && mirrorHeads === null) throw new InputError("--require-anchored needs --mirror", "USAGE");
  const cap = localCaps && hasOwn(localCaps, "export_bytes") ? localCaps.export_bytes : null;
  if (cap !== null && cap !== undefined && EXPORT_LIMITS.maxBytes >= exportBytes.length && exportBytes.length > cap) {
    throw new InputError(`export of ${exportBytes.length} bytes exceeds this verifier's local cap of ${cap} bytes; the content was not ` +
      "read and no other protocol limit was checked", "LOCAL_CAP");
  }
  const rep = new Report();
  let doc;
  try {
    doc = inflateExport(canonLoads(exportBytes, EXPORT_LIMITS));
  } catch (e) {
    if (!(e instanceof CanonError)) throw e;
    rep.reject(e.code, "export refused by the canonical parser: " + e.message);
    return { report: rep, extra: null };
  }
  if (!(isDict(doc) && keySetEq(doc, EXPORT_KEYS))) {
    rep.reject("EXPORT_FORM", "export must have exactly the fields " + EXPORT_KEYS.join(", "));
    return { report: rep, extra: null };
  }
  if (doc.format !== FORMAT || doc.kind !== "record_export") {
    rep.reject("EXPORT_FORM", "export format/kind is not handoff/v0 record_export");
    return { report: rep, extra: null };
  }
  const rid = doc.record_id;
  if (!isHex(rid, HEX32_RE)) {
    rep.reject("EXPORT_FORM", "record_id form");
    return { report: rep, extra: null };
  }
  const tag = recordTag(rid);

  // ---- key history (G6): --keys, else the mirror's copy; the export's own copy is never trusted
  let kh;
  try {
    if (keysBytes !== null) kh = KeyHistory.fromBytes(keysBytes);
    else if (mirrorKeys !== null) kh = KeyHistory.fromBytes(mirrorKeys);
    else throw new InputError("no key history: supply --keys or --mirror (the export's own copy is not trusted)");
  } catch (e) {
    if (!(e instanceof KeysError)) throw e;
    throw new InputError(`key history refused: ${e.message} (${e.code})`, e.code);
  }
  if (doc.keys !== null) {
    if (!(isDict(doc.keys) && keySetEq(doc.keys, ["format", "entries"]))) {
      rep.reject("EXPORT_FORM", "the export's keys copy must be null or {format, entries}");
      return { report: rep, extra: null };
    }
    let differs;
    try {
      differs = canonDumpsText(doc.keys, EXPORT_LIMITS) !== canonDumpsText(kh.toDoc(), EXPORT_LIMITS);
    } catch (e) {
      if (!(e instanceof CanonError)) throw e;
      rep.reject("EXPORT_FORM", "the export's keys copy is malformed: " + e.message);
      return { report: rep, extra: null };
    }
    if (differs) {
      rep.add("warning", "KEYS_EXPORT_DIFFERS", "the export's own key history copy differs from the supplied one; the supplied one was used");
    }
  }

  const known = loadHeadEntries(knownLines || [], kh, "known-heads", rep, true);
  const mirror = loadHeadEntries(mirrorHeads || [], kh, "mirror", rep);

  // ---- heads carried by the export
  const heads = doc.heads;
  if (!Array.isArray(heads)) {
    rep.reject("EXPORT_FORM", "heads is not a list");
    return { report: rep, extra: null };
  }
  const byN = new Map();
  heads.forEach((entry, i) => {
    try {
      checkHeadEntry(entry);
      verifyHeadSigs(entry, kh);
    } catch (e) {
      if (!isHandoffError(e)) throw e;
      rep.reject(codeOf(e), `export head ${i}: ${msgOf(e)}`);
      return;
    }
    if (byN.has(entry.head.n)) rep.reject("HEAD_DUPLICATE", `export carries head ${entry.head.n} twice`);
    byN.set(entry.head.n, entry);
  });
  if (rep.result === "REJECT") return { report: rep, extra: null };
  const chain = [...byN.keys()].sort((a, b) => a - b).map((n) => byN.get(n));
  if (!pyEq(chain.map((e) => e.head.n), heads.map((e) => e.head.n))) {
    rep.reject("EXPORT_FORM", "export heads are not in increasing n");
    return { report: rep, extra: null };
  }
  try {
    checkAnnouncements(byN, kh);
  } catch (e) {
    if (!(e instanceof HeadError)) throw e;
    rep.reject(e.code, e.message);
  }
  for (const f of checkChain(chain, "export")) {
    if (f.code === "HEAD_GAP") Object.assign(f, { level: "reject", code: "HEAD_CHAIN_GAP" });
    else if (f.code === "HEAD_CONSISTENCY") Object.assign(f, { level: "reject", code: "HEAD_CONSISTENCY_UNPROVEN" });
    else f.class = detectClass(f.code);
    rep.findings.push(f);
  }
  const anchor = chain.length ? chain[chain.length - 1] : null;

  // ---- events: structure, S_w, inclusion
  const entries = doc.events;
  if (!Array.isArray(entries) || !entries.length) {
    rep.reject("EXPORT_FORM", "events must be a non-empty list");
    return { report: rep, extra: null };
  }
  if (entries.length > 1000) {
    rep.reject("LIMIT_EVENTS", "more than 1,000 events in one record");
    return { report: rep, extra: null };
  }
  const events = [], sigAs = [];
  let structural = false;
  entries.forEach((en, i) => {
    let ev, w, a;
    try {
      if (!(isDict(en) && keySetEq(en, ENTRY_KEYS))) throw new EventError("EXPORT_FORM", `event entry ${i} has the wrong fields`);
      ev = en.event;
      checkEvent(ev);
      if (ev.seq !== i) throw new TransitionError("R1_SEQ", `event at position ${i} carries seq ${pyRepr(ev.seq)}`, i);
      [w, a] = checkSigs(en.sigs);
    } catch (e) {
      if (!isHandoffError(e)) throw e;
      rep.reject(codeOf(e), `event ${i}: ${msgOf(e)}`, i);
      structural = true;
      events.push(isDict(en) ? get(en, "event") : null);
      sigAs.push(null);
      return;
    }
    events.push(ev);
    sigAs.push(a);
    try {
      if (w.key_id !== ev.server_key_id) throw new EventError("SIG_W_KEY_ID", "S_w key_id differs from the signed server_key_id");
      if (!kh.known(w.key_id)) throw new EventError("SIG_W_UNKNOWN_KEY", "S_w by a key not in the key history (V12)");
      try {
        ed25519Verify(kh.pubkey(w.key_id), fromHex(w.sig), signedBytes(ev, "sig-event"));
      } catch (ce) {
        if (!(ce instanceof CryptoError)) throw ce;
        throw new EventError("SIG_W_INVALID", `S_w fails strict verification (${ce.code})`);
      }
    } catch (e) {
      if (!(e instanceof EventError)) throw e;
      rep.reject(e.code, `event ${i}: ${e.message}`, i);
    }
    const li = en.log_index, inc = en.inclusion;
    if ((li === null) !== (inc === null)) {
      rep.reject("INCLUSION_FORM", "log_index and inclusion must both be set or both be null", i);
      return;
    }
    if (li === null) return;
    try {
      if (!isNat(li)) throw new ProofError("INCLUSION_FORM", "log_index form");
      if (!(isDict(inc) && keySetEq(inc, ["head_n", "path"]))) throw new ProofError("INCLUSION_FORM", "inclusion must be {head_n, path}");
      const path = parsePath(inc.path);
      if (!isInt(inc.head_n)) throw new ProofError("INCLUSION_FORM", "inclusion.head_n is not an integer");
      const hn = byN.get(inc.head_n);
      if (hn === undefined) throw new ProofError("INCLUSION_HEAD_UNKNOWN", "inclusion names a head the export does not carry");
      const leaf = leafHash(eventLeafInput(tag, ev.seq, eventHash(ev)));
      verifyInclusion(li, hn.head.tree_size, leaf, path, fromHex(hn.head.log_root));
    } catch (e) {
      if (!(e instanceof ProofError)) throw e;
      rep.reject(e.code, `event ${i}: ${e.message}`, i);
    }
  });

  // ---- chain pass over every adjacent pair (G2)
  if (!structural) {
    events.forEach((ev, i) => {
      const st = new RecordState();
      st.n = i;
      if (i) {
        st.record_id = events[0].record_id;
        st.last_hash = toHex(eventHash(events[i - 1]));
      }
      try {
        checkLink(st, ev);
      } catch (e) {
        if (!(e instanceof TransitionError)) throw e;
        rep.reject(e.code, `event ${i}: ${e.message}`, i);
      }
    });
    if (events[0].record_id !== rid) rep.reject("RECORD_ID_MISMATCH", "export record_id differs from the events' record_id", 0);
  }

  // ---- the G1 table and R1-R6
  const st = new RecordState();
  if (!structural) {
    for (let i = 0; i < events.length; i++) {
      const ev = events[i];
      try {
        applyEvent(st, ev, sigAs[i]);
      } catch (e) {
        if (!isHandoffError(e)) throw e;
        rep.reject(codeOf(e), `event ${i} (${ev.type} by ${ev.actor}): ${msgOf(e)}`, i);
        break;
      }
    }
  }
  if (rep.result === "REJECT") return { report: rep, extra: null };

  // ---- anchoring, first inclusion, key windows (G6) and time bounds (E2)
  const anchored = [];
  entries.forEach((en, i) => {
    if (en.log_index !== null) anchored.push(i);
  });
  if (!anchored.every((x, k) => x === k)) rep.reject("ANCHOR_ORDER", "anchored events must precede unanchored ones");
  const lis = anchored.map((i) => entries[i].log_index);
  if (lis.some((b, k) => k > 0 && b <= lis[k - 1])) rep.reject("LOG_ORDER", "log_index must increase with seq");
  const firstHead = new Map();
  for (const i of anchored) {
    const li = entries[i].log_index;
    const fi = chain.find((e) => e.head.tree_size > li);
    if (fi === undefined) {
      rep.reject("FIRST_INCLUSION_UNPROVEN", `no export head includes event ${i}`, i);
      continue;
    }
    if (fi === chain[0] && fi.head.n !== 0) {
      rep.reject("FIRST_INCLUSION_UNPROVEN", `the export's head chain must start before event ${i}'s first including head`, i);
      continue;
    }
    firstHead.set(i, fi);
  }
  if (rep.result === "REJECT") return { report: rep, extra: null };
  for (const i of anchored) {
    const ev = events[i], fh = firstHead.get(i).head;
    if (!kh.validAt(ev.server_key_id, fh.n)) {
      rep.reject("EVENT_KEY_WINDOW", `event ${i} is signed by key ${ev.server_key_id}, which is not valid at its first including ` +
        `head ${fh.n} (V19)`, i);
    }
    const at = parseTime(ev.at), pub = parseTime(fh.published_at);
    if (at > pub) {
      rep.reject("TIME_AFTER_HEAD", `event ${i} declares a time after the publication of its first including head ${fh.n} (V41)`, i);
    }
    rep.time_bounds.push({
      seq: i, type: ev.type, head_n: fh.n, head_published_at: fh.published_at, time_source: "publisher-declared",
      declared_at: ev.at, declared_gap_seconds: pub - at, witnessed_by: [],
      statement: `included in head ${fh.n}; publisher-declared publication time ${fh.published_at}; declared event time ${ev.at} is self-declared`,
    });
  }
  let nextN = anchor ? anchor.head.n + 1 : 0;
  for (const e of known) if (e.head.n + 1 > nextN) nextN = e.head.n + 1;
  for (const e of mirror) if (e.head.n + 1 > nextN) nextN = e.head.n + 1;
  for (const e of kh.intro.values()) if (e.valid_from_head > nextN) nextN = e.valid_from_head;
  for (let i = anchored.length; i < events.length; i++) {
    const ev = events[i];
    if (!kh.validAt(ev.server_key_id, nextN)) {
      rep.reject("EVENT_KEY_WINDOW", `unanchored event ${i} is signed by key ${ev.server_key_id}, which cannot be valid at the next ` +
        `head ${nextN}`, i);
    } else if (kh.compromised(ev.server_key_id)) {
      rep.add("detect", "EVENT_KEY_REVOKED", `unanchored event ${i} is signed by key ${ev.server_key_id}, revoked for compromise ` +
        `from head ${kh.state.get(ev.server_key_id).revoked_from_head}; it stands only if a head before that includes it`, i,
      { key: kh.state.get(ev.server_key_id), event: entries[i] });
    }
    rep.time_bounds.push({ seq: i, type: ev.type, declared_at: ev.at, statement: "unanchored, not yet provable" });
  }
  const cb = get(events[0].body, "confirm_by");
  if (cb !== null) {
    for (const i of anchored) {
      const ev = events[i];
      if (ev.type === "CONFIRM" && ev.body.ref === toHex(eventHash(events[0]))) {
        const pub = parseTime(firstHead.get(i).head.published_at);
        if (pub > parseTime(cb) + CONFIRM_ANCHOR_TOLERANCE) {
          rep.add("detect", "CONFIRM_ANCHOR_LATE", `the CONFIRM's first including head ${firstHead.get(i).head.n} was published ` +
            `more than 24 h after confirm_by ${cb} (G7)`, i, [{ head: firstHead.get(i).head, sigs: firstHead.get(i).sigs }]);
        }
      }
    }
  }

  // ---- the tip commitment (G3)
  let tipT = null;
  if (anchor === null) {
    if (doc.tip !== null) rep.reject("TIP_FORM", "an export without heads carries no tip");
    rep.add("warning", "NO_HEADS", "no event is anchored in a head; nothing here is provable against a head yet");
  } else {
    let kind;
    try {
      [kind, tipT] = verifyTip(doc.tip, tag, anchor.head);
    } catch (e) {
      if (!(e instanceof ProofError)) throw e;
      rep.reject(e.code, "tip: " + e.message);
      kind = null;
    }
    if (kind === "absent" && anchored.length) {
      rep.reject("TIP_ABSENT_BUT_ANCHORED", "the latest head says the record does not exist, yet events are anchored");
    }
    if (kind === "member") {
      const lastSeq = events.length - 1;
      const lastAnchored = anchored.length ? anchored[anchored.length - 1] : -1;
      const evTip = { head: anchor.head, sigs: anchor.sigs, tip: doc.tip.member };
      if (tipT[1] > lastSeq) {
        rep.add("detect", "TIP_AHEAD_TRUNCATED", `the export is incomplete: head ${anchor.head.n} commits this record's ` +
          `tip at seq ${tipT[1]}, but the export ends at seq ${lastSeq}. The signed head and the exported events do ` +
          "not disagree; this finding does not say who shortened the export (G3, V10)", null, evTip);
      } else if (tipT[1] < lastAnchored) {
        rep.reject("TIP_BEHIND", `the export anchors seq ${lastAnchored} but head ${anchor.head.n}'s tip is seq ${tipT[1]}`);
      } else if (tipT[1] > lastAnchored) {
        rep.reject("TIP_MISSING_PROOF", `head ${anchor.head.n} includes seq ${tipT[1]} but the export carries no inclusion proof for it`);
      } else if (!bytesEq(tipT[2], eventHash(events[lastAnchored])) || tipT[3] !== entries[lastAnchored].log_index) {
        rep.reject("TIP_MISMATCH", `head ${anchor.head.n}'s tip does not match the export's event ${lastAnchored}`, lastAnchored);
      }
    }
  }
  if (events.length > anchored.length) {
    rep.add("info", "UNANCHORED_EVENTS", `events ${anchored.length}-${events.length - 1} are unanchored, not yet provable: a truncation of them ` +
      "cannot be detected until the next head");
  }

  // ---- witnesses (G4 a-f)
  if (!known.length && !mirror.length) {
    rep.add("warning", "NO_WITNESS", "no witness supplied (--known-heads, --mirror): a split view or a rewrite cannot be detected");
  }
  const groups = [...chain.map((e) => ["export", e]), ...mirror.map((e) => ["mirror", e]), ...known.map((e) => ["known-heads", e])];
  for (const f of equivocation(groups)) rep.findings.push(f);
  if (anchor === null && known.length) {
    rep.add("detect", "HEAD_ROLLBACK", "the export carries no head while known heads exist: it does not show this " +
      "record absent from the latest head (G4 b)", null, known.slice(-1).map((e) => ({ head: e.head, sigs: e.sigs })));
  }
  if (anchor !== null) {
    for (const f of rollback(anchor, [...mirror.map((e) => ["mirror", e]), ...known.map((e) => ["known-heads", e])])) rep.findings.push(f);
  }
  let mirrorProven = true;
  if (mirror.length) {
    const seenN = new Set(), mchain = [];
    for (const e of [...mirror].sort((a, b) => a.head.n - b.head.n)) {
      if (!seenN.has(e.head.n)) {
        seenN.add(e.head.n);
        mchain.push(e);
      }
    }
    for (const f of checkChain(mchain, "mirror")) {
      if (f.code === "HEAD_GAP" || f.code === "HEAD_CONSISTENCY") {
        Object.assign(f, { level: "error", code: "WITNESS_UNPROVEN" });
        mirrorProven = false;
      } else {
        f.class = detectClass(f.code);
      }
      rep.findings.push(f);
    }
  }
  const mirrorBytes = new Set(mirror.map((e) => headBytes(e.head)));
  const knownBytes = new Set(known.map((e) => headBytes(e.head)));
  const witnessOk = new Set([...mirrorBytes, ...knownBytes]);
  const exportBytesSet = new Set(chain.map((e) => headBytes(e.head)));
  const mirrorLinked = mirrorProven && [...mirrorBytes].some((b) => exportBytesSet.has(b));
  const linked = new Set([...exportBytesSet, ...(mirrorLinked ? mirrorBytes : [])]);
  for (const [src, lst] of [["mirror", mirror], ["known-heads", known]]) {
    for (const e of lst) {
      if (!linked.has(headBytes(e.head))) {
        rep.add("warning", "WITNESS_UNLINKED", `${src} head ${e.head.n} is not linked to the export's head chain; no consistency with it is claimed`);
      }
    }
  }
  if (requireAnchored) {
    const needed = [...new Set([...[...firstHead.values()].map((fh) => fh.head.n), ...(anchor ? [anchor.head.n] : [])])].sort((a, b) => a - b);
    for (const n of needed) {
      if (!mirrorBytes.has(headBytes(byN.get(n).head))) {
        rep.add("detect", "HEAD_UNANCHORED", `anchoring head ${n} is not in the supplied mirror (G4 e)`, null,
          { head: byN.get(n).head, sigs: byN.get(n).sigs });
      }
    }
    if (anchor === null) rep.add("detect", "HEAD_UNANCHORED", "no event is anchored, so nothing is in the mirror (G4 e)");
  }
  const forkPairs = new Set();
  groups.forEach(([sa, a], i) => {
    for (const [sb, b] of groups.slice(i + 1)) {
      const ha = a.head, hb = b.head;
      if (ha.tree_size !== hb.tree_size) continue;
      if (ha.log_root === hb.log_root && ha.tip_root === hb.tip_root && ha.tip_count === hb.tip_count) continue;
      const key = JSON.stringify([headBytes(ha), headBytes(hb)].sort(cmpCodePoints));
      if (forkPairs.has(key)) continue;
      forkPairs.add(key);
      rep.add("detect", "HEAD_FORK_SAME_SIZE", `head ${ha.n} (${sa}) and head ${hb.n} (${sb}) have the same tree_size ${ha.tree_size} but ` +
        "commit different log states", null, [{ head: ha, sigs: a.sigs }, { head: hb, sigs: b.sigs }]);
    }
  });
  const merged = new Map();
  for (const [src, e] of groups) if (!merged.has(e.head.n)) merged.set(e.head.n, [src, e]);
  const order = [...merged.keys()].sort((a, b) => a - b).map((n) => merged.get(n));
  order.forEach(([sa, a], i) => {
    for (const [sb, b] of order.slice(i + 1)) {
      if (b.head.tree_size < a.head.tree_size) {
        rep.add("detect", "HEAD_SIZE_DECREASE", `head ${b.head.n} (${sb}) has a smaller tree_size than head ${a.head.n} (${sa}) (G4 d)`,
          null, [{ head: a.head, sigs: a.sigs }, { head: b.head, sigs: b.sigs }]);
        break;
      }
    }
  });
  const tipsByN = [];
  if (tipT !== null) tipsByN.push([anchor.head.n, tipT, { head: anchor.head, sigs: anchor.sigs, tip: doc.tip.member }]);
  for (const e of known) {
    const t = get(e, "tip");
    if (t === null) continue;
    let kt;
    try {
      if (!(isDict(t) && keySetEq(t, ["index", "leaf", "path"]))) throw new ProofError("TIP_FORM", "known tip must be exactly {index, leaf, path}");
      kt = tipTuple(t.leaf);
      if (!bytesEq(kt[0], tag)) continue;
      if (!isNat(t.index)) throw new ProofError("TIP_FORM", "known tip index form");
      const path = parsePath(t.path);
      verifyTipMember(tag, kt, t.index, path, e.head.tip_count, fromHex(e.head.tip_root));
    } catch (ex) {
      if (!(ex instanceof ProofError)) throw ex;
      rep.add("warning", "WITNESS_TIP_IGNORED", `known tip at head ${e.head.n} ignored: ${ex.toString()}`);
      continue;
    }
    const evK = { head: e.head, sigs: e.sigs, tip: t };
    tipsByN.push([e.head.n, kt, evK]);
    if (kt[1] >= events.length) {
      rep.add("detect", "TIP_AHEAD_TRUNCATED", `the export is incomplete: known head ${e.head.n} commits this record's ` +
        `tip at seq ${kt[1]} but the export ends at seq ${events.length - 1}; this finding does not say who shortened the export`, null, evK);
    } else if (!bytesEq(eventHash(events[kt[1]]), kt[2])) {
      rep.add("detect", "TIP_FORK", `known head ${e.head.n} committed a different event at seq ${kt[1]} than the export carries`, kt[1], evK);
    }
  }
  tipsByN.sort((x, y) => x[0] - y[0]);
  for (let k = 0; k + 1 < tipsByN.length; k++) {
    const [na, ta, ea] = tipsByN[k], [nb, tb, eb] = tipsByN[k + 1];
    if (nb > na && (tb[1] < ta[1] || (tb[1] === ta[1] && !bytesEq(tb[2], ta[2])))) {
      rep.add("detect", "TIP_BACKWARDS", `this record's tip at head ${nb} (seq ${tb[1]}) is behind or differs from its tip at head ${na} ` +
        `(seq ${ta[1]}) (G4 f)`, null, [ea, eb]);
    } else if (nb === na && (tb[1] !== ta[1] || !bytesEq(tb[2], ta[2]))) {
      rep.add("detect", "TIP_FORK", `two different tips for this record at head ${na}`, null, [ea, eb]);
    }
  }

  // ---- compromised keys (G6)
  for (const i of anchored) {
    const kid = events[i].server_key_id;
    if (kh.compromised(kid)) {
      const fh = firstHead.get(i);
      if (!witnessOk.has(headBytes(fh.head))) {
        rep.add("detect", "KEY_COMPROMISED_UNWITNESSED", `event ${i} is signed by key ${kid}, later revoked for ` +
          `compromise; its first including head ${fh.head.n} is not in any supplied witness`, i,
        { key: kh.state.get(kid), event: entries[i], first_head: { head: fh.head, sigs: fh.sigs } });
      }
    }
  }
  for (const e of chain) {
    const bad = e.sigs.filter((s) => kh.compromised(s.key_id)).map((s) => s.key_id);
    if (bad.length && !witnessOk.has(headBytes(e.head))) {
      rep.add("detect", "KEY_COMPROMISED_UNWITNESSED", `export head ${e.head.n} is signed by key ${bad[0]}, later revoked for ` +
        "compromise, and is not in any supplied witness", null, { key: kh.state.get(bad[0]), head: e.head, sigs: e.sigs });
    }
  }
  for (const tb of rep.time_bounds) {
    if (hasOwn(tb, "head_n")) {
      const hb = headBytes(byN.get(tb.head_n).head);
      tb.witnessed_by = [["mirror", mirrorBytes], ["known-heads", knownBytes]].filter(([, bs]) => bs.has(hb)).map(([src]) => src);
    }
  }
  const announced = new Set([...chain, ...mirror, ...known].filter((e) => e.head.next_key !== null)
    .map((e) => `${e.head.n + 1}:${e.head.next_key.key_id}`));
  const used = [...new Set([...chain.flatMap((e) => e.sigs.map((s) => s.key_id)), ...events.map((ev) => ev.server_key_id)])].sort();
  for (const kid of used) {
    const intro = kh.intro.has(kid) ? kh.intro.get(kid) : null;
    if (intro === null || intro === kh.entries[0] || intro.valid_from_head === 0) continue;
    if (!announced.has(`${intro.valid_from_head}:${kid}`)) {
      rep.add("warning", "KEY_ANNOUNCEMENT_UNSEEN", `key ${kid} (valid from head ${intro.valid_from_head}) signs this export, but no ` +
        `supplied head ${intro.valid_from_head - 1} carries a next_key announcing it: the announcement is unverified`);
    }
  }

  // ---- party data (E1, G8) and display warnings (V54)
  for (const line of eraseStatusLines(st)) rep.add("status", "PARTY_ERASED", line);
  checkPlaintext(doc.plaintext, st, rep);
  for (const role of ["P", "C"]) {
    const name = get(st.parties[role], "name");
    if (name !== null) {
      const sc = scriptsOf(name);
      if (sc.size > 1) {
        rep.add("warning", "NAME_MIXED_SCRIPT", `party ${role} name mixes scripts (${[...sc].sort().join(", ")}); names are self-described, not verified`);
      }
    }
  }
  for (const f of rep.findings) if (f.level === "detect" && !hasOwn(f, "class")) f.class = detectClass(f.code);
  const s = st.summary();
  rep.add("status", "RECORD_STATE", `state ${s.state} after ${s.events} events; pending ` +
    `${s.pending === null ? "none" : `${s.pending.kind} by ${s.pending.by} at seq ${s.pending.seq}`}; disputes ${s.disputed}`);
  return { report: rep, extra: { doc, chain, anchor, tip: tipT } };
}

function checkPlaintext(pt, st, rep) {
  if (pt === null) {
    for (const role of ["P", "C"]) if (!st.erased.has(role)) rep.add("status", "PLAINTEXT_UNAVAILABLE", `party ${role}: plaintext unavailable (not included)`);
    return;
  }
  if (!(isDict(pt) && Object.keys(pt).every((k) => ["claimed", "p", "c"].includes(k)) && Array.isArray(get(pt, "claimed")) &&
    pt.claimed.every((x) => typeof x === "string") && pt.claimed.every((x) => x === "P" || x === "C") &&
    new Set(pt.claimed).size === pt.claimed.length)) {
    rep.reject("PLAINTEXT_FORM", "plaintext section form");
    return;
  }
  for (const role of ["P", "C"]) {
    const data = get(pt, role.toLowerCase());
    const claimed = pt.claimed.includes(role);
    if (st.erased.has(role)) {
      if (data !== null || claimed) rep.reject("PLAINTEXT_AFTER_ERASE", `party ${role} was erased but the export carries its plaintext`);
      continue;
    }
    if (data === null) {
      if (claimed) {
        rep.reject("PLAINTEXT_MISSING", `the export claims party ${role}'s plaintext but omits it (r7 N6: the export contradicts itself; REJECT)`);
      } else {
        rep.add("status", "PLAINTEXT_UNAVAILABLE", `party ${role}: plaintext unavailable (not included)`);
      }
      continue;
    }
    if (!claimed) {
      rep.reject("PLAINTEXT_FORM", `party ${role} plaintext present but not claimed`);
      continue;
    }
    if (!(isDict(data) && keySetEq(data, ["email", "k_rec"]) && typeof data.email === "string" && isHex(data.k_rec, HEX64_RE))) {
      rep.reject("PLAINTEXT_FORM", `party ${role} plaintext form`);
      continue;
    }
    if (emailDigest(fromHex(data.k_rec), data.email) !== st.parties[role].digest) {
      rep.reject("PLAINTEXT_DIGEST", `party ${role} plaintext does not match its committed digest`);
    }
  }
}

// A one-call convenience for pages and scripts: the verdict and the report as plain JSON (the CLI's --json shape).
export function verifyRecord(exportBytes, opts = {}) {
  try {
    const { report } = verifyExport(exportBytes, opts);
    return report.toJSON();
  } catch (e) {
    if (e instanceof InputError) {
      return { result: "ERROR", findings: [{ level: "error", code: e.code, seq: null, message: e.message }], time_bounds: [] };
    }
    // A verifier fault must never look like a verdict (cli.py maps it to exit 3 for the same reason).
    return { result: "ERROR", findings: [{ level: "error", code: "INTERNAL", seq: null,
      message: `internal error while verifying (${e && e.name ? e.name : "Error"}); please report it` }], time_bounds: [] };
  }
}

// ================================================================ cli.py: `handoff verify`, with injectable file access

export const EXIT = { ACCEPT: 0, REJECT: 1, DETECT: 2, ERROR: 3 };
const MAX_SIDE_FILE = 16 * 1024 * 1024;
const MAX_MIRROR_FILES = 100000;
class UsageError extends Error { }

export const USAGE = "usage: handoff verify RECORD.json [--known-heads FILE] [--mirror DIR] [--require-anchored]\n" +
  "                      [--update-known-heads FILE] [--keys FILE] [--json]";

function parseArgv(argv) {
  const opts = { command: null, record: null, known_heads: null, mirror: null, require_anchored: false, update_known_heads: null,
    keys: null, json: false, help: false };
  const valued = { "--known-heads": "known_heads", "--mirror": "mirror", "--update-known-heads": "update_known_heads", "--keys": "keys" };
  const flags = { "--require-anchored": "require_anchored", "--json": "json" };
  const positional = [], unknown = [];
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i];
    if (a === "-h" || a === "--help") opts.help = true;
    else if (hasOwn(flags, a)) opts[flags[a]] = true;
    else if (hasOwn(valued, a)) {
      if (i + 1 >= argv.length) throw new UsageError(`argument ${a}: expected one argument`);
      opts[valued[a]] = argv[++i];
    } else if (a.startsWith("--") && a.includes("=") && hasOwn(valued, a.slice(0, a.indexOf("=")))) {
      opts[valued[a.slice(0, a.indexOf("="))]] = a.slice(a.indexOf("=") + 1);
    } else if (a.startsWith("-") && a !== "-") unknown.push(a);
    else positional.push(a);
  }
  if (opts.help) return opts;
  if (!positional.length) throw new UsageError("usage: handoff verify RECORD.json [options]");
  opts.command = positional.shift();
  if (opts.command !== "verify") throw new UsageError(`argument command: invalid choice: ${pyRepr(opts.command)} (choose from 'verify')`);
  if (!positional.length) throw new UsageError("the following arguments are required: RECORD.json");
  opts.record = positional.shift();
  if (positional.length || unknown.length) throw new UsageError("unrecognized arguments: " + [...positional, ...unknown].join(" "));
  return opts;
}

// io: {readFile(path) -> Uint8Array, size(path) -> number, isFile(path), isDir(path), listHeadFiles(dir) -> sorted
// paths of *.json under dir/heads, join(a, b), basename(p), appendFile(path, bytes), exists(path)}.
function cliRead(io, path, limit = MAX_SIDE_FILE) {
  try {
    const b = io.readFile(path);
    return b.length > limit ? b.slice(0, limit + 1) : b;
  } catch (e) {
    throw new UsageError(`cannot read ${io.basename(path)}: ${e && e.strerror ? e.strerror : "No such file or directory"}`);
  }
}

function splitLinesBytes(b) {
  // bytes.splitlines(): \n, \r\n and \r end a line
  const out = [];
  let s = 0;
  for (let i = 0; i < b.length; i++) {
    if (b[i] === 0x0a || b[i] === 0x0d) {
      out.push(b.slice(s, i));
      if (b[i] === 0x0d && b[i + 1] === 0x0a) i++;
      s = i + 1;
    }
  }
  if (s < b.length) out.push(b.slice(s));
  return out;
}
const ASCII_WS = new Set([0x20, 0x09, 0x0a, 0x0d, 0x0b, 0x0c]);
export const bytesStripNonEmpty = (b) => b.some((x) => !ASCII_WS.has(x));
function bytesStrip(b) {
  let a = 0, e = b.length;
  while (a < e && ASCII_WS.has(b[a])) a++;
  while (e > a && ASCII_WS.has(b[e - 1])) e--;
  return b.slice(a, e);
}

function textReport(rep, out) {
  out.write(`RESULT: ${rep.result}\n`);
  for (const f of rep.findings) {
    const seq = f.seq === null ? "" : ` (seq ${f.seq})`;
    out.write(`[${f.level}] ${f.code}${seq}: ${f.message}\n`);
    if (hasOwn(f, "evidence")) out.write(`    evidence: ${pyJsonDumps(f.evidence)}\n`);
  }
  for (const t of rep.time_bounds) out.write(`time: seq ${t.seq} ${t.type}: ${t.statement}\n`);
}

export function cliMain(argv, io, out, err) {
  const asJson = argv.includes("--json");
  let repJson;
  try {
    const args = parseArgv(argv);
    if (args.help) {
      out.write(USAGE + "\n\nOffline verifier for Handoff v0 record exports. Exit codes: 0 ACCEPT, 1 REJECT, 2 DETECT, 3 ERROR.\n");
      return 0;
    }
    if (args.require_anchored && !args.mirror) throw new UsageError("--require-anchored needs --mirror");
    const record = cliRead(io, args.record, EXPORT_LIMITS.maxBytes);
    const keys = args.keys ? cliRead(io, args.keys) : null;
    let known = null;
    if (args.known_heads) known = splitLinesBytes(cliRead(io, args.known_heads)).filter(bytesStripNonEmpty);
    let mheads = null, mkeys = null;
    if (args.mirror) {
      if (!io.isDir(args.mirror)) throw new UsageError("--mirror is not a directory");
      const files = io.listHeadFiles(args.mirror);
      if (files.length > MAX_MIRROR_FILES) throw new UsageError("mirror holds too many head files");
      mheads = files.map((f) => cliRead(io, f));
      const kp = io.join(args.mirror, "keys.json");
      mkeys = io.isFile(kp) ? cliRead(io, kp) : null;
    }
    let report, extra;
    try {
      ({ report, extra } = verifyExport(record, { keysBytes: keys, knownLines: known, mirrorHeads: mheads, mirrorKeys: mkeys,
        requireAnchored: args.require_anchored }));
    } catch (e) {
      if (e instanceof InputError) throw new UsageError(e.message);
      throw new UsageError(`internal error while verifying (${e && e.name ? e.name : "Error"}); please report it`);
    }
    repJson = report.toJSON();
    if (args.update_known_heads) {
      if (report.result === "ACCEPT" && extra !== null) updateKnown(io, args.update_known_heads, extra, repJson);
      else {
        repJson.findings.push({ level: "info", code: "KNOWN_HEADS_NOT_UPDATED", seq: null,
          message: "the --update-known-heads file was not changed (result is not ACCEPT)" });
      }
    }
  } catch (e) {
    if (!(e instanceof UsageError)) throw e;
    if (asJson) {
      out.write(pyJsonDumps({ result: "ERROR", findings: [{ level: "error", code: "USAGE", seq: null, message: e.message }], time_bounds: [] }) + "\n");
    } else {
      err.write(`handoff: ${e.message}\n`);
    }
    return 3;
  }
  if (asJson) out.write(pyJsonDumps(repJson) + "\n");
  else textReport(repJson, out);
  return EXIT[repJson.result];
}

function updateKnown(io, path, extra, repJson) {
  const { chain, anchor, doc } = extra;
  const existing = new Set();
  if (io.exists(path)) {
    for (const line of splitLinesBytes(cliRead(io, path))) if (bytesStripNonEmpty(line)) existing.add(toHex(bytesStrip(line)));
  }
  const lines = [];
  for (const e of chain) {
    const item = { head: e.head, sigs: e.sigs };
    if (e === anchor && doc.tip !== null && hasOwn(doc.tip, "member")) item.tip = doc.tip.member;
    const b = canonDumps(item, SIDE_LIMITS);
    if (!existing.has(toHex(b))) lines.push(b);
  }
  try {
    io.appendFile(path, concat(...lines.flatMap((b) => [b, new Uint8Array([10])])));
  } catch (e) {
    throw new UsageError(`cannot write --update-known-heads file: ${e && e.strerror ? e.strerror : "error"}`);
  }
  repJson.findings.push({ level: "info", code: "KNOWN_HEADS_UPDATED", seq: null, message: `appended ${lines.length} line(s) to the --update-known-heads file` });
}

// ================================================================ fixture helpers (SPEC section 15 digest rule)

export function scanMatches(text, candidates, forms, methods) {
  const FORMS = { as_given: (c) => c, lower: (c) => lower15(c), nfc_strip_lower: (c) => lower15(pyStrip(nfc15(c))) };
  const METHODS_ = {
    sha256: (f) => toHex(sha256(utf8(f))),
    "sha256-lower": (f) => toHex(sha256(utf8(lower15(f)))),
    "hmac-sha256-empty-key": (f) => toHex(hmacSha256(new Uint8Array(0), utf8(f))),
  };
  const present = new Set();
  let run = "";
  for (const ch of text + "\u0000") {
    if ("0123456789abcdef".includes(ch) && ch.length === 1) {
      run += ch;
      continue;
    }
    for (let k = 0; k + 64 <= run.length; k++) present.add(run.slice(k, k + 64));
    run = "";
  }
  const values = new Set();
  for (const c of candidates) for (const f of forms) for (const m of methods) values.add(METHODS_[m](FORMS[f](c)));
  let n = 0;
  for (const v of values) if (present.has(v)) n++;
  return n;
}

// ================================================================ conformance runner (SPEC section 15 fixtures)
// The same checks as the reference runner (run_fixtures.py and fxlib) for every fixture kind: verify, canon, digest,
// text, render and ed25519. Server expectations (expect.server, expect.server_code, expect.server_refused_seq) are not
// executed: there is no server here, and the reference runner does not run them either. Every file is checked against
// the fixtures' SHA256SUMS.txt before it is used.

function fxExportBytes(i) {
  if ("export_b64" in i) return b64decode(i.export_b64);
  const g = i.export_gen;
  const pre = b64decode(g.prefix_b64), unit = b64decode(g.unit_b64), suf = b64decode(g.suffix_b64);
  const b = new Uint8Array(pre.length + unit.length * g.count + suf.length);
  b.set(pre);
  let o = pre.length;
  if (unit.length && g.count) {
    b.set(unit, o);
    let filled = unit.length;
    const total = unit.length * g.count;
    while (filled < total) {
      const n = Math.min(filled, total - filled);
      b.copyWithin(o + filled, o, o + n);
      filled += n;
    }
    o += total;
  }
  b.set(suf, o);
  if (toHex(sha256(b)) !== g.sha256) throw new Error("export_gen sha256 mismatch");
  return b;
}

function fxSplitNL(b) {
  const out = [];
  let s = 0;
  for (let k = 0; k <= b.length; k++) {
    if (k === b.length || b[k] === 0x0a) {
      out.push(b.slice(s, k));
      s = k + 1;
    }
  }
  return out;
}

// fxlib.run_verify
function fxRunVerify(i) {
  const keys = "keys_b64" in i ? b64decode(i.keys_b64) : null;
  let known = null;
  if ("known_heads_b64" in i) known = fxSplitNL(b64decode(i.known_heads_b64)).filter(bytesStripNonEmpty);
  let mheads = null, mkeys = null;
  if ("mirror" in i) {
    mheads = i.mirror.heads_b64.map(b64decode);
    mkeys = "keys_b64" in i.mirror ? b64decode(i.mirror.keys_b64) : null;
  }
  const opts = { keysBytes: keys, knownLines: known, mirrorHeads: mheads, mirrorKeys: mkeys, requireAnchored: !!i.require_anchored };
  if (i.local_caps !== undefined && i.local_caps !== null) opts.localCaps = i.local_caps;
  let rep;
  try {
    rep = verifyExport(fxExportBytes(i), opts).report;
  } catch (e) {
    if (!(e instanceof InputError)) throw e;
    return {
      result: "ERROR", code: e.code, reject_codes: [], detect_codes: [], error_codes: [e.code], other_codes: [], time_bounds: [],
      messages: [e.message], error_findings: [{ code: e.code, message: e.message }],
    };
  }
  const rej = rep.codes("reject"), det = rep.codes("detect"), err = rep.codes("error");
  const oth = rep.findings.filter((f) => !["reject", "detect", "error"].includes(f.level)).map((f) => f.code);
  const res = rep.result;
  const code = res === "REJECT" ? rej[0] : res === "DETECT" ? det[0] : res === "ERROR" ? err[0] : null;
  const tb = rep.time_bounds.filter((t) => "head_n" in t).map((t) => ({ seq: t.seq, head_n: t.head_n, declared_gap_seconds: t.declared_gap_seconds }));
  return {
    result: res, code, reject_codes: rej, detect_codes: det, error_codes: err, other_codes: oth, time_bounds: tb,
    messages: rep.findings.map((f) => f.message),
    classes: rep.findings.filter((f) => f.level === "detect").map((f) => (f.class === undefined ? null : f.class)),
    detect_findings: rep.findings.filter((f) => f.level === "detect").map((f) => ({ code: f.code, class: f.class === undefined ? null : f.class, message: f.message })),
    error_findings: rep.findings.filter((f) => f.level === "error").map((f) => ({ code: f.code, message: f.message })),
  };
}

// Python == over JSON-like values (dict key order ignored)
function fxEq(a, b) {
  if (a === undefined) a = null;
  if (b === undefined) b = null;
  if (a === null || b === null) return a === b;
  if (typeof a !== typeof b) return false;
  if (typeof a !== "object") return a === b;
  if (Array.isArray(a) !== Array.isArray(b)) return false;
  if (Array.isArray(a)) return a.length === b.length && a.every((x, k) => fxEq(x, b[k]));
  const ka = Object.keys(a), kb = Object.keys(b);
  return ka.length === kb.length && ka.every((k) => hasOwn(b, k) && fxEq(a[k], b[k]));
}

const fxShow = (v) => JSON.stringify(v === undefined ? null : v);

function fxTextOk(spec, msgs, flags) {
  return msgs.length > 0 && msgs.every((m) => spec.must_match.every((p) => new RegExp(p, flags).test(m)) &&
    !(spec.must_not_match || []).some((p) => new RegExp(p, flags).test(m)));
}

function fxCountMatches(rx, t) {
  let n = 0;
  for (const _ of t.matchAll(rx)) n++;
  return n;
}

// In-memory files for cliMain, so render fixtures run the same way in a browser and in Node.
function memIO(files) {
  const base = (p) => p.slice(p.lastIndexOf("/") + 1);
  return {
    readFile(p) {
      if (!files.has(p)) {
        const e = new Error("No such file or directory");
        e.strerror = "No such file or directory";
        throw e;
      }
      return files.get(p);
    },
    isDir: () => false,
    isFile: (p) => files.has(p),
    exists: (p) => files.has(p),
    join: (a, b) => a.replace(/\/+$/, "") + "/" + b,
    basename: base,
    appendFile: (p, bytes) => files.set(p, concat(files.get(p) || new Uint8Array(0), bytes)),
    listHeadFiles: () => [],
  };
}

// fxlib.run_render: run the command line once per argv, with the placeholder names replaced by files
function fxRunRender(i) {
  const files = new Map();
  const paths = { "RECORD.json": "/fixture/record.json", "keys.json": "/fixture/keys.json" };
  files.set(paths["RECORD.json"], fxExportBytes(i));
  files.set(paths["keys.json"], b64decode(i.keys_b64));
  if ("known_heads_b64" in i) {
    paths["known-heads.json"] = "/fixture/known-heads.json";
    files.set(paths["known-heads.json"], b64decode(i.known_heads_b64));
  }
  const stdouts = [], stderrs = [], exits = [];
  for (const argv of i.cli_argv) {
    let o = "", e = "";
    const code = cliMain(argv.map((a) => (hasOwn(paths, a) ? paths[a] : a)), memIO(files), { write: (s) => { o += s; } }, { write: (s) => { e += s; } });
    exits.push(code);
    stdouts.push(o);
    stderrs.push(e);
  }
  const outs = stdouts.map((s, k) => s + stderrs[k]);
  const pats = i.banned_regex || [];
  const fl = (i.regex_flags || "").includes("i") ? "i" : "";
  let banned = 0;
  if (pats.length) {
    const rx = new RegExp(pats.join("|"), "g" + fl);
    banned = outs.reduce((n, t) => n + fxCountMatches(rx, t), 0);
  }
  let doc = null, hasJson = false;
  i.cli_argv.forEach((argv, k) => {
    if (argv.includes("--json")) {
      hasJson = true;
      try {
        doc = JSON.parse(stdouts[k]);
      } catch (e) {
        doc = null;
      }
    }
  });
  return {
    result: doc !== null && typeof doc === "object" && !Array.isArray(doc) ? (doc.result === undefined ? null : doc.result) : null,
    cli_exits: exits, banned_matches: banned, json: doc, has_json: hasJson, outputs: outs,
    empty_captures: outs.map((t, k) => (t.trim() ? -1 : k)).filter((k) => k >= 0),
    empty_patterns: pats.filter((x) => new RegExp("^(?:" + x + ")$", fl).test("")),
  };
}

// fxlib.check_time_bounds_form
function fxCheckTimeBoundsForm(form, doc) {
  if (!(doc && typeof doc === "object" && Array.isArray(doc.time_bounds))) return "no time_bounds array in the --json output";
  if (!doc.time_bounds.every((t) => t && typeof t === "object" && !Array.isArray(t))) return "a time_bounds entry is not an object";
  const anchored = doc.time_bounds.filter((t) => "head_n" in t), unanch = doc.time_bounds.filter((t) => !("head_n" in t));
  if (anchored.length !== form.anchored_count || unanch.length !== form.unanchored_count) return `entry counts ${anchored.length}/${unanch.length}`;
  for (const t of anchored) {
    const miss = form.anchored_members.filter((m) => !(m in t));
    if (miss.length) return "anchored entry lacks " + fxShow(miss);
    if (t.time_source !== form.time_source) return "time_source " + fxShow(t.time_source);
    if (!Number.isInteger(t.declared_gap_seconds)) return "declared_gap_seconds is not an integer";
    const stmt = form.statement_template.replace(/\{(\w+)\}/g, (_, k) => String(t[k]));
    if (t.statement !== stmt) return "statement " + fxShow(t.statement);
    const wb = t.witnessed_by;
    if ("witnessed_by" in form && !fxEq(wb, form.witnessed_by)) return `witnessed_by ${fxShow(wb)} != ${fxShow(form.witnessed_by)}`;
    if (!Array.isArray(wb) || wb.some((x) => x !== "mirror" && x !== "known-heads") ||
      !fxEq(wb, ["mirror", "known-heads"].filter((x) => wb.includes(x)))) return "witnessed_by " + fxShow(wb);
  }
  for (const t of unanch) {
    const miss = form.unanchored_members.filter((m) => !(m in t));
    if (miss.length || t.statement !== form.unanchored_statement) return "unanchored entry " + fxShow(t);
  }
  return "";
}

// One fixture (a parsed fixture file). Returns {why, got}: why is "" when the fixture passes.
export function runFixture(fx) {
  const e = fx.expect, i = fx.inputs, k = fx.kind;
  let why = "", got = null;
  if (k === "verify") {
    got = fxRunVerify(i);
    for (const f of ["result", "code", "reject_codes", "detect_codes", "error_codes", "other_codes"]) {
      if (!fxEq(got[f], e[f])) why += `${f} ${fxShow(got[f])} != ${fxShow(e[f])}; `;
    }
    if ("time_bounds" in e && !fxEq(got.time_bounds, e.time_bounds)) why += "time_bounds differ; ";
    const allc = [...got.reject_codes, ...got.detect_codes, ...got.error_codes, ...got.other_codes];
    if ((e.absent_codes || []).some((c) => allc.includes(c))) why += "absent_codes reported; ";
    if ("detect_classes" in e && !fxEq(got.classes, e.detect_classes)) why += `detect_classes ${fxShow(got.classes)} != ${fxShow(e.detect_classes)}; `;
    if ((e.required_codes || []).some((c) => !allc.includes(c))) why += "required_codes missing; ";
    const ft = e.finding_text;
    if (ft) {
      const msgs = (got.detect_findings || []).filter((f) => f.code === ft.code).map((f) => f.message);
      if (!fxTextOk(ft, msgs, "i")) why += "finding_text; ";
    }
    const et = e.error_text;
    if (et && !(et.must_match && et.must_match.length)) why += "fixture: error_text.must_match is empty; ";
    else if (et) {
      const msgs = (got.error_findings || []).filter((f) => f.code === et.code).map((f) => f.message);
      if (!fxTextOk(et, msgs, (et.regex_flags || "").includes("i") ? "i" : "")) why += "error_text; ";
    }
  } else if (k === "canon") {
    try {
      const out = canonDumps(canonLoads(b64decode(i.json_b64), EVENT_LIMITS), EVENT_LIMITS);
      got = { result: "OK", canonical_b64: b64encode(out) };
    } catch (ex) {
      if (!(ex instanceof CanonError)) throw ex;
      got = { result: "ERROR", code: ex.code };
    }
    if (!fxEq(got, e)) why = "canon " + fxShow(got);
  } else if (k === "digest") {
    if ("candidates" in i) got = { matches: scanMatches(utf8Decode(b64decode(i.export_b64)), i.candidates, i.forms, i.methods) };
    else got = { digest: emailDigest(fromHex(i.k_rec_hex), i.value) };
    if (!fxEq(got, e)) why = "digest " + fxShow(got);
  } else if (k === "text") {
    const rx = new RegExp(i.banned_regex.join("|"), "gi");
    const nb = fxCountMatches(rx, i.cli_output_json) + fxCountMatches(rx, i.cli_output_text);
    const v = fxRunVerify({ export_b64: i.export_b64, keys_b64: i.keys_b64 });
    got = { banned_matches: nb, result: v.result, verify: v };
    if (!(nb === e.banned_matches && v.result === e.result)) why = "text " + fxShow([nb, v.result]);
  } else if (k === "render") {
    const av = i.cli_argv;
    if (!(Array.isArray(av) && av.length && av.every((x) => Array.isArray(x) && x.length))) {
      why = "fixture: cli_argv is not a non-empty list of argument lists";
    } else if (!["result", "cli_exit", "banned_matches", "time_bounds_form"].some((m) => m in e)) {
      why = "fixture: no expectation member";
    } else {
      got = fxRunRender(i);
      if (got.empty_captures.length) why += `empty capture (invocation ${fxShow(got.empty_captures)} printed nothing); `;
      if ("banned_matches" in e && (!(i.banned_regex && i.banned_regex.length) || got.empty_patterns.length)) {
        why += "fixture: banned_regex empty or matching the empty string; ";
      }
      if (("result" in e || "time_bounds_form" in e) && !got.has_json) why += "fixture: no --json invocation; ";
      if ("result" in e && got.result !== e.result) why += `result ${fxShow(got.result)} != ${fxShow(e.result)}; `;
      if ("cli_exit" in e && !fxEq(got.cli_exits, av.map(() => e.cli_exit))) why += `cli_exit ${fxShow(got.cli_exits)} != ${fxShow(e.cli_exit)}; `;
      if ("banned_matches" in e && got.banned_matches !== e.banned_matches) why += `banned_matches ${got.banned_matches} != ${e.banned_matches}; `;
      if ("time_bounds_form" in e) {
        const p = fxCheckTimeBoundsForm(e.time_bounds_form, got.json);
        if (p) why += `time_bounds_form: ${p}; `;
      }
    }
  } else if (k === "ed25519") {
    try {
      ed25519Verify(fromHex(i.pubkey_hex), fromHex(i.sig_hex), fromHex(i.msg_hex));
      got = { result: "OK", code: null };
    } catch (ex) {
      if (!(ex instanceof CryptoError)) throw ex;
      got = { result: "FAIL", code: ex.code };
    }
    if (!fxEq(got, e)) why = "ed25519 " + fxShow(got);
  } else {
    why = "unknown kind " + k;
  }
  return { why, got };
}

// SHA256SUMS.txt lines: "<64 hex>  <relative path>".
function parseSums(text) {
  const m = new Map();
  for (const line of text.split("\n")) {
    const r = /^([0-9a-f]{64}) [ *](.+)$/.exec(line.replace(/\r$/, ""));
    if (r) m.set(r[2], r[1]);
  }
  return m;
}
// A fixture file name is a relative path inside the fixtures directory: no leading "/", no "\\", no empty, "." or ".."
// segment, no control character.
const fxNameOk = (n) => typeof n === "string" && n.length > 0 && n.length <= 255 && !/[\u0000-\u001f\u007f\\:?#]/.test(n) &&
  n.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");

// runConformance(load, opts): load(name) returns (a promise of) the bytes of a file of the fixtures directory, by its
// relative name. It reads SHA256SUMS.txt and MANIFEST.json, checks the SHA-256 of every file SHA256SUMS.txt lists, and
// runs every fixture in MANIFEST.json order (a fixture whose file is missing from SHA256SUMS.txt or does not match
// fails without running). opts.onLine(line) receives each PASS or FAIL line and the summary lines;
// opts.onCase(record) receives {id, kind, pass, why, got}; opts.pause, if given, is awaited between fixtures (a page
// passes a short timer so it can repaint). Returns {fixtures, pass, fail, base, profile, lines}. Throws if
// SHA256SUMS.txt or MANIFEST.json cannot be read, or a listed file that is not a fixture does not match.
export async function runConformance(load, opts = {}) {
  const onLine = opts.onLine || (() => {});
  const onCase = opts.onCase || (() => {});
  const lines = [];
  const say = (l) => {
    lines.push(l);
    onLine(l);
  };
  const sums = parseSums(utf8Decode(asBytes(await load("SHA256SUMS.txt"), "SHA256SUMS.txt")));
  const manBytes = asBytes(await load("MANIFEST.json"), "MANIFEST.json");
  if (sums.get("MANIFEST.json") !== toHex(sha256(manBytes))) throw new Error("MANIFEST.json does not match SHA256SUMS.txt");
  const manifest = JSON.parse(utf8Decode(manBytes));
  if (!Array.isArray(manifest)) throw new Error("MANIFEST.json is not a list");
  const names = manifest.map((m) => (m && fxNameOk(m.file) ? m.file : null));
  // every other file listed in SHA256SUMS.txt (INDEX.txt, TEST-KEYS.json) is checked too
  const listed = new Set(["MANIFEST.json", ...names.filter((x) => x !== null)]);
  for (const [name, hex] of sums) {
    if (listed.has(name) || !fxNameOk(name)) continue;
    const b = asBytes(await load(name), name);
    if (toHex(sha256(b)) !== hex) throw new Error(name + " does not match SHA256SUMS.txt");
  }
  // load ahead, at most 8 files at a time, and run in order
  const pending = new Array(manifest.length);
  let next = 0;
  const start = () => {
    while (next < manifest.length && next < done + 8) {
      const k = next++;
      pending[k] = names[k] === null ? Promise.resolve(null) : Promise.resolve().then(() => load(names[k])).then((b) => asBytes(b, names[k]), (e) => e);
    }
  };
  let done = 0, bad = 0, nBase = 0, nBaseBad = 0, nProf = 0, nProfBad = 0;
  start();
  for (let k = 0; k < manifest.length; k++) {
    const m = manifest[k];
    const got0 = await pending[k];
    pending[k] = null;
    done = k + 1;
    start();
    let why = "", got = null, fx = null;
    const id = m && m.id !== undefined ? m.id : names[k];
    if (names[k] === null) why = "manifest entry has no usable file name";
    else if (!(got0 instanceof Uint8Array)) why = "cannot load " + names[k] + (got0 && got0.message ? " (" + got0.message + ")" : "");
    else if (sums.get(names[k]) !== toHex(sha256(got0))) why = "sha256 of " + names[k] + " does not match SHA256SUMS.txt";
    else {
      try {
        fx = JSON.parse(utf8Decode(got0));
        ({ why, got } = runFixture(fx));
      } catch (ex) {
        why = "crash " + (ex && ex.name ? ex.name : "Error") + (ex && ex.message ? " (" + ex.message + ")" : "");
      }
    }
    if (why) bad++;
    const prof = fx ? !!fx.profile : !!(m && m.profile);
    if (prof) {
      nProf++;
      if (why) nProfBad++;
    } else {
      nBase++;
      if (why) nBaseBad++;
    }
    say(`${why ? "FAIL" : "PASS"} ${fx ? fx.id : id} ${why}`);
    onCase({ id: fx ? fx.id : id, kind: fx ? fx.kind : (m && m.kind) || null, pass: !why, why, got });
    if (opts.pause) await opts.pause();
  }
  const n = manifest.length;
  say(`SUMMARY-BASE fixtures=${nBase} pass=${nBase - nBaseBad} fail=${nBaseBad}`);
  say(`SUMMARY-PROFILE fixtures=${nProf} pass=${nProf - nProfBad} fail=${nProfBad}`);
  say("NOTE server expectations (expect.server, expect.server_code, expect.server_refused_seq) are not executed by this runner");
  say(`SUMMARY fixtures=${n} pass=${n - bad} fail=${bad}`);
  return { fixtures: n, pass: n - bad, fail: bad, base: { fixtures: nBase, fail: nBaseBad }, profile: { fixtures: nProf, fail: nProfBad }, lines };
}

// ================================================================ Node command line
//   node handoff-verify.mjs verify RECORD.json --keys keys.json [--known-heads FILE] [--mirror DIR]
//                          [--require-anchored] [--update-known-heads FILE] [--json]
//   node handoff-verify.mjs conformance <fixtures URL or directory> [--dump FILE]
// verify reads local files only: no network, no clock. conformance loads the fixtures from the directory, or from the
// URL with its own User-Agent. Exit codes: verify 0 ACCEPT, 1 REJECT, 2 DETECT, 3 ERROR; conformance 0 when every
// fixture passes, 1 when any fails, 3 when the fixtures cannot be loaded.

export const USER_AGENT = "weio-handoff-verify/r8.1a (+https://weio.ai/verify/)";

const STRERROR = { ENOENT: "No such file or directory", EACCES: "Permission denied", EISDIR: "Is a directory", ENOTDIR: "Not a directory" };

// File access for cliMain with Node's fs and path, with the semantics of cli.py (_read, _mirror).
export function nodeIO(fs, path) {
  const wrap = (fn) => {
    try {
      return fn();
    } catch (e) {
      e.strerror = STRERROR[e.code] || e.message;
      throw e;
    }
  };
  const isDir = (p) => {
    try {
      return fs.statSync(p).isDirectory();
    } catch (e) {
      return false;
    }
  };
  const isFile = (p) => {
    try {
      return fs.statSync(p).isFile();
    } catch (e) {
      return false;
    }
  };
  return {
    readFile: (p) => wrap(() => new Uint8Array(fs.readFileSync(p))),
    isDir,
    isFile,
    exists: (p) => fs.existsSync(p),
    join: (a, b) => path.join(a, b),
    basename: (p) => path.basename(p),
    appendFile: (p, bytes) => wrap(() => fs.appendFileSync(p, bytes)),
    listHeadFiles(dir) {
      const root = path.join(dir, "heads");
      const files = [];
      if (!isDir(root)) return files;
      const walk = (d) => {
        const ents = fs.readdirSync(d, { withFileTypes: true });
        const dirs = ents.filter((e) => e.isDirectory()).map((e) => e.name).sort(cmpCodePoints);
        const names = ents.filter((e) => !e.isDirectory()).map((e) => e.name).sort(cmpCodePoints);
        for (const n of names) if (n.endsWith(".json")) files.push(path.join(d, n));
        for (const n of dirs) walk(path.join(d, n));
      };
      walk(root);
      return files.sort(cmpCodePoints);
    },
  };
}

async function conformanceCli(args, fs, path) {
  let dump = null;
  const d = args.indexOf("--dump");
  if (d >= 0) {
    dump = args[d + 1];
    args = args.slice(0, d).concat(args.slice(d + 2));
  }
  if (args.length !== 1 || !dump && d >= 0) {
    process.stderr.write("usage: node handoff-verify.mjs conformance <fixtures URL or directory> [--dump FILE]\n");
    return 3;
  }
  const src = args[0];
  let load;
  if (/^https?:\/\//i.test(src)) {
    const base = src.endsWith("/") ? src : src + "/";
    load = async (name) => {
      const r = await fetch(new URL(name, base), { headers: { "user-agent": USER_AGENT, accept: "*/*" } });
      if (!r.ok) throw new Error(`HTTP ${r.status} for ${name}`);
      return new Uint8Array(await r.arrayBuffer());
    };
  } else {
    const dir = path.resolve(src);
    load = async (name) => new Uint8Array(fs.readFileSync(path.join(dir, name)));
  }
  const dumpLines = [];
  let res;
  try {
    res = await runConformance(load, {
      onLine: (l) => process.stdout.write(l + "\n"),
      onCase: (c) => {
        if (dump) dumpLines.push(JSON.stringify(c));
      },
    });
  } catch (e) {
    process.stderr.write(`conformance: cannot load the fixtures: ${e && e.message ? e.message : e}\n`);
    return 3;
  }
  if (dump) fs.writeFileSync(dump, dumpLines.join("\n") + "\n");
  return res.fail ? 1 : 0;
}

async function nodeMain() {
  const fs = (await import("node:fs")).default;
  const path = (await import("node:path")).default;
  let argv = process.argv.slice(2);
  if (argv[0] === "conformance") return conformanceCli(argv.slice(1), fs, path);
  if (argv[0] !== "verify" && !argv.includes("-h") && !argv.includes("--help")) argv = ["verify", ...argv];
  return cliMain(argv, nodeIO(fs, path), process.stdout, process.stderr);
}

// Run as a command only when Node runs this file itself; in a browser, or when imported, nothing below executes.
if (typeof process === "object" && process !== null && process.versions && process.versions.node && process.argv && process.argv[1]) {
  let isMain = import.meta.main;
  if (isMain === undefined) {
    const { pathToFileURL } = await import("node:url");
    const { resolve } = await import("node:path");
    isMain = import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
  }
  if (isMain) {
    try {
      process.exitCode = await nodeMain();
    } catch (e) {
      // a verifier fault must never look like a verdict
      process.stderr.write(`handoff: internal error (${e && e.name ? e.name : "Error"}); please report it\n`);
      process.exitCode = 3;
    }
  }
}
