from __future__ import annotations
import html
import json
import re
from pathlib import Path
from reportlab.graphics.shapes import Drawing, Line, Polygon, Rect, String
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.platypus import (
KeepTogether,
PageBreak,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "paper" / "paper.md"
RESULTS = ROOT / "results" / "summary.json"
OUTPUT = ROOT / "paper" / "paper.pdf"
INK = colors.HexColor("#172033")
MUTED = colors.HexColor("#5d6778")
BLUE = colors.HexColor("#2563eb")
TEAL = colors.HexColor("#0f766e")
AMBER = colors.HexColor("#b45309")
LIGHT_BLUE = colors.HexColor("#eaf1ff")
LIGHT_TEAL = colors.HexColor("#e7f6f3")
LIGHT_AMBER = colors.HexColor("#fff3df")
GRID = colors.HexColor("#d6dce6")
PAPER = colors.HexColor("#ffffff")
CONDITION_COLORS = [BLUE, AMBER, TEAL]
def load_rows() -> list[dict]:
document = json.loads(RESULTS.read_text(encoding="utf-8"))
return document["aggregates"]
def arrow(drawing: Drawing, x1: float, y1: float, x2: float, y2: float, color=INK) -> None:
drawing.add(Line(x1, y1, x2, y2, strokeColor=color, strokeWidth=1.3))
drawing.add(
Polygon(
[x2, y2, x2 - 6, y2 + 3.5, x2 - 6, y2 - 3.5],
fillColor=color,
strokeColor=color,
)
)
def architecture_figure() -> Drawing:
drawing = Drawing(500, 235)
boxes = [
(8, 138, 104, 62, LIGHT_BLUE, "Raw experience", "immutable traces"),
(132, 138, 104, 62, LIGHT_TEAL, "Pattern Registry", "support + counterexamples"),
(256, 138, 104, 62, LIGHT_AMBER, "Active Skill", "executable procedure"),
(380, 138, 104, 62, colors.HexColor("#f2edff"), "Executor", "source / target model"),
]
for x, y, w, h, fill, title, subtitle in boxes:
drawing.add(Rect(x, y, w, h, 7, 7, fillColor=fill, strokeColor=GRID, strokeWidth=1))
drawing.add(String(x + w / 2, y + 39, title, fontName="Helvetica-Bold", fontSize=9.5,
textAnchor="middle", fillColor=INK))
drawing.add(String(x + w / 2, y + 21, subtitle, fontName="Helvetica", fontSize=7.3,
textAnchor="middle", fillColor=MUTED))
arrow(drawing, 112, 169, 132, 169)
arrow(drawing, 236, 169, 256, 169)
arrow(drawing, 360, 169, 380, 169)
drawing.add(Rect(70, 44, 360, 56, 8, 8, fillColor=colors.HexColor("#f7f8fb"),
strokeColor=GRID, strokeWidth=1))
drawing.add(String(250, 80, "File protocols preserve authority boundaries",
fontName="Helvetica-Bold", fontSize=9.5, textAnchor="middle", fillColor=INK))
drawing.add(String(250, 61,
"Agent Memory: prospective plan | Guard: exact bytes | BeforeDone: final freshness",
fontName="Helvetica", fontSize=7.4, textAnchor="middle", fillColor=MUTED))
drawing.add(Line(184, 138, 184, 100, strokeColor=TEAL, strokeWidth=1.1))
drawing.add(Line(308, 138, 308, 100, strokeColor=AMBER, strokeWidth=1.1))
drawing.add(String(250, 18,
"Skill Impact Ledger forward-chains proposals, decisions, metrics, and evidence references.",
fontName="Helvetica-Oblique", fontSize=7.8, textAnchor="middle", fillColor=MUTED))
return drawing
def bar_panel(
drawing: Drawing,
x: float,
y: float,
width: float,
height: float,
title: str,
values: list[float],
maximum: float,
formatter,
) -> None:
drawing.add(String(x, y + height + 17, title, fontName="Helvetica-Bold", fontSize=8.2, fillColor=INK))
bar_height = 17
gap = 12
labels = ["No Wiki", "Flat", "Persistent"]
label_width = 48
track_x = x + label_width
track_width = width - label_width - 5
for index, (label, value) in enumerate(zip(labels, values, strict=True)):
current_y = y + height - (index + 1) * (bar_height + gap)
drawing.add(String(x, current_y + 5, label, fontName="Helvetica", fontSize=7.2, fillColor=MUTED))
drawing.add(Rect(track_x, current_y, track_width, bar_height, 3, 3,
fillColor=colors.HexColor("#eef1f5"), strokeColor=None))
length = max(1, track_width * value / maximum)
drawing.add(Rect(track_x, current_y, length, bar_height, 3, 3,
fillColor=CONDITION_COLORS[index], strokeColor=None))
text = formatter(value)
inside = stringWidth(text, "Helvetica-Bold", 6.8) + 8 < length
text_x = track_x + length - 4 if inside else track_x + length + 4
drawing.add(String(text_x, current_y + 5, text, fontName="Helvetica-Bold", fontSize=6.8,
textAnchor="end" if inside else "start",
fillColor=PAPER if inside else INK))
def results_figure() -> Drawing:
rows = {row["condition"]: row for row in load_rows()}
ordered = [rows["no_wiki"], rows["flat_history"], rows["persistent_wiki"]]
drawing = Drawing(500, 230)
bar_panel(
drawing, 8, 55, 154, 128, "Task quality (0-100)",
[row["mean_task_quality"] for row in ordered], 100,
lambda value: f"{value:.1f}",
)
bar_panel(
drawing, 173, 55, 154, 128, "Input tokens (thousands)",
[row["mean_input_tokens"] / 1000 for row in ordered], 150,
lambda value: f"{value:.1f}k",
)
bar_panel(
drawing, 338, 55, 154, 128, "Target-model Skill gain",
[row["mean_target_skill_gain"] for row in ordered], 20,
lambda value: f"{value:.1f}",
)
drawing.add(String(250, 20,
"Flat history led on quality; persistent Wiki reduced context and improved target gain relative to flat.",
fontName="Helvetica-Oblique", fontSize=7.6, textAnchor="middle", fillColor=MUTED))
return drawing
def inline_markup(text: str) -> str:
escaped = html.escape(text)
escaped = re.sub(
r"(https://[^\s<]+)",
r'\1',
escaped,
)
return escaped
def make_styles() -> dict[str, ParagraphStyle]:
base = getSampleStyleSheet()
return {
"title": ParagraphStyle(
"PaperTitle", parent=base["Title"], fontName="Helvetica-Bold", fontSize=22,
leading=25, textColor=INK, alignment=TA_LEFT, spaceAfter=8,
),
"subtitle": ParagraphStyle(
"PaperSubtitle", parent=base["Heading2"], fontName="Helvetica", fontSize=14,
leading=18, textColor=BLUE, alignment=TA_LEFT, spaceAfter=18,
),
"author": ParagraphStyle(
"Author", parent=base["Normal"], fontName="Helvetica-Bold", fontSize=10,
leading=14, textColor=INK, spaceAfter=2,
),
"meta": ParagraphStyle(
"Meta", parent=base["Normal"], fontName="Helvetica", fontSize=8.7,
leading=12, textColor=MUTED, spaceAfter=2,
),
"h1": ParagraphStyle(
"Section", parent=base["Heading1"], fontName="Helvetica-Bold", fontSize=14,
leading=17, textColor=INK, spaceBefore=14, spaceAfter=7, keepWithNext=True,
),
"h2": ParagraphStyle(
"Subsection", parent=base["Heading2"], fontName="Helvetica-Bold", fontSize=10.5,
leading=13, textColor=TEAL, spaceBefore=10, spaceAfter=5, keepWithNext=True,
),
"body": ParagraphStyle(
"Body", parent=base["BodyText"], fontName="Times-Roman", fontSize=9.3,
leading=12.2, textColor=INK, alignment=TA_JUSTIFY, spaceAfter=6,
allowWidows=0, allowOrphans=0,
),
"abstract": ParagraphStyle(
"Abstract", parent=base["BodyText"], fontName="Times-Roman", fontSize=8.8,
leading=11.6, textColor=INK, alignment=TA_JUSTIFY, spaceAfter=6,
leftIndent=9 * mm, rightIndent=9 * mm,
),
"caption": ParagraphStyle(
"Caption", parent=base["BodyText"], fontName="Helvetica", fontSize=7.5,
leading=9.5, textColor=MUTED, alignment=TA_LEFT, spaceBefore=3, spaceAfter=9,
),
"list": ParagraphStyle(
"ListBody", parent=base["BodyText"], fontName="Times-Roman", fontSize=9.1,
leading=12, textColor=INK, alignment=TA_JUSTIFY,
),
"small": ParagraphStyle(
"Small", parent=base["BodyText"], fontName="Helvetica", fontSize=7.4,
leading=9.5, textColor=MUTED,
),
}
def table_flowable(lines: list[str], styles: dict[str, ParagraphStyle]) -> Table:
rows = []
for line in lines:
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
if all(set(cell) <= {"-", ":"} for cell in cells):
continue
rows.append([Paragraph(inline_markup(cell), styles["small"]) for cell in cells])
columns = len(rows[0])
width = A4[0] - 30 * mm
table = Table(rows, colWidths=[width / columns] * columns, repeatRows=1, hAlign="LEFT")
font_size = 5.7 if columns >= 10 else 6.8 if columns >= 7 else 7.4
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#edf2f8")),
("TEXTCOLOR", (0, 0), (-1, 0), INK),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
("FONTSIZE", (0, 0), (-1, -1), font_size),
("LEADING", (0, 0), (-1, -1), font_size + 2.2),
("GRID", (0, 0), (-1, -1), 0.45, GRID),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [PAPER, colors.HexColor("#fafbfc")]),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("ALIGN", (1, 1), (-1, -1), "RIGHT"),
("LEFTPADDING", (0, 0), (-1, -1), 3),
("RIGHTPADDING", (0, 0), (-1, -1), 3),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]
)
)
return table
def parse_body(lines: list[str], styles: dict[str, ParagraphStyle]) -> list:
story = []
paragraph: list[str] = []
bullets: list[str] = []
def flush_paragraph() -> None:
if paragraph:
story.append(Paragraph(inline_markup(" ".join(paragraph)), styles["body"]))
paragraph.clear()
def flush_bullets() -> None:
if bullets:
bullet_style = ParagraphStyle(
"VisibleList", parent=styles["list"], leftIndent=14, firstLineIndent=-10, spaceAfter=3
)
for item in bullets:
story.append(Paragraph(inline_markup(item), bullet_style))
story.append(Spacer(1, 4))
bullets.clear()
index = 0
while index < len(lines):
line = lines[index].rstrip()
if line.startswith("|"):
flush_paragraph()
flush_bullets()
table_lines = []
while index < len(lines) and lines[index].strip().startswith("|"):
table_lines.append(lines[index].strip())
index += 1
story.append(table_flowable(table_lines, styles))
story.append(Spacer(1, 8))
continue
if not line.strip():
flush_paragraph()
flush_bullets()
elif line.startswith("## "):
flush_paragraph()
flush_bullets()
story.append(Paragraph(inline_markup(line[3:]), styles["h1"]))
elif line.startswith("### "):
flush_paragraph()
flush_bullets()
story.append(Paragraph(inline_markup(line[4:]), styles["h2"]))
elif line.startswith("- "):
flush_paragraph()
bullets.append("- " + line[2:].strip())
elif re.match(r"^\d+\. ", line):
flush_paragraph()
bullets.append(line.strip())
elif line == "[[FIGURE:architecture]]":
flush_paragraph()
flush_bullets()
story.append(KeepTogether([
architecture_figure(),
Paragraph("Figure 1. Governed persistent-evolution architecture and authority boundaries.",
styles["caption"]),
]))
elif line == "[[FIGURE:results]]":
flush_paragraph()
flush_bullets()
story.append(KeepTogether([
results_figure(),
Paragraph("Figure 2. Condition-level quality, input-token cost, and target-model Skill gain.",
styles["caption"]),
]))
else:
paragraph.append(line.strip())
index += 1
flush_paragraph()
flush_bullets()
return story
def page_decor(canvas, document) -> None:
page = canvas.getPageNumber()
canvas.saveState()
canvas.setStrokeColor(GRID)
canvas.setLineWidth(0.45)
canvas.line(15 * mm, 13 * mm, A4[0] - 15 * mm, 13 * mm)
canvas.setFont("Helvetica", 7)
canvas.setFillColor(MUTED)
canvas.drawString(15 * mm, 8.5 * mm, "Governed Skill Evolution from Persistent Agent Experience")
canvas.drawRightString(A4[0] - 15 * mm, 8.5 * mm, str(page))
canvas.restoreState()
def build() -> None:
source = SOURCE.read_text(encoding="utf-8")
if re.search(r"\bdraft\b", source, re.IGNORECASE):
raise SystemExit("publication source contains a prohibited status marker")
lines = source.splitlines()
if lines[:8] != [
"# Governed Skill Evolution from Persistent Agent Experience",
"",
"## A Prospective Ablation and Cross-Model Transfer Study",
"",
"Song Luo",
"",
"Independent Researcher",
"",
]:
raise SystemExit("paper front matter changed")
styles = make_styles()
story = [
Spacer(1, 7 * mm),
Paragraph("Governed Skill Evolution from Persistent Agent Experience", styles["title"]),
Paragraph("A Prospective Ablation and Cross-Model Transfer Study", styles["subtitle"]),
Paragraph("Song Luo", styles["author"]),
Paragraph("Independent Researcher", styles["meta"]),
Paragraph("September 2026", styles["meta"]),
Spacer(1, 6 * mm),
Table([[""]], colWidths=[A4[0] - 30 * mm], rowHeights=[1],
style=TableStyle([("BACKGROUND", (0, 0), (-1, -1), BLUE)])),
Spacer(1, 4 * mm),
]
abstract_index = lines.index("[[ABSTRACT]]")
keywords_index = lines.index("[[KEYWORDS]]")
abstract_text = " ".join(line.strip() for line in lines[abstract_index + 1:keywords_index] if line.strip())
keyword_text = " ".join(line.strip() for line in lines[keywords_index + 1:] if line.strip())
keyword_line = keyword_text.split("## 1. Introduction", 1)[0].strip()
story.append(Paragraph("Abstract", styles["h2"]))
story.append(Paragraph(inline_markup(abstract_text), styles["abstract"]))
story.append(Paragraph("Keywords: " + inline_markup(keyword_line), styles["abstract"]))
story.append(Spacer(1, 3 * mm))
introduction_index = lines.index("## 1. Introduction")
story.extend(parse_body(lines[introduction_index:], styles))
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
document = SimpleDocTemplate(
str(OUTPUT),
pagesize=A4,
rightMargin=15 * mm,
leftMargin=15 * mm,
topMargin=15 * mm,
bottomMargin=18 * mm,
title="Governed Skill Evolution from Persistent Agent Experience",
author="Song Luo",
subject="Prospective ablation and cross-model transfer study of persistent Agent experience",
keywords="agent skills, persistent memory, skill evolution, ablation, transfer",
)
document.build(story, onFirstPage=page_decor, onLaterPages=page_decor)
print(OUTPUT)
if __name__ == "__main__":
build()