1use crate::error::{GraphError, Result};
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7use std::fmt;
8use std::str::FromStr;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17#[serde(try_from = "String", into = "String")]
18pub struct CommitId([u8; 32]);
19
20impl CommitId {
21 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
25 Self(bytes)
26 }
27
28 pub const fn as_bytes(&self) -> &[u8; 32] {
30 &self.0
31 }
32
33 pub fn to_hex(&self) -> String {
35 hex::encode(self.0)
36 }
37}
38
39impl fmt::Display for CommitId {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "{}", self.to_hex())
42 }
43}
44
45impl fmt::LowerHex for CommitId {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 for byte in &self.0 {
49 write!(f, "{byte:02x}")?;
50 }
51 Ok(())
52 }
53}
54
55impl fmt::UpperHex for CommitId {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 for byte in &self.0 {
59 write!(f, "{byte:02X}")?;
60 }
61 Ok(())
62 }
63}
64
65impl fmt::Octal for CommitId {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 for (i, byte) in self.0.iter().enumerate() {
71 if i > 0 {
72 f.write_str(".")?;
73 }
74 write!(f, "{byte:03o}")?;
75 }
76 Ok(())
77 }
78}
79
80impl fmt::Binary for CommitId {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 for (i, byte) in self.0.iter().enumerate() {
86 if i > 0 {
87 f.write_str(".")?;
88 }
89 write!(f, "{byte:08b}")?;
90 }
91 Ok(())
92 }
93}
94
95impl FromStr for CommitId {
96 type Err = GraphError;
97
98 fn from_str(s: &str) -> Result<Self> {
99 let bytes = hex::decode(s).map_err(|e| GraphError::InvalidCommitId(format!("{s}: {e}")))?;
100 if bytes.len() != 32 {
101 return Err(GraphError::InvalidCommitId(format!(
102 "expected 32 bytes, got {}",
103 bytes.len()
104 )));
105 }
106 let mut arr = [0u8; 32];
107 arr.copy_from_slice(&bytes);
108 Ok(CommitId(arr))
109 }
110}
111
112impl TryFrom<String> for CommitId {
113 type Error = GraphError;
114 fn try_from(value: String) -> Result<Self> {
115 CommitId::from_str(&value)
116 }
117}
118
119impl From<CommitId> for String {
120 fn from(value: CommitId) -> Self {
121 value.to_hex()
122 }
123}
124
125mod hex {
127 pub fn encode(bytes: [u8; 32]) -> String {
128 bytes.iter().map(|b| format!("{b:02x}")).collect()
129 }
130
131 #[derive(Debug)]
132 pub struct HexError(pub String);
133 impl std::fmt::Display for HexError {
134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 write!(f, "invalid hex: {}", self.0)
136 }
137 }
138
139 pub fn decode(s: &str) -> std::result::Result<Vec<u8>, HexError> {
140 if !s.len().is_multiple_of(2) {
141 return Err(HexError(s.to_string()));
142 }
143 let mut out = Vec::with_capacity(s.len() / 2);
144 let bytes = s.as_bytes();
145 for chunk in bytes.chunks(2) {
146 let hi = (chunk[0] as char)
147 .to_digit(16)
148 .ok_or_else(|| HexError(s.to_string()))?;
149 let lo = (chunk[1] as char)
150 .to_digit(16)
151 .ok_or_else(|| HexError(s.to_string()))?;
152 out.push(((hi << 4) | lo) as u8);
153 }
154 Ok(out)
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum Author {
162 #[default]
163 User,
164 Assistant,
165 Tool,
166 System,
167}
168
169impl fmt::Display for Author {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 let s = match self {
172 Author::User => "user",
173 Author::Assistant => "assistant",
174 Author::Tool => "tool",
175 Author::System => "system",
176 };
177 write!(f, "{s}")
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(tag = "kind", rename_all = "snake_case")]
190pub enum Delta {
191 Message {
192 content: String,
193 },
194 ToolCall {
195 call_id: String,
196 name: String,
197 arguments: serde_json::Value,
198 },
199 ToolResult {
200 call_id: String,
201 result: serde_json::Value,
202 },
203 Compaction {
204 replaces: Vec<CommitId>,
205 summary: String,
206 },
207 Merge {
211 strategy: MergeStrategy,
212 },
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
221#[serde(rename_all = "snake_case")]
222pub enum MergeStrategy {
223 #[default]
226 RecordOnly,
227 PreferOther,
229}
230
231#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
233pub struct TokenUsage {
234 pub prompt_tokens: u64,
235 pub completion_tokens: u64,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
240pub struct Metadata {
241 pub model_id: Option<String>,
242 pub token_usage: Option<TokenUsage>,
243 pub timestamp: DateTime<Utc>,
244 pub tags: BTreeMap<String, String>,
247}
248
249impl Metadata {
250 pub fn new(timestamp: DateTime<Utc>) -> Self {
251 Self {
252 model_id: None,
253 token_usage: None,
254 timestamp,
255 tags: BTreeMap::new(),
256 }
257 }
258
259 pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
260 self.tags.insert(key.into(), value.into());
261 self
262 }
263}
264
265#[derive(Serialize)]
268struct CommitContent<'a> {
269 parent_ids: &'a [CommitId],
270 author: &'a Author,
271 delta: &'a Delta,
272 metadata: &'a Metadata,
273}
274
275pub fn compute_commit_id(
278 parent_ids: &[CommitId],
279 author: &Author,
280 delta: &Delta,
281 metadata: &Metadata,
282) -> CommitId {
283 let content = CommitContent {
284 parent_ids,
285 author,
286 delta,
287 metadata,
288 };
289 let bytes = serde_json::to_vec(&content).expect("commit content is always serializable");
292 CommitId(*blake3::hash(&bytes).as_bytes())
293}
294
295#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
297pub struct Commit {
298 pub id: CommitId,
299 pub parent_ids: Vec<CommitId>,
300 pub author: Author,
301 pub delta: Delta,
302 pub metadata: Metadata,
303}
304
305impl Commit {
306 pub fn new(
308 parent_ids: Vec<CommitId>,
309 author: Author,
310 delta: Delta,
311 metadata: Metadata,
312 ) -> Self {
313 let id = compute_commit_id(&parent_ids, &author, &delta, &metadata);
314 Self {
315 id,
316 parent_ids,
317 author,
318 delta,
319 metadata,
320 }
321 }
322
323 pub fn is_root(&self) -> bool {
324 self.parent_ids.is_empty()
325 }
326
327 pub fn is_merge(&self) -> bool {
328 self.parent_ids.len() > 1
329 }
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335
336 fn ts() -> DateTime<Utc> {
337 DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
338 .unwrap()
339 .with_timezone(&Utc)
340 }
341
342 #[test]
343 fn identical_content_yields_identical_commit_id() {
344 let delta = Delta::Message {
345 content: "hello".into(),
346 };
347 let meta = Metadata::new(ts()).with_tag("step", "planning");
348 let id1 = compute_commit_id(&[], &Author::User, &delta, &meta);
349 let id2 = compute_commit_id(&[], &Author::User, &delta, &meta);
350 assert_eq!(id1, id2);
351 }
352
353 #[test]
354 fn different_delta_content_yields_different_commit_id() {
355 let meta = Metadata::new(ts());
356 let id1 = compute_commit_id(
357 &[],
358 &Author::User,
359 &Delta::Message {
360 content: "a".into(),
361 },
362 &meta,
363 );
364 let id2 = compute_commit_id(
365 &[],
366 &Author::User,
367 &Delta::Message {
368 content: "b".into(),
369 },
370 &meta,
371 );
372 assert_ne!(id1, id2);
373 }
374
375 #[test]
376 fn tag_insertion_order_does_not_affect_commit_id() {
377 let delta = Delta::Message {
378 content: "hi".into(),
379 };
380 let mut meta_a = Metadata::new(ts());
381 meta_a.tags.insert("a".into(), "1".into());
382 meta_a.tags.insert("b".into(), "2".into());
383
384 let mut meta_b = Metadata::new(ts());
385 meta_b.tags.insert("b".into(), "2".into());
386 meta_b.tags.insert("a".into(), "1".into());
387
388 let id_a = compute_commit_id(&[], &Author::User, &delta, &meta_a);
389 let id_b = compute_commit_id(&[], &Author::User, &delta, &meta_b);
390 assert_eq!(id_a, id_b);
391 }
392
393 #[test]
394 fn different_parent_order_yields_different_commit_id() {
395 let delta = Delta::Message {
396 content: "merge".into(),
397 };
398 let meta = Metadata::new(ts());
399 let p1 = CommitId::from_bytes([1u8; 32]);
400 let p2 = CommitId::from_bytes([2u8; 32]);
401 let id_ab = compute_commit_id(&[p1, p2], &Author::System, &delta, &meta);
402 let id_ba = compute_commit_id(&[p2, p1], &Author::System, &delta, &meta);
403 assert_ne!(
404 id_ab, id_ba,
405 "parent order is semantically significant for merges"
406 );
407 }
408
409 #[test]
410 fn commit_id_round_trips_through_hex_string() {
411 let id = CommitId::from_bytes([42u8; 32]);
412 let hex = id.to_hex();
413 let parsed: CommitId = hex.parse().unwrap();
414 assert_eq!(id, parsed);
415 }
416
417 #[test]
418 fn commit_id_from_str_rejects_wrong_length() {
419 let err = CommitId::from_str("abcd").unwrap_err();
420 assert!(matches!(err, GraphError::InvalidCommitId(_)));
421 }
422
423 #[test]
424 fn commit_id_from_str_rejects_non_hex_characters() {
425 let bad = "zz".repeat(32);
426 let err = CommitId::from_str(&bad).unwrap_err();
427 assert!(matches!(err, GraphError::InvalidCommitId(_)));
428 }
429
430 #[test]
431 fn root_commit_has_no_parents_and_is_recognized_as_root() {
432 let commit = Commit::new(
433 vec![],
434 Author::System,
435 Delta::Message {
436 content: "init".into(),
437 },
438 Metadata::new(ts()),
439 );
440 assert!(commit.is_root());
441 assert!(!commit.is_merge());
442 }
443
444 #[test]
445 fn commit_with_two_parents_is_recognized_as_merge() {
446 let commit = Commit::new(
447 vec![CommitId::from_bytes([1; 32]), CommitId::from_bytes([2; 32])],
448 Author::System,
449 Delta::Message {
450 content: "merge".into(),
451 },
452 Metadata::new(ts()),
453 );
454 assert!(commit.is_merge());
455 assert!(!commit.is_root());
456 }
457
458 #[test]
459 fn committing_identical_content_twice_is_idempotent_at_the_id_level() {
460 let meta = Metadata::new(ts());
461 let c1 = Commit::new(
462 vec![],
463 Author::User,
464 Delta::Message {
465 content: "x".into(),
466 },
467 meta.clone(),
468 );
469 let c2 = Commit::new(
470 vec![],
471 Author::User,
472 Delta::Message {
473 content: "x".into(),
474 },
475 meta,
476 );
477 assert_eq!(c1.id, c2.id);
478 }
479
480 #[test]
481 fn empty_message_delta_is_representable_and_hashes_consistently() {
482 let meta = Metadata::new(ts());
483 let delta = Delta::Message {
484 content: String::new(),
485 };
486 let id1 = compute_commit_id(&[], &Author::User, &delta, &meta);
487 let id2 = compute_commit_id(&[], &Author::User, &delta, &meta);
488 assert_eq!(id1, id2);
489 }
490}