#!/usr/bin/env node
/**
 * verify-first-in-time-dried-up-in-order.mjs
 *
 * The evidence for the page public/strata/first-in-time-dried-up-in-order/.
 * Recomputes every number the page displays from independently written
 * reference implementations, reproduces the independent anchor (the seniority
 * walk is the lexicographic maximum by priority, checked against a closed-form
 * prefix characterization across a swept set of registers and flows, plus
 * exact conservation), unit-tests the small pure helpers first, replays
 * battery.json, and supports --mutate.
 *
 * Tie policy, asserted here so it cannot decay: the top lease gain can be a
 * TIE, and the page must never present one member of a tie as the unique
 * best. bestBilateralTrade therefore returns the WHOLE argmax set in a
 * documented order (descending quantity, then seller seniority, then buyer
 * seniority), and section 4b pins that order against hand-worked tie cases
 * and an exhaustive recount, so a future change of tie-break cannot pass
 * silently.
 *
 * Reads the source tree only (this directory's engine.mjs). Never reads a
 * build directory. Prints its check count. Exits non-zero on any failure and
 * on zero checks.
 *
 * Usage:
 *   node verify-first-in-time-dried-up-in-order.mjs
 *   node verify-first-in-time-dried-up-in-order.mjs --mutate
 */

import { readFile, writeFile, rm } from 'node:fs/promises';
import { fileURLToPath, pathToFileURL } from 'node:url';
import path from 'node:path';
import { createHash } from 'node:crypto';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ENGINE_PATH = path.join(HERE, 'engine.mjs');
const BATTERY_PATH = path.join(HERE, 'battery.json');

const eng = await import(pathToFileURL(ENGINE_PATH).href);

// ── harness ───────────────────────────────────────────────────────────────
let CHECKS = 0;
let FAILURES = 0;

function ck(name, cond, extra) {
  CHECKS++;
  if (cond) {
    console.log('  ok  ' + name);
  } else {
    FAILURES++;
    console.log('FAIL  ' + name + (extra !== undefined ? '  ::  ' + JSON.stringify(extra) : ''));
  }
}

function jsonEq(a, b) { return JSON.stringify(a) === JSON.stringify(b); }

function throws(fn) {
  try { fn(); return false; } catch { return true; }
}

console.log('verify-first-in-time-dried-up-in-order');
console.log('anchor: lexicographic-maximum prefix characterization (closed form over');
console.log('        cumulative decrees), written independently of the engine greedy loop;');
console.log('        plus exact integer conservation on every swept case, and the full');
console.log('        argmax set of leases: ties reported whole, never broken silently.');

// ════════════════════════════════════════════════════════════════════════
// SECTION 1. Unit tests for the small pure helpers, BEFORE anything else.
// These are the checks that catch a wrong primitive under a correct algorithm.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[1] helper unit tests (hand-worked cases)');

ck('toMilli(1) === 1000', eng.toMilli(1) === 1000);
ck('toMilli(0.001) === 1', eng.toMilli(0.001) === 1);
ck('toMilli(2.5) === 2500', eng.toMilli(2.5) === 2500);
ck('toMilli(0.0005) throws (more than 3 decimals)', throws(() => eng.toMilli(0.0005)));
ck('toMilli(NaN) throws', throws(() => eng.toMilli(NaN)));
ck('toMilli("3") throws', throws(() => eng.toMilli('3')));
ck('fromMilli(1000) === 1', eng.fromMilli(1000) === 1);
ck('fromMilli(0) === 0', eng.fromMilli(0) === 0);
ck('fromMilli(1.5) throws', throws(() => eng.fromMilli(1.5)));

let rt = true;
for (let i = 0; i <= 2000; i++) {
  const x = i / 1000;
  if (eng.fromMilli(eng.toMilli(x)) !== x) { rt = false; break; }
}
ck('toMilli/fromMilli roundtrip exact on 0.000..2.000 step 0.001 (2001 cases)', rt);

// ceilDiv is not exported; exercise it through the forfeiture ceiling it drives:
// decree 30000 at 85% must reserve exactly 25500 (hand-worked).
{
  const reg = [{ id: 'a', name: 'A', date: '1900-01-01', decreeMilli: 30000, valuePerUnit: 10, needMilli: 0 }];
  const alloc = [{ id: 'a', allocatedMilli: 30000 }];
  const out = eng.forfeitureDiversion(reg, alloc, 85);
  ck('forfeiture ceiling: ceil(30000*85/100) === 25500 (drives ceilDiv)',
     out[0].divertedMilli === 25500, out);
}

