@ansonlai/docx-redline-js 0.4.0 → 0.5.1

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.
Files changed (104) hide show
  1. package/AGENTS.md +646 -288
  2. package/ARCHITECTURE.md +215 -9
  3. package/CHANGELOG.md +319 -0
  4. package/README.md +604 -360
  5. package/adapters/config.js +45 -43
  6. package/bin/docx-redline.js +3 -0
  7. package/core/list-targeting.js +101 -110
  8. package/core/paragraph-targeting.js +501 -61
  9. package/core/paragraph-text.js +209 -0
  10. package/core/redline-validation.js +11 -5
  11. package/core/revision-cloning.js +38 -0
  12. package/core/types.js +64 -10
  13. package/core/word-xml.js +43 -15
  14. package/dist/docx-redline-js.esm.js +3145 -505
  15. package/dist/docx-redline-js.esm.js.map +4 -4
  16. package/dist/docx-redline-js.esm.min.js +88 -76
  17. package/dist/docx-redline-js.esm.min.js.map +4 -4
  18. package/docs/TESTING.md +342 -23
  19. package/docs/plans/2026-09-05-structural-revisions-and-fidelity-oracles.md +1669 -0
  20. package/docs/plans/2026-09-08-cross-author-revision-slicing.md +505 -0
  21. package/docs/plans/completed/2026-09-01-performance-and-complexity-reduction.md +669 -0
  22. package/docs/plans/completed/2026-09-03-agent-friendly-document-workflows.md +427 -0
  23. package/docs/plans/completed/2026-09-04-comment-anchor-and-cli-reliability.md +519 -0
  24. package/docs/plans/completed/PERFORMANCE-CONSOLIDATION.md +69 -0
  25. package/docs/plans/completed/structural-revision-capability-matrix.md +115 -0
  26. package/docs/schemas/document-operations.schema.json +109 -0
  27. package/docs/test-comparison-dashboard.html +4250 -7
  28. package/engine/formatting-removal.js +11 -2
  29. package/engine/oxml-engine.js +508 -336
  30. package/engine/reconstruction-mode.js +15 -14
  31. package/engine/reconstruction-writer.js +247 -142
  32. package/engine/route-selection.js +35 -0
  33. package/engine/rpr-helpers.js +334 -35
  34. package/engine/run-builders.js +239 -196
  35. package/engine/surgical-diff-application.js +407 -50
  36. package/engine/surgical-mode.js +142 -6
  37. package/engine/surgical-run-splitting.js +103 -0
  38. package/engine/surgical-spans.js +52 -1
  39. package/engine/table-cell-context.js +3 -6
  40. package/engine/table-mode.js +1 -1
  41. package/index.d.ts +234 -6
  42. package/index.js +24 -1
  43. package/node/cli.js +322 -0
  44. package/node/docx-document.js +302 -0
  45. package/node/index.d.ts +31 -0
  46. package/node/index.js +2 -0
  47. package/node/zip-archive.js +52 -0
  48. package/orchestration/list-markdown.js +10 -16
  49. package/orchestration/list-parsing.js +7 -12
  50. package/orchestration/list-structural-fallback.js +21 -10
  51. package/package.json +123 -102
  52. package/pipeline/content-analysis.js +12 -17
  53. package/pipeline/ingestion-export.js +3 -31
  54. package/pipeline/ingestion-paragraph.js +10 -5
  55. package/pipeline/list-generation.js +150 -55
  56. package/pipeline/list-markers.js +70 -3
  57. package/pipeline/serialization.js +4 -2
  58. package/pipeline/structured-content.js +160 -0
  59. package/scripts/apply_changes.mjs +27 -0
  60. package/scripts/benchmark-operation-session.mjs +137 -0
  61. package/scripts/benchmark-targeting-browser.html +74 -0
  62. package/scripts/benchmark-targeting-hot-paths.mjs +67 -0
  63. package/scripts/benchmark-test-runner.mjs +59 -0
  64. package/scripts/build-test-dashboard.mjs +23 -0
  65. package/scripts/export-lane1-fixtures.mjs +380 -0
  66. package/scripts/export-reredline-stress-fixtures.mjs +317 -0
  67. package/scripts/export-validation-fixtures.mjs +1 -1
  68. package/scripts/extract_text.mjs +7 -0
  69. package/scripts/generate-cross-author-slicing-fixtures.ps1 +256 -0
  70. package/scripts/generate-paragraph-boundary-fixtures.ps1 +215 -0
  71. package/scripts/generate-test-dashboard.mjs +362 -11
  72. package/scripts/lib/word-coverage-catalogue.mjs +6 -2
  73. package/scripts/profile-route-selection.mjs +19 -0
  74. package/scripts/render-agenda-multilevel.mjs +0 -5
  75. package/scripts/render-multilevel-cases.mjs +0 -1
  76. package/scripts/run-tests.mjs +107 -35
  77. package/scripts/word-com-corpus-suite.ps1 +3 -0
  78. package/scripts/word-com-differential.ps1 +64 -4
  79. package/scripts/word-com-suite.ps1 +3 -0
  80. package/services/batch-operation-orchestrator.js +513 -0
  81. package/services/capture-engine.js +226 -0
  82. package/services/comment-builders.js +23 -6
  83. package/services/comment-engine.js +108 -47
  84. package/services/comment-locator.js +187 -82
  85. package/services/comment-replies.js +95 -0
  86. package/services/document-inspection.js +258 -0
  87. package/services/document-operation-applier.js +372 -0
  88. package/services/document-operation-contract.js +345 -0
  89. package/services/document-operation-mutations.js +1749 -0
  90. package/services/document-operation-session.js +258 -0
  91. package/services/numbering-service.js +14 -5
  92. package/services/operation-heuristics.js +173 -0
  93. package/services/operation-preflight.js +390 -0
  94. package/services/receipt-collector.js +288 -0
  95. package/services/revision-comment-management.js +77 -5
  96. package/services/revision-token.js +290 -0
  97. package/services/standalone-docx-plumbing.js +123 -8
  98. package/services/standalone-operation-runner.d.ts +296 -0
  99. package/services/standalone-operation-runner.js +10 -1455
  100. package/services/table-reconciliation.js +15 -6
  101. package/docs/VALIDATION.md +0 -183
  102. package/docs/WORD-MANUAL-REVIEW.md +0 -138
  103. package/docs/plans/2026-09-01-performance-and-complexity-reduction.md +0 -210
  104. /package/docs/plans/{2026-08-30-reliability-testing-improvements.md → completed/2026-08-30-reliability-testing-improvements.md} +0 -0
