#!/usr/bin/env python3 """ Atomic Rollback & Forward Migration Script for Option #4 (Hybrid Numogrammatic Curve). Reads /workspace/ingglish-hyperdope-gematria/option-4-curve-migration-manifest.json, verifies SHA-256 digests of all 14 workspace/archive Markdown files before writing, and regenerates all 7 PDFs atomically. Usage: python3 /workspace/ingglish-hyperdope-gematria/reconstruct_option4_curve.py --status python3 /workspace/ingglish-hyperdope-gematria/reconstruct_option4_curve.py --to-pre-curve [--dry-run] python3 /workspace/ingglish-hyperdope-gematria/reconstruct_option4_curve.py --to-option-4 [--dry-run] """ import argparse import hashlib import json import os import re import sys from pathlib import Path REPO_ROOT = "/workspace/ingglish-hyperdope-gematria" if os.path.exists("/workspace/ingglish-hyperdope-gematria") else str(Path(__file__).resolve().parent) MANIFEST_PATH = os.path.join(REPO_ROOT, "option-4-curve-migration-manifest.json") def sha256_str(s: str) -> str: return hashlib.sha256(s.encode("utf-8")).hexdigest() def render_md_to_pdf(md_path: str, pdf_path: str) -> None: from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, HRFlowable from xml.sax.saxutils import escape def fmt_inline(text): text = escape(text) text = text.replace("Δ", 'D') text = text.replace("μ", 'm') text = text.replace("σ", 's') text = text.replace("π", 'p') text = ( text.replace("⁴", "4") .replace("⁵", "5") .replace("⁶", "6") .replace("⁷", "7") ) code_spans = [] def _save_code(m): idx = len(code_spans) code_spans.append(f'{m.group(1)}') return f"\x00CODE{idx}\x00" text = re.sub(r"`([^`]+)`", _save_code, text) text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) text = re.sub(r"\*([^*]+)\*", r"\1", text) for idx, span in enumerate(code_spans): text = text.replace(f"\x00CODE{idx}\x00", span) return text def add_page_number(canvas, doc): canvas.saveState() canvas.setFont("Helvetica", 9) canvas.setFillColor(colors.HexColor("#555555")) canvas.drawRightString(letter[0] - 54, 36, f"Page {doc.page}") canvas.restoreState() with open(md_path, "r", encoding="utf-8") as f: lines = f.read().splitlines() doc = SimpleDocTemplate( pdf_path, pagesize=letter, leftMargin=54, rightMargin=54, topMargin=54, bottomMargin=54, ) styles = getSampleStyleSheet() h1 = ParagraphStyle( "H1", parent=styles["Heading1"], fontName="Helvetica-Bold", fontSize=15, leading=19, spaceAfter=8, textColor=colors.HexColor("#111111"), ) h2 = ParagraphStyle( "H2", parent=styles["Heading2"], fontName="Helvetica-Bold", fontSize=12.5, leading=16, spaceBefore=10, spaceAfter=6, textColor=colors.HexColor("#1a1a1a"), ) h3 = ParagraphStyle( "H3", parent=styles["Heading3"], fontName="Helvetica-Bold", fontSize=10.5, leading=14, spaceBefore=8, spaceAfter=4, textColor=colors.HexColor("#222222"), ) body = ParagraphStyle( "Body", parent=styles["Normal"], fontName="Helvetica", fontSize=9.5, leading=13.5, spaceAfter=5, ) bullet = ParagraphStyle("Bullet", parent=body, leftIndent=14, firstLineIndent=-8, spaceAfter=4) subbullet = ParagraphStyle("SubBullet", parent=body, leftIndent=28, firstLineIndent=-8, spaceAfter=3) subsubbullet = ParagraphStyle("SubSubBullet", parent=body, leftIndent=42, firstLineIndent=-8, spaceAfter=3) story = [] headers = [] in_table = False for line in lines: s = line.strip() if not s: in_table = False headers = [] continue if s == "---": story.append(Spacer(1, 4)) story.append(HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#cccccc"))) story.append(Spacer(1, 4)) continue if s.startswith("|") and s.endswith("|"): cells = [c.strip() for c in s.strip("|").split("|")] if all(re.match(r"^:?-+:?$", c) for c in cells): in_table = True continue if not in_table and not headers: headers = cells continue else: parts = [] for h, val in zip(headers, cells): h_clean = re.sub(r"\*\*([^*]+)\*\*", r"\1", h) parts.append(f"**{h_clean}:** {val}") row_text = " | ".join(parts) story.append(Paragraph("• " + fmt_inline(row_text), bullet)) continue else: in_table = False headers = [] if s.startswith("# "): story.append(Paragraph(fmt_inline(s[2:]), h1)) elif s.startswith("## "): story.append(Paragraph(fmt_inline(s[3:]), h2)) elif s.startswith("### "): story.append(Paragraph(fmt_inline(s[4:]), h3)) elif re.match(r"^\d+\.\s+", s): story.append(Paragraph(fmt_inline(s), bullet)) elif line.startswith(" - "): story.append(Paragraph("· " + fmt_inline(s[2:]), subsubbullet)) elif line.startswith(" - ") or line.startswith(" - "): story.append(Paragraph("– " + fmt_inline(s[2:]), subbullet)) elif s.startswith("- "): story.append(Paragraph("• " + fmt_inline(s[2:]), bullet)) else: story.append(Paragraph(fmt_inline(s), body)) doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number) def main(): parser = argparse.ArgumentParser(description="Atomic Option 4 Curve Reconstructor") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--status", action="store_true", help="Check current SHA-256 state of all tracked files") group.add_argument("--to-pre-curve", action="store_true", help="Atomically reconstruct pre-Option-4 uncurved state") group.add_argument("--to-option-4", action="store_true", help="Atomically apply Option 4 Hybrid Numogrammatic Curve") parser.add_argument("--dry-run", action="store_true", help="Verify transformation and SHA-256 hashes without writing") args = parser.parse_args() with open(MANIFEST_PATH, "r", encoding="utf-8") as f: manifest = json.load(f) if args.status: for rec in manifest["files"]: path = rec["path"] with open(path, "r", encoding="utf-8") as f: cur_sha = sha256_str(f.read()) if cur_sha == rec["post_sha256"]: state = "OPTION-4 (Post-Curve)" elif cur_sha == rec["pre_sha256"]: state = "PRE-CURVE (Uncurved Raw)" else: state = f"MODIFIED ({cur_sha[:12]})" print(f"{path:68s} -> {state}") return target_mode = "pre" if args.to_pre_curve else "post" staged_writes = {} for rec in manifest["files"]: path = rec["path"] with open(path, "r", encoding="utf-8") as f: content = f.read() cur_sha = sha256_str(content) expected_target_sha = rec["pre_sha256"] if target_mode == "pre" else rec["post_sha256"] if cur_sha == expected_target_sha: staged_writes[path] = content continue new_content = content for hunk in rec["hunks"]: src_blk = hunk["post"] if target_mode == "pre" else hunk["pre"] dst_blk = hunk["pre"] if target_mode == "pre" else hunk["post"] if src_blk not in new_content: print(f"ABORT: Expected hunk missing in {path}", file=sys.stderr) sys.exit(1) new_content = new_content.replace(src_blk, dst_blk, 1) new_sha = sha256_str(new_content) if new_sha != expected_target_sha: print( f"ABORT: SHA-256 mismatch on {path}: got {new_sha}, expected {expected_target_sha}", file=sys.stderr, ) sys.exit(1) staged_writes[path] = new_content print(f"All {len(staged_writes)} files verified against target '{target_mode}' SHA-256 digests.") if args.dry_run: print("Dry-run complete: 0 files written.") return # Atomic write via temporary files + os.replace for path, new_content in staged_writes.items(): tmp_path = path + ".tmp_atomic" with open(tmp_path, "w", encoding="utf-8") as f: f.write(new_content) os.replace(tmp_path, path) # Regenerate workspace PDFs pdf_stems = [ "30-eval-the-thing-bidirectional", "31-eval-the-dark-tower-bidirectional", "32-eval-typhonian-entities-bidirectional", "33-eval-theorists-and-philosophers-bidirectional", "34-eval-bellows-lungs-voices-bidirectional", "35-eval-news-2026-11-01-bidirectional", "curve-grading-options-evaluation", ] for stem in pdf_stems: render_md_to_pdf(os.path.join(REPO_ROOT, f"{stem}.md"), os.path.join(REPO_ROOT, f"{stem}.pdf")) print(f"Successfully transitioned all 14 Markdown files and 7 PDFs to '{target_mode}' state.") if __name__ == "__main__": main()