@ansonlai/docx-redline-js 0.6.0 → 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.
@@ -20,23 +20,23 @@ It is a development sample, not a package API.
20
20
  1. Extract only the relevant clause or range:
21
21
 
22
22
  ```bash
23
- docx-redline extract contract.docx --search "termination"
23
+ docx-redline extract contract.docx --search "termination" --around 3
24
24
  ```
25
25
 
26
- 2. Copy `exactText` with `paragraphId` or `fingerprint`. Serialize the final
27
- operation array directly to stdin, then apply once:
26
+ Search is case-insensitive. Direct hits are capped; follow `selection.nextAfter` with `--after`, and cite `humanReference`, not `P42`.
27
+
28
+ 2. Copy `exactText` with `paragraphId` or `fingerprint`. Use a UTF-8 operations
29
+ file or serializer-backed stdin, then apply once:
28
30
 
29
31
  ```bash
30
- node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --output reviewed.docx
32
+ node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --compact --output reviewed.docx
31
33
  ```
32
34
 
33
35
  `emit-operations.mjs` should use `JSON.stringify`; do not interpolate legal
34
36
  text through shell quoting. `modified` is the complete desired accepted-view
35
37
  paragraph, not only the inserted words.
36
38
 
37
- The `agent` profile is explicit and reproducible. It uses atomic rollback,
38
- strict targets, validation, tracked changes, `merge-same-author`, and nonzero
39
- exit codes for incomplete work. The result reports `effectiveOptions`.
39
+ The `agent` profile preserves progressive execution and the ordinary revision policy while making incomplete work exit nonzero. Add `--atomic` deliberately; check `effectiveOptions`. Run `docx-redline apply --help` for redline, comment, and rejected-view restore shapes.
40
40
 
41
41
  ## Batch and result rules
42
42
 
@@ -482,8 +482,9 @@ Use this for everything by default. `apply` is fast, progressive, and self-valid
482
482
 
483
483
  The short route for a document-editing request is:
484
484
 
485
- 1. Run one focused `extract` for the clauses or range being edited and copy
486
- `exactText` plus `paragraphId` or `fingerprint`.
485
+ 1. Run one focused `extract` for the clauses or range being edited. Search is a
486
+ case-insensitive substring match; add `--around 3` when surrounding drafting
487
+ context is needed. Copy `exactText` plus `paragraphId` or `fingerprint`.
487
488
  2. Build the final operations from the operation table above. Use one operation
488
489
  per target paragraph, and consolidate multiple changes to that paragraph.
489
490
  3. Run `apply` once per stable batch. Strong inspected targets are bound against
@@ -501,21 +502,24 @@ Do not probe operation behavior with disposable apply commands or read a vendor
501
502
  bundle before this route. If `apply` returns an error, use the recovery matrix
502
503
  below and make one cause-specific correction.
503
504
 
504
- ```bash
505
- # 1. Inline one-liner edit (fastest for 1–2 edits; no JSON file needed)
506
- docx-redline apply contract.docx --target "Original clause" --modified "New clause" --output reviewed.docx
507
-
508
- # 2. Direct edit without tracked changes (clean text, no revision clutter)
505
+ ```bash
506
+ # 1. Focused contextual discovery
507
+ docx-redline extract contract.docx --search "termination" --around 3
508
+
509
+ # 2. Inline one-liner edit (fastest for 1–2 edits; no JSON file needed)
510
+ docx-redline apply contract.docx --target "Original clause" --modified "New clause" --output reviewed.docx
511
+
512
+ # 3. Direct edit without tracked changes (clean text, no revision clutter)
509
513
  docx-redline apply contract.docx --target "Typo fix" --modified "Fixed typo" --no-redlines --output clean.docx
510
514
 
511
- # 3. Cross-author edit inside another reviewer's pending insertion
515
+ # 4. Cross-author edit inside another reviewer's pending insertion
512
516
  docx-redline apply contract.docx --target "Pending clause text" --modified "Updated clause text" --existing-revisions slice-cross-author --output reviewed.docx
