pointbreak 0.8.0

Durable terminal code review for changes humans and coding agents collaborate on together
Documentation
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! Full-document characterization guard for the `pointbreak review-*` command JSON.
//!
//! These tests drive the real `pointbreak` binary against a deterministic fixture
//! repository and assert that the ENTIRE serialized document (the normalized
//! stdout string, preserving key order) stays stable. Because the documents are
//! content-addressed, the nondeterministic substrings are content hashes,
//! timestamps, the absolute repository path, and the producer version compiled
//! into the binary, which are normalized to fixed placeholders before comparison.
//!
//! Snapshots live under `tests/fixtures/review_documents/<command>.snap`. Run
//! with `BLESS=1` to (re)generate them from the current binary; otherwise the
//! normalized output is asserted against the stored snapshot.
//!
//! The guard exists so the #118 extraction of the document/envelope layer into
//! `pointbreak::documents` provably preserves the documented bytes, field order,
//! renames, and `skip_serializing_if` behavior.

mod support;

use std::fs;
use std::path::{Path, PathBuf};

use serde_json::Value;
use support::git_repo::GitRepo;
use support::pointbreak;

fn snapshot_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/review_documents")
}

/// Canonicalized absolute path of the fixture repo, as it appears in command
/// output (e.g. `worktreeRoot`). macOS resolves `/var` to `/private/var`, so we
/// compare against the canonical form.
fn canonical_repo_path(repo: &GitRepo) -> String {
    repo.path()
        .canonicalize()
        .expect("canonicalize fixture repo path")
        .to_string_lossy()
        .into_owned()
}

/// Replace every `sha256:<64 lowercase hex>` with `sha256:<h>`.
fn normalize_hashes(text: &str) -> String {
    replace_prefixed(text, "sha256:", "sha256:<h>", |rest| {
        let hex: String = rest.chars().take(64).collect();
        if hex.len() == 64
            && hex
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        {
            Some(64)
        } else {
            None
        }
    })
}

/// Replace locally minted timestamp fields with the snapshot's stable token.
fn normalize_timestamps(text: &str) -> String {
    ["occurredAt", "createdAt", "observedAt", "capturedAt"]
        .into_iter()
        .fold(text.to_owned(), |text, key| {
            normalize_timestamp_field(&text, key)
        })
}

fn normalize_timestamp_field(text: &str, key: &str) -> String {
    let prefix = format!("\"{key}\":\"");
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(start) = rest.find(&prefix) {
        let value_start = start + prefix.len();
        out.push_str(&rest[..value_start]);
        let value_and_rest = &rest[value_start..];
        let Some(end) = value_and_rest.find('"') else {
            out.push_str(value_and_rest);
            return out;
        };
        let value = &value_and_rest[..end];
        if pointbreak::session::parse_event_instant(value).is_some() {
            out.push_str("unix-ms:<t>");
        } else {
            out.push_str(value);
        }
        rest = &value_and_rest[end..];
    }
    out.push_str(rest);
    out
}

/// Scan `text` for occurrences of `prefix`; when `match_len` accepts the suffix
/// (returning how many chars after the prefix the token consumes), replace the
/// whole `prefix + token` span with `replacement`.
fn replace_prefixed(
    text: &str,
    prefix: &str,
    replacement: &str,
    match_len: impl Fn(&str) -> Option<usize>,
) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(idx) = rest.find(prefix) {
        out.push_str(&rest[..idx]);
        let after_prefix = &rest[idx + prefix.len()..];
        if let Some(token_len) = match_len(after_prefix) {
            out.push_str(replacement);
            let byte_len: usize = after_prefix
                .chars()
                .take(token_len)
                .map(char::len_utf8)
                .sum();
            rest = &after_prefix[byte_len..];
        } else {
            out.push_str(prefix);
            rest = after_prefix;
        }
    }
    out.push_str(rest);
    out
}

/// Replace a 40-char lowercase-hex git object id that immediately follows
/// `"<key>":"` with `<oid>`. Git OIDs depend on commit timestamp/author and so
/// vary between runs even for identical content.
fn normalize_git_oid(text: &str, key: &str) -> String {
    let prefix = format!("\"{key}\":\"");
    replace_prefixed(text, &prefix, &format!("\"{key}\":\"<oid>"), |rest| {
        let hex: String = rest.chars().take(40).collect();
        let closes = rest.chars().nth(40) == Some('"');
        if hex.len() == 40
            && closes
            && hex
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
        {
            Some(40)
        } else {
            None
        }
    })
}

