packdiff-dto 0.4.2

The packdiff data model: diff + review documents, parser, operations, exports. Pure logic, no I/O.
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
//! The review document: the comments a reviewer leaves on a diff, and every
//! operation that may change them.
//!
//! This is the state that lives in the browser's localStorage. The page's
//! JavaScript never edits it directly — it calls into the WASM build of this
//! crate for every mutation, so upsert/delete/merge/ordering semantics are
//! defined exactly once, here, and are identical in tests, in the CLI, and in
//! the browser.
//!
//! Purity contract: the model has no clock and no entropy. Comment `id`s and
//! RFC 3339 timestamps are supplied by the caller; the model validates and
//! orders them.

use serde::{Deserialize, Serialize};

use crate::{ModelError, RefInfo, SCHEMA_VERSION, TOOL};

/// Which side of the diff a comment anchors to. Serialized as the bare
/// `CamelCase` variant name (`"Old"` / `"New"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Side {
  /// Pre-image (a deleted line): `line` is an old-file line number.
  Old,
  /// Post-image (an added or context line): `line` is a new-file line number.
  New,
}

/// The reviewer's verdict on the whole change, GitHub-style. Encoded as a
/// single-key union — `{ "Approved": { "at": "…" } }` — with no
/// discriminator field. The timestamp is the payload on purpose: it is what
/// lets two documents merge deterministically (newer verdict wins).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum Verdict {
  /// The change is approved as it stands.
  Approved {
    /// When the verdict was given, RFC 3339 UTC, caller-supplied.
    at: String,
  },
  /// The change needs work before it can land.
  ChangesRequired {
    /// When the verdict was given, RFC 3339 UTC, caller-supplied.
    at: String,
  },
}

impl Verdict {
  /// When the verdict was given — the merge tiebreaker.
  pub fn at(&self) -> &str {
    match self {
      Verdict::Approved { at } | Verdict::ChangesRequired { at } => at,
    }
  }

  /// Human label for exports: `approved` / `changes required`.
  pub fn label(&self) -> &'static str {
    match self {
      Verdict::Approved { .. } => "approved",
      Verdict::ChangesRequired { .. } => "changes required",
    }
  }

  fn validate(&self) -> Result<(), ModelError> {
    if self.at().trim().is_empty() {
      return Err(ModelError::InvalidVerdict("at must be non-empty".to_string()));
    }
    Ok(())
  }
}

/// One review comment, anchored to a diff line.
///
/// Anchor identity is `(file, side, line)` where `file` is the post-image
/// path ([`crate::diff::FileDiff::anchor_path`]). Comment identity is `id` —
/// anchors may collide (several comments on one line), ids may not.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Comment {
  /// Caller-supplied unique id — the comment's identity for upsert, delete,
  /// and import merging.
  pub id: String,
  /// Post-image path of the file the comment anchors to.
  pub file: String,
  /// Which side of the diff `line` counts in.
  pub side: Side,
  /// 1-based line number on `side`.
  pub line: u32,
  /// The comment body, verbatim; may span multiple lines.
  pub text: String,
  /// Creation time, RFC 3339 UTC, caller-supplied; part of the stable sort
  /// order so threads on one line read chronologically.
  pub created_at: String,
  /// Last-edit time, RFC 3339 UTC, caller-supplied; drives merge conflict
  /// resolution (newer wins).
  pub updated_at: String,
  /// When the comment was resolved, RFC 3339 UTC, caller-supplied.
  /// Present = resolved; absent (and omitted from JSON) = open. Reopening
  /// removes it. Absent from v1 documents, which parse as all-open.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub resolved_at: Option<String>,
}