513
517
 
514
- # 4. Batch operations with ops.json
518
+ # 5. Batch operations with ops.json
515
519
  docx-redline apply contract.docx --operations operations.json --output reviewed.docx
516
520
 
517
- # 5. Shell-agent batch without an operations file
518
- node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --output reviewed.docx
521
+ # 6. Serializer-backed stdin with compact stdout
522
+ node emit-operations.mjs | docx-redline apply contract.docx --operations - --profile agent --compact --output reviewed.docx
519
523
  ```
520
524
 
521
525
  Key CLI defaults and behaviors:
@@ -525,9 +529,9 @@ Key CLI defaults and behaviors:
525
529
  - **Tracked changes**: Defaults to `generateRedlines: true`. When clean direct text is needed, pass `--no-redlines`.
526
530
  - **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`.
527
531
  - **Complete-success exit (optional)**: Pass `--require-complete` when `partial` must exit nonzero (`3`). Errors exit `2`; the legacy zero exit for partial results remains when the flag is omitted.
528
- - **Agent profile**: `--profile agent` explicitly defaults `atomic` and complete-success behavior to true and reports `effectiveOptions`. Call flags override the profile. It does not enable authorization-sensitive revision normalization.
529
- - **Stdin operations**: `--operations -` accepts the same JSON array or `{ operations, expectedRevision }` envelope as a file. Supply UTF-8 JSON through a serializer/structured process API; do not interpolate legal text in the shell.
530
- - **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.
532
+ - **Agent profile**: `--profile agent` enables complete-success exit behavior but preserves progressive execution and the ordinary revision policy. Compose it with `--atomic` or an explicit `--existing-revisions` choice when intended; resolved values appear in `effectiveOptions`.
533
+ - **Operation transport**: A UTF-8 operations file and serializer-backed `--operations -` are peers. Use whichever the host can construct without interpolating legal text in the shell.
534
+ - **Compact mutation JSON**: `apply`, `accept`, `reject`, and `delete-comments` omit document/package XML, full validation arrays, and duplicate nested receipts. Top-level `receipts` is authoritative. Pass `--compact` for one-line JSON; run `validate` for full issue records.
531
535
  - 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.
532
536
 
533
537
  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.
@@ -568,15 +572,21 @@ normalize or reconstruct `exactText`. Operation files follow
568
572
  text for human follow-up; do not silently convert this into comment removal.
569
573
  - `validate` audits revision markup and DOCX package wiring, optionally comparing against a `--baseline`.
570
574
 
571
- Paragraph indexes are 1-based. Inspection filters are `--index 12`,
572
- `--range 10:30`, `--indexes 2,5,8`, `--search text`, `--revised`, `--table`,
573
- `--body`, `--non-empty`, and `--view accepted|rejected|current`. A malformed
574
- filter or unknown option is an error rather than an unfiltered fallback.
575
-
576
- Mutating commands require `--author`, authors on every operation, or
577
- `--all-authors` where applicable. Without `--output`, a sibling such as
578
- `contract.redlined.docx` is chosen. Existing outputs are refused unless
579
- `--force` is present. `--in-place` is the only way to overwrite the input.
575
+ Paragraph indexes are 1-based. Inspection filters are `--index 12`,
576
+ `--range 10:30`, `--indexes 2,5,8`, `--search text`, `--revised`, `--table`,
577
+ `--body`, `--non-empty`, and `--view accepted|rejected|current`. Search is
578
+ case-insensitive. Add `--around N` (`--context N` or `-C N`) to a search;
579
+ context records are labeled separately and do not consume the direct-hit
580
+ `--limit`. Continue a bounded result with `--after <paragraph-index>`. Ordinary
581
+ unscoped CLI inspection defaults to 20 direct records and a 48 KiB soft budget;
582
+ `--all` deliberately opts out. A malformed filter or unknown option is an error
583
+ rather than an unfiltered fallback.
584
+
585
+ Mutating commands use `--author`, operation-level authors, then
586
+ `DOCX_REDLINE_AUTHOR`, falling back visibly to `AI Redliner`; review-resolution
587
+ commands may use `--all-authors` where applicable. Without `--output`, a sibling
588
+ such as `contract.redlined.docx` is chosen. Existing outputs are refused unless
589
+ `--force` is present. `--in-place` is the only way to overwrite the input.
580
590
 
