#!/usr/bin/env python3
"""Deterministic Witness 2 (w2_hour_deg15_boundary) generator.

Reads local comparator records, manuscript dissections, MS 408 zodiac census TSVs,
and research register (strictly mode=ro), verifies every cited on-disk source,
and emits ANALYSIS.json, RESULT.md, and RECEIPT.json inside the W2 directory.
"""

from __future__ import annotations

import csv
import datetime as dt
import hashlib
import json
import pathlib
import sqlite3
from typing import Any, Dict, List

W2_DIR = pathlib.Path("../../../resources/tools/provenance/index.html#s-7513842bc7f8f835")
SCRIPT_PATH = W2_DIR / "scripts" / "run_w2.py"
ANALYSIS_PATH = W2_DIR / "ANALYSIS.json"
RESULT_PATH = W2_DIR / "RESULT.md"
RECEIPT_PATH = W2_DIR / "RECEIPT.json"

DB_PATH = pathlib.Path("../../../resources/tools/substrate/index.html")
CENSUS_DIR = pathlib.Path("../../../resources/readers/provenance/source-9aacdd8f2e5195d6.html")

SOURCE_PATHS_TO_VERIFY: List[str] = [
    "cb7449e9c540c4bbb08c6e25.json",
    "66b3a3bbc4dc27558806daeb.txt",
    "../../../resources/tools/provenance/index.html#s-d3ee1906f84c3b67",
    "../../../resources/tools/provenance/index.html#s-3fa5dee07e563403",
    "../../../resources/readers/voynich_consolidation_2026-11-18/campaign_zodiac_uses/cambridge/sources/cambridge_illuminations.txt",
    "../../../resources/tools/provenance/index.html#s-e200456d1ff33a09",
    "b8e202285a7c8ff96633d686.txt",
    "../../../resources/tools/provenance/index.html#s-4e994efcda3c9b50",
    "../../../resources/readers/voynich_consolidation_2026-11-18/campaign_zodiac_uses/if35/inventory.json",
    "../../../resources/tools/provenance/index.html#s-9da7bfbf447dfaaf",
    "../../../resources/tools/provenance/index.html#s-bdcaa6e3b4f5820d",
    "../../../resources/tools/provenance/index.html#s-52c84e84d3c8cd0f",
    "../../../resources/readers/voynich_consolidation_2026-11-18/campaign_cgm561_415_resolution/report.source.html",
    "../../../resources/readers/star_timing_intake_2026-10-10/reverse_lens/a_computation_layer.source.html",
    "../../../resources/tools/provenance/index.html#s-f20917f88b156647",
    "0d0ed184a9210bd8c8ecfaf5.md",
    "../../../resources/tools/provenance/index.html#s-aca3ade944a13c1e",
    "../../../resources/tools/provenance/index.html#s-223d4883f2d3d40c",
    "5043d454bb856d1d55149655.md",
    "b3968c493f816596c5f02d96.md",
    "bc20202ac99d966f6051d4a6.md",
    "5b0b27ee7599bd830da35be1.md",
    "09302c4cdddff7b50dce2213.md",
    "d4be6d68b3bfd09aac2c216b.md",
    "9079fee0a2c8f2ed089b426b.md",
    "7820998d9edbfef998e9c4f9.md",
    "../../../resources/readers/caius_158v_reader_2026-11-20/evidence.json",
    "../../../resources/readers/aries_reader_2026-11-20/sources/result.source.html",
    "../../../resources/readers/aries_reader_2026-11-20/sources/readings.json",
    "../../../resources/readers/static_wheel_dispatch_2026-11-20/historical/result.source.html",
    "../../../resources/readers/static_wheel_dispatch_2026-11-20/historical/readings.json",
    "../../../resources/tools/provenance/index.html#s-08f65643ccc360e4",
    "d23573606894bb2be346be66.json",
    "5a1206d3a2c4922c3c9e1baa.md",
    "../../../resources/readers/collection/md2_dissection_2026-05-03/MD2_DISSECTION_v1.source.html",
    "e0dc69eb1938a9de9eb9c365.md",
    "883294febb4a18820e3a8935.md",
    "b0e2f7f1bea9aeb0b826ae0f.md",
    "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_557/REFERENCE.source.html",
    "../../../resources/tools/provenance/index.html#s-e4300b70d0481016",
    "../../../resources/tools/provenance/index.html#s-d1d5f2d982edf26d",
    "../../../resources/tools/provenance/index.html#s-ab77814892685015",
    "dbbdec6e1e0a271835ef3365.md",
    "../../../resources/tools/provenance/index.html#s-0fed77f455468b01",
    "../../../resources/tools/provenance/index.html#s-b089eb9aaa32abac",
    "../../../resources/tools/provenance/index.html#s-27af94bd0297ed7b",
    "../../../resources/tools/provenance/index.html#s-6ce272d0da8306a7",
    "../../../resources/tools/provenance/index.html#s-c8ec2a4aec247842",
    "../../../resources/tools/provenance/index.html#s-4c6e99e12768b578",
    "../../../resources/tools/provenance/index.html#s-280a67b18b22b5d7",
    "../../../resources/tools/provenance/index.html#s-2205e95a7fbc4db9",
    "../../../resources/tools/provenance/index.html#s-36316c76c0b520dc",
    "../../../resources/tools/provenance/index.html#s-4ecdc3300e99945c",
    "../../../resources/tools/provenance/index.html#s-31d4ed67817a85dc",
    "../../../resources/tools/provenance/index.html#s-07ca99271041e14c",
    "../../../resources/tools/provenance/index.html#s-703b7fe4e07c4c54",
    "../../../resources/tools/provenance/index.html#s-196ccf582c5859ec",
    "5dee724088398e007af6f00c.md",
    "../../../resources/tools/provenance/index.html#s-f08fde11216c9f65",
    "../../../resources/tools/provenance/index.html#s-afd8520b57ed778b",
    "../../../resources/tools/provenance/index.html#s-2e6a9e39717dd664",
    "95f2916fe6d28cd9e9e90f2e.md",
    "20e9ff88cb62a98d310a920a.md",
    "e19670fff9b0875e656b1cb1.md",
    "5fcb5930ea583bfd87bcc19b.md",
    "../../../resources/readers/collection/voynich/hartlieb/CGM7958_KEY_PASSAGES_TRANSCRIPTION_2026-05-18.source.html",
    "e7e36e36a75bf45e7517c96a.md",
    "../../../resources/tools/substrate/index.html",
]