// seniority comparator, hand-worked: date ascending, ties by input position.
{
  const reg = [
    { id: 'c', name: 'C', date: '1990-01-01', decreeMilli: 1000, valuePerUnit: 1, needMilli: 1000 },
    { id: 'a', name: 'A', date: '1970-01-01', decreeMilli: 1000, valuePerUnit: 1, needMilli: 1000 },
    { id: 'b', name: 'B', date: '1970-01-01', decreeMilli: 1000, valuePerUnit: 1, needMilli: 1000 }
  ];
  ck('seniorityOrder: dates ascend, ties keep input order',
     jsonEq(eng.seniorityOrder(reg).map(r => r.id), ['a', 'b', 'c']),
     eng.seniorityOrder(reg).map(r => r.id));
}

ck('normalizeRegister rejects 1987-02-30 (not a real date)',
   throws(() => eng.normalizeRegister(
     [{ id: 'x', name: 'X', date: '1987-02-30', decreeMilli: 1, valuePerUnit: 1, needMilli: 1 }])));
ck('normalizeRegister rejects duplicate ids',
   throws(() => eng.normalizeRegister([
     { id: 'x', name: 'X', date: '1987-02-01', decreeMilli: 1, valuePerUnit: 1, needMilli: 1 },
     { id: 'x', name: 'Y', date: '1988-02-01', decreeMilli: 1, valuePerUnit: 1, needMilli: 1 }
   ])));
ck('normalizeRegister rejects a negative decree',
   throws(() => eng.normalizeRegister(
     [{ id: 'x', name: 'X', date: '1987-02-01', decreeMilli: -1, valuePerUnit: 1, needMilli: 1 }])));

// ════════════════════════════════════════════════════════════════════════
// SECTION 2. Independent reference implementations, written differently from
// the engine on purpose. These, not the engine, produce the expected values
// the page's displayed numbers are checked against.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[2] independent reference implementations');

function sortBySeniority(reg) {
  return reg.slice().sort((a, b) =>
    a.date < b.date ? -1 : a.date > b.date ? 1 : a.seq - b.seq);
}

// Closed form: alloc_i = clamp(flow - cum_{i-1}, 0, decree_i), with cum the
// prefix sums of decrees in seniority order. No running remainder.
function refPriority(reg, flow) {
  const s = sortBySeniority(reg);
  const cum = [0];
  s.forEach((r, i) => cum.push(cum[i] + r.decreeMilli));
  const byId = new Map();
  s.forEach((r, i) => {
    byId.set(r.id, Math.max(0, Math.min(r.decreeMilli, flow - cum[i])));
  });
  return reg.map(r => ({ id: r.id, allocatedMilli: byId.get(r.id) }));
}

// Characterization check: an allocation equals the lexicographic maximum by
// priority iff, for EVERY seniority prefix k, the prefix delivers exactly
// min(flow, cumulative decree through k), with each right within [0, decree].
// This is a different sufficient-and-necessary condition from the greedy loop.
function refPrefixPropertyOk(reg, alloc, flow) {
  const s = sortBySeniority(reg);
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  let cumD = 0, cumA = 0;
  for (const r of s) {
    const a = byId.get(r.id);
    if (!(a >= 0 && a <= r.decreeMilli)) return false;
    cumD += r.decreeMilli;
    cumA += a;
    if (cumA !== Math.min(flow, cumD)) return false;
  }
  return true;
}

// Proportional reference via BigInt rationals: a different arithmetic path
// from the engine's float-floor-of-exact-integer-quotient.
function refProportional(reg, flow) {
  const s = sortBySeniority(reg);
  const T = s.reduce((acc, r) => acc + r.decreeMilli, 0);
  const byId = new Map(s.map(r => [r.id, 0]));
  if (T === 0) return reg.map(r => ({ id: r.id, allocatedMilli: 0 }));
  const eff = Math.min(flow, T);
  const BT = BigInt(T), BE = BigInt(eff);
  let rem = eff;
  for (const r of s) {
    if (r.decreeMilli === 0) continue;
    const base = Number(BE * BigInt(r.decreeMilli) / BT);
    byId.set(r.id, base);
    rem -= base;
  }
  for (const r of s) {
    if (rem <= 0) break;
    if (r.decreeMilli > 0) { byId.set(r.id, byId.get(r.id) + 1); rem -= 1; }
  }
  return reg.map(r => ({ id: r.id, allocatedMilli: byId.get(r.id) }));
}

// Efficient reference: sort by value descending, seniority tiebreak, greedy.
function refEfficient(reg, flow) {
  const s = reg.slice().sort((a, b) =>
    b.valuePerUnit - a.valuePerUnit ||
    (a.date < b.date ? -1 : a.date > b.date ? 1 : a.seq - b.seq));
  let rem = flow;
  const byId = new Map();
  for (const r of s) {
    const take = Math.min(r.decreeMilli, rem);
    rem -= take;
    byId.set(r.id, take);
  }
  return reg.map(r => ({ id: r.id, allocatedMilli: byId.get(r.id) }));
}

