Files
ingglish-hyperdope-gematria/reconstruct_option4_curve.py
T

253 lines
9.1 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Atomic Rollback & Forward Migration Script for Option #4 (Hybrid Numogrammatic Curve).
Reads /workspace/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/reconstruct_option4_curve.py --status
python3 /workspace/reconstruct_option4_curve.py --to-pre-curve [--dry-run]
python3 /workspace/reconstruct_option4_curve.py --to-option-4 [--dry-run]
"""
import argparse
import hashlib
import json
import os
import re
import sys
MANIFEST_PATH = "/workspace/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("Δ", '<font name="Symbol">D</font>')
text = text.replace("μ", '<font name="Symbol">m</font>')
text = text.replace("σ", '<font name="Symbol">s</font>')
text = text.replace("π", '<font name="Symbol">p</font>')
text = (
text.replace("⁴", "<super>4</super>")
.replace("⁵", "<super>5</super>")
.replace("⁶", "<super>6</super>")
.replace("⁷", "<super>7</super>")
)
text = re.sub(r"`([^`]+)`", r'<font name="Courier">\1</font>', text)
text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
text = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", text)
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(f"/workspace/{stem}.md", f"/workspace/{stem}.pdf")
print(f"Successfully transitioned all 14 Markdown files and 7 PDFs to '{target_mode}' state.")
if __name__ == "__main__":
main()