#!/usr/bin/env node
/* THE LOOM OF THE SINGER — offline verifier
 *
 * The claim, in one sentence: Homer's verse is built from prefabricated,
 * metrically-shaped word-groups (Milman Parry's "formulae"), and a bard
 * assembled a hexameter line in performance by slotting them together — a
 * generative technology you can operate. This verifier checks every factual
 * thing the page shows, from one public-domain source, with the check in view.
 *
 * FOUR checks:
 *
 *   A · VERBATIM — every Greek word-group and every full line the page shows
 *       is re-extracted from the Monro-Allen Oxford Iliad (Perseus DL XML,
 *       edition perseus-grc2) and compared to that text. The SHA-256 of the
 *       XML is asserted so a future reader sees the same bytes.
 *
 *   B · SCANSION — every full line the page shows is scanned by a conservative
 *       textbook hexameter scanner (ported from research/the-sixth-letter,
 *       the project's vetted scanner) and must fit the dactylic-hexameter
 *       pattern. Rules applied, each standard and named in comments:
 *         · long by nature: η ω, the diphthongs, and α ι υ under a
 *           circumflex (a circumflex stands only on a long vowel);
 *         · long by position: a short vowel before 2+ consonants (ζ ξ ψ = 2);
 *         · muta cum liquida (stop + ρ/λ): ambiguous;
 *         · epic correption: a word-final long vowel/diphthong before a vowel
 *           may shorten;
 *         · a tiny, explicitly-sourced lexical-quantity table (θεά's epic
 *           long final ᾱ, from Cunliffe s.v. θεά and LSJ, the metre requires it;
 *           the long ῡ of χρῡσόθρονος, from χρῡσός, Wiktionary and LSJ).
 *       The scanner is deliberately conservative; where a line needs a rule
 *       above, that is reported, not hidden.
 *
 *   C · ATTESTATION — the "loom" lets a reader combine a first-hemistich brick
 *       with a line-final name-brick. For every combination the page marks as
 *       ATTESTED, we assert the exact word-sequence occurs at the cited line
 *       of Iliad Book 1. Combinations the page marks "system-valid (not in our
 *       text)" are never claimed to be lines of Homer — only well-formed
 *       hexameters the formula-system licenses (check B confirms they scan).
 *
 *   D · ECONOMY (computed, not asserted) — Parry's "thrift": for a character
 *       in a given metrical slot, the poet keeps essentially ONE formula. We
 *       scan all 611 lines of Book 1, collect every line-final nominative
 *       noun-epithet naming of the seven principal figures, group by the
 *       metrical length of the naming, and print the tally. The page reports
 *       the same numbers.
 *
 * Source: Perseus Digital Library, urn:cts:greekLit:tlg0012.tlg001.perseus-grc2
 *   (Monro-Allen Oxford Classical Text, 1902). Public domain.
 *
 * Run: node research/loom-of-the-singer/verify.mjs
 */

import { readFileSync, existsSync } from "node:fs";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import path from "node:path";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const XML_PATH = path.join(__dirname, "iliad-monro-allen.xml");
if (!existsSync(XML_PATH)) {
  console.error("Missing Perseus Iliad XML at", XML_PATH);
  console.error("Download: curl -sL https://raw.githubusercontent.com/PerseusDL/canonical-greekLit/master/data/tlg0012/tlg001/tlg0012.tlg001.perseus-grc2.xml -o", XML_PATH);
  process.exit(2);
}
const xml = readFileSync(XML_PATH, "utf8");
const xmlSha = createHash("sha256").update(xml).digest("hex");

let passed = 0, failed = 0;
function check(label, ok, detail = "") {
  if (ok) { passed++; console.log(`  ✓ ${label}`); }
  else { failed++; console.log(`  ✗ ${label}${detail}`); }
}