// Exchange-argument optimality: no improving pairwise transfer exists.
function refEfficientOptimalOk(reg, alloc) {
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  for (const i of reg) {
    for (const j of reg) {
      if (i.id === j.id) continue;
      if (byId.get(i.id) > 0 && j.valuePerUnit > i.valuePerUnit &&
          byId.get(j.id) < j.decreeMilli) return false;
    }
  }
  return true;
}

// Bilateral lease reference, structured differently (per-seller inner scan).
// Returns the single first-in-scan maximum; used by refOptimalLeases only to
// establish the top gain independently of the engine.
function refBestLease(reg, alloc, forfeitPercent) {
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  const ceil = (a, b) => Math.floor((a + b - 1) / b);
  let best = null;
  for (const s of reg) {
    const a = byId.get(s.id);
    const reserved = forfeitPercent > 0
      ? Math.min(a, ceil(s.decreeMilli * forfeitPercent, 100)) : 0;
    const sellable = Math.max(0, a - reserved);
    // The per-seller maximum is tracked as a bare NUMBER alongside the trade
    // object. The previous revision compared `gain > localBest.gain`, but the
    // object carries gainMilliDollars, so localBest.gain was undefined, the
    // comparison was always false, and the scanner silently froze on the
    // FIRST positive-gain buyer for each seller. On the page register at 85%
    // forfeiture that froze on Willow Bend -> Highline (+$135.00) and hid the
    // true unique maximum, Willow Bend -> Sun Mesa, 4.000 AF (+$280.00),
    // while the engine was right all along. The reference now computes the
    // same quantity the engine computes; neither side moved.
    let localGain = 0;
    let localBest = null;
    for (const b of reg) {
      if (s.id === b.id) continue;
      if (byId.get(b.id) >= b.decreeMilli) continue;
      const qty = Math.min(sellable, b.decreeMilli);
      const gain = Math.max(0, b.valuePerUnit - s.valuePerUnit) * qty;
      if (gain > localGain) {
        localGain = gain;
        localBest = { sellerId: s.id, buyerId: b.id, qtyMilli: qty, gainMilliDollars: gain };
      }
    }
    if (localBest && (!best || localGain > best.gainMilliDollars)) {
      best = localBest;
    }
  }
  return best || { sellerId: null, buyerId: null, qtyMilli: 0, gainMilliDollars: 0 };
}

// Full argmax-set reference: the top gain comes from the independent scanner
// above, membership is an exhaustive filter over every candidate pair, and
// the ordering is the documented rule (descending quantity, then seller
// seniority, then buyer seniority) with an independently computed ranking.
function refOptimalLeases(reg, alloc, forfeitPercent) {
  const top = refBestLease(reg, alloc, forfeitPercent).gainMilliDollars;
  if (top === 0) return [];
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  const ceil = (a, b) => Math.floor((a + b - 1) / b);
  const rank = new Map();
  sortBySeniority(reg).forEach((r, i) => rank.set(r.id, i));
  const out = [];
  for (const s of reg) {
    const a = byId.get(s.id);
    const reserved = forfeitPercent > 0
      ? Math.min(a, ceil(s.decreeMilli * forfeitPercent, 100)) : 0;
    const sellable = Math.max(0, a - reserved);
    for (const b of reg) {
      if (s.id === b.id) continue;
      if (byId.get(b.id) >= b.decreeMilli) continue;
      const qty = Math.min(sellable, b.decreeMilli);
      const gain = Math.max(0, b.valuePerUnit - s.valuePerUnit) * qty;
      if (gain === top) {
        out.push({ sellerId: s.id, buyerId: b.id, qtyMilli: qty, gainMilliDollars: gain });
      }
    }
  }
  return out.sort((x, y) =>
    y.qtyMilli - x.qtyMilli ||
    rank.get(x.sellerId) - rank.get(y.sellerId) ||
    rank.get(x.buyerId) - rank.get(y.buyerId));
}

// Exhaustive recount of how many candidate pairs achieve the top gain. Used
// to prove a reported tied set is COMPLETE: a sorting bug can hide a missing
// member, a count cannot.
function countTopPairs(reg, alloc, forfeitPercent) {
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  const ceil = (a, b) => Math.floor((a + b - 1) / b);
  const gains = [];
  for (const s of reg) {
    const a = byId.get(s.id);
    const reserved = forfeitPercent > 0
      ? Math.min(a, ceil(s.decreeMilli * forfeitPercent, 100)) : 0;
    const sellable = Math.max(0, a - reserved);
    for (const b of reg) {
      if (s.id === b.id) continue;
      if (byId.get(b.id) >= b.decreeMilli) continue;
      const qty = Math.min(sellable, b.decreeMilli);
      const gain = Math.max(0, b.valuePerUnit - s.valuePerUnit) * qty;
      if (gain > 0) gains.push(gain);
    }
  }
  if (gains.length === 0) return 0;
  const top = Math.max.apply(null, gains);
  return gains.filter(g => g === top).length;
}

