Skip to main content

agentic_graph_spec/
canonical.rs

1use base64::{Engine as _, engine::general_purpose::STANDARD};
2use sha2::{Digest, Sha256};
3use thiserror::Error;
4
5use crate::Document;
6
7/// Failure while producing canonical JSON.
8#[derive(Debug, Error)]
9pub enum CanonicalError {
10    /// The value could not be serialized.
11    #[error("canonical JSON error: {0}")]
12    Serialize(#[from] serde_json::Error),
13}
14
15/// Serializes a value using RFC 8785 JSON Canonicalization Scheme rules.
16pub fn canonical_json(value: &impl serde::Serialize) -> Result<Vec<u8>, CanonicalError> {
17    Ok(serde_jcs::to_vec(value)?)
18}
19
20/// Computes the AGS `sha256-<base64>` identity of a graph document.
21pub fn graph_digest(document: &Document) -> Result<String, CanonicalError> {
22    let digest = Sha256::digest(canonical_json(document)?);
23    Ok(format!("sha256-{}", STANDARD.encode(digest)))
24}