impl Comment {
  /// Validation applied on every entry into the document.
  pub fn validate(&self) -> Result<(), ModelError> {
    fn need(cond: bool, msg: &str) -> Result<(), ModelError> {
      if cond {
        Ok(())
      } else {
        Err(ModelError::InvalidComment(msg.to_string()))
      }
    }
    need(!self.id.trim().is_empty(), "id must be non-empty")?;
    need(!self.file.trim().is_empty(), "file must be non-empty")?;
    need(self.line >= 1, "line must be >= 1")?;
    need(!self.text.trim().is_empty(), "text must be non-empty")?;
    need(!self.created_at.trim().is_empty(), "created_at must be non-empty")?;
    need(!self.updated_at.trim().is_empty(), "updated_at must be non-empty")?;
    if let Some(at) = &self.resolved_at {
      need(!at.trim().is_empty(), "resolved_at, when present, must be non-empty")?;
    }
    Ok(())
  }

  /// Deterministic document order: by file, then line, then side (old
  /// before new), then creation time, then id as the final tiebreaker.
  fn sort_key(&self) -> (&str, u32, Side, &str, &str) {
    (&self.file, self.line, self.side, &self.created_at, &self.id)
  }
}

/// The mutable review state for one `(repo, base_sha, head_sha)` diff.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReviewDocument {
  /// Schema generation this document was written with; readers reject
  /// documents newer than they understand ([`SCHEMA_VERSION`]).
  pub schema_version: u32,
  /// Producing tool identifier (`"packdiff"`); distinguishes exported files
  /// from look-alike JSON of other origins.
  pub tool: String,
  /// Repository directory name the review belongs to.
  pub repo: String,
  /// The reviewed diff's base ref, pinned to its SHA.
  pub base: RefInfo,
  /// The reviewed diff's head ref, pinned to its SHA.
  pub head: RefInfo,
  /// The comments, always in the canonical order ([`ReviewDocument::sort`]).
  pub comments: Vec<Comment>,
  /// The reviewer's verdict on the whole change; `None` (and omitted from
  /// JSON) while the review is in progress — and in v1 documents, which
  /// parse as verdict-less.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub verdict: Option<Verdict>,
}

impl ReviewDocument {
  pub fn new(repo: String, base: RefInfo, head: RefInfo) -> Self {
    Self {
      schema_version: SCHEMA_VERSION,
      tool: TOOL.to_string(),
      repo,
      base,
      head,
      comments: Vec::new(),
      verdict: None,
    }
  }

  /// Parse and validate a document. Rejects documents from a newer schema
  /// and any unknown field (strict deserialization); re-validates and
  /// re-sorts every comment so untrusted input (an imported file, a
  /// hand-edited store) is normalized on the way in.
  pub fn parse(json: &str) -> Result<Self, ModelError> {
    let mut doc: ReviewDocument = serde_json::from_str(json).map_err(|e| ModelError::Json(e.to_string()))?;
    if doc.schema_version > SCHEMA_VERSION {
      return Err(ModelError::UnsupportedSchema { found: doc.schema_version, supported: SCHEMA_VERSION });
    }
    for c in &doc.comments {
      c.validate()?;
    }
    if let Some(v) = &doc.verdict {
      v.validate()?;
    }
    doc.sort();
    Ok(doc)
  }

  /// Canonical serialized form (pretty, trailing newline) — what exports
  /// and the localStorage round-trip use.
  pub fn to_json_pretty(&self) -> String {
    let mut s = serde_json::to_string_pretty(self).expect("document serializes: no non-string keys, no fallible types");
    s.push('\n');
    s
  }

  /// Insert a new comment or replace the one with the same `id`.
  pub fn upsert(&mut self, comment: Comment) -> Result<(), ModelError> {
    comment.validate()?;
    match self.comments.iter_mut().find(|c| c.id == comment.id) {
      Some(existing) => *existing = comment,
      None => self.comments.push(comment),
    }
    self.sort();
    Ok(())
  }

  /// Set, replace, or (with `None`) clear the review verdict.
  pub fn set_verdict(&mut self, verdict: Option<Verdict>) -> Result<(), ModelError> {
    if let Some(v) = &verdict {
      v.validate()?;
    }
    self.verdict = verdict;
    Ok(())
  }