// Forfeiture reference, direct formulas.
function refForfeiture(reg, alloc, f) {
  const byId = new Map(alloc.map(a => [a.id, a.allocatedMilli]));
  const ceil = (a, b) => Math.floor((a + b - 1) / b);
  return reg.map(r => {
    const a = byId.get(r.id);
    const target = Math.max(r.needMilli, ceil(r.decreeMilli * f, 100));
    const diverted = Math.min(a, target);
    return { id: r.id, divertedMilli: diverted, wastedMilli: Math.max(0, diverted - r.needMilli) };
  });
}

// ════════════════════════════════════════════════════════════════════════
// SECTION 3. The independent anchor: a swept set of registers and flows on
// which the engine's greedy walk, the closed-form lexicographic maximum, the
// prefix characterization, and exact conservation must ALL agree.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[3] anchor sweep: greedy walk vs closed-form lexicographic maximum');

// Deterministic LCG so the sweep is reproducible run to run.
let seed = 42;
function rnd() {
  seed = (seed * 1103515245 + 12345) % 2147483648;
  return seed / 2147483648;
}
function randDate() {
  const y = 1850 + Math.floor(rnd() * 170);
  const mo = 1 + Math.floor(rnd() * 12);
  const da = 1 + Math.floor(rnd() * 28);
  return y + '-' + String(mo).padStart(2, '0') + '-' + String(da).padStart(2, '0');
}
function randRegister(n) {
  const reg = [];
  for (let i = 0; i < n; i++) {
    const d = Math.floor(rnd() * 40000);
    reg.push({
      id: 'r' + i, name: 'R' + i, date: randDate(),
      decreeMilli: d, valuePerUnit: Math.floor(rnd() * 200),
      needMilli: Math.floor(rnd() * (d + 1))
    });
  }
  // shuffle input order so order-independence is exercised every trial
  for (let i = reg.length - 1; i > 0; i--) {
    const j = Math.floor(rnd() * (i + 1));
    [reg[i], reg[j]] = [reg[j], reg[i]];
  }
  return reg;
}

let prioCases = 0, prioBad = 0, propCases = 0, propBad = 0;
let effCases = 0, effBad = 0, leaseCases = 0, leaseBad = 0, forfeitCases = 0, forfeitBad = 0;

for (let trial = 0; trial < 200; trial++) {
  const reg = randRegister(1 + Math.floor(rnd() * 6));
  const norm = eng.normalizeRegister(reg);
  const demand = norm.reduce((s, r) => s + r.decreeMilli, 0);
  const flows = [0, 1, demand, demand + 1,
    Math.floor(rnd() * (demand + 2)), Math.floor(rnd() * (demand + 2))];
  for (const flow of flows) {
    // priority: engine vs closed form vs prefix characterization vs conservation
    const ea = eng.allocateByPriority(reg, flow);
    const ra = refPriority(norm, flow);
    prioCases++;
    if (!jsonEq(ea, ra) || !refPrefixPropertyOk(norm, ea, flow) ||
        ea.reduce((s, a) => s + a.allocatedMilli, 0) !== Math.min(flow, demand)) {
      prioBad++;
    }
    // proportional: engine vs BigInt reference vs conservation
    const ep = eng.allocateProportional(reg, flow);
    const rp = refProportional(norm, flow);
    propCases++;
    if (!jsonEq(ep, rp) ||
        ep.reduce((s, a) => s + a.allocatedMilli, 0) !== Math.min(flow, demand)) {
      propBad++;
    }
    // efficient: engine vs reference vs exchange-argument optimality
    const ee = eng.efficientAllocation(reg, flow);
    const re = refEfficient(norm, flow);
    effCases++;
    if (!jsonEq(ee, re) || !refEfficientOptimalOk(norm, ee)) effBad++;
    // lease: ONE forfeit percent per case, fed to both sides. The engine's
    // full argmax set must equal the independent reference set, and the
    // scalar top gain must agree with it (0 exactly when the set is empty).
    const fL = Math.floor(rnd() * 101);
    const eb = eng.bestBilateralTrade(reg, ee, { forfeitPercent: fL });
    const eo = refOptimalLeases(norm, ee, fL);
    leaseCases++;
    if (!jsonEq(eb.trades, eo) ||
        eb.topGainMilliDollars !== (eo.length ? eo[0].gainMilliDollars : 0)) {
      leaseBad++;
    }
    // forfeiture: engine vs reference plus invariant wasted = max(0, diverted - need)
    const f = Math.floor(rnd() * 101);
    const ef = eng.forfeitureDiversion(reg, ee, f);
    const rf = refForfeiture(norm, ee, f);
    forfeitCases++;
    if (!jsonEq(ef, rf) ||
        ef.some(x => x.wastedMilli !== Math.max(0, x.divertedMilli -
          norm.find(r => r.id === x.id).needMilli))) {
      forfeitBad++;
    }
  }
}
ck('priority sweep: engine == closed form == prefix property == conservation (' +
   prioCases + ' cases)', prioBad === 0, prioBad + ' bad');
