@ansonlai/docx-redline-js 0.5.4 → 0.6.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.
- package/AGENTS.md +82 -697
- package/ARCHITECTURE.md +13 -1
- package/CHANGELOG.md +8 -0
- package/README.md +177 -45
- package/core/paragraph-targeting.js +14 -2
- package/dist/docx-redline-js.esm.js +184 -51
- package/dist/docx-redline-js.esm.js.map +3 -3
- package/dist/docx-redline-js.esm.min.js +77 -77
- package/dist/docx-redline-js.esm.min.js.map +4 -4
- package/docs/AGENT_FAST_START.md +59 -0
- package/docs/AGENT_KNOWLEDGE_BASE.md +878 -0
- package/docs/SKILL_AUTHORING.md +126 -0
- package/docs/TESTING.md +35 -1
- package/docs/schemas/document-operations.schema.json +5 -1
- package/docs/validation-reports/2026-09-12-agent-cli-discovery-baseline.md +56 -0
- package/docs/validation-reports/2026-09-12-agent-protocol-rollout.md +86 -0
- package/docs/validation-reports/2026-09-13-agent-cli-efficiency-rollout.md +86 -0
- package/engine/oxml-engine.js +80 -13
- package/engine/run-builders.js +5 -15
- package/index.d.ts +28 -3
- package/node/cli-help.js +209 -0
- package/node/cli.js +323 -65
- package/node/docx-document.js +120 -69
- package/node/index.d.ts +6 -2
- package/package.json +15 -3
- package/scripts/generate-cross-author-slicing-fixtures.ps1 +25 -25
- package/services/batch-operation-orchestrator.js +215 -120
- package/services/document-inspection.js +89 -11
- package/services/document-operation-applier.js +52 -34
- package/services/document-operation-contract.js +10 -6
- package/services/document-operation-mutations.js +51 -5
- package/services/document-operation-session.js +4 -0
- package/services/error-recovery.js +174 -0
- package/services/operation-batch-compiler.js +394 -0
- package/services/operation-preflight.js +91 -72
- package/services/standalone-operation-runner.d.ts +17 -1
- package/docs/plans/2026-09-05-structural-revisions-and-fidelity-oracles.md +0 -1669
- package/docs/plans/2026-09-08-cross-author-revision-slicing.md +0 -1399
- package/docs/plans/completed/2026-03-01-release-0.1.4-design.md +0 -33
- package/docs/plans/completed/2026-03-01-release-0.1.4.md +0 -110
- package/docs/plans/completed/2026-05-31-architectural changes.md +0 -593
- package/docs/plans/completed/2026-08-02-reliability-improvements.md +0 -1155
- package/docs/plans/completed/2026-08-30-reliability-testing-improvements.md +0 -488
- package/docs/plans/completed/2026-09-01-performance-and-complexity-reduction.md +0 -669
- package/docs/plans/completed/2026-09-03-agent-friendly-document-workflows.md +0 -427
- package/docs/plans/completed/2026-09-04-comment-anchor-and-cli-reliability.md +0 -519
- package/docs/plans/completed/PERFORMANCE-CONSOLIDATION.md +0 -69
- package/docs/plans/completed/structural-revision-capability-matrix.md +0 -115
- package/docs/test-comparison-dashboard.html +0 -4338
- package/docs/validation-reports/2026-08-30-phase-1-word-visual-preflight.md +0 -22
- package/docs/validation-reports/2026-08-30-phase-2-word-visual-preflight.md +0 -24
- package/docs/validation-reports/2026-08-30-phase-3-coverage.md +0 -73
- package/docs/validation-reports/2026-09-02-multilevel-bullets-visual-review.md +0 -82
- package/docs/validation-reports/2026-09-02-multimodal-visual-samples.md +0 -114
- package/docs/validation-reports/2026-09-02-visual-failures-preflight.md +0 -79
package/AGENTS.md
CHANGED
|
@@ -1,706 +1,91 @@
|
|
|
1
|
-
# AGENTS.md
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
```
|
|
1
|
+
# AGENTS.md — Launch Card
|
|
2
|
+
|
|
3
|
+
Use this file to route work on `@ansonlai/docx-redline-js`. Do not explore the
|
|
4
|
+
whole repository before acting, and never inspect `dist/`, a vendored CLI bundle,
|
|
5
|
+
or an installed plugin bundle to infer public behavior.
|
|
6
|
+
|
|
7
|
+
## Pick the route
|
|
8
|
+
|
|
9
|
+
| Task | Start here |
|
|
10
|
+
|---|---|
|
|
11
|
+
| Edit or review a complete `.docx` | [Agent Fast Start](docs/AGENT_FAST_START.md) and the `docx-redline` CLI |
|
|
12
|
+
| Build or update an agent skill/tool wrapper | [Skill Authoring Contract](docs/SKILL_AUTHORING.md), then [README wrapper example](README.md#example-agent-session-wrapper-development-only) |
|
|
13
|
+
| Change paragraph/range reconciliation | `index.js` → `engine/oxml-engine.js` → selected `engine/*-mode.js` |
|
|
14
|
+
| Change complete-document operations | `services/standalone-operation-runner.js` → `services/document-operation-*.js` |
|
|
15
|
+
| Change DOCX ZIP or CLI behavior | `node/index.js`, `node/docx-document.js`, `node/cli.js` |
|
|
16
|
+
| Choose or add tests | Closest `tests/*.mjs`, then [Testing Guide](docs/TESTING.md) |
|
|
17
|
+
| Understand ownership/dependencies | [Architecture](ARCHITECTURE.md) |
|
|
153
18
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
`FOREIGN_PARAGRAPH_MARK_DELETION`:
|
|
19
|
+
Open the full [Agent Knowledge Base](docs/AGENT_KNOWLEDGE_BASE.md) only for the
|
|
20
|
+
specific advanced operation, API, or recovery topic you need.
|
|
157
21
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
22
|
+
## Ordinary document edits
|
|
23
|
+
|
|
24
|
+
Use one focused extraction and one apply call. With a structured wrapper, use
|
|
25
|
+
its revision-bound target handles. For shell-only work, use a UTF-8 operations
|
|
26
|
+
file or serializer-backed stdin and the explicit agent profile:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
docx-redline extract contract.docx --search "termination" --around 3
|
|
30
|
+
node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --compact --output reviewed.docx
|
|
165
31
|
```
|
|
166
32
|
|
|
167
|
-
For
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
33
|
+
For every ordinary text operation, `modified` is the complete desired
|
|
34
|
+
accepted-view content. Copy inspected `exactText` verbatim and include
|
|
35
|
+
`paragraphId` or `fingerprint`. Independent strong targets are bound against the
|
|
36
|
+
batch-start document, so do not manually sort around structural edits.
|
|
37
|
+
Consolidate incompatible writes to the same source; use captures for intentional
|
|
38
|
+
created-content dependencies.
|
|
39
|
+
|
|
40
|
+
Require `completion: true`, `written: true`, a non-null output path, and no
|
|
41
|
+
per-operation errors. Follow `error.recovery.action` and `retryPlan`; never retry
|
|
42
|
+
unchanged failed arguments. Do not accept/reject another reviewer's work or
|
|
43
|
+
remove comments without explicit user authorization. The source is never
|
|
44
|
+
overwritten unless `--in-place` is explicit.
|
|
173
45
|
|
|
174
|
-
|
|
175
|
-
|
|
46
|
+
The agent profile preserves progressive execution and the ordinary revision
|
|
47
|
+
policy. Add `--atomic` or `--existing-revisions slice-cross-author` only when
|
|
48
|
+
that policy is intended, and confirm the resolved `effectiveOptions`.
|
|
176
49
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
50
|
+
Advanced restore, rejected-view insertion, list, table, formatting, comments,
|
|
51
|
+
revision policies, and failure examples live in the
|
|
52
|
+
[knowledge base](docs/AGENT_KNOWLEDGE_BASE.md#agent-document-workflow-cli) and
|
|
53
|
+
[operation schema](docs/schemas/document-operations.schema.json).
|
|
54
|
+
|
|
55
|
+
## Thin wrappers
|
|
56
|
+
|
|
57
|
+
Wrap the CLI for shell hosts or `openDocx` from
|
|
58
|
+
`@ansonlai/docx-redline-js/node` for byte-oriented Node hosts. A wrapper should
|
|
59
|
+
inspect, translate narrow ergonomic inputs into canonical operations, call the
|
|
60
|
+
facade once, and return its structured result. Do not reproduce ZIP handling,
|
|
61
|
+
targeting, revision allocation, comments, numbering, validation, or rollback.
|
|
62
|
+
|
|
63
|
+
The stateful wrapper in `examples/agent-session-wrapper.mjs` is a testable
|
|
64
|
+
development demonstration only. It is excluded from package files and exports.
|
|
65
|
+
Production harnesses own their transport and negotiate the minimum CLI
|
|
66
|
+
`contractVersion`/capabilities they use.
|
|
67
|
+
|
|
68
|
+
## Code map
|
|
69
|
+
|
|
70
|
+
```text
|
|
71
|
+
index.js host-independent public API
|
|
72
|
+
core/ OOXML primitives, text views, targeting, validation
|
|
73
|
+
pipeline/ ingestion, diffing, Markdown, lists, serialization
|
|
74
|
+
engine/ reconciliation modes and run-level mutation
|
|
75
|
+
orchestration/ route planning and structural conversion
|
|
76
|
+
services/ document operations, comments, receipts, artifacts
|
|
77
|
+
node/ Node-only ZIP and whole-DOCX facade/CLI
|
|
78
|
+
tests/*.mjs directly runnable suites
|
|
186
79
|
```
|
|
187
80
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
`targetRef` is an optional 1-based paragraph reference used to disambiguate
|
|
194
|
-
duplicate text. An operation-level `author` overrides the batch author; batch
|
|
195
|
-
results report both `authorUsed` per item and the aggregate `authorsUsed` list.
|
|
196
|
-
|
|
197
|
-
For safer targeting, `target` may be a descriptor:
|
|
198
|
-
|
|
199
|
-
```js
|
|
200
|
-
{
|
|
201
|
-
type: 'replace',
|
|
202
|
-
target: {
|
|
203
|
-
exactText: 'Repeated paragraph text',
|
|
204
|
-
paragraphId: '1A2B3C4D', // when present in the source OOXML
|
|
205
|
-
index: 12,
|
|
206
|
-
occurrence: 2,
|
|
207
|
-
inTable: false,
|
|
208
|
-
fingerprint: 'fnv1a32:...'
|
|
209
|
-
},
|
|
210
|
-
modified: 'Replacement text',
|
|
211
|
-
author: 'Editor'
|
|
212
|
-
}
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
Call `preflightOperations(documentXml, operations, author)` when you want a
|
|
216
|
-
read-only inspection of an agent-generated batch before applying it. Preflight is
|
|
217
|
-
read-only and strict by default: duplicate exact text returns `AMBIGUOUS_TARGET`,
|
|
218
|
-
approximate text is not selected, and the result reports candidate targets,
|
|
219
|
-
missing anchors, existing revisions, authors, required artifacts, and
|
|
220
|
-
same-paragraph conflicts. For direct execution, `applyOperationsToDocumentXml` is
|
|
221
|
-
already transactional and atomic by default. When permissive resolution
|
|
222
|
-
encounters duplicate candidate paragraphs, it emits an
|
|
223
|
-
`AMBIGUOUS_TARGET_HEURISTIC_USED` warning; migrate to `{ strictTargets: true }`
|
|
224
|
-
with strict descriptors (`paragraphId`, `index`, `occurrence`, or `fingerprint`)
|
|
225
|
-
before v1.0.0.
|
|
226
|
-
|
|
227
|
-
Whole-paragraph deletions targeting paragraphs with existing comments fail with
|
|
228
|
-
`COMMENTED_CONTENT_DELETE`. Resolve or remove the comments first.
|
|
229
|
-
|
|
230
|
-
Use `result.documentXml` from these APIs when replacing full `word/document.xml`.
|
|
231
|
-
For mixed batches, prefer `applyOperationsToDocumentXml(...)`; it applies comments
|
|
232
|
-
before replacements so earlier edits cannot invalidate their anchors.
|
|
233
|
-
|
|
234
|
-
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).
|
|
235
|
-
|
|
236
|
-
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`).
|
|
237
|
-
|
|
238
|
-
Internally, a batch uses one live document DOM and one revision allocator, then
|
|
239
|
-
serializes the full document once. Every operation has a DOM/allocator savepoint;
|
|
240
|
-
do not remove this isolation merely for speed. Redline accuracy, accepted and
|
|
241
|
-
rejected text, and exact rollback take precedence over throughput.
|
|
242
|
-
|
|
243
|
-
Every operation produces a commit-aware `receipt` (and batch-level `receipts`)
|
|
244
|
-
enumerating exact allocated `revisionItems`, `commentIds`, `numberingIds`,
|
|
245
|
-
`relationshipIds`, `affectedTargets`, and `warnings`. The output reconciliation
|
|
246
|
-
oracle (`reconcileReceiptsAgainstOutput`) validates that all reported durable IDs
|
|
247
|
-
are present in the serialized output; any discrepancy triggers rollback and fails closed.
|
|
248
|
-
|
|
249
|
-
Always inspect `status` and `error`, not only `hasChanges`. A failed transform
|
|
250
|
-
can return `{ hasChanges: false, status: 'error', error: ... }`. Missing or
|
|
251
|
-
ambiguous comment anchors are structured errors and roll back atomic batches;
|
|
252
|
-
`no_change` is reserved for genuine no-ops. Continue to inspect warnings for
|
|
253
|
-
non-fatal diagnostics.
|
|
254
|
-
|
|
255
|
-
### Detect existing tracked changes
|
|
256
|
-
|
|
257
|
-
```js
|
|
258
|
-
import { containsTrackedChanges } from '@ansonlai/docx-redline-js';
|
|
259
|
-
const hasTrackedChanges = containsTrackedChanges(xmlDoc);
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
### Inspect document parts before editing
|
|
263
|
-
|
|
264
|
-
```js
|
|
265
|
-
import { inspectDocumentParts } from '@ansonlai/docx-redline-js';
|
|
266
|
-
const inspection = inspectDocumentParts({ documentXml, commentsXml, numberingXml });
|
|
267
|
-
```
|
|
268
|
-
|
|
269
|
-
Reuse `exactText` plus `paragraphId` or `fingerprint` in an operation. Computed
|
|
270
|
-
list labels and excerpts are for display, not replacements for exact targets.
|
|
271
|
-
|
|
272
|
-
### Safely edit a complete DOCX in Node
|
|
273
|
-
|
|
274
|
-
```js
|
|
275
|
-
import { openDocx } from '@ansonlai/docx-redline-js/node';
|
|
276
|
-
const document = openDocx(inputBuffer);
|
|
277
|
-
const result = await document.applyOperations(operations, {
|
|
278
|
-
author: 'Agent', atomic: true, validate: true
|
|
279
|
-
});
|
|
280
|
-
if (!result.written) throw new Error(result.error?.message || 'No output written');
|
|
281
|
-
const outputBuffer = result.toBuffer();
|
|
282
|
-
```
|
|
283
|
-
|
|
284
|
-
This facade defaults to strict targets, allocates package-safe comment IDs,
|
|
285
|
-
merges numbering, updates relationships/content types, and rolls back to the
|
|
286
|
-
original buffer when an atomic transaction fails.
|
|
287
|
-
|
|
288
|
-
### Agent Document Workflow (CLI)
|
|
289
|
-
|
|
290
|
-
Use the `docx-redline` CLI for complete `.docx` files. It emits JSON on stdout,
|
|
291
|
-
keeps exact text intact, and never overwrites the source unless `--in-place` is
|
|
292
|
-
explicitly supplied.
|
|
293
|
-
|
|
294
|
-
#### Standard Workflow (Fast & Direct)
|
|
295
|
-
|
|
296
|
-
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:
|
|
297
|
-
|
|
298
|
-
```bash
|
|
299
|
-
# 1. Inline one-liner edit (fastest for 1–2 edits; no JSON file needed)
|
|
300
|
-
docx-redline apply contract.docx --target "Original clause" --modified "New clause" --output reviewed.docx
|
|
301
|
-
|
|
302
|
-
# 2. Direct edit without tracked changes (clean text, no revision clutter)
|
|
303
|
-
docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
|
|
304
|
-
|
|
305
|
-
# 3. Cross-author edit inside another reviewer's pending insertion
|
|
306
|
-
docx-redline apply contract.docx --target "Pending clause text" --modified "Updated clause text" --existing-revisions slice-cross-author --output reviewed.docx
|
|
307
|
-
|
|
308
|
-
# 4. Batch operations with ops.json
|
|
309
|
-
docx-redline apply contract.docx --operations operations.json --output reviewed.docx
|
|
310
|
-
```
|
|
311
|
-
|
|
312
|
-
Key CLI defaults and behaviors:
|
|
313
|
-
- **Author**: Automatically defaults to `'AI Redliner'` (overridable via `--author` or `DOCX_REDLINE_AUTHOR` environment variable).
|
|
314
|
-
- **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.
|
|
315
|
-
- **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.
|
|
316
|
-
- **Tracked changes**: Defaults to `generateRedlines: true`. When clean direct text is needed, pass `--no-redlines`.
|
|
317
|
-
- **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`.
|
|
318
|
-
- **Compact mutation JSON**: `apply`, `accept`, `reject`, and `delete-comments` omit document/package XML and full validation arrays. `validation.originalIssues` and `validation.generatedIssues` are code/count summaries; run `validate` for full issue records.
|
|
319
|
-
- Check `completion: true`, `written: true`, and a non-null `outputPath` on stdout. `completion` is derived from the write result, top-level status, and every operation status, so failed, partial, and unwritten work cannot appear complete. If an error occurs, inspect `error.code` or `results[i].error.code` (e.g. `TARGET_NOT_FOUND`, `ANCHOR_NOT_FOUND`) before correcting the cause and re-applying.
|
|
320
|
-
|
|
321
|
-
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.
|
|
322
|
-
|
|
323
|
-
#### High-Assurance / Staged Verification Workflow (Optional)
|
|
324
|
-
|
|
325
|
-
This is an opt-in, higher-latency path for cases like large automated batch
|
|
326
|
-
migrations or workflows where the user specifically requests a non-mutating dry run
|
|
327
|
-
and an independent baseline audit report. **Never switch into it on your own initiative**
|
|
328
|
-
(not even for "high-stakes" contracts); unless the user explicitly requests it, stick with the
|
|
329
|
-
Standard workflow above. Use the extended verification cycle:
|
|
330
|
-
|
|
331
|
-
```bash
|
|
332
|
-
docx-redline inspect contract.docx --non-empty
|
|
333
|
-
docx-redline extract contract.docx --range 10:30 > paragraphs.json
|
|
334
|
-
docx-redline preflight contract.docx --operations operations.json --author "Editor"
|
|
335
|
-
docx-redline apply contract.docx --operations operations.json --author "Editor" --output reviewed.docx
|
|
336
|
-
docx-redline validate reviewed.docx --baseline contract.docx
|
|
337
|
-
```
|
|
338
|
-
|
|
339
|
-
Copy `exactText`, `paragraphId`, and `fingerprint` from `extract` into operation
|
|
340
|
-
targets. For most unique clauses, `"target": "exact paragraph text"` is
|
|
341
|
-
sufficient; use discriminators (`paragraphId`, `fingerprint`, `index`, or
|
|
342
|
-
`occurrence`) when duplicate paragraph text appears in the document. Never
|
|
343
|
-
normalize or reconstruct `exactText`. Operation files follow
|
|
344
|
-
[`docs/schemas/document-operations.schema.json`](docs/schemas/document-operations.schema.json).
|
|
345
|
-
|
|
346
|
-
#### Commands
|
|
347
|
-
|
|
348
|
-
- `inspect` returns the structured inventory, comments, authors, and counts.
|
|
349
|
-
- `extract` returns a compact target inventory with exact text.
|
|
350
|
-
- `preflight` checks targets, anchors, revisions, conflicts, authors, and needed artifacts without mutation (read-only).
|
|
351
|
-
- `apply` applies an operation file transactionally with automatic rollback and internal markup validation.
|
|
352
|
-
- `accept` and `reject` resolve revisions selected by `--author` or `--all-authors`.
|
|
353
|
-
- `delete-comments` removes matching definitions and document anchors together.
|
|
354
|
-
- A whole-paragraph delete stops with `COMMENTED_CONTENT_DELETE` when the
|
|
355
|
-
paragraph has an existing comment. Surface the returned reviewer and comment
|
|
356
|
-
text for human follow-up; do not silently convert this into comment removal.
|
|
357
|
-
- `validate` audits revision markup and DOCX package wiring, optionally comparing against a `--baseline`.
|
|
358
|
-
|
|
359
|
-
Paragraph indexes are 1-based. Inspection filters are `--index 12`,
|
|
360
|
-
`--range 10:30`, `--indexes 2,5,8`, `--search text`, `--revised`, `--table`,
|
|
361
|
-
`--body`, `--non-empty`, and `--view accepted|rejected|current`. A malformed
|
|
362
|
-
filter or unknown option is an error rather than an unfiltered fallback.
|
|
363
|
-
|
|
364
|
-
Mutating commands require `--author`, authors on every operation, or
|
|
365
|
-
`--all-authors` where applicable. Without `--output`, a sibling such as
|
|
366
|
-
`contract.redlined.docx` is chosen. Existing outputs are refused unless
|
|
367
|
-
`--force` is present. `--in-place` is the only way to overwrite the input.
|
|
368
|
-
|
|
369
|
-
Treat a nonzero exit code or JSON `status: "error"` as failure. A failed atomic
|
|
370
|
-
operation reports `written: false` and does not write an output file.
|
|
371
|
-
Missing or repeated comment anchors are errors rather than no-ops. Explicit
|
|
372
|
-
anchors match exact text first and then a unique ordinary-space/NBSP equivalent;
|
|
373
|
-
omit `textToComment` to comment the entire resolved paragraph.
|
|
374
|
-
|
|
375
|
-
To reply inside an existing Word comment thread, use the comment ID returned by
|
|
376
|
-
`inspect` and do not supply a paragraph target:
|
|
377
|
-
|
|
378
|
-
```json
|
|
379
|
-
{ "type": "comment_reply", "parentCommentId": "8", "commentContent": "Agreed; updated.", "author": "Editor" }
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
Replies are represented in `word/commentsExtended.xml` and deliberately add no
|
|
383
|
-
new `commentRangeStart`, `commentRangeEnd`, or `commentReference` to the body.
|
|
384
|
-
|
|
385
|
-
#### Legacy skill wrapper migration
|
|
386
|
-
|
|
387
|
-
Older skills that invoke `scripts/extract_text.mjs` and
|
|
388
|
-
`scripts/apply_changes.mjs` should use the compatibility entrypoints published
|
|
389
|
-
with this package rather than carrying copied targeting or ZIP logic. The
|
|
390
|
-
legacy positional apply form remains supported:
|
|
391
|
-
|
|
392
|
-
```bash
|
|
393
|
-
node scripts/apply_changes.mjs input.docx changes.json output.docx --author "Editor"
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
Operation files may contain an array, an `operations` array, or a legacy
|
|
397
|
-
`changes` array. The wrapper delegates to the same strict, atomic, validated
|
|
398
|
-
CLI described above. If `--author` and operation authors are absent, its
|
|
399
|
-
compatibility fallback is `DOCX_REDLINE_AUTHOR` and then `Agent`. Consumers
|
|
400
|
-
must use the JSON status and process exit code; failed atomic work has
|
|
401
|
-
`written: false`, `outputPath: null`, and does not modify the output path.
|
|
402
|
-
|
|
403
|
-
#### Safe Operations File Creation (JSON vs. Shell Heredocs)
|
|
404
|
-
|
|
405
|
-
When composing batch operations files (`operations.json`):
|
|
406
|
-
|
|
407
|
-
- **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`).
|
|
408
|
-
- **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.
|
|
409
|
-
|
|
410
|
-
#### Walking Progressive Batch Results (Status & Partial Execution)
|
|
411
|
-
|
|
412
|
-
In default progressive mode (`atomic: false`), operations execute independently: valid operations commit to the document while failing operations report errors without aborting the batch:
|
|
413
|
-
|
|
414
|
-
- **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.
|
|
415
|
-
- **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.
|
|
416
|
-
- **`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.
|
|
417
|
-
|
|
418
|
-
#### Human-Readable References vs. Internal Machine Handles
|
|
419
|
-
|
|
420
|
-
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:
|
|
421
|
-
|
|
422
|
-
- **Never surface `P11`, `P42`, or bare paragraph numbers** in user-facing prose, comments, redline summaries, or negotiation notes.
|
|
423
|
-
- Instead, cite locations using the human-readable fields provided by `inspect` / `extract`:
|
|
424
|
-
- **`provision`**: Lead with section/clause numbers when present (e.g., `§14.1 Entire Agreement`).
|
|
425
|
-
- **`nearestHeading` + ordinal offset**: When `provision` is absent, describe position relative to the nearest heading (e.g., `under "Limitation of Liability", 2nd paragraph`).
|
|
426
|
-
- **Structural context**: For unnumbered clauses prior to the first heading, use plain language (e.g., `opening recital, before Section 1`).
|
|
427
|
-
- **`humanReference`**: Use the pre-joined citation string provided directly on inspected paragraph objects.
|
|
428
|
-
|
|
429
|
-
#### Actionable Error Recovery Matrix
|
|
430
|
-
|
|
431
|
-
When the CLI or runner returns an error code, follow these specific recovery actions:
|
|
432
|
-
|
|
433
|
-
| Error Code | Meaning | Actionable Recovery |
|
|
434
|
-
|---|---|---|
|
|
435
|
-
| `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`). |
|
|
436
|
-
| `AMBIGUOUS_TARGET` | Multiple paragraphs match identical text. | Disambiguate by supplying `paragraphId`, `fingerprint`, `occurrence`, or `index` in the target descriptor. |
|
|
437
|
-
| `ANCHOR_NOT_FOUND` / `AMBIGUOUS_ANCHOR` | A comment or rejected-view insertion anchor was not uniquely matched. | For comments, narrow `textToComment` or omit it to anchor the whole paragraph. For rejected-view insertion, copy exact rejected text and provide `anchor.occurrence`. |
|
|
438
|
-
| `OVERLAPPING_TEXT_EDITS` | Multiple operations target the same paragraph concurrently. | Consolidate all changes to the same paragraph into a single `redline` or `replace` operation. |
|
|
439
|
-
| `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. |
|
|
440
|
-
| `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. |
|
|
441
|
-
| `FOREIGN_PARAGRAPH_MARK_DELETION` | A normal edit attempted to write into a paragraph wholly deleted by another reviewer. | Use an explicit `restore` operation if the user intends to counterpropose that paragraph; otherwise leave the deletion unresolved. |
|
|
442
|
-
| `RESTORATION_STATE_REQUIRED` / `RESTORATION_COUNT_MISMATCH` | A `restore` target is not a wholly foreign-deleted paragraph, or its replacement count does not match the paragraph range. | Re-inspect the document and target the deleted paragraph by stable descriptor; provide exactly one replacement string per source paragraph. |
|
|
443
|
-
| `REJECTED_INSERTION_STATE_REQUIRED` / `UNSAFE_REVISION_BOUNDARY` | An explicit rejected-view insertion did not resolve to supported plain run text inside a wholly foreign-deleted paragraph. | Do not fall back to a generic edit. Narrow the exact anchor/offset, or handle comments, bookmarks, fields, hyperlinks, moves, or other structural boundaries manually. |
|
|
444
|
-
| `GENERATED_OOXML_INVALID` | The operation introduced a new validation error relative to its baseline. | Treat the operation as unapplied and inspect `generatedIssues`; correct the generating operation or builder rather than repairing or accepting the source document's unrelated baseline defects. |
|
|
445
|
-
| `UNSAFE_DELETED_TABLE_ROW` / `UNSUPPORTED_MOVE_REVISION` / `SECTION_BREAK_PARAGRAPH` / `UNSAFE_PARAGRAPH_PLACEMENT` | Paragraph restoration cannot preserve the source structural boundary safely. | Do not retry as an ordinary redline. Resolve the row/move/section/placement condition manually or narrow the restoration to a safe paragraph. |
|
|
446
|
-
| `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. |
|
|
447
|
-
| `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. |
|
|
448
|
-
| `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. |
|
|
449
|
-
|
|
450
|
-
**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.
|
|
451
|
-
|
|
452
|
-
#### Document Scope & Boundary Invariants
|
|
453
|
-
|
|
454
|
-
The `docx-redline` engine and CLI operate specifically on the **main document body**:
|
|
455
|
-
|
|
456
|
-
- **Supported Content**: Body paragraphs, numbered/bulleted lists, tables and table cells, comments, and comment replies.
|
|
457
|
-
- **Unsupported Content**: Headers, footers, footnotes, endnotes, floating text boxes, shape drawings, watermarks, and embedded macros.
|
|
458
|
-
- 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.
|
|
459
|
-
|
|
460
|
-
### Convert paragraph text into a Word list
|
|
461
|
-
|
|
462
|
-
```js
|
|
463
|
-
const result = await applyRedlineToOxml(oxml, 'Item text', '1. Item text', {
|
|
464
|
-
generateRedlines: true
|
|
465
|
-
});
|
|
466
|
-
```
|
|
467
|
-
|
|
468
|
-
### Insert a large mixed-content block safely
|
|
469
|
-
|
|
470
|
-
Do not send a long attachment containing literal pipe rows, headings, lists,
|
|
471
|
-
and paragraphs as an unchecked replacement. Plan it first:
|
|
472
|
-
|
|
473
|
-
```js
|
|
474
|
-
import { planStructuredReplacement } from '@ansonlai/docx-redline-js';
|
|
475
|
-
|
|
476
|
-
const plan = planStructuredReplacement(targetDescriptor, markdown, {
|
|
477
|
-
author: 'Agent'
|
|
478
|
-
});
|
|
479
|
-
if (!plan.valid || !plan.operation) {
|
|
480
|
-
throw new Error(plan.issues.map(issue => issue.message).join(' '));
|
|
481
|
-
}
|
|
482
|
-
const result = await document.applyOperations([plan.operation], {
|
|
483
|
-
author: 'Agent', atomic: true, validate: true
|
|
484
|
-
});
|
|
485
|
-
```
|
|
486
|
-
|
|
487
|
-
Use blank lines between paragraphs, `#`/`##` for headings, normal Markdown
|
|
488
|
-
markers for lists, and a separator row immediately after every table header:
|
|
489
|
-
|
|
490
|
-
```markdown
|
|
491
|
-
| Agency | Contact |
|
|
492
|
-
| --- | --- |
|
|
493
|
-
| BCHD | Dr. Jenkins |
|
|
494
|
-
```
|
|
495
|
-
|
|
496
|
-
The planner returns typed `blocks`, counts, normalized Markdown, and structured
|
|
497
|
-
issues. `TABLE_SEPARATOR_REQUIRED` is an error: never remove `structuredContent`
|
|
498
|
-
or retry the same content as plain text merely to make the operation pass. Keep
|
|
499
|
-
the result as one atomic replacement operation so the first inserted block does
|
|
500
|
-
not invalidate the anchor for later blocks. After applying, require real
|
|
501
|
-
`w:tbl`, positive list `w:numId` values, valid redline OOXML, and independent
|
|
502
|
-
Accept/Reject checks.
|
|
503
|
-
|
|
504
|
-
### Reconcile a table
|
|
505
|
-
|
|
506
|
-
```js
|
|
507
|
-
import { reconcileMarkdownTableOoxml } from '@ansonlai/docx-redline-js';
|
|
508
|
-
const result = await reconcileMarkdownTableOoxml(tableOoxml, originalText, markdownTable);
|
|
509
|
-
```
|
|
510
|
-
|
|
511
|
-
## Module Map
|
|
512
|
-
|
|
513
|
-
```
|
|
514
|
-
index.js
|
|
515
|
-
adapters/
|
|
516
|
-
config.js
|
|
517
|
-
xml-adapter.js
|
|
518
|
-
logger.js
|
|
519
|
-
core/
|
|
520
|
-
types.js
|
|
521
|
-
paragraph-text.js
|
|
522
|
-
word-xml.js
|
|
523
|
-
paragraph-targeting.js
|
|
524
|
-
list-targeting.js
|
|
525
|
-
table-targeting.js
|
|
526
|
-
engine/
|
|
527
|
-
oxml-engine.js
|
|
528
|
-
surgical-mode.js
|
|
529
|
-
surgical-run-splitting.js
|
|
530
|
-
surgical-diff-application.js
|
|
531
|
-
surgical-spans.js
|
|
532
|
-
reconstruction-mode.js
|
|
533
|
-
reconstruction-writer.js
|
|
534
|
-
format-application.js
|
|
535
|
-
formatting-removal.js
|
|
536
|
-
run-builders.js
|
|
537
|
-
table-mode.js
|
|
538
|
-
pipeline/
|
|
539
|
-
pipeline.js
|
|
540
|
-
ingestion.js
|
|
541
|
-
ingestion-export.js
|
|
542
|
-
diff-engine.js
|
|
543
|
-
markdown-processor.js
|
|
544
|
-
serialization.js
|
|
545
|
-
list-generation.js
|
|
546
|
-
services/
|
|
547
|
-
document-operation-session.js
|
|
548
|
-
document-operation-applier.js
|
|
549
|
-
document-operation-mutations.js
|
|
550
|
-
batch-operation-orchestrator.js
|
|
551
|
-
operation-heuristics.js
|
|
552
|
-
standalone-operation-runner.js
|
|
553
|
-
standalone-operation-runner.d.ts
|
|
554
|
-
document-operation-contract.js
|
|
555
|
-
operation-preflight.js
|
|
556
|
-
standalone-docx-plumbing.js
|
|
557
|
-
numbering-helpers.js
|
|
558
|
-
comment-engine.js
|
|
559
|
-
revision-comment-management.js
|
|
560
|
-
table-reconciliation.js
|
|
561
|
-
package-builder.js
|
|
562
|
-
document-inspection.js
|
|
563
|
-
node/
|
|
564
|
-
docx-document.js
|
|
565
|
-
zip-archive.js
|
|
566
|
-
orchestration/
|
|
567
|
-
route-plan.js
|
|
568
|
-
list-markdown.js
|
|
569
|
-
list-structural-fallback.js
|
|
570
|
-
```
|
|
571
|
-
|
|
572
|
-
## Common Patterns
|
|
573
|
-
|
|
574
|
-
### Options and Defaults Reference
|
|
575
|
-
|
|
576
|
-
| Option | Type | Default | Description |
|
|
577
|
-
|--------|------|---------|-------------|
|
|
578
|
-
| `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. |
|
|
579
|
-
| `author` | `string` | `'AI Redliner'` | Reviewer/author name stamped on generated tracked changes and comments. Overridable via `DOCX_REDLINE_AUTHOR` environment variable. |
|
|
580
|
-
| `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. |
|
|
581
|
-
| `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. |
|
|
582
|
-
| `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. |
|
|
583
|
-
| `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. |
|
|
584
|
-
| `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. |
|
|
585
|
-
| `removeFormatting` | `boolean` | `false` | When `true` and the text is unchanged with no Markdown hints, strips existing bold/italic/underline/strikethrough formatting. |
|
|
586
|
-
| `sanitizeInput` | `boolean` | `false` | Opt-in removal of standalone leading assistant-preface lines. Literal dollar signs and `\n` sequences are always preserved. |
|
|
587
|
-
|
|
588
|
-
### Options shape
|
|
589
|
-
|
|
590
|
-
```js
|
|
591
|
-
{
|
|
592
|
-
generateRedlines: true,
|
|
593
|
-
author: 'AI Redliner',
|
|
594
|
-
atomic: false,
|
|
595
|
-
structuredContent: true,
|
|
596
|
-
pairReplacements: true,
|
|
597
|
-
existingRevisions: 'merge-same-author',
|
|
598
|
-
removeFormatting: false,
|
|
599
|
-
sanitizeInput: false
|
|
600
|
-
}
|
|
601
|
-
```
|
|
602
|
-
|
|
603
|
-
### Typical return shape
|
|
604
|
-
|
|
605
|
-
```js
|
|
606
|
-
{
|
|
607
|
-
oxml: string,
|
|
608
|
-
hasChanges: boolean,
|
|
609
|
-
status?: 'ok' | 'no-op' | 'error',
|
|
610
|
-
error?: { code: string, message: string },
|
|
611
|
-
warnings?: string[],
|
|
612
|
-
numberingXml?: string,
|
|
613
|
-
useNativeApi?: boolean
|
|
614
|
-
}
|
|
615
|
-
```
|
|
616
|
-
|
|
617
|
-
Known error codes include `PARSE_ERROR`, `TARGET_NOT_FOUND`, `PARTIAL_TARGET`,
|
|
618
|
-
`EXISTING_REVISIONS`, `COMMENTED_CONTENT_MERGE`, `UNSAFE_REVISION_NESTING`, `UNSUPPORTED_REVISION_VIEW_MUTATION`,
|
|
619
|
-
`UNSAFE_PARAGRAPH_BOUNDARY`, `DIFF_TOKEN_LIMIT`, and `BATCH_OPERATION_FAILED`.
|
|
620
|
-
|
|
621
|
-
For ingestion that must distinguish an empty document from malformed OOXML,
|
|
622
|
-
use `ingestWordOoxmlToPlainTextResult` or
|
|
623
|
-
`ingestWordOoxmlToMarkdownResult`. The legacy ingestion helpers intentionally
|
|
624
|
-
retain their string-only return type and return `''` for parse failures.
|
|
625
|
-
|
|
626
|
-
### Target text versus replacement text
|
|
627
|
-
|
|
628
|
-
Target resolution may normalize surrounding or repeated whitespace while
|
|
629
|
-
matching a paragraph. Replacement text is not normalized: tabs, line breaks,
|
|
630
|
-
non-breaking spaces, repeated spaces, and leading/trailing whitespace become
|
|
631
|
-
part of the requested edit. When editing extracted document text, copy the
|
|
632
|
-
exact paragraph text and modify it in place rather than round-tripping it
|
|
633
|
-
through a formatter that may change whitespace.
|
|
81
|
+
Keep shared modules from importing `index.js`; keep host-independent code from
|
|
82
|
+
importing `node/`. Use `rg` to follow only the symbol being changed. Preserve
|
|
83
|
+
unrelated worktree changes and edit source files, never generated `dist/` files.
|
|
84
|
+
|
|
85
|
+
## Verification
|
|
634
86
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
source, `resolvedTarget.targetTextMatch` reports `space_equivalent`, escaped
|
|
641
|
-
source/request excerpts, and differing code points. An NBSP-to-space request is
|
|
642
|
-
tracked as a replacement; it must not retain the NBSP and append another space.
|
|
643
|
-
The CLI keeps these bounded diagnostics but removes resolved clause text.
|
|
644
|
-
|
|
645
|
-
For ordinary insertions and deletions, target the visible accepted view:
|
|
646
|
-
inserted `w:t` text is visible and deleted `w:delText` is not. Move revisions
|
|
647
|
-
and other complex structures require additional care until targeting and
|
|
648
|
-
ingestion share one canonical text extractor. Prefer a `targetRef` plus the full
|
|
649
|
-
paragraph text when duplicate paragraphs are possible. Current text-only
|
|
650
|
-
matching can select the first matching paragraph, so callers that cannot
|
|
651
|
-
disambiguate safely should stop instead of guessing.
|
|
652
|
-
|
|
653
|
-
### OOXML wrapping for Word insertOoxml scenarios
|
|
654
|
-
|
|
655
|
-
```js
|
|
656
|
-
import { wrapInDocumentFragment } from '@ansonlai/docx-redline-js';
|
|
657
|
-
const wrapped = wrapInDocumentFragment(rawOoxml, { includeNumbering: true, numberingXml });
|
|
658
|
-
```
|
|
659
|
-
|
|
660
|
-
### Output shape guardrail (important for packaging)
|
|
661
|
-
|
|
662
|
-
When consuming `result.oxml`, do not assume the payload is always safe to write
|
|
663
|
-
directly into `word/document.xml`.
|
|
664
|
-
|
|
665
|
-
- Paragraph/range/table APIs can return a fragment, `<w:document>`, or package payload (`<pkg:package>`).
|
|
666
|
-
- `applyOperationToDocumentXml(...).documentXml` is the document-safe path when you need a full `word/document.xml` replacement.
|
|
667
|
-
- Use `extractReplacementNodesFromOoxml(payload)` to normalize unknown payloads.
|
|
668
|
-
- If `sourceType === 'package'` or the payload starts with `<pkg:package`, do not write it into `word/document.xml` as-is.
|
|
669
|
-
|
|
670
|
-
## Gotchas
|
|
671
|
-
|
|
672
|
-
1. Call `configureXmlProvider` first in Node.js.
|
|
673
|
-
2. `applyRedlineToOxml` is async.
|
|
674
|
-
3. Paragraph APIs expect paragraph-level OOXML, not full `word/document.xml` in all cases.
|
|
675
|
-
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.
|
|
676
|
-
That replacement behavior is deprecated and will become an error in the next major version.
|
|
677
|
-
5. `useNativeApi: true` means standalone mode cannot fully handle that operation path.
|
|
678
|
-
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.
|
|
679
|
-
7. If output begins with `<pkg:package`, treat it as package-level OOXML and normalize it before writing anything back to `word/document.xml`.
|
|
680
|
-
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.
|
|
681
|
-
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.
|
|
682
|
-
10. Hyperlinks, bookmarks, comment markers, tabs/breaks, and footnote/endnote references are structural OOXML and should survive adjacent redline edits.
|
|
683
|
-
11. Internally, create Word elements through `createWordElement` and tracked-change metadata through `createRevisionMetadata`.
|
|
684
|
-
12. Revision IDs are document-scoped in public operation paths. Thread the
|
|
685
|
-
internal allocator through new string-serialization paths; generated
|
|
686
|
-
`w:id` values are not stable across documents.
|
|
687
|
-
13. Splitting or cloning a run can duplicate nested `w:rPrChange` metadata.
|
|
688
|
-
Preserve the original ID on at most one resulting run and allocate fresh
|
|
689
|
-
IDs for every additional clone through the document-scoped allocator.
|
|
690
|
-
14. Run `validateRedlineOoxml` on generated markup before packaging it, then
|
|
691
|
-
run `validateDocxPackage` after merging comments and numbering artifacts.
|
|
692
|
-
|
|
693
|
-
## Validation Commands
|
|
694
|
-
|
|
695
|
-
```bash
|
|
696
|
-
npm test
|
|
697
|
-
npm run test:isolation
|
|
698
|
-
npm run check:types
|
|
699
|
-
node scripts/export-validation-fixtures.mjs
|
|
700
|
-
```
|
|
701
|
-
|
|
702
|
-
Optional Windows/Word smoke test for a completed `.docx`:
|
|
703
|
-
|
|
704
|
-
```bash
|
|
705
|
-
npm run smoke:word -- path/to/file.docx
|
|
706
|
-
```
|
|
87
|
+
Run the closest test first: `node tests/<focused-suite>.mjs`. Use `npm test` for
|
|
88
|
+
cross-subsystem or release handoff, plus `npm run check:types` and
|
|
89
|
+
`npm run test:isolation` when boundaries or declarations change. Word COM,
|
|
90
|
+
visual, corpus, coverage, and fixture-generation lanes are separate; select them
|
|
91
|
+
from the [Testing Guide](docs/TESTING.md).
|