File size: 16,170 Bytes
c406af5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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'<link href="\1" color="#2563eb">\1</link>',
        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("<b>Keywords:</b> " + 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()