ck('proportional sweep: engine == BigInt reference == conservation (' +
   propCases + ' cases)', propBad === 0, propBad + ' bad');
ck('efficient sweep: engine == reference == exchange-optimal (' +
   effCases + ' cases)', effBad === 0, effBad + ' bad');
ck('lease sweep: engine argmax set == independent reference, top gain consistent (' +
   leaseCases + ' cases)', leaseBad === 0, leaseBad + ' bad');
ck('forfeiture sweep: engine == reference, waste invariant holds (' +
   forfeitCases + ' cases)', forfeitBad === 0, forfeitBad + ' bad');

// ════════════════════════════════════════════════════════════════════════
// SECTION 4. Every number the page displays, recomputed here from the
// REFERENCE implementations (not the engine), then cross-checked against the
// engine. The register literal is duplicated from the page on purpose: if the
// page and this file drift apart, these checks fail loudly.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[4] page-displayed numbers, recomputed independently');

const PAGE_REG = [
  { id: 'willow',    name: 'Willow Bend Ditch',       date: '1868-05-01', decreeMilli: 30000, valuePerUnit: 80,  needMilli: 24000 },
  { id: 'highline',  name: 'Highline Canal',          date: '1874-04-12', decreeMilli: 25000, valuePerUnit: 110, needMilli: 18000 },
  { id: 'miller',    name: 'Miller and Sons Ditch',   date: '1889-03-03', decreeMilli: 18000, valuePerUnit: 65,  needMilli: 14000 },
  { id: 'cedar',     name: 'Cedar Gulch Orchard Co.', date: '1902-06-20', decreeMilli: 15000, valuePerUnit: 130, needMilli: 9000  },
  { id: 'riverside', name: 'Riverside Acres Mutual',  date: '1958-07-15', decreeMilli: 8000,  valuePerUnit: 45,  needMilli: 6000  },
  { id: 'sunmesa',   name: 'Sun Mesa Greenhouses',    date: '1987-09-09', decreeMilli: 4000,  valuePerUnit: 150, needMilli: 2500  }
];
const PRIO = eng.normalizeRegister(PAGE_REG);
const AGG = PRIO.reduce((s, r) => s + r.decreeMilli, 0);
ck('page register aggregate decree is 100000 milli-AF (100.000 AF)', AGG === 100000, AGG);

const F40 = 40000; // the page's default: 40% of aggregate decree

// Reference-computed expectations (closed form, not the engine):
const ref40 = refPriority(PRIO, F40);
const byId40 = new Map(ref40.map(a => [a.id, a.allocatedMilli]));
ck('at 40%: senior-most (Willow Bend, 1868) keeps its FULL decree of 30.000 AF',
   byId40.get('willow') === 30000, byId40.get('willow'));
ck('at 40%: second (Highline, 1874) gets the residual 10.000 AF, partially cut',
   byId40.get('highline') === 10000, byId40.get('highline'));
ck('at 40%: most junior (Sun Mesa, 1987) gets exactly 0',
   byId40.get('sunmesa') === 0, byId40.get('sunmesa'));
ck('at 40%: rights short of decree = 5 of 6 (only Willow Bend is whole)',
   ref40.filter(a => a.allocatedMilli <
     PRIO.find(r => r.id === a.id).decreeMilli).length === 5);

const refProp40 = refProportional(PRIO, F40);
const propExpect = { willow: 12000, highline: 10000, miller: 7200,
                     cedar: 6000, riverside: 3200, sunmesa: 1600 };
ck('at 40%: proportional gives every right exactly 40% of its decree',
   refProp40.every(a => a.allocatedMilli === propExpect[a.id]), refProp40);
ck('at 40%: proportional conserves the same 40.000 AF',
   refProp40.reduce((s, a) => s + a.allocatedMilli, 0) === 40000);

const valPrio = ref40.reduce((s, a) =>
  s + a.allocatedMilli * PRIO.find(r => r.id === a.id).valuePerUnit, 0);
const valProp = refProp40.reduce((s, a) =>
  s + a.allocatedMilli * PRIO.find(r => r.id === a.id).valuePerUnit, 0);
ck('at 40%: seniority delivers $3,500.00 of model crop value', valPrio === 3500000, valPrio);
ck('at 40%: proportional delivers $3,692.00, MORE than seniority on this register',
   valProp === 3692000 && valProp > valPrio, { valPrio, valProp });

