stemma-cli 0.1.0

Command-line interface to the stemma DOCX engine: compare two files into a tracked-changes redline, extract text/JSON, resolve tracked changes, and validate — a zero-integration path to the core verbs for non-Rust adopters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Integration tests driving the built `stemma` binary against real engine
//! fixtures. Each test shells out to the CLI (never the library) and, where a
//! round-trip is the contract, reopens the output with the engine to verify by
//! CONTENT — accept-all of a compare is the target, reject-all is the base.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use stemma::ExportOptions;
use stemma::api::Document;
use stemma::edit_v4::parse_transaction;

/// Absolute path to a fixture under the engine's testdata tree.
fn fixture(rel: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../stemma-engine/testdata")
        .join(rel)
}

/// Run the built binary with `args`, returning the captured output.
fn run(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_stemma"))
        .args(args)
        .output()
        .expect("spawn stemma binary")
}

fn text_of(path: &Path) -> String {
    let bytes = std::fs::read(path).expect("read output docx");
    Document::parse(&bytes)
        .expect("parse output docx")
        .to_text()
}

/// The accept-all / reject-all plain-text readings of a document on disk.
fn readings(path: &Path) -> (String, String) {
    let bytes = std::fs::read(path).expect("read docx");
    let doc = Document::parse(&bytes).expect("parse docx");
    let accepted = doc.read_accepted().expect("accept-all").to_text();
    let rejected = doc.read_rejected().expect("reject-all").to_text();
    (accepted, rejected)
}

#[test]
fn compare_produces_a_reviewable_redline() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("redline.docx");

    let output = run(&[
        "compare",
        fixture("simple-text/before.docx").to_str().unwrap(),
        fixture("simple-text/after.docx").to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
    ]);
    assert!(
        output.status.success(),
        "compare should succeed: {output:?}"
    );
    assert!(out.exists(), "compare must write the redline file");

    // The round-trip contract: reject-all reconstructs the base, accept-all the
    // target. This proves the redline carries the discovered changes.
    let base = text_of(&fixture("simple-text/before.docx"));
    let target = text_of(&fixture("simple-text/after.docx"));
    let (accepted, rejected) = readings(&out);
    assert_eq!(rejected, base, "reject-all == base");
    assert_eq!(accepted, target, "accept-all == target");
}

#[test]
fn resolve_accept_all_yields_the_target_text() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let accepted = dir.path().join("accepted.docx");

    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    let output = run(&[
        "resolve",
        redline.to_str().unwrap(),
        "-o",
        accepted.to_str().unwrap(),
        "--accept-all",
    ]);
    assert!(
        output.status.success(),
        "resolve --accept-all should succeed: {output:?}"
    );

    let target = text_of(&fixture("simple-text/after.docx"));
    assert_eq!(
        text_of(&accepted),
        target,
        "accept-all of the redline == target"
    );
}

#[test]
fn resolve_reject_all_yields_the_base_text() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let rejected = dir.path().join("rejected.docx");

    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    let output = run(&[
        "resolve",
        redline.to_str().unwrap(),
        "-o",
        rejected.to_str().unwrap(),
        "--reject-all",
    ]);
    assert!(
        output.status.success(),
        "resolve --reject-all should succeed: {output:?}"
    );

    let base = text_of(&fixture("simple-text/before.docx"));
    assert_eq!(
        text_of(&rejected),
        base,
        "reject-all of the redline == base"
    );
}

#[test]
fn resolve_accept_author_keeps_that_authors_change() {
    // A redline carrying one named author's tracked change, authored through the
    // engine so the CLI has a real by-author selection to resolve.
    let dir = tempfile::tempdir().unwrap();
    let redlined = dir.path().join("named-redline.docx");
    let resolved = dir.path().join("resolved.docx");
    write_named_redline(&redlined, "Alice", "Alice's revised clause.");

    let output = run(&[
        "resolve",
        redlined.to_str().unwrap(),
        "-o",
        resolved.to_str().unwrap(),
        "--accept-author",
        "Alice",
    ]);
    assert!(
        output.status.success(),
        "resolve --accept-author should succeed: {output:?}"
    );
    assert!(
        text_of(&resolved).contains("Alice's revised clause."),
        "accepting Alice's change keeps her new text"
    );
}