def sha256_file(path: pathlib.Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        for chunk in iter(lambda: fh.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def verify_sources() -> Dict[str, Any]:
    records = []
    missing = []
    for s in SOURCE_PATHS_TO_VERIFY:
        p = pathlib.Path(s)
        exists = p.exists()
        records.append({
            "path": s,
            "exists": exists,
            "bytes": p.stat().st_size if exists and p.is_file() else None,
        })
        if not exists:
            missing.append(s)
    dissections = sorted(str(p) for p in pathlib.Path("../../../resources/readers/provenance/source-49f1898a1c38ccac.html").glob("*/DISSECTION_2026-11-26.md"))
    return {
        "checked_count": len(records),
        "existing_count": sum(1 for r in records if r["exists"]),
        "missing_paths": missing,
        "dissection_2026_11_26_total_on_disk": len(dissections),
        "records": records,
    }


def compute_ms408_zodiac_census() -> Dict[str, Any]:
    panel_order = [
        ("f70v2", "Pisces", "mars", "single"),
        ("f70v1", "Aries (dark/uncoloured)", "abril", "split_1_of_2"),
        ("f71r", "Aries (light/coloured)", "abril", "split_2_of_2"),
        ("f71v", "Taurus (coloured)", "may", "split_1_of_2"),
        ("f72r1", "Taurus (uncoloured)", "may", "split_2_of_2"),
        ("f72r2", "Gemini", "yony", "single"),
        ("f72r3", "Cancer", "iollet", "single"),
        ("f72v3", "Leo", "augst", "single"),
        ("f72v2", "Virgo", "septembre", "single"),
        ("f72v1", "Libra", "octembre-like", "single"),
        ("f73r", "Scorpio", "novebre", "single"),
        ("f73v", "Sagittarius", "illegible", "single"),
    ]
    panels = []
    total_labelled_rows = 0
    for folio, sign, month_label, layout_type in panel_order:
        tsv = CENSUS_DIR / f"{folio}_rows.tsv"
        with tsv.open("r", encoding="utf-8", newline="") as fh:
            rows = list(csv.DictReader(fh, delimiter="\t"))
        ring_counts: Dict[str, int] = {}
        face_red_y = 0
        body_red_y = 0
        container_nonempty = 0
        star_missing = 0
        has_container_col = "container" in rows[0] if rows else False
        for row in rows:
            ring = (row.get("ring") or "").strip()
            ring_counts[ring] = ring_counts.get(ring, 0) + 1
            if (row.get("face_red") or "").strip().startswith("Y"):
                face_red_y += 1
            if (row.get("body_red") or "").strip().startswith("Y"):
                body_red_y += 1
            if has_container_col:
                cont = (row.get("container") or "").strip()
                if cont and cont not in ("N", "none", "None", "-"):
                    container_nonempty += 1
            if (row.get("star") or "").strip() == "N":
                star_missing += 1
        unlabelled_figures = 1 if folio == "f72r2" else 0
        total_figures = len(rows) + unlabelled_figures
        total_labelled_rows += len(rows)
        panels.append({
            "folio": folio,
            "sign": sign,
            "month_label": month_label,
            "layout_type": layout_type,
            "labelled_rows": len(rows),
            "unlabelled_figures": unlabelled_figures,
            "total_figures": total_figures,
            "ring_counts": ring_counts,
            "face_red_Y": face_red_y,
            "body_red_Y": body_red_y,
            "container_count": container_nonempty if has_container_col else None,
            "container_note": "1 barrel (f71r.4) + colored containers in notes (no container col in TSV)" if not has_container_col else None,
            "explicit_star_N": star_missing,
            "census_tsv": str(tsv),
        })
    return {
        "panel_count": len(panels),
        "signs_present": 10,
        "signs_absent": ["Capricorn", "Aquarius"],
        "split_15_plus_15_signs": ["Aries (f70v1/f71r)", "Taurus (f71v/f72r1)"],
        "single_panel_signs_count": 8,
        "total_labelled_rows": total_labelled_rows,
        "total_figures_including_unlabelled_K": total_labelled_rows + 1,
        "has_any_10_10_10_decan_panel": False,
        "panels": panels,
    }


def compute_historical_metrics() -> Dict[str, Any]:
    sw = json.loads(pathlib.Path("../../../resources/readers/static_wheel_dispatch_2026-11-20/historical/readings.json").read_text(encoding="utf-8"))
    ar = json.loads(pathlib.Path("../../../resources/readers/aries_reader_2026-11-20/sources/readings.json").read_text(encoding="utf-8"))
    ev = json.loads(pathlib.Path("../../../resources/readers/caius_158v_reader_2026-11-20/evidence.json").read_text(encoding="utf-8"))

    obs = sw["berlin"]["observations"]
    pair_checks = []
    for i in range(12):
        h1 = obs[i]
        h2 = obs[i + 12]
        pair_checks.append({
            "hour_day": h1["hour"],
            "hour_night_plus_12": h2["hour"],
            "zodiac": h1["zodiac"],
            "same_zodiac": h1["zodiac"] == h2["zodiac"],
            "same_judgment": h1["judgment"] == h2["judgment"],
            "qualities": [h1["quality"], h2["quality"]],
            "distinct_quality": h1["quality"] != h2["quality"],
        })

    return {
        "berlin_f144v": {
            "radial_columns_total": sw["berlin"]["count"]["radial_columns_total"],
            "numbered_hour_columns": sw["berlin"]["count"]["numbered_hour_columns"],
            "headings_column": sw["berlin"]["count"]["headings_column"],
            "same_sign_pairs_12h_apart": sum(1 for p in pair_checks if p["same_zodiac"]),
            "pairs_with_same_judgment": sum(1 for p in pair_checks if p["same_judgment"]),
            "pairs_with_distinct_quality": sum(1 for p in pair_checks if p["distinct_quality"]),
            "pair_sample_aries_1_13": pair_checks[0],
        },
        "caius_degree_tables": {
            "f164r_noon_solar_14_to_17_ascendant": ar["angular_tables"]["solar_input_f164r"],
            "f165v_rising_14_to_17_house2_taurus": ar["angular_tables"]["rising_input_f165v"],
            "f164r_f166v_22m_vs_25m_tie_at_aries_1deg": sw["caius"]["rows"],
            "caius_vs_pal1373_f134v_cells_compared": 5,
            "caius_vs_pal1373_f134v_exact_matches": 2,
            "caius_vs_pal1373_f134v_1deg_differences": 3,
            "evidence_source": "../../../resources/readers/caius_158v_reader_2026-11-20/evidence.json",
        },
    }


def query_substrate_db() -> Dict[str, Any]:
    conn = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)
    cur = conn.cursor()
    counts = {
        "manuscripts": cur.execute("SELECT COUNT(*) FROM manuscripts").fetchone()[0],
        "findings": cur.execute("SELECT COUNT(*) FROM findings").fetchone()[0],
        "folio_substrate": cur.execute("SELECT COUNT(*) FROM folio_substrate").fetchone()[0],
        "citations": cur.execute("SELECT COUNT(*) FROM citations").fetchone()[0],
        "relationships": cur.execute("SELECT COUNT(*) FROM relationships").fetchone()[0],
    }
    key_ids = (95, 129, 132, 152, 156, 160, 218, 441, 696, 719, 722, 723, 748, 749)
    placeholders = ",".join("?" for _ in key_ids)
    findings = []
    for row in cur.execute(
        f"SELECT id, code, title, status, confidence FROM findings WHERE id IN ({placeholders}) ORDER BY id",
        key_ids,
    ):
        findings.append({
            "id": row[0],
            "code": row[1],
            "title": row[2],
            "status": row[3],
            "confidence": row[4],
        })
    conn.close()
    return {"table_counts": counts, "key_findings": findings}


def build_comparator_catalog() -> List[Dict[str, Any]]:
    return [
        {
            "id": "COMP-PAL1373",
            "shelfmark": "Vatican, BAV, Pal. lat. 1373 (Kirschgarten, c. 1412)",
            "subdivision_classes": ["two_half_15_plus_15", "three_part_10deg_decan", "degree_30", "mansion_28"],
            "subdivision_details": (
                "Explicit 15+15 two-page per sign house-equation tables across all 12 signs (ff.134v-146r: 24 pages, "
                "15 cells per page 3x5 grid, degrees 1-15 then 16-30); 12 signs x 3 faces of 10 degrees on f.110v; "
                "28-row mansion quality table on f.111r and 28 mansions with asterisks on ff.124v-125r; 30-day September grid f.116r; "
                "15 deg/hour conversion in Alfonsine tables."
            ),
            "folios": ["f.97v", "f.110v", "f.111r", "f.111v", "f.116r", "ff.124v-125r", "ff.134v-146r"],
            "verbatim_quotes": [
                "Tabula equationis dierum cum suis noctibus (f.97v)",
                "Tabula experimenti 28 mansionum lune (f.111r)",
                "Circulus perfectus (f.111v, 38 rows 1-38)",
            ],
            "visual_boundary_markers": [
                "2 pages per sign splitting 1-15 vs 16-30 across facing/consecutive layouts (ff.134v-146r)",
                "Red degree numerals 1-15 and 16-30 centered inside square-in-square 3x5 cells",
                "Red asterisk counts per lunar mansion (ff.124v-125r)",
                "Pasted paper/parchment fore-edge finding slips and red column heads",
            ],
            "source_paths": [
                "5b0b27ee7599bd830da35be1.md",
                "../../../resources/readers/star_timing_intake_2026-10-10/reverse_lens/a_computation_layer.source.html",
                "../../../resources/tools/provenance/index.html#s-703b7fe4e07c4c54",
                "09302c4cdddff7b50dce2213.md",
            ],
        },
        {
            "id": "COMP-CAIUS336",
            "shelfmark": "Cambridge, Gonville & Caius College, MS 336/725 (England, 15c)",
            "subdivision_classes": ["two_half_beg_vs_end", "two_half_day_vs_night", "three_part_10deg_decan", "degree_30", "hours_24_unequal"],
            "subdivision_details": (
                "Prose beginning-vs-end Aries split (f.128v); three 10-degree faces explained among 5 planetary dignities (f.44r); "
                "30-degree solar/ascendant lookup with smooth 1-degree resolution across 14-17 deg Aries (ff.163v-168r, no 15 deg jump); "
                "day vs night unequal hours and sunrise/sunset splits (ff.105v, 168v-172r); circular volvelle with Sun/Moon pointers and phase aperture (f.158v)."
            ),
            "folios": ["ff.43r-45r", "f.105v", "f.106r", "ff.128v-130v", "f.132r", "f.137r", "f.158v", "f.159v", "ff.163r-172r"],
            "verbatim_quotes": [
                "in the begynnynges of Aries ... in the ende as in the begynnyng (f.128v)",
                "Whanne a planete is in domo pat is to sei in his hous . he hap .5. strenkpis in his exaltacioun .5. in his triplicite .3. in his terminus .2. in his face .i. (f.44r)",
                "Tabula ad sciendum quis planeta regnat in omni hora in equali incipiendo diem ab ortus solis / Hore noctis incipiendo noctem ab occusu soli (f.105v)",
                "pe sixte part of pe sercle . pat is to seie .60. degrees (f.106r)",
                "Working from the outside to the centre of the volvelle, we see the points of the compass in English, the hours, days, and months, then the days within astrological houses and states of digestion, and finally the days of the moon. ... There are two pointing indexes for the sun and the moon. (f.158v, Cambridge Illuminations)",
            ],
            "visual_boundary_markers": [
                "Concentric instrument rings on f.158v with two pointing indexes (Sun/Moon) and movable moon-phase aperture",
                "Ruled numerical degree tables (ff.163v-172r) with red headers",
                "Zodiac Man anatomical label placement (f.159v)",
            ],
            "source_paths": [
                "b8e202285a7c8ff96633d686.txt",
                "../../../resources/readers/voynich_consolidation_2026-11-18/campaign_zodiac_uses/cambridge/sources/cambridge_illuminations.txt",
                "../../../resources/readers/aries_reader_2026-11-20/sources/readings.json",
                "../../../resources/readers/caius_158v_reader_2026-11-20/evidence.json",
            ],
        },
        {
            "id": "COMP-O720",
            "shelfmark": "Cambridge, Trinity College, MS O.7.20 (England, 15c)",
            "subdivision_classes": ["two_half_direct_indirect", "three_part_decan_face", "hours_24_volvelle"],
            "subdivision_details": (
                "10 concentric circles divided by 12 radial lines creating 12 sign rows of 8 cells each, tagging Directe/Indirecte oritur, domiciles, "
                "exaltations, triplicities, and faces (f.1:17v); branching 4-element quality diagram + planetary circle (f.1:21r); "
                "3-disc paper volvelle sewn with blue thread carrying month/sign, outer numbered hours, inner lunar age, two pointers, and red/black phase aperture (f.1:25v)."
            ),
            "folios": ["f.1:1r", "f.1:17r", "f.1:17v", "f.1:21r", "f.1:25v"],
            "verbatim_quotes": [
                "Per hanc figuram scies domos exaltaciones tripli[cita]tes [...] et facies planetarum ad signa (f.1:17v)",
                "Directe oritur / Indirecte oritur (f.1:17v outer cell per sign row)",
            ],
            "visual_boundary_markers": [
                "10 concentric circles crossed by 12 radial dividers (f.1:17v)",
                "3 stacked paper volvelle discs sewn with blue thread, two indexed pointers, and red/black phase aperture (f.1:25v)",
                "Red/brown manicules in margins with Middle English reader notes",
            ],
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-e200456d1ff33a09",
                "cb7449e9c540c4bbb08c6e25.json",
            ],
        },
        {
            "id": "COMP-MD2",
            "shelfmark": "Tübingen, Universitätsbibliothek, Cod. Md 2 (Tübinger Hausbuch, c. 1430s-1480)",
            "subdivision_classes": ["three_part_10deg_decan", "two_half_gender_or_day_night", "degree_30_month_hours", "houses_12"],
            "subdivision_details": (
                "12 sign chapters (ff.51r-144v) with explicit 3-decan subdivision ('erstes/anderes/drittes angesichte', 10 degrees each), "
                "gender split (knaben/maget), 12-house cross-product, and monthly daylight/night hour totals (e.g. f.72r 12h/12h, f.94r 13h/10h); "
                "Aquarius f.133r-v also has a 4-part body split (Heubt/Libe/ende/nature); f.323v displays a 12+12+12=36 three-ring wheel (Scotus decans, F-95); "
                "f.321r-v displays paired-tower planetary co-domiciles; f.13r is a 12x7 medical grid."
            ),
            "folios": ["ff.1r-6v", "f.9r-v", "f.12v", "f.13r-v", "f.23r", "f.35r", "ff.51r-144v", "f.321r-v", "f.323v"],
            "verbatim_quotes": [
                "Wer geboren wirt In dem ersten angesichte / In dem andern angesichte / In dem dritten angesichte (ff.51r-144v S6)",
                "Der mond hat 27 tage Der monet hat 30 tage Der tag hat 12 stunden... (f.72r)",
                "Der August hat 31 tage Der mond hat 29 tage Der tag hat 13 stunden die nacht 10... (f.94r)",
                "Signum / dz glieth lassen / Sirop / pulver / die natur / zeichen (f.13r)",
            ],
            "visual_boundary_markers": [
                "Three-ring 12+12+12=36 concentric wheel around central 8-point star (f.323v)",
                "Ruled 12x19 Golden Number grid (f.7r) and 12x7 medical grid (f.13r) with red glyphs",
                "Red/blue/green elemental roundel fields on month leaves (ff.1r-6v)",
                "Compass construction cross visible inside moon-face roundel (f.8r)",
            ],
            "source_paths": [
                "../../../resources/readers/collection/md2_dissection_2026-05-03/MD2_DISSECTION_v1.source.html",
                "e0dc69eb1938a9de9eb9c365.md",
                "883294febb4a18820e3a8935.md",
                "dbbdec6e1e0a271835ef3365.md",
            ],
        },
        {
            "id": "COMP-BERLIN1191",
            "shelfmark": "Berlin, SBB, Ms. germ. fol. 1191 (Heinrich Laufenberg, Versehung des Leibs, 1429)",
            "subdivision_classes": ["hours_24_paired_12h", "two_half_phrases_and_12h_split", "sidereal_19x27"],
            "subdivision_details": (
                "f.144v 'Spere' has 25 radial columns: 1 heading wedge + 24 Roman hours I-XXIIII, where each sign repeats 12 hours apart with identical judgment "
                "(12/12 pairs) and distinct physical quality (12/12 pairs); f.51r hour wheel has 7 planetary rings of 25 cells (24 hours + 1 weekday header, no verdict); "
                "f.22r is a 19x27 lunar-sign grid; half-units appear only in prose phrases (f.42v 'half wet', f.44v 'Halb drucken halb regen', 'Ein halbs ior'), never as half-hour table slots."
            ),
            "folios": ["f.20v", "f.21r", "f.22r", "ff.25r-36v", "f.42v", "f.44v", "f.51r", "f.108r", "f.144v"],
            "verbatim_quotes": [
                "yeglichs het sin sunderstunde ... was es tun sol oder myden (f.144v)",
                "Halb drucken halb regen ... In siben iaren da by stat / Ein halbs ior und ouch da zu (f.44v)",
                "bös oder güt / Oder mittel (f.39r)",
            ],
            "visual_boundary_markers": [
                "25th radial heading wedge separating hour I from hour XXIIII on f.144v; 25th weekday header cell on f.51r",
                "Red/black alternating cells (f.51r)",
                "Manicules on f.20v (7-cell dominical wheel) and f.21r (19-cell golden-number wheel), none on f.144v",
                "Nude sign figures on rayed gold discs with red 6-point stars (ff.25r-36v)",
            ],
            "source_paths": [
                "../../../resources/readers/static_wheel_dispatch_2026-11-20/historical/readings.json",
                "../../../resources/tools/provenance/index.html#s-aca3ade944a13c1e",
                "../../../resources/tools/provenance/index.html#s-223d4883f2d3d40c",
                "../../../resources/tools/provenance/index.html#s-07ca99271041e14c",
            ],
        },
        {
            "id": "COMP-IF35",
            "shelfmark": "Prague, Národní knihovna, I F 35 (Matouš Beran Confundarium, Erfurt, 1431)",
            "subdivision_classes": ["two_half_prima_medietas", "degree_30_moon_days", "hours_planetary_7"],
            "subdivision_details": (
                "Explicit half-sign split in Libra prose ('prima medietas ipsius', f.26r) and partial-sign exclusion ('last part of Sagittarius', f.24r); "
                "30 moon days parted among 12 signs (f.13v); 28+14=42-row Moon-sign x 12-sign grid with checkerboard parity 347/348 (ff.22v-23r); "
                "7-column planetary-hour grid by weekday and metal (f.22r); lunar mansions with drawn star points (ff.10r-11r)."
            ),
            "folios": ["ff.3r-9v", "ff.10r-11v", "f.13v", "ff.22r-23r", "f.24r", "f.26r", "ff.24v-28r"],
            "verbatim_quotes": [
                "maxime in prima medietate ipsius ... luna ab aliunde non impedita (f.26r, Libra)",
                "cum rubeis signis sunt boni, cum nigris nulli, cum mediis indifferentes (f.22r)",
            ],
            "visual_boundary_markers": [
                "Red/black/middle ink grade coding in planetary-hour grid (f.22r)",
                "Checkerboard parity cells with B/m/o grades (ff.22v-23r)",
                "Drawn red/outlined star points on sign/mansion figures (ff.10r-11r)",
            ],
            "source_paths": [
                "cb7449e9c540c4bbb08c6e25.json",
                "bc20202ac99d966f6051d4a6.md",
            ],
        },
        {
            "id": "COMP-CGM7958",
            "shelfmark": "Munich, BSB, Cgm 7958 (Johannes Hartlieb, Mondwahrsagebuch, 1456)",
            "subdivision_classes": ["two_half_day_binary", "mansion_28", "degree_30_modulo", "hours_12_am_pm"],
            "subdivision_details": (
                "28 lunar mansions computed mod-19 and mod-28 (ff.3r-9r); binary half-week/Sunday-noon baptismal split between Our Lady's brothers "
                "(Tue/Thu/Sat + Sunday afternoon) and St. George's brothers (Mon/Wed/Fri + Sunday before noon) plus 12h AM/PM x L/R wound matrix (f.10r / pp.24-28); "
                "24-cell wheel on f.15r/p.33 (23 Latin letters + 1 cross-and-plumb marker cell) subtracting xxx (30, probable; F-749) and adding moon age."
            ),
            "folios": ["ff.3r-9r", "f.10r (pp.24-28)", "f.15r (p.33)", "p.35"],
            "verbatim_quotes": [
                "zu der zall sollt ir die zall des monds tun (f.15r / p.33)",
                "Ite die ... mansion (mansion prose paragraphs)",
            ],
            "visual_boundary_markers": [
                "Cross-T (cum cruce) at 12 o'clock top start/zero marker on >=10 operational volvelles (pp.33, 35; F-218)",
                "24th cross-and-plumb marker cell interrupting 23-letter ring (f.15r / p.33)",
                "Ruled four-quadrant circle (p.32) and red paragraph marks",
            ],
            "source_paths": [
                "5fcb5930ea583bfd87bcc19b.md",
                "../../../resources/readers/collection/voynich/hartlieb/CGM7958_KEY_PASSAGES_TRANSCRIPTION_2026-05-18.source.html",
                "09302c4cdddff7b50dce2213.md",
            ],
        },
        {
            "id": "COMP-PALLAT1369",
            "shelfmark": "Vatican, BAV, Pal. lat. 1369 (mid-15c)",
            "subdivision_classes": ["three_part_10deg_ticks", "degree_30_ticks"],
            "subdivision_details": (
                "FA-001 corrected: f.54r is a gridded quadrant instrument with two concentric zodiac rings calibrated at 10, 20, and 30 degrees; "
                "f.62r is a mostly blank template wheel with 12-sign rim, 30-tick ring, and two crossing diagonals (not a month calendar)."
            ),
            "folios": ["f.54r", "f.57v", "f.60r", "f.62r"],
            "verbatim_quotes": [],
            "visual_boundary_markers": [
                "Two concentric zodiac rings with explicit 10, 20, 30 degree calibration marks (f.54r)",
                "30-tick graduation ring and two crossing diagonals on template wheel (f.62r)",
            ],
            "source_paths": [
                "09302c4cdddff7b50dce2213.md",
                "../../../resources/tools/provenance/index.html#s-4ecdc3300e99945c",
            ],
        },
        {
            "id": "COMP-PALLAT1370",
            "shelfmark": "Vatican, BAV, Pal. lat. 1370 (Matthias von Kemnat, 1461)",
            "subdivision_classes": ["hours_24_daylight", "hours_planetary_weekday_grid", "election_36x12"],
            "subdivision_details": (
                "f.51r 4-ring zodiac, month, and hours-of-daylight wheel; f.57v (FA-001 corrected) planetary-hour weekday grid; "
                "f.60v 36-activity x 12-sign election table; ff.61v-62v computus volvelles; f.100r German 'Redlin' with Sunday letter, golden number, moon letter."
            ),
            "folios": ["f.51r", "f.57v", "f.60v", "ff.61v-62v", "f.100r", "f.150r"],
            "verbatim_quotes": [],
            "visual_boundary_markers": [
                "Fore-edge finding slip/tab at f.61v beside computus wheel",
                "4-ring concentric zodiac/month/hours wheel (f.51r) and 5 polygon aspect wheels",
            ],
            "source_paths": [
                "09302c4cdddff7b50dce2213.md",
                "../../../resources/tools/provenance/index.html#s-31d4ed67817a85dc",
            ],
        },
        {
            "id": "COMP-CGM415-CGM561",
            "shelfmark": "Munich, BSB, Cgm 415 (ff.279r-348v) & Cgm 561 (ff.154r-163r)",
            "subdivision_classes": ["two_half_day_vs_night", "degree_30_lunation"],
            "subdivision_details": (
                "Cgm 415 f.326v flips Moon->Sun vs Sun->Moon arc calculation between night and day births; f.327r defines 30 degrees per sign and 60 minutes per degree; "
                "f.327v states synodic lunation 29d 12h 45m. Control Cgm 561 ff.154r-163r carries 24h and 36h furnace state durations (non-astronomical)."
            ),
            "folios": ["Cgm 415 ff.326v-328r", "Cgm 561 ff.154r-163r"],
            "verbatim_quotes": [],
            "visual_boundary_markers": ["Prose rules and tabular horary entries (no concentric zodiac diagrams in inspected blocks)"],
            "source_paths": [
                "../../../resources/readers/voynich_consolidation_2026-11-18/campaign_cgm561_415_resolution/report.source.html",
                "../../../resources/readers/aries_reader_2026-11-20/sources/readings.json",
            ],
        },
        {
            "id": "COMP-CGM75",
            "shelfmark": "Munich, BSB, Cgm 75 (Nuremberg, 1475)",
            "subdivision_classes": ["degree_30_month"],
            "subdivision_details": (
                "f.5r 30-day April calendar heading ('Abrill hat 30 tag') with red 'Wider' and 'Stier' ingress at April 11; "
                "f.1r movable-disc lunar instrument; f.14r 6 eclipse discs with 'halbe werung' (half duration)."
            ),
            "folios": ["f.1r", "f.5r", "f.14r"],
            "verbatim_quotes": [
                "Abrill hat 30 tag (f.5r)",
                "halbe werung / kein punkht (f.14r)",
            ],
            "visual_boundary_markers": [
                "Red ingress sign rubric ('Stier') inside 30-row month table (f.5r)",
                "Movable rotating paper disc instrument (f.1r) and dark/light eclipse half-discs (f.14r)",
            ],
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-2e6a9e39717dd664",
                "../../../resources/readers/aries_reader_2026-11-20/sources/readings.json",
            ],
        },
        {
            "id": "COMP-MORGAN-B27",
            "shelfmark": "New York, Morgan Library, MS B.27 (Germany, 1450-1475; exemplar 1388/1394)",
            "subdivision_classes": ["two_half_waxing_waning", "degree_30_lunar"],
            "subdivision_details": (
                "f.56v upper carries a 30-slot waxing/waning moonshine ring ('Dies lune') encoding nocturnal shine hours by dot/pip counts; "
                "f.56v lower carries a planetary-house wheel; f.58v gives 12 signs x 7 planets essential dignity sums (5/4/3/2/1)."
            ),
            "folios": ["f.55r", "f.56v", "f.58v"],
            "verbatim_quotes": [
                "Das ist die zunemung des mans vnd die abnemung wie lang er all nacht scheinet (f.56v)",
                "Hie findst du die husz am yetlichen planeten (f.56v)",
            ],
            "visual_boundary_markers": [
                "30 radial slots around sun face with dot/pip sequences encoding waxing/waning duration (f.56v)",
                "4-quadrant triplicity tetrad wheel (f.55r)",
            ],
            "source_paths": [
                "d4be6d68b3bfd09aac2c216b.md",
                "9079fee0a2c8f2ed089b426b.md",
                "../../../resources/tools/provenance/index.html#s-b089eb9aaa32abac",
            ],
        },
        {
            "id": "COMP-MORGAN-B28-B12",
            "shelfmark": "New York, Morgan Library, MS B.28 (1458-1476) & MS B.12 (England, c.1425)",
            "subdivision_classes": ["houses_12", "quadrant_4_compass"],
            "subdivision_details": (
                "B.28 ff.30r-33r carry single computus wheels beneath a cross with Roman numerals and repeating letter cycles; f.17v has a 4-direction circle "
                "in a ruled square with red stars; B.12 f.49r is a 12-house square with diagonals numbered 1-12, and f.42v is a concentric sign-quality/direction rota."
            ),
            "folios": ["B.28 f.17v", "B.28 ff.30r-33r", "B.28 f.34r", "B.12 f.42v", "B.12 f.49r"],
            "verbatim_quotes": [],
            "visual_boundary_markers": [
                "Explicit cross positioned above top of wheels (B.28 ff.30r-33r)",
                "Red star markers and ruled corner square around circle (B.28 f.17v)",
                "Crossing diagonals + Arabic numerals 1-12 for houses (B.12 f.49r)",
            ],
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-27af94bd0297ed7b",
                "../../../resources/tools/provenance/index.html#s-0fed77f455468b01",
            ],
        },
        {
            "id": "COMP-WELLCOME-49-349",
            "shelfmark": "London, Wellcome Library, MS 49 (c.1420?) & MS 349 (Heymandus, 1488)",
            "subdivision_classes": ["degree_30_lunar_and_modulo", "hours_bloodletting"],
            "subdivision_details": (
                "MS 49 f.45r holds a 29+1=30 moon-phase ring (1..29 + sun face) plus bloodletting-hour verses; f.45v holds a zodiac ring marked with "
                "equinoctium vernale/autumnale and solstitium estivale/hiemale around 4 triplicity lobes; ff.41r/43v are Zodiac/Phlebotomy figures. "
                "MS 349 f.22r pairs a 12-roundel Zodiac Man with a Latin moon-in-sign degree computation; ff.25r-26r use cast-out divisor 30 onomantic wheels (F-749)."
            ),
            "folios": ["MS 49 ff.41r, 43v, 45r-v", "MS 349 ff.22r-v, 25r-26r"],
            "verbatim_quotes": [
                "Item si vis scire horas minutionis (MS 49 f.45r)",
                "equinoctium vernale / autumnale / solstitium estivale / hiemale (MS 49 f.45v)",
            ],
            "visual_boundary_markers": [
                "Numbered 1-29 crescent/dark-light discs closing at round sun face (MS 49 f.45r)",
                "Explicit cardinal turning-point labels (equinoctium/solstitium) separating sign quadrants (MS 49 f.45v)",
                "Red connecting lines / brackets from 12 sign roundels to body (MS 49 f.41r, MS 349 f.22r)",
            ],
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-52c84e84d3c8cd0f",
                "../../../resources/tools/provenance/index.html#s-bdcaa6e3b4f5820d",
                "../../../resources/tools/provenance/index.html#s-280a67b18b22b5d7",
                "../../../resources/tools/provenance/index.html#s-4c6e99e12768b578",
            ],
        },
        {
            "id": "COMP-CPG557-CPG3-CPG5",
            "shelfmark": "Heidelberg, UB, Cpg 557 (1468), Cpg 213, Cpg 3 (c.1400), Cpg 5 (c.1400-1425)",
            "subdivision_classes": ["two_half_waxing_waning", "two_half_seasonal_arm", "mansion_28", "sidereal_19x27", "houses_or_sites_36"],
            "subdivision_details": (
                "Cpg 557 carries a 19x27 moon-sign table (ff.19v-20v), weekly planetary-hour table (f.36r), explicit waning-moon gate matching Cpg 213 f.155r (f.77v), "
                "and 36 venesection sites (ff.84v-88r). Cpg 3 uses 28 mansions with 29-N reversal and mod-28 rotating lines (ff.1v-16v). "
                "Cpg 5 f.16v splits the year into two seasonal halves mapped to right arm (spring/summer) vs left arm (autumn/winter)."
            ),
            "folios": ["Cpg 557 ff.19v-20v, 36r, 77v, 84v-88r", "Cpg 3 ff.1v-16v", "Cpg 5 ff.13v, 16v-17v"],
            "verbatim_quotes": [
                "So sol der mon sein in dem ab neme (Cpg 557 f.77v / Cpg 213 f.155r)",
            ],
            "visual_boundary_markers": [
                "Empty double circles (Cpg 557 f.23r)",
                "Crescent face + compass star (Cpg 3 f.1v) and rubricated 4-column table",
                "Red lead lines on head/arm figures (Cpg 5 f.13v, f.16v)",
            ],
            "source_paths": [
                "5a1206d3a2c4922c3c9e1baa.md",
                "../../../resources/readers/collection/manuscripts/Heidelberg_Cpg_557/REFERENCE.source.html",
                "../../../resources/tools/provenance/index.html#s-e4300b70d0481016",
                "5043d454bb856d1d55149655.md",
                "b3968c493f816596c5f02d96.md",
            ],
        },
        {
            "id": "COMP-COLLANGE-1561",
            "shelfmark": "Gabriel de Collange, Polygraphie (Paris 1561) / Trithemius (1518)",
            "subdivision_classes": ["hours_24_12_pair_cipher_wheels"],
            "subdivision_details": (
                "Non-astronomical cryptographic comparator: 13 circular wheels (f.263r+); 4 recta and 4 aversa wheels each hold 6 alphabets arranged as "
                "2 x 12 half-rows. Alidade reads across diameter or circumference; requires external key selection (explicitly distinct from MS 408)."
            ),
            "folios": ["f.263r+ (13 wheels)"],
            "verbatim_quotes": [],
            "visual_boundary_markers": [
                "Rotating mechanical alidade (diametral vs circumferential read)",
                "Concentric 2x12 half-row Latin alphabet bands",
            ],
            "source_paths": [
                "7820998d9edbfef998e9c4f9.md",
            ],
        },
        {
            "id": "COMP-NEGATIVE-SURVEYED",
            "shelfmark": "Cpg 597, Cpg 291, Morgan G.47 & M.941, LJS 449, Pal. lat. 1197, Pal. lat. 1438 (checked blocks)",
            "subdivision_classes": ["absent_15deg_and_10deg_in_inspected_blocks"],
            "subdivision_details": (
                "Surveyed prompt /manuscripts comparators without documented 15+15 or 10+10+10 zodiac ring splits in local dissections: "
                "Cpg 597 (text herbal/medical), Cpg 291 (Hausbuch narrative + miniatures, no tables/tabs), Morgan G.47 (1464 folding almanac Zodiac/Vein Man), "
                "Morgan M.941 (1433 almanac 'sol [sign]' roundels + concentric God-centered wheel), LJS 449 (13 diagrams + 12 block medallions ff.12r-18v), "
                "Pal. lat. 1197 (medical/anatomical prose & tables), Pal. lat. 1438 (30-day aspectaria ff.65r/85r, 12-house Quaestiones f.77r, daily planet degrees f.129r)."
            ),
            "folios": ["G.47 ff.6r-v", "M.941 f.002v", "LJS 449 ff.12r-18v", "Pal. lat. 1438 ff.65r, 77r, 85r, 129r"],
            "verbatim_quotes": [],
            "visual_boundary_markers": [
                "Pointer lines on Zodiac/Vein Men (G.47), block medallions (LJS 449), Saints-day margin annotations (Pal. lat. 1438 f.129r)",
            ],
            "source_paths": [
                "../../../resources/tools/provenance/index.html#s-d1d5f2d982edf26d",
                "../../../resources/tools/provenance/index.html#s-ab77814892685015",
                "../../../resources/tools/provenance/index.html#s-6ce272d0da8306a7",
                "../../../resources/tools/provenance/index.html#s-c8ec2a4aec247842",
                "../../../resources/tools/provenance/index.html#s-2205e95a7fbc4db9",
                "../../../resources/tools/provenance/index.html#s-36316c76c0b520dc",
                "e19670fff9b0875e656b1cb1.md",
            ],
        },
    ]