  /// Remove a comment by id. Returns whether anything was removed.
  pub fn delete(&mut self, id: &str) -> bool {
    let before = self.comments.len();
    self.comments.retain(|c| c.id != id);
    let removed = self.comments.len() != before;
    if removed {
      self.sort();
    }
    removed
  }

  /// Merge another document's comments and verdict into this one (the
  /// import path).
  ///
  /// Semantics: union by `id`; on an id collision the comment with the
  /// **later `updated_at`** wins (RFC 3339 UTC strings compare correctly
  /// lexicographically); an exact tie keeps the existing comment. The
  /// verdict follows the same rule on its `at`: the later decision wins, a
  /// decision beats no decision, a tie keeps the existing one. Metadata
  /// (repo/refs) of `self` is kept — importing does not re-target a store.
  pub fn merge(&mut self, incoming: &ReviewDocument) {
    for inc in &incoming.comments {
      match self.comments.iter_mut().find(|c| c.id == inc.id) {
        Some(existing) => {
          if inc.updated_at > existing.updated_at {
            *existing = inc.clone();
          }
        }
        None => self.comments.push(inc.clone()),
      }
    }
    if let Some(inc) = &incoming.verdict {
      if self.verdict.as_ref().map_or(true, |cur| inc.at() > cur.at()) {
        self.verdict = Some(inc.clone());
      }
    }
    self.sort();
  }

