microsoft-word 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,507 @@
1
+ #!/usr/bin/env python3
2
+ """Make a clean copy of a Word document for sharing: accept tracked changes, remove comments,
3
+ hidden text, glossary, personal metadata and active content. Then re-inspect the copy and
4
+ report what remains.
5
+
6
+ Usage:
7
+ python docx_sanitize.py IN OUT [--accept-changes] [--remove-comments] [--strip-metadata]
8
+ [--remove-hidden] [--remove-glossary] [--remove-active]
9
+ [--all | --share] [--json]
10
+
11
+ What each option does (only the parts it names are rewritten; other parts keep their bytes):
12
+ --accept-changes w:ins and w:moveTo are unwrapped; w:del, w:moveFrom and move range marks are
13
+ removed; formatting changes (rPrChange, pPrChange, sectPrChange, tbl/tr/tc
14
+ PrChange, numberingChange) are dropped so the current formatting stays; a
15
+ deleted paragraph mark merges the paragraph into the next one; deleted table
16
+ rows are removed. Cell-level insert/delete/merge marks are not handled and
17
+ are reported as residue: finish those in Word.
18
+ --remove-comments Comment ranges, references and the comments, commentsExtended, commentsIds,
19
+ commentsExtensible and people parts with their relationships.
20
+ --strip-metadata docProps/core.xml creator, lastModifiedBy, lastPrinted, revision, created,
21
+ modified; app.xml Company, Manager, Template, TotalTime, HyperlinkBase,
22
+ Application, AppVersion; all custom properties; the thumbnail
23
+ (docProps/thumbnail.*, a picture of page 1); w:rsids and every w:rsid*
24
+ attribute; w:docVars; the attached template reference; customXml parts
25
+ (SharePoint and data-binding properties) and w:dataBinding links to them.
26
+ Title, subject, keywords, description, category and contentStatus are kept
27
+ and listed: check them yourself.
28
+ --remove-hidden Runs hidden by w:vanish, w:specVanish or w:webHidden, set directly or through
29
+ character styles, paragraph styles (basedOn chains) or docDefaults, in the
30
+ body, headers, footers, notes and the glossary. Hidden runs that hold field
31
+ codes are kept (removing them breaks the field) and reported; exit 1.
32
+ --remove-glossary The glossary document (building blocks, AutoText): its text travels with the
33
+ file but is never shown in the body.
34
+ --remove-active vbaProject.bin and vbaData.xml (a .docm becomes a .docx: name OUT .docx),
35
+ ActiveX controls, OLE objects (embedded and linked, with their pictures),
36
+ altChunk imports, every external relationship except hyperlinks (remote
37
+ template, linked images and beacons, frames, subdocuments) and the elements
38
+ that use them, the mail merge data source and updateFields. DDE, DDEAUTO,
39
+ INCLUDETEXT, INCLUDEPICTURE, INCLUDE, IMPORT, LINK, DATABASE, MACROBUTTON,
40
+ AUTOOPEN, AUTOEXEC fields, and fields built from nested fields or QUOTE
41
+ character codes, are replaced by their stored result text.
42
+ --all All of the above. Exits 1 if any risk remains after the re-inspection.
43
+ --share --all, and exits 1 if any residue remains too (for example visually masked
44
+ text, which only a person can decide to delete).
45
+
46
+ This is not full redaction. It does not touch images (EXIF, cropped areas), charts, alt text,
47
+ text the user covered with black highlight, white font or shapes, or the visible text itself.
48
+ The final inspection lists what remains; read it before sharing.
49
+
50
+ Safety: OUT must not exist and must differ from IN. A macro-enabled input with a .docx OUT
51
+ is refused unless --remove-active is given, and --remove-active refuses a .docm or .dotm OUT
52
+ (Word rejects a file whose extension and content type disagree).
53
+ Exit codes: 0 clean for the requested categories (and no risks with --remove-active, no
54
+ residue with --share), 1 something requested remains (see "remaining", "risks_after"),
55
+ 2 unsupported or unreadable input, 3 safety refusal (output exists, size cap, DOCTYPE,
56
+ duplicate zip entries, extension mismatch). Requires: pip install lxml
57
+ """
58
+ import argparse
59
+ import json
60
+ import os
61
+ import sys
62
+
63
+ import inspect_docx
64
+ import wordpkg as wp
65
+ from wordpkg import NS, clean, w
66
+
67
+ PROP_CHANGES = ["rPrChange", "pPrChange", "sectPrChange", "tblPrChange", "trPrChange",
68
+ "tcPrChange", "tblGridChange", "tblPrExChange", "numberingChange"]
69
+ MOVE_MARKS = ["moveFromRangeStart", "moveFromRangeEnd", "moveToRangeStart", "moveToRangeEnd"]
70
+ COMMENT_TYPES = {"comments", "commentsExtended", "commentsIds", "commentsExtensible", "people"}
71
+ OFF = {"0", "false", "off"}
72
+
73
+
74
+ def unwrap(el):
75
+ parent = el.getparent()
76
+ idx = parent.index(el)
77
+ for i, c in enumerate(list(el)):
78
+ parent.insert(idx + i, c)
79
+ # keep tail text (whitespace) attached
80
+ parent.remove(el)
81
+
82
+
83
+ def accept(root):
84
+ n = 0
85
+ for tag in PROP_CHANGES:
86
+ for el in list(root.iter(w(tag))):
87
+ el.getparent().remove(el)
88
+ n += 1
89
+ for tag in MOVE_MARKS:
90
+ for el in list(root.iter(w(tag))):
91
+ el.getparent().remove(el)
92
+ # paragraph marks and table rows first (they sit in pPr/rPr and trPr)
93
+ for mark in list(root.iter(w("ins"))):
94
+ par = mark.getparent()
95
+ if par is not None and par.tag in (w("rPr"), w("trPr")):
96
+ par.remove(mark)
97
+ n += 1
98
+ for mark in list(root.iter(w("del"))):
99
+ par = mark.getparent()
100
+ if par is None:
101
+ continue
102
+ if par.tag == w("trPr"):
103
+ row = par.getparent()
104
+ row.getparent().remove(row)
105
+ n += 1
106
+ elif par.tag == w("rPr") and par.getparent() is not None and par.getparent().tag == w("pPr"):
107
+ p = par.getparent().getparent()
108
+ par.remove(mark)
109
+ nxt = p.getnext()
110
+ if nxt is not None and nxt.tag == w("p"):
111
+ # the deleted mark joins this paragraph's content to the next paragraph,
112
+ # which keeps its own paragraph properties (its mark survives)
113
+ kids = [c for c in p if c.tag != w("pPr")]
114
+ npr = nxt.find("w:pPr", NS)
115
+ pos = 0 if npr is None else nxt.index(npr) + 1
116
+ for i, c in enumerate(kids):
117
+ nxt.insert(pos + i, c)
118
+ p.getparent().remove(p)
119
+ n += 1
120
+ for el in list(root.iter(w("del"), w("moveFrom"))):
121
+ if el.getparent() is not None:
122
+ el.getparent().remove(el)
123
+ n += 1
124
+ for el in list(root.iter(w("ins"), w("moveTo"))):
125
+ if el.getparent() is not None:
126
+ unwrap(el)
127
+ n += 1
128
+ return n
129
+
130
+
131
+ def remove_comment_marks(root):
132
+ n = 0
133
+ for el in list(root.iter(w("commentRangeStart"), w("commentRangeEnd"))):
134
+ el.getparent().remove(el)
135
+ for ref in list(root.iter(w("commentReference"))):
136
+ r = ref.getparent()
137
+ r.remove(ref)
138
+ n += 1
139
+ if r.tag == w("r") and all(c.tag == w("rPr") for c in r):
140
+ r.getparent().remove(r)
141
+ return n
142
+
143
+
144
+ def remove_hidden(root, hid):
145
+ """Remove hidden runs. Returns (removed, kept_field_runs)."""
146
+ n = kept = 0
147
+ for r in list(root.iter(w("r"))):
148
+ if r.getparent() is None or not hid.run_hidden(r):
149
+ continue
150
+ if r.find("w:fldChar", NS) is not None or r.find("w:instrText", NS) is not None:
151
+ kept += 1 # never break field structure; reported instead
152
+ continue
153
+ r.getparent().remove(r)
154
+ n += 1
155
+ return n, kept
156
+
157
+
158
+ def neutralize_fields(root):
159
+ """Replace risky fields by their stored result: drop the begin..separate runs (the
160
+ instruction, including fields nested in it) and the end run; unwrap risky fldSimple."""
161
+ fields = [f for f in inspect_docx.fields_of(root) if inspect_docx.field_risk(f)]
162
+ if not fields:
163
+ return 0
164
+ runs = list(root.iter(w("r")))
165
+ idx = {id(r): i for i, r in enumerate(runs)}
166
+ drop = set()
167
+ n = 0
168
+ for f in fields:
169
+ if "simple" in f:
170
+ el = f["simple"]
171
+ if el.getparent() is not None:
172
+ unwrap(el)
173
+ n += 1
174
+ continue
175
+ if f["end"] is None:
176
+ continue
177
+ ib = idx.get(id(f["begin"].getparent()))
178
+ ie = idx.get(id(f["end"].getparent()))
179
+ isep = idx.get(id(f["sep"].getparent())) if f["sep"] is not None else ie
180
+ if ib is None or ie is None or isep is None:
181
+ continue
182
+ drop.update(range(ib, isep + 1))
183
+ drop.add(ie)
184
+ n += 1
185
+ for i in sorted(drop):
186
+ r = runs[i]
187
+ if r.getparent() is not None:
188
+ r.getparent().remove(r)
189
+ return n
190
+
191
+
192
+ def rels_source(rels_name):
193
+ """word/_rels/document.xml.rels -> word/document.xml; _rels/.rels -> '' (the package)."""
194
+ return rels_name.replace("_rels/", "").rsplit(".rels", 1)[0]
195
+
196
+
197
+ CORE_DROP = ("creator", "lastModifiedBy", "lastPrinted", "revision", "created", "modified")
198
+ CORE_KEEP = ("title", "subject", "keywords", "description", "category", "contentStatus")
199
+ APP_DROP = ("Company", "Manager", "Template", "TotalTime", "HyperlinkBase", "Application", "AppVersion")
200
+ CATEGORIES = ("accept-changes", "remove-comments", "strip-metadata", "remove-hidden", "remove-glossary",
201
+ "remove-active")
202
+ PLAIN_TYPE = {"docm": "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
203
+ "dotm": "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"}
204
+ VML_O = "urn:schemas-microsoft-com:office:office"
205
+ R_ATTR = f"{{{wp.R}}}"
206
+
207
+
208
+ def main():
209
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
210
+ ap.add_argument("input")
211
+ ap.add_argument("output")
212
+ for f in CATEGORIES + ("all", "share"):
213
+ ap.add_argument(f"--{f}", action="store_true")
214
+ ap.add_argument("--json", action="store_true")
215
+ ap.add_argument("--max-mb", type=int, default=200)
216
+ a = ap.parse_args()
217
+ if a.all or a.share:
218
+ for f in CATEGORIES:
219
+ setattr(a, f.replace("-", "_"), True)
220
+
221
+ def done(code, **kw):
222
+ if a.json:
223
+ print(json.dumps(kw, ensure_ascii=False, indent=1))
224
+ elif not kw.get("ok"):
225
+ sys.stderr.write(f"error: {kw.get('error')}\n")
226
+ if kw.get("remaining"):
227
+ sys.stderr.write(f"remaining residue: {kw['remaining']}\n")
228
+ if kw.get("risks_after"):
229
+ sys.stderr.write(f"remaining risks: {kw['risks_after']}\n")
230
+ else:
231
+ print(f"wrote {kw['output']}: {kw['actions']}")
232
+ print(f"residue still present (not requested or not handled): {kw['remaining'] or 'none'}")
233
+ print(f"risks still present: {kw['risks_after'] or 'none'}")
234
+ if kw.get("kept_metadata"):
235
+ print(f"kept metadata, review it: {kw['kept_metadata']}")
236
+ sys.exit(code)
237
+
238
+ if not any(getattr(a, f.replace("-", "_")) for f in CATEGORIES):
239
+ done(2, ok=False, error="choose at least one of " + " ".join("--" + f for f in CATEGORIES)
240
+ + " --all --share")
241
+ if wp.same_file(a.input, a.output):
242
+ done(3, ok=False, error="OUT is the same file as IN; write to a new path")
243
+ out_ext = os.path.splitext(a.output)[1].lower()
244
+ try:
245
+ pkg = wp.Package(a.input, max_mb=a.max_mb)
246
+ if pkg.kind in ("docm", "dotm") and out_ext in (".docx", ".dotx") and not a.remove_active:
247
+ raise wp.Refusal(f"input is a macro-enabled {pkg.kind} but OUT is {out_ext}: add --remove-active "
248
+ f"to drop the macros, or name OUT .{pkg.kind}")
249
+ if a.remove_active and out_ext in (".docm", ".dotm"):
250
+ raise wp.Refusal("--remove-active writes a macro-free document: name OUT .docx (or .dotx)")
251
+ replaced, removed, actions = {}, set(), {}
252
+ main_rels_name = pkg.rels_name(pkg.main)
253
+ stories = pkg.story_parts(include_comments=False)
254
+ glossary = pkg.glossary_parts()
255
+ xml_parts = [n for n in pkg.names if n.startswith("word/") and n.endswith(".xml")]
256
+ touched = set()
257
+ hidden_field_runs = 0
258
+ if a.accept_changes:
259
+ c = 0
260
+ for part in xml_parts:
261
+ k = accept(pkg.xml(part))
262
+ if k:
263
+ touched.add(part)
264
+ c += k
265
+ actions["tracked_changes_accepted"] = c
266
+ if a.remove_comments:
267
+ c = 0
268
+ for part in stories + glossary:
269
+ k = remove_comment_marks(pkg.xml(part))
270
+ if k:
271
+ touched.add(part)
272
+ c += k
273
+ drop = {r["id"]: r["target"] for r in pkg.rels(pkg.main) if r["type"] in COMMENT_TYPES}
274
+ if drop:
275
+ rels = pkg.xml(main_rels_name)
276
+ for r in list(rels.findall("pr:Relationship", NS)):
277
+ if r.get("Id") in drop:
278
+ rels.remove(r)
279
+ touched.add(main_rels_name)
280
+ removed |= set(drop.values())
281
+ actions["comment_references_removed"] = c
282
+ actions["comment_parts_removed"] = sorted(set(drop.values()))
283
+ if a.remove_hidden:
284
+ hid = wp.Hidden(pkg)
285
+ c = 0
286
+ for part in stories + glossary:
287
+ k, kept_f = remove_hidden(pkg.xml(part), hid)
288
+ hidden_field_runs += kept_f
289
+ if k:
290
+ touched.add(part)
291
+ c += k
292
+ actions["hidden_runs_removed"] = c
293
+ actions["hidden_field_code_runs_kept"] = hidden_field_runs
294
+ if a.remove_glossary and glossary:
295
+ removed |= set(glossary)
296
+ removed |= {n for n in pkg.names if n.startswith("word/glossary/")}
297
+ actions["glossary_parts_removed"] = sorted(removed & set(glossary))
298
+ kept = {}
299
+ if a.strip_metadata:
300
+ stripped = []
301
+ for r in pkg.rels(""):
302
+ if r["external"] or r["target"] not in pkg.names:
303
+ continue
304
+ if r["type"] == "core-properties":
305
+ x = pkg.xml(r["target"])
306
+ for el in list(x):
307
+ k = el.tag.rsplit("}", 1)[-1]
308
+ if k in CORE_DROP:
309
+ x.remove(el)
310
+ stripped.append(k)
311
+ elif k in CORE_KEEP and (el.text or "").strip():
312
+ kept[k] = clean(el.text, 120)
313
+ touched.add(r["target"])
314
+ elif r["type"] == "extended-properties":
315
+ x = pkg.xml(r["target"])
316
+ for el in list(x):
317
+ k = el.tag.rsplit("}", 1)[-1]
318
+ if k in APP_DROP:
319
+ x.remove(el)
320
+ stripped.append(k)
321
+ touched.add(r["target"])
322
+ elif r["type"] == "custom-properties":
323
+ x = pkg.xml(r["target"])
324
+ for el in list(x):
325
+ x.remove(el)
326
+ stripped.append("custom properties")
327
+ touched.add(r["target"])
328
+ elif r["type"] == "thumbnail":
329
+ removed.add(r["target"])
330
+ removed |= {n for n in pkg.names if n.lower().startswith("docprops/thumbnail")}
331
+ removed |= {n for n in pkg.names if n.startswith("customXml/")}
332
+ rsid_n = 0
333
+ for part in xml_parts:
334
+ root = pkg.xml(part)
335
+ hit = False
336
+ for el in root.iter():
337
+ for k in [k for k in el.attrib if k.startswith(f"{{{wp.W}}}rsid")]:
338
+ del el.attrib[k]
339
+ rsid_n += 1
340
+ hit = True
341
+ for db in list(root.iter(w("dataBinding"))):
342
+ db.getparent().remove(db)
343
+ hit = True
344
+ if hit:
345
+ touched.add(part)
346
+ st = [r for r in pkg.rels(pkg.main) if r["type"] == "settings"]
347
+ if st and st[0]["target"] in pkg.names:
348
+ sx = pkg.xml(st[0]["target"])
349
+ for tag in ("rsids", "attachedTemplate", "docVars"):
350
+ for el in sx.findall(f"w:{tag}", NS):
351
+ sx.remove(el)
352
+ stripped.append(tag)
353
+ srels_name = pkg.rels_name(st[0]["target"])
354
+ if srels_name in pkg.names:
355
+ sr = pkg.xml(srels_name)
356
+ for r in list(sr.findall("pr:Relationship", NS)):
357
+ if r.get("Type", "").endswith("/attachedTemplate"):
358
+ sr.remove(r)
359
+ touched.add(srels_name)
360
+ touched.add(st[0]["target"])
361
+ actions["metadata_stripped"] = sorted(set(stripped))
362
+ actions["rsid_attributes_removed"] = rsid_n
363
+ if a.remove_active:
364
+ act = {}
365
+ macro = {n for n in pkg.names if n.lower().endswith(("vbaproject.bin", "vbadata.xml"))}
366
+ ax = {n for n in pkg.names if n.startswith(("word/activeX/", "word/embeddings/"))}
367
+ removed |= macro | ax
368
+ act["macro_parts_removed"] = sorted(macro)
369
+ act["activex_and_ole_parts_removed"] = len(ax)
370
+ objs = chunks = fields_n = 0
371
+ for part in stories + glossary + [n for n in xml_parts if n.endswith("comments.xml")]:
372
+ if part not in pkg.names or part in removed:
373
+ continue
374
+ root = pkg.xml(part)
375
+ hit = False
376
+ for el in list(root.iter(w("object"), w("control"))):
377
+ if el.getparent() is not None:
378
+ el.getparent().remove(el)
379
+ objs += 1
380
+ hit = True
381
+ for el in list(root.iter(w("altChunk"))):
382
+ rid = el.get(f"{R_ATTR}id")
383
+ tgt = next((r["target"] for r in pkg.rels(part) if r["id"] == rid and not r["external"]), None)
384
+ if tgt:
385
+ removed.add(tgt)
386
+ el.getparent().remove(el)
387
+ chunks += 1
388
+ hit = True
389
+ k = neutralize_fields(root)
390
+ if k:
391
+ fields_n += k
392
+ hit = True
393
+ if hit:
394
+ touched.add(part)
395
+ act["objects_and_controls_removed"] = objs
396
+ act["alt_chunks_removed"] = chunks
397
+ act["risky_fields_replaced_by_result"] = fields_n
398
+ # external relationships other than hyperlinks, and the elements that use them
399
+ ext_n = 0
400
+ for rn in [n for n in pkg.names if n.endswith(".rels")]:
401
+ src = rels_source(rn)
402
+ gone = set()
403
+ rx = pkg.xml(rn)
404
+ for r in list(rx.findall("pr:Relationship", NS)):
405
+ if r.get("TargetMode") == "External" and not r.get("Type", "").endswith("/hyperlink"):
406
+ gone.add(r.get("Id"))
407
+ rx.remove(r)
408
+ if not gone:
409
+ continue
410
+ ext_n += len(gone)
411
+ touched.add(rn)
412
+ if src and src in pkg.names and src.endswith(".xml") and src not in removed:
413
+ root = pkg.xml(src)
414
+ for el in list(root.iter()):
415
+ hits = [k for k, v in el.attrib.items() if k.startswith(R_ATTR) and v in gone]
416
+ if not hits or el.getparent() is None:
417
+ continue
418
+ if el.tag.rsplit("}", 1)[-1] in ("blip", "imagedata"):
419
+ for k in hits:
420
+ del el.attrib[k]
421
+ else:
422
+ el.getparent().remove(el)
423
+ touched.add(src)
424
+ for part in stories + glossary:
425
+ if part in pkg.names and part not in removed:
426
+ for el in pkg.xml(part).iter("{urn:schemas-microsoft-com:vml}imagedata"):
427
+ if el.attrib.pop(f"{{{VML_O}}}href", None) is not None:
428
+ ext_n += 1
429
+ touched.add(part)
430
+ act["external_relationships_removed"] = ext_n
431
+ st = [r for r in pkg.rels(pkg.main) if r["type"] == "settings"]
432
+ if st and st[0]["target"] in pkg.names:
433
+ sx = pkg.xml(st[0]["target"])
434
+ for tag in ("mailMerge", "updateFields"):
435
+ for el in sx.findall(f"w:{tag}", NS):
436
+ sx.remove(el)
437
+ act.setdefault("settings_removed", []).append(tag)
438
+ touched.add(st[0]["target"])
439
+ if pkg.kind in PLAIN_TYPE:
440
+ ct = pkg.xml("[Content_Types].xml")
441
+ for o in ct.findall("ct:Override", NS):
442
+ if o.get("PartName", "").lstrip("/") == pkg.main:
443
+ o.set("ContentType", PLAIN_TYPE[pkg.kind])
444
+ touched.add("[Content_Types].xml")
445
+ act["content_type"] = f"{pkg.kind} -> {'docx' if pkg.kind == 'docm' else 'dotx'}"
446
+ actions["active_content"] = act
447
+ if removed:
448
+ # relationships that point at removed parts, from every remaining .rels file
449
+ for rn in [n for n in pkg.names if n.endswith(".rels")]:
450
+ src = rels_source(rn)
451
+ if src in removed or rn in removed:
452
+ removed.add(rn)
453
+ continue
454
+ targets = {r["id"]: r["target"] for r in pkg.rels(src) if not r["external"]}
455
+ rx = pkg.xml(rn)
456
+ for r in list(rx.findall("pr:Relationship", NS)):
457
+ if targets.get(r.get("Id")) in removed:
458
+ rx.remove(r)
459
+ touched.add(rn)
460
+ ct = pkg.xml("[Content_Types].xml")
461
+ for o in list(ct.findall("ct:Override", NS)):
462
+ if o.get("PartName", "").lstrip("/") in removed:
463
+ ct.remove(o)
464
+ touched.add("[Content_Types].xml")
465
+ for part in touched:
466
+ if part not in removed:
467
+ replaced[part] = wp.serialize(pkg.xml(part))
468
+ wp.write_package(pkg.zip, a.output, replaced, removed)
469
+ except (wp.Unsupported, wp.Refusal, OSError) as e:
470
+ done(3 if isinstance(e, wp.Refusal) else 2, ok=False, error=clean(str(e), 400))
471
+
472
+ after = inspect_docx.inspect(a.output)
473
+ remaining = after["residue"]
474
+ wanted = set()
475
+ if a.accept_changes:
476
+ wanted.add("tracked_changes")
477
+ if a.remove_comments:
478
+ wanted.add("comments")
479
+ if a.remove_hidden:
480
+ wanted.add("hidden_text")
481
+ if a.remove_glossary:
482
+ wanted.add("glossary_document")
483
+ if a.strip_metadata:
484
+ wanted |= {"personal_metadata", "custom_properties", "thumbnail", "edit_session_ids",
485
+ "document_variables", "template_or_base_path", "custom_xml"}
486
+ if a.remove_active:
487
+ wanted |= {"macros_or_activex", "embedded_objects", "external_relationships"}
488
+ bad = sorted(set(remaining) & wanted)
489
+ errors = []
490
+ if bad:
491
+ errors.append(f"requested categories still present: {bad}")
492
+ if a.remove_hidden and hidden_field_runs:
493
+ errors.append(f"{hidden_field_runs} hidden runs hold field codes and were kept; fix them in Word")
494
+ if a.remove_active and after["risks"]:
495
+ errors.append("risks remain after --remove-active")
496
+ if a.share and remaining:
497
+ errors.append(f"--share: residue remains: {remaining}")
498
+ res = {"ok": not errors, "output": a.output, "actions": actions, "remaining": remaining,
499
+ "kept_metadata": kept, "risks_after": after["risks"],
500
+ "not_checked": after["clean_scope"]["not_checked"]}
501
+ if errors:
502
+ res["error"] = "; ".join(errors)
503
+ done(1 if errors else 0, **res)
504
+
505
+
506
+ if __name__ == "__main__":
507
+ main()