// Leases at 40%, no forfeiture. The top gain is a genuine TIE: two different
// leases both yield +$750.00. The page therefore reports the whole set and
// never names one member as "the best"; the old single-lease expectation
// (Willow Bend -> Cedar Gulch) was one arbitrary member of this tie and was
// the defect. Both members are asserted, in the documented order.
const set0 = refOptimalLeases(PRIO, ref40, 0);
ck('at 40%, no forfeiture: the top gain +$750.00 is a TIE between EXACTLY two leases',
   set0.length === 2 && set0.every(t => t.gainMilliDollars === 750000), set0);
ck('at 40%, no forfeiture: the tied pair is Willow Bend -> Highline 25.000 AF, ' +
   'then Willow Bend -> Cedar Gulch 15.000 AF (most water moved first)',
   jsonEq(set0.map(t => [t.sellerId, t.buyerId, t.qtyMilli]),
          [['willow', 'highline', 25000], ['willow', 'cedar', 15000]]), set0);
ck('at 40%, no forfeiture: engine returns the same full tied set, not one member',
   jsonEq(eng.bestBilateralTrade(PAGE_REG, ref40).trades, set0) &&
   eng.bestBilateralTrade(PAGE_REG, ref40).topGainMilliDollars === 750000,
   eng.bestBilateralTrade(PAGE_REG, ref40));

// Forfeiture at 85%: reservations, waste, and the shrinking market. Here the
// top gain is UNIQUE, so the set has exactly one member. Hand-worked: only
// Willow Bend holds sellable water (30000 allocated, 25500 reserved, so
// 4500 sellable; everyone else is allocated at or below their reserve).
// Candidate gains: ->Highline 30 x 4500 = 135000; ->Cedar 50 x 4500 = 225000;
// ->Sun Mesa 70 x min(4500, 4000 decree) = 280000. Unique max 280000.
// (Under either reading of the quantity cap, full decree or buyer shortfall,
// Sun Mesa's pair is 4000 AF at 280000, so the expectation is cap-independent.)
const ff85 = refForfeiture(PRIO, ref40, 85);
const waste85 = ff85.reduce((s, x) => s + x.wastedMilli, 0);
ck('at 40%, forfeiture 85%: Willow Bend diverts 25.500 AF, wasting 1.500 AF past need',
   ff85.find(x => x.id === 'willow').divertedMilli === 25500 &&
   ff85.find(x => x.id === 'willow').wastedMilli === 1500, ff85[0]);
ck('at 40%, forfeiture 85%: system-wide paper-water waste is exactly 1.500 AF',
   waste85 === 1500, waste85);
const set85 = refOptimalLeases(PRIO, ref40, 85);
ck('at 40%, forfeiture 85%: top gain +$280.00 is UNIQUE: Willow Bend -> Sun Mesa, 4.000 AF',
   set85.length === 1 && set85[0].sellerId === 'willow' && set85[0].buyerId === 'sunmesa' &&
   set85[0].qtyMilli === 4000 && set85[0].gainMilliDollars === 280000, set85);
const set100 = refOptimalLeases(PRIO, ref40, 100);
ck('at 40%, forfeiture 100%: no profitable lease exists (empty set, top gain 0)',
   set100.length === 0 &&
   eng.bestBilateralTrade(PAGE_REG, ref40, { forfeitPercent: 100 }).topGainMilliDollars === 0,
   set100);

// Full supply: everyone whole, no lease, no waste without the rule. WITH the
// rule at 85%, paper-water waste appears even with no shortage. Hand-worked,
// right by right (target = max(need, ceil(0.85 x decree)); everyone is
// allocated their full decree, so waste = target - need):
//   willow     25500 - 24000 =  1500
//   highline   21250 - 18000 =  3250
//   miller     15300 - 14000 =  1300
//   cedar      12750 -  9000 =  3750
//   riverside   6800 -  6000 =   800
//   sunmesa     3400 -  2500 =   900
//   total                     = 11500
// An earlier revision asserted 13500 here. That literal matches no reading of
// the model on the current register; it predated the register's present needs
// and was simply a stale constant, not a disagreement between two routes.
// The substantive claim (strictly positive waste at full supply under the
// rule) is kept, and the exact hand-worked total is pinned beside it.
const wasteFull85 =
  refForfeiture(PRIO, refFullSafe(), 85).reduce((s, x) => s + x.wastedMilli, 0);
ck('at 100% flow, forfeiture 85%: paper-water waste appears even with no shortage',
   wasteFull85 > 0, wasteFull85);
ck('at 100% flow, forfeiture 85%: system-wide waste is exactly 11.500 AF (hand-worked)',
   wasteFull85 === 11500, wasteFull85);