def build_model_comparison(ms408: Dict[str, Any]) -> List[Dict[str, Any]]:
    return [
        {
            "historical_model": "15+15 two-half split (Pal. lat. 1373 ff.134v-146r; Caius f.128v; Prague f.26r; 15 deg/hour)",
            "what_it_explains_on_ms408": (
                "Confirms that splitting a 30-degree zodiac sign into two 15-unit halves (1-15 and 16-30, or beginning vs end) is an attested medieval layout, "
                "matching MS 408's 15+15 division of Aries (f70v1/f71r) and Taurus (f71v/f72r1), each with 10 outer + 5 inner figures. "
                "F-160 also notes 15 matches a half-synodic month."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Fails completely on selectivity and uniformity: Pal. lat. 1373 splits ALL 12 signs symmetrically into 2 pages of 15 cells (24 pages total), "
                "whereas MS 408 splits ONLY Aries and Taurus while keeping Pisces (29), Gemini (29+1=30), Cancer (30), Leo (30), Virgo (30), Libra (30), "
                "Scorpio (30), and Sagittarius (30) as single 30-ish panels, and omits Capricorn and Aquarius entirely (F-132, F-152). "
                "MS 408 also marks its Aries/Taurus pairs by pigment/container shifts (15/15 barrels vs 11/15 garment red in Aries; 12/15 garment red + 15/15 tubs vs 0/15 red + 5/15 tubs in Taurus) rather than degree numerals 1-15 / 16-30."
            ),
        },
        {
            "historical_model": "10+10+10 decan / face model (Md 2 ff.51r-144v & f.323v 12+12+12=36; Pal. lat. 1373 f.110v; Caius f.44r; Pal. lat. 1369 f.54r)",
            "what_it_explains_on_ms408": (
                "Explains why a sign circle uses concentric rings and sums near 30 (3 x 10 = 30), and shows triple-ring 36-cell geometry exists in Md 2 f.323v."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Refuted by exact ring counts across MS 408's single-panel signs: 0 of 12 MS 408 panels carry a 10+10+10 decan split (F-156 Falsified). "
                "Even the 3-group panels split as 5+15+9 (+1 unlabelled = 30, Gemini f72r2), 12+11+7 (Cancer f72r3), and 4+16+10 (Scorpio f73r, Sagittarius f73v), "
                "while 2-ring panels split as 19+10 (Pisces), 18+12 (Leo, Virgo), and 20+10 (Libra). Non-decanic integers (19, 11, 7, 16, 20, 4) falsify a 10-degree decan partition."
            ),
        },
        {
            "historical_model": "30-degree / 30-day lunar-synodic model (Cgm 415 f.327r; Cgm 75 f.5r; Morgan B.27 f.56v; Wellcome MS 49 f.45r; F-160; F-749)",
            "what_it_explains_on_ms408": (
                "Accounts for the ~30 figure count per sign (7 panels at 30, Pisces at 29 matching a 29-day/29.53-day lunar month, and Gemini with 29 labelled + 1 unlabelled K = 30), "
                "and accounts for waxing/waning half-cycle counts of 15 (F-160)."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Does not explain why ONLY Aries and Taurus are split across two panels while 8 signs sit on single panels, why Capricorn and Aquarius are absent, "
                "or why concentric sub-rings split unevenly (e.g. 19+10, 12+11+7, 20+10). Nor do MS 408 panels display day numbers (1-29/30), moon-phase discs (Wellcome 49 f.45r), or dot/pip hour counts (B.27 f.56v)."
            ),
        },
        {
            "historical_model": "12-hour / 24-hour paired wheel (Berlin f.144v 25-column Spere & f.51r; Caius f.105v & ff.168v-172r; Trinity O.7.20 f.1:25v; Collange f.263r)",
            "what_it_explains_on_ms408": (
                "Provides an exact structural parallel for repeating 12+12 sectors distinguished by an inner/outer attribute layer (Berlin f.144v repeats 12 signs 12h apart "
                "and disambiguates them via quality; comparable in sector count to MS 408 f67r1's 24 alternating star/text cells and f67r2's 12 sectors / 24 rim motifs)."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Does not map onto MS 408's 12 zodiac panels f70v2-f73v, which have 15, 29, or 30 nymphs without 24-hour Roman numerals (I-XXIIII), heading wedges (Berlin 25th column), or rotating alidades/pointers."
            ),
        },
        {
            "historical_model": "28-mansion apparatus (Cgm 7958 ff.3r-9r; Cpg 3; Pal. lat. 1373 ff.111r, 124v-125r)",
            "what_it_explains_on_ms408": (
                "Comparable only as a ~28-30 compartment lunar schema (and MS 408 f69v carries 28 radiating words, though F-129/F-441 falsify count-only mansion assignment)."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Fails to explain 30 figures per zodiac sign panel across 10 zodiac signs (28 mansions span the whole ecliptic once, not 30 compartments inside each sign)."
            ),
        },
        {
            "historical_model": "Visual start/boundary marking across comparators vs MS 408",
            "what_it_explains_on_ms408": (
                "Shows that medieval wheel/table designers routinely mark a radial start/origin explicitly (cross-T at 12 o'clock on Cgm 7958, cross above wheel on B.28, "
                "25th heading wedge on Berlin f.144v, wide gap near 11:45 on MS 408 f67r1, 11:00 gap on f69v, vertical stripe on f72v1, start markers on f71r C1-C2)."
            ),
            "what_it_fails_to_explain_on_ms408": (
                "Comparators use readable Latin/Arabic boundary markers (cross-T, numerals 1-15/16-30, 10/20/30 degree ticks, equinoctium/solstitium labels, weekday headers, "
                "rotating pointer tabs), all of which are absent on MS 408 f70v2-f73v."
            ),
        },
    ]


