| 1 | #!/usr/bin/env python3 |
| 2 | """Build the report as a reflowable EPUB, with offline citation navigation. |
| 3 | |
| 4 | Requires Python 3, Pandoc 3, and rsvg-convert. EPUBCheck can validate the output. |
| 5 | The Markdown report remains the source; presentation changes happen in the AST. |
| 6 | """ |
| 7 | |
| 8 | import argparse |
| 9 | import copy |
| 10 | import json |
| 11 | from pathlib import Path |
| 12 | import re |
| 13 | import subprocess |
| 14 | import tempfile |
| 15 | from urllib.parse import unquote, urlsplit |
| 16 | from xml.etree import ElementTree |
| 17 | from zipfile import ZipFile |
| 18 | |
| 19 | HERE = Path(__file__).resolve().parent |
| 20 | REPORT = HERE.parent |
| 21 | REPO = REPORT.parent.parent |
| 22 | FILES = [ |
| 23 | "README.md", |
| 24 | "01-project-and-problem-map.md", |
| 25 | "02-existing-systems.md", |
| 26 | "03-verification-and-integration.md", |
| 27 | "04-events-trust-and-durability.md", |
| 28 | "05-knowledge-agents-and-outcomes.md", |
| 29 | "06-synthesis-and-research-agenda.md", |
| 30 | "07-reading-guide-and-glossary.md", |
| 31 | "sources-systems.md", |
| 32 | "sources-verification.md", |
| 33 | "sources-distributed.md", |
| 34 | "sources-agents.md", |
| 35 | ] |
| 36 | TITLES = { |
| 37 | "README.md": "Overview and principal findings", |
| 38 | "03-verification-and-integration.md": "3. Verification that can travel with a change", |
| 39 | "04-events-trust-and-durability.md": "4. Events, trust, and durability", |
| 40 | "05-knowledge-agents-and-outcomes.md": "5. Knowledge, agents, and outcomes", |
| 41 | "sources-systems.md": "Sources S: architecture and existing systems", |
| 42 | "sources-verification.md": "Sources V: verification and integration", |
| 43 | "sources-distributed.md": "Sources D: events, trust, and durability", |
| 44 | "sources-agents.md": "Sources A: knowledge, agents, and outcomes", |
| 45 | } |
| 46 | INTRO = """# About this reading edition |
| 47 | |
| 48 | This edition contains the complete research report and its annotated sources. It is |
| 49 | prepared for a Kindle Scribe, with adjustable text and a linked table of contents. |
| 50 | The research is dated September 20, 2026. |
| 51 | |
| 52 | Start with the overview and chapter 6 for the main judgments. Read the chapters in |
| 53 | order for the full argument. Chapter 7 offers a route through the original literature. |
| 54 | |
| 55 | Citations bearing an S, V, D, or A source number link to the annotation included in this |
| 56 | book. The annotation retains the link to the original publication, which needs an |
| 57 | internet connection. Use the reader's Back command to return after following a link. |
| 58 | |
| 59 | Compact comparison tables remain tables. Dense tables are presented as a sequence of |
| 60 | labeled entries, and the architecture diagram is rendered as a list of connections. |
| 61 | Repository references appear as notes containing the original file paths. Those source |
| 62 | files are not included; they refer to the report's inspected repository snapshot, |
| 63 | `5bb3a7736fe49b0cc4914299b142c0c9bafb6870`. |
| 64 | """ |
| 65 | |
| 66 | |
| 67 | def node(kind, content): |
| 68 | return {"t": kind, "c": content} |
| 69 | |
| 70 | |
| 71 | def words(text): |
| 72 | result = [] |
| 73 | for word in text.split(): |
| 74 | if result: |
| 75 | result.append({"t": "Space"}) |
| 76 | result.append(node("Str", word)) |
| 77 | return result |
| 78 | |
| 79 | |
| 80 | def plain(value): |
| 81 | if isinstance(value, list): |
| 82 | return "".join(map(plain, value)) |
| 83 | if not isinstance(value, dict): |
| 84 | return "" |
| 85 | kind = value["t"] |
| 86 | if kind == "Str": |
| 87 | return value["c"] |
| 88 | if kind in ("Space", "SoftBreak", "LineBreak"): |
| 89 | return " " |
| 90 | if kind == "Code": |
| 91 | return value["c"][1] |
| 92 | if kind in ("Link", "Image", "Span"): |
| 93 | return plain(value["c"][1]) |
| 94 | return plain(value.get("c", [])) |
| 95 | |
| 96 | |
| 97 | def div(blocks, css_class): |
| 98 | return node("Div", [["", [css_class], []], blocks]) |
| 99 | |
| 100 | |
| 101 | def parse(pandoc, text): |
| 102 | return json.loads(subprocess.check_output( |
| 103 | [pandoc, "--from=gfm", "--to=json"], input=text.encode() |
| 104 | )) |
| 105 | |
| 106 | |
| 107 | def cell_inlines(cell): |
| 108 | # The report's pipe-table cells contain only inline paragraphs. Fail if a |
| 109 | # future table uses richer content rather than silently dropping it. |
| 110 | result = [] |
| 111 | if cell[2:4] != [1, 1]: |
| 112 | raise ValueError("Spanning table cells require an explicit reading layout") |
| 113 | for block in cell[4]: |
| 114 | if block["t"] not in ("Plain", "Para"): |
| 115 | raise ValueError("A table cell contains unsupported block content") |
| 116 | if result: |
| 117 | result.append({"t": "Space"}) |
| 118 | result.extend(block["c"]) |
| 119 | return result |
| 120 | |
| 121 | |
| 122 | def table_layout(table, stats, compatibility=False): |
| 123 | attr, caption, specs, head, bodies, foot = table["c"] |
| 124 | if caption != [None, []] or foot[1] or any(body[2] for body in bodies): |
| 125 | raise ValueError("A table has captions or row groups requiring explicit handling") |
| 126 | headers = [cell_inlines(cell) for cell in head[1][0][1]] |
| 127 | rows = [[cell_inlines(cell) for cell in row[1]] |
| 128 | for body in bodies for row in body[3]] |
| 129 | lengths = [[len(plain(cell)) for cell in row] for row in [headers] + rows] |
| 130 | compact = (not compatibility and len(headers) <= 3 and max(map(max, lengths)) <= 95 |
| 131 | and max(map(sum, lengths)) <= 180) |
| 132 | if compact: |
| 133 | # Give prose more space while reserving enough width in every column |
| 134 | # for enlarged type on the Scribe. |
| 135 | weights = [max(12, max(row[i] for row in lengths)) ** 0.7 |
| 136 | for i in range(len(headers))] |
| 137 | total = sum(weights) |
| 138 | floor = 0.24 if len(headers) == 3 else 0.28 |
| 139 | remainder = 1 - floor * len(headers) |
| 140 | table["c"][2] = [[spec[0], node("ColWidth", floor + remainder * weight / total)] |
| 141 | for spec, weight in zip(specs, weights)] |
| 142 | stats["compact_tables"] += 1 |
| 143 | return table |
| 144 | records = [] |
| 145 | for row in rows: |
| 146 | if len(row) != len(headers): |
| 147 | raise ValueError("Table row width does not match its header") |
| 148 | title = div([node("Para", [node("Strong", row[0])])], "record-title") |
| 149 | fields = [title] |
| 150 | for header, cell in zip(headers[1:], row[1:]): |
| 151 | label = node("Strong", header + [node("Str", ":")]) |
| 152 | fields.append(div([node("Para", [label, {"t": "Space"}] + cell)], |
| 153 | "record-field")) |
| 154 | records.append(div(fields, "table-record")) |
| 155 | stats["stacked_tables"] += 1 |
| 156 | stats["stacked_rows"] += len(rows) |
| 157 | return div(records, "stacked-table") |
| 158 | |
| 159 | |
| 160 | def diagram_as_list(code, stats): |
| 161 | labels = dict(re.findall(r'(\w+)\["([^"]+)"\]', code)) |
| 162 | edges = [] |
| 163 | for line in code.splitlines()[1:]: |
| 164 | match = re.fullmatch( |
| 165 | r'\s*(\w+)(?:\["[^"]+"\])? --> (\w+)(?:\["[^"]+"\])?\s*', line |
| 166 | ) |
| 167 | if not match: |
| 168 | raise ValueError(f"Unrecognized diagram connection: {line}") |
| 169 | left, right = match.groups() |
| 170 | edges.append([node("Plain", words(labels[left] + " → " + labels[right]))]) |
| 171 | stats["diagram_connections"] += len(edges) |
| 172 | return div([ |
| 173 | node("Para", [node("Strong", words("Information flow"))]), |
| 174 | node("Para", words("Each arrow means that the receiving stage needs information " |
| 175 | "from the preceding stage. The connections are:")), |
| 176 | node("BulletList", edges), |
| 177 | ], "diagram-reading") |
| 178 | |
| 179 | |
| 180 | def kindle_cover(path): |
| 181 | # Pandoc wraps the raster cover in SVG. Use a plain image so the delivered |
| 182 | # book does not depend on Amazon's handling of embedded SVG. |
| 183 | with ZipFile(path) as archive: |
| 184 | contents = [(entry, archive.read(entry.filename)) for entry in archive.infolist()] |
| 185 | with ZipFile(path, "w") as archive: |
| 186 | for entry, data in contents: |
| 187 | if entry.filename.endswith("/text/cover.xhtml"): |
| 188 | text = data.decode() |
| 189 | image = re.search(r'xlink:href="([^"]+)"', text) |
| 190 | if not image: |
| 191 | raise ValueError("Pandoc's cover structure has changed") |
| 192 | text = re.sub(r'<svg\b.*?</svg>', |
| 193 | '<img src="' + image.group(1) + '" ' |
| 194 | 'alt="the-valley: Foundations and Research Opportunities" />', |
| 195 | text, flags=re.S) |
| 196 | data = text.encode() |
| 197 | elif entry.filename.endswith("/content.opf"): |
| 198 | data = data.replace(b' properties="svg"', b'') |
| 199 | archive.writestr(entry, data) |
| 200 | |
| 201 | |
| 202 | def normalize_navigation(path): |
| 203 | # Keep the legacy NCX's declared depth consistent with its actual tree. |
| 204 | # Its optional, nonstandard cover hint is unnecessary: the OPF owns that |
| 205 | # information, and Pandoc's hint can name an image ID that does not exist. |
| 206 | namespace = "{http://www.daisy.org/z3986/2005/ncx/}" |
| 207 | |
| 208 | def depth(element): |
| 209 | children = element.findall(namespace + "navPoint") |
| 210 | return 1 + max(map(depth, children), default=0) if children else 0 |
| 211 | |
| 212 | with ZipFile(path) as archive: |
| 213 | contents = [(entry, archive.read(entry.filename)) for entry in archive.infolist()] |
| 214 | with ZipFile(path, "w") as archive: |
| 215 | for entry, data in contents: |
| 216 | if entry.filename.endswith(".ncx"): |
| 217 | text = data.decode() |
| 218 | nav = ElementTree.fromstring(text).find(namespace + "navMap") |
| 219 | text = re.sub(r'(<meta name="dtb:depth" content=")\d+("\s*/>)', |
| 220 | lambda match: match[1] + str(depth(nav)) + match[2], text) |
| 221 | text = re.sub(r'\s*<meta name="cover"[^>]*/>', "", text) |
| 222 | data = text.encode() |
| 223 | archive.writestr(entry, data) |
| 224 | |
| 225 | |
| 226 | def main(): |
| 227 | parser = argparse.ArgumentParser(description=__doc__) |
| 228 | parser.add_argument("--pandoc", default="pandoc") |
| 229 | parser.add_argument("--rsvg-convert", default="rsvg-convert") |
| 230 | parser.add_argument("--epubcheck", help="Optional EPUBCheck executable") |
| 231 | parser.add_argument("--compatibility", action="store_true", |
| 232 | help="Build EPUB 2 with plain layouts and ordinary reference links") |
| 233 | parser.add_argument("--output", type=Path) |
| 234 | parser.add_argument("--title", help="Optional title for a distinct revised edition") |
| 235 | parser.add_argument("--identifier", help="Optional EPUB identifier for a distinct revised edition") |
| 236 | parser.add_argument("--preview", type=Path, help="Optional standalone HTML preview") |
| 237 | args = parser.parse_args() |
| 238 | if args.output is None: |
| 239 | filename = "the-valley-research-compatibility.epub" if args.compatibility else "the-valley-research.epub" |
| 240 | args.output = REPORT / filename |
| 241 | docs = {name: parse(args.pandoc, (REPORT / name).read_text()) for name in FILES} |
| 242 | ids = {} |
| 243 | starts = {} |
| 244 | sources = {} |
| 245 | for index, (name, doc) in enumerate(docs.items()): |
| 246 | prefix = f"report-{index:02d}-" |
| 247 | for block in doc["blocks"]: |
| 248 | if block["t"] == "Header": |
| 249 | level, attr, title = block["c"] |
| 250 | old = attr[0] |
| 251 | attr[0] = f"h{len(ids) + 1:04d}" if args.compatibility else prefix + old |
| 252 | ids[(name, old)] = attr[0] |
| 253 | if level == 1: |
| 254 | starts[name] = attr[0] |
| 255 | if name in TITLES: |
| 256 | block["c"][2] = words(TITLES[name]) |
| 257 | match = re.match(r"([SVDA]\d{2})\b", plain(title)) |
| 258 | if name.startswith("sources-") and match: |
| 259 | sources[match.group(1)] = attr[0] |
| 260 | if name.startswith("sources-") and level > 1: |
| 261 | # Direct citation links retain all entry anchors without |
| 262 | # turning the contents into a second 106-entry bibliography. |
| 263 | attr[1].append("unlisted") |
| 264 | # Local numbering in these chapters becomes book numbering. |
| 265 | if name[:2] in ("03", "04", "05") and level == 2: |
| 266 | text = plain(title) |
| 267 | if re.match(r"\d+\. ", text): |
| 268 | block["c"][2] = words(f"{int(name[:2])}." + text) |
| 269 | stats = {key: 0 for key in ("compact_tables", "stacked_tables", "stacked_rows", |
| 270 | "diagram_connections", "offline_citations", |
| 271 | "repository_notes")} |
| 272 | repository_refs = {} |
| 273 | |
| 274 | def transform(value, name): |
| 275 | if isinstance(value, list): |
| 276 | return [transform(item, name) for item in value] |
| 277 | if not isinstance(value, dict): |
| 278 | return value |
| 279 | kind = value.get("t") |
| 280 | if kind == "Link": |
| 281 | attr, label, target = copy.deepcopy(value["c"]) |
| 282 | url, title = target |
| 283 | source = re.search(r"\b([SVDA]\d{2})\b", plain(label)) |
| 284 | if source and source.group(1) in sources and not name.startswith("sources-"): |
| 285 | stats["offline_citations"] += 1 |
| 286 | return node("Link", [attr, label, ["#" + sources[source.group(1)], title]]) |
| 287 | parts = urlsplit(url) |
| 288 | if parts.scheme or parts.netloc: |
| 289 | return value |
| 290 | dest = ((REPORT / name).parent / unquote(parts.path)).resolve() |
| 291 | if not parts.path: |
| 292 | dest = REPORT / name |
| 293 | if dest.parent == REPORT and dest.name in docs: |
| 294 | anchor = unquote(parts.fragment) |
| 295 | key = ids[(dest.name, anchor)] if anchor else starts[dest.name] |
| 296 | return node("Link", [attr, label, ["#" + key, title]]) |
| 297 | if not dest.exists() or not dest.is_relative_to(REPO): |
| 298 | raise ValueError(f"Unresolved local reference in {name}: {url}") |
| 299 | path = dest.relative_to(REPO).as_posix() |
| 300 | if dest.is_dir(): |
| 301 | path += "/" |
| 302 | if parts.fragment: |
| 303 | path += "#" + unquote(parts.fragment) |
| 304 | if args.compatibility: |
| 305 | ref_id = repository_refs.setdefault(path, f"r{len(repository_refs) + 1:03d}") |
| 306 | stats["repository_notes"] += 1 |
| 307 | reference = node("Link", [["", [], []], words(f"[{ref_id.upper()}]"), |
| 308 | ["#" + ref_id, "Repository reference"]]) |
| 309 | return node("Span", [["", [], []], label + [{"t": "Space"}, reference]]) |
| 310 | note = node("Note", [node("Para", words("Repository source:") + [ |
| 311 | {"t": "Space"}, node("Code", [["", ["repository-path"], []], path]) |
| 312 | ])]) |
| 313 | stats["repository_notes"] += 1 |
| 314 | return node("Span", [["", [], []], label + [note]]) |
| 315 | if kind == "CodeBlock" and "mermaid" in value["c"][0][1]: |
| 316 | return diagram_as_list(value["c"][1], stats) |
| 317 | mapped = {key: transform(item, name) for key, item in value.items()} |
| 318 | if kind == "Table": |
| 319 | return table_layout(mapped, stats, args.compatibility) |
| 320 | return mapped |
| 321 | |
| 322 | intro = INTRO |
| 323 | if args.compatibility: |
| 324 | intro = intro.replace( |
| 325 | "Compact comparison tables remain tables. Dense tables are presented as a sequence of\n" |
| 326 | "labeled entries, and the architecture diagram is rendered as a list of connections.\n" |
| 327 | "Repository references appear as notes containing the original file paths.", |
| 328 | "This compatibility edition presents every table as a sequence of labeled entries.\n" |
| 329 | "The architecture diagram is rendered as a list of connections. Repository references\n" |
| 330 | "link to an appendix containing the original file paths." |
| 331 | ) |
| 332 | book = parse(args.pandoc, intro) |
| 333 | for name, doc in docs.items(): |
| 334 | book["blocks"].extend(transform(doc["blocks"], name)) |
| 335 | if args.compatibility: |
| 336 | book["blocks"].append(node("Header", [1, ["repository-references", [], []], |
| 337 | words("Repository references")])) |
| 338 | book["blocks"].append(node("Para", words( |
| 339 | "These paths refer to the repository snapshot inspected for this report. " |
| 340 | "The source files are not embedded in the book. Use the reader's Back command " |
| 341 | "to return to the passage that cited a path." |
| 342 | ))) |
| 343 | for path, ref_id in repository_refs.items(): |
| 344 | book["blocks"].append(node("Div", [[ref_id, [], []], [node("Para", [ |
| 345 | node("Strong", words(ref_id.upper() + ":")), {"t": "Space"}, |
| 346 | node("Code", [["", [], []], path]) |
| 347 | ])]])) |
| 348 | metadata = { |
| 349 | "title": "the-valley: Foundations & Research Opportunities", |
| 350 | "subtitle": "A critical literature and systems review", |
| 351 | "author": "the-valley", |
| 352 | "lang": "en-US", |
| 353 | "date": "2026-09-20", |
| 354 | "identifier": "urn:uuid:fe8306ef-12c2-4975-bc95-c019a83816e1", |
| 355 | "toc-title": "Contents", |
| 356 | } |
| 357 | if args.compatibility: |
| 358 | metadata["title"] = "the-valley Research - Compatibility Edition" |
| 359 | metadata["identifier"] = "urn:uuid:3e1f6cc5-8a16-472c-bba1-a9a66f8a0e9d" |
| 360 | if args.title: |
| 361 | metadata["title"] = args.title |
| 362 | if args.identifier: |
| 363 | metadata["identifier"] = args.identifier |
| 364 | book["meta"] = {key: node("MetaString", value) for key, value in metadata.items()} |
| 365 | args.output = args.output.resolve() |
| 366 | args.output.parent.mkdir(parents=True, exist_ok=True) |
| 367 | with tempfile.TemporaryDirectory(prefix="valley-reader-") as temp: |
| 368 | cover = Path(temp) / "cover.png" |
| 369 | if not args.compatibility: |
| 370 | subprocess.run([args.rsvg_convert, "--output", str(cover), str(HERE / "cover.svg")], |
| 371 | check=True) |
| 372 | data = json.dumps(book).encode() |
| 373 | stylesheet = "compatibility.css" if args.compatibility else "reader.css" |
| 374 | common = [args.pandoc, "--from=json", "--standalone", "--toc", "--toc-depth=2", |
| 375 | "--css", str(HERE / stylesheet), "--wrap=none"] |
| 376 | epub_options = (["--to=epub2"] if args.compatibility else |
| 377 | ["--to=epub3", "--epub-cover-image", str(cover)]) |
| 378 | subprocess.run(common + epub_options + ["--split-level=1", "--output", str(args.output)], |
| 379 | input=data, check=True) |
| 380 | if args.preview: |
| 381 | subprocess.run(common + ["--to=html5", "--embed-resources", |
| 382 | "--output", str(args.preview)], input=data, check=True) |
| 383 | if not args.compatibility: |
| 384 | kindle_cover(args.output) |
| 385 | normalize_navigation(args.output) |
| 386 | if args.epubcheck: |
| 387 | subprocess.run([args.epubcheck, str(args.output)], check=True) |
| 388 | print(json.dumps({"output": str(args.output), "bytes": args.output.stat().st_size, |
| 389 | "source_documents": len(docs), "annotated_sources": len(sources), |
| 390 | **stats}, indent=2)) |
| 391 | |
| 392 | |
| 393 | if __name__ == "__main__": |
| 394 | main() |