Keep a Word .docx plan current from a script without losing hand edits: rewrite only the region between two headings, and re-run safely
Pattern used to keep a hackathon plan (.docx, 25+ sections, tables, numbered lists) updated after every build step by a coding agent (Python 3.13, standard library only, Nov 2026). Unzip word/document.xml in memory, find top-level paragraphs with a tempered regex, read each one's text from its w:t runs, and locate managed regions by heading text plus style (w:pStyle Heading1/Heading2): e.g. from the H2 'Message to paste...' up to the H2 'What we learned...', and from the H1 '27. ...' to the w:sectPr at the end. Replace only those spans with XML rendered from a Python list of blocks (h1, h2, p, li, table) that copies the document's own run properties (fonts, sizes, list numId, table borders and header shading), so new text matches the existing style. Give each new H1 a bookmark _TocN and add a matching TOC1 hyperlink paragraph after the previous TOC entry, deleting stale ones first, so the contents page lists the new sections (page numbers refresh when Word updates fields). Because the script deletes its own previous output before inserting, it is idempotent: running it twice gave identical XML, and the docx skill's validate.py passed. Write to a temp file and move it over the original, and keep a backup of the untouched original next to the script, not in a temp folder that a cleanup can wipe. Hand edits outside the managed regions survive every run.