// --- extract Book 1 verbatim (same routine as the-sixth-letter) ---
function extractBook(xml, book) {
  const re = new RegExp(`<div type="textpart" subtype="Book" n="${book}">([\\s\\S]*?)</div>\\s*(?=<div|</body)`, "m");
  const m = xml.match(re);
  if (!m) throw new Error(`Book ${book} not found`);
  const body = m[1];
  const lines = {};
  const lre = /<l n="(\d+)">([\s\S]*?)<\/l>/g;
  let lm;
  while ((lm = lre.exec(body))) {
    const text = lm[2].replace(/<milestone[^>]*\/>/g, "").replace(/<[^>]+>/g, "").trim();
    lines[lm[1]] = text;
  }
  return lines;
}
const book1 = extractBook(xml, 1);
const norm = s => (s || "").normalize("NFC").replace(/[ʼ’']/g, "ʼ").replace(/\s+/g, " ").trim();
// editorial punctuation (·,;:.) is a modern editor's addition, not part of the
// word — strip it from token ENDS for word-level comparison. The verbatim text
// itself is never altered; this only governs whether two word-runs are "the
// same words".
const depunct = w => w.replace(/[·,;:.·;]+$/u, "");
const wordsOf = n => norm(book1[String(n)]).split(" ").map(depunct);

console.log("THE LOOM OF THE SINGER — verifier\n");
console.log(`  Perseus Iliad XML SHA-256: ${xmlSha}`);
console.log(`  Book 1: ${Object.keys(book1).length} lines extracted\n`);

// ===========================================================================
//  THE DATA — every brick, its home line, and the lines the loom can build.
//  Greek is taken from the Perseus text (checked in A); translit + gloss are
//  editorial and marked as such on the page.
// ===========================================================================

// First-hemistich "speech-introduction" bricks: they run from line-start to
// the caesura and hand off to a line-final name. (home = a line where the
// brick + a name make the whole verse.)
const HEMISTICHS = [
  { id: "apameib_m", greek: "τὸν δʼ ἀπαμειβόμενος προσέφη", tr: "ton d' apameibomenos prosephē", gloss: "Then in answer addressed him", home: 84 },
  { id: "apameib_f", greek: "τὴν δʼ ἀπαμειβόμενος προσέφη", tr: "tēn d' apameibomenos prosephē", gloss: "Then in answer addressed her", home: 215 },
  { id: "hypodra",   greek: "τὸν δʼ ἄρʼ ὑπόδρα ἰδὼν προσέφη", tr: "ton d' ar' hypodra idōn prosephē", gloss: "Then with a dark look addressed him", home: 148 },
  { id: "stenachon", greek: "τὴν δὲ βαρὺ στενάχων προσέφη", tr: "tēn de baru stenachōn prosephē", gloss: "Then heavily groaning addressed her", home: 364 },
  { id: "aute",      greek: "τὸν δʼ αὖτε προσέειπε θεὰ", tr: "ton d' aute proseeipe thea", gloss: "Then in turn the goddess addressed him", home: 206 },
];

// Line-final name bricks (nominative noun-epithet formulae): they fill the
// verse-end from a caesura. length = syllable count (for the slot they fill).
const NAMES = [
  { id: "achilleus", greek: "πόδας ὠκὺς Ἀχιλλεύς", tr: "podas ōkus Achilleus", gloss: "swift-footed Achilles", who: "Achilles" },
  { id: "agam_short", greek: "κρείων Ἀγαμέμνων", tr: "kreiōn Agamemnōn", gloss: "lord Agamemnon", who: "Agamemnon" },
  { id: "agam_long", greek: "ἄναξ ἀνδρῶν Ἀγαμέμνων", tr: "anax andrōn Agamemnōn", gloss: "Agamemnon, lord of men", who: "Agamemnon" },
  { id: "zeus", greek: "νεφεληγερέτα Ζεύς", tr: "nephelēgereta Zeus", gloss: "cloud-gathering Zeus", who: "Zeus" },
  { id: "athene", greek: "γλαυκῶπις Ἀθήνη", tr: "glaukōpis Athēnē", gloss: "grey-eyed Athena", who: "Athena" },
  { id: "here", greek: "λευκώλενος Ἥρη", tr: "leukōlenos Hērē", gloss: "white-armed Hera", who: "Hera" },
  { id: "apollon", greek: "Φοῖβος Ἀπόλλων", tr: "Phoibos Apollōn", gloss: "Phoebus Apollo", who: "Apollo" },
  { id: "odysseus", greek: "πολύμητις Ὀδυσσεύς", tr: "polymētis Odysseus", gloss: "Odysseus of many wiles", who: "Odysseus" },
];

// The lines the page shows whole (openings + the loom's attested rows).
// combo: [hemistichId, nameId] when the line is exactly brick+brick.
const LINES = [
  { n: 1, note: "the opening — introduces the hexameter template (synizesis of -εω noted)", auto: false },
  { n: 84, combo: ["apameib_m", "achilleus"] },
  { n: 215, combo: ["apameib_f", "achilleus"] },
  { n: 148, combo: ["hypodra", "achilleus"] },
  { n: 364, combo: ["stenachon", "achilleus"] },
  { n: 130, combo: ["apameib_m", "agam_short"] },
  { n: 285, combo: ["apameib_m", "agam_short"] },
  { n: 560, combo: ["apameib_f", "zeus"] },
  { n: 206, combo: ["aute", "athene"] },
  { n: 172, note: "Agamemnon's LONGER formula — extension", auto: true },   // τὸν δʼ ἠμείβετʼ ἔπειτα ἄναξ ἀνδρῶν Ἀγαμέμνων
  { n: 55,  note: "Hera named — needs θεά's long ᾱ", auto: true },          // ... θεὰ λευκώλενος Ἥρη
  { n: 311, note: "Odysseus named at line-end", auto: true },
  { n: 43,  note: "Apollo named at line-end", auto: true },
];

// ===========================================================================
//  A — VERBATIM
// ===========================================================================
console.log("[A] VERBATIM — every brick and line matches the Perseus text\n");

// each name/hemistich brick must be a contiguous word-run of its home/any line
function isContiguousSubsequence(brickWords, lineWords) {
  for (let i = 0; i + brickWords.length <= lineWords.length; i++) {
    let ok = true;
    for (let j = 0; j < brickWords.length; j++) if (lineWords[i + j] !== brickWords[j]) { ok = false; break; }
    if (ok) return i;
  }
  return -1;
}
for (const h of HEMISTICHS) {
  const bw = norm(h.greek).split(" ");
  const lw = wordsOf(h.home);
  check(`hemistich "${h.tr}" opens Il. 1.${h.home} verbatim`, isContiguousSubsequence(bw, lw) === 0,
    `\n      line ${h.home}: ${book1[String(h.home)]}`);
}
for (const nm of NAMES) {
  // the name-brick must end some Book-1 line verbatim
  const bw = norm(nm.greek).split(" ");
  let foundAt = null;
  for (const n of Object.keys(book1)) {
    const lw = wordsOf(Number(n));
    const idx = isContiguousSubsequence(bw, lw);
    if (idx >= 0 && idx + bw.length === lw.length) { foundAt = n; break; }
  }
  check(`name "${nm.tr}" ends a Book-1 line verbatim (first: 1.${foundAt})`, foundAt !== null);
}
for (const L of LINES) {
  check(`Il. 1.${L.n} present in Perseus`, book1[String(L.n)] !== undefined);
}

// ===========================================================================
//  THE SCANNER  (ported from research/the-sixth-letter/verify.mjs, extended)
// ===========================================================================
function deaccent(s) { return s.normalize("NFD").replace(/[̀-ͅ]/g, "").normalize("NFC"); }
const LV = new Set(["η", "ω"]);
const SV = new Set(["α", "ε", "ι", "ο", "υ"]);
const DIPH = ["ηυ", "ευ", "αυ", "ου", "αι", "ει", "οι", "υι", "ηι", "ωι"];
// tiny, sourced lexical-quantity table: (deaccented word) -> {sylIndex: "L"|"S"}
// θεά (epic nom.) has a long final ᾱ — Cunliffe s.v. θεά; LSJ; the metre requires it.
// χρυσόθρονος has a long ῡ (χρῡσόθρονος, from χρῡσός: Wiktionary; LSJ). Added 2026-10-18 (assay line).
const LEXQ = { "θεα": { 1: "L" }, "χρυσοθρονος": { 0: "L" } };
// A circumflex stands only on a long vowel, so α ι υ carrying one are long by
// nature (δῖος). Mark those positions before the accents are stripped.
// Added 2026-10-18 (assay line); before, δῖος scanned with a short ι.
const CIRC_MARK = "\uE000";
function circumflexLongMask(raw) {
  const nfd = raw.normalize("NFD").replace(/([αιυΑΙΥ])([\u0300-\u0345]*\u0342[\u0300-\u0345]*)/g, CIRC_MARK);
  return deaccent(nfd).replace(/[·,;:.]/g, "");
}

function syllabify(rawline, { correption = true } = {}) {
  const clean = deaccent(rawline.normalize("NFC").replace(/[’'ʼ]/g, "ʼ")).replace(/[·,;:.]/g, "").toLowerCase();
  const circ = circumflexLongMask(rawline.normalize("NFC").replace(/[’'ʼ]/g, "ʼ"));
  if (circ.length !== clean.length) throw new Error("circumflex mask misaligned: " + rawline);
  // build char->word index map (word = maximal run of non-space, sans elision mark)
  let wi = -1, prevSpace = true;
  const wordAt = [];
  const words = [];
  for (let k = 0; k < clean.length; k++) {
    const ch = clean[k];
    if (ch === " ") { prevSpace = true; wordAt.push(-1); continue; }
    if (prevSpace) { wi++; words.push(""); prevSpace = false; }
    if (ch !== "ʼ" && ch !== "'") words[wi] += ch;
    wordAt.push(wi);
  }
  const sylls = [];
  let i = 0;
  while (i < clean.length) {
    const c = clean[i];
    if (c === " " || c === "ʼ" || c === "'") { i++; continue; }
    let vlen = 0, isLongNature = false;
    for (const dp of DIPH) if (clean.substr(i, 2) === dp) { vlen = 2; isLongNature = true; break; }
    if (!vlen) { if (LV.has(c)) { vlen = 1; isLongNature = true; } else if (SV.has(c)) { vlen = 1; isLongNature = circ[i] === CIRC_MARK; } }
    if (!vlen) { i++; continue; }
    const wIdx = wordAt[i];
    i += vlen;
    let cons = "", sawSpace = false;
    while (i < clean.length) {
      const d = clean[i];
      if (d === " ") { sawSpace = true; i++; continue; }
      if (d === "ʼ" || d === "'") { i++; continue; }
      let isV = LV.has(d) || SV.has(d);
      if (!isV) for (const dp of DIPH) if (clean.substr(i, 2) === dp) { isV = true; break; }
      if (isV) break;
      cons += d; i++;
    }
    sylls.push({ isLongNature, cons, wIdx, wordFinalBeforeVowel: (cons === "" && sawSpace) });
  }
  // per-word syllable index
  const seen = {};
  for (const s of sylls) { seen[s.wIdx] = (seen[s.wIdx] ?? -1) + 1; s.sylInWord = seen[s.wIdx]; s.word = words[s.wIdx]; }
  for (const s of sylls) {
    let cn = 0; for (const ch of s.cons) cn += (ch === "ζ" || ch === "ξ" || ch === "ψ") ? 2 : 1;
    const mutaLiquida = /^[βγδθκπτφχ][ρλ]$/.test(s.cons);
    const lex = LEXQ[s.word] && LEXQ[s.word][s.sylInWord];
    if (lex) s.q = lex;
    else if (cn >= 2 && !mutaLiquida) s.q = "L";     // long by position
    else if (cn >= 2 && mutaLiquida) s.q = "?";        // muta cum liquida
    else if (s.isLongNature) {
      if (correption && s.wordFinalBeforeVowel) s.q = "?"; // epic correption
      else s.q = "L";
    } else s.q = "S";
  }
  return sylls;
}
function combos(n, k, arr = []) { if (k === 0) return [arr.concat(Array(n).fill("S"))]; if (n === 0) return []; return [...combos(n - 1, k - 1, arr.concat("D")), ...combos(n - 1, k, arr.concat("S"))]; }
function scan(sylls) {
  const qs = sylls.map(s => s.q);
  const d = qs.length - 12; if (d < 0 || d > 5) return null;
  for (const feet of combos(5, d)) {
    const need = [];
    for (let f = 0; f < 5; f++) { need.push("L"); if (feet[f] === "D") { need.push("S"); need.push("S"); } else need.push("L"); }
    need.push("L"); need.push("X");
    let ok = true;
    for (let k = 0; k < qs.length; k++) { if (need[k] === "X") continue; if (qs[k] === "?") continue; if (qs[k] !== need[k]) { ok = false; break; } }
    if (ok) return { feet, qs };
  }
  return null;
}
function footString(r) {
  // render as — and ⏑ groups per foot
  let out = [], idx = 0;
  for (let f = 0; f < 5; f++) { out.push(r.feet[f] === "D" ? "—⏑⏑" : "——"); idx += r.feet[f] === "D" ? 3 : 2; }
  out.push("—X");
  return out.join(" | ");
}

// ===========================================================================
//  B — SCANSION
// ===========================================================================
console.log("\n[B] SCANSION — every full line the page shows is a valid hexameter\n");
for (const L of LINES) {
  if (L.auto === false) { console.log(`  · Il. 1.${L.n} shown with sourced scansion (synizesis) — not auto-scanned`); continue; }
  const r = scan(syllabify(book1[String(L.n)]));
  check(`Il. 1.${L.n} scans as dactylic hexameter  [${r ? footString(r) : "FAILED"}]`, r !== null,
    r ? "" : `\n      ${book1[String(L.n)]}\n      pattern: ${syllabify(book1[String(L.n)]).map(s => s.q).join("")}`);
}

// ===========================================================================
//  C — ATTESTATION of the loom's marked-attested combinations
// ===========================================================================
console.log("\n[C] ATTESTATION — every combination the loom marks ATTESTED is a real line\n");
const byId = { ...Object.fromEntries(HEMISTICHS.map(h => [h.id, h])), ...Object.fromEntries(NAMES.map(n => [n.id, n])) };
for (const L of LINES) {
  if (!L.combo) continue;
  const [hId, nId] = L.combo;
  const expect = norm(byId[hId].greek + " " + byId[nId].greek).split(" ").map(depunct).join(" ");
  const actual = wordsOf(L.n).join(" ");
  check(`Il. 1.${L.n} = "${byId[hId].tr}" + "${byId[nId].tr}"`, expect === actual,
    expect === actual ? "" : `\n      expect: ${expect}\n      actual: ${actual}`);
}

// ===========================================================================
//  D — ECONOMY, computed from all 611 lines of Book 1
// ===========================================================================
console.log("\n[D] ECONOMY (computed) — line-final nominative namings in Book 1\n");
// The seven figures, by the stem that ends the nominative naming.
const FIGURES = [
  { who: "Achilles", stem: "αχιλλευς" },
  { who: "Agamemnon", stem: "αγαμεμνων" },
  { who: "Zeus", stem: "ζευς" },
  { who: "Athena", stem: "αθηνη" },
  { who: "Hera", stem: "ηρη" },
  { who: "Apollo", stem: "απολλων" },
  { who: "Odysseus", stem: "οδυσσευς" },
];
// For each figure, find every line whose LAST word (deaccented) is the stem.
// The naming = the noun-epithet run at line end. We group the recurring
// noun-epithet formulae by their METRICAL SHAPE (the quantity string of the
// naming's own syllables) — because Parry's economy is "one formula per
// metrical shape", NOT one formula per hero. The honest picture: a hero has a
// few formulae of DIFFERENT shapes (extension), with little duplication WITHIN
// a shape (economy). One-off namings by verb/particle+name are shown as such.
function nameShape(words) {
  const s = scan ? null : null; // (placeholder to keep lints quiet)
  const sy = syllabify(words.join(" "));
  return sy.map(x => x.q === "?" ? "L" : x.q).join(""); // resolve ambiguous to L for shape display
}
// the canonical recurring noun-epithet formulae we look for (any shape)
const KNOWN = {
  Achilles: [["πόδας", "ὠκὺς", "Ἀχιλλεύς"], ["δῖος", "Ἀχιλλεύς"]],
  Agamemnon: [["εὐρὺ", "κρείων", "Ἀγαμέμνων"], ["ἄναξ", "ἀνδρῶν", "Ἀγαμέμνων"], ["κρείων", "Ἀγαμέμνων"]],
  Zeus: [["νεφεληγερέτα", "Ζεύς"], ["μητίετα", "Ζεύς"]],
  Athena: [["γλαυκῶπις", "Ἀθήνη"], ["Παλλὰς", "Ἀθήνη"]],
  // θεὰ λευκώλενος Ἥρη added 2026-10-18 (assay line): Parry's own formula (19
  // times, MHV p. 234); before, its four Book-1 lines were filed under the
  // shorter λευκώλενος Ἥρη, which hid the one same-shape doublet in Book 1.
  Hera: [["λευκώλενος", "Ἥρη"], ["θεὰ", "λευκώλενος", "Ἥρη"], ["πότνια", "Ἥρη"], ["χρυσόθρονος", "Ἥρη"], ["βοῶπις", "πότνια", "Ἥρη"]],
  Apollo: [["Φοῖβος", "Ἀπόλλων"], ["ἑκάεργος", "Ἀπόλλων"]],
  Odysseus: [["πολύμητις", "Ὀδυσσεύς"], ["δῖος", "Ὀδυσσεύς"]],
};
const tally = {};
for (const f of FIGURES) tally[f.who] = {};
for (const n of Object.keys(book1)) {
  const lw = wordsOf(Number(n));
  if (!lw.length) continue;
  const last = deaccent(lw[lw.length - 1]).toLowerCase();
  const fig = FIGURES.find(f => last === f.stem);
  if (!fig) continue;
  let matched = null;
  for (const bw of (KNOWN[fig.who] || [])) {
    // grave and acute are one accent (a final acute turns grave before another
    // word), so compare with graves read as acutes. Added 2026-10-18 (assay
    // line); before, 1.145 and 1.440 (Ὀδυσσεὺς with a grave) were missed.
    const ga = w => w.normalize("NFD").replace(/\u0300/g, "\u0301").normalize("NFC");
    const idx = isContiguousSubsequence(bw.map(depunct).map(ga), lw.map(ga));
    if (idx >= 0 && idx + bw.length === lw.length) { if (!matched || bw.length > matched.length) matched = bw; }
  }
  const key = matched ? matched.join(" ") : `· one-off: …${lw.slice(-2).join(" ")}`;
  const shape = matched ? nameShape(matched) : "";
  const kk = matched ? `${key}  [${shape}]` : key;
  tally[fig.who][kk] = (tally[fig.who][kk] || 0) + 1;
}
// Economy is a tendency, not a law: Parry himself names βοῶπις πότνια Ἥρη ~
// θεὰ λευκώλενος Ἥρη as "one of the rare cases of formulae equivalent in both
// sense and metre" (MHV p. 234), and both recur in Book 1. The check asserts
// that this is the ONLY such shared shape among recurring formulae. (Until
// 2026-10-18 it asserted there were none, which held only because the
// θεὰ λευκώλενος lines were filed under λευκώλενος Ἥρη.)
const EXPECTED_DOUBLETS = ["Hera: βοῶπις πότνια Ἥρη ~ θεὰ λευκώλενος Ἥρη"];
const foundDoublets = [];
for (const f of FIGURES) {
  const entries = Object.entries(tally[f.who]).sort((a, b) => b[1] - a[1]);
  const total = entries.reduce((s, [, c]) => s + c, 0);
  console.log(`  ${f.who} (named at line-end ${total}×):`);
  for (const [k, c] of entries) console.log(`      ${String(c).padStart(2)}×  ${k}`);
  // economy test: among the RECURRING noun-epithet formulae (count>=2), no two
  // share the same metrical shape.
  const shapes = {};
  for (const [k, c] of entries) {
    const m = k.match(/^(.*)\s+\[([LS]+)\]$/);
    if (m && c >= 2) { (shapes[m[2]] = shapes[m[2]] || []).push(m[1].trim()); }
  }
  for (const sh in shapes) if (shapes[sh].length > 1) {
    const d = `${f.who}: ${shapes[sh].slice().sort().join(" ~ ")}`;
    foundDoublets.push(d);
    console.log(`      ⚠ recurring formulae share shape ${sh}: ${shapes[sh].join(" ~ ")}`);
  }
}
check(`Economy in Book 1: the only RECURRING noun-epithet formulae for a figure that share a metrical shape are Parry's named doublet (${EXPECTED_DOUBLETS.join("; ")})`,
  JSON.stringify(foundDoublets.slice().sort()) === JSON.stringify(EXPECTED_DOUBLETS.slice().sort()),
  `\n      found: ${JSON.stringify(foundDoublets)}`);

// ===========================================================================
//  EMIT — verified data for the page (single source of truth)
// ===========================================================================
import { writeFileSync } from "node:fs";
function fullFoot(n) { const r = scan(syllabify(book1[String(n)])); return r ? footString(r) : null; }
const out = {
  source: "Perseus Digital Library, urn:cts:greekLit:tlg0012.tlg001.perseus-grc2 (Monro-Allen Oxford Iliad, 1902; public domain)",
  xmlSha256: xmlSha,
  hemistichs: HEMISTICHS.map(h => ({ id: h.id, greek: norm(book1[String(h.home)]).split(" ").slice(0, norm(h.greek).split(" ").length).join(" "), tr: h.tr, gloss: h.gloss, home: h.home })),
  names: NAMES.map(n => ({ id: n.id, greek: n.greek, tr: n.tr, gloss: n.gloss, who: n.who })),
  lines: LINES.filter(L => L.combo).map(L => ({ n: L.n, greek: book1[String(L.n)], hemistichId: L.combo[0], nameId: L.combo[1], feet: fullFoot(L.n) })),
  opening: { n: 1, greek: book1["1"], note: "the first line of the Iliad; -εω of Πηληϊάδεω is read by synizesis as one long syllable" },
  economy: (() => {
    const o = {};
    for (const f of FIGURES) {
      o[f.who] = { formulae: [], oneoffs: 0, total: 0 };
      const entries = Object.entries(tally[f.who]);
      for (const [k, c] of entries) {
        o[f.who].total += c;
        const m = k.match(/^(.*)\s+\[([LS]+)\]$/);
        if (m) o[f.who].formulae.push({ greek: m[1].trim(), shape: m[2], syl: m[2].length, count: c });
        else o[f.who].oneoffs += c;
      }
      o[f.who].formulae.sort((a, b) => b.count - a.count);
    }
    return o;
  })(),
  caesura: { book: 1, lines: 611, trochaic: 356, masculine: 247, source: "Monro, Homeric hexameter, via Dickinson College Commentaries" },
};
writeFileSync(path.join(__dirname, "loom-data.json"), JSON.stringify(out, null, 2));
console.log("\n  → wrote loom-data.json");

console.log(`\n${failed === 0 ? "✓ ALL CHECKS PASSED" : "✗ FAILURES"}: ${passed} passed, ${failed} failed`);
process.exit(failed === 0 ? 0 : 1);
