@ansonlai/docx-redline-js 0.5.0 → 0.5.2

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/AGENTS.md CHANGED
@@ -55,15 +55,18 @@ const result = await applyRedlineToOxml(oxml, originalText, modifiedText, {
55
55
  contains tracked changes from the same author, prior revisions by that author are
56
56
  reverted to the pre-revision baseline and re-diffed to the new text, cleanly
57
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
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
60
63
  `existingRevisions: 'accept-all-first'` (or `--existing-revisions accept-all-first`
61
64
  via CLI) to normalize all prior revisions first, or `'reject-input'` to refuse any
62
65
  paragraph with open revisions. Use `'accept-all-first-keep-normalized'` only when
63
- accepted revisions should be returned as a real change even on a no-op edit.
64
- Same-author merging also fails with `COMMENTED_CONTENT_MERGE` when the revised
65
- paragraph contains comment anchors, because reverting the prior revision could
66
- remove or orphan those comments. Resolve the comments before re-editing.
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.
67
70
 
68
71
  ### Apply a text edit without tracked changes (Direct Edits)
69
72
 
@@ -251,7 +254,7 @@ explicitly supplied.
251
254
 
252
255
  #### Standard Workflow (Fast & Direct)
253
256
 
254
- `apply` is fast, progressive, and self-validating by default. It supports inline one-liners as well as batch operations files:
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:
255
258
 
256
259
  ```bash
257
260
  # 1. Inline one-liner edit (fastest for 1–2 edits; no JSON file needed)
@@ -260,12 +263,16 @@ docx-redline apply contract.docx --target "Original clause" --modified "New clau
260
263
  # 2. Direct edit without tracked changes (clean text, no revision clutter)
261
264
  docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
262
265
 
263
- # 3. Batch operations with ops.json
266
+ # 3. Cross-author edit inside another reviewer's pending insertion
267
+ docx-redline apply contract.docx --target "Pending clause text" --modified "Updated clause text" --existing-revisions slice-cross-author --output reviewed.docx
268
+
269
+ # 4. Batch operations with ops.json
264
270
  docx-redline apply contract.docx --operations operations.json --output reviewed.docx
265
271
  ```
266
272
 
267
273
  Key CLI defaults and behaviors:
268
274
  - **Author**: Automatically defaults to `'AI Redliner'` (overridable via `--author` or `DOCX_REDLINE_AUTHOR` environment variable).
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.
269
276
  - **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.
270
277
  - **Tracked changes**: Defaults to `generateRedlines: true`. When clean direct text is needed, pass `--no-redlines`.
271
278
  - **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,9 +282,11 @@ For multi-clause or multi-page reviews, apply edits **section-by-section** or cl
275
282
 
276
283
  #### High-Assurance / Staged Verification Workflow (Optional)
277
284
 
278
- For high-stakes legal contracts, large automated batch migrations, or workflows
279
- requiring explicit non-mutating pre-checks and an independent baseline audit
280
- report, use the extended verification cycle:
285
+ This is an opt-in, higher-latency path for cases like large automated batch
286
+ migrations or workflows where the user specifically requests a non-mutating dry run
287
+ and an independent baseline audit report. **Never switch into it on your own initiative**
288
+ (not even for "high-stakes" contracts); unless the user explicitly requests it, stick with the
289
+ Standard workflow above. Use the extended verification cycle:
281
290
 
282
291
  ```bash
283
292
  docx-redline inspect contract.docx --non-empty
@@ -351,6 +360,58 @@ compatibility fallback is `DOCX_REDLINE_AUTHOR` and then `Agent`. Consumers
351
360
  must use the JSON status and process exit code; failed atomic work has
352
361
  `written: false`, `outputPath: null`, and does not modify the output path.
353
362
 
363
+ #### Safe Operations File Creation (JSON vs. Shell Heredocs)
364
+
365
+ When composing batch operations files (`operations.json`):
366
+
367
+ - **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`).
368
+ - **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.
369
+
370
+ #### Walking Progressive Batch Results (Status & Partial Execution)
371
+
372
+ In default progressive mode (`atomic: false`), operations execute independently: valid operations commit to the document while failing operations report errors without aborting the batch:
373
+
374
+ - **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.
375
+ - **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.
376
+ - **`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.
377
+
378
+ #### Human-Readable References vs. Internal Machine Handles
379
+
380
+ 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:
381
+
382
+ - **Never surface `P11`, `P42`, or bare paragraph numbers** in user-facing prose, comments, redline summaries, or negotiation notes.
383
+ - Instead, cite locations using the human-readable fields provided by `inspect` / `extract`:
384
+ - **`provision`**: Lead with section/clause numbers when present (e.g., `§14.1 Entire Agreement`).
385
+ - **`nearestHeading` + ordinal offset**: When `provision` is absent, describe position relative to the nearest heading (e.g., `under "Limitation of Liability", 2nd paragraph`).
386
+ - **Structural context**: For unnumbered clauses prior to the first heading, use plain language (e.g., `opening recital, before Section 1`).
387
+ - **`humanReference`**: Use the pre-joined citation string provided directly on inspected paragraph objects.
388
+
389
+ #### Actionable Error Recovery Matrix
390
+
391
+ When the CLI or runner returns an error code, follow these specific recovery actions:
392
+
393
+ | Error Code | Meaning | Actionable Recovery |
394
+ |---|---|---|
395
+ | `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`). |
396
+ | `AMBIGUOUS_TARGET` | Multiple paragraphs match identical text. | Disambiguate by supplying `paragraphId`, `fingerprint`, `occurrence`, or `index` in the target descriptor. |
397
+ | `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. |
398
+ | `OVERLAPPING_TEXT_EDITS` | Multiple operations target the same paragraph concurrently. | Consolidate all changes to the same paragraph into a single `redline` or `replace` operation. |
399
+ | `EXISTING_REVISIONS` | Target paragraph contains tracked changes from another author. | Fails closed to protect third-party review marks. If editing inside that reviewer's pending insertion is intended, pass `--existing-revisions slice-cross-author` (or `existingRevisions: 'slice-cross-author'`). Do not pass `accept-all-first` without explicit user authorization. |
400
+ | `PATCH_ROUNDTRIP_MISMATCH` | A cross-author surgical edit did not reconstruct the requested modified text exactly. | Treat the operation as unapplied. Re-extract the exact paragraph text and split the edit into a narrower operation that does not cross the reported structural boundary. |
401
+ | `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. |
402
+ | `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. |
403
+ | `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. |
404
+
405
+ **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.
406
+
407
+ #### Document Scope & Boundary Invariants
408
+
409
+ The `docx-redline` engine and CLI operate specifically on the **main document body**:
410
+
411
+ - **Supported Content**: Body paragraphs, numbered/bulleted lists, tables and table cells, comments, and comment replies.
412
+ - **Unsupported Content**: Headers, footers, footnotes, endnotes, floating text boxes, shape drawings, watermarks, and embedded macros.
413
+ - 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.
414
+
354
415
  ### Convert paragraph text into a Word list
355
416
 
356
417
  ```js
@@ -475,7 +536,7 @@ orchestration/
475
536
  | `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. |
476
537
  | `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. |
477
538
  | `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. |
478
- | `existingRevisions` | `string` | `'merge-same-author'` | How to handle paragraphs with existing tracked changes. `'merge-same-author'` automatically merges subsequent edits from the same author against the pre-revision baseline while protecting different authors' revisions with `EXISTING_REVISIONS`. Pass `'accept-all-first'` to normalize prior revisions or `'reject-input'` to refuse editing revised paragraphs. |
539
+ | `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. |
479
540
  | `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
480
541
  | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
481
542
 
@@ -508,8 +569,8 @@ orchestration/
508
569
  }
509
570
  ```
510
571
 
511
- Known error codes include `PARSE_ERROR`, `TARGET_NOT_FOUND`, `PARTIAL_TARGET`,
512
- `EXISTING_REVISIONS`, `COMMENTED_CONTENT_MERGE`, `UNSAFE_REVISION_NESTING`, `UNSUPPORTED_REVISION_VIEW_MUTATION`,
572
+ Known error codes include `PARSE_ERROR`, `TARGET_NOT_FOUND`, `PARTIAL_TARGET`,
573
+ `EXISTING_REVISIONS`, `COMMENTED_CONTENT_MERGE`, `UNSAFE_REVISION_NESTING`, `UNSUPPORTED_REVISION_VIEW_MUTATION`,
513
574
  `UNSAFE_PARAGRAPH_BOUNDARY`, `DIFF_TOKEN_LIMIT`, and `BATCH_OPERATION_FAILED`.
514
575
 
515
576
  For ingestion that must distinguish an empty document from malformed OOXML,
@@ -561,7 +622,7 @@ directly into `word/document.xml`.
561
622
  5. `useNativeApi: true` means standalone mode cannot fully handle that operation path.
562
623
  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.
563
624
  7. If output begins with `<pkg:package`, treat it as package-level OOXML and normalize it before writing anything back to `word/document.xml`.
564
- 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: 'accept-all-first'` to normalize all prior revisions first, or `'reject-input'` to refuse any revised paragraph.
625
+ 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.
565
626
  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.
566
627
  10. Hyperlinks, bookmarks, comment markers, tabs/breaks, and footnote/endnote references are structural OOXML and should survive adjacent redline edits.
567
628
  11. Internally, create Word elements through `createWordElement` and tracked-change metadata through `createRevisionMetadata`.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,29 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.5.1
4
+
5
+ ### Highlights & New Features
6
+
7
+ - **Cross-Author Revision Slicing (`existingRevisions: 'slice-cross-author'`)**: Adds native support for editing text inside another reviewer's pending tracked insertion without erasing their attribution or requiring prior acceptance.
8
+ - **Word-Native Insertion Slicing**: When inserting text inside another author's pending `<w:ins>`, the engine splits the outer carrier into sibling `<w:ins>` elements at the paragraph level (`[ins(A), ins(B), ins(A)]`), ensuring strict ECMA-376 schema compliance without illegal `ins/ins` nesting.
9
+ - **Word-Native Deletion Slicing**: When deleting text inside another author's pending `<w:ins>`, the engine nests `<w:del>` directly inside `<w:ins>` per ECMA-376 Part 1 `CT_RunTrackChange` Section 17.13.5.21 and Microsoft Word Desktop 365 native behavior.
10
+ - **Boundary & Straddle Deletions**: Deletions straddling baseline text and pending insertions cleanly partition into separate top-level and nested `<w:del>` containers while sharing unified event/author attribution.
11
+ - **Multi-Author Stacked Revisions**: Multiple reviewers can independently delete or insert content within the same carrier insertion without cross-author interference.
12
+ - **Cascading & Coalescing Lifecycles**: Full round-trip lifecycle parity with Microsoft Word Desktop:
13
+ - Rejecting Author A cleanly discards Author A's insertion and any dependent nested deletions by Author B.
14
+ - Accepting Author A unwraps the insertion into baseline text while leaving Author B's deletions pending against the baseline.
15
+ - Rejecting Author B restores Author B's deleted text within Author A's insertion, and coalesces adjacent split `<w:ins>` fragments back into a single continuous carrier.
16
+ - **CLI & Facade Integration**: Fully exposed via the `docx-redline` CLI (`--existing-revisions slice-cross-author`), Node facade (`openDocx`), and batch operation runner.
17
+
18
+ ### Non-breaking Changes & Improvements
19
+
20
+ - **Validation Update (`validateRedlineOoxml`)**: Refined `NESTED_REVISION` checks to permit direct `<w:ins><w:del>...</w:del></w:ins>` nesting (standard ECMA-376 and Word Desktop behavior), while continuing to strictly reject `ins/ins`, `del/del`, and `del/ins` nesting.
21
+ - **Slicing Round-Trip Guard**: Cross-author surgical edits now preserve whitespace-only insertions (including ordinary-space replacements for NBSP characters beside hyperlinks) and verify the exact accepted-view text before reporting success. A mismatch fails closed with `PATCH_ROUNDTRIP_MISMATCH` and returns the original OOXML unchanged.
22
+ - **Insertion Stress Hardening**: Slicing now detects edge whitespace changes exactly, uses a character-local insertion-only diff when the original text is an exact subsequence of the modified text, and coalesces new text into an existing same-author carrier when foreign revisions are also present. This prevents repeated phrases from relocating insertions and prevents invalid `w:ins/w:ins` nesting in mixed-author paragraphs.
23
+ - **Preflight Inspection**: `preflightOperations` now inspects and validates `slice-cross-author` batches, reporting pending foreign-author carrier targets as `ready` instead of `EXISTING_REVISIONS`.
24
+ - **Test Suite Expansion**: Added 6 new test suites covering 36 Word Desktop COM golden fixtures, carrier splitting invariants, the SYN-01..12d synthetic test matrix, PKG-01..06 strict package differential replay, the repeated-text/hyperlink whitespace regression, and 76 deterministic insertion stress scenarios (expanding the suite from 88 to 94 passing suites).
25
+
26
+ ## 0.5.0
4
27
 
5
28
  ### ⚠️ Breaking changes
6
29
 
package/README.md CHANGED
@@ -143,6 +143,8 @@ docx-redline extract contract.docx --range 10:30
143
143
  docx-redline preflight contract.docx --operations operations.json --author "Editor"
144
144
  docx-redline apply contract.docx --operations operations.json --author "Editor" --output reviewed.docx
145
145
  docx-redline validate reviewed.docx
146
+ ```
147
+
146
148
  ```bash
147
149
  # Inline one-liner edit (no operations file needed)
148
150
  docx-redline apply contract.docx --target "Original clause text" --modified "New clause text" --output reviewed.docx
@@ -150,6 +152,9 @@ docx-redline apply contract.docx --target "Original clause text" --modified "New
150
152
  # Direct edit without tracked changes
151
153
  docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
152
154
 
155
+ # Cross-author edit inside another reviewer's pending insertion
156
+ docx-redline apply contract.docx --target "Another author's clause" --modified "Revised clause" --existing-revisions slice-cross-author --output reviewed.docx
157
+
153
158
  # High-assurance atomic batch
154
159
  docx-redline apply contract.docx --operations operations.json --atomic --output reviewed.docx
155
160
  ```
@@ -157,6 +162,7 @@ docx-redline apply contract.docx --operations operations.json --atomic --output
157
162
  All commands emit JSON on stdout. `apply` defaults:
158
163
  - **Author**: Defaults to `'AI Redliner'` (or `DOCX_REDLINE_AUTHOR` environment variable).
159
164
  - **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.
165
+ - **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.
160
166
  - **Transactionality**: Defaults to `atomic: false` (applies valid operations and reports any failures). Pass `--atomic` for all-or-nothing rollback on any operation error.
161
167
  - **Tracked changes**: Defaults to `generateRedlines: true`. Pass `--no-redlines` when clean direct text edits are desired.
162
168
  - **Inline edits**: Use `--target <text>` with `--modified <text>` or `--comment <text>` for quick one-liners without creating a JSON file.
@@ -183,13 +189,13 @@ See [the agent workflow in AGENTS.md](./AGENTS.md#agent-document-workflow-cli) a
183
189
  | `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. |
184
190
  | `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. |
185
191
  | `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. |
186
- | `existingRevisions` | `string` | `'merge-same-author'` | How to handle paragraphs with existing tracked changes. `'merge-same-author'` automatically merges subsequent edits from the same author against the pre-revision baseline while protecting different authors' revisions with `EXISTING_REVISIONS`. Pass `'accept-all-first'` to normalize prior revisions or `'reject-input'` to refuse editing revised paragraphs. |
192
+ | `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. |
187
193
  | `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
188
- | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
189
-
190
- Same-author revision merging refuses paragraphs containing comment anchors with
191
- `COMMENTED_CONTENT_MERGE`; resolve those comments first so the merge cannot
192
- remove or orphan their anchors.
194
+ | `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
195
+
196
+ Same-author revision merging refuses paragraphs containing comment anchors with
197
+ `COMMENTED_CONTENT_MERGE`; resolve those comments first so the merge cannot
198
+ remove or orphan their anchors.
193
199
 
194
200
  Common result fields:
195
201
 
@@ -205,6 +211,24 @@ the safe ceiling of 262,144 unique diff tokens return `DIFF_TOKEN_LIMIT` with
205
211
  the original OOXML unchanged so callers can split the operation without risking
206
212
  silent text loss.
207
213
 
214
+ ### Editing inside existing revisions (cross-author slicing)
215
+
216
+ 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:
217
+
218
+ ```js
219
+ const result = await applyRedlineToOxml(paragraphOoxml, originalText, modifiedText, {
220
+ generateRedlines: true,
221
+ author: 'Anson Lai',
222
+ existingRevisions: 'slice-cross-author'
223
+ });
224
+ ```
225
+
226
+ The engine applies Microsoft Word Desktop-native tracked change structures:
227
+ - **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.
228
+ - **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.
229
+ - **Straddle deletions**: Deletions spanning between baseline text and pending insertions cleanly partition across their respective container contexts without invalid coalescing.
230
+ - **Lifecycle parity**: Accepting or rejecting either reviewer independently produces identical results to Microsoft Word Desktop's native review pane.
231
+
208
232
  ### Replacing a heading with a tracked list
209
233
 
210
234
  The list route treats a one-paragraph heading expanded into multiple markdown
@@ -309,11 +333,19 @@ an earlier block has already replaced.
309
333
  | `ensureCommentsExtendedArtifactsInZip(zip, commentsExtendedXml)` | Add or replace modern Word comment-thread metadata in a `.docx` package. |
310
334
  | `validateDocxPackage(zip)` | Validate `.docx` structural consistency. |
311
335
 
312
- Malformed OOXML never escapes these public transform APIs as a raw parser
313
- exception. Transforms return `status: 'error'` with `error.code === 'PARSE_ERROR'`;
314
- validators return a `PARSE_ERROR` issue. Recoverable XML parser
315
- diagnostics are forwarded through the configured logger and included in
316
- `warnings` where the result shape supports them.
336
+ Malformed OOXML never escapes these public transform APIs as a raw parser
337
+ exception. Transforms return `status: 'error'` with `error.code === 'PARSE_ERROR'`;
338
+ validators return a `PARSE_ERROR` issue. Recoverable XML parser
339
+ diagnostics are forwarded through the configured logger and included in
340
+ `warnings` where the result shape supports them.
341
+
342
+ Cross-author slicing also verifies its exact accepted-view text before success.
343
+ If a structural boundary prevents exact reconstruction, the transform returns
344
+ `status: 'error'` with `error.code === 'PATCH_ROUNDTRIP_MISMATCH'`,
345
+ `hasChanges: false`, and the original OOXML unchanged.
346
+ Pure insertion-only slicing uses an exact character-local diff so repeated words
347
+ cannot move an insertion to a different occurrence. Leading/trailing spaces,
348
+ tabs, and non-breaking spaces are treated as real changes rather than no-ops.
317
349
 
318
350
  ### Deep Imports
319
351
 
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * Mirrors the invariants enforced by the test-suite round-trip harness so
5
5
  * downstream consumers can verify output before writing it into a package:
6
- * no nested revisions, deleted text uses w:delText, revision metadata is
7
- * complete, revision ids are unique, and boundary whitespace is preserved.
6
+ * only schema-permitted nested revisions, deleted text uses w:delText,
7
+ * revision metadata is complete, revision ids are unique, and boundary
8
+ * whitespace is preserved.
8
9
  */
9
10
 
10
11
  import { parseXml } from '../adapters/xml-adapter.js';
@@ -107,13 +108,18 @@ export function validateRedlineOoxml(oxml) {
107
108
  }
108
109
  }
109
110
 
110
- // No w:ins/w:del nested inside another w:ins/w:del.
111
+ // A w:del may be a direct revision child of w:ins. All other insertion /
112
+ // deletion nesting is rejected, including deeper revisions inside that del.
111
113
  for (const revision of revisions) {
112
114
  const nested = Array.from(revision.getElementsByTagName('*'))
113
115
  .filter(el => el !== revision && ['ins', 'del'].includes(localNameOf(el)));
114
- if (nested.length > 0) {
116
+ const invalidNested = nested.find(candidate => {
117
+ if (localNameOf(revision) !== 'ins' || localNameOf(candidate) !== 'del') return true;
118
+ return candidate.parentNode !== revision;
119
+ });
120
+ if (invalidNested) {
115
121
  addIssue('NESTED_REVISION', 'error',
116
- `<${revision.nodeName}> (w:id="${wordAttribute(revision, 'id')}") contains nested <${nested[0].nodeName}>.`);
122
+ `<${revision.nodeName}> (w:id="${wordAttribute(revision, 'id')}") contains invalid nested <${invalidNested.nodeName}>.`);
117
123
  }
118
124
  }
119
125