The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): preserve office document semantics
fangliquanflq64c4f634f419
diff --git a/skills/productivity/microsoft-office/references/restructuring.md b/skills/productivity/microsoft-office/references/restructuring.mdindex 66f0bef1771..06a94b43ce5 100644--- a/skills/productivity/microsoft-office/references/restructuring.md+++ b/skills/productivity/microsoft-office/references/restructuring.md@@ -30,8 +30,10 @@ gives the exact rewrite rules and honest limits.- String literals inside formulas (`"See B2"`) are never rewritten.- Function names that look like cells (`LOG10(...)`) are not touched(a reference is never followed by `(`).-- Whole-row/column refs (`B:B`, `2:2`) pass through unchanged — Excel- semantics keep them valid across inserts within the span.+- Whole-row/column refs (`B:B`, `2:2`) are shifted for operations on+ their own axis and pass through unchanged for the other axis. A span+ grows when an insertion lands inside it and becomes `#REF!` when a+ deletion removes it completely.## Shift semanticsdiff --git a/skills/productivity/microsoft-office/scripts/docx_read.py b/skills/productivity/microsoft-office/scripts/docx_read.pyindex 4465f99be81..8a56aa6efc1 100644--- a/skills/productivity/microsoft-office/scripts/docx_read.py+++ b/skills/productivity/microsoft-office/scripts/docx_read.py@@ -24,21 +24,43 @@ import zipfilefrom docx import Document+def cell_text(cell) -> str:+ """Flatten a cell's own paragraphs and any nested table text."""+ parts = [p.text for p in cell.paragraphs if p.text]+ for nested in cell.tables:+ for row in table_to_rows(nested):+ parts.extend(text for text in row if text)+ return "\n".join(parts)++def table_to_rows(table) -> list:- return [[cell.text for cell in row.cells] for row in table.rows]+ return [[cell_text(cell) for cell in row.cells] for row in table.rows]+++def append_part_text(target: list[str], part, seen: set[int]) -> None:+ """Append one header/footer variant without duplicating linked parts."""+ marker = id(part._element)+ if marker in seen:+ return+ seen.add(marker)+ target.extend(p.text for p in part.paragraphs)+ for table in part.tables:+ target.append(json.dumps(table_to_rows(table), ensure_ascii=False))def extract_text(doc) -> dict:out = {"body": [p.text for p in doc.paragraphs],"tables": [table_to_rows(t) for t in doc.tables],"headers": [], "footers": []}+ seen_headers: set[int] = set()+ seen_footers: set[int] = set()for section in doc.sections:- out["headers"].extend(p.text for p in section.header.paragraphs)- out["footers"].extend(p.text for p in section.footer.paragraphs)- for t in section.header.tables:- out["headers"].append(json.dumps(table_to_rows(t), ensure_ascii=False))- for t in section.footer.tables:- out["footers"].append(json.dumps(table_to_rows(t), ensure_ascii=False))+ for part in (section.header, section.first_page_header,+ section.even_page_header):+ append_part_text(out["headers"], part, seen_headers)+ for part in (section.footer, section.first_page_footer,+ section.even_page_footer):+ append_part_text(out["footers"], part, seen_footers)return outdiff --git a/skills/productivity/microsoft-office/scripts/pptx_create.py b/skills/productivity/microsoft-office/scripts/pptx_create.pyindex 71d18765a87..9cf0a8e6096 100644--- a/skills/productivity/microsoft-office/scripts/pptx_create.py+++ b/skills/productivity/microsoft-office/scripts/pptx_create.py@@ -100,6 +100,20 @@ def copy_layout_placeholder(slide, ph_idx):return None+def set_slide_title(slide, text, slide_width):+ """Set a layout title or add a conventional title box as fallback."""+ if slide.shapes.title is not None:+ slide.shapes.title.text = text+ return slide.shapes.title+ shape = slide.shapes.add_textbox(+ Inches(0.5), Inches(0.3), slide_width - Inches(1), Inches(0.8))+ run = shape.text_frame.paragraphs[0].add_run()+ run.text = text+ run.font.size = Pt(28)+ run.font.bold = True+ return shape++def build_slide(prs, spec):layout_idx = LAYOUTS.get(spec.get("layout", "title_content"), 1)slide = prs.slides.add_slide(prs.slide_layouts[layout_idx])@@ -115,8 +129,8 @@ def build_slide(prs, spec):if shape is not None:shape.text_frame.text = spec["footer"]- if spec.get("title") is not None and slide.shapes.title is not None:- slide.shapes.title.text = spec["title"]+ if spec.get("title") is not None:+ set_slide_title(slide, spec["title"], prs.slide_width)if spec.get("subtitle") is not None:for ph in slide.placeholders:if ph.placeholder_format.idx == 1:diff --git a/skills/productivity/microsoft-office/scripts/pptx_from_template.py b/skills/productivity/microsoft-office/scripts/pptx_from_template.pyindex d097510d92c..40c716b2d91 100644--- a/skills/productivity/microsoft-office/scripts/pptx_from_template.py+++ b/skills/productivity/microsoft-office/scripts/pptx_from_template.py@@ -38,12 +38,12 @@ def find_layout(prs, ref):def add_slides(prs, spec):- from pptx_create import add_bullets+ from pptx_create import add_bullets, set_slide_titlefor slide_spec in spec.get("slides", []):layout = find_layout(prs, slide_spec.get("layout", 1))slide = prs.slides.add_slide(layout)- if slide_spec.get("title") is not None and slide.shapes.title:- slide.shapes.title.text = slide_spec["title"]+ if slide_spec.get("title") is not None:+ set_slide_title(slide, slide_spec["title"], prs.slide_width)if slide_spec.get("bullets"):body = next((ph for ph in slide.placeholdersif ph.placeholder_format.idx != 0), None)diff --git a/skills/productivity/microsoft-office/scripts/xlsx_restructure.py b/skills/productivity/microsoft-office/scripts/xlsx_restructure.pyindex 9bff3d2c731..66074d4b44c 100644--- a/skills/productivity/microsoft-office/scripts/xlsx_restructure.py+++ b/skills/productivity/microsoft-office/scripts/xlsx_restructure.py@@ -43,12 +43,23 @@ from openpyxl.utils import (column_index_from_string, get_column_letter,# A1-style reference, optionally sheet-qualified, optionally a range.# Guards: not preceded by a word char/$/. (avoids ABC123 identifiers) and# not followed by a word char or "(" (avoids function names like LOG10().+SHEET_PATTERN = r"(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!"REF_RE = re.compile(r"(?<![\w$.:])"- r"(?P<sheet>(?:'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?"+ rf"(?P<sheet>{SHEET_PATTERN})?"r"(?P<start>\$?[A-Za-z]{1,3}\$?[0-9]{1,7})"r"(?::(?P<end>\$?[A-Za-z]{1,3}\$?[0-9]{1,7}))?"r"(?![\w(])")+WHOLE_COL_RE = re.compile(+ r"(?<![\w$.:])"+ rf"(?P<sheet>{SHEET_PATTERN})?"+ r"(?P<start>\$?[A-Za-z]{1,3}):(?P<end>\$?[A-Za-z]{1,3})"+ r"(?![\w(])")+WHOLE_ROW_RE = re.compile(+ r"(?<![\w$.:])"+ rf"(?P<sheet>{SHEET_PATTERN})?"+ r"(?P<start>\$?[0-9]{1,7}):(?P<end>\$?[0-9]{1,7})"+ r"(?![\w(])")STRING_RE = re.compile(r'"(?:[^"]|"")*"')COORD_RE = re.compile(r"^(\$?)([A-Za-z]{1,3})(\$?)([0-9]+)$")@@ -138,8 +149,7 @@ class RefRewriter:f"{e.group(3)}{e.group(4)}")return new_start, new_end- def _sub(self, match, home_sheet):- prefix = match.group("sheet") or ""+ def _targets_sheet(self, prefix, home_sheet):if prefix:name = prefix[:-1]if name.startswith("'"):@@ -147,7 +157,11 @@ class RefRewriter:ref_sheet = nameelse:ref_sheet = home_sheet- if ref_sheet.lower() != self.target:+ return ref_sheet.lower() == self.target++ def _sub(self, match, home_sheet):+ prefix = match.group("sheet") or ""+ if not self._targets_sheet(prefix, home_sheet):return match.group(0)start, end = match.group("start"), match.group("end")if end is None:@@ -157,15 +171,42 @@ class RefRewriter:return (prefix + "#REF!" if pair is Noneelse f"{prefix}{pair[0]}:{pair[1]}")+ def _sub_whole(self, match, home_sheet, axis):+ prefix = match.group("sheet") or ""+ if axis != self.axis or not self._targets_sheet(prefix, home_sheet):+ return match.group(0)+ start, end = match.group("start"), match.group("end")+ start_abs, end_abs = start.startswith("$"), end.startswith("$")+ if axis == "cols":+ a = column_index_from_string(start.lstrip("$").upper())+ b = column_index_from_string(end.lstrip("$").upper())+ else:+ a, b = int(start.lstrip("$")), int(end.lstrip("$"))+ span = shift_span(a, b, self.idx, self.n, self.delete)+ if span is None:+ return prefix + "#REF!"+ if axis == "cols":+ new_start, new_end = map(get_column_letter, span)+ else:+ new_start, new_end = map(str, span)+ return (f"{prefix}{'$' if start_abs else ''}{new_start}:"+ f"{'$' if end_abs else ''}{new_end}")++ def _rewrite_segment(self, text, home_sheet):+ text = WHOLE_COL_RE.sub(+ lambda m: self._sub_whole(m, home_sheet, "cols"), text)+ text = WHOLE_ROW_RE.sub(+ lambda m: self._sub_whole(m, home_sheet, "rows"), text)+ return REF_RE.sub(lambda m: self._sub(m, home_sheet), text)+def rewrite(self, text, home_sheet):"""Rewrite refs outside quoted string literals. Returns new text."""out, pos = [], 0for lit in STRING_RE.finditer(text):- out.append(REF_RE.sub(lambda m: self._sub(m, home_sheet),- text[pos:lit.start()]))+ out.append(self._rewrite_segment(text[pos:lit.start()], home_sheet))out.append(lit.group(0))pos = lit.end()- out.append(REF_RE.sub(lambda m: self._sub(m, home_sheet), text[pos:]))+ out.append(self._rewrite_segment(text[pos:], home_sheet))return "".join(out)@@ -176,7 +217,9 @@ def shift_dimensions(dims, idx, n, delete, is_row):for key, dim in items:pos = key if is_row else column_index_from_string(key)new = shift_point(pos, idx, n, delete)- if new is not None and new != pos:+ if new is None:+ del dims[key]+ elif new != pos:saved[new if is_row else get_column_letter(new)] = dimdel dims[key]for key, dim in saved.items():@@ -277,13 +320,17 @@ def main(argv=None):ws.freeze_panes = new# 6. data validations + conditional formatting applied ranges- for dv in ws.data_validations.dataValidation:+ for dv in list(ws.data_validations.dataValidation):old = str(dv.sqref)parts = [shift_range(p, axis, idx, n, delete) for p in old.split()]parts = [p for p in parts if p]- if parts and " ".join(parts) != old:- dv.sqref = " ".join(parts)- report["validations"].append({"from": old, "to": str(dv.sqref)})+ new = " ".join(parts) if parts else None+ if new != old:+ if new is None:+ ws.data_validations.dataValidation.remove(dv)+ else:+ dv.sqref = new+ report["validations"].append({"from": old, "to": new})new_cf = ConditionalFormattingList()for cf in ws.conditional_formatting:old = str(cf.sqref)@@ -300,12 +347,15 @@ def main(argv=None):ws.conditional_formatting = new_cf# 7. native tables on the edited sheet- for table in ws.tables.values():- new = shift_range(table.ref, axis, idx, n, delete)- if new and new != table.ref:- report["tables"][table.displayName] = {"from": table.ref,- "to": new}- table.ref = new+ for table in list(ws.tables.values()):+ old = table.ref+ new = shift_range(old, axis, idx, n, delete)+ if new != old:+ report["tables"][table.displayName] = {"from": old, "to": new}+ if new is None:+ del ws.tables[table.displayName]+ else:+ table.ref = new# 8. workbook-scope defined namesfor name, dn in wb.defined_names.items():diff --git a/skills/productivity/microsoft-office/tests/test_docx_skill.py b/skills/productivity/microsoft-office/tests/test_docx_skill.pyindex 8476c4f502a..c72d82a96e1 100644--- a/skills/productivity/microsoft-office/tests/test_docx_skill.py+++ b/skills/productivity/microsoft-office/tests/test_docx_skill.py@@ -147,6 +147,24 @@ class TestCreateAndRead:assert rev["has_tracked_changes"] is Falseassert rev["comments"] is False+ def test_text_includes_nested_tables_and_header_variants(self, workdir: Path):+ path = workdir / "nested-and-headers.docx"+ doc = Document()+ outer = doc.add_table(rows=1, cols=1)+ outer.cell(0, 0).text = "outer"+ nested = outer.cell(0, 0).add_table(rows=1, cols=1)+ nested.cell(0, 0).text = "nested-only"+ section = doc.sections[0]+ section.different_first_page_header_footer = True+ section.first_page_header.paragraphs[0].text = "first-header"+ section.even_page_header.paragraphs[0].text = "even-header"+ doc.save(path)++ text = run("docx_read.py", path, "--text")+ assert "nested-only" in text["tables"][0][0][0]+ assert "first-header" in text["headers"]+ assert "even-header" in text["headers"]+class TestEdit:def test_replace_preserves_formatting(self, created: Path, workdir: Path):diff --git a/skills/productivity/microsoft-office/tests/test_powerpoint_skill.py b/skills/productivity/microsoft-office/tests/test_powerpoint_skill.pyindex 3f624387786..e5bc72c95b1 100644--- a/skills/productivity/microsoft-office/tests/test_powerpoint_skill.py+++ b/skills/productivity/microsoft-office/tests/test_powerpoint_skill.py@@ -128,6 +128,16 @@ def test_create_43_size(workdir):assert outline["slide_size_inches"] == [10.0, 7.5]+def test_create_blank_slide_keeps_explicit_title(workdir):+ spec_path = workdir / "blank_title.json"+ write_json(spec_path, {"slides": [+ {"layout": "blank", "title": "Visible title"}]})+ out = workdir / "blank_title.pptx"+ run("pptx_create.py", str(spec_path), str(out))+ outline = run("pptx_read.py", str(out))+ assert "Visible title" in outline["slides"][0]["texts"]++def test_notes_mode(deck):result = run("pptx_read.py", deck, "--notes")assert result["notes"][1] == "Keep this under two minutes."@@ -185,6 +195,18 @@ def test_template_add_slides(workdir):assert "Appended" in outline["slides"][2]["texts"]+def test_template_add_blank_slide_keeps_explicit_title(workdir):+ template = workdir / "template.pptx"+ add_spec = workdir / "add_blank.json"+ write_json(add_spec, {"slides": [+ {"layout": 6, "title": "Blank layout title"}]})+ out = workdir / "appended_blank.pptx"+ run("pptx_from_template.py", str(template), str(out),+ "--add-slides", str(add_spec))+ outline = run("pptx_read.py", str(out))+ assert "Blank layout title" in outline["slides"][-1]["texts"]++def test_edit_replace_text(deck, workdir):edited = workdir / "edited.pptx"result = run("pptx_edit.py", deck, "--output", str(edited),diff --git a/skills/productivity/microsoft-office/tests/test_xlsx_skill.py b/skills/productivity/microsoft-office/tests/test_xlsx_skill.pyindex 284198d8066..24f8f59e9bc 100644--- a/skills/productivity/microsoft-office/tests/test_xlsx_skill.py+++ b/skills/productivity/microsoft-office/tests/test_xlsx_skill.py@@ -15,7 +15,9 @@ from datetime import datefrom pathlib import Pathimport pytest-from openpyxl import load_workbook+from openpyxl import Workbook, load_workbook+from openpyxl.worksheet.datavalidation import DataValidation+from openpyxl.worksheet.table import TableSCRIPTS = Path(__file__).resolve().parent.parent / "scripts"@@ -332,7 +334,7 @@ def test_restructure_insert_rows_shifts_everything(restructure_book):assert data["B8"].value == "=SUM(B2:B6)"# absolute ref before insert point unchanged; relative arm shiftedassert data["C8"].value == "=$B$2*C2"- # function names, whole-column refs, string literals untouched+ # function names, whole-column refs on a row operation, strings untouchedassert data["D8"].value == "=LOG10(B6)"assert data["E8"].value == "=SUM(B:B)"assert data["F8"].value == '="row B2: "&B2'@@ -392,6 +394,50 @@ def test_restructure_insert_cols(restructure_book):assert "A7:C7" in merged # merge expanded across col B+def test_restructure_whole_axis_refs(restructure_book):+ wb = load_workbook(restructure_book)+ wb["Summary"]["C1"] = "=SUM(Data!B:B)"+ wb["Summary"]["C2"] = "=SUM(Data!2:2)"+ wb.save(restructure_book)++ report = json.loads(run(+ "xlsx_restructure.py", restructure_book, "--sheet", "Data",+ "--insert-cols", "B:1").stdout)+ wb = load_workbook(restructure_book)+ assert wb["Summary"]["C1"].value == "=SUM(Data!C:C)"+ assert wb["Summary"]["C2"].value == "=SUM(Data!2:2)"+ assert any(item["cell"] == "C1" for item in report["formulas"])++ run("xlsx_restructure.py", restructure_book, "--sheet", "Data",+ "--insert-rows", "2:1")+ wb = load_workbook(restructure_book)+ assert wb["Summary"]["C1"].value == "=SUM(Data!C:C)"+ assert wb["Summary"]["C2"].value == "=SUM(Data!3:3)"+++def test_restructure_removes_fully_deleted_artifacts(tmp_path):+ book = tmp_path / "deleted-artifacts.xlsx"+ wb = Workbook()+ ws = wb.active+ ws.append(["Name", "Value"])+ ws.append(["old", 1])+ ws.row_dimensions[2].height = 44+ validation = DataValidation(type="list", formula1='"x,y"')+ validation.add("A2")+ ws.add_data_validation(validation)+ ws.add_table(Table(displayName="OnlyTable", ref="A1:B2"))+ wb.save(book)++ report = json.loads(run(+ "xlsx_restructure.py", book, "--delete-rows", "1:2").stdout)+ ws = load_workbook(book).active+ assert all(dim.height != 44 for dim in ws.row_dimensions.values())+ assert not ws.data_validations.dataValidation+ assert "OnlyTable" not in ws.tables+ assert report["validations"] == [{"from": "A2", "to": None}]+ assert report["tables"]["OnlyTable"]["to"] is None++# ---------------------------------------------------------------------------# Tables, defined names, hyperlinks, notes, protection (edit + read paths)# ---------------------------------------------------------------------------diff --git a/skills/productivity/pdf/scripts/pdf_fill_form.py b/skills/productivity/pdf/scripts/pdf_fill_form.pyindex a2f7dffa413..37733e4e9f6 100644--- a/skills/productivity/pdf/scripts/pdf_fill_form.py+++ b/skills/productivity/pdf/scripts/pdf_fill_form.py@@ -67,24 +67,33 @@ def main() -> int:value = on_state if value else "/Off"fill[name] = valuefor page in writer.pages:- writer.update_page_form_field_values(page, fill, auto_regenerate=False)+ writer.update_page_form_field_values(+ page, fill, flags=1 if args.flatten else 0,+ auto_regenerate=False, flatten=args.flatten)- # Set NeedAppearances so viewers render values even without appearance streams.root = writer._root_object- if "/AcroForm" in root:- root["/AcroForm"][NameObject("/NeedAppearances")] = BooleanObject(True)-- flattened = False+ flattened = args.flattenif args.flatten:- try:- # pypdf >= 5: flatten via update with flags making fields read-only,- # then remove interactivity by merging appearances.- for page in writer.pages:- writer.update_page_form_field_values(page, fill, flags=1) # 1 = ReadOnly- flattened = True- except Exception as exc:- print(f"Warning: flatten step failed ({exc}); output keeps interactive fields",- file=sys.stderr)+ # pypdf's flatten=True merges each widget appearance into page+ # content but intentionally leaves the annotations behind. Remove+ # those widgets and the form dictionary to make the result genuinely+ # non-interactive; preserve unrelated links/comments.+ from pypdf.generic import ArrayObject+ for page in writer.pages:+ annots = page.get("/Annots")+ if not annots:+ continue+ kept = ArrayObject(+ ref for ref in annots+ if ref.get_object().get("/Subtype") != "/Widget")+ if kept:+ page[NameObject("/Annots")] = kept+ else:+ page.pop(NameObject("/Annots"), None)+ root.pop(NameObject("/AcroForm"), None)+ elif "/AcroForm" in root:+ # Let conforming viewers regenerate interactive field appearances.+ root["/AcroForm"][NameObject("/NeedAppearances")] = BooleanObject(True)with open(args.output, "wb") as fh:writer.write(fh)diff --git a/skills/productivity/pdf/tests/test_pdf_skill.py b/skills/productivity/pdf/tests/test_pdf_skill.pyindex aaff9f5c109..c9282f7def5 100644--- a/skills/productivity/pdf/tests/test_pdf_skill.py+++ b/skills/productivity/pdf/tests/test_pdf_skill.py@@ -122,6 +122,24 @@ def test_form_fill_unicode_roundtrip(form_pdf: Path, workdir: Path):assert fields["size"]["value"] == "large"+def test_form_fill_flatten_removes_widgets(form_pdf: Path, workdir: Path):+ values = workdir / "flat_values.json"+ values.write_text(json.dumps({"surname": "Ada", "agree": True}),+ encoding="utf-8")+ flattened = workdir / "flattened.pdf"+ result = json.loads(run(+ "pdf_fill_form.py", str(form_pdf), "--fields-json", str(values),+ "-o", str(flattened), "--flatten").stdout)+ assert result["flattened"] is True++ from pypdf import PdfReader+ reader = PdfReader(str(flattened))+ assert reader.get_fields() in (None, {})+ annots = reader.pages[0].get("/Annots", [])+ assert all(ref.get_object().get("/Subtype") != "/Widget" for ref in annots)+ assert "Ada" in (reader.pages[0].extract_text() or "")++def test_merge_split_rotate(report_pdf: Path, workdir: Path):merged = workdir / "merged.pdf"out = json.loads(run("pdf_merge.py", str(report_pdf), str(report_pdf),