// Cross-check: the engine must agree with every reference expectation above.
ck('engine agrees with references on all page-displayed numbers',
   jsonEq(eng.allocateByPriority(PAGE_REG, F40), ref40) &&
   jsonEq(eng.allocateProportional(PAGE_REG, F40), refProp40) &&
   jsonEq(eng.bestBilateralTrade(PAGE_REG, ref40).trades, set0) &&
   jsonEq(eng.bestBilateralTrade(PAGE_REG, ref40, { forfeitPercent: 85 }).trades, set85) &&
   jsonEq(eng.bestBilateralTrade(PAGE_REG, ref40, { forfeitPercent: 100 }).trades, set100) &&
   jsonEq(eng.forfeitureDiversion(PAGE_REG, ref40, 85), ff85));

// refFull is defined after first use above via a tiny indirection so the
// hand-worked block reads next to the other full-supply claims; this helper
// just recomputes the closed-form full-supply allocation.
function refFullSafe() {
  return refPriority(PRIO, AGG);
}

// ════════════════════════════════════════════════════════════════════════
// SECTION 4b. Tie-handling, pinned so it cannot decay silently. The page
// must never present one member of a tie as the unique best: the engine
// returns the whole argmax set in a documented order (descending quantity,
// then seller seniority, then buyer seniority), and these checks hold that
// order against hand-worked literals and an exhaustive recount.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[4b] tie-handling: the whole argmax set, in a pinned order');

// Case A: FOUR leases tie at +$700.00 across two distinct quantities, so the
// check exercises the quantity ordering AND the seller-seniority ordering.
{
  const tieRegA = [
    { id: 's1', name: 'S1', date: '1950-01-01', decreeMilli: 10000, valuePerUnit: 0,   needMilli: 0 },
    { id: 's2', name: 'S2', date: '1960-01-01', decreeMilli: 10000, valuePerUnit: 0,   needMilli: 0 },
    { id: 'b1', name: 'B1', date: '1970-01-01', decreeMilli: 5000,  valuePerUnit: 140, needMilli: 0 },
    { id: 'b2', name: 'B2', date: '1980-01-01', decreeMilli: 10000, valuePerUnit: 70,  needMilli: 0 }
  ];
  const tieAllocA = [
    { id: 's1', allocatedMilli: 10000 }, { id: 's2', allocatedMilli: 10000 },
    { id: 'b1', allocatedMilli: 0 }, { id: 'b2', allocatedMilli: 0 }
  ];
  const expectA = [
    { sellerId: 's1', buyerId: 'b2', qtyMilli: 10000, gainMilliDollars: 700000 },
    { sellerId: 's2', buyerId: 'b2', qtyMilli: 10000, gainMilliDollars: 700000 },
    { sellerId: 's1', buyerId: 'b1', qtyMilli: 5000,  gainMilliDollars: 700000 },
    { sellerId: 's2', buyerId: 'b1', qtyMilli: 5000,  gainMilliDollars: 700000 }
  ];
  const gotA = eng.bestBilateralTrade(tieRegA, tieAllocA);
  ck('tie case A: all four tied leases come back, in the documented order',
     jsonEq(gotA.trades, expectA), gotA);
  ck('tie case A: engine set matches the independent reference set',
     jsonEq(gotA.trades, refOptimalLeases(tieRegA, tieAllocA, 0)));
  ck('tie case A: reported set is COMPLETE (exhaustive recount of top-gain pairs)',
     gotA.trades.length === countTopPairs(tieRegA, tieAllocA, 0));
  ck('tie case A: deterministic across two calls',
     jsonEq(gotA, eng.bestBilateralTrade(tieRegA, tieAllocA)));
}

// Case B: equal quantities, so buyer seniority alone must order the tie.
{
  const tieRegB = [
    { id: 'old', name: 'Old', date: '1900-01-01', decreeMilli: 8000, valuePerUnit: 0,   needMilli: 0 },
    { id: 'y1',  name: 'Y1',  date: '1970-01-01', decreeMilli: 4000, valuePerUnit: 100, needMilli: 0 },
    { id: 'y2',  name: 'Y2',  date: '1980-01-01', decreeMilli: 4000, valuePerUnit: 100, needMilli: 0 }
  ];
  const tieAllocB = [
    { id: 'old', allocatedMilli: 8000 },
    { id: 'y1',  allocatedMilli: 0 },
    { id: 'y2',  allocatedMilli: 0 }
  ];
  const expectB = [
    { sellerId: 'old', buyerId: 'y1', qtyMilli: 4000, gainMilliDollars: 400000 },
    { sellerId: 'old', buyerId: 'y2', qtyMilli: 4000, gainMilliDollars: 400000 }
  ];
  const gotB = eng.bestBilateralTrade(tieRegB, tieAllocB);
  ck('tie case B: equal quantities order by buyer seniority, exactly',
     jsonEq(gotB.trades, expectB), gotB);
  ck('tie case B: engine set matches the independent reference set',
     jsonEq(gotB.trades, refOptimalLeases(tieRegB, tieAllocB, 0)));
  ck('tie case B: reported set is COMPLETE',
     gotB.trades.length === countTopPairs(tieRegB, tieAllocB, 0));
}