  /// Restore the canonical deterministic order.
  pub fn sort(&mut self) {
    self.comments.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  fn refinfo(name: &str, sha_char: char) -> RefInfo {
    RefInfo { name: name.into(), sha: std::iter::repeat(sha_char).take(40).collect() }
  }

  fn doc() -> ReviewDocument {
    ReviewDocument::new("repo".into(), refinfo("main", 'a'), refinfo("feat", 'b'))
  }

  fn comment(id: &str, file: &str, line: u32, updated: &str) -> Comment {
    Comment {
      id: id.into(),
      file: file.into(),
      side: Side::New,
      line,
      text: format!("note {id}"),
      created_at: "2026-07-03T10:00:00Z".into(),
      updated_at: updated.into(),
      resolved_at: None,
    }
  }

  fn verdict_approved(at: &str) -> Verdict {
    Verdict::Approved { at: at.into() }
  }

  #[test]
  fn side_serializes_as_camelcase_variant_name() {
    assert_eq!(serde_json::to_value(Side::Old).unwrap(), serde_json::json!("Old"));
    assert_eq!(serde_json::to_value(Side::New).unwrap(), serde_json::json!("New"));
  }

  #[test]
  fn unknown_fields_are_rejected() {
    let mut v = serde_json::to_value(comment("c1", "a.rs", 5, "t")).unwrap();
    v.as_object_mut().unwrap().insert("sneaky".into(), serde_json::json!(true));
    assert!(serde_json::from_value::<Comment>(v).is_err());
  }

  #[test]
  fn upsert_inserts_then_replaces() {
    let mut d = doc();
    d.upsert(comment("c1", "a.rs", 5, "2026-07-03T10:00:00Z")).unwrap();
    let mut edited = comment("c1", "a.rs", 5, "2026-07-03T11:00:00Z");
    edited.text = "edited".into();
    d.upsert(edited).unwrap();
    assert_eq!(d.comments.len(), 1);
    assert_eq!(d.comments[0].text, "edited");
  }

  #[test]
  fn upsert_rejects_invalid() {
    let mut d = doc();
    let mut bad = comment("c1", "a.rs", 5, "2026-07-03T10:00:00Z");
    bad.text = "   ".into();
    assert!(matches!(d.upsert(bad), Err(ModelError::InvalidComment(_))));
    let mut bad = comment("c2", "a.rs", 5, "2026-07-03T10:00:00Z");
    bad.line = 0;
    assert!(d.upsert(bad).is_err());
    assert!(d.comments.is_empty());
  }

  #[test]
  fn delete_by_id() {
    let mut d = doc();
    d.upsert(comment("c1", "a.rs", 5, "2026-07-03T10:00:00Z")).unwrap();
    assert!(d.delete("c1"));
    assert!(!d.delete("c1"));
    assert!(d.comments.is_empty());
  }

  #[test]
  fn ordering_is_file_line_side_created_id() {
    let mut d = doc();
    d.upsert(comment("z", "b.rs", 1, "2026-07-03T10:00:00Z")).unwrap();
    d.upsert(comment("y", "a.rs", 9, "2026-07-03T10:00:00Z")).unwrap();
    d.upsert(comment("x", "a.rs", 2, "2026-07-03T10:00:00Z")).unwrap();
    let mut old_side = comment("w", "a.rs", 2, "2026-07-03T10:00:00Z");
    old_side.side = Side::Old;
    d.upsert(old_side).unwrap();
    let order: Vec<&str> = d.comments.iter().map(|c| c.id.as_str()).collect();
    assert_eq!(order, vec!["w", "x", "y", "z"]); // old before new on the same line
  }

  #[test]
  fn merge_unions_and_newer_updated_at_wins() {
    let mut ours = doc();
    ours.upsert(comment("shared", "a.rs", 1, "2026-07-03T10:00:00Z")).unwrap();
    ours.upsert(comment("only-ours", "a.rs", 2, "2026-07-03T10:00:00Z")).unwrap();

    let mut theirs = doc();
    let mut newer = comment("shared", "a.rs", 1, "2026-07-03T12:00:00Z");
    newer.text = "their newer edit".into();
    theirs.upsert(newer).unwrap();
    theirs.upsert(comment("only-theirs", "a.rs", 3, "2026-07-03T10:00:00Z")).unwrap();

    ours.merge(&theirs);
    assert_eq!(ours.comments.len(), 3);
    let shared = ours.comments.iter().find(|c| c.id == "shared").unwrap();
    assert_eq!(shared.text, "their newer edit");
  }

  #[test]
  fn merge_older_incoming_loses() {
    let mut ours = doc();
    let mut mine = comment("shared", "a.rs", 1, "2026-07-03T12:00:00Z");
    mine.text = "my newer edit".into();
    ours.upsert(mine).unwrap();

    let mut theirs = doc();
    theirs.upsert(comment("shared", "a.rs", 1, "2026-07-03T10:00:00Z")).unwrap();

    ours.merge(&theirs);
    assert_eq!(ours.comments[0].text, "my newer edit");
  }

  #[test]
  fn parse_rejects_newer_schema() {
    let mut d = doc();
    d.schema_version = SCHEMA_VERSION + 1;
    let json = serde_json::to_string(&d).unwrap();
    assert_eq!(
      ReviewDocument::parse(&json),
      Err(ModelError::UnsupportedSchema { found: SCHEMA_VERSION + 1, supported: SCHEMA_VERSION })
    );
  }

  #[test]
  fn parse_rejects_garbage_and_invalid_comments() {
    assert!(matches!(ReviewDocument::parse("not json"), Err(ModelError::Json(_))));
    let mut d = doc();
    d.comments.push(Comment {
      id: "".into(),
      file: "a.rs".into(),
      side: Side::New,
      line: 1,
      text: "x".into(),
      created_at: "t".into(),
      updated_at: "t".into(),
      resolved_at: None,
    });
    let json = serde_json::to_string(&d).unwrap();
    assert!(matches!(ReviewDocument::parse(&json), Err(ModelError::InvalidComment(_))));
  }

  #[test]
  fn parse_normalizes_order() {
    let mut d = doc();
    d.comments.push(comment("b", "z.rs", 9, "2026-07-03T10:00:00Z"));
    d.comments.push(comment("a", "a.rs", 1, "2026-07-03T10:00:00Z"));
    let parsed = ReviewDocument::parse(&serde_json::to_string(&d).unwrap()).unwrap();
    assert_eq!(parsed.comments[0].id, "a");
  }

  #[test]
  fn verdict_serializes_as_single_key_union_with_timestamp() {
    assert_eq!(
      serde_json::to_value(verdict_approved("2026-07-13T10:00:00Z")).unwrap(),
      serde_json::json!({ "Approved": { "at": "2026-07-13T10:00:00Z" } })
    );
    assert_eq!(
      serde_json::to_value(Verdict::ChangesRequired { at: "t".into() }).unwrap(),
      serde_json::json!({ "ChangesRequired": { "at": "t" } })
    );
  }

  #[test]
  fn set_verdict_validates_and_clears() {
    let mut d = doc();
    assert!(matches!(d.set_verdict(Some(verdict_approved("  "))), Err(ModelError::InvalidVerdict(_))));
    assert_eq!(d.verdict, None, "a rejected verdict leaves the document untouched");
    d.set_verdict(Some(verdict_approved("2026-07-13T10:00:00Z"))).unwrap();
    assert_eq!(d.verdict.as_ref().unwrap().label(), "approved");
    d.set_verdict(None).unwrap();
    assert_eq!(d.verdict, None, "clearing returns the review to in-progress");
  }

  #[test]
  fn merge_verdict_later_decision_wins() {
    // A decision beats no decision.
    let mut ours = doc();
    let mut theirs = doc();
    theirs.set_verdict(Some(verdict_approved("2026-07-13T10:00:00Z"))).unwrap();
    ours.merge(&theirs);
    assert_eq!(ours.verdict, theirs.verdict);
    // A later decision beats an earlier one.
    let mut newer = doc();
    newer.set_verdict(Some(Verdict::ChangesRequired { at: "2026-07-13T12:00:00Z".into() })).unwrap();
    ours.merge(&newer);
    assert_eq!(ours.verdict.as_ref().unwrap().label(), "changes required");
    // An earlier decision loses; no decision never clears one.
    ours.merge(&theirs);
    assert_eq!(ours.verdict, newer.verdict);
    ours.merge(&doc());
    assert_eq!(ours.verdict, newer.verdict);
  }

  #[test]
  fn resolved_comments_validate_and_roundtrip() {
    let mut d = doc();
    let mut resolved = comment("c1", "a.rs", 5, "2026-07-13T11:00:00Z");
    resolved.resolved_at = Some("2026-07-13T11:00:00Z".into());
    d.upsert(resolved).unwrap();
    let back = ReviewDocument::parse(&d.to_json_pretty()).unwrap();
    assert_eq!(back.comments[0].resolved_at.as_deref(), Some("2026-07-13T11:00:00Z"));
    // Present-but-blank is rejected; absent stays absent in the JSON.
    let mut blank = comment("c2", "a.rs", 6, "t");
    blank.resolved_at = Some("  ".into());
    assert!(matches!(d.upsert(blank), Err(ModelError::InvalidComment(_))));
    let open = comment("c3", "a.rs", 7, "t");
    d.upsert(open).unwrap();
    assert!(!serde_json::to_string(&d.comments[1]).unwrap().contains("resolved_at"));
  }

  #[test]
  fn v1_documents_parse_with_the_new_fields_defaulted() {
    // A document exactly as a v1 page wrote it: no verdict, no resolved_at.
    let v1 = r#"{
      "schema_version": 1, "tool": "packdiff", "repo": "repo",
      "base": { "name": "main", "sha": "a" }, "head": { "name": "feat", "sha": "b" },
      "comments": [ { "id": "c1", "file": "a.rs", "side": "New", "line": 5,
        "text": "note", "created_at": "t", "updated_at": "t" } ]
    }"#;
    let doc = ReviewDocument::parse(v1).unwrap();
    assert_eq!(doc.verdict, None);
    assert_eq!(doc.comments[0].resolved_at, None);
  }

  #[test]
  fn canonical_json_roundtrips() {
    let mut d = doc();
    d.upsert(comment("c1", "a.rs", 5, "2026-07-03T10:00:00Z")).unwrap();
    let json = d.to_json_pretty();
    assert!(json.ends_with('\n'));
    let back = ReviewDocument::parse(&json).unwrap();
    assert_eq!(back, d);
  }
}