@ansonlai/docx-redline-js 0.8.3 → 0.8.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.
package/README.md CHANGED
@@ -1,901 +1,905 @@
1
- # @ansonlai/docx-redline-js
2
-
3
- Host-independent OOXML reconciliation engine for `.docx` manipulation with track changes (redlines).
4
-
5
- Converts AI-generated or programmatic text/markdown edits into valid Office Open XML (OOXML) with `w:ins`/`w:del` revision markup that Microsoft Word renders as native tracked changes.
6
-
7
- ## Features
8
-
9
- - Text reconciliation with word-level diffing and native-looking redlines
10
- - Formatting updates (bold, italic, underline, strikethrough) via surgical `w:rPrChange`
11
- - Lists: generate and edit real Word lists (`w:numPr`) from markdown
12
- - Tables: virtual-grid diffing for cell-level edits with merge safety
13
- - Comments: inject OOXML comments anchored to text ranges
14
- - Revision management: detect existing revisions, consume move revisions, and accept/reject tracked changes by author or for all authors
15
- - Comment management: delete comments by author or for all authors
16
- - Highlights: apply highlight colors to runs
17
- - Markdown and OOXML conversion in both directions
18
- - Status/error result fields for parse, targeting, and existing-revision failures
19
- - Localized exact replacements against inspected targets, plus optional fail-closed speculative CLI edits
20
- - Package plumbing helpers for numbering.xml, comments.xml, content types, and relationships
21
- - Zero host dependencies: works in Node.js, browsers, Deno, and similar JS runtimes with DOM parsing support
22
-
23
- ## What's New in 0.8.x
24
-
25
- The current release is 0.8.3. The CLI contract remains version 8 throughout the 0.8 line.
26
-
27
- - **0.8.0, universal document facade:** `openDocx` and `DocxDocument` are exported from the primary entry point and work
28
- on `Uint8Array` input in any JavaScript runtime. ZIP handling uses `fflate` and SHA-256 is pure JavaScript, so there are no
29
- Node built-in dependencies. The XML provider falls back to `@xmldom/xmldom` automatically, and the
30
- `@ansonlai/docx-redline-js/bundle` export provides zero-dependency single-file bundles for sandboxes such as n8n Code
31
- nodes. The `/node` entry point keeps its existing API. See the [0.8.0 release notes](./docs/releases/0.8.0.md).
32
- - **0.8.1, headers, footers and comment threads:** an operation's `part` field edits headers and footers;
33
- `inspect().headersFooters` lists them. Comment threads can be resolved or reopened with `doc.resolveComment` or the
34
- `comment_resolve` operation, and comments can be deleted by id with `doc.deleteComments({ ids })` or
35
- `docx-redline delete-comments --comment-id`. See the [0.8.1 release notes](./docs/releases/0.8.1.md).
36
- - **0.8.2, fixes:** a replacement beside a hyperlink no longer pulls adjacent plain text into the link, and Reject All no
37
- longer reorders text around a manual line break. See the [0.8.2 release notes](./docs/releases/0.8.2.md).
38
- - **0.8.3, list fixes:** Reject All now restores list edits exactly (no extra empty paragraph after an inserted
39
- paragraph, no merged source paragraphs after a list-range replacement, original list numbering kept through `openDocx`),
40
- and inspection no longer reports tracked historical list, style or heading properties as current. See the
41
- [0.8.3 release notes](./docs/releases/0.8.3.md).
42
-
43
- Version 0.7.0 introduced contract-8 localized edits: a small `find`/`replace` request against an inspected target instead
44
- of a complete paragraph, plus an optional speculative form that fails without writing when the anchor is missing or
45
- ambiguous. They remain available unchanged; see the [0.7.0 release notes](./docs/releases/0.7.0.md).
46
-
47
- ## Documentation Index
48
-
49
- | Document | Description |
50
- |---|---|
51
- | **[README.md](./README.md)** | Library overview, installation, quick start, and public API reference |
52
- | **[docs/AGENT_FAST_START.md](./docs/AGENT_FAST_START.md)** | Compact ordinary-edit protocol for structured tools and shell-only agents |
53
- | **[AGENTS.md](./AGENTS.md)** | Short repository launch card for task routing and contributor verification |
54
- | **[docs/AGENT_KNOWLEDGE_BASE.md](./docs/AGENT_KNOWLEDGE_BASE.md)** | Full agent reference, CLI workflow, operation examples, error recovery, options, and gotchas |
55
- | **[ARCHITECTURE.md](./ARCHITECTURE.md)** | Contributor architecture, module responsibilities, end-to-end data flow, and contracts |
56
- | **[docs/TESTING.md](./docs/TESTING.md)** | Complete testing guide, test lanes, independent oracle validation, and Word visual review checklist |
57
- | **[CHANGELOG.md](./CHANGELOG.md)** | Release history, breaking changes, and migration notes |
58
-
59
- ## Repository Layout
60
-
61
- The package exposes three levels of API:
62
-
63
- | Level | Entry point | Use it for |
64
- |---|---|---|
65
- | Host-independent OOXML API | `index.js` | Paragraph/range transforms and exported OOXML utilities in browsers, Node.js, or another DOM-capable runtime |
66
- | Standalone document XML runner | `services/standalone-operation-runner.js` | Applying operations to a complete `word/document.xml` string |
67
- | Node/DOCX API and CLI | `node/index.js`, `bin/docx-redline.js` | Reading, changing, validating, and writing complete `.docx` ZIP packages |
68
-
69
- Implementation folders have distinct roles: `core/` holds shared OOXML and
70
- targeting primitives; `pipeline/` handles ingestion, diffing, markdown, lists,
71
- and serialization; `engine/` performs reconciliation; `services/` coordinates
72
- document operations and package artifacts; `node/` contains Node-only ZIP and
73
- whole-document code. Tests are directly runnable `tests/*.mjs` files, while
74
- `tests/helpers/` and `tests/fixtures/` contain support code and data.
75
-
76
- Contributors and coding agents should start with the routing table in
77
- [AGENTS.md](./AGENTS.md#pick-the-route) before exploring the tree. The full
78
- dependency and ownership map is in [ARCHITECTURE.md](./ARCHITECTURE.md).
79
-
80
- For document-operation JSON, choose operations by the desired output structure,
81
- not by the everyday meaning of the type name. `redline` and `replace` provide
82
- ordinary text replacement; `list-change` and `table-reconciliation` provide
83
- structural intent; and ordinary `insert` is a compatibility alias of the
84
- redline path unless it includes a rejected-view target and anchor. In every
85
- ordinary text-bearing operation, `modified` is the complete desired content for
86
- the target. See the [operation model](./docs/AGENT_KNOWLEDGE_BASE.md#operation-model-choose-by-output-shape)
87
- and the [JSON schema](./docs/schemas/document-operations.schema.json).
88
-
89
- ## Install
90
-
91
- ### npm / Node.js
92
-
93
- ```bash
94
- npm install @ansonlai/docx-redline-js
95
- ```
96
-
97
- ### CDN (browser `<script type="module">`)
98
-
99
- ```html
100
- <script type="module">
101
- import { applyRedlineToOxml } from 'https://esm.sh/@ansonlai/docx-redline-js';
102
- </script>
103
- ```
104
-
105
- Or use the pre-bundled file (no import map needed, `diff-match-patch` is inlined):
106
-
107
- ```html
108
- <script type="module">
109
- import { applyRedlineToOxml } from 'https://cdn.jsdelivr.net/npm/@ansonlai/docx-redline-js/dist/docx-redline-js.esm.min.js';
110
- </script>
111
- ```
112
-
113
- ### Local git clone
114
-
115
- ```bash
116
- git clone https://github.com/AnsonLai/docx-redline-js.git
117
- ```
118
-
119
- ```js
120
- import { applyRedlineToOxml } from './docx-redline-js/index.js';
121
- ```
122
-
123
- ## Quick Start
124
-
125
- ### Node.js
126
-
127
- ```js
128
- import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
129
- import {
130
- configureXmlProvider,
131
- setDefaultAuthor,
132
- applyRedlineToOxml
133
- } from '@ansonlai/docx-redline-js';
134
-
135
- configureXmlProvider({ DOMParser, XMLSerializer });
136
- setDefaultAuthor('My App');
137
-
138
- const result = await applyRedlineToOxml(
139
- paragraphOoxml,
140
- 'Original sentence.',
141
- 'Updated sentence.',
142
- { generateRedlines: true, author: 'Editor' }
143
- );
144
-
145
- console.log(result.hasChanges);
146
- console.log(result.oxml);
147
- ```
148
-
149
- ### Browser
150
-
151
- ```js
152
- import {
153
- setDefaultAuthor,
154
- applyRedlineToOxml
155
- } from '@ansonlai/docx-redline-js';
156
-
157
- setDefaultAuthor('Browser Editor');
158
-
159
- const result = await applyRedlineToOxml(oxml, original, modified, {
160
- generateRedlines: true
161
- });
162
- ```
163
-
164
- ## API Reference
165
-
166
- ### Agent-friendly inspection and complete DOCX editing
167
-
168
- ```js
169
- import { inspectDocumentParts } from '@ansonlai/docx-redline-js';
170
- const inventory = inspectDocumentParts({ documentXml, commentsXml, numberingXml });
171
- ```
172
-
173
- Inspection returns exact paragraph text, target IDs/fingerprints, headings,
174
- table/list context, revision authors, and joined comment anchors. Filters such
175
- as `search`, `indexes`, `range`, `revisedOnly`, `inTable`, and `skipEmpty`
176
- limit output. Search is a case-insensitive substring match; `around` adds nearby drafting
177
- context, while `limit` and `after` page direct hits. When a search yields 0
178
- matches in the active view, `selection.hint` provides guidance if matches exist
179
- in the alternate revision view (such as searching for deleted text to restore).
180
- Compact `extract --revised` output retains revision authors and marks paragraphs
181
- whose content is wholly hidden in the selected view as `deleted` or `inserted`.
182
- One such paragraph can be restored without restating it:
183
- `docx-redline apply input.docx --restore --target-id ID --output reviewed.docx`.
184
- Add one exact `--find`/`--replace` pair to make a localized correction while
185
- restoring. The shortcut requires a strong rejected-view paragraph ID and does
186
- not infer a range or adjacent content.
187
- `revisionView` accepts `accepted`, `rejected`, or `current`. Returned
188
- paragraphs identify matches versus context and include `humanReference` for
189
- user-facing summaries.
190
-
191
- For complete `.docx` buffers in Node:
192
-
193
- ```js
194
- import { openDocx } from '@ansonlai/docx-redline-js/node';
195
- const document = openDocx(inputBuffer);
196
- const result = await document.applyOperations(operations, {
197
- author: 'Editor', atomic: true, validate: true
198
- });
199
- const outputBuffer = result.toBuffer();
200
- ```
201
-
202
- The Node facade performs edits, artifact merges, package wiring, validation,
203
- and commit as one transaction. It defaults to strict targets and returns the
204
- untouched input with `written: false` on atomic failure. It is isolated from
205
- the root/browser dependency graph.
206
-
207
- Install `@xmldom/xmldom` alongside the package when using the Node facade or
208
- CLI; it remains an optional peer so browser consumers do not install a DOM shim.
209
-
210
- #### Example agent session wrapper (development only)
211
-
212
- [`examples/agent-session-wrapper.mjs`](./examples/agent-session-wrapper.mjs)
213
- demonstrates how a custom agent harness can keep one `DocxDocument` open, return
214
- short revision-bound target handles, apply safe defaults once, and translate a
215
- narrow edit request into canonical document operations:
216
-
217
- ```js
218
- import { readFile } from 'node:fs/promises';
219
- import { createExampleAgentSession } from './examples/agent-session-wrapper.mjs';
220
-
221
- const session = createExampleAgentSession(await readFile('contract.docx'), {
222
- profile: { author: 'Editor' }
223
- });
224
- const inspection = session.inspect({ search: 'termination', around: 2 });
225
- const clause = inspection.targets.find(target => target.role === 'match');
226
- const result = await session.applyEdits([{
227
- target: clause.handle,
228
- replacements: [{
229
- find: 'The Company may terminate',
230
- replace: 'Either party may terminate'
231
- }]
232
- }]);
233
- ```
234
-
235
- This file is a testable sample, not a package export or supported alternate
236
- mutation engine. It delegates to `@ansonlai/docx-redline-js/node`, is excluded
237
- from the published package files, and is intended to help MCP servers, Claude
238
- skills, OpenCode tools, and other custom harnesses design thin integrations.
239
- The sample binds each handle to the inspected package revision and view, returns
240
- new handles after successful mutations, and expands localized exact replacements
241
- into complete desired paragraph text before delegating to the canonical redline
242
- operation. Duplicate matches require an explicit `occurrence`; missing,
243
- ambiguous, overlapping, and conflicting patches fail before document mutation.
244
- From a source checkout, run `npm run benchmark:agent` to compare its native
245
- execution and serialized request size with a canonical stateless Node workflow.
246
- The example and its benchmark are excluded from the published package. The
247
- benchmark explicitly does not claim to measure LLM reasoning or provider/tool
248
- latency. Checked comparative results are in the
249
- [agent protocol rollout audit](./docs/validation-reports/2026-09-12-agent-protocol-rollout.md).
250
-
251
- > **Pre-1.0 integration warning:** Agent skills, MCP servers, and harnesses
252
- > should pin the exact `@ansonlai/docx-redline-js` release they were tested
253
- > against and declare the CLI contract version/capabilities they require. Do
254
- > not treat a newly installed release or contract as verified until the
255
- > integration's compatibility tests pass. See the
256
- > [skill-authoring contract](./docs/SKILL_AUTHORING.md#runtime-negotiation).
257
-
258
- ### Agent CLI
259
-
260
- ```bash
261
- # Default agent workflow: inspect once, then apply once
262
- docx-redline extract contract.docx --search "termination" --around 3
263
- node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --compact --output reviewed.docx
264
- ```
265
-
266
- ```bash
267
- # Inline one-liner edit (no operations file needed)
268
- docx-redline apply contract.docx --target "Original clause text" --modified "New clause text" --output reviewed.docx
269
-
270
- # Direct edit without tracked changes
271
- docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
272
-
273
- # Cross-author edit inside another reviewer's pending insertion
274
- docx-redline apply contract.docx --target "Another author's clause" --modified "Revised clause" --existing-revisions slice-cross-author --output reviewed.docx
275
-
276
- # High-assurance atomic batch with nonzero exit on any incomplete result
277
- docx-redline apply contract.docx --operations operations.json --atomic --require-complete --output reviewed.docx
278
-
279
- # Optional read-only audit before a deliberately staged batch
280
- docx-redline preflight contract.docx --operations operations.json --author "Editor"
281
- ```
282
-
283
- All commands emit JSON on stdout. `apply` defaults:
284
- - **Author**: Defaults to `'AI Redliner'` (or `DOCX_REDLINE_AUTHOR` environment variable).
285
- - **Output overwrite**: Destination files provided via `--output` overwrite by default. Pass `--no-overwrite` or `--no-clobber` to safeguard existing destination files. The source input is never overwritten unless `--in-place` is specified.
286
- - **Existing revisions**: Defaults to `'merge-same-author'`. Pass `--existing-revisions slice-cross-author` to edit inside another reviewer's pending insertions with native carrier slicing.
287
- - **Transactionality**: Defaults to `atomic: false` (applies valid operations and reports any failures). Pass `--atomic` for all-or-nothing rollback on any operation error.
288
- - **Complete-success exit**: Pass `--require-complete` when a progressive `partial` result must exit with code `3`; errors exit with code `2`. Without the flag, partial results retain the legacy zero exit code, so always inspect `completion`.
289
- - **Agent profile**: `--profile agent` enables complete-success exit behavior while retaining the ordinary progressive transaction and existing-revision defaults. Compose it with `--atomic` or an explicit `--existing-revisions` policy when intended, and verify the resolved `effectiveOptions`.
290
- - **Operations from stdin**: `--operations -` reads the same array or `{ operations, expectedRevision }` envelope accepted from a file. Feed it from a JSON serializer or structured process API, not shell-interpolated legal text.
291
- - **Compact stdout**: `--compact` emits one-line mutation JSON. It changes serialization only, not operation semantics.
292
- - **Tracked changes**: Defaults to `generateRedlines: true`. Pass `--no-redlines` when clean direct text edits are desired.
293
- - **Inline edits**: Use `--target <text>` with `--modified <text>` or `--comment <text>` for quick one-liners without creating a JSON file.
294
- - **Localized edits**: After extraction, use `replacements` with the inspected `paragraphId` plus `fingerprint` to avoid restating a long paragraph. Retain `exactText` locally for drafting. Targetless `--find`/`--replace` is an optional speculative path described below.
295
- - **Invisible spaces**: Localized matching is case-sensitive and tries exact text first. If no exact span exists, ordinary spaces may match DOCX non-breaking spaces; ambiguous equivalent matches still fail closed, and `change.replacements[i].matchMode` reports `space_equivalent` when used.
296
- - **Compact mutation results**: `apply`, `accept`, `reject`, and `delete-comments` omit full OOXML/package payloads and inspection text from stdout. CLI operation results omit duplicate nested receipt bodies; the ordered top-level `receipts` array is authoritative. Successful exact target-match diagnostics are omitted and equivalent-whitespace matches retain only mode/count. Node and standalone-runner results remain unchanged. Use `validate` when full issue arrays are needed.
297
-
298
- Inspection commands default to 20 direct matches and a 48 KiB soft response
299
- budget when no explicit positional scope is supplied. When a search returns 0
300
- matches in the requested view, `selection.hint` provides immediate guidance if
301
- matches exist in the alternate view (such as searching for a deleted clause to
302
- restore). Use `--limit` with `--after <paragraph-index>` to continue, `--around N`
303
- (aliases `--context` and `-C`) to include nearby paragraphs, and `--all` only
304
- for deliberate unbounded inspection. Every retained target is complete; an
305
- individually oversized paragraph is returned whole with an `oversizeItem`
306
- marker. Machine `index` and `ref` fields are for targeting and pagination, not
307
- user-facing Word locations; use `humanReference`, `provision`, or
308
- `nearestHeading` in reports.
309
-
310
- `docx-redline version` reports contract version 8 and the additive
311
- `command-help-v1`, `inspection-context-v1`, `bounded-inspection-v1`,
312
- `human-document-references-v1`, `batch-start-source-binding`,
313
- `recovery-envelope-v1`, `require-complete-exit`, `operations-stdin`,
314
- `agent-safety-profile-v2`, `deduplicated-cli-receipts`, and
315
- `compact-cli-json-v1`, `localized-replacements-v1`,
316
- `speculative-search-apply-v1`, `localized-change-summary-v1`, and
317
- `restore-shortcuts-v1`, plus `localized-space-equivalence-v1` capabilities. Header/footer
318
- `part` targeting, the `comment_resolve` operation and `delete-comments --comment-id` are advertised as
319
- `header-footer-parts-v1`, `comment-resolve-operation-v1` and `delete-comments-by-id-v1`.
320
- Wrappers should negotiate only the
321
- capabilities they use. Run `docx-redline <command> --help` for that command's
322
- machine-readable options, behavior, exit codes, canonical GitHub documentation links, and compact examples.
323
-
324
- #### Optional speculative CLI path
325
-
326
- Harnesses with a measured confidence policy may attempt a targetless localized
327
- edit. This is not the default agent workflow:
328
-
329
- ```bash
330
- # Globally unique literal
331
- docx-redline apply contract.docx --find "thirty (30) days" --replace "sixty (60) days" --profile agent --output reviewed.docx
332
-
333
- # Optional directional scope using a longer, fairly unique nearby phrase
334
- docx-redline apply contract.docx --search "distinctive nearby heading or phrase" --context-range 1:3 --find "thirty (30) days" --replace "sixty (60) days" --profile agent --output reviewed.docx
335
- ```
336
-
337
- Generic or repeated anchors can widen the unioned scope until multiple
338
- paragraphs contain `find`, causing a safe `AMBIGUOUS_TARGET` failure and a
339
- recovery turn. `--around 3` is symmetric. On success,
340
- `change.context.anchorMatchCount > 1` signals a repeated anchor; confirm the
341
- returned location and bounded evidence. Matching remains case-sensitive and
342
- exact-first, with a narrow ordinary-space/NBSP fallback that still refuses
343
- ambiguity.
344
-
345
- See the [compact agent fast start](./docs/AGENT_FAST_START.md), the
346
- [skill/harness authoring contract](./docs/SKILL_AUTHORING.md), and the
347
- [operation JSON Schema](docs/schemas/document-operations.schema.json).
348
-
349
- ### Configuration (call once at startup)
350
-
351
- | Function | Purpose |
352
- |----------|---------|
353
- | `configureXmlProvider({ DOMParser, XMLSerializer })` | Inject XML parser. Required in Node.js; browsers usually provide native support. |
354
- | `configureLogger({ log, warn, error })` | Replace default console logger. |
355
- | `setDefaultAuthor(name)` | Set fallback track-change author (default: `'AI Redliner'`, configurable via `DOCX_REDLINE_AUTHOR` environment variable). |
356
- | `setPlatform(label)` | Set platform label for diagnostics (default: `'Unknown'`). |
357
-
358
- ### Options and Defaults Reference
359
-
360
- | Option | Type | Default | Description |
361
- |--------|------|---------|-------------|
362
- | `generateRedlines` | `boolean` | `true` | When `true`, emit Word-native tracked changes (`w:ins`/`w:del`). When `false`, apply clean direct edits without revision markup. **Note: Redlines are not always the preferred method** — pass `generateRedlines: false` (or `--no-redlines` via CLI) when producing clean execution drafts, restructuring documents, or when revision clutter is unwanted. |
363
- | `author` | `string` | `'AI Redliner'` | Reviewer/author name stamped on generated tracked changes and comments. Overridable via `DOCX_REDLINE_AUTHOR` env variable. |
364
- | `atomic` | `boolean` | `false` | Batch transaction mode. By default (`false`), valid edits are applied and failing operations report errors. When `true`, any operation failure rolls back the entire batch to the original document state (`rolledBack: true`, `hasChanges: false`). Feature prominently in high-assurance workflows. |
365
- | `structuredContent` | `boolean` | `true` | Auto-detects Markdown tables, headings (`#`), and lists in replacement text and renders them as native Word elements (`w:tbl`, `w:pStyle`, `w:numPr`). Pass `false` to treat replacement text strictly as plain text. |
366
- | `pairReplacements` | `boolean` | `true` | Links adjacent `<w:del>` and `<w:ins>` revisions with matching timestamps so Word groups them as a single replacement in the Reviewing Pane. |
367
- | `strictTargets` | `boolean` | `true` (CLI/facade) | Requires exact target descriptors (`exactText`, `paragraphId`, `index`, `occurrence`, `fingerprint`) and forbids ambiguous matching. Defaults to `false` in low-level runner for backwards compatibility. |
368
- | `existingRevisions` | `string` | `'merge-same-author'` | How to handle paragraphs with existing tracked changes. `'merge-same-author'` merges revisions from the same author and protects other authors with `EXISTING_REVISIONS`. `'slice-cross-author'` keeps that same-author merge behavior while allowing Word-native edits inside another author's pending insertion. Pass `'accept-all-first'` to normalize prior revisions or `'reject-input'` to refuse editing revised paragraphs. |
369
- | `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
370
- | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
371
-
372
- Same-author revision merging refuses paragraphs containing comment anchors with
373
- `COMMENTED_CONTENT_MERGE`; resolve those comments first so the merge cannot
374
- remove or orphan their anchors.
375
-
376
- Common result fields:
377
-
378
- | Field | Purpose |
379
- |-------|---------|
380
- | `status` | Operation status: `'ok'`, `'partial'`, `'no-op'`, or `'error'`. |
381
- | `error` | Present on failure; retains a stable `code` and adds recovery envelope version, stage, category, bounded context, and a machine-readable recovery action. |
382
- | `written` | CLI/facade boolean indicating whether the output file was successfully written to disk. |
383
- | `completion` | CLI-only boolean that is `true` only when a destination was written, top-level status is neither error nor partial, and no operation result failed. |
384
- | `rolledBack` | Present and `true` when an atomic batch encountered an error and rolled back all changes. |
385
-
386
- Word diffs are deterministic by default (no wall-clock timeout). Inputs above
387
- the safe ceiling of 262,144 unique diff tokens return `DIFF_TOKEN_LIMIT` with
388
- the original OOXML unchanged so callers can split the operation without risking
389
- silent text loss.
390
-
391
- ### Editing inside existing revisions (cross-author slicing)
392
-
393
- During multi-round legal negotiations, a reviewer often needs to edit text that was previously inserted by another reviewer whose revision is still pending. Pass `existingRevisions: 'slice-cross-author'` (or `--existing-revisions slice-cross-author` via CLI) to edit inside another author's pending insertion without erasing their attribution or requiring prior acceptance:
394
-
395
- ```js
396
- const result = await applyRedlineToOxml(paragraphOoxml, originalText, modifiedText, {
397
- generateRedlines: true,
398
- author: 'Reviewer B',
399
- existingRevisions: 'slice-cross-author'
400
- });
401
- ```
402
-
403
- The engine applies Microsoft Word Desktop-native tracked change structures:
404
- - **Insertions inside pending insertions**: The carrier `<w:ins>` is split into sibling `<w:ins>` containers at the paragraph level (`[ins(Author A), ins(Author B), ins(Author A)]`), maintaining strict schema compliance without illegal `ins/ins` nesting.
405
- - **Deletions inside pending insertions**: The new `<w:del>` is nested directly inside the carrier `<w:ins>` (valid under ECMA-376 Part 1 `CT_RunTrackChange`), ensuring that if Author A's insertion is rejected, Author B's dependent deletion is cleanly removed with it.
406
- - **Straddle deletions**: Deletions spanning between baseline text and pending insertions cleanly partition across their respective container contexts without invalid coalescing.
407
- - **Lifecycle parity**: Accepting or rejecting either reviewer independently produces identical results to Microsoft Word Desktop's native review pane.
408
-
409
- ### Replacing a heading with a tracked list
410
-
411
- The list route treats a one-paragraph heading expanded into multiple markdown
412
- items as a structural block replacement. The deleted heading stays in its own
413
- tracked paragraph, and every inserted item becomes a separate Word list
414
- paragraph. Accepting the revisions produces only the list items; rejecting them
415
- restores the original heading exactly.
416
-
417
- ```js
418
- const result = await applyRedlineToOxml(
419
- headingParagraphOoxml,
420
- 'A.\tPURPOSE',
421
- '* Article A. Purpose and Interagency Alignment\n' +
422
- '* Key Focus: Joint Street Outreach & Medical Triage',
423
- { generateRedlines: true, author: 'Editor' }
424
- );
425
- ```
426
-
427
- `w:numId w:val="0"` means numbering is explicitly suppressed; it is not a list
428
- definition and is never reused for generated bullets. New list items receive a
429
- positive numbering ID. Font family, size, language, and related script
430
- properties are inherited from the source paragraph, while heading emphasis
431
- (such as bold or underline) is not copied unless the replacement markdown asks
432
- for it. For a complete `word/document.xml`, prefer
433
- `applyOperationToDocumentXml(...)` so replacement nodes and numbering artifacts
434
- are imported at the correct scope.
435
-
436
- ### Planning large mixed-content insertions
437
-
438
- For an attachment or schedule containing several kinds of content, use
439
- `planStructuredReplacement(...)` before applying the edit. It decomposes the
440
- Markdown into typed heading, paragraph, list, and table blocks, normalizes the
441
- block boundaries, and returns one atomic operation with
442
- `structuredContent: true`.
443
-
444
- ```js
445
- import { planStructuredReplacement } from '@ansonlai/docx-redline-js';
446
-
447
- const plan = planStructuredReplacement(
448
- { exactText: 'Date', index: 172 },
449
- `# ATTACHMENT 4
450
-
451
- Introductory paragraph.
452
-
453
- | Agency | Contact |
454
- | --- | --- |
455
- | BCHD | Dr. Jenkins |
456
-
457
- ## Protocol
458
-
459
- 1. Joint clearance
460
- 2. Rapid escalation`,
461
- { author: 'Editor' }
462
- );
463
-
464
- if (!plan.valid || !plan.operation) {
465
- throw new Error(plan.issues.map(issue => issue.message).join(' '));
466
- }
467
-
468
- const result = await document.applyOperations([plan.operation], {
469
- author: 'Editor', atomic: true, validate: true
470
- });
471
- ```
472
-
473
- Every Markdown table must include a separator row immediately below its header.
474
- Missing separators, missing data rows, and inconsistent column counts are
475
- reported as structured errors instead of being inserted as visible pipe text.
476
- Use `#` through `#########` to request Word heading paragraphs; blank lines
477
- separate paragraphs; adjacent list markers form a real Word list. Keep the
478
- planned content in one operation so later blocks do not depend on an anchor that
479
- an earlier block has already replaced.
480
-
481
- ### Pipeline (lower-level access)
482
-
483
- | Function | Purpose |
484
- |----------|---------|
485
- | `ReconciliationPipeline` | Direct pipeline access (ingest, diff, patch, serialize). |
486
- | `ingestWordOoxmlToPlainText(oxml)` | Extract plain text from OOXML. |
487
- | `ingestWordOoxmlToMarkdown(oxml)` | Convert OOXML to markdown. |
488
- | `ingestWordOoxmlToPlainTextResult(oxml)` | Extract text as `{ text, status, error?, warnings? }`, distinguishing malformed input from an empty document. |
489
- | `ingestWordOoxmlToMarkdownResult(oxml)` | Markdown counterpart to the result-returning plain-text helper. |
490
- | `ingestOoxml(oxml)` | Flatten OOXML into an internal run model with offsets. |
491
- | `preprocessMarkdown(text)` | Normalize markdown and extract format hints. |
492
- | `analyzeStructuredContent(markdown)` | Decompose mixed Markdown into typed blocks and report malformed table syntax without creating an operation. |
493
- | `planStructuredReplacement(target, markdown, options)` | Validate mixed content and return one atomic `structuredContent` replacement operation, or `operation: null` with issues. |
494
- | `containsTrackedChanges(xmlDoc)` | Detect `w:ins`, `w:del`, move revisions, property changes, and paragraph-mark revision markup in a parsed OOXML document/fragment. |
495
- | `validateRedlineOoxml(oxml)` | Validate generated redline OOXML against the package's structural invariants (no nested revisions, `w:delText` inside `w:del`, complete metadata, unique revision ids, preserved boundary whitespace). Returns `{ valid, issues }`; run it before writing output into a package. |
496
-
497
- ### Services
498
-
499
- | Function | Purpose |
500
- |----------|---------|
501
- | `injectCommentsIntoOoxml(oxml, comments, options)` | Add comments anchored to text ranges. |
502
- | `applyCommentReplyToParts(options)` | Build a threaded reply in `comments.xml` and `commentsExtended.xml` without adding a document-body anchor. |
503
- | `acceptTrackedChangesInOoxml(oxml, { author?, allAuthors? })` | Accept `w:ins` / `w:del` / `w:moveFrom` / `w:moveTo` / `*PrChange` revisions for one author or all authors. |
504
- | `rejectTrackedChangesInOoxml(oxml, { author?, allAuthors? })` | Reject `w:ins` / `w:del` / `w:moveFrom` / `w:moveTo` / `*PrChange` revisions for one author or all authors. |
505
- | `deleteCommentsByAuthorInOoxml(oxml, { author?, allAuthors? })` | Delete matching comment definitions and anchors present in the supplied OOXML payload. Real `.docx` packages require updating both `word/comments.xml` and `word/document.xml`. |
506
- | `generateTableOoxml(headers, rows, options)` | Generate a `w:tbl` from tabular data. |
507
- | `createDynamicNumberingIdState(numberingXml)` | Allocate numbering IDs without collisions. |
508
- | `ensureNumberingArtifactsInZip(zip, numberingXml, options)` | Add numbering artifacts to a `.docx` package. Replacement of existing numbering without `mergeNumberingXmlBySchemaOrder` is deprecated and will throw in the next major version. |
509
- | `ensureCommentsArtifactsInZip(zip, commentsXml)` | Merge comments artifacts into a `.docx` package. |
510
- | `ensureCommentsExtendedArtifactsInZip(zip, commentsExtendedXml)` | Add or replace modern Word comment-thread metadata in a `.docx` package. |
511
- | `validateDocxPackage(zip)` | Validate `.docx` structural consistency. |
512
-
513
- Malformed OOXML never escapes these public transform APIs as a raw parser
514
- exception. Transforms return `status: 'error'` with `error.code === 'PARSE_ERROR'`;
515
- validators return a `PARSE_ERROR` issue. Recoverable XML parser
516
- diagnostics are forwarded through the configured logger and included in
517
- `warnings` where the result shape supports them.
518
-
519
- Cross-author slicing also verifies its exact accepted-view text before success.
520
- If a structural boundary prevents exact reconstruction, the transform returns
521
- `status: 'error'` with `error.code === 'PATCH_ROUNDTRIP_MISMATCH'`,
522
- `hasChanges: false`, and the original OOXML unchanged.
523
- Pure insertion-only slicing uses an exact character-local diff so repeated words
524
- cannot move an insertion to a different occurrence. Leading/trailing spaces,
525
- tabs, and non-breaking spaces are treated as real changes rather than no-ops.
526
- For text-bearing replacements, the exact accepted-view text of the resolved
527
- paragraph—not a space-normalized caller target—defines mutation offsets. Word-level replacement
528
- hunks that differ only by ordinary spaces and NBSPs are refined to character
529
- edits so unchanged hyperlinks and their relationship attributes stay in place.
530
- Runner results expose bounded `resolvedTarget.targetTextMatch` code-point
531
- diagnostics when equivalent whitespace was used to identify the target.
532
-
533
- ### Deep Imports
534
-
535
- For advanced usage, import specific submodules:
536
-
537
- ```js
538
- import {
539
- applyOperationToDocumentXml,
540
- applyOperationsToDocumentXml,
541
- preflightOperations,
542
- orderOperationsForStableTargets
543
- } from '@ansonlai/docx-redline-js/standalone-runner';
544
- import { getParagraphText } from '@ansonlai/docx-redline-js/core/paragraph-targeting.js';
545
- ```
546
-
547
- Use `applyOperationsToDocumentXml(...)` for mixed batches. It stably runs comments before text-changing operations so replacements cannot invalidate their original anchors. Other operation types retain their relative order. Batch results retain each operation's original 1-based index and expose the actual `executionOrder`.
548
-
549
- Before mutation, the runner resolves strong source descriptors against the
550
- immutable batch-start document and binds them to session-local source
551
- identities. Independent edits therefore do not need to be manually sorted when
552
- an earlier structural rewrite changes later paragraph indexes or fingerprints.
553
- Targets that deliberately refer to uniquely created paragraph text are compiled
554
- into an internal capture dependency. True overlap is not guessed: incompatible
555
- writes to one source fail before mutation with `OVERLAPPING_SOURCE_TARGETS` or
556
- `REVISION_ORDER_CONFLICT`, and mutating capture fan-out without distinct
557
- selectors fails with `CAPTURE_FANOUT_CONFLICT`.
558
-
559
- Threaded replies use a comment operation with no body target:
560
-
561
- ```js
562
- { type: 'comment_reply', parentCommentId: 8, commentContent: 'Agreed; I revised this.', author: 'Editor' }
563
- ```
564
-
565
- For complete `.docx` files, use `openDocx(...).applyOperations(...)`; it reads
566
- the existing comments parts, writes the required `commentsExtended.xml`
567
- relationship and content type, adds the reply's own range/reference markers to the body
568
- (Word does not display a reply without them), and keeps `commentsIds.xml` and
569
- `commentsExtensible.xml` in step when they exist. Inspection reports `paraId`, `parentCommentId` and `done`
570
- so callers can discover and verify the thread hierarchy.
571
-
572
- Resolve or reopen a thread with an operation (usable from the CLI through `apply --operations`) or the API:
573
-
574
- ```js
575
- { type: 'comment_resolve', commentId: 8 } // resolve
576
- { type: 'comment_resolve', commentId: 8, resolved: false } // reopen
577
- await doc.resolveComment(8, { resolved: true });
578
- ```
579
-
580
- Resolved is a thread-level state in Word, so any id in the thread updates the root and all replies. Delete
581
- specific comments with `doc.deleteComments({ ids: [8] })` or `docx-redline delete-comments file.docx --comment-id 8`;
582
- deleting a thread root also deletes its replies.
583
-
584
- Headers and footers are edited by adding `part` to an operation: `{ type: 'replace', part: { kind: 'footer' }, target: { exactText: 'Draft v1' }, modified: 'Draft v2' }`.
585
- `openDocx(...).inspect().headersFooters` lists the parts (path, kind, type, sections, text, whether they contain
586
- fields). Fields such as `PAGE` are treated as atomic, comments are not allowed in headers or footers, and `accept`/`reject`
587
- also resolve revisions inside them. Creating a header or footer that does not exist is not supported; see
588
- [Known limitations](docs/plans/KNOWN_BUGS.md#4-headers-and-footers).
589
-
590
- A whole-paragraph `delete` that targets existing comment markup fails with
591
- `COMMENTED_CONTENT_DELETE`. In the Node facade and CLI, the error also includes
592
- the affected comment author and text. Resolve the feedback or explicitly remove
593
- the comment first; the library will not silently discard reviewer context.
594
-
595
- The batch runner keeps one live document DOM and performs one final full-document
596
- serialization. Accuracy remains the controlling constraint: each operation has
597
- an internal savepoint so an error or no-op cannot leak a partial edit or consumed
598
- revision ID into later operations.
599
-
600
- Batches are progressive by default (`atomic: false`): valid operations commit
601
- while failed operations remain unapplied and are reported in `results`. Pass
602
- `{ atomic: true }` when any operation error must return the original
603
- `documentXml`, `hasChanges: false`, empty package artifacts, and
604
- `rolledBack: true`. The default `continueOnError: true` still attempts the full
605
- batch so `results` describes every operation; use `{ continueOnError: false }`
606
- to stop after the first error.
607
-
608
- Every failed or partial mutation includes `retryPlan`. Its `base` is `original`
609
- after rollback/no commit and `output` after a progressive partial commit;
610
- `committedIndexes`, `failedIndexes`, and `unattemptedIndexes` identify the safe
611
- replay scope. Errors use recovery envelope version 1 and always report
612
- `sameArgumentsSafe: false`. Follow `error.recovery.action`; do not infer a retry
613
- from prose. Authorization-sensitive actions, such as resolving comments, are
614
- marked with `requiresUserAuthorization: true`. For `EXISTING_REVISIONS`, the
615
- non-normalizing surgical recommendation is `slice-cross-author`; accepting or
616
- rejecting prior revisions still requires explicit authority.
617
-
618
- Comment anchors use exact matching first, then a unique ASCII-space/NBSP
619
- equivalent match that preserves source offsets and text. Missing anchors return
620
- `ANCHOR_NOT_FOUND`; repeated matches return `AMBIGUOUS_ANCHOR`. Both are
621
- operation errors and therefore roll back atomic batches. When `textToComment`
622
- is omitted, the exact text of the resolved paragraph is used.
623
-
624
- Operations may override the batch author and may use a strict target descriptor:
625
-
626
- ```js
627
- const operations = [{
628
- type: 'replace',
629
- author: 'Contract Editor',
630
- target: {
631
- exactText: 'Either party may terminate on notice.',
632
- paragraphId: '1A2B3C4D',
633
- index: 12,
634
- fingerprint: 'fnv1a32:...'
635
- },
636
- modified: 'Either party may terminate on 30 days written notice.'
637
- }];
638
-
639
- const preflight = preflightOperations(documentXml, operations, 'Fallback Author');
640
- if (!preflight.valid) {
641
- // Resolve missing/ambiguous targets, anchors, revision policies, or conflicts.
642
- }
643
-
644
- const result = await applyOperationsToDocumentXml(
645
- documentXml,
646
- operations,
647
- 'Fallback Author',
648
- null,
649
- { strictTargets: true }
650
- );
651
- ```
652
-
653
- Preflight is read-only and uses strict targeting by default. It reports
654
- `AMBIGUOUS_TARGET` with candidates instead of selecting the first duplicate,
655
- does not use fuzzy fallback, checks comment/highlight anchors and existing
656
- revision policy, identifies same-paragraph operation conflicts, and reports
657
- authors plus required comments/numbering artifacts.
658
-
659
- Application currently defaults to permissive targeting for backward compatibility,
660
- but will default to `strictTargets: true` in v1.0.0. When permissive resolution
661
- chooses among multiple candidate paragraphs heuristically, it emits an
662
- `AMBIGUOUS_TARGET_HEURISTIC_USED` warning containing candidate count and migration
663
- guidance. Callers should pass `{ strictTargets: true }` and use strict descriptors
664
- (`paragraphId`, `index`, `occurrence`, or `fingerprint`) to prepare for v1.0.0.
665
-
666
- ### Mutation Receipts
667
-
668
- Both single-operation (`applyOperationToDocumentXml`) and batch
669
- (`applyOperationsToDocumentXml`) results expose commit-aware **Mutation Receipts**
670
- (`result.receipt` on single results and per-item `results[i].receipt`, plus `result.receipts`
671
- for the full batch).
672
-
673
- This full receipt shape is retained by the Node facade and standalone runner.
674
- Only compact CLI JSON removes duplicate `results[i].receipt` bodies and keeps
675
- the ordered top-level `receipts` array.
676
-
677
- ```js
678
- const result = await applyOperationsToDocumentXml(documentXml, operations, 'Agent');
679
- for (const receipt of result.receipts) {
680
- console.log(receipt.operationIndex, receipt.finalDisposition, receipt.committed);
681
- console.log('Revisions:', receipt.revisionItems);
682
- console.log('Comments:', receipt.commentIds);
683
- }
684
- ```
685
-
686
- Receipts report:
687
- - `operationIndex` (1-based), `operationId`, and `authorUsed`
688
- - `attemptedDisposition` and `finalDisposition` (`applied`, `refused`, `no_change`, `rolled_back`, or `not_attempted`)
689
- - `committed` (boolean: verified committed into serialized package output)
690
- - `revisionItems` (exact allocated revision IDs with kind and target part)
691
- - `commentIds`, `numberingIds`, and `relationshipIds`
692
- - `affectedTargets` (resolved target coordinates) and `warnings`
693
-
694
- Before completing an operation or batch transaction, `reconcileReceiptsAgainstOutput`
695
- verifies every reported committed durable ID against a fresh parse of the output OOXML.
696
- Any discrepancy fails closed and triggers immediate rollback.
697
-
698
- ### Output Shape Matrix
699
-
700
- Different APIs return different OOXML shapes. Use this as a packaging safety check.
701
-
702
- | API | Typical input scope | Output field | Possible root/output shape | Safe to write directly into `word/document.xml` |
703
- |-----|----------------------|--------------|----------------------------|--------------------------------------------------|
704
- | `applyRedlineToOxml(...)` | Paragraph, range, or table-scope OOXML | `result.oxml` | Fragment, `<w:document>`, or package payload (`<pkg:package>`) | No. Inspect first. |
705
- | `applyRedlineToOxmlWithListFallback(...)` | Paragraph or range-scope OOXML | `result.oxml` | Fragment, `<w:document>`, or package payload (`<pkg:package>`) | No. Inspect first. |
706
- | `reconcileMarkdownTableOoxml(...)` | Table or paragraph-scope OOXML | `result.oxml` | Same shapes as `applyRedlineToOxml(...)` for the supplied scope | No. Inspect first. |
707
- | `applyOperationToDocumentXml(...)` | Full `word/document.xml` string | `result.documentXml` | `<w:document>` | Yes. This is the document-safe helper. |
708
- | `applyOperationsToDocumentXml(...)` | Full `word/document.xml` plus an operation batch | `result.documentXml` | `<w:document>` | Yes. Atomic by default; comments are applied before text-changing operations. |
709
- | `extractReplacementNodesFromOoxml(...)` | Any OOXML payload | `{ replacementNodes, numberingXml, sourceType }` | Normalized to `fragment`, `document`, or `package` | Yes. Use this when consuming `result.oxml`. |
710
-
711
- ### Do / Don't for Packaging
712
-
713
- - Do use `applyOperationToDocumentXml(...).documentXml` when your intent is to replace `word/document.xml`.
714
- - Do use `applyOperationsToDocumentXml(...)` rather than an unsorted loop for batches containing comments and replacements that target the same original paragraph.
715
- - Redline application strips proofing markers (`w:proofErr`) from the matched target paragraph before diffing, while preserving complex-field scaffolding (`w:fldChar`, `w:instrText`) and its cached visible result as inert structure. Adjacent edits do not revise or move an unchanged field result.
716
- - Hyperlinks, bookmarks, comment range markers, tabs/breaks, and footnote/endnote references are treated as structural OOXML that should survive adjacent redline edits instead of being orphaned or wrapped in deletions.
717
- - Treat `w:numId w:val="0"` as numbering suppression, never as a reusable list
718
- ID. Generated bullet and numbered paragraphs must reference a positive ID
719
- whose definition is merged into `word/numbering.xml`.
720
- - Do use `extractReplacementNodesFromOoxml(...)` when you are consuming `result.oxml` from paragraph/range/table APIs.
721
- - Do merge numbering/comments artifacts with `ensureNumberingArtifactsInZip(...)` and `ensureCommentsArtifactsInZip(...)` when those parts are present. Supply `mergeNumberingXmlBySchemaOrder` when numbering already exists.
722
- - Don't write payloads that start with `<pkg:package` directly into `word/document.xml`.
723
- - Don't assume every `result.oxml` payload is a raw paragraph fragment.
724
-
725
- ## Working With `.docx` Files
726
-
727
- This package operates on OOXML strings (XML parts inside `.docx` zip archives), not raw `.docx` binaries.
728
-
729
- Typical flow:
730
-
731
- 1. Extract the `.docx` zip (for example with JSZip, fflate, or similar)
732
- 2. Read `word/document.xml`
733
- 3. Apply reconciliation APIs to XML strings
734
- 4. Merge numbering/comments artifacts when needed
735
- 5. Write the archive back to a `.docx` file
736
-
737
- ```js
738
- import JSZip from 'jszip';
739
- import {
740
- applyRedlineToOxml,
741
- extractReplacementNodesFromOoxml,
742
- ensureNumberingArtifactsInZip,
743
- mergeNumberingXmlBySchemaOrder,
744
- validateDocxPackage
745
- } from '@ansonlai/docx-redline-js';
746
- import { applyOperationToDocumentXml } from '@ansonlai/docx-redline-js/standalone-runner';
747
-
748
- const zip = await JSZip.loadAsync(docxBuffer);
749
- const documentXml = await zip.file('word/document.xml').async('string');
750
-
751
- const opResult = await applyOperationToDocumentXml(
752
- documentXml,
753
- { type: 'redline', target: 'old text', modified: 'new text' },
754
- 'Editor'
755
- );
756
-
757
- // Restoring another reviewer's pending whole-paragraph deletion requires
758
- // explicit intent. The restored counterproposal becomes a separately tracked
759
- // sibling paragraph; a normal redline operation remains fail-closed.
760
- const restoration = await applyOperationToDocumentXml(
761
- documentXml,
762
- {
763
- type: 'restore',
764
- // restore targets default to the rejected view, where deleted text exists
765
- target: { paragraphId: '1A2B3C4D', exactText: 'Original deleted paragraph text.' },
766
- modified: 'Restored or adjusted paragraph text.'
767
- },
768
- 'Editor'
769
- );
770
-
771
- // A single restoration follows its deleted source paragraph. A range
772
- // restoration follows the complete deleted source block. Unchanged legacy
773
- // validation defects are retained as baseline issues; newly generated errors
774
- // fail closed before commit.
775
- // inspect/extract descriptors report their revisionView, and each fingerprint
776
- // is computed from the same view as exactText. Keep those fields together.
777
-
778
- // To insert run-level text at a location visible only in the rejected view,
779
- // provide explicit rejected-view intent and an exact anchor-relative offset.
780
- const deletedTextInsertion = await applyOperationToDocumentXml(
781
- documentXml,
782
- {
783
- type: 'insert',
784
- target: { paragraphId: '1A2B3C4D', revisionView: 'rejected' },
785
- anchor: { exactText: 'must pay', occurrence: 1, offset: 5 },
786
- modified: '[clarification] ',
787
- existingRevisions: 'slice-cross-author'
788
- },
789
- 'Editor'
790
- );
791
-
792
- // applyOperationToDocumentXml(...) returns a full w:document payload.
793
- zip.file('word/document.xml', opResult.documentXml);
794
-
795
- const fragmentResult = await applyRedlineToOxml(
796
- paragraphOoxml,
797
- 'Item text',
798
- '1. Item text',
799
- { generateRedlines: true, author: 'Editor' }
800
- );
801
- const normalized = extractReplacementNodesFromOoxml(fragmentResult.oxml);
802
-
803
- // If sourceType === 'package', merge extracted content/artifacts instead of
804
- // writing the raw pkg:package payload into word/document.xml.
805
- if (normalized.numberingXml) {
806
- await ensureNumberingArtifactsInZip(zip, normalized.numberingXml, {
807
- mergeNumberingXml: mergeNumberingXmlBySchemaOrder
808
- });
809
- }
810
-
811
- await validateDocxPackage(zip);
812
- const output = await zip.generateAsync({ type: 'nodebuffer' });
813
- ```
814
-
815
- ## Validating Output
816
-
817
- For the test-lane design and instructions for adding regression, synthetic
818
- Word, and real-corpus cases, see [docs/TESTING.md](./docs/TESTING.md).
819
-
820
- Run the automated package checks:
821
-
822
- ```bash
823
- npm test
824
- npm run test:isolation
825
- npm run check:types
826
- npm run lint
827
- npm run test:coverage
828
- ```
829
-
830
- For release-time fixture export:
831
-
832
- ```bash
833
- node scripts/export-validation-fixtures.mjs
834
- ```
835
-
836
- On Windows with desktop Word installed, you can smoke-test a completed `.docx`:
837
-
838
- ```bash
839
- npm run smoke:word -- path/to/file.docx
840
- ```
841
-
842
- To validate against Word as an independent oracle (Word itself accepts and
843
- rejects the generated revisions and the resulting text is compared to the
844
- expected outcomes):
845
-
846
- ```bash
847
- npm run test:word
848
- ```
849
-
850
- This Windows-only test command generates an English legal/administrative task
851
- suite under `tmp/word-validation/` and drives installed desktop Microsoft Word
852
- through COM. Its 33 cases include targeted reliability checks for literal
853
- content, multi-paragraph replacement, prior-revision no-op, atomic rollback,
854
- hostile revision IDs, bookmarks, internal hyperlinks, mixed formatted runs,
855
- content controls, table cells, structural tabs, locked complex fields,
856
- comments, footnotes/endnotes, headers/footers, and external hyperlinks.
857
- Structure-focused cases also assert required
858
- OOXML elements before Word independently checks Accept All and Reject All. The
859
- published library remains clean, host-independent JavaScript; Word automation
860
- exists only in development scripts.
861
-
862
- Use `npm run report:word:coverage` to print the validated task-by-structure
863
- matrix across all 33 synthetic and 31 SuperDoc scenarios. Before a release,
864
- `npm run review:word:prepare -- --cycle=0` creates a pending human-review
865
- manifest with changed cases, a rotating 20% synthetic sample, and legal plus
866
- administrative corpus representatives. See the [Word visual review guide in docs/TESTING.md](./docs/TESTING.md#microsoft-word-visual-review-guide);
867
- preparation and AI preflight never count as human sign-off.
868
-
869
- A nightly GitHub Actions workflow additionally validates generated fixtures
870
- against the ECMA-376 transitional schemas (`xmllint`), opens them with
871
- LibreOffice, and runs an extended fuzz sweep of the accept/reject round-trip
872
- invariant with a fresh seed. See [Release validation in docs/TESTING.md](./docs/TESTING.md#release-validation-and-independent-oracles).
873
-
874
- ## Architecture & Contributing
875
-
876
- - **[ARCHITECTURE.md](./ARCHITECTURE.md)**: Detailed module layout, end-to-end reconciliation flow, and contributor fast orientation.
877
- - **[AGENTS.md](./AGENTS.md)**: Fast-start routing and operational guardrails for AI coding agents.
878
- - **[docs/AGENT_FAST_START.md](./docs/AGENT_FAST_START.md)**: Minimal ordinary-edit contract for agent integrations.
879
- - **[docs/AGENT_KNOWLEDGE_BASE.md](./docs/AGENT_KNOWLEDGE_BASE.md)**: Full agent reference for APIs, operations, CLI automation, recovery, and gotchas.
880
- - **[docs/TESTING.md](./docs/TESTING.md)**: Comprehensive testing model, test lanes, independent oracle checks, and visual review checklist.
881
- - **[CHANGELOG.md](./CHANGELOG.md)**: Version history, migration guides, and deprecation schedules.
882
-
883
- ## Test Corpus Attribution
884
-
885
- Real-document reliability testing uses selected references from
886
- [docx-corpus](https://docxcorp.us/), built by
887
- [SuperDoc](https://superdoc.dev/). The dataset is licensed under the
888
- [Open Data Commons Attribution License (ODC-By) 1.0](https://opendatacommons.org/licenses/by/1-0/).
889
-
890
- Only explicitly pinned English legal and administrative documents are eligible
891
- for the initial corpus lane. References and provenance live in
892
- `tests/corpus/superdoc-english-legal-administrative.json`; downloaded documents
893
- are hash-verified and kept in ignored `tmp/` storage rather than committed. On
894
- Windows with desktop Word installed, run the reviewed 31-scenario/23-document lane with:
895
-
896
- ```bash
897
- npm run test:corpus:word
898
- ```
899
-
900
- ODC-By applies to the database; individual documents may carry additional
901
- rights, so each selected document must be reviewed before becoming a test case.
1
+ # @ansonlai/docx-redline-js
2
+
3
+ Host-independent OOXML reconciliation engine for `.docx` manipulation with track changes (redlines).
4
+
5
+ Converts AI-generated or programmatic text/markdown edits into valid Office Open XML (OOXML) with `w:ins`/`w:del` revision markup that Microsoft Word renders as native tracked changes.
6
+
7
+ ## Features
8
+
9
+ - Text reconciliation with word-level diffing and native-looking redlines
10
+ - Formatting updates (bold, italic, underline, strikethrough) via surgical `w:rPrChange`
11
+ - Lists: generate and edit real Word lists (`w:numPr`) from markdown
12
+ - Tables: virtual-grid diffing for cell-level edits with merge safety
13
+ - Comments: inject OOXML comments anchored to text ranges
14
+ - Revision management: detect existing revisions, consume move revisions, and accept/reject tracked changes by author or for all authors
15
+ - Comment management: delete comments by author or for all authors
16
+ - Highlights: apply highlight colors to runs
17
+ - Markdown and OOXML conversion in both directions
18
+ - Status/error result fields for parse, targeting, and existing-revision failures
19
+ - Localized exact replacements against inspected targets, plus optional fail-closed speculative CLI edits
20
+ - Package plumbing helpers for numbering.xml, comments.xml, content types, and relationships
21
+ - Zero host dependencies: works in Node.js, browsers, Deno, and similar JS runtimes with DOM parsing support
22
+
23
+ ## What's New in 0.8.x
24
+
25
+ The current release is 0.8.4. The CLI contract remains version 8 throughout the 0.8 line.
26
+
27
+ - **0.8.0, universal document facade:** `openDocx` and `DocxDocument` are exported from the primary entry point and work
28
+ on `Uint8Array` input in any JavaScript runtime. ZIP handling uses `fflate` and SHA-256 is pure JavaScript, so there are no
29
+ Node built-in dependencies. The XML provider falls back to `@xmldom/xmldom` automatically, and the
30
+ `@ansonlai/docx-redline-js/bundle` export provides zero-dependency single-file bundles for sandboxes such as n8n Code
31
+ nodes. The `/node` entry point keeps its existing API. See the [0.8.0 release notes](./docs/releases/0.8.0.md).
32
+ - **0.8.1, headers, footers and comment threads:** an operation's `part` field edits headers and footers;
33
+ `inspect().headersFooters` lists them. Comment threads can be resolved or reopened with `doc.resolveComment` or the
34
+ `comment_resolve` operation, and comments can be deleted by id with `doc.deleteComments({ ids })` or
35
+ `docx-redline delete-comments --comment-id`. See the [0.8.1 release notes](./docs/releases/0.8.1.md).
36
+ - **0.8.2, fixes:** a replacement beside a hyperlink no longer pulls adjacent plain text into the link, and Reject All no
37
+ longer reorders text around a manual line break. See the [0.8.2 release notes](./docs/releases/0.8.2.md).
38
+ - **0.8.3, list fixes:** Reject All now restores list edits exactly (no extra empty paragraph after an inserted
39
+ paragraph, no merged source paragraphs after a list-range replacement, original list numbering kept through `openDocx`),
40
+ and inspection no longer reports tracked historical list, style or heading properties as current. See the
41
+ [0.8.3 release notes](./docs/releases/0.8.3.md).
42
+ - **0.8.4, fixes:** localized replacements and list conversion work in paragraphs with soft line breaks, generated
43
+ bullets get their own numbering IDs, `format` accepts `textOccurrence` to format a later match, and tracked tables use
44
+ Word's row-level markup, so Word's Reject All removes them and an appended table keeps the paragraph's formatting. See
45
+ the [0.8.4 release notes](./docs/releases/0.8.4.md).
46
+
47
+ Version 0.7.0 introduced contract-8 localized edits: a small `find`/`replace` request against an inspected target instead
48
+ of a complete paragraph, plus an optional speculative form that fails without writing when the anchor is missing or
49
+ ambiguous. They remain available unchanged; see the [0.7.0 release notes](./docs/releases/0.7.0.md).
50
+
51
+ ## Documentation Index
52
+
53
+ | Document | Description |
54
+ |---|---|
55
+ | **[README.md](./README.md)** | Library overview, installation, quick start, and public API reference |
56
+ | **[docs/AGENT_FAST_START.md](./docs/AGENT_FAST_START.md)** | Compact ordinary-edit protocol for structured tools and shell-only agents |
57
+ | **[AGENTS.md](./AGENTS.md)** | Short repository launch card for task routing and contributor verification |
58
+ | **[docs/AGENT_KNOWLEDGE_BASE.md](./docs/AGENT_KNOWLEDGE_BASE.md)** | Full agent reference, CLI workflow, operation examples, error recovery, options, and gotchas |
59
+ | **[ARCHITECTURE.md](./ARCHITECTURE.md)** | Contributor architecture, module responsibilities, end-to-end data flow, and contracts |
60
+ | **[docs/TESTING.md](./docs/TESTING.md)** | Complete testing guide, test lanes, independent oracle validation, and Word visual review checklist |
61
+ | **[CHANGELOG.md](./CHANGELOG.md)** | Release history, breaking changes, and migration notes |
62
+
63
+ ## Repository Layout
64
+
65
+ The package exposes three levels of API:
66
+
67
+ | Level | Entry point | Use it for |
68
+ |---|---|---|
69
+ | Host-independent OOXML API | `index.js` | Paragraph/range transforms and exported OOXML utilities in browsers, Node.js, or another DOM-capable runtime |
70
+ | Standalone document XML runner | `services/standalone-operation-runner.js` | Applying operations to a complete `word/document.xml` string |
71
+ | Node/DOCX API and CLI | `node/index.js`, `bin/docx-redline.js` | Reading, changing, validating, and writing complete `.docx` ZIP packages |
72
+
73
+ Implementation folders have distinct roles: `core/` holds shared OOXML and
74
+ targeting primitives; `pipeline/` handles ingestion, diffing, markdown, lists,
75
+ and serialization; `engine/` performs reconciliation; `services/` coordinates
76
+ document operations and package artifacts; `node/` contains Node-only ZIP and
77
+ whole-document code. Tests are directly runnable `tests/*.mjs` files, while
78
+ `tests/helpers/` and `tests/fixtures/` contain support code and data.
79
+
80
+ Contributors and coding agents should start with the routing table in
81
+ [AGENTS.md](./AGENTS.md#pick-the-route) before exploring the tree. The full
82
+ dependency and ownership map is in [ARCHITECTURE.md](./ARCHITECTURE.md).
83
+
84
+ For document-operation JSON, choose operations by the desired output structure,
85
+ not by the everyday meaning of the type name. `redline` and `replace` provide
86
+ ordinary text replacement; `list-change` and `table-reconciliation` provide
87
+ structural intent; and ordinary `insert` is a compatibility alias of the
88
+ redline path unless it includes a rejected-view target and anchor. In every
89
+ ordinary text-bearing operation, `modified` is the complete desired content for
90
+ the target. See the [operation model](./docs/AGENT_KNOWLEDGE_BASE.md#operation-model-choose-by-output-shape)
91
+ and the [JSON schema](./docs/schemas/document-operations.schema.json).
92
+
93
+ ## Install
94
+
95
+ ### npm / Node.js
96
+
97
+ ```bash
98
+ npm install @ansonlai/docx-redline-js
99
+ ```
100
+
101
+ ### CDN (browser `<script type="module">`)
102
+
103
+ ```html
104
+ <script type="module">
105
+ import { applyRedlineToOxml } from 'https://esm.sh/@ansonlai/docx-redline-js';
106
+ </script>
107
+ ```
108
+
109
+ Or use the pre-bundled file (no import map needed, `diff-match-patch` is inlined):
110
+
111
+ ```html
112
+ <script type="module">
113
+ import { applyRedlineToOxml } from 'https://cdn.jsdelivr.net/npm/@ansonlai/docx-redline-js/dist/docx-redline-js.esm.min.js';
114
+ </script>
115
+ ```
116
+
117
+ ### Local git clone
118
+
119
+ ```bash
120
+ git clone https://github.com/AnsonLai/docx-redline-js.git
121
+ ```
122
+
123
+ ```js
124
+ import { applyRedlineToOxml } from './docx-redline-js/index.js';
125
+ ```
126
+
127
+ ## Quick Start
128
+
129
+ ### Node.js
130
+
131
+ ```js
132
+ import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
133
+ import {
134
+ configureXmlProvider,
135
+ setDefaultAuthor,
136
+ applyRedlineToOxml
137
+ } from '@ansonlai/docx-redline-js';
138
+
139
+ configureXmlProvider({ DOMParser, XMLSerializer });
140
+ setDefaultAuthor('My App');
141
+
142
+ const result = await applyRedlineToOxml(
143
+ paragraphOoxml,
144
+ 'Original sentence.',
145
+ 'Updated sentence.',
146
+ { generateRedlines: true, author: 'Editor' }
147
+ );
148
+
149
+ console.log(result.hasChanges);
150
+ console.log(result.oxml);
151
+ ```
152
+
153
+ ### Browser
154
+
155
+ ```js
156
+ import {
157
+ setDefaultAuthor,
158
+ applyRedlineToOxml
159
+ } from '@ansonlai/docx-redline-js';
160
+
161
+ setDefaultAuthor('Browser Editor');
162
+
163
+ const result = await applyRedlineToOxml(oxml, original, modified, {
164
+ generateRedlines: true
165
+ });
166
+ ```
167
+
168
+ ## API Reference
169
+
170
+ ### Agent-friendly inspection and complete DOCX editing
171
+
172
+ ```js
173
+ import { inspectDocumentParts } from '@ansonlai/docx-redline-js';
174
+ const inventory = inspectDocumentParts({ documentXml, commentsXml, numberingXml });
175
+ ```
176
+
177
+ Inspection returns exact paragraph text, target IDs/fingerprints, headings,
178
+ table/list context, revision authors, and joined comment anchors. Filters such
179
+ as `search`, `indexes`, `range`, `revisedOnly`, `inTable`, and `skipEmpty`
180
+ limit output. Search is a case-insensitive substring match; `around` adds nearby drafting
181
+ context, while `limit` and `after` page direct hits. When a search yields 0
182
+ matches in the active view, `selection.hint` provides guidance if matches exist
183
+ in the alternate revision view (such as searching for deleted text to restore).
184
+ Compact `extract --revised` output retains revision authors and marks paragraphs
185
+ whose content is wholly hidden in the selected view as `deleted` or `inserted`.
186
+ One such paragraph can be restored without restating it:
187
+ `docx-redline apply input.docx --restore --target-id ID --output reviewed.docx`.
188
+ Add one exact `--find`/`--replace` pair to make a localized correction while
189
+ restoring. The shortcut requires a strong rejected-view paragraph ID and does
190
+ not infer a range or adjacent content.
191
+ `revisionView` accepts `accepted`, `rejected`, or `current`. Returned
192
+ paragraphs identify matches versus context and include `humanReference` for
193
+ user-facing summaries.
194
+
195
+ For complete `.docx` buffers in Node:
196
+
197
+ ```js
198
+ import { openDocx } from '@ansonlai/docx-redline-js/node';
199
+ const document = openDocx(inputBuffer);
200
+ const result = await document.applyOperations(operations, {
201
+ author: 'Editor', atomic: true, validate: true
202
+ });
203
+ const outputBuffer = result.toBuffer();
204
+ ```
205
+
206
+ The Node facade performs edits, artifact merges, package wiring, validation,
207
+ and commit as one transaction. It defaults to strict targets and returns the
208
+ untouched input with `written: false` on atomic failure. It is isolated from
209
+ the root/browser dependency graph.
210
+
211
+ Install `@xmldom/xmldom` alongside the package when using the Node facade or
212
+ CLI; it remains an optional peer so browser consumers do not install a DOM shim.
213
+
214
+ #### Example agent session wrapper (development only)
215
+
216
+ [`examples/agent-session-wrapper.mjs`](./examples/agent-session-wrapper.mjs)
217
+ demonstrates how a custom agent harness can keep one `DocxDocument` open, return
218
+ short revision-bound target handles, apply safe defaults once, and translate a
219
+ narrow edit request into canonical document operations:
220
+
221
+ ```js
222
+ import { readFile } from 'node:fs/promises';
223
+ import { createExampleAgentSession } from './examples/agent-session-wrapper.mjs';
224
+
225
+ const session = createExampleAgentSession(await readFile('contract.docx'), {
226
+ profile: { author: 'Editor' }
227
+ });
228
+ const inspection = session.inspect({ search: 'termination', around: 2 });
229
+ const clause = inspection.targets.find(target => target.role === 'match');
230
+ const result = await session.applyEdits([{
231
+ target: clause.handle,
232
+ replacements: [{
233
+ find: 'The Company may terminate',
234
+ replace: 'Either party may terminate'
235
+ }]
236
+ }]);
237
+ ```
238
+
239
+ This file is a testable sample, not a package export or supported alternate
240
+ mutation engine. It delegates to `@ansonlai/docx-redline-js/node`, is excluded
241
+ from the published package files, and is intended to help MCP servers, Claude
242
+ skills, OpenCode tools, and other custom harnesses design thin integrations.
243
+ The sample binds each handle to the inspected package revision and view, returns
244
+ new handles after successful mutations, and expands localized exact replacements
245
+ into complete desired paragraph text before delegating to the canonical redline
246
+ operation. Duplicate matches require an explicit `occurrence`; missing,
247
+ ambiguous, overlapping, and conflicting patches fail before document mutation.
248
+ From a source checkout, run `npm run benchmark:agent` to compare its native
249
+ execution and serialized request size with a canonical stateless Node workflow.
250
+ The example and its benchmark are excluded from the published package. The
251
+ benchmark explicitly does not claim to measure LLM reasoning or provider/tool
252
+ latency. Checked comparative results are in the
253
+ [agent protocol rollout audit](./docs/validation-reports/2026-09-12-agent-protocol-rollout.md).
254
+
255
+ > **Pre-1.0 integration warning:** Agent skills, MCP servers, and harnesses
256
+ > should pin the exact `@ansonlai/docx-redline-js` release they were tested
257
+ > against and declare the CLI contract version/capabilities they require. Do
258
+ > not treat a newly installed release or contract as verified until the
259
+ > integration's compatibility tests pass. See the
260
+ > [skill-authoring contract](./docs/SKILL_AUTHORING.md#runtime-negotiation).
261
+
262
+ ### Agent CLI
263
+
264
+ ```bash
265
+ # Default agent workflow: inspect once, then apply once
266
+ docx-redline extract contract.docx --search "termination" --around 3
267
+ node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --compact --output reviewed.docx
268
+ ```
269
+
270
+ ```bash
271
+ # Inline one-liner edit (no operations file needed)
272
+ docx-redline apply contract.docx --target "Original clause text" --modified "New clause text" --output reviewed.docx
273
+
274
+ # Direct edit without tracked changes
275
+ docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
276
+
277
+ # Cross-author edit inside another reviewer's pending insertion
278
+ docx-redline apply contract.docx --target "Another author's clause" --modified "Revised clause" --existing-revisions slice-cross-author --output reviewed.docx
279
+
280
+ # High-assurance atomic batch with nonzero exit on any incomplete result
281
+ docx-redline apply contract.docx --operations operations.json --atomic --require-complete --output reviewed.docx
282
+
283
+ # Optional read-only audit before a deliberately staged batch
284
+ docx-redline preflight contract.docx --operations operations.json --author "Editor"
285
+ ```
286
+
287
+ All commands emit JSON on stdout. `apply` defaults:
288
+ - **Author**: Defaults to `'AI Redliner'` (or `DOCX_REDLINE_AUTHOR` environment variable).
289
+ - **Output overwrite**: Destination files provided via `--output` overwrite by default. Pass `--no-overwrite` or `--no-clobber` to safeguard existing destination files. The source input is never overwritten unless `--in-place` is specified.
290
+ - **Existing revisions**: Defaults to `'merge-same-author'`. Pass `--existing-revisions slice-cross-author` to edit inside another reviewer's pending insertions with native carrier slicing.
291
+ - **Transactionality**: Defaults to `atomic: false` (applies valid operations and reports any failures). Pass `--atomic` for all-or-nothing rollback on any operation error.
292
+ - **Complete-success exit**: Pass `--require-complete` when a progressive `partial` result must exit with code `3`; errors exit with code `2`. Without the flag, partial results retain the legacy zero exit code, so always inspect `completion`.
293
+ - **Agent profile**: `--profile agent` enables complete-success exit behavior while retaining the ordinary progressive transaction and existing-revision defaults. Compose it with `--atomic` or an explicit `--existing-revisions` policy when intended, and verify the resolved `effectiveOptions`.
294
+ - **Operations from stdin**: `--operations -` reads the same array or `{ operations, expectedRevision }` envelope accepted from a file. Feed it from a JSON serializer or structured process API, not shell-interpolated legal text.
295
+ - **Compact stdout**: `--compact` emits one-line mutation JSON. It changes serialization only, not operation semantics.
296
+ - **Tracked changes**: Defaults to `generateRedlines: true`. Pass `--no-redlines` when clean direct text edits are desired.
297
+ - **Inline edits**: Use `--target <text>` with `--modified <text>` or `--comment <text>` for quick one-liners without creating a JSON file.
298
+ - **Localized edits**: After extraction, use `replacements` with the inspected `paragraphId` plus `fingerprint` to avoid restating a long paragraph. Retain `exactText` locally for drafting. Targetless `--find`/`--replace` is an optional speculative path described below.
299
+ - **Invisible spaces**: Localized matching is case-sensitive and tries exact text first. If no exact span exists, ordinary spaces may match DOCX non-breaking spaces; ambiguous equivalent matches still fail closed, and `change.replacements[i].matchMode` reports `space_equivalent` when used.
300
+ - **Compact mutation results**: `apply`, `accept`, `reject`, and `delete-comments` omit full OOXML/package payloads and inspection text from stdout. CLI operation results omit duplicate nested receipt bodies; the ordered top-level `receipts` array is authoritative. Successful exact target-match diagnostics are omitted and equivalent-whitespace matches retain only mode/count. Node and standalone-runner results remain unchanged. Use `validate` when full issue arrays are needed.
301
+
302
+ Inspection commands default to 20 direct matches and a 48 KiB soft response
303
+ budget when no explicit positional scope is supplied. When a search returns 0
304
+ matches in the requested view, `selection.hint` provides immediate guidance if
305
+ matches exist in the alternate view (such as searching for a deleted clause to
306
+ restore). Use `--limit` with `--after <paragraph-index>` to continue, `--around N`
307
+ (aliases `--context` and `-C`) to include nearby paragraphs, and `--all` only
308
+ for deliberate unbounded inspection. Every retained target is complete; an
309
+ individually oversized paragraph is returned whole with an `oversizeItem`
310
+ marker. Machine `index` and `ref` fields are for targeting and pagination, not
311
+ user-facing Word locations; use `humanReference`, `provision`, or
312
+ `nearestHeading` in reports.
313
+
314
+ `docx-redline version` reports contract version 8 and the additive
315
+ `command-help-v1`, `inspection-context-v1`, `bounded-inspection-v1`,
316
+ `human-document-references-v1`, `batch-start-source-binding`,
317
+ `recovery-envelope-v1`, `require-complete-exit`, `operations-stdin`,
318
+ `agent-safety-profile-v2`, `deduplicated-cli-receipts`, and
319
+ `compact-cli-json-v1`, `localized-replacements-v1`,
320
+ `speculative-search-apply-v1`, `localized-change-summary-v1`, and
321
+ `restore-shortcuts-v1`, plus `localized-space-equivalence-v1` capabilities. Header/footer
322
+ `part` targeting, the `comment_resolve` operation and `delete-comments --comment-id` are advertised as
323
+ `header-footer-parts-v1`, `comment-resolve-operation-v1` and `delete-comments-by-id-v1`.
324
+ Wrappers should negotiate only the
325
+ capabilities they use. Run `docx-redline <command> --help` for that command's
326
+ machine-readable options, behavior, exit codes, canonical GitHub documentation links, and compact examples.
327
+
328
+ #### Optional speculative CLI path
329
+
330
+ Harnesses with a measured confidence policy may attempt a targetless localized
331
+ edit. This is not the default agent workflow:
332
+
333
+ ```bash
334
+ # Globally unique literal
335
+ docx-redline apply contract.docx --find "thirty (30) days" --replace "sixty (60) days" --profile agent --output reviewed.docx
336
+
337
+ # Optional directional scope using a longer, fairly unique nearby phrase
338
+ docx-redline apply contract.docx --search "distinctive nearby heading or phrase" --context-range 1:3 --find "thirty (30) days" --replace "sixty (60) days" --profile agent --output reviewed.docx
339
+ ```
340
+
341
+ Generic or repeated anchors can widen the unioned scope until multiple
342
+ paragraphs contain `find`, causing a safe `AMBIGUOUS_TARGET` failure and a
343
+ recovery turn. `--around 3` is symmetric. On success,
344
+ `change.context.anchorMatchCount > 1` signals a repeated anchor; confirm the
345
+ returned location and bounded evidence. Matching remains case-sensitive and
346
+ exact-first, with a narrow ordinary-space/NBSP fallback that still refuses
347
+ ambiguity.
348
+
349
+ See the [compact agent fast start](./docs/AGENT_FAST_START.md), the
350
+ [skill/harness authoring contract](./docs/SKILL_AUTHORING.md), and the
351
+ [operation JSON Schema](docs/schemas/document-operations.schema.json).
352
+
353
+ ### Configuration (call once at startup)
354
+
355
+ | Function | Purpose |
356
+ |----------|---------|
357
+ | `configureXmlProvider({ DOMParser, XMLSerializer })` | Inject XML parser. Required in Node.js; browsers usually provide native support. |
358
+ | `configureLogger({ log, warn, error })` | Replace default console logger. |
359
+ | `setDefaultAuthor(name)` | Set fallback track-change author (default: `'AI Redliner'`, configurable via `DOCX_REDLINE_AUTHOR` environment variable). |
360
+ | `setPlatform(label)` | Set platform label for diagnostics (default: `'Unknown'`). |
361
+
362
+ ### Options and Defaults Reference
363
+
364
+ | Option | Type | Default | Description |
365
+ |--------|------|---------|-------------|
366
+ | `generateRedlines` | `boolean` | `true` | When `true`, emit Word-native tracked changes (`w:ins`/`w:del`). When `false`, apply clean direct edits without revision markup. **Note: Redlines are not always the preferred method** — pass `generateRedlines: false` (or `--no-redlines` via CLI) when producing clean execution drafts, restructuring documents, or when revision clutter is unwanted. |
367
+ | `author` | `string` | `'AI Redliner'` | Reviewer/author name stamped on generated tracked changes and comments. Overridable via `DOCX_REDLINE_AUTHOR` env variable. |
368
+ | `atomic` | `boolean` | `false` | Batch transaction mode. By default (`false`), valid edits are applied and failing operations report errors. When `true`, any operation failure rolls back the entire batch to the original document state (`rolledBack: true`, `hasChanges: false`). Feature prominently in high-assurance workflows. |
369
+ | `structuredContent` | `boolean` | `true` | Auto-detects Markdown tables, headings (`#`), and lists in replacement text and renders them as native Word elements (`w:tbl`, `w:pStyle`, `w:numPr`). Pass `false` to treat replacement text strictly as plain text. |
370
+ | `pairReplacements` | `boolean` | `true` | Links adjacent `<w:del>` and `<w:ins>` revisions with matching timestamps so Word groups them as a single replacement in the Reviewing Pane. |
371
+ | `strictTargets` | `boolean` | `true` (CLI/facade) | Requires exact target descriptors (`exactText`, `paragraphId`, `index`, `occurrence`, `fingerprint`) and forbids ambiguous matching. Defaults to `false` in low-level runner for backwards compatibility. |
372
+ | `existingRevisions` | `string` | `'merge-same-author'` | How to handle paragraphs with existing tracked changes. `'merge-same-author'` merges revisions from the same author and protects other authors with `EXISTING_REVISIONS`. `'slice-cross-author'` keeps that same-author merge behavior while allowing Word-native edits inside another author's pending insertion. Pass `'accept-all-first'` to normalize prior revisions or `'reject-input'` to refuse editing revised paragraphs. |
373
+ | `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
374
+ | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
375
+
376
+ Same-author revision merging refuses paragraphs containing comment anchors with
377
+ `COMMENTED_CONTENT_MERGE`; resolve those comments first so the merge cannot
378
+ remove or orphan their anchors.
379
+
380
+ Common result fields:
381
+
382
+ | Field | Purpose |
383
+ |-------|---------|
384
+ | `status` | Operation status: `'ok'`, `'partial'`, `'no-op'`, or `'error'`. |
385
+ | `error` | Present on failure; retains a stable `code` and adds recovery envelope version, stage, category, bounded context, and a machine-readable recovery action. |
386
+ | `written` | CLI/facade boolean indicating whether the output file was successfully written to disk. |
387
+ | `completion` | CLI-only boolean that is `true` only when a destination was written, top-level status is neither error nor partial, and no operation result failed. |
388
+ | `rolledBack` | Present and `true` when an atomic batch encountered an error and rolled back all changes. |
389
+
390
+ Word diffs are deterministic by default (no wall-clock timeout). Inputs above
391
+ the safe ceiling of 262,144 unique diff tokens return `DIFF_TOKEN_LIMIT` with
392
+ the original OOXML unchanged so callers can split the operation without risking
393
+ silent text loss.
394
+
395
+ ### Editing inside existing revisions (cross-author slicing)
396
+
397
+ During multi-round legal negotiations, a reviewer often needs to edit text that was previously inserted by another reviewer whose revision is still pending. Pass `existingRevisions: 'slice-cross-author'` (or `--existing-revisions slice-cross-author` via CLI) to edit inside another author's pending insertion without erasing their attribution or requiring prior acceptance:
398
+
399
+ ```js
400
+ const result = await applyRedlineToOxml(paragraphOoxml, originalText, modifiedText, {
401
+ generateRedlines: true,
402
+ author: 'Reviewer B',
403
+ existingRevisions: 'slice-cross-author'
404
+ });
405
+ ```
406
+
407
+ The engine applies Microsoft Word Desktop-native tracked change structures:
408
+ - **Insertions inside pending insertions**: The carrier `<w:ins>` is split into sibling `<w:ins>` containers at the paragraph level (`[ins(Author A), ins(Author B), ins(Author A)]`), maintaining strict schema compliance without illegal `ins/ins` nesting.
409
+ - **Deletions inside pending insertions**: The new `<w:del>` is nested directly inside the carrier `<w:ins>` (valid under ECMA-376 Part 1 `CT_RunTrackChange`), ensuring that if Author A's insertion is rejected, Author B's dependent deletion is cleanly removed with it.
410
+ - **Straddle deletions**: Deletions spanning between baseline text and pending insertions cleanly partition across their respective container contexts without invalid coalescing.
411
+ - **Lifecycle parity**: Accepting or rejecting either reviewer independently produces identical results to Microsoft Word Desktop's native review pane.
412
+
413
+ ### Replacing a heading with a tracked list
414
+
415
+ The list route treats a one-paragraph heading expanded into multiple markdown
416
+ items as a structural block replacement. The deleted heading stays in its own
417
+ tracked paragraph, and every inserted item becomes a separate Word list
418
+ paragraph. Accepting the revisions produces only the list items; rejecting them
419
+ restores the original heading exactly.
420
+
421
+ ```js
422
+ const result = await applyRedlineToOxml(
423
+ headingParagraphOoxml,
424
+ 'A.\tPURPOSE',
425
+ '* Article A. Purpose and Interagency Alignment\n' +
426
+ '* Key Focus: Joint Street Outreach & Medical Triage',
427
+ { generateRedlines: true, author: 'Editor' }
428
+ );
429
+ ```
430
+
431
+ `w:numId w:val="0"` means numbering is explicitly suppressed; it is not a list
432
+ definition and is never reused for generated bullets. New list items receive a
433
+ positive numbering ID. Font family, size, language, and related script
434
+ properties are inherited from the source paragraph, while heading emphasis
435
+ (such as bold or underline) is not copied unless the replacement markdown asks
436
+ for it. For a complete `word/document.xml`, prefer
437
+ `applyOperationToDocumentXml(...)` so replacement nodes and numbering artifacts
438
+ are imported at the correct scope.
439
+
440
+ ### Planning large mixed-content insertions
441
+
442
+ For an attachment or schedule containing several kinds of content, use
443
+ `planStructuredReplacement(...)` before applying the edit. It decomposes the
444
+ Markdown into typed heading, paragraph, list, and table blocks, normalizes the
445
+ block boundaries, and returns one atomic operation with
446
+ `structuredContent: true`.
447
+
448
+ ```js
449
+ import { planStructuredReplacement } from '@ansonlai/docx-redline-js';
450
+
451
+ const plan = planStructuredReplacement(
452
+ { exactText: 'Date', index: 172 },
453
+ `# ATTACHMENT 4
454
+
455
+ Introductory paragraph.
456
+
457
+ | Agency | Contact |
458
+ | --- | --- |
459
+ | BCHD | Dr. Jenkins |
460
+
461
+ ## Protocol
462
+
463
+ 1. Joint clearance
464
+ 2. Rapid escalation`,
465
+ { author: 'Editor' }
466
+ );
467
+
468
+ if (!plan.valid || !plan.operation) {
469
+ throw new Error(plan.issues.map(issue => issue.message).join(' '));
470
+ }
471
+
472
+ const result = await document.applyOperations([plan.operation], {
473
+ author: 'Editor', atomic: true, validate: true
474
+ });
475
+ ```
476
+
477
+ Every Markdown table must include a separator row immediately below its header.
478
+ Missing separators, missing data rows, and inconsistent column counts are
479
+ reported as structured errors instead of being inserted as visible pipe text.
480
+ Use `#` through `#########` to request Word heading paragraphs; blank lines
481
+ separate paragraphs; adjacent list markers form a real Word list. Keep the
482
+ planned content in one operation so later blocks do not depend on an anchor that
483
+ an earlier block has already replaced.
484
+
485
+ ### Pipeline (lower-level access)
486
+
487
+ | Function | Purpose |
488
+ |----------|---------|
489
+ | `ReconciliationPipeline` | Direct pipeline access (ingest, diff, patch, serialize). |
490
+ | `ingestWordOoxmlToPlainText(oxml)` | Extract plain text from OOXML. |
491
+ | `ingestWordOoxmlToMarkdown(oxml)` | Convert OOXML to markdown. |
492
+ | `ingestWordOoxmlToPlainTextResult(oxml)` | Extract text as `{ text, status, error?, warnings? }`, distinguishing malformed input from an empty document. |
493
+ | `ingestWordOoxmlToMarkdownResult(oxml)` | Markdown counterpart to the result-returning plain-text helper. |
494
+ | `ingestOoxml(oxml)` | Flatten OOXML into an internal run model with offsets. |
495
+ | `preprocessMarkdown(text)` | Normalize markdown and extract format hints. |
496
+ | `analyzeStructuredContent(markdown)` | Decompose mixed Markdown into typed blocks and report malformed table syntax without creating an operation. |
497
+ | `planStructuredReplacement(target, markdown, options)` | Validate mixed content and return one atomic `structuredContent` replacement operation, or `operation: null` with issues. |
498
+ | `containsTrackedChanges(xmlDoc)` | Detect `w:ins`, `w:del`, move revisions, property changes, and paragraph-mark revision markup in a parsed OOXML document/fragment. |
499
+ | `validateRedlineOoxml(oxml)` | Validate generated redline OOXML against the package's structural invariants (no nested revisions, `w:delText` inside `w:del`, complete metadata, unique revision ids, preserved boundary whitespace). Returns `{ valid, issues }`; run it before writing output into a package. |
500
+
501
+ ### Services
502
+
503
+ | Function | Purpose |
504
+ |----------|---------|
505
+ | `injectCommentsIntoOoxml(oxml, comments, options)` | Add comments anchored to text ranges. |
506
+ | `applyCommentReplyToParts(options)` | Build a threaded reply in `comments.xml` and `commentsExtended.xml` without adding a document-body anchor. |
507
+ | `acceptTrackedChangesInOoxml(oxml, { author?, allAuthors? })` | Accept `w:ins` / `w:del` / `w:moveFrom` / `w:moveTo` / `*PrChange` revisions for one author or all authors. |
508
+ | `rejectTrackedChangesInOoxml(oxml, { author?, allAuthors? })` | Reject `w:ins` / `w:del` / `w:moveFrom` / `w:moveTo` / `*PrChange` revisions for one author or all authors. |
509
+ | `deleteCommentsByAuthorInOoxml(oxml, { author?, allAuthors? })` | Delete matching comment definitions and anchors present in the supplied OOXML payload. Real `.docx` packages require updating both `word/comments.xml` and `word/document.xml`. |
510
+ | `generateTableOoxml(headers, rows, options)` | Generate a `w:tbl` from tabular data. |
511
+ | `createDynamicNumberingIdState(numberingXml)` | Allocate numbering IDs without collisions. |
512
+ | `ensureNumberingArtifactsInZip(zip, numberingXml, options)` | Add numbering artifacts to a `.docx` package. Replacement of existing numbering without `mergeNumberingXmlBySchemaOrder` is deprecated and will throw in the next major version. |
513
+ | `ensureCommentsArtifactsInZip(zip, commentsXml)` | Merge comments artifacts into a `.docx` package. |
514
+ | `ensureCommentsExtendedArtifactsInZip(zip, commentsExtendedXml)` | Add or replace modern Word comment-thread metadata in a `.docx` package. |
515
+ | `validateDocxPackage(zip)` | Validate `.docx` structural consistency. |
516
+
517
+ Malformed OOXML never escapes these public transform APIs as a raw parser
518
+ exception. Transforms return `status: 'error'` with `error.code === 'PARSE_ERROR'`;
519
+ validators return a `PARSE_ERROR` issue. Recoverable XML parser
520
+ diagnostics are forwarded through the configured logger and included in
521
+ `warnings` where the result shape supports them.
522
+
523
+ Cross-author slicing also verifies its exact accepted-view text before success.
524
+ If a structural boundary prevents exact reconstruction, the transform returns
525
+ `status: 'error'` with `error.code === 'PATCH_ROUNDTRIP_MISMATCH'`,
526
+ `hasChanges: false`, and the original OOXML unchanged.
527
+ Pure insertion-only slicing uses an exact character-local diff so repeated words
528
+ cannot move an insertion to a different occurrence. Leading/trailing spaces,
529
+ tabs, and non-breaking spaces are treated as real changes rather than no-ops.
530
+ For text-bearing replacements, the exact accepted-view text of the resolved
531
+ paragraph—not a space-normalized caller target—defines mutation offsets. Word-level replacement
532
+ hunks that differ only by ordinary spaces and NBSPs are refined to character
533
+ edits so unchanged hyperlinks and their relationship attributes stay in place.
534
+ Runner results expose bounded `resolvedTarget.targetTextMatch` code-point
535
+ diagnostics when equivalent whitespace was used to identify the target.
536
+
537
+ ### Deep Imports
538
+
539
+ For advanced usage, import specific submodules:
540
+
541
+ ```js
542
+ import {
543
+ applyOperationToDocumentXml,
544
+ applyOperationsToDocumentXml,
545
+ preflightOperations,
546
+ orderOperationsForStableTargets
547
+ } from '@ansonlai/docx-redline-js/standalone-runner';
548
+ import { getParagraphText } from '@ansonlai/docx-redline-js/core/paragraph-targeting.js';
549
+ ```
550
+
551
+ Use `applyOperationsToDocumentXml(...)` for mixed batches. It stably runs comments before text-changing operations so replacements cannot invalidate their original anchors. Other operation types retain their relative order. Batch results retain each operation's original 1-based index and expose the actual `executionOrder`.
552
+
553
+ Before mutation, the runner resolves strong source descriptors against the
554
+ immutable batch-start document and binds them to session-local source
555
+ identities. Independent edits therefore do not need to be manually sorted when
556
+ an earlier structural rewrite changes later paragraph indexes or fingerprints.
557
+ Targets that deliberately refer to uniquely created paragraph text are compiled
558
+ into an internal capture dependency. True overlap is not guessed: incompatible
559
+ writes to one source fail before mutation with `OVERLAPPING_SOURCE_TARGETS` or
560
+ `REVISION_ORDER_CONFLICT`, and mutating capture fan-out without distinct
561
+ selectors fails with `CAPTURE_FANOUT_CONFLICT`.
562
+
563
+ Threaded replies use a comment operation with no body target:
564
+
565
+ ```js
566
+ { type: 'comment_reply', parentCommentId: 8, commentContent: 'Agreed; I revised this.', author: 'Editor' }
567
+ ```
568
+
569
+ For complete `.docx` files, use `openDocx(...).applyOperations(...)`; it reads
570
+ the existing comments parts, writes the required `commentsExtended.xml`
571
+ relationship and content type, adds the reply's own range/reference markers to the body
572
+ (Word does not display a reply without them), and keeps `commentsIds.xml` and
573
+ `commentsExtensible.xml` in step when they exist. Inspection reports `paraId`, `parentCommentId` and `done`
574
+ so callers can discover and verify the thread hierarchy.
575
+
576
+ Resolve or reopen a thread with an operation (usable from the CLI through `apply --operations`) or the API:
577
+
578
+ ```js
579
+ { type: 'comment_resolve', commentId: 8 } // resolve
580
+ { type: 'comment_resolve', commentId: 8, resolved: false } // reopen
581
+ await doc.resolveComment(8, { resolved: true });
582
+ ```
583
+
584
+ Resolved is a thread-level state in Word, so any id in the thread updates the root and all replies. Delete
585
+ specific comments with `doc.deleteComments({ ids: [8] })` or `docx-redline delete-comments file.docx --comment-id 8`;
586
+ deleting a thread root also deletes its replies.
587
+
588
+ Headers and footers are edited by adding `part` to an operation: `{ type: 'replace', part: { kind: 'footer' }, target: { exactText: 'Draft v1' }, modified: 'Draft v2' }`.
589
+ `openDocx(...).inspect().headersFooters` lists the parts (path, kind, type, sections, text, whether they contain
590
+ fields). Fields such as `PAGE` are treated as atomic, comments are not allowed in headers or footers, and `accept`/`reject`
591
+ also resolve revisions inside them. Creating a header or footer that does not exist is not supported; see
592
+ [Known limitations](docs/plans/KNOWN_BUGS.md#4-headers-and-footers).
593
+
594
+ A whole-paragraph `delete` that targets existing comment markup fails with
595
+ `COMMENTED_CONTENT_DELETE`. In the Node facade and CLI, the error also includes
596
+ the affected comment author and text. Resolve the feedback or explicitly remove
597
+ the comment first; the library will not silently discard reviewer context.
598
+
599
+ The batch runner keeps one live document DOM and performs one final full-document
600
+ serialization. Accuracy remains the controlling constraint: each operation has
601
+ an internal savepoint so an error or no-op cannot leak a partial edit or consumed
602
+ revision ID into later operations.
603
+
604
+ Batches are progressive by default (`atomic: false`): valid operations commit
605
+ while failed operations remain unapplied and are reported in `results`. Pass
606
+ `{ atomic: true }` when any operation error must return the original
607
+ `documentXml`, `hasChanges: false`, empty package artifacts, and
608
+ `rolledBack: true`. The default `continueOnError: true` still attempts the full
609
+ batch so `results` describes every operation; use `{ continueOnError: false }`
610
+ to stop after the first error.
611
+
612
+ Every failed or partial mutation includes `retryPlan`. Its `base` is `original`
613
+ after rollback/no commit and `output` after a progressive partial commit;
614
+ `committedIndexes`, `failedIndexes`, and `unattemptedIndexes` identify the safe
615
+ replay scope. Errors use recovery envelope version 1 and always report
616
+ `sameArgumentsSafe: false`. Follow `error.recovery.action`; do not infer a retry
617
+ from prose. Authorization-sensitive actions, such as resolving comments, are
618
+ marked with `requiresUserAuthorization: true`. For `EXISTING_REVISIONS`, the
619
+ non-normalizing surgical recommendation is `slice-cross-author`; accepting or
620
+ rejecting prior revisions still requires explicit authority.
621
+
622
+ Comment anchors use exact matching first, then a unique ASCII-space/NBSP
623
+ equivalent match that preserves source offsets and text. Missing anchors return
624
+ `ANCHOR_NOT_FOUND`; repeated matches return `AMBIGUOUS_ANCHOR`. Both are
625
+ operation errors and therefore roll back atomic batches. When `textToComment`
626
+ is omitted, the exact text of the resolved paragraph is used.
627
+
628
+ Operations may override the batch author and may use a strict target descriptor:
629
+
630
+ ```js
631
+ const operations = [{
632
+ type: 'replace',
633
+ author: 'Contract Editor',
634
+ target: {
635
+ exactText: 'Either party may terminate on notice.',
636
+ paragraphId: '1A2B3C4D',
637
+ index: 12,
638
+ fingerprint: 'fnv1a32:...'
639
+ },
640
+ modified: 'Either party may terminate on 30 days written notice.'
641
+ }];
642
+
643
+ const preflight = preflightOperations(documentXml, operations, 'Fallback Author');
644
+ if (!preflight.valid) {
645
+ // Resolve missing/ambiguous targets, anchors, revision policies, or conflicts.
646
+ }
647
+
648
+ const result = await applyOperationsToDocumentXml(
649
+ documentXml,
650
+ operations,
651
+ 'Fallback Author',
652
+ null,
653
+ { strictTargets: true }
654
+ );
655
+ ```
656
+
657
+ Preflight is read-only and uses strict targeting by default. It reports
658
+ `AMBIGUOUS_TARGET` with candidates instead of selecting the first duplicate,
659
+ does not use fuzzy fallback, checks comment/highlight anchors and existing
660
+ revision policy, identifies same-paragraph operation conflicts, and reports
661
+ authors plus required comments/numbering artifacts.
662
+
663
+ Application currently defaults to permissive targeting for backward compatibility,
664
+ but will default to `strictTargets: true` in v1.0.0. When permissive resolution
665
+ chooses among multiple candidate paragraphs heuristically, it emits an
666
+ `AMBIGUOUS_TARGET_HEURISTIC_USED` warning containing candidate count and migration
667
+ guidance. Callers should pass `{ strictTargets: true }` and use strict descriptors
668
+ (`paragraphId`, `index`, `occurrence`, or `fingerprint`) to prepare for v1.0.0.
669
+
670
+ ### Mutation Receipts
671
+
672
+ Both single-operation (`applyOperationToDocumentXml`) and batch
673
+ (`applyOperationsToDocumentXml`) results expose commit-aware **Mutation Receipts**
674
+ (`result.receipt` on single results and per-item `results[i].receipt`, plus `result.receipts`
675
+ for the full batch).
676
+
677
+ This full receipt shape is retained by the Node facade and standalone runner.
678
+ Only compact CLI JSON removes duplicate `results[i].receipt` bodies and keeps
679
+ the ordered top-level `receipts` array.
680
+
681
+ ```js
682
+ const result = await applyOperationsToDocumentXml(documentXml, operations, 'Agent');
683
+ for (const receipt of result.receipts) {
684
+ console.log(receipt.operationIndex, receipt.finalDisposition, receipt.committed);
685
+ console.log('Revisions:', receipt.revisionItems);
686
+ console.log('Comments:', receipt.commentIds);
687
+ }
688
+ ```
689
+
690
+ Receipts report:
691
+ - `operationIndex` (1-based), `operationId`, and `authorUsed`
692
+ - `attemptedDisposition` and `finalDisposition` (`applied`, `refused`, `no_change`, `rolled_back`, or `not_attempted`)
693
+ - `committed` (boolean: verified committed into serialized package output)
694
+ - `revisionItems` (exact allocated revision IDs with kind and target part)
695
+ - `commentIds`, `numberingIds`, and `relationshipIds`
696
+ - `affectedTargets` (resolved target coordinates) and `warnings`
697
+
698
+ Before completing an operation or batch transaction, `reconcileReceiptsAgainstOutput`
699
+ verifies every reported committed durable ID against a fresh parse of the output OOXML.
700
+ Any discrepancy fails closed and triggers immediate rollback.
701
+
702
+ ### Output Shape Matrix
703
+
704
+ Different APIs return different OOXML shapes. Use this as a packaging safety check.
705
+
706
+ | API | Typical input scope | Output field | Possible root/output shape | Safe to write directly into `word/document.xml` |
707
+ |-----|----------------------|--------------|----------------------------|--------------------------------------------------|
708
+ | `applyRedlineToOxml(...)` | Paragraph, range, or table-scope OOXML | `result.oxml` | Fragment, `<w:document>`, or package payload (`<pkg:package>`) | No. Inspect first. |
709
+ | `applyRedlineToOxmlWithListFallback(...)` | Paragraph or range-scope OOXML | `result.oxml` | Fragment, `<w:document>`, or package payload (`<pkg:package>`) | No. Inspect first. |
710
+ | `reconcileMarkdownTableOoxml(...)` | Table or paragraph-scope OOXML | `result.oxml` | Same shapes as `applyRedlineToOxml(...)` for the supplied scope | No. Inspect first. |
711
+ | `applyOperationToDocumentXml(...)` | Full `word/document.xml` string | `result.documentXml` | `<w:document>` | Yes. This is the document-safe helper. |
712
+ | `applyOperationsToDocumentXml(...)` | Full `word/document.xml` plus an operation batch | `result.documentXml` | `<w:document>` | Yes. Atomic by default; comments are applied before text-changing operations. |
713
+ | `extractReplacementNodesFromOoxml(...)` | Any OOXML payload | `{ replacementNodes, numberingXml, sourceType }` | Normalized to `fragment`, `document`, or `package` | Yes. Use this when consuming `result.oxml`. |
714
+
715
+ ### Do / Don't for Packaging
716
+
717
+ - Do use `applyOperationToDocumentXml(...).documentXml` when your intent is to replace `word/document.xml`.
718
+ - Do use `applyOperationsToDocumentXml(...)` rather than an unsorted loop for batches containing comments and replacements that target the same original paragraph.
719
+ - Redline application strips proofing markers (`w:proofErr`) from the matched target paragraph before diffing, while preserving complex-field scaffolding (`w:fldChar`, `w:instrText`) and its cached visible result as inert structure. Adjacent edits do not revise or move an unchanged field result.
720
+ - Hyperlinks, bookmarks, comment range markers, tabs/breaks, and footnote/endnote references are treated as structural OOXML that should survive adjacent redline edits instead of being orphaned or wrapped in deletions.
721
+ - Treat `w:numId w:val="0"` as numbering suppression, never as a reusable list
722
+ ID. Generated bullet and numbered paragraphs must reference a positive ID
723
+ whose definition is merged into `word/numbering.xml`.
724
+ - Do use `extractReplacementNodesFromOoxml(...)` when you are consuming `result.oxml` from paragraph/range/table APIs.
725
+ - Do merge numbering/comments artifacts with `ensureNumberingArtifactsInZip(...)` and `ensureCommentsArtifactsInZip(...)` when those parts are present. Supply `mergeNumberingXmlBySchemaOrder` when numbering already exists.
726
+ - Don't write payloads that start with `<pkg:package` directly into `word/document.xml`.
727
+ - Don't assume every `result.oxml` payload is a raw paragraph fragment.
728
+
729
+ ## Working With `.docx` Files
730
+
731
+ This package operates on OOXML strings (XML parts inside `.docx` zip archives), not raw `.docx` binaries.
732
+
733
+ Typical flow:
734
+
735
+ 1. Extract the `.docx` zip (for example with JSZip, fflate, or similar)
736
+ 2. Read `word/document.xml`
737
+ 3. Apply reconciliation APIs to XML strings
738
+ 4. Merge numbering/comments artifacts when needed
739
+ 5. Write the archive back to a `.docx` file
740
+
741
+ ```js
742
+ import JSZip from 'jszip';
743
+ import {
744
+ applyRedlineToOxml,
745
+ extractReplacementNodesFromOoxml,
746
+ ensureNumberingArtifactsInZip,
747
+ mergeNumberingXmlBySchemaOrder,
748
+ validateDocxPackage
749
+ } from '@ansonlai/docx-redline-js';
750
+ import { applyOperationToDocumentXml } from '@ansonlai/docx-redline-js/standalone-runner';
751
+
752
+ const zip = await JSZip.loadAsync(docxBuffer);
753
+ const documentXml = await zip.file('word/document.xml').async('string');
754
+
755
+ const opResult = await applyOperationToDocumentXml(
756
+ documentXml,
757
+ { type: 'redline', target: 'old text', modified: 'new text' },
758
+ 'Editor'
759
+ );
760
+
761
+ // Restoring another reviewer's pending whole-paragraph deletion requires
762
+ // explicit intent. The restored counterproposal becomes a separately tracked
763
+ // sibling paragraph; a normal redline operation remains fail-closed.
764
+ const restoration = await applyOperationToDocumentXml(
765
+ documentXml,
766
+ {
767
+ type: 'restore',
768
+ // restore targets default to the rejected view, where deleted text exists
769
+ target: { paragraphId: '1A2B3C4D', exactText: 'Original deleted paragraph text.' },
770
+ modified: 'Restored or adjusted paragraph text.'
771
+ },
772
+ 'Editor'
773
+ );
774
+
775
+ // A single restoration follows its deleted source paragraph. A range
776
+ // restoration follows the complete deleted source block. Unchanged legacy
777
+ // validation defects are retained as baseline issues; newly generated errors
778
+ // fail closed before commit.
779
+ // inspect/extract descriptors report their revisionView, and each fingerprint
780
+ // is computed from the same view as exactText. Keep those fields together.
781
+
782
+ // To insert run-level text at a location visible only in the rejected view,
783
+ // provide explicit rejected-view intent and an exact anchor-relative offset.
784
+ const deletedTextInsertion = await applyOperationToDocumentXml(
785
+ documentXml,
786
+ {
787
+ type: 'insert',
788
+ target: { paragraphId: '1A2B3C4D', revisionView: 'rejected' },
789
+ anchor: { exactText: 'must pay', occurrence: 1, offset: 5 },
790
+ modified: '[clarification] ',
791
+ existingRevisions: 'slice-cross-author'
792
+ },
793
+ 'Editor'
794
+ );
795
+
796
+ // applyOperationToDocumentXml(...) returns a full w:document payload.
797
+ zip.file('word/document.xml', opResult.documentXml);
798
+
799
+ const fragmentResult = await applyRedlineToOxml(
800
+ paragraphOoxml,
801
+ 'Item text',
802
+ '1. Item text',
803
+ { generateRedlines: true, author: 'Editor' }
804
+ );
805
+ const normalized = extractReplacementNodesFromOoxml(fragmentResult.oxml);
806
+
807
+ // If sourceType === 'package', merge extracted content/artifacts instead of
808
+ // writing the raw pkg:package payload into word/document.xml.
809
+ if (normalized.numberingXml) {
810
+ await ensureNumberingArtifactsInZip(zip, normalized.numberingXml, {
811
+ mergeNumberingXml: mergeNumberingXmlBySchemaOrder
812
+ });
813
+ }
814
+
815
+ await validateDocxPackage(zip);
816
+ const output = await zip.generateAsync({ type: 'nodebuffer' });
817
+ ```
818
+
819
+ ## Validating Output
820
+
821
+ For the test-lane design and instructions for adding regression, synthetic
822
+ Word, and real-corpus cases, see [docs/TESTING.md](./docs/TESTING.md).
823
+
824
+ Run the automated package checks:
825
+
826
+ ```bash
827
+ npm test
828
+ npm run test:isolation
829
+ npm run check:types
830
+ npm run lint
831
+ npm run test:coverage
832
+ ```
833
+
834
+ For release-time fixture export:
835
+
836
+ ```bash
837
+ node scripts/export-validation-fixtures.mjs
838
+ ```
839
+
840
+ On Windows with desktop Word installed, you can smoke-test a completed `.docx`:
841
+
842
+ ```bash
843
+ npm run smoke:word -- path/to/file.docx
844
+ ```
845
+
846
+ To validate against Word as an independent oracle (Word itself accepts and
847
+ rejects the generated revisions and the resulting text is compared to the
848
+ expected outcomes):
849
+
850
+ ```bash
851
+ npm run test:word
852
+ ```
853
+
854
+ This Windows-only test command generates an English legal/administrative task
855
+ suite under `tmp/word-validation/` and drives installed desktop Microsoft Word
856
+ through COM. Its 33 cases include targeted reliability checks for literal
857
+ content, multi-paragraph replacement, prior-revision no-op, atomic rollback,
858
+ hostile revision IDs, bookmarks, internal hyperlinks, mixed formatted runs,
859
+ content controls, table cells, structural tabs, locked complex fields,
860
+ comments, footnotes/endnotes, headers/footers, and external hyperlinks.
861
+ Structure-focused cases also assert required
862
+ OOXML elements before Word independently checks Accept All and Reject All. The
863
+ published library remains clean, host-independent JavaScript; Word automation
864
+ exists only in development scripts.
865
+
866
+ Use `npm run report:word:coverage` to print the validated task-by-structure
867
+ matrix across all 33 synthetic and 31 SuperDoc scenarios. Before a release,
868
+ `npm run review:word:prepare -- --cycle=0` creates a pending human-review
869
+ manifest with changed cases, a rotating 20% synthetic sample, and legal plus
870
+ administrative corpus representatives. See the [Word visual review guide in docs/TESTING.md](./docs/TESTING.md#microsoft-word-visual-review-guide);
871
+ preparation and AI preflight never count as human sign-off.
872
+
873
+ A nightly GitHub Actions workflow additionally validates generated fixtures
874
+ against the ECMA-376 transitional schemas (`xmllint`), opens them with
875
+ LibreOffice, and runs an extended fuzz sweep of the accept/reject round-trip
876
+ invariant with a fresh seed. See [Release validation in docs/TESTING.md](./docs/TESTING.md#release-validation-and-independent-oracles).
877
+
878
+ ## Architecture & Contributing
879
+
880
+ - **[ARCHITECTURE.md](./ARCHITECTURE.md)**: Detailed module layout, end-to-end reconciliation flow, and contributor fast orientation.
881
+ - **[AGENTS.md](./AGENTS.md)**: Fast-start routing and operational guardrails for AI coding agents.
882
+ - **[docs/AGENT_FAST_START.md](./docs/AGENT_FAST_START.md)**: Minimal ordinary-edit contract for agent integrations.
883
+ - **[docs/AGENT_KNOWLEDGE_BASE.md](./docs/AGENT_KNOWLEDGE_BASE.md)**: Full agent reference for APIs, operations, CLI automation, recovery, and gotchas.
884
+ - **[docs/TESTING.md](./docs/TESTING.md)**: Comprehensive testing model, test lanes, independent oracle checks, and visual review checklist.
885
+ - **[CHANGELOG.md](./CHANGELOG.md)**: Version history, migration guides, and deprecation schedules.
886
+
887
+ ## Test Corpus Attribution
888
+
889
+ Real-document reliability testing uses selected references from
890
+ [docx-corpus](https://docxcorp.us/), built by
891
+ [SuperDoc](https://superdoc.dev/). The dataset is licensed under the
892
+ [Open Data Commons Attribution License (ODC-By) 1.0](https://opendatacommons.org/licenses/by/1-0/).
893
+
894
+ Only explicitly pinned English legal and administrative documents are eligible
895
+ for the initial corpus lane. References and provenance live in
896
+ `tests/corpus/superdoc-english-legal-administrative.json`; downloaded documents
897
+ are hash-verified and kept in ignored `tmp/` storage rather than committed. On
898
+ Windows with desktop Word installed, run the reviewed 31-scenario/23-document lane with:
899
+
900
+ ```bash
901
+ npm run test:corpus:word
902
+ ```
903
+
904
+ ODC-By applies to the database; individual documents may carry additional
905
+ rights, so each selected document must be reviewed before becoming a test case.