def render_result_md(analysis: Dict[str, Any]) -> str:
    ms408 = analysis["ms408_zodiac_census"]
    hist = analysis["historical_metrics"]
    src_ver = analysis["source_verification"]
    lines = [
        "# Witness 2 (`w2_hour_deg15_boundary`): Hour, Degree, and `15°` Boundary Witnesses",
        "",
        f"**Generated UTC:** `{analysis['generated_utc']}`",
        f"**Source Verification:** `{src_ver['existing_count']}/{src_ver['checked_count']}` cited paths present on disk (`DISSECTION_2026-11-26.md` files under `../../../resources/readers/provenance/source-49f1898a1c38ccac.html`: `{src_ver['dissection_2026_11_26_total_on_disk']}`). Missing path from prompt list: `{', '.join(src_ver['missing_paths']) if src_ver['missing_paths'] else 'none'}` (`A_COMPUTATION_LAYER.md` in the same folder is present).",
        "",
        "---",
        "",
        "## Method & Layer Separation",
        "- **Historical comparators** are described strictly from verified shelfmarks, folios, and verbatim transcriptions/catalogues on disk; no comparator table or wheel rule is projected onto MS 408 as a hidden key or cipher solution (MS 408 is not a cipher).",
        "- **MS 408 (`f70v2`–`f73v`, plus `f67r1`–`f69v`)** is quantified directly from the verified zodiac census TSVs (`298` labelled rows, `299` figures including unlabelled Gemini `K`), IVTFF structural notes, and read-only `research register` findings.",
        "",
        "---",
        "",
        "## 1. Historical Comparator Subdivision Catalog",
        "",
        "### A. Two-Half Splits (`15°` / Beginning-vs-End / Day-vs-Night / Waxing-vs-Waning / Half-Year)",
        "- **Vatican, BAV, Pal. lat. 1373 (`ff.134v–146r`)**: 24 pages, **2 pages per sign (`15+15`)** across all 12 signs; each page is a `3×5` grid of 15 square-in-square house-equation cells with red degree numerals `1–15` on the first page (e.g. `f.134v` Aries `1–15`) and `16–30` on the second (e.g. `f.142r` Scorpio `16–30`). Alfonsine tables also use `15° = 1 hour` conversion.",
        "- **Cambridge, Gonville & Caius MS 336/725**:",
        "  - `f.128v` (Aries Moonbook): explicit prose beginning-vs-end split — *\"in the begynnynges of Aries\"* vs *\"in the ende as in the begynnyng\"* (no numeric `15°` threshold in the Moonbook prose).",
        "  - `ff.163v–168r` (Ascendant & House Equation tables): continuous `1°` solar/ascendant lookup across `30°`. Tested across `14°–17°` Aries (`f.164r` noon solar → Leo rising `7°, 8°, 9°, 9°`; `f.165v` rising → House II Taurus `13°, 14°, 14°, 15°`), showing smooth rounding rather than a `15°` regime break. Compared against `Pal. lat. 1373 f.134v`: `2/5` cells match exactly, `3/5` differ by `1°`.",
        "  - `f.105v` & `ff.168v–172r`: day vs night boundary (`\"Tabula ad sciendum quis planeta regnat in omni hora in equali incipiendo diem ab ortus solis\"` / `\"Hore noctis incipiendo noctem ab occusu soli\"`; day sunrise/unequal-hour tables `168v–170r` vs night tables `170v–172r`).",
        "- **Cambridge, Trinity College, MS O.7.20 (`f.1:17v`)**: binary `Directe oritur` vs `Indirecte oritur` rising flag in the outermost cell of each of the 12 sign rows.",
        "- **Prague, NK I F 35 (`f.26r`, `f.24r`)**: explicit half-sign prose split in Libra — *\"maxime in prima medietate ipsius ... luna ab aliunde non impedita\"* (`f.26r`); Sagittarius excludes *\"the last part of Sagittarius\"* (`f.24r`).",
        "- **Munich, BSB, Cgm 415 (`ff.326v–327r`) vs Cgm 561 (`ff.154r–163r`)**: `Cgm 415 f.326v` reverses the Moon↔Sun arc between day and night births (`Moon→Sun` by night, `Sun→Moon` by day). Non-astronomical control `Cgm 561` carries 24h vs 36h furnace-state durations.",
        "- **Munich, BSB, Cgm 7958 (`f.10r` / `pp.24–28`)**: binary day-half split of baptismal names into Our Lady's brothers (Tue/Thu/Sat + Sunday afternoon) vs St. George's brothers (Mon/Wed/Fri + Sunday before noon), plus a `12-hour × 2 (AM/PM) × 2 (L/R)` wound matrix.",
        "- **Heidelberg, UB, Cpg 5 (`f.16v`)**: seasonal half-year arm switch (`glentz`/`sumer` right arm vs `herbst`/`winter` left arm).",
        "- **Heidelberg, UB, Cpg 557 (`f.77v`) & Cpg 213 (`f.155r`)**: waning-moon treatment gate — *\"So sol der mon sein in dem ab neme\"*.",
        "- **New York, Morgan MS B.27 (`f.56v`)**: 30-slot waxing/waning moonshine ring — *\"Das ist die zunemung des mans vnd die abnemung wie lang er all nacht scheinet\"*.",
        "- **Berlin, SBB, Ms. germ. fol. 1191 (`f.42v`, `f.44v`, `f.144v`)**: half-units appear in prose phrases (*\"Halb drucken halb regen\"*, *\"Ein halbs ior\"* on `f.44v`; *\"half wet\"* on `f.42v`), never as half-hour table slots; on `f.144v`, all 12 signs split across 12h pairs (`I/XIII` through `XII/XXIIII`).",
        "- **Wellcome MS 16 (`f.12v–13r`)**: 4 moon quarters tied to age/complexion; half/quarter hours appear only as step durations (`quasi ad mediam horam`, `F-719`).",
        "- **Collange (1561, `f.263r+`) / Trithemius (1518)**: 13 cipher wheels; 4 *recta* + 4 *aversa* wheels each carry 6 alphabets split into `2×12` half-rows (`24` positions read via alidade + external key; cryptographic comparator only).",
        "",
        "### B. Three-Part (`10°` Decan / Face) Splits",
        "- **Tübingen, UB, Cod. Md 2 (`ff.51r–144v`, `f.323v`)**: all 12 sign chapters carry 3 decan sub-entries (*\"Wer geboren wirt In dem ersten angesichte\"* / `andern` / `dritten angesichte`, `10°` each); `f.323v` draws a concentric `12 + 12 + 12 = 36` wheel (Scotus 36 decans, `F-95`). Note contrast: Aquarius `f.133r–v` also partitions bodily prose into 4 zones (`Heubt` / `Libe` / `ende` / `nature des menschen`).",
        "- **Vatican, BAV, Pal. lat. 1373 (`f.110v`)**: 12 signs × 3 faces of `10°` each, with a planet assigned to each face (below 16 fixed stars).",
        "- **Cambridge, Gonville & Caius MS 336/725 (`f.44r`)**: defines the 5 planetary dignities (*\"in his face .i.\"*), where faces divide each sign into three `10°` portions (`CAIUS-Z01`).",
        "- **Cambridge, Trinity College, MS O.7.20 (`f.1:17v`)**: rubricated wheel *\"Per hanc figuram scies domos exaltaciones tripli[cita]tes [...] et facies planetarum ad signa\"* (`10` concentric rings × `12` sign rows of `8` cells).",
        "- **Vatican, BAV, Pal. lat. 1369 (`f.54r`, FA-001 corrected)**: gridded quadrant instrument with two concentric zodiac rings graduated explicitly at **`10, 20, 30`** degrees.",
        "- **Vatican, BAV, Pal. lat. 1370 (`f.60v`)**: `36`-activity × `12`-sign election table (`F-696` context).",
        "- **Heidelberg, UB, Cpg 557 (`ff.84v–88r`)**: `36` venesection sites (anatomical list, not `10°` decans).",
        "",
        "### C. Degree (`30°` / 30-Day), 28-Mansion, 12/24-Hour, and Ascendant-House Systems",
        "- **`30°` sign / `30`-day lunar systems**: `Cgm 415 f.327r` (`30°` sign, `60'` degree, `29d 12h 45m` lunation); `Cgm 75 f.5r` (`\"Abrill hat 30 tag\"`, red `Stier` ingress at April 11); `Pal. lat. 1373 ff.134v–146r` (`360` single-degree cells) & `f.116r` (30-day Sept); `Pal. lat. 1369 f.62r` (`30`-tick wheel); `Pal. lat. 1438 ff.65r, 85r` (30-day aspectaria) & `f.129r` (daily planet positions by sign and degree with saints' days, FA-001 corrected); `Morgan B.27 f.56v` (`30`-slot moonshine ring); `Wellcome MS 49 f.45r` (`1–29` + sun face = `30` phase slots); `Wellcome MS 438 pp.397–411` (`30` moon-age prognostics); `Wellcome MS 349 ff.25r–26r` & `Cgm 7958 f.15r` (cast-out divisor `30`, `F-749`); `Prague I F 35 f.13v` (30 moon days parted among 12 signs); `Md 2 ff.1r–6v` (`30`-day lunar month headings).",
        f"- **24-hour / 12-hour wheels & grids**: `Berlin Ms. germ. fol. 1191 f.144v` (`{hist['berlin_f144v']['radial_columns_total']}` radial columns: `{hist['berlin_f144v']['headings_column']}` heading wedge + `{hist['berlin_f144v']['numbered_hour_columns']}` Roman hours `I–XXIIII`; `{hist['berlin_f144v']['same_sign_pairs_12h_apart']}/12` sign pairs repeat 12h apart with `{hist['berlin_f144v']['pairs_with_same_judgment']}/12` identical judgments and `{hist['berlin_f144v']['pairs_with_distinct_quality']}/12` distinct physical qualities resolving the pair, e.g. Hour I `Aries/warm/gut` vs Hour XIII `Aries/dry/gut`) & `f.51r` (7 planetary rings × `25` cells = `24` hours + weekday header); `Prague I F 35 f.22r` (`7` planetary hour columns × weekdays); `Pal. lat. 1370 f.51r` (4-ring zodiac/month/daylight-hours wheel) & `f.57v` (planetary-hour weekday grid, FA-001 corrected); `Caius ff.105v, 163r–172r` (equal/unequal hours + ascendant/houses II–VI); `Morgan B.12 f.49r` (12-house square numbered `1–12`).",
        "- **28-mansion / 27-sidereal-day apparatus**: `Cgm 7958 ff.3r–9r` (28 mansions, mod-19 + mod-28); `Cpg 3 ff.1v–16v` (28 mansions, `29 - N` reversal, mod-28 rotating lines); `Pal. lat. 1373 f.111r` (28-row mansion quality table) & `ff.124v–125r` (28 mansions with asterisks); `Cpg 557 ff.19v–20v` & `Berlin f.22r` (`19 × 27` sidereal moon-sign tables); `Prague I F 35 ff.10r–11r` (drawn star points on mansions).",
        "- **Negative / absent sub-sign splits in remaining `/manuscripts` comparators**: `Heidelberg Cpg 597` (medical/herbal prose), `Heidelberg Cpg 291` (Hausbuch narrative + miniatures, no tables/finding tabs), `Morgan G.47` (1464 Zodiac/Vein Man folding almanac), `Morgan M.941` (1433 `sol [sign]` roundels + God-centered wheel), `LJS 449` (13 circular diagrams + 12 block medallions `ff.12r–18v`), and `Vatican Pal. lat. 1197` (medical prose/tables) carry no documented `15+15` or `10+10+10` zodiac ring subdivision in their local dissections.",
        "",
        "---",
        "",
        "## 2. Visual Boundary Marking Audit",
        "",
        "| Device Class | Historical Comparator Witnesses | MS 408 (`f67r1`–`f73v`) Observed State |",
        "|---|---|---|",
        "| **Top start cross / cross-T** | `Cgm 7958 pp.33, 35` (`cum cruce` cross-T at 12 o'clock on ≥10 volvelles, `F-218`); `f.15r` 24th cross-and-plumb cell; `Morgan B.28 ff.30r–33r` crosses above wheels | **Absent** across all zodiac and cosmological panels |",
        "| **Heading wedge / header cell** | `Berlin f.144v` 25th radial wedge; `Berlin f.51r` 25th weekday header cell per ring | **Absent** as a labelled heading column |",
        "| **Split folios + numbered degrees** | `Pal. lat. 1373 ff.134v–146r` (`2` pages/sign, `3×5` grids with red `1–15` and `16–30`) | **Split panels ONLY on Aries (`f70v1`/`f71r`) and Taurus (`f71v`/`f72r1`)** (`15+15`); **zero Arabic or Roman degree numerals** |",
        "| **Graduated degree ticks / cardinal axes** | `Pal. lat. 1369 f.54r` (`10, 20, 30` marks) & `f.62r` (`30` ticks + crossing diagonals); `Wellcome MS 49 f.45v` (`equinoctium`/`solstitium` cross-labels); `Morgan B.12 f.49r` diagonals + `1–12` | **Absent** (`f69r` has 16 sectors, `f67r2` has 12 sectors, no degree ticks or cardinal text) |",
        "| **Gaps, radial stripes & start strokes** | `Md 2 f.8r` compass construction cross; `Pal. lat. 1370 f.61v` / `Pal. lat. 1373` fore-edge paper slips | **Present as non-numeric visual breaks**: `f72v1` vertical stripe (ignoring ThP), `f71r` C1–C2 start markers, `f67r1` 11:45 ring gap, `f67r2` 8:30 dotted ray & NW line, `f69v` 11:00 gap; no fore-edge tabs/slips |",
        "| **Pigment / container & ink shifts** | `Prague I F 35 f.22r` red/black/middle inks & `22v–23r` checkerboard; `Md 2 ff.1r–6v` elemental trine roundel colors; `Wellcome MS 49 f.45r` 1–29 discs; `Morgan B.27 f.56v` dot/pip counts | **Split-pair contrast on Aries/Taurus**: `f70v1` 15/15 barrels + star tan wash vs `f71r` 1/15 barrel + 11/15 garment red + no star wash; `f71v` 15/15 tubs + 12/15 garment red vs `f72r1` 5/15 tubs + 0/15 garment red. (`f67r2` red/yellow faces; `f69r` blue/green) |",
        "| **Rotating volvelle hardware** | `Caius f.158v` (Sun/Moon pointers + phase aperture); `Trinity O.7.20 f.1:25v` (3 discs, blue thread); `Cgm 75 f.1r`; `Pal. lat. 1368 ff.1v–3r` (`Drehscheibe`) | **Absent** (static parchment drawings; no threads, pointers, or stacked paper discs) |",
        "",
        "---",
        "",
        "## 3. MS 408 Observed 12-Panel Zodiac Geometry (Direct Census)",
        "",
        "| Folio | Sign (Month Label) | Layout | Total Figures (Labelled) | Exact Ring Split (`ring` column) | `face_red` Y | `body_red` Y | Containers | Explicit `star=N` |",
        "|---|---|---|---:|---|---:|---:|---:|---:|",
    ]
    for p in ms408["panels"]:
        rc = ", ".join(f"{k}:{v}" for k, v in p["ring_counts"].items())
        fig_str = f"{p['total_figures']} ({p['labelled_rows']})" if p["unlabelled_figures"] else f"{p['total_figures']}"
        cont_str = str(p["container_count"]) if p["container_count"] is not None else "1 barrel (notes)"
        lines.append(
            f"| `{p['folio']}` | {p['sign']} (`{p['month_label']}`) | `{p['layout_type']}` | {fig_str} | `{rc}` | {p['face_red_Y']} | {p['body_red_Y']} | {cont_str} | {p['explicit_star_N']} |"
        )
    lines.extend([
        "",
        f"**Census Totals:** `{ms408['panel_count']}` panels covering `{ms408['signs_present']}` signs (`{', '.join(ms408['signs_absent'])}` absent — `F-132`, `F-152`); `{ms408['total_labelled_rows']}` labelled nymph rows (`{ms408['total_figures_including_unlabelled_K']}` figures including unlabelled Gemini `K`); **`0/12` panels exhibit a `10+10+10` decan ring split**.",
        "",
        "---",
        "",
        "## 4. Direct Model-to-MS 408 Comparison (Explains vs Fails to Explain)",
        "",
    ])
    for item in analysis["model_comparison"]:
        lines.extend([
            f"### {item['historical_model']}",
            f"- **Explains / Parallels:** {item['what_it_explains_on_ms408']}",
            f"- **Fails to Explain:** {item['what_it_fails_to_explain_on_ms408']}",
            "",
        ])

    lines.extend([
        "---",
        "",
        "## 5. Substrate DB Cross-Check (`research register`, read-only)",
        f"- Verified table counts: `manuscripts={analysis['substrate_db']['table_counts']['manuscripts']}`, `findings={analysis['substrate_db']['table_counts']['findings']}`, `folio_substrate={analysis['substrate_db']['table_counts']['folio_substrate']}`, `citations={analysis['substrate_db']['table_counts']['citations']}`, `relationships={analysis['substrate_db']['table_counts']['relationships']}`.",
        "- Relevant settled findings:",
    ])
    for f in analysis["substrate_db"]["key_findings"]:
        lines.append(f"  - `F-{f['id']}` (`{f['status']}`): {f['title']}")

    lines.extend([
        "",
        "## 6. Verdict",
        "Historical comparators robustly document **two-half (`15+15` / beginning-vs-end / day-vs-night / waxing-vs-waning)** splits, **three-part (`10°` decan)** splits, **`30°`/`30`-day** counts, **`28`-mansion** cycles, and **`24`-hour dual-ring** tables — **but no single historical model reproduces MS 408's 12-panel zodiac architecture**. In particular: (1) `10+10+10` decan arithmetic is directly falsified across all 12 MS 408 panels (`0/12` decanic panels; non-decanic inner/outer counts `19+10`, `5+15+9`, `12+11+7`, `20+10`, `18+12`, `4+16+10`), and (2) historical `15+15` degree splits (`Pal. lat. 1373 ff.134v–146r`) divide *all 12 signs symmetrically* with explicit degree numerals `1–15`/`16–30`, leaving MS 408's selective `15+15` split of **only Aries and Taurus** (distinguished by pigment/tubs without numerals) and its omission of Capricorn/Aquarius historically unexplained by any comparator currently on disk.",
        "",
    ])
    return "\n".join(lines)