package/AGENTS.md CHANGED
@@ -1,288 +1,646 @@
1
- # AGENTS.md - AI Agent Quick Reference
2
-
3
- > This file helps AI coding agents understand @ansonlai/docx-redline-js quickly.
4
- > Read this instead of exploring the full source tree.
5
-
6
- ## What This Package Does
7
-
8
- Converts text/markdown edits into valid Office Open XML (OOXML) with Word-native tracked changes. Feed it original OOXML + desired text and it returns OOXML with `w:ins`/`w:del` revision markup.
9
-
10
- ## Conceptual Model
11
-
12
- ```
13
- Input: (paragraph OOXML, original text, modified text, options)
14
- |
15
- v
16
- Engine routes to: format-only | surgical | reconstruction | list | table mode
17
- |
18
- v
19
- Output: { oxml: string, hasChanges: boolean, status?: string, error?: object, warnings?: string[] }
20
- ```
21
-
22
- The engine usually works at paragraph/range/table scope. For full-document
23
- operations, use the standalone operation runner so the result is safe to write
24
- back to `word/document.xml`.
25
-
26
- ## Entry Point
27
-
28
- ```js
29
- import { applyRedlineToOxml, configureXmlProvider } from '@ansonlai/docx-redline-js';
30
- ```
31
-
32
- `index.js` is the single package entry point.
33
-
34
- ## Required Setup (Node.js only)
35
-
36
- ```js
37
- import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
38
- configureXmlProvider({ DOMParser, XMLSerializer });
39
- ```
40
-
41
- Browsers have native DOM APIs, so no provider injection is typically needed.
42
-
43
- ## Key APIs by Use Case
44
-
45
- ### Apply a text edit with tracked changes
46
-
47
- ```js
48
- const result = await applyRedlineToOxml(oxml, originalText, modifiedText, {
49
- generateRedlines: true,
50
- author: 'Agent Name',
51
- existingRevisions: 'reject-input'
52
- });
53
- ```
54
-
55
- `existingRevisions` defaults to `'reject-input'`. Use `'accept-all-first'` only
56
- when the caller intentionally wants to accept prior tracked changes before
57
- applying a new edit. A no-op still returns the untouched input; use
58
- `'accept-all-first-keep-normalized'` only when accepted revisions should be
59
- returned as a real change even without a new redline.
60
-
61
- ### Apply a text edit without tracked changes
62
-
63
- ```js
64
- const result = await applyRedlineToOxml(oxml, originalText, modifiedText, {
65
- generateRedlines: false
66
- });
67
- ```
68
-
69
- ### Convert OOXML to readable text or markdown
70
-
71
- ```js
72
- import { ingestWordOoxmlToPlainText, ingestWordOoxmlToMarkdown } from '@ansonlai/docx-redline-js';
73
- const plainText = ingestWordOoxmlToPlainText(documentXml);
74
- const markdown = ingestWordOoxmlToMarkdown(documentXml);
75
- ```
76
-
77
- ### Add a comment to OOXML
78
-
79
- ```js
80
- import { injectCommentsIntoOoxml } from '@ansonlai/docx-redline-js';
81
- const result = injectCommentsIntoOoxml(paragraphOoxml, [
82
- { text: 'Review this clause', targetText: 'force majeure', author: 'Agent' }
83
- ]);
84
- ```
85
-
86
- ### Accept tracked changes from one user (or all users)
87
-
88
- ```js
89
- import { acceptTrackedChangesInOoxml } from '@ansonlai/docx-redline-js';
90
- const acceptedMine = acceptTrackedChangesInOoxml(documentXml, { author: 'Agent' });
91
- const acceptedAll = acceptTrackedChangesInOoxml(documentXml, { allAuthors: true });
92
- ```
93
-
94
- ### Reject tracked changes from one user (or all users)
95
-
96
- ```js
97
- import { rejectTrackedChangesInOoxml } from '@ansonlai/docx-redline-js';
98
- const rejectedMine = rejectTrackedChangesInOoxml(documentXml, { author: 'Agent' });
99
- const rejectedAll = rejectTrackedChangesInOoxml(documentXml, { allAuthors: true });
100
- ```
101
-
102
- Move revisions are consumed too: accept removes `w:moveFrom` and unwraps
103
- `w:moveTo`; reject unwraps `w:moveFrom` and removes `w:moveTo`.
104
-
105
- ### Delete comments from one user (or all users)
106
-
107
- ```js
108
- import { deleteCommentsByAuthorInOoxml } from '@ansonlai/docx-redline-js';
109
- const removedMine = deleteCommentsByAuthorInOoxml(packageOrDocumentOoxml, { author: 'Agent' });
110
- const removedAll = deleteCommentsByAuthorInOoxml(packageOrDocumentOoxml, { allAuthors: true });
111
- ```
112
-
113
- ### Apply multiple operations to full document XML
114
-
115
- ```js
116
- import {
117
- applyOperationToDocumentXml,
118
- applyOperationsToDocumentXml
119
- } from '@ansonlai/docx-redline-js/services/standalone-operation-runner.js';
120
-
121
- const result = await applyOperationsToDocumentXml(documentXml, operations, 'Agent', runtimeContext, options);
122
- ```
123
-
124
- Use `result.documentXml` from these APIs when replacing full `word/document.xml`.
125
- For mixed batches, prefer `applyOperationsToDocumentXml(...)`; it applies comments
126
- before replacements so earlier edits cannot invalidate their anchors.
127
-
128
- Batches are atomic by default. If any operation fails, the batch returns the
129
- original `documentXml`, `hasChanges: false`, no comment/numbering artifacts, and
130
- `rolledBack: true`; `results` still describes every attempted operation because
131
- `continueOnError` defaults to `true`. Pass `{ atomic: false }` only when a
132
- partially applied document is intentional. Pass `{ continueOnError: false }` to
133
- stop attempting operations after the first error.
134
-
135
- ### Detect existing tracked changes
136
-
137
- ```js
138
- import { containsTrackedChanges } from '@ansonlai/docx-redline-js';
139
- const hasTrackedChanges = containsTrackedChanges(xmlDoc);
140
- ```
141
-
142
- ### Convert paragraph text into a Word list
143
-
144
- ```js
145
- const result = await applyRedlineToOxml(oxml, 'Item text', '1. Item text', {
146
- generateRedlines: true
147
- });
148
- ```
149
-
150
- ### Reconcile a table
151
-
152
- ```js
153
- import { reconcileMarkdownTableOoxml } from '@ansonlai/docx-redline-js';
154
- const result = await reconcileMarkdownTableOoxml(tableOoxml, originalText, markdownTable);
155
- ```
156
-
157
- ## Module Map
158
-
159
- ```
160
- index.js
161
- adapters/
162
- config.js
163
- xml-adapter.js
164
- logger.js
165
- core/
166
- types.js
167
- word-xml.js
168
- paragraph-targeting.js
169
- list-targeting.js
170
- table-targeting.js
171
- engine/
172
- oxml-engine.js
173
- surgical-mode.js
174
- surgical-run-splitting.js
175
- surgical-diff-application.js
176
- surgical-spans.js
177
- reconstruction-mode.js
178
- reconstruction-writer.js
179
- format-application.js
180
- formatting-removal.js
181
- run-builders.js
182
- table-mode.js
183
- pipeline/
184
- pipeline.js
185
- ingestion.js
186
- ingestion-export.js
187
- diff-engine.js
188
- markdown-processor.js
189
- serialization.js
190
- list-generation.js
191
- services/
192
- standalone-operation-runner.js
193
- standalone-docx-plumbing.js
194
- numbering-helpers.js
195
- comment-engine.js
196
- revision-comment-management.js
197
- table-reconciliation.js
198
- package-builder.js
199
- orchestration/
200
- route-plan.js
201
- list-markdown.js
202
- list-structural-fallback.js
203
- ```
204
-
205
- ## Common Patterns
206
-
207
- ### Options shape
208
-
209
- ```js
210
- {
211
- generateRedlines: true,
212
- author: 'Name',
213
- existingRevisions: 'reject-input',
214
- removeFormatting: false,
215
- sanitizeInput: false
216
- }
217
- ```
218
-
219
- ### Typical return shape
220
-
221
- ```js
222
- {
223
- oxml: string,
224
- hasChanges: boolean,
225
- status?: 'ok' | 'no-op' | 'error',
226
- error?: { code: string, message: string },
227
- warnings?: string[],
228
- numberingXml?: string,
229
- useNativeApi?: boolean
230
- }
231
- ```
232
-
233
- Known error codes include `PARSE_ERROR`, `TARGET_NOT_FOUND`, `PARTIAL_TARGET`,
234
- `EXISTING_REVISIONS`, `DIFF_TOKEN_LIMIT`, and `BATCH_OPERATION_FAILED`.
235
-
236
- For ingestion that must distinguish an empty document from malformed OOXML,
237
- use `ingestWordOoxmlToPlainTextResult` or
238
- `ingestWordOoxmlToMarkdownResult`. The legacy ingestion helpers intentionally
239
- retain their string-only return type and return `''` for parse failures.
240
-
241
- ### OOXML wrapping for Word insertOoxml scenarios
242
-
243
- ```js
244
- import { wrapInDocumentFragment } from '@ansonlai/docx-redline-js';
245
- const wrapped = wrapInDocumentFragment(rawOoxml, { includeNumbering: true, numberingXml });
246
- ```
247
-
248
- ### Output shape guardrail (important for packaging)
249
-
250
- When consuming `result.oxml`, do not assume the payload is always safe to write
251
- directly into `word/document.xml`.
252
-
253
- - Paragraph/range/table APIs can return a fragment, `<w:document>`, or package payload (`<pkg:package>`).
254
- - `applyOperationToDocumentXml(...).documentXml` is the document-safe path when you need a full `word/document.xml` replacement.
255
- - Use `extractReplacementNodesFromOoxml(payload)` to normalize unknown payloads.
256
- - If `sourceType === 'package'` or the payload starts with `<pkg:package`, do not write it into `word/document.xml` as-is.
257
-
258
- ## Gotchas
259
-
260
- 1. Call `configureXmlProvider` first in Node.js.
261
- 2. `applyRedlineToOxml` is async.
262
- 3. Paragraph APIs expect paragraph-level OOXML, not full `word/document.xml` in all cases.
263
- 4. List operations may return `numberingXml` that must be merged into package parts.
264
- 5. `useNativeApi: true` means standalone mode cannot fully handle that operation path.
265
- 6. `deleteCommentsByAuthorInOoxml` removes matching `comments.xml` entries and linked comment anchors/references in the document.
266
- 7. If output begins with `<pkg:package`, treat it as package-level OOXML and normalize it before writing anything back to `word/document.xml`.
267
- 8. Existing revisions are rejected by default; `accept-all-first` preserves the original OOXML on no-op, while `accept-all-first-keep-normalized` explicitly returns normalization as a change.
268
- 9. Caller content is not sanitized by default. Pass `sanitizeInput: true` only for raw assistant output; literal dollar delimiters and `\\n` sequences are never rewritten.
269
- 10. Hyperlinks, bookmarks, comment markers, tabs/breaks, and footnote/endnote references are structural OOXML and should survive adjacent redline edits.
270
- 11. Internally, create Word elements through `createWordElement` and tracked-change metadata through `createRevisionMetadata`.
271
- 12. Revision IDs are document-scoped in public operation paths. Thread the
272
- internal allocator through new string-serialization paths; generated
273
- `w:id` values are not stable across documents.
274
-
275
- ## Validation Commands
276
-
277
- ```bash
278
- npm test
279
- npm run test:isolation
280
- npm run check:types
281
- node scripts/export-validation-fixtures.mjs
282
- ```
283
-
284
- Optional Windows/Word smoke test for a completed `.docx`:
285
-
286
- ```bash
287
- npm run smoke:word -- path/to/file.docx
288
- ```
1
+ # AGENTS.md - AI Agent Quick Reference
2
+
3
+ > This file helps AI coding agents understand @ansonlai/docx-redline-js quickly.
4
+ > Read this instead of exploring the full source tree.
5
+
6
+ ## What This Package Does
7
+
8
+ Converts text/markdown edits into valid Office Open XML (OOXML) with Word-native tracked changes. Feed it original OOXML + desired text and it returns OOXML with `w:ins`/`w:del` revision markup.
9
+
10
+ ## Conceptual Model
11
+
12
+ ```
13
+ Input: (paragraph OOXML, original text, modified text, options)
14
+ |
15
+ v
16
+ Engine routes to: format-only | surgical | reconstruction | list | table mode
17
+ |
18
+ v
19
+ Output: { oxml: string, hasChanges: boolean, status?: string, error?: object, warnings?: string[] }
20
+ ```
21
+
22
+ The engine usually works at paragraph/range/table scope. For full-document
23
+ operations, use the standalone operation runner so the result is safe to write
24
+ back to `word/document.xml`.
25
+
26
+ ## Entry Point
27
+
28
+ ```js
29
+ import { applyRedlineToOxml, configureXmlProvider } from '@ansonlai/docx-redline-js';
30
+ ```
31
+
32
+ `index.js` is the single package entry point.
33
+
34
+ ## Required Setup (Node.js only)
35
+
36
+ ```js
37
+ import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
38
+ configureXmlProvider({ DOMParser, XMLSerializer });
39
+ ```
40
+
41
+ Browsers have native DOM APIs, so no provider injection is typically needed.
42
+
43
+ ## Key APIs by Use Case
44
+
45
+ ### Apply a text edit with tracked changes
46
+
47
+ ```js
48
+ const result = await applyRedlineToOxml(oxml, originalText, modifiedText, {
49
+ generateRedlines: true,
50
+ author: 'Agent Name'
51
+ });
52
+ ```
53
+
54
+ `existingRevisions` defaults to `'merge-same-author'`. When a target paragraph
55
+ contains tracked changes from the same author, prior revisions by that author are
56
+ reverted to the pre-revision baseline and re-diffed to the new text, cleanly
57
+ merging the edits without accumulating intermediate revisions or nesting markup.
58
+ If the paragraph contains revisions from a different reviewer, the edit fails
59
+ with `EXISTING_REVISIONS` to safeguard third-party marks. Pass
60
+ `existingRevisions: 'slice-cross-author'` (or `--existing-revisions slice-cross-author`)
61
+ to preserve the other reviewer's attribution while applying Word-native
62
+ insertions and deletions inside their pending insertion. Pass
63
+ `existingRevisions: 'accept-all-first'` (or `--existing-revisions accept-all-first`
64
+ via CLI) to normalize all prior revisions first, or `'reject-input'` to refuse any
65
+ paragraph with open revisions. Use `'accept-all-first-keep-normalized'` only when
66
+ accepted revisions should be returned as a real change even on a no-op edit.
67
+ Same-author merging also fails with `COMMENTED_CONTENT_MERGE` when the revised
68
+ paragraph contains comment anchors, because reverting the prior revision could
69
+ remove or orphan those comments. Resolve the comments before re-editing.
70
+
71
+ ### Apply a text edit without tracked changes (Direct Edits)
72
+
73
+ > [!IMPORTANT]
74
+ > **Tracked redlines are not always the preferred method.** When finalizing execution copies of contracts, restructuring documents, correcting minor typos, or whenever the user specifically desires clean document text without tracked changes markup clutter, pass `generateRedlines: false` (or `--no-redlines` via CLI).
75
+
76
+ ```js
77
+ const result = await applyRedlineToOxml(oxml, originalText, modifiedText, {
78
+ generateRedlines: false
79
+ });
80
+ ```
81
+
82
+ ### Convert OOXML to readable text or markdown
83
+
84
+ ```js
85
+ import { ingestWordOoxmlToPlainText, ingestWordOoxmlToMarkdown } from '@ansonlai/docx-redline-js';
86
+ const plainText = ingestWordOoxmlToPlainText(documentXml);
87
+ const markdown = ingestWordOoxmlToMarkdown(documentXml);
88
+ ```
89
+
90
+ ### Add a comment to OOXML
91
+
92
+ ```js
93
+ import { injectCommentsIntoOoxml } from '@ansonlai/docx-redline-js';
94
+ const result = injectCommentsIntoOoxml(paragraphOoxml, [
95
+ {
96
+ paragraphIndex: 1,
97
+ textToFind: 'force majeure',
98
+ commentContent: 'Review this clause'
99
+ }
100
+ ], { author: 'Agent' });
101
+ ```
102
+
103
+ `paragraphIndex` is 1-based within the supplied OOXML payload. The comment
104
+ author belongs in the options object and applies to the injected comments.
105
+
106
+ ### Accept tracked changes from one user (or all users)
107
+
108
+ ```js
109
+ import { acceptTrackedChangesInOoxml } from '@ansonlai/docx-redline-js';
110
+ const acceptedMine = acceptTrackedChangesInOoxml(documentXml, { author: 'Agent' });
111
+ const acceptedAll = acceptTrackedChangesInOoxml(documentXml, { allAuthors: true });
112
+ ```
113
+
114
+ ### Reject tracked changes from one user (or all users)
115
+
116
+ ```js
117
+ import { rejectTrackedChangesInOoxml } from '@ansonlai/docx-redline-js';
118
+ const rejectedMine = rejectTrackedChangesInOoxml(documentXml, { author: 'Agent' });
119
+ const rejectedAll = rejectTrackedChangesInOoxml(documentXml, { allAuthors: true });
120
+ ```
121
+
122
+ Move revisions are consumed too: accept removes `w:moveFrom` and unwraps
123
+ `w:moveTo`; reject unwraps `w:moveFrom` and removes `w:moveTo`.
124
+
125
+ ### Delete comments from one user (or all users)
126
+
127
+ ```js
128
+ import { deleteCommentsByAuthorInOoxml } from '@ansonlai/docx-redline-js';
129
+ const removedMine = deleteCommentsByAuthorInOoxml(packageOrDocumentOoxml, { author: 'Agent' });
130
+ const removedAll = deleteCommentsByAuthorInOoxml(packageOrDocumentOoxml, { allAuthors: true });
131
+ ```
132
+
133
+ ### Apply multiple operations to full document XML
134
+
135
+ ```js
136
+ import {
137
+ applyOperationToDocumentXml,
138
+ applyOperationsToDocumentXml
139
+ } from '@ansonlai/docx-redline-js/standalone-runner';
140
+
141
+ const result = await applyOperationsToDocumentXml(documentXml, operations, 'Agent', runtimeContext, options);
142
+ ```
143
+
144
+ The operation runner uses these field names:
145
+
146
+ ```js
147
+ const operations = [
148
+ { type: 'redline', target: 'Old paragraph text', modified: 'New paragraph text', targetRef: 12 },
149
+ { type: 'comment', target: 'Paragraph text', textToComment: 'anchor text', commentContent: 'Comment body', targetRef: 18 },
150
+ { type: 'highlight', target: 'Paragraph text', textToHighlight: 'anchor text', color: 'yellow', targetRef: 24 }
151
+ ];
152
+ ```
153
+
154
+ `targetRef` is an optional 1-based paragraph reference used to disambiguate
155
+ duplicate text. An operation-level `author` overrides the batch author; batch
156
+ results report both `authorUsed` per item and the aggregate `authorsUsed` list.
157
+
158
+ For safer targeting, `target` may be a descriptor:
159
+
160
+ ```js
161
+ {
162
+ type: 'replace',
163
+ target: {
164
+ exactText: 'Repeated paragraph text',
165
+ paragraphId: '1A2B3C4D', // when present in the source OOXML
166
+ index: 12,
167
+ occurrence: 2,
168
+ inTable: false,
169
+ fingerprint: 'fnv1a32:...'
170
+ },
171
+ modified: 'Replacement text',
172
+ author: 'Editor'
173
+ }
174
+ ```
175
+
176
+ Call `preflightOperations(documentXml, operations, author)` when you want a
177
+ read-only inspection of an agent-generated batch before applying it. Preflight is
178
+ read-only and strict by default: duplicate exact text returns `AMBIGUOUS_TARGET`,
179
+ approximate text is not selected, and the result reports candidate targets,
180
+ missing anchors, existing revisions, authors, required artifacts, and
181
+ same-paragraph conflicts. For direct execution, `applyOperationsToDocumentXml` is
182
+ already transactional and atomic by default. When permissive resolution
183
+ encounters duplicate candidate paragraphs, it emits an
184
+ `AMBIGUOUS_TARGET_HEURISTIC_USED` warning; migrate to `{ strictTargets: true }`
185
+ with strict descriptors (`paragraphId`, `index`, `occurrence`, or `fingerprint`)
186
+ before v1.0.0.
187
+
188
+ Whole-paragraph deletions targeting paragraphs with existing comments fail with
189
+ `COMMENTED_CONTENT_DELETE`. Resolve or remove the comments first.
190
+
191
+ Use `result.documentXml` from these APIs when replacing full `word/document.xml`.
192
+ For mixed batches, prefer `applyOperationsToDocumentXml(...)`; it applies comments
193
+ before replacements so earlier edits cannot invalidate their anchors.
194
+
195
+ Batches default to `atomic: false` for maximum speed and progressive execution: valid operations are applied directly, while problematic operations report structured errors in `results` (with `continueOnError: true` by default).
196
+
197
+ When all-or-nothing transactional protection is desired (e.g. in high-stakes legal contracts, large automated migrations, or strict CI pipelines where partial edits are inadmissible), pass `{ atomic: true }` (or `--atomic` on the CLI). In atomic mode, if any operation fails or yields invalid markup, the entire batch is rolled back to the original untouched document (`rolledBack: true`, `hasChanges: false`, `documentXml: original`).
198
+
199
+ Internally, a batch uses one live document DOM and one revision allocator, then
200
+ serializes the full document once. Every operation has a DOM/allocator savepoint;
201
+ do not remove this isolation merely for speed. Redline accuracy, accepted and
202
+ rejected text, and exact rollback take precedence over throughput.
203
+
204
+ Every operation produces a commit-aware `receipt` (and batch-level `receipts`)
205
+ enumerating exact allocated `revisionItems`, `commentIds`, `numberingIds`,
206
+ `relationshipIds`, `affectedTargets`, and `warnings`. The output reconciliation
207
+ oracle (`reconcileReceiptsAgainstOutput`) validates that all reported durable IDs
208
+ are present in the serialized output; any discrepancy triggers rollback and fails closed.
209
+
210
+ Always inspect `status` and `error`, not only `hasChanges`. A failed transform
211
+ can return `{ hasChanges: false, status: 'error', error: ... }`. Missing or
212
+ ambiguous comment anchors are structured errors and roll back atomic batches;
213
+ `no_change` is reserved for genuine no-ops. Continue to inspect warnings for
214
+ non-fatal diagnostics.
215
+
216
+ ### Detect existing tracked changes
217
+
218
+ ```js
219
+ import { containsTrackedChanges } from '@ansonlai/docx-redline-js';
220
+ const hasTrackedChanges = containsTrackedChanges(xmlDoc);
221
+ ```
222
+
223
+ ### Inspect document parts before editing
224
+
225
+ ```js
226
+ import { inspectDocumentParts } from '@ansonlai/docx-redline-js';
227
+ const inspection = inspectDocumentParts({ documentXml, commentsXml, numberingXml });
228
+ ```
229
+
230
+ Reuse `exactText` plus `paragraphId` or `fingerprint` in an operation. Computed
231
+ list labels and excerpts are for display, not replacements for exact targets.
232
+
233
+ ### Safely edit a complete DOCX in Node
234
+
235
+ ```js
236
+ import { openDocx } from '@ansonlai/docx-redline-js/node';
237
+ const document = openDocx(inputBuffer);
238
+ const result = await document.applyOperations(operations, {
239
+ author: 'Agent', atomic: true, validate: true
240
+ });
241
+ if (!result.written) throw new Error(result.error?.message || 'No output written');
242
+ const outputBuffer = result.toBuffer();
243
+ ```
244
+
245
+ This facade defaults to strict targets, allocates package-safe comment IDs,
246
+ merges numbering, updates relationships/content types, and rolls back to the
247
+ original buffer when an atomic transaction fails.
248
+
249
+ ### Agent Document Workflow (CLI)
250
+
251
+ Use the `docx-redline` CLI for complete `.docx` files. It emits JSON on stdout,
252
+ keeps exact text intact, and never overwrites the source unless `--in-place` is
253
+ explicitly supplied.
254
+
255
+ #### Standard Workflow (Fast & Direct)
256
+
257
+ Use this for everything by default. `apply` is fast, progressive, and self-validating by default—it validates the resulting package and revision markup internally before writing. **Do not insert a `preflight` or baseline `validate` step on top of it "to be safe"**; `apply` already covers that internally. It supports inline one-liners as well as batch operations files:
258
+
259
+ ```bash
260
+ # 1. Inline one-liner edit (fastest for 1–2 edits; no JSON file needed)
261
+ docx-redline apply contract.docx --target "Original clause" --modified "New clause" --output reviewed.docx
262
+
263
+ # 2. Direct edit without tracked changes (clean text, no revision clutter)
264
+ docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
265
+
266
+ # 3. Batch operations with ops.json
267
+ docx-redline apply contract.docx --operations operations.json --output reviewed.docx
268
+ ```
269
+
270
+ Key CLI defaults and behaviors:
271
+ - **Author**: Automatically defaults to `'AI Redliner'` (overridable via `--author` or `DOCX_REDLINE_AUTHOR` environment variable).
272
+ - **Overwrite behavior**: Destination files provided via `--output` overwrite by default. To protect existing destination files, pass `--no-overwrite` or `--no-clobber`. The source document is never overwritten unless `--in-place` is specified.
273
+ - **Tracked changes**: Defaults to `generateRedlines: true`. When clean direct text is needed, pass `--no-redlines`.
274
+ - **Atomic rollback (optional)**: Operations apply progressively by default (`atomic: false`). For all-or-nothing transactional rollback where any error halts and reverts all changes, pass `--atomic`.
275
+ - Check `written: true` on stdout. If an error occurs, inspect `error.code` or `results[i].error.code` (e.g. `TARGET_NOT_FOUND`, `ANCHOR_NOT_FOUND`) to correct the target text and re-apply.
276
+
277
+ For multi-clause or multi-page reviews, apply edits **section-by-section** or clause-by-clause (e.g., using `--in-place` on a working copy) rather than bundling dozens of edits into one massive batch. This keeps context compact, simplifies error diagnosis, and prevents cascading anchor drift.
278
+
279
+ #### High-Assurance / Staged Verification Workflow (Optional)
280
+
281
+ This is an opt-in, higher-latency path for cases like large automated batch
282
+ migrations or workflows where the user specifically requests a non-mutating dry run
283
+ and an independent baseline audit report. **Never switch into it on your own initiative**
284
+ (not even for "high-stakes" contracts); unless the user explicitly requests it, stick with the
285
+ Standard workflow above. Use the extended verification cycle:
286
+
287
+ ```bash
288
+ docx-redline inspect contract.docx --non-empty
289
+ docx-redline extract contract.docx --range 10:30 > paragraphs.json
290
+ docx-redline preflight contract.docx --operations operations.json --author "Editor"
291
+ docx-redline apply contract.docx --operations operations.json --author "Editor" --output reviewed.docx
292
+ docx-redline validate reviewed.docx --baseline contract.docx
293
+ ```
294
+
295
+ Copy `exactText`, `paragraphId`, and `fingerprint` from `extract` into operation
296
+ targets. For most unique clauses, `"target": "exact paragraph text"` is
297
+ sufficient; use discriminators (`paragraphId`, `fingerprint`, `index`, or
298
+ `occurrence`) when duplicate paragraph text appears in the document. Never
299
+ normalize or reconstruct `exactText`. Operation files follow
300
+ [`docs/schemas/document-operations.schema.json`](docs/schemas/document-operations.schema.json).
301
+
302
+ #### Commands
303
+
304
+ - `inspect` returns the structured inventory, comments, authors, and counts.
305
+ - `extract` returns a compact target inventory with exact text.
306
+ - `preflight` checks targets, anchors, revisions, conflicts, authors, and needed artifacts without mutation (read-only).
307
+ - `apply` applies an operation file transactionally with automatic rollback and internal markup validation.
308
+ - `accept` and `reject` resolve revisions selected by `--author` or `--all-authors`.
309
+ - `delete-comments` removes matching definitions and document anchors together.
310
+ - A whole-paragraph delete stops with `COMMENTED_CONTENT_DELETE` when the
311
+ paragraph has an existing comment. Surface the returned reviewer and comment
312
+ text for human follow-up; do not silently convert this into comment removal.
313
+ - `validate` audits revision markup and DOCX package wiring, optionally comparing against a `--baseline`.
314
+
315
+ Paragraph indexes are 1-based. Inspection filters are `--index 12`,
316
+ `--range 10:30`, `--indexes 2,5,8`, `--search text`, `--revised`, `--table`,
317
+ `--body`, `--non-empty`, and `--view accepted|rejected|current`. A malformed
318
+ filter or unknown option is an error rather than an unfiltered fallback.
319
+
320
+ Mutating commands require `--author`, authors on every operation, or
321
+ `--all-authors` where applicable. Without `--output`, a sibling such as
322
+ `contract.redlined.docx` is chosen. Existing outputs are refused unless
323
+ `--force` is present. `--in-place` is the only way to overwrite the input.
324
+
325
+ Treat a nonzero exit code or JSON `status: "error"` as failure. A failed atomic
326
+ operation reports `written: false` and does not write an output file.
327
+ Missing or repeated comment anchors are errors rather than no-ops. Explicit
328
+ anchors match exact text first and then a unique ordinary-space/NBSP equivalent;
329
+ omit `textToComment` to comment the entire resolved paragraph.
330
+
331
+ To reply inside an existing Word comment thread, use the comment ID returned by
332
+ `inspect` and do not supply a paragraph target:
333
+
334
+ ```json
335
+ { "type": "comment_reply", "parentCommentId": "8", "commentContent": "Agreed; updated.", "author": "Editor" }
336
+ ```
337
+
338
+ Replies are represented in `word/commentsExtended.xml` and deliberately add no
339
+ new `commentRangeStart`, `commentRangeEnd`, or `commentReference` to the body.
340
+
341
+ #### Legacy skill wrapper migration
342
+
343
+ Older skills that invoke `scripts/extract_text.mjs` and
344
+ `scripts/apply_changes.mjs` should use the compatibility entrypoints published
345
+ with this package rather than carrying copied targeting or ZIP logic. The
346
+ legacy positional apply form remains supported:
347
+
348
+ ```bash
349
+ node scripts/apply_changes.mjs input.docx changes.json output.docx --author "Editor"
350
+ ```
351
+
352
+ Operation files may contain an array, an `operations` array, or a legacy
353
+ `changes` array. The wrapper delegates to the same strict, atomic, validated
354
+ CLI described above. If `--author` and operation authors are absent, its
355
+ compatibility fallback is `DOCX_REDLINE_AUTHOR` and then `Agent`. Consumers
356
+ must use the JSON status and process exit code; failed atomic work has
357
+ `written: false`, `outputPath: null`, and does not modify the output path.
358
+
359
+ #### Safe Operations File Creation (JSON vs. Shell Heredocs)
360
+
361
+ When composing batch operations files (`operations.json`):
362
+
363
+ - **Use structured file-writing tools or JSON serializers**: Write operations files via your environment's file-creation tools or a language JSON serializer (`JSON.stringify`).
364
+ - **Never compose operations in raw shell heredocs** (e.g., `cat << 'EOF'` in bash or PowerShell `@" ... "@`): Legal clauses routinely contain curly quotes (`“ ”`), smart apostrophes (`’`), em-dashes (`—`), section symbols (`§`), non-breaking spaces, and backslashes. Shell heredocs frequently mangle Unicode character encodings, quote escaping, and whitespace formatting, causing immediate `TARGET_NOT_FOUND` failures.
365
+
366
+ #### Walking Progressive Batch Results (Status & Partial Execution)
367
+
368
+ In default progressive mode (`atomic: false`), operations execute independently: valid operations commit to the document while failing operations report errors without aborting the batch:
369
+
370
+ - **Do not rely solely on top-level `written: true` or `status !== "error"`**: A progressive batch can return `status: "partial"` with `written: true` when some operations succeed and others fail.
371
+ - **Walk every entry in `results`**: Check `results[i].status` and `results[i].error`. Any `status: "error"` entry in `results` represents an unapplied change that must be investigated and resolved.
372
+ - **`written: false`**: Indicates that zero operations were committed (or an atomic rollback occurred). Never treat or present an unwritten or partial output file as complete.
373
+
374
+ #### Human-Readable References vs. Internal Machine Handles
375
+
376
+ Target handles such as `ref` (`P<index>`), `targetRef`, and bare paragraph `index` numbers are **strictly internal machine handles** for the CLI and engine. They do not correspond to any visual or followable marker in Microsoft Word:
377
+
378
+ - **Never surface `P11`, `P42`, or bare paragraph numbers** in user-facing prose, comments, redline summaries, or negotiation notes.
379
+ - Instead, cite locations using the human-readable fields provided by `inspect` / `extract`:
380
+ - **`provision`**: Lead with section/clause numbers when present (e.g., `§14.1 Entire Agreement`).
381
+ - **`nearestHeading` + ordinal offset**: When `provision` is absent, describe position relative to the nearest heading (e.g., `under "Limitation of Liability", 2nd paragraph`).
382
+ - **Structural context**: For unnumbered clauses prior to the first heading, use plain language (e.g., `opening recital, before Section 1`).
383
+ - **`humanReference`**: Use the pre-joined citation string provided directly on inspected paragraph objects.
384
+
385
+ #### Actionable Error Recovery Matrix
386
+
387
+ When the CLI or runner returns an error code, follow these specific recovery actions:
388
+
389
+ | Error Code | Meaning | Actionable Recovery |
390
+ |---|---|---|
391
+ | `TARGET_NOT_FOUND` | Target text did not match any paragraph. | **Do NOT retry with paraphrased text.** Re-run `extract`/`inspect`, copy `exactText` verbatim (including exact whitespace/punctuation), and add a discriminator (`paragraphId`, `fingerprint`, or `occurrence`). |
392
+ | `AMBIGUOUS_TARGET` | Multiple paragraphs match identical text. | Disambiguate by supplying `paragraphId`, `fingerprint`, `occurrence`, or `index` in the target descriptor. |
393
+ | `ANCHOR_NOT_FOUND` / `AMBIGUOUS_ANCHOR` | Comment anchor text was not uniquely matched in paragraph. | Narrow `textToComment` to a unique exact substring, or omit `textToComment` to anchor the comment to the entire paragraph. |
394
+ | `OVERLAPPING_TEXT_EDITS` | Multiple operations target the same paragraph concurrently. | Consolidate all changes to the same paragraph into a single `redline` or `replace` operation. |
395
+ | `EXISTING_REVISIONS` | Target paragraph contains tracked changes from another author. | Fails closed to protect third-party review marks. Report the other reviewer's name to the user. Do not pass `accept-all-first` without explicit authorization. |
396
+ | `COMMENTED_CONTENT_MERGE` / `COMMENTED_CONTENT_DELETE` | Operation would overwrite, revert, or delete content with comments. | Fails closed to prevent orphaned comment threads. Report the comment author and text to the user; resolve the comment before re-editing. |
397
+ | `INVALID_OPERATION` | Operation object violates schema or has incompatible fields. | Validate the JSON structure against [`document-operations.schema.json`](file:///c:/Users/Phara/Desktop/Projects/Docx%20Redline%20JS/docs/schemas/document-operations.schema.json) before targeting is attempted. |
398
+ | `STRUCTURED_CONTENT_INVALID` | Malformed Markdown table or structure in replacement text. | Ensure tables include a separator row (`\| --- \| --- \|`) and consistent column counts; do not downgrade to raw text. |
399
+
400
+ **Important Rule:** Never repeat the exact same failing command without correcting the reported cause. If an error persists after one correction attempt, stop and report the diagnostic code to the user.
401
+
402
+ #### Document Scope & Boundary Invariants
403
+
404
+ The `docx-redline` engine and CLI operate specifically on the **main document body**:
405
+
406
+ - **Supported Content**: Body paragraphs, numbered/bulleted lists, tables and table cells, comments, and comment replies.
407
+ - **Unsupported Content**: Headers, footers, footnotes, endnotes, floating text boxes, shape drawings, watermarks, and embedded macros.
408
+ - Do not attempt to target, edit, or comment on header/footer text or footnote citations using `docx-redline`. Use specialized document manipulation tools or manual editing for layout frames outside the body text.
409
+
410
+ ### Convert paragraph text into a Word list
411
+
412
+ ```js
413
+ const result = await applyRedlineToOxml(oxml, 'Item text', '1. Item text', {
414
+ generateRedlines: true
415
+ });
416
+ ```
417
+
418
+ ### Insert a large mixed-content block safely
419
+
420
+ Do not send a long attachment containing literal pipe rows, headings, lists,
421
+ and paragraphs as an unchecked replacement. Plan it first:
422
+
423
+ ```js
424
+ import { planStructuredReplacement } from '@ansonlai/docx-redline-js';
425
+
426
+ const plan = planStructuredReplacement(targetDescriptor, markdown, {
427
+ author: 'Agent'
428
+ });
429
+ if (!plan.valid || !plan.operation) {
430
+ throw new Error(plan.issues.map(issue => issue.message).join(' '));
431
+ }
432
+ const result = await document.applyOperations([plan.operation], {
433
+ author: 'Agent', atomic: true, validate: true
434
+ });
435
+ ```
436
+
437
+ Use blank lines between paragraphs, `#`/`##` for headings, normal Markdown
438
+ markers for lists, and a separator row immediately after every table header:
439
+
440
+ ```markdown
441
+ | Agency | Contact |
442
+ | --- | --- |
443
+ | BCHD | Dr. Jenkins |
444
+ ```
445
+
446
+ The planner returns typed `blocks`, counts, normalized Markdown, and structured
447
+ issues. `TABLE_SEPARATOR_REQUIRED` is an error: never remove `structuredContent`
448
+ or retry the same content as plain text merely to make the operation pass. Keep
449
+ the result as one atomic replacement operation so the first inserted block does
450
+ not invalidate the anchor for later blocks. After applying, require real
451
+ `w:tbl`, positive list `w:numId` values, valid redline OOXML, and independent
452
+ Accept/Reject checks.
453
+
454
+ ### Reconcile a table
455
+
456
+ ```js
457
+ import { reconcileMarkdownTableOoxml } from '@ansonlai/docx-redline-js';
458
+ const result = await reconcileMarkdownTableOoxml(tableOoxml, originalText, markdownTable);
459
+ ```
460
+
461
+ ## Module Map
462
+
463
+ ```
464
+ index.js
465
+ adapters/
466
+ config.js
467
+ xml-adapter.js
468
+ logger.js
469
+ core/
470
+ types.js
471
+ paragraph-text.js
472
+ word-xml.js
473
+ paragraph-targeting.js
474
+ list-targeting.js
475
+ table-targeting.js
476
+ engine/
477
+ oxml-engine.js
478
+ surgical-mode.js
479
+ surgical-run-splitting.js
480
+ surgical-diff-application.js
481
+ surgical-spans.js
482
+ reconstruction-mode.js
483
+ reconstruction-writer.js
484
+ format-application.js
485
+ formatting-removal.js
486
+ run-builders.js
487
+ table-mode.js
488
+ pipeline/
489
+ pipeline.js
490
+ ingestion.js
491
+ ingestion-export.js
492
+ diff-engine.js
493
+ markdown-processor.js
494
+ serialization.js
495
+ list-generation.js
496
+ services/
497
+ document-operation-session.js
498
+ document-operation-applier.js
499
+ document-operation-mutations.js
500
+ batch-operation-orchestrator.js
501
+ operation-heuristics.js
502
+ standalone-operation-runner.js
503
+ standalone-operation-runner.d.ts
504
+ document-operation-contract.js
505
+ operation-preflight.js
506
+ standalone-docx-plumbing.js
507
+ numbering-helpers.js
508
+ comment-engine.js
509
+ revision-comment-management.js
510
+ table-reconciliation.js
511
+ package-builder.js
512
+ document-inspection.js
513
+ node/
514
+ docx-document.js
515
+ zip-archive.js
516
+ orchestration/
517
+ route-plan.js
518
+ list-markdown.js
519
+ list-structural-fallback.js
520
+ ```
521
+
522
+ ## Common Patterns
523
+
524
+ ### Options and Defaults Reference
525
+
526
+ | Option | Type | Default | Description |
527
+ |--------|------|---------|-------------|
528
+ | `generateRedlines` | `boolean` | `true` | When `true`, emits Word-native tracked changes (`w:ins`/`w:del`). When `false`, applies direct text 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. |
529
+ | `author` | `string` | `'AI Redliner'` | Reviewer/author name stamped on generated tracked changes and comments. Overridable via `DOCX_REDLINE_AUTHOR` environment variable. |
530
+ | `atomic` | `boolean` | `false` | Batch transaction mode. By default (`false`), valid edits are applied directly and failing operations report errors. When `true`, any operation failure rolls back the entire batch to the original document state (`rolledBack: true`, `hasChanges: false`). Use `atomic: true` (or `--atomic` in CLI) for high-assurance workflows. |
531
+ | `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. |
532
+ | `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. |
533
+ | `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. |
534
+ | `existingRevisions` | `string` | `'merge-same-author'` | How to handle paragraphs with existing tracked changes. `'merge-same-author'` merges the same author's work and protects other authors with `EXISTING_REVISIONS`. `'slice-cross-author'` retains same-author merging 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. |
535
+ | `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
536
+ | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
537
+
538
+ ### Options shape
539
+
540
+ ```js
541
+ {
542
+ generateRedlines: true,
543
+ author: 'AI Redliner',
544
+ atomic: false,
545
+ structuredContent: true,
546
+ pairReplacements: true,
547
+ existingRevisions: 'merge-same-author',
548
+ removeFormatting: false,
549
+ sanitizeInput: false
550
+ }
551
+ ```
552
+
553
+ ### Typical return shape
554
+
555
+ ```js
556
+ {
557
+ oxml: string,
558
+ hasChanges: boolean,
559
+ status?: 'ok' | 'no-op' | 'error',
560
+ error?: { code: string, message: string },
561
+ warnings?: string[],
562
+ numberingXml?: string,
563
+ useNativeApi?: boolean
564
+ }
565
+ ```
566
+
567
+ Known error codes include `PARSE_ERROR`, `TARGET_NOT_FOUND`, `PARTIAL_TARGET`,
568
+ `EXISTING_REVISIONS`, `COMMENTED_CONTENT_MERGE`, `UNSAFE_REVISION_NESTING`, `UNSUPPORTED_REVISION_VIEW_MUTATION`,
569
+ `UNSAFE_PARAGRAPH_BOUNDARY`, `DIFF_TOKEN_LIMIT`, and `BATCH_OPERATION_FAILED`.
570
+
571
+ For ingestion that must distinguish an empty document from malformed OOXML,
572
+ use `ingestWordOoxmlToPlainTextResult` or
573
+ `ingestWordOoxmlToMarkdownResult`. The legacy ingestion helpers intentionally
574
+ retain their string-only return type and return `''` for parse failures.
575
+
576
+ ### Target text versus replacement text
577
+
578
+ Target resolution may normalize surrounding or repeated whitespace while
579
+ matching a paragraph. Replacement text is not normalized: tabs, line breaks,
580
+ non-breaking spaces, repeated spaces, and leading/trailing whitespace become
581
+ part of the requested edit. When editing extracted document text, copy the
582
+ exact paragraph text and modify it in place rather than round-tripping it
583
+ through a formatter that may change whitespace.
584
+
585
+ For ordinary insertions and deletions, target the visible accepted view:
586
+ inserted `w:t` text is visible and deleted `w:delText` is not. Move revisions
587
+ and other complex structures require additional care until targeting and
588
+ ingestion share one canonical text extractor. Prefer a `targetRef` plus the full
589
+ paragraph text when duplicate paragraphs are possible. Current text-only
590
+ matching can select the first matching paragraph, so callers that cannot
591
+ disambiguate safely should stop instead of guessing.
592
+
593
+ ### OOXML wrapping for Word insertOoxml scenarios
594
+
595
+ ```js
596
+ import { wrapInDocumentFragment } from '@ansonlai/docx-redline-js';
597
+ const wrapped = wrapInDocumentFragment(rawOoxml, { includeNumbering: true, numberingXml });
598
+ ```
599
+
600
+ ### Output shape guardrail (important for packaging)
601
+
602
+ When consuming `result.oxml`, do not assume the payload is always safe to write
603
+ directly into `word/document.xml`.
604
+
605
+ - Paragraph/range/table APIs can return a fragment, `<w:document>`, or package payload (`<pkg:package>`).
606
+ - `applyOperationToDocumentXml(...).documentXml` is the document-safe path when you need a full `word/document.xml` replacement.
607
+ - Use `extractReplacementNodesFromOoxml(payload)` to normalize unknown payloads.
608
+ - If `sourceType === 'package'` or the payload starts with `<pkg:package`, do not write it into `word/document.xml` as-is.
609
+
610
+ ## Gotchas
611
+
612
+ 1. Call `configureXmlProvider` first in Node.js.
613
+ 2. `applyRedlineToOxml` is async.
614
+ 3. Paragraph APIs expect paragraph-level OOXML, not full `word/document.xml` in all cases.
615
+ 4. List operations may return `numberingXml` that must be merged into package parts. When `word/numbering.xml` already exists, pass `mergeNumberingXmlBySchemaOrder` to `ensureNumberingArtifactsInZip`; without a merge callback the helper replaces the prior payload.
616
+ That replacement behavior is deprecated and will become an error in the next major version.
617
+ 5. `useNativeApi: true` means standalone mode cannot fully handle that operation path.
618
+ 6. `deleteCommentsByAuthorInOoxml` removes definitions and linked anchors only when they are present in the same OOXML payload. In a real `.docx`, `word/comments.xml` and `word/document.xml` are separate parts and must both be updated by the package integration layer.
619
+ 7. If output begins with `<pkg:package`, treat it as package-level OOXML and normalize it before writing anything back to `word/document.xml`.
620
+ 8. Existing revisions from the same author are merged by default against the pre-revision baseline (`merge-same-author`), while third-party revisions fail closed with `EXISTING_REVISIONS`. Pass `existingRevisions: 'slice-cross-author'` to preserve third-party attribution while editing inside pending insertions, `'accept-all-first'` to normalize all prior revisions first, or `'reject-input'` to refuse any revised paragraph.
621
+ 9. Caller content is not sanitized by default. Pass `sanitizeInput: true` only for raw assistant output; literal dollar delimiters and `\\n` sequences are never rewritten.
622
+ 10. Hyperlinks, bookmarks, comment markers, tabs/breaks, and footnote/endnote references are structural OOXML and should survive adjacent redline edits.
623
+ 11. Internally, create Word elements through `createWordElement` and tracked-change metadata through `createRevisionMetadata`.
624
+ 12. Revision IDs are document-scoped in public operation paths. Thread the
625
+ internal allocator through new string-serialization paths; generated
626
+ `w:id` values are not stable across documents.
627
+ 13. Splitting or cloning a run can duplicate nested `w:rPrChange` metadata.
628
+ Preserve the original ID on at most one resulting run and allocate fresh
629
+ IDs for every additional clone through the document-scoped allocator.
630
+ 14. Run `validateRedlineOoxml` on generated markup before packaging it, then
631
+ run `validateDocxPackage` after merging comments and numbering artifacts.
632
+
633
+ ## Validation Commands
634
+
635
+ ```bash
636
+ npm test
637
+ npm run test:isolation
638
+ npm run check:types
639
+ node scripts/export-validation-fixtures.mjs
640
+ ```
641
+
642
+ Optional Windows/Word smoke test for a completed `.docx`:
643
+
644
+ ```bash
645
+ npm run smoke:word -- path/to/file.docx
646
+ ```