Skip to main content

agentstategraph_core/
commit.rs

1//! Commit — an immutable record linking a state tree to its history and metadata.
2//!
3//! This is where AgentStateGraph diverges most from git. Beyond the standard state-root
4//! and parents, a commit carries: agent identity, authority, structured intent,
5//! reasoning, confidence, and tool call provenance.
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use crate::intent::{AgentId, Authority, DeviceId, Intent, ToolCall};
11use crate::object::ObjectId;
12
13/// Maximum length (in `char`s) of `Intent::description` stored on a commit.
14/// Overlong values are silently truncated on `CommitBuilder::build` — this is
15/// advisory provenance, not identity, so rejecting would force the blame/log
16/// path into a failure mode callers don't expect.
17pub const MAX_DESCRIPTION_LEN: usize = 1024;
18
19/// Maximum length (in `char`s) of `Commit::reasoning`. Truncated silently.
20pub const MAX_REASONING_LEN: usize = 8192;
21
22/// Maximum length (in `char`s) of `Commit::agent_id`. Truncated silently.
23pub const MAX_AGENT_ID_LEN: usize = 128;
24
25/// Maximum number of tool calls recorded on a single commit. Excess tail is
26/// silently dropped on `CommitBuilder::build`.
27pub const MAX_TOOL_CALLS: usize = 256;
28
29/// Maximum length (in `char`s) of `Commit::device`. Truncated silently.
30pub const MAX_DEVICE_LEN: usize = 128;
31
32fn truncate_chars(s: &str, max: usize) -> String {
33    if s.chars().count() <= max {
34        s.to_string()
35    } else {
36        s.chars().take(max).collect()
37    }
38}
39
40/// A device id as a commit stores it: control characters dropped, capped at
41/// [`MAX_DEVICE_LEN`] chars. `None` when nothing printable is left, so an
42/// empty device hashes like no device at all.
43fn clean_device(device: &str) -> Option<String> {
44    let printable: String = device
45        .chars()
46        .filter(|c| !c.is_control())
47        .take(MAX_DEVICE_LEN)
48        .collect();
49    (!printable.is_empty()).then_some(printable)
50}
51
52/// An immutable record that links a state tree to its history and provenance metadata.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct Commit {
55    /// Content-address of this commit (BLAKE3 hash of all other fields).
56    pub id: ObjectId,
57    /// Root of the state tree at this commit.
58    pub state_root: ObjectId,
59    /// Parent commit(s). Empty for initial commit, one for normal, two+ for merge.
60    pub parents: Vec<ObjectId>,
61    /// When this commit was created.
62    pub timestamp: DateTime<Utc>,
63
64    // -- Identity: who performed this action --
65    /// The agent or human who made this state change.
66    pub agent_id: AgentId,
67    /// The device (install, machine) the change was made from, when the host
68    /// knows it: CTXone sends a per-install id. Provenance only — nothing
69    /// authorizes on it.
70    ///
71    /// Left out of the stored JSON and of the hashed fields when `None`, so a
72    /// commit without a device keeps the id it had before this field existed,
73    /// and readers older than 1.6 load commits that have one (they ignore it).
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub device: Option<DeviceId>,
76
77    // -- Authority: who authorized this action --
78    /// The authorization chain for this action.
79    pub authority: Authority,
80
81    // -- Intent: why this action was taken --
82    /// Structured intent metadata.
83    pub intent: Intent,
84
85    // -- Reasoning: how the agent decided on this approach --
86    /// Agent's chain-of-thought or explanation.
87    pub reasoning: Option<String>,
88    /// Agent's self-assessed confidence (0.0 to 1.0).
89    pub confidence: Option<f64>,
90
91    // -- Provenance: what tool calls produced this state change --
92    /// Tool calls that contributed to this state change.
93    pub tool_calls: Vec<ToolCall>,
94}
95
96impl Commit {
97    /// The content address of this commit's fields, computed the way
98    /// [`CommitBuilder::build`] computes `id`. A commit is intact when this
99    /// equals its `id`; sync and import recompute it for every commit they
100    /// receive rather than trust the sender's `id` (DESIGN.md Plan G).
101    pub fn compute_id(&self) -> ObjectId {
102        let bytes = serde_json::to_vec(&CommitHashInput {
103            state_root: &self.state_root,
104            parents: &self.parents,
105            timestamp: &self.timestamp,
106            agent_id: &self.agent_id,
107            device: &self.device,
108            authority: &self.authority,
109            intent: &self.intent,
110            reasoning: &self.reasoning,
111            confidence: &self.confidence,
112            tool_calls: &self.tool_calls,
113        })
114        .expect("commit serialization should never fail");
115        ObjectId::hash(&bytes)
116    }
117
118    /// Apply the same size caps `CommitBuilder::build` uses to a commit
119    /// loaded from storage. Idempotent — commits already within caps are
120    /// returned unchanged.
121    ///
122    /// `CommitBuilder::build` truncates on construction, but a `.db` file
123    /// seeded out-of-band (older ASG versions without caps, or a malicious
124    /// operator) may contain unbounded `description` / `reasoning` /
125    /// `agent_id` / `tool_calls`. Blame/log would otherwise replay them
126    /// verbatim to untrusted readers. Higher-level APIs that surface
127    /// commits to callers invoke this implicitly.
128    /// (security threat model v2, F3)
129    ///
130    /// Note: this mutates the commit in place and does NOT recompute the
131    /// content-addressed `id` — a commit's `id` is a historical identifier
132    /// of what was stored, and re-hashing on read would break log/blame
133    /// identity. The caps here exist purely to bound what's shown to
134    /// readers, not to rewrite history.
135    pub fn enforce_caps(&mut self) {
136        if self.agent_id.chars().count() > MAX_AGENT_ID_LEN {
137            self.agent_id = truncate_chars(&self.agent_id, MAX_AGENT_ID_LEN);
138        }
139        if let Some(device) = self.device.as_deref() {
140            let cleaned = clean_device(device);
141            if cleaned.as_deref() != Some(device) {
142                self.device = cleaned;
143            }
144        }
145        if self.intent.description.chars().count() > MAX_DESCRIPTION_LEN {
146            self.intent.description = truncate_chars(&self.intent.description, MAX_DESCRIPTION_LEN);
147        }
148        if let Some(reasoning) = self.reasoning.as_mut()
149            && reasoning.chars().count() > MAX_REASONING_LEN
150        {
151            *reasoning = truncate_chars(reasoning, MAX_REASONING_LEN);
152        }
153        if self.tool_calls.len() > MAX_TOOL_CALLS {
154            self.tool_calls.truncate(MAX_TOOL_CALLS);
155        }
156    }
157}
158
159/// Builder for creating commits. The commit ID is computed on build.
160pub struct CommitBuilder {
161    state_root: ObjectId,
162    parents: Vec<ObjectId>,
163    agent_id: AgentId,
164    device: Option<DeviceId>,
165    authority: Authority,
166    intent: Intent,
167    reasoning: Option<String>,
168    confidence: Option<f64>,
169    tool_calls: Vec<ToolCall>,
170}
171
172impl CommitBuilder {
173    /// Start building a commit with the required fields.
174    pub fn new(
175        state_root: ObjectId,
176        agent_id: impl Into<AgentId>,
177        authority: Authority,
178        intent: Intent,
179    ) -> Self {
180        Self {
181            state_root,
182            parents: Vec::new(),
183            agent_id: agent_id.into(),
184            device: None,
185            authority,
186            intent,
187            reasoning: None,
188            confidence: None,
189            tool_calls: Vec::new(),
190        }
191    }
192
193    /// Set parent commits.
194    pub fn parents(mut self, parents: Vec<ObjectId>) -> Self {
195        self.parents = parents;
196        self
197    }
198
199    /// Set a single parent commit (most common case).
200    pub fn parent(mut self, parent: ObjectId) -> Self {
201        self.parents = vec![parent];
202        self
203    }
204
205    /// Set the device the change was made from. Control characters are
206    /// dropped and the id is capped at [`MAX_DEVICE_LEN`] chars on build; an
207    /// id with nothing printable left is no device.
208    pub fn device(mut self, device: impl Into<DeviceId>) -> Self {
209        self.device = Some(device.into());
210        self
211    }
212
213    /// Set the reasoning trace.
214    pub fn reasoning(mut self, reasoning: impl Into<String>) -> Self {
215        self.reasoning = Some(reasoning.into());
216        self
217    }
218
219    /// Set the confidence score.
220    pub fn confidence(mut self, confidence: f64) -> Self {
221        self.confidence = Some(confidence.clamp(0.0, 1.0));
222        self
223    }
224
225    /// Add tool calls.
226    pub fn tool_calls(mut self, calls: Vec<ToolCall>) -> Self {
227        self.tool_calls = calls;
228        self
229    }
230
231    /// Build the commit, computing its content-addressed ID.
232    ///
233    /// Silently truncates overlong provenance fields to their caps —
234    /// `MAX_DESCRIPTION_LEN`, `MAX_REASONING_LEN`, `MAX_AGENT_ID_LEN`,
235    /// `MAX_DEVICE_LEN`, `MAX_TOOL_CALLS`. Truncation uses `chars()` so UTF-8
236    /// codepoints are never split.
237    pub fn build(self) -> Commit {
238        let timestamp = Utc::now();
239
240        // Enforce length caps up front — see the module-level MAX_* constants.
241        let agent_id = truncate_chars(&self.agent_id, MAX_AGENT_ID_LEN);
242        let device = self.device.as_deref().and_then(clean_device);
243        let mut intent = self.intent;
244        intent.description = truncate_chars(&intent.description, MAX_DESCRIPTION_LEN);
245        let reasoning = self
246            .reasoning
247            .map(|r| truncate_chars(&r, MAX_REASONING_LEN));
248        let mut tool_calls = self.tool_calls;
249        if tool_calls.len() > MAX_TOOL_CALLS {
250            tool_calls.truncate(MAX_TOOL_CALLS);
251        }
252
253        // Create the commit without the ID first
254        let mut commit = Commit {
255            id: ObjectId::from_bytes([0u8; 32]), // placeholder
256            state_root: self.state_root,
257            parents: self.parents,
258            timestamp,
259            agent_id,
260            device,
261            authority: self.authority,
262            intent,
263            reasoning,
264            confidence: self.confidence,
265            tool_calls,
266        };
267
268        // Compute the content-addressed ID from all fields
269        commit.id = commit.compute_id();
270        commit
271    }
272}
273
274/// Internal struct used for computing the commit hash.
275/// Excludes the `id` field (which is what we're computing).
276///
277/// Field order and serialization are part of every commit id: change neither.
278/// A new field must be skipped when unset, as `device` is, so commits made
279/// without it keep their ids.
280#[derive(Serialize)]
281struct CommitHashInput<'a> {
282    state_root: &'a ObjectId,
283    parents: &'a Vec<ObjectId>,
284    timestamp: &'a DateTime<Utc>,
285    agent_id: &'a AgentId,
286    #[serde(skip_serializing_if = "Option::is_none")]
287    device: &'a Option<DeviceId>,
288    authority: &'a Authority,
289    intent: &'a Intent,
290    reasoning: &'a Option<String>,
291    confidence: &'a Option<f64>,
292    tool_calls: &'a Vec<ToolCall>,
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::intent::IntentCategory;
299
300    fn test_intent() -> Intent {
301        Intent::new(IntentCategory::Checkpoint, "test commit")
302    }
303
304    fn test_authority() -> Authority {
305        Authority::simple("test-agent")
306    }
307
308    #[test]
309    fn test_commit_builder() {
310        let state_root = ObjectId::hash(b"test-state");
311        let commit = CommitBuilder::new(state_root, "agent/test", test_authority(), test_intent())
312            .reasoning("this is a test")
313            .confidence(0.95)
314            .build();
315
316        assert_eq!(commit.state_root, state_root);
317        assert_eq!(commit.agent_id, "agent/test");
318        assert_eq!(commit.reasoning, Some("this is a test".to_string()));
319        assert_eq!(commit.confidence, Some(0.95));
320        assert!(commit.parents.is_empty());
321    }
322
323    #[test]
324    fn test_commit_id_is_content_addressed() {
325        let state_root = ObjectId::hash(b"test-state");
326
327        // Two commits with different intents should have different IDs
328        let commit1 = CommitBuilder::new(
329            state_root,
330            "agent/test",
331            test_authority(),
332            Intent::new(IntentCategory::Explore, "exploring option A"),
333        )
334        .build();
335
336        let commit2 = CommitBuilder::new(
337            state_root,
338            "agent/test",
339            test_authority(),
340            Intent::new(IntentCategory::Fix, "fixing a bug"),
341        )
342        .build();
343
344        assert_ne!(
345            commit1.id, commit2.id,
346            "different commits should have different IDs"
347        );
348    }
349
350    #[test]
351    fn compute_id_matches_build_and_survives_a_json_round_trip() {
352        let commit = CommitBuilder::new(
353            ObjectId::hash(b"root"),
354            "agent/test",
355            test_authority(),
356            test_intent(),
357        )
358        .parent(ObjectId::hash(b"parent"))
359        .reasoning("why")
360        .confidence(0.3)
361        .build();
362        assert_eq!(commit.compute_id(), commit.id);
363
364        // Storage keeps commits as JSON, and sync recomputes ids from what it
365        // reads back, so the round trip must not change any hashed field.
366        let back: Commit = serde_json::from_slice(&serde_json::to_vec(&commit).unwrap()).unwrap();
367        assert_eq!(back.compute_id(), commit.id);
368
369        let mut tampered = back;
370        tampered.intent.description = "something else".into();
371        assert_ne!(tampered.compute_id(), commit.id);
372    }
373
374    #[test]
375    fn test_commit_with_parent() {
376        let parent_id = ObjectId::hash(b"parent-commit");
377        let state_root = ObjectId::hash(b"child-state");
378
379        let commit = CommitBuilder::new(state_root, "agent/test", test_authority(), test_intent())
380            .parent(parent_id)
381            .build();
382
383        assert_eq!(commit.parents, vec![parent_id]);
384    }
385
386    #[test]
387    fn test_description_truncated() {
388        let state_root = ObjectId::hash(b"test");
389        let long = "x".repeat(MAX_DESCRIPTION_LEN + 500);
390        let commit = CommitBuilder::new(
391            state_root,
392            "agent/test",
393            test_authority(),
394            Intent::new(IntentCategory::Checkpoint, long),
395        )
396        .build();
397        assert_eq!(
398            commit.intent.description.chars().count(),
399            MAX_DESCRIPTION_LEN
400        );
401    }
402
403    #[test]
404    fn test_reasoning_truncated() {
405        let state_root = ObjectId::hash(b"test");
406        let long = "r".repeat(MAX_REASONING_LEN + 10);
407        let commit = CommitBuilder::new(state_root, "agent/test", test_authority(), test_intent())
408            .reasoning(long)
409            .build();
410        assert_eq!(
411            commit.reasoning.as_ref().unwrap().chars().count(),
412            MAX_REASONING_LEN
413        );
414    }
415
416    #[test]
417    fn test_agent_id_truncated() {
418        let state_root = ObjectId::hash(b"test");
419        let long = "a".repeat(MAX_AGENT_ID_LEN + 50);
420        let commit = CommitBuilder::new(state_root, long, test_authority(), test_intent()).build();
421        assert_eq!(commit.agent_id.chars().count(), MAX_AGENT_ID_LEN);
422    }
423
424    #[test]
425    fn test_tool_calls_truncated() {
426        let state_root = ObjectId::hash(b"test");
427        let calls: Vec<ToolCall> = (0..(MAX_TOOL_CALLS + 20))
428            .map(|i| ToolCall {
429                tool_name: format!("tool_{}", i),
430                arguments: serde_json::json!({}),
431                result: None,
432                timestamp: Utc::now(),
433            })
434            .collect();
435        let commit = CommitBuilder::new(state_root, "agent/test", test_authority(), test_intent())
436            .tool_calls(calls)
437            .build();
438        assert_eq!(commit.tool_calls.len(), MAX_TOOL_CALLS);
439    }
440
441    #[test]
442    fn test_truncation_preserves_utf8_boundaries() {
443        let state_root = ObjectId::hash(b"test");
444        // 4-byte UTF-8 emoji; chars().take() must not split them.
445        let emoji_flood = "🎉".repeat(MAX_DESCRIPTION_LEN + 10);
446        let commit = CommitBuilder::new(
447            state_root,
448            "agent/test",
449            test_authority(),
450            Intent::new(IntentCategory::Checkpoint, emoji_flood),
451        )
452        .build();
453        assert_eq!(
454            commit.intent.description.chars().count(),
455            MAX_DESCRIPTION_LEN
456        );
457        // If we'd split a codepoint, the String would not round-trip through char count equal to byte/4.
458        assert!(
459            commit
460                .intent
461                .description
462                .is_char_boundary(commit.intent.description.len())
463        );
464    }
465
466    #[test]
467    fn test_enforce_caps_truncates_bypassed_builder() {
468        // Simulate a commit loaded from a `.db` written out-of-band
469        // (direct struct construction bypasses `CommitBuilder::build`).
470        let big_reasoning = "r".repeat(100_000); // ~100 KB
471        let big_desc = "d".repeat(MAX_DESCRIPTION_LEN * 4);
472        let big_agent = "a".repeat(MAX_AGENT_ID_LEN * 10);
473        let big_tools: Vec<ToolCall> = (0..(MAX_TOOL_CALLS * 2))
474            .map(|i| ToolCall {
475                tool_name: format!("t{}", i),
476                arguments: serde_json::json!({}),
477                result: None,
478                timestamp: Utc::now(),
479            })
480            .collect();
481
482        let mut commit = Commit {
483            id: ObjectId::hash(b"test"),
484            state_root: ObjectId::hash(b"state"),
485            parents: vec![],
486            timestamp: Utc::now(),
487            agent_id: big_agent,
488            device: Some(format!("dev\u{7}{}", "d".repeat(MAX_DEVICE_LEN * 2))),
489            authority: test_authority(),
490            intent: Intent::new(IntentCategory::Checkpoint, big_desc),
491            reasoning: Some(big_reasoning),
492            confidence: Some(0.5),
493            tool_calls: big_tools,
494        };
495
496        commit.enforce_caps();
497
498        assert_eq!(commit.agent_id.chars().count(), MAX_AGENT_ID_LEN);
499        assert_eq!(
500            commit.intent.description.chars().count(),
501            MAX_DESCRIPTION_LEN
502        );
503        assert_eq!(
504            commit.reasoning.as_ref().unwrap().chars().count(),
505            MAX_REASONING_LEN
506        );
507        assert_eq!(commit.tool_calls.len(), MAX_TOOL_CALLS);
508        let device = commit.device.as_deref().unwrap();
509        assert_eq!(device.chars().count(), MAX_DEVICE_LEN);
510        assert!(device.starts_with("devd"), "control character dropped");
511    }
512
513    #[test]
514    fn test_enforce_caps_is_idempotent() {
515        // A commit already within caps must be unchanged.
516        let commit_orig = CommitBuilder::new(
517            ObjectId::hash(b"s"),
518            "agent/test",
519            test_authority(),
520            test_intent(),
521        )
522        .reasoning("short")
523        .device("0123456789abcdef0123456789abcdef")
524        .build();
525        let mut commit = commit_orig.clone();
526        commit.enforce_caps();
527        assert_eq!(commit.agent_id, commit_orig.agent_id);
528        assert_eq!(commit.intent.description, commit_orig.intent.description);
529        assert_eq!(commit.reasoning, commit_orig.reasoning);
530        assert_eq!(commit.device, commit_orig.device);
531        assert_eq!(commit.tool_calls.len(), commit_orig.tool_calls.len());
532    }
533
534    /// The hashed fields exactly as they were before `device` existed (1.5.x).
535    #[derive(Serialize)]
536    struct HashInputBeforeDevice<'a> {
537        state_root: &'a ObjectId,
538        parents: &'a Vec<ObjectId>,
539        timestamp: &'a DateTime<Utc>,
540        agent_id: &'a AgentId,
541        authority: &'a Authority,
542        intent: &'a Intent,
543        reasoning: &'a Option<String>,
544        confidence: &'a Option<f64>,
545        tool_calls: &'a Vec<ToolCall>,
546    }
547
548    fn hash_input_before_device(c: &Commit) -> Vec<u8> {
549        serde_json::to_vec(&HashInputBeforeDevice {
550            state_root: &c.state_root,
551            parents: &c.parents,
552            timestamp: &c.timestamp,
553            agent_id: &c.agent_id,
554            authority: &c.authority,
555            intent: &c.intent,
556            reasoning: &c.reasoning,
557            confidence: &c.confidence,
558            tool_calls: &c.tool_calls,
559        })
560        .unwrap()
561    }
562
563    fn hash_input(c: &Commit) -> Vec<u8> {
564        serde_json::to_vec(&CommitHashInput {
565            state_root: &c.state_root,
566            parents: &c.parents,
567            timestamp: &c.timestamp,
568            agent_id: &c.agent_id,
569            device: &c.device,
570            authority: &c.authority,
571            intent: &c.intent,
572            reasoning: &c.reasoning,
573            confidence: &c.confidence,
574            tool_calls: &c.tool_calls,
575        })
576        .unwrap()
577    }
578
579    #[test]
580    fn a_commit_without_a_device_hashes_as_before() {
581        let commit = CommitBuilder::new(
582            ObjectId::hash(b"root"),
583            "agent/test",
584            test_authority(),
585            test_intent(),
586        )
587        .parent(ObjectId::hash(b"parent"))
588        .reasoning("why")
589        .confidence(0.4)
590        .tool_calls(vec![ToolCall {
591            tool_name: "set".into(),
592            arguments: serde_json::json!({"path": "/a"}),
593            result: None,
594            timestamp: Utc::now(),
595        }])
596        .build();
597        assert_eq!(commit.device, None);
598        assert_eq!(hash_input(&commit), hash_input_before_device(&commit));
599        assert_eq!(
600            commit.id,
601            ObjectId::hash(&hash_input_before_device(&commit)),
602            "the id a 1.5 build would give this commit"
603        );
604        // And the stored JSON has no device key at all.
605        let stored = serde_json::to_value(&commit).unwrap();
606        assert!(stored.get("device").is_none(), "{stored}");
607    }
608
609    #[test]
610    fn a_device_is_part_of_the_id() {
611        let commit = CommitBuilder::new(
612            ObjectId::hash(b"root"),
613            "agent/test",
614            test_authority(),
615            test_intent(),
616        )
617        .device("0123456789abcdef0123456789abcdef")
618        .build();
619        assert_eq!(
620            commit.device.as_deref(),
621            Some("0123456789abcdef0123456789abcdef")
622        );
623        assert_eq!(commit.compute_id(), commit.id);
624        assert_ne!(hash_input(&commit), hash_input_before_device(&commit));
625
626        let mut other = commit.clone();
627        other.device = Some("fedcba9876543210fedcba9876543210".into());
628        assert_ne!(other.compute_id(), commit.id);
629        other.device = None;
630        assert_ne!(other.compute_id(), commit.id);
631
632        // The device survives the JSON round trip storage and sync use.
633        let back: Commit = serde_json::from_slice(&serde_json::to_vec(&commit).unwrap()).unwrap();
634        assert_eq!(back.device, commit.device);
635        assert_eq!(back.compute_id(), commit.id);
636    }
637
638    #[test]
639    fn a_commit_stored_before_devices_still_loads() {
640        // A commit as 1.5.x stored it: no `device` key.
641        let commit = CommitBuilder::new(
642            ObjectId::hash(b"root"),
643            "agent/test",
644            test_authority(),
645            test_intent(),
646        )
647        .build();
648        let mut stored = serde_json::to_value(&commit).unwrap();
649        stored.as_object_mut().unwrap().remove("device");
650        let back: Commit = serde_json::from_value(stored).unwrap();
651        assert_eq!(back.device, None);
652        assert_eq!(back.compute_id(), commit.id);
653    }
654
655    #[test]
656    fn a_reader_without_devices_ignores_one() {
657        // What a 1.5.x reader does with a commit that has a device: serde
658        // skips the unknown key (nothing in Commit denies unknown fields).
659        #[derive(Deserialize)]
660        #[allow(dead_code)]
661        struct CommitBeforeDevice {
662            id: ObjectId,
663            state_root: ObjectId,
664            parents: Vec<ObjectId>,
665            timestamp: DateTime<Utc>,
666            agent_id: AgentId,
667            authority: Authority,
668            intent: Intent,
669            reasoning: Option<String>,
670            confidence: Option<f64>,
671            tool_calls: Vec<ToolCall>,
672        }
673        let commit = CommitBuilder::new(
674            ObjectId::hash(b"root"),
675            "agent/test",
676            test_authority(),
677            test_intent(),
678        )
679        .device("laptop-1")
680        .build();
681        let old: CommitBeforeDevice =
682            serde_json::from_slice(&serde_json::to_vec(&commit).unwrap()).unwrap();
683        assert_eq!(old.id, commit.id);
684        assert_eq!(old.agent_id, commit.agent_id);
685    }
686
687    #[test]
688    fn device_is_capped_and_cleaned() {
689        let build = |device: &str| {
690            CommitBuilder::new(
691                ObjectId::hash(b"s"),
692                "agent/test",
693                test_authority(),
694                test_intent(),
695            )
696            .device(device)
697            .build()
698        };
699        let long = build(&"é".repeat(MAX_DEVICE_LEN + 7));
700        assert_eq!(
701            long.device.as_deref().unwrap().chars().count(),
702            MAX_DEVICE_LEN
703        );
704        assert_eq!(
705            build("dev\nice\u{0}\t\u{1b}[31m").device.as_deref(),
706            Some("device[31m")
707        );
708        // Nothing printable left is no device, and hashes like none.
709        let blank = build("\n\r\t");
710        assert_eq!(blank.device, None);
711        assert_eq!(hash_input(&blank), hash_input_before_device(&blank));
712        assert_eq!(build("").device, None);
713    }
714
715    #[test]
716    fn test_confidence_clamped() {
717        let state_root = ObjectId::hash(b"test");
718        let commit = CommitBuilder::new(state_root, "agent/test", test_authority(), test_intent())
719            .confidence(1.5) // over 1.0
720            .build();
721
722        assert_eq!(commit.confidence, Some(1.0));
723    }
724}