def main() -> None:
    W2_DIR.mkdir(parents=True, exist_ok=True)
    (W2_DIR / "scripts").mkdir(parents=True, exist_ok=True)

    source_verification = verify_sources()
    ms408_census = compute_ms408_zodiac_census()
    historical_metrics = compute_historical_metrics()
    substrate_db = query_substrate_db()
    comparator_catalog = build_comparator_catalog()
    model_comparison = build_model_comparison(ms408_census)

    analysis: Dict[str, Any] = {
        "witness_id": "w2_hour_deg15_boundary",
        "generated_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
        "source_verification": source_verification,
        "ms408_zodiac_census": ms408_census,
        "historical_metrics": historical_metrics,
        "comparator_catalog": comparator_catalog,
        "model_comparison": model_comparison,
        "substrate_db": substrate_db,
        "verdict": {
            "decan_10_10_10_supported_on_ms408": False,
            "uniform_15_15_supported_on_ms408": False,
            "selective_aries_taurus_15_15_explained_by_local_comparators": False,
            "summary": (
                "Local comparators attest 15+15 sign splits (uniformly across all 12 signs, Pal. lat. 1373), "
                "beginning-vs-end prose splits (Caius 128v, Prague 26r), 10-degree decans (Md 2, Pal. lat. 1373, Caius, Pal. lat. 1369), "
                "30-degree/30-day cycles, 28-mansion cycles, and 24-hour paired wheels (Berlin f.144v), "
                "but none explains MS 408's selective 15+15 split of only Aries & Taurus paired with 8 unequal-ring 29/30-figure single panels and absent Capricorn/Aquarius."
            ),
        },
    }

    ANALYSIS_PATH.write_text(json.dumps(analysis, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    RESULT_PATH.write_text(render_result_md(analysis), encoding="utf-8")

    # Build receipt over all generated/present files inside W2_DIR (excluding RECEIPT.json itself, then writing RECEIPT.json)
    tracked_files = sorted(
        p for p in W2_DIR.rglob("*")
        if p.is_file() and p != RECEIPT_PATH and "__pycache__" not in p.parts
    )
    receipt = {
        "witness_id": "w2_hour_deg15_boundary",
        "generated_utc": analysis["generated_utc"],
        "output_dir": str(W2_DIR),
        "files": [
            {
                "relpath": str(p.relative_to(W2_DIR)),
                "path": str(p),
                "bytes": p.stat().st_size,
                "sha256": sha256_file(p),
            }
            for p in tracked_files
        ],
    }
    RECEIPT_PATH.write_text(json.dumps(receipt, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"W2 generated successfully: {len(receipt['files'])} tracked files + RECEIPT.json")


if __name__ == "__main__":
    main()