// The page's own register at the default flow is itself a tie case; the
// completeness of its reported pair is asserted against a recount here too.
ck('page register at 40%: the reported tied pair is COMPLETE',
   eng.bestBilateralTrade(PAGE_REG, ref40).trades.length ===
   countTopPairs(PAGE_REG, ref40, 0));

// ════════════════════════════════════════════════════════════════════════
// SECTION 5. Battery replay: every exported function is exercised by
// battery.json, runs clean (or throws exactly where the battery says it must),
// and is deterministic across two runs.
// ════════════════════════════════════════════════════════════════════════
console.log('\n[5] battery replay');

const battery = JSON.parse(await readFile(BATTERY_PATH, 'utf8'));
const exportNames = Object.keys(eng).filter(k => typeof eng[k] === 'function');
const covered = new Set(battery.calls.map(c => c.fn));
ck('battery covers every exported function of engine.mjs',
   exportNames.every(fn => covered.has(fn)),
   exportNames.filter(fn => !covered.has(fn)));

let batteryBad = 0, batteryRuns = 0;
const runBattery = () => battery.calls.map(c => {
  batteryRuns++;
  if (c.throws) {
    let threw = false;
    try { eng[c.fn](...c.args); } catch { threw = true; }
    if (!threw) batteryBad++;
    return 'threw';
  }
  const out = eng[c.fn](...c.args);
  return JSON.stringify(out);
});
const run1 = runBattery();
const run2 = runBattery();
ck('battery: ' + battery.calls.length + ' calls behave as annotated (incl. ' +
   battery.calls.filter(c => c.throws).length + ' expected throws)',
   batteryBad === 0, batteryBad + ' bad');
ck('battery: engine is deterministic across two full replays', jsonEq(run1, run2));

// ════════════════════════════════════════════════════════════════════════
// SECTION 6. --mutate: corrupt a COPY of the engine, confirm the corruption
// landed byte-for-byte, confirm the checks then FAIL, and leave nothing behind.
// ════════════════════════════════════════════════════════════════════════
if (process.argv.includes('--mutate')) {
  console.log('\n[6] --mutate: corrupting a copy of engine.mjs');
  const original = await readFile(ENGINE_PATH, 'utf8');
  const origHash = createHash('sha256').update(original).digest('hex');
  if (!original.includes('Math.min')) {
    console.log('FAIL  mutation target "Math.min" not found in engine source');
    FAILURES++; CHECKS++;
  } else {
    const mutated = original.split('Math.min').join('Math.max');
    ck('mutation changed the bytes', mutated !== original);
    const tmpPath = ENGINE_PATH + '.mutated-tmp.mjs';
    try {
      await writeFile(tmpPath, mutated, 'utf8');
      const bad = await import(pathToFileURL(tmpPath).href + '?mutate=' + Date.now());
      // A conservation-and-bounds probe the mutated engine must fail.
      const reg = [
        { id: 'a', name: 'A', date: '1900-01-01', decreeMilli: 5000, valuePerUnit: 10, needMilli: 5000 },
        { id: 'b', name: 'B', date: '1901-01-01', decreeMilli: 3000, valuePerUnit: 20, needMilli: 3000 }
      ];
      let survived = false;
      try {
        const out = bad.allocateByPriority(reg, 6000);
        const sum = out.reduce((s, a) => s + a.allocatedMilli, 0);
        const within = out.every(a =>
          a.allocatedMilli <= reg.find(r => r.id === a.id).decreeMilli);
        survived = (sum === 6000 && within);
      } catch { survived = false; }
      ck('corrupted engine FAILS the conservation/bounds probe (checks can fail)',
         !survived);
      if (survived) {
        console.log('FAIL  mutated engine still passes: the mutation did not land where intended');
        FAILURES++; CHECKS++;
      }
    } finally {
      await rm(tmpPath, { force: true });
      const after = await readFile(ENGINE_PATH, 'utf8');
      ck('original engine.mjs restored byte-for-byte',
         createHash('sha256').update(after).digest('hex') === origHash);
    }
  }
}

// ── verdict ───────────────────────────────────────────────────────────────
console.log('');
console.log('verify-first-in-time-dried-up-in-order: ' + CHECKS + ' checks, ' +
            FAILURES + ' failures');
if (CHECKS === 0) {
  console.log('ZERO CHECKS PERFORMED: this run proves nothing, exiting non-zero.');
  process.exit(1);
}
process.exit(FAILURES > 0 ? 1 : 0);