#[test]
fn extract_json_parses_and_carries_blocks_and_revisions() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    let output = run(&["extract", redline.to_str().unwrap(), "--format", "json"]);
    assert!(
        output.status.success(),
        "extract json should succeed: {output:?}"
    );

    let value: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("stdout is valid JSON");
    assert!(
        value["blocks"].as_array().is_some_and(|b| !b.is_empty()),
        "json carries a non-empty blocks array"
    );
    let revisions = value["revisions"].as_array().expect("revisions array");
    assert!(
        !revisions.is_empty(),
        "a redline's json carries pending revisions"
    );
    // Each revision row has the documented shape.
    for rev in revisions {
        assert!(rev["revision_id"].is_number());
        assert!(rev["kind"].is_string());
        assert!(rev["block_id"].is_string());
        assert!(rev["excerpt"].is_string());
    }
}

#[test]
fn compare_author_attributes_the_discovered_revisions() {
    // `compare --author NAME` attributes every discovered revision to NAME; the
    // attribution surfaces in `extract --format json`'s revision rows and the
    // diff round-trip is unchanged.
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let output = run(&[
        "compare",
        fixture("simple-text/before.docx").to_str().unwrap(),
        fixture("simple-text/after.docx").to_str().unwrap(),
        "-o",
        redline.to_str().unwrap(),
        "--author",
        "Reviewer",
    ]);
    assert!(
        output.status.success(),
        "compare --author should succeed: {output:?}"
    );

    let json = run(&["extract", redline.to_str().unwrap(), "--format", "json"]);
    assert!(
        json.status.success(),
        "extract json should succeed: {json:?}"
    );
    let value: serde_json::Value =
        serde_json::from_slice(&json.stdout).expect("stdout is valid JSON");
    let revisions = value["revisions"].as_array().expect("revisions array");
    assert!(!revisions.is_empty(), "the redline carries revisions");
    assert!(
        revisions
            .iter()
            .all(|r| r["author"].as_str() == Some("Reviewer")),
        "every revision row must be attributed to the supplied author: {revisions:?}"
    );

    // Attribution does not disturb the diff round-trip.
    let base = text_of(&fixture("simple-text/before.docx"));
    let target = text_of(&fixture("simple-text/after.docx"));
    let (accepted, rejected) = readings(&redline);
    assert_eq!(rejected, base, "reject-all == base");
    assert_eq!(accepted, target, "accept-all == target");
}

#[test]
fn compare_empty_author_is_refused() {
    // No silent fallback to anonymous: an explicit empty `--author` is refused.
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let output = run(&[
        "compare",
        fixture("simple-text/before.docx").to_str().unwrap(),
        fixture("simple-text/after.docx").to_str().unwrap(),
        "-o",
        redline.to_str().unwrap(),
        "--author",
        "",
    ]);
    assert!(
        !output.status.success(),
        "an empty --author must fail, not silently produce an anonymous redline"
    );
    assert!(
        !redline.exists(),
        "no redline is written when the author is refused"
    );
}

#[test]
fn extract_text_prints_the_body() {
    let output = run(&[
        "extract",
        fixture("simple-text/before.docx").to_str().unwrap(),
    ]);
    assert!(
        output.status.success(),
        "extract text should succeed: {output:?}"
    );
    let stdout = String::from_utf8(output.stdout).expect("utf8 stdout");
    assert!(!stdout.trim().is_empty(), "extract text prints the body");
}

#[test]
fn validate_reports_ok_on_a_valid_fixture() {
    let output = run(&[
        "validate",
        fixture("simple-text/before.docx").to_str().unwrap(),
    ]);
    assert!(output.status.success(), "validate should pass: {output:?}");
    let stdout = String::from_utf8(output.stdout).expect("utf8 stdout");
    assert!(
        stdout.starts_with("OK:"),
        "validate prints an OK line: {stdout:?}"
    );
    assert!(
        stdout.contains("block"),
        "the OK line reports a block count"
    );
}