581
591
  Treat a nonzero exit code or JSON `status: "error"` as failure. A failed atomic
582
592
  operation reports `written: false` and does not write an output file.
@@ -0,0 +1,126 @@
1
+ # Skill and Harness Authoring Contract
2
+
3
+ Use this page when creating or updating an agent skill, MCP server, or custom
4
+ harness for `@ansonlai/docx-redline-js`. Ordinary document-editing agents should
5
+ load [Agent Fast Start](AGENT_FAST_START.md), not this design contract.
6
+
7
+ ## Runtime negotiation
8
+
9
+ Run this before the first document operation when the skill vendors or invokes
10
+ the CLI:
11
+
12
+ ```bash
13
+ docx-redline version
14
+ ```
15
+
16
+ Require contract version 7 and only the capabilities the integration uses. A
17
+ typical shell skill should require `command-help-v1`, `inspection-context-v1`,
18
+ `bounded-inspection-v1`, `human-document-references-v1`,
19
+ `agent-safety-profile-v2`, `deduplicated-cli-receipts`, and
20
+ `recovery-envelope-v1`. Require `operations-stdin` or `compact-cli-json-v1` only
21
+ when the host uses those features. Fail closed with an upgrade instruction when
22
+ a required capability is absent. Never inspect `dist/`, minified source, or ZIP
23
+ parts to compensate for a stale runtime.
24
+
25
+ ## Safety invariants
26
+
27
+ Every generated integration must preserve these rules:
28
+
29
+ - Inspect narrowly and copy `exactText` plus `paragraphId` or `fingerprint`.
30
+ - Treat `modified` as the complete desired accepted-view target content.
31
+ - Use strict targeting, package validation, and a derived output path; never
32
+ overwrite the source unless the caller explicitly requests `--in-place`.
33
+ - Require `completion: true`, `written: true`, a non-null `outputPath`, and no
34
+ per-operation error before reporting completion.
35
+ - Never accept or reject another reviewer's work or delete comments without
36
+ explicit user authorization.
37
+ - Never retry unchanged failed arguments.
38
+
39
+ The `agent` profile enables complete-success exit behavior and retains the
40
+ ordinary progressive default. It does not select atomic execution or a special
41
+ existing-revision policy. A skill must state those choices explicitly when its
42
+ workflow needs them.
43
+
44
+ ## Workflow policy choices
45
+
46
+ Choose and document these separately from safety invariants:
47
+
48
+ | Choice | Options | Guidance |
49
+ |---|---|---|
50
+ | Transaction | progressive default or `--atomic` | Use progressive for independent edits; use atomic when partial output is unacceptable. |
51
+ | Existing revisions | `merge-same-author` default or explicit policy | Use `slice-cross-author` only when editing inside another reviewer's pending insertion is intended. |
52
+ | Reviewer identity | flag, operation author, environment, or fallback | `AI Redliner` is a valid visible fallback. `DOCX_REDLINE_AUTHOR` is an optional harness preference, not a guard. |
53
+ | Output naming | derived sibling or explicit destination | Keep source immutability unless in-place mutation is deliberately authorized. |
54
+
55
+ Examples of valid profile composition:
56
+
57
+ ```bash
58
+ docx-redline apply input.docx --operations operations.json --profile agent --output reviewed.docx
59
+ docx-redline apply input.docx --operations operations.json --profile agent --atomic --output reviewed.docx
60
+ docx-redline apply input.docx --operations operations.json --profile agent --existing-revisions slice-cross-author --output reviewed.docx
61
+ ```
62
+
63
+ Check `effectiveOptions` rather than assuming the resolved transaction,
64
+ revision, author, or redline policy.
65
+
66
+ ## Transport choices
67
+
68
+ A UTF-8 operations file and serializer-backed stdin are peer transports. Choose
69
+ the form the host can construct safely:
70
+
71
+ ```bash
72
+ docx-redline apply input.docx --operations operations.json --profile agent --output reviewed.docx
73
+ node emit-operations.mjs | docx-redline apply input.docx --operations - --profile agent --compact --output reviewed.docx
74
+ ```
75
+
76
+ Use `JSON.stringify` or a structured tool API. Never demonstrate `echo`, a
77
+ heredoc, or shell-interpolated legal text. `--compact` changes stdout formatting,
78
+ not result semantics. A Node byte-oriented wrapper should call `openDocx` and
79
+ return the full structured result rather than recreating the CLI serializer.
80
+
81
+ ## Ordinary generated workflow
82
+
83
+ The first executable document-editing example in a generated skill should be a
84
+ focused contextual extraction:
85
+
86
+ ```bash
87
+ docx-redline extract input.docx --search "force majeure" --around 3
88
+ ```
89
+
90
+ Use `selection.nextAfter` with `--after` when truncated. Apply once per stable
91
+ batch. Run `docx-redline apply --help` for canonical redline, whole-paragraph
92
+ comment, and rejected-view restore shapes; the operation schema remains
93
+ [document-operations.schema.json](schemas/document-operations.schema.json).
94
+
95
+ ## Recovery contract
96
+
97
+ Lead error handling with exactly these runtime fields:
98
+
99
+ 1. `error.recovery.action`
100
+ 2. `error.recovery.requiresReinspection`
101
+ 3. `error.recovery.requiresUserAuthorization`
102
+ 4. `error.recovery.sameArgumentsSafe`
103
+
104
+ Use `retryPlan.base` and its operation indexes to select the original or partial
105
+ output package. Do not generate a second prose decision tree for every error
106
+ code; error messages and bounded diagnostics explain the cause, while the four
107
+ fields above determine the next action.
108
+
109
+ ## Presentation rules
110
+
111
+ Use `humanReference`, `provision`, or `nearestHeading` in user-facing completion
112
+ reports. `P55`, `index: 55`, and phrases such as “the 55th paragraph” are machine
113
+ targeting and pagination coordinates, not locations a Word user can follow.
114
+ When no formal heading exists, use the returned short text lead. Never replace
115
+ an exact machine target with a human-facing reference.
116
+
117
+ ## Generation checklist
118
+
119
+ - Runtime version and required capabilities are checked once.
120
+ - The first ordinary edit command is focused `extract --search ... --around`.
121
+ - Safety invariants are not mixed with transaction or revision-policy choices.
122
+ - Operations-file and stdin examples use structured serialization.
123
+ - The four-field recovery contract precedes any diagnostic commentary.
124
+ - Completion prose uses legal references rather than machine ordinals.
125
+ - The wrapper delegates mutation, validation, rollback, comments, numbering,
126
+ receipts, and OOXML packaging to the library.
package/docs/TESTING.md CHANGED
@@ -22,10 +22,10 @@ fixtures rarely contain.
22
22
  | Multimodal LLM visual spot check | On-demand / sampled | Evaluates rendered real-document pages with vision models for layout, table alignment, and typography regressions | Full-corpus automated coverage (intentionally decoupled and sampled due to cost/time) |