/// Replace the JSON string value of `"worktreeRoot":"…"` with `<repo>`,
/// regardless of path shape. This is portable across platforms: on Windows the
/// captured path is an extended-length `\\?\C:\…` form with escaped backslashes
/// that a literal path replacement would miss.
fn normalize_worktree_root(text: &str) -> String {
    replace_prefixed(
        text,
        "\"worktreeRoot\":\"",
        "\"worktreeRoot\":\"<repo>",
        |rest| {
            // Consume the JSON string contents up to (not including) the closing
            // unescaped quote, honoring backslash escapes.
            let mut escaped = false;
            let mut chars = 0usize;
            for c in rest.chars() {
                if escaped {
                    escaped = false;
                    chars += 1;
                    continue;
                }
                match c {
                    '\\' => {
                        escaped = true;
                        chars += 1;
                    }
                    '"' => return Some(chars),
                    _ => chars += 1,
                }
            }
            None
        },
    )
}

/// Preserve the pre-cutover snapshots while masking the native producer axis.
///
/// Those golden files are historical compatibility artifacts and must not be
/// regenerated for the prospective producer rename. Native producer identity
/// is pinned separately by `producer_identity` and `event_signature_vectors`.
fn normalize_producer_for_historical_snapshot(text: &str) -> String {
    ["shore", "pointbreak"]
        .into_iter()
        .fold(text.to_owned(), |text, producer| {
            replace_prefixed(
                &text,
                &format!(r#""producer":{{"name":"{producer}","version":""#),
                r#""producer":{"name":"shore","version":"<producerVersion>"#,
                |rest| rest.find('"'),
            )
        })
}

/// Mask the CLI release version in the version-handshake body without touching
/// the envelope's numeric document version.
fn normalize_cli_version(text: &str) -> String {
    replace_prefixed(
        text,
        r#""cliVersion":""#,
        r#""cliVersion":"<cliVersion>"#,
        |rest| rest.find('"'),
    )
}

fn normalize_build_identity(text: &str) -> String {
    let text = replace_prefixed(
        text,
        r#""build":{"source":"git","commit":""#,
        r#""build":{"source":"git","commit":"<buildCommit>"#,
        |rest| rest.find('"'),
    );
    let text = replace_prefixed(
        &text,
        r#""commit":"<buildCommit>","describe":""#,
        r#""commit":"<buildCommit>","describe":"<buildDescribe>"#,
        |rest| rest.find('"'),
    );
    let text = replace_prefixed(
        &text,
        r#""build":{"source":"package","commit":null,"describe":""#,
        r#""build":{"source":"package","commit":null,"describe":"<buildDescribe>"#,
        |rest| rest.find('"'),
    );
    let text = text.replace(
        r#""describe":"<buildDescribe>","dirty":true"#,
        r#""describe":"<buildDescribe>","dirty":false"#,
    );
    text.replace(
        r#""build":{"source":"git","commit":"<buildCommit>""#,
        r#""build":{"source":"<buildSource>","commit":null"#,
    )
    .replace(
        r#""build":{"source":"package","commit":null"#,
        r#""build":{"source":"<buildSource>","commit":null"#,
    )
}

/// Normalize the nondeterministic substrings while preserving every key and the
/// document's exact serialized field order.
fn normalize(raw: &str, repo_path: &str) -> String {
    // Strip Windows CRLF so snapshots compare equal regardless of the platform's
    // git autocrlf checkout behavior.
    let text = raw.replace("\r\n", "\n");
    // Replace the absolute repo path first (Unix), then the worktreeRoot value
    // generically (covers the Windows extended-length path form).
    let text = text.replace(repo_path, "<repo>");
    let text = normalize_worktree_root(&text);
    let text = normalize_hashes(&text);
    let text = normalize_timestamps(&text);
    let text = normalize_producer_for_historical_snapshot(&text);
    let text = normalize_cli_version(&text);
    let text = normalize_build_identity(&text);
    let text = normalize_git_oid(&text, "commitOid");
    let text = normalize_git_oid(&text, "treeOid");
    // `headOid` rides on auto-recorded ref associations (the capture-time branch
    // head), a real commit OID that varies run to run like the others; the ref
    // continuity block echoes it as `recordedHeadOid` alongside the ref's
    // `currentTipOid`.
    let text = normalize_git_oid(&text, "headOid");
    let text = normalize_git_oid(&text, "recordedHeadOid");
    normalize_git_oid(&text, "currentTipOid")
}

#[test]
fn normalizer_masks_release_versions_without_masking_schema_version() {
    let old = r#"{"version":1,"cliVersion":"0.5.0","writer":{"producer":{"name":"shore","version":"0.5.0"}}}"#;
    let current = r#"{"version":1,"cliVersion":"0.6.0","writer":{"producer":{"name":"pointbreak","version":"0.6.0"}}}"#;

    assert_eq!(normalize(old, "<absent>"), normalize(current, "<absent>"));
    assert!(normalize(current, "<absent>").contains(r#""version":1"#));
}

#[test]
fn normalizer_masks_store_and_context_identity_hashes() {
    let hash = "1".repeat(64);
    let document = format!(
        r#"{{"storeIdentity":"store:sha256:{hash}","contextIdentity":"context:sha256:{hash}"}}"#
    );

    let normalized = normalize(&document, "<absent>");

    assert!(normalized.contains(r#""storeIdentity":"store:sha256:<h>""#));
    assert!(normalized.contains(r#""contextIdentity":"context:sha256:<h>""#));
    assert!(!normalized.contains(&hash));
}

#[test]
fn version_flag_remains_available() {
    let output = pointbreak(["--version"]);
    assert!(output.status.success());
    assert!(
        String::from_utf8(output.stdout)
            .unwrap()
            .starts_with("pointbreak ")
    );
}

#[track_caller]
fn run_command(repo: &GitRepo, args: &[&str]) -> String {
    let output = pointbreak(args);
    assert!(
        output.status.success(),
        "command {args:?} failed\nstderr:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let raw = String::from_utf8(output.stdout).expect("stdout is utf-8");
    normalize(&raw, &canonical_repo_path(repo))
}

#[track_caller]
fn assert_snapshot(name: &str, normalized: &str) {
    let path = snapshot_dir().join(format!("{name}.snap"));
    if std::env::var_os("BLESS").is_some() {
        fs::create_dir_all(snapshot_dir()).expect("create snapshot dir");
        fs::write(&path, normalized).expect("write snapshot");
        return;
    }
    let expected = fs::read_to_string(&path)
        .unwrap_or_else(|error| {
            panic!(
                "missing snapshot {}: {error}. Re-run with BLESS=1 to generate it.",
                path.display()
            )
        })
        .replace("\r\n", "\n");
    assert_eq!(
        normalized,
        expected,
        "documented JSON for `{name}` drifted from the stored snapshot {}.\n\
         If this change is intentional, re-run with BLESS=1 to regenerate.",
        path.display()
    );
}

#[test]
fn version_document_is_byte_stable() {
    let repo = GitRepo::new();
    let output = run_command(&repo, &["version"]);
    assert_snapshot("version", &output);
}

/// Build the deterministic fixture repo and capture a single Revision, returning
/// the captured review-unit id (already normalized in snapshots, used here only to
/// pass back into commands as a literal argument).
fn fixture_repo() -> (GitRepo, String) {
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");

    let raw =
        String::from_utf8(pointbreak(["capture", "--repo", repo.path().to_str().unwrap()]).stdout)
            .expect("capture stdout is utf-8");
    let value: Value = serde_json::from_str(&raw).expect("valid capture json");
    let revision_id = value["revision"]["id"]
        .as_str()
        .expect("review unit id")
        .to_owned();
    (repo, revision_id)
}

fn repo_arg(repo: &GitRepo) -> String {
    repo.path().to_str().unwrap().to_owned()
}

/// One test exercises the documented `pointbreak review-*` commands against a
/// single deterministic fixture, snapshotting the full normalized document for
/// each. Driving them in sequence keeps content-addressed ids stable across
/// commands (each new write references the same captured Revision).
#[test]
fn review_documents_are_byte_stable() {
    // 1. pointbreak capture (re-run on a fresh repo to snapshot the capture document
    //    itself; the shared fixture below reuses its own capture).
    {
        let repo = GitRepo::new();
        repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
        repo.commit_all("base");
        repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");
        let out = run_command(&repo, &["capture", "--repo", &repo_arg(&repo)]);
        assert_snapshot("capture", &out);
    }

    let (repo, unit) = fixture_repo();
    let repo_path = repo_arg(&repo);

    // 2. review observation add
    let observation_add = run_command(
        &repo,
        &[
            "observation",
            "add",
            "--repo",
            &repo_path,
            "--track",
            "agent:codex",
            "--title",
            "Observed change",
            "--body",
            "the return value changed",
        ],
    );
    assert_snapshot("observation_add", &observation_add);

    // 3. review observation list
    let observation_list = run_command(
        &repo,
        &[
            "observation",
            "list",
            "--repo",
            &repo_path,
            "--include-body",
        ],
    );
    assert_snapshot("observation_list", &observation_list);

    // 4. review input-request open
    let open_raw = pointbreak([
        "input-request",
        "open",
        "--repo",
        &repo_path,
        "--track",
        "agent:codex",
        "--title",
        "Need a decision",
        "--reason",
        "manual-decision-required",
        "--body",
        "should we ship this?",
    ]);
    assert!(open_raw.status.success());
    let open_value: Value =
        serde_json::from_slice(&open_raw.stdout).expect("valid input-request open json");
    let input_request_id = open_value["inputRequestId"]
        .as_str()
        .expect("input request id")
        .to_owned();
    let input_request_open = normalize(
        &String::from_utf8(open_raw.stdout).unwrap(),
        &canonical_repo_path(&repo),
    );
    assert_snapshot("input_request_open", &input_request_open);

    // 5. review input-request fetch
    let input_request_fetch = run_command(
        &repo,
        &[
            "input-request",
            "show",
            &input_request_id,
            "--repo",
            &repo_path,
            "--include-body",
        ],
    );
    assert_snapshot("input_request_fetch", &input_request_fetch);

    // 6. review input-request respond
    let input_request_respond = run_command(
        &repo,
        &[
            "input-request",
            "respond",
            &input_request_id,
            "--repo",
            &repo_path,
            "--outcome",
            "approved",
            "--reason",
            "looks good",
        ],
    );
    assert_snapshot("input_request_respond", &input_request_respond);

    // 7. review input-request list (after a response so the view includes it)
    let input_request_list = run_command(
        &repo,
        &[
            "input-request",
            "list",
            "--repo",
            &repo_path,
            "--status",
            "all",
            "--include-body",
        ],
    );
    assert_snapshot("input_request_list", &input_request_list);

    // 8. review assessment add
    let assessment_add = run_command(
        &repo,
        &[
            "assessment",
            "add",
            "--repo",
            &repo_path,
            "--track",
            "human:kevin",
            "--assessment",
            "accepted",
            "--summary",
            "ship it",
        ],
    );
    assert_snapshot("assessment_add", &assessment_add);

    // 9. review assessment show
    let assessment_show = run_command(
        &repo,
        &[
            "assessment",
            "show",
            "--repo",
            &repo_path,
            "--include-summary",
        ],
    );
    assert_snapshot("assessment_show", &assessment_show);

    // 10. review unit show
    let unit_show = run_command(
        &repo,
        &[
            "revision",
            "show",
            &unit,
            "--repo",
            &repo_path,
            "--include-body",
        ],
    );
    assert_snapshot("unit_show", &unit_show);

    // 11. review unit list
    let unit_list = run_command(&repo, &["revision", "list", "--repo", &repo_path]);
    assert_snapshot("unit_list", &unit_list);

    // 12. review history
    let history = run_command(&repo, &["history", "--repo", &repo_path, "--include-body"]);
    assert_snapshot("history", &history);

    // 13. review validation add
    let validation_add = run_command(
        &repo,
        &[
            "validation",
            "add",
            "--repo",
            &repo_path,
            "--track",
            "agent:codex",
            "--check-name",
            "cargo test",
            "--status",
            "passed",
            "--command",
            "cargo test --all",
            "--exit-code",
            "0",
            "--source-fingerprint",
            "rev:sha256:1111111111111111111111111111111111111111111111111111111111111111",
            "--summary",
            "all tests passed",
            "--started-at",
            "2026-05-10T00:00:00Z",
            "--completed-at",
            "2026-05-10T00:01:00Z",
            "--log-content-hash",
            "sha256:2222222222222222222222222222222222222222222222222222222222222222",
        ],
    );
    assert_snapshot("validation_add", &validation_add);

    // 14. review validation list
    let validation_list = run_command(
        &repo,
        &["validation", "list", "--repo", &repo_path, "--include-body"],
    );
    assert_snapshot("validation_list", &validation_list);

    // 15. attention list — a fresh open input request surfaces as an attention
    //     item, so the snapshot exercises the full item wire shape.
    let attention_open = pointbreak([
        "input-request",
        "open",
        "--repo",
        &repo_path,
        "--track",
        "human:kevin",
        "--title",
        "Runtime trace required",
        "--reason",
        "insufficient-evidence",
    ]);
    assert!(attention_open.status.success());
    let attention_list = run_command(
        &repo,
        &[
            "attention",
            "list",
            "--repo",
            &repo_path,
            "--format",
            "json",
        ],
    );
    assert_snapshot("attention_list", &attention_list);
}