#[test]
fn garbage_input_fails_actionably_without_panicking() {
    let dir = tempfile::tempdir().unwrap();
    let garbage = dir.path().join("garbage.docx");
    std::fs::write(&garbage, b"this is not a docx package").unwrap();

    let output = run(&["validate", garbage.to_str().unwrap()]);
    assert!(!output.status.success(), "garbage input must fail");
    let stderr = String::from_utf8(output.stderr).expect("utf8 stderr");
    assert!(
        stderr.starts_with("error:"),
        "one-line actionable error: {stderr:?}"
    );
    assert!(
        stderr.contains("garbage.docx"),
        "the error names the offending file: {stderr:?}"
    );
    assert!(!stderr.contains("panicked"), "must not panic: {stderr:?}");
}

#[test]
fn unknown_revision_id_is_a_named_error() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let out = dir.path().join("out.docx");
    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    let output = run(&[
        "resolve",
        redline.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
        "--accept-ids",
        "99999",
    ]);
    assert!(
        !output.status.success(),
        "an unknown id must fail, not no-op"
    );
    let stderr = String::from_utf8(output.stderr).expect("utf8 stderr");
    assert!(
        stderr.contains("99999"),
        "the error names the missing id: {stderr:?}"
    );
    assert!(!out.exists(), "no output is written on a failed selection");
}

#[test]
fn refuses_to_write_output_over_the_input() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    let output = run(&[
        "resolve",
        redline.to_str().unwrap(),
        "-o",
        redline.to_str().unwrap(),
        "--accept-all",
    ]);
    assert!(
        !output.status.success(),
        "overwriting the input must be refused"
    );
    let stderr = String::from_utf8(output.stderr).expect("utf8 stderr");
    assert!(
        stderr.contains("refusing to overwrite"),
        "the refusal is explicit: {stderr:?}"
    );
}

#[test]
fn resolve_requires_a_disposition() {
    let dir = tempfile::tempdir().unwrap();
    let redline = dir.path().join("redline.docx");
    let out = dir.path().join("out.docx");
    assert!(
        run(&[
            "compare",
            fixture("simple-text/before.docx").to_str().unwrap(),
            fixture("simple-text/after.docx").to_str().unwrap(),
            "-o",
            redline.to_str().unwrap(),
        ])
        .status
        .success()
    );

    // No disposition flag: clap's required ArgGroup rejects the invocation.
    let output = run(&[
        "resolve",
        redline.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
    ]);
    assert!(!output.status.success(), "a disposition is required");
    assert!(
        !out.exists(),
        "nothing is written when the invocation is rejected"
    );
}

/// Author one tracked whole-paragraph replacement as `author`, via the engine's
/// v4 wire path, and write the resulting redline to `path`. Mirrors the
/// `resolve_a_redline` example's seeding helper.
fn write_named_redline(path: &Path, author: &str, replacement: &str) {
    const ORIGINAL: &str = "This is a very interesting test that includes lots of stuff.";
    let bytes = std::fs::read(fixture("paragraphs/before.docx")).unwrap();
    let doc = Document::parse(&bytes).expect("parse fixture");
    let view = doc.read();
    let target = view
        .blocks
        .iter()
        .find(|b| b.text.contains(ORIGINAL))
        .expect("fixture contains the seed paragraph");
    let txn_json = format!(
        r#"{{ "ops": [ {{ "op": "replace", "target": "{}", "guard": "{}",
               "content": {{ "type": "paragraph",
                             "content": [ {{ "type": "text", "text": "{replacement}" }} ] }} }} ],
             "revision": {{ "author": "{author}" }} }}"#,
        target.id, target.guard
    );
    let txn = parse_transaction(&txn_json)
        .expect("v4 schema-valid")
        .into_edit_transaction()
        .expect("v4 -> EditTransaction");
    let edited = doc.apply(&txn).expect("apply tracked replace");
    let out = edited
        .serialize(&ExportOptions::default())
        .expect("serialize redline");
    std::fs::write(path, out).expect("write named redline");
}