@ansonlai/docx-redline-js 0.8.2 → 0.8.3

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