23
23
  | XSD and LibreOffice | See [Release validation and independent oracles](#release-validation-and-independent-oracles) | Schema conformance and acceptance by a second consumer | Word-specific revision semantics |
24
24
  | Agent inspection and package facade | `node tests/document_inspection_tests.mjs`, `node tests/docx_package_facade_tests.mjs` | Canonical text, comment/list resolution, package-scoped IDs, untouched-part preservation, and atomic rollback | Desktop Word rendering |
25
- | Agent CLI | `node tests/agent_cli_tests.mjs`, `node tests/agent_cli_protocol_tests.mjs` | JSON contracts, exact-text extraction, stdin operations, named agent-profile defaults, UTF-8 fidelity, complete-success exits, source safety, all command families, and operation-schema readability | Cross-platform CI beyond the current runner |
25
+ | Agent CLI | `node tests/agent_cli_tests.mjs`, `node tests/agent_cli_protocol_tests.mjs`, `node tests/agent_cli_help_tests.mjs`, `node tests/agent_cli_inspection_context_tests.mjs`, `node tests/agent_cli_output_budget_tests.mjs` | JSON contracts, command-specific help, contextual pagination, composable progressive/atomic profiles, deduplicated receipts, compact stdout, file/stdin Unicode fidelity, complete-success exits, source safety, command families, and schema readability | Cross-platform CI beyond the current runner |
26
26
  | Example agent session | `node tests/agent_session_example_tests.mjs`, `node tests/localized_edit_example_tests.mjs` | A non-package sample wrapper delegates to the Node facade, binds and refreshes opaque handles across package revisions, returns context windows, compiles exact localized edits, preserves accepted/rejected lifecycle and atomic rollback, and supports review resolution | LLM/provider latency or a production tool-server transport |
27
27
  | Batch compilation and recovery | `node tests/batch_source_binding_tests.mjs`, `node tests/error_recovery_contract_tests.mjs`, `node tests/capture_dependency_graph_tests.mjs` | Batch-start source identity survives structural index drift and savepoint restoration; true overlap and capture fan-out fail before mutation; recovery envelopes, retry bases, bounded CLI diagnostics, and complete-success exits remain stable | Whether a model follows the returned recovery action correctly |
28
- | Agent documentation contract | `node tests/agent_documentation_contract_tests.mjs` | The ordinary fast start stays within its 40–60 line/600-word budget, retains required safety contracts, and the launch card routes to detailed sources while the development wrapper stays outside package files | Whether a particular model reads or follows the instructions |
28
+ | Agent documentation contract | `node tests/agent_documentation_contract_tests.mjs` | The ordinary fast start stays within its 40–60 line/600-word budget, examples lead with scoped contextual extraction, and packaged skill-authoring guidance separates invariants, policies, transports, recovery, and presentation while the development wrapper stays outside package files | Whether a particular model reads or follows the instructions |
29
29
  | Agent edge cases | `node tests/canonical_paragraph_text_tests.mjs`, `node tests/document_inspection_edge_tests.mjs`, `node tests/docx_package_transaction_edge_tests.mjs`, `node tests/node_zip_archive_tests.mjs`, `node tests/agent_cli_edge_tests.mjs` | Revision-view semantics, cross-paragraph anchors, nested numbering, transaction reuse, multi-author cleanup, malformed ZIP handling, and destructive CLI safeguards | Desktop Word rendering and non-Windows CI |
30
30
  | Performance boundary regression | `node tests/performance_phase2_boundary_tests.mjs` | Stable facade re-exports, leaf imports, session rollback, isolated context commit, and comment-first scheduling | The Phase 1 one-parse/one-serialize performance target |
31
31
  | Live-session accuracy and instrumentation | `node tests/performance_phase1_session_tests.mjs` | One full parse/serialization, sequential semantic equivalence, exact accepted/rejected text, valid revisions, list/table/comment/highlight preservation, savepoint no-ops, and zero-serialization rollback | Desktop Word rendering |
@@ -98,6 +98,21 @@ tokens, tool transport, Claude, or OpenCode wall time; collect those separately
98
98
  in the calling harness. The checked WP-07 results are summarized in the
99
99
  [agent protocol rollout audit](validation-reports/2026-09-12-agent-protocol-rollout.md).
100
100
 
101
+ Run the CLI discovery/output benchmark with:
102
+
103
+ ```powershell
104
+ npm run benchmark:agent-cli
105
+ ```
106
+
107
+ It records command-specific help size, broad inspect/search response size,
108
+ context-window call count, pagination metadata, case-insensitive match parity,
109
+ and native elapsed time in `tmp/benchmarks/agent-cli-discovery-latest.json`.
110
+ The checked WP-00 through WP-02 before/after measurements are in the
111
+ [agent CLI discovery baseline](validation-reports/2026-09-12-agent-cli-discovery-baseline.md).
112
+ WP-03 through WP-05 profile, output-size, workflow, documentation, and package
113
+ results are in the
114
+ [agent CLI efficiency rollout audit](validation-reports/2026-09-13-agent-cli-efficiency-rollout.md).
115
+
101
116
  ## Cross-author revision slicing test suite
102
117
 
103
118
  The cross-author revision slicing subsystem introduces six complementary test lanes:
@@ -0,0 +1,56 @@
1
+ # Agent CLI Discovery Baseline
2
+
3
+ **Date:** 2026-09-12
4
+
5
+ **Scope:** WP-00 baseline for command discovery, inspection breadth, contextual
6
+ search, and compact mutation output
7
+
8
+ ## Before-state
9
+
10
+ Measurements were captured from the source CLI immediately before WP-01/WP-02,
11
+ using `tests/fixtures/sample_doc_test.docx` and pretty-printed CLI JSON:
12
+
13
+ | Case | Result |
14
+ |---|---:|
15
+ | Global help | 171 bytes |
16
+ | `apply --help` | 171 bytes; identical to global help |
17
+ | `inspect --non-empty` | 72,387 bytes / 63 paragraphs |
18
+ | Broad `extract --search "the"` | 13,968 bytes / 31 paragraphs |
19
+ | Context retrieval | Search plus range: 2 commands |
20
+ | Successful one-operation receipt | 464 bytes nested plus the same 464 bytes at root |
21
+
22
+ The help payload did not describe command flags, search case behavior, or
23
+ redline/comment/restore shapes. The detailed unscoped inspection exceeded the
24
+ observed 64 KiB harness ceiling. Receipt deduplication is recorded here but is
25
+ owned by WP-04, not WP-00 through WP-02.
26
+
27
+ ## WP-01/WP-02 result
28
+
29
+ The checked post-change run produced:
30
+
31
+ | Case | Result |
32
+ |---|---:|
33
+ | Global command-index help | 1,390 bytes |
34
+ | Command-specific apply help | 4,400 bytes with flags and three operation shapes |
35
+ | Bounded `inspect --non-empty` | 25,093 bytes / first 20 of 63 paragraphs |
36
+ | Bounded `extract --search "the"` | 12,855 bytes / first 20 of 31 matches |
37
+ | `extract --search "agreement" --around 2 --limit 1` | 2,178 bytes / one command / three paragraphs |
38
+
39
+ Both formerly broad responses remain valid JSON below the 48 KiB soft limit and
40
+ include stable continuation metadata. Search case variants returned identical
41
+ indexes. A paragraph that individually exceeds the soft limit is returned whole
42
+ and marked `oversizeItem` rather than truncating `exactText`.
43
+
44
+ ## Reproduction
45
+
46
+ Run:
47
+
48
+ ```bash
49
+ npm run benchmark:agent-cli
50
+ ```
51
+
52
+ The benchmark retains the observed before-state constants and records the active
53
+ post-change results in `tmp/benchmarks/agent-cli-discovery-latest.json`. It
54
+ measures CLI response bytes, calls, paragraphs, selection metadata, and native
55
+ elapsed time. It does not estimate model tokens, provider wall time, or tool
56
+ transport latency.
@@ -60,11 +60,15 @@ win.
60
60
 
61
61
  ## Configuration decision
62
62
 
63
+ > Historical note: this section records CLI contract version 5. Contract version
64
+ > 7 decomposes `--profile agent`: it now supplies complete-success execution
65
+ > without forcing atomic mode. Skills choose `--atomic` separately.
66
+
63
67
  No project or auto-discovered configuration file was added. The CLI already
64
68
  defaults author, strict targeting, validation, tracked changes, revision safety,
65
- and output naming. The explicit `--profile agent` flag captures the remaining
66
- atomic/complete-success policy and reports `effectiveOptions`. Removing that one
67
- flag would not justify hidden configuration discovery or precedence reasoning.
69
+ and output naming. The explicit `--profile agent` flag reports
70
+ `effectiveOptions`; hidden configuration discovery still would not justify its
71
+ additional precedence reasoning.
68
72
 
69
73
  ## Remaining external measurement
70
74
 
@@ -0,0 +1,86 @@
1
+ # Agent CLI Efficiency Rollout Audit
2
+
3
+ **Date:** 2026-09-13
4
+ **Scope:** WP-03 through WP-05 profile composition, compact mutation output,
5
+ skill-authoring guidance, and package parity
6
+
7
+ ## Outcome
8
+
9
+ CLI contract version 7 separates complete-success behavior from workflow
10
+ policy. `--profile agent` now retains progressive execution and the ordinary
11
+ `merge-same-author` policy; `--atomic` and explicit revision policies compose
12
+ with it and appear in `effectiveOptions`. Reviewer precedence and the visible
13
+ `AI Redliner` fallback are unchanged.
14
+
15
+ Compact CLI mutation output now contains one authoritative top-level receipt per
16
+ operation and no nested receipt copy. Successful exact-match diagnostics are
17
+ omitted; successful space-equivalent matches retain `{ mode, differenceCount }`.
18
+ Errors keep their bounded recovery evidence. The Node facade and standalone
19
+ runner retain their complete per-result receipt and target-match structures.
20
+
21
+ ## Measured output
22
+
23
+ `npm run benchmark:agent-cli` uses the same one-operation sample established in
24
+ the WP-00 baseline:
25
+
26
+ | Mutation response | Bytes | Change from pre-WP-04 |
27
+ |---|---:|---:|
28
+ | Pre-WP-04 pretty JSON | 2,968 | — |
29
+ | Contract-7 pretty JSON | 2,216 | 25.34% smaller |
30
+ | Contract-7 `--compact` JSON | 1,557 | 47.54% smaller |
31
+
32
+ One-line serialization is 29.74% smaller than the structurally deduplicated
33
+ pretty response, so contract version 7 exposes it explicitly through `--compact`
34
+ and `compact-cli-json-v1`. It changes whitespace only.
35
+
36
+ ## Representative workflow audit
37
+
38
+ The checked repository run records:
39
+
40
+ - one relevant command-help lookup;
41
+ - zero source, distribution-bundle, or ZIP-part inspection calls;
42
+ - one contextual clause search and one apply attempt;
43
+ - progressive agent-profile execution with complete-success exits;
44
+ - exact accepted text and exact source restoration after rejection;
45
+ - unchanged comment count and byte-identical source input; and
46
+ - one top-level receipt with no nested copy.
47
+
48
+ The existing agent workflow benchmark separately covers mixed comment/redline
49
+ work, independent batch permutations, stale and ambiguous targeting recovery,
50
+ and cross-author attribution. File-based and serializer-backed stdin operations
51
+ are both exercised with the same Unicode payload by the CLI protocol suite.
52
+
53
+ ## Documentation and package parity
54
+
55
+ The shipped documentation now includes `docs/SKILL_AUTHORING.md`. It separates
56
+ safety invariants, workflow policy, transport choices, four-field recovery, and
57
+ presentation rules. Executable documentation tests require each ordinary-use
58
+ section to lead with focused contextual extraction and require skills to cite
59
+ `humanReference`, provisions, or headings rather than machine paragraph
60
+ ordinals.
61
+
62
+ The npm allowlist includes the launch card, fast start, knowledge base,
63
+ skill-authoring contract, schema, testing guide, and checked rollout reports.
64
+ Development-only session examples and benchmark scripts remain excluded.
65
+
66
+ The checked `npm pack --dry-run` contains 152 files (approximately 1.07 MB).
67
+ It includes `node/cli-help.js`, the fast start, skill-authoring contract, and this
68
+ audit; it excludes both agent benchmark scripts and the development session
69
+ example.
70
+ An unpacked tarball invocation reported contract version 7 and the same 16
71
+ capabilities as the source CLI.
72
+
73
+ ## Automated verification
74
+
75
+ - `npm test`: 110 passed, 0 failed.
76
+ - `npm run check:types`: 123 runtime exports have declarations.
77
+ - `npm run test:isolation`: dependency and Word-API isolation passed.
78
+ - Focused ESLint for every WP-03 through WP-05 source, test, and benchmark file
79
+ passed.
80
+ - `npm run build` and `npm pack --dry-run`: passed.
81
+
82
+ ## Measurement boundary
83
+
84
+ These are native runtime, serialized-byte, command-count, and correctness
85
+ measurements. They do not estimate Claude/OpenCode tokens, model reasoning time,
86
+ provider transport latency, or end-to-end harness wall time.
package/index.d.ts CHANGED
@@ -278,13 +278,15 @@ export function getTrackedChangeAuthors(xmlDocOrElement: Document | Element | nu
278
278
  export interface InspectedParagraph {
279
279
  index: number; ref: string; paragraphId: string | null; fingerprint: string | null;
280
280
  text: string; exactText: string; excerpt: string; inTable: boolean;
281
- humanReference: string; styleId: string | null;
281
+ humanReference: string; provision: string | null; styleId: string | null;
282
282
  table: { tableIndex: number; rowIndex: number; cellIndex: number } | null;
283
283
  structuralReferences: Array<{ type: 'footnote' | 'endnote' | 'comment'; id: string | null }>;
284
284
  headingLevel: number | null; nearestHeading: { level: number; text: string } | null;
285
285
  list: { numId: string; level: number; label: string | null; format: string | null } | null;
286
286
  hasRevisions: boolean; revisionAuthors: string[]; commentIds: string[];
287
287
  segments: RevisionTextSegment[];
288
+ selectionRole?: 'match' | 'context';
289
+ contextFor?: number[];
288
290
  }
289
291
  export interface RevisionToken {
290
292
  algorithm: 'sha256';
@@ -295,10 +297,17 @@ export interface RevisionToken {
295
297
  }
296
298
 
297
299
  export interface InspectedComment { id: string; author: string | null; date: string | null; text: string; paraId?: string | null; parentParaId?: string; parentCommentId?: string | null; done?: boolean; paragraphIndex?: number; targetRef?: string; anchoredText?: string; }
298
- export interface DocumentInspectionOptions { revisionView?: 'accepted' | 'rejected' | 'current'; excerptLength?: number; revisedOnly?: boolean; inTable?: boolean; skipEmpty?: boolean; search?: string; indexes?: number[]; range?: { start: number; end: number } | [number, number]; digestFn?: (bytes: Uint8Array) => string; }
300
+ export interface DocumentInspectionOptions { revisionView?: 'accepted' | 'rejected' | 'current'; excerptLength?: number; revisedOnly?: boolean; inTable?: boolean; skipEmpty?: boolean; search?: string; indexes?: number[]; range?: { start: number; end: number } | [number, number]; around?: number; limit?: number; after?: number; digestFn?: (bytes: Uint8Array) => string; }
301
+ export interface DocumentInspectionSelection {
302
+ search?: string; caseSensitive?: false; totalMatches: number; returnedMatches: number;
303
+ returnedParagraphs: number; truncated: boolean; nextAfter: number | null;
304
+ limit?: number; after?: number; around?: number; softByteLimit?: number;
305
+ oversizeItem?: boolean; contextTruncated?: boolean;
306
+ }
299
307
  export interface DocumentInspectionResult {
300
308
  status: 'ok' | 'error'; paragraphs: InspectedParagraph[]; comments: InspectedComment[];
301
309
  revisionAuthors?: string[]; commentAuthors?: string[]; counts?: { paragraphs: number; comments: number; revisedParagraphs: number };
310
+ selection?: DocumentInspectionSelection;
302
311
  revisionToken?: RevisionToken | null;
303
312
  coveredParts?: string[];
304
313
  warnings: string[]; error?: RedlineError;