Skip to main content

agentmux_srv_core/backend/agent_archive/
manifest.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The manifest of an agent archive: what is in it, with a hash per part and per chunk, and the signature of the
5//! computer that wrote it (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 4).
6//!
7//! The manifest is the only thing a reader trusts before it has read a part: it names every part, its size and the
8//! SHA-256 of each 256 KiB chunk of it, so a part is checked chunk by chunk as it is read and a chunk can be
9//! checked alone when the archive travels in chunks. It holds no map, only structs and lists, so serializing it
10//! twice gives the same bytes: that is what the signature covers.
11
12use serde::{Deserialize, Serialize};
13
14/// The `kind` of an agent archive. A bundle archive has a different one and neither importer takes the other.
15pub const KIND: &str = "agent";
16/// The format this build writes and the newest it reads.
17pub const FORMAT: u32 = 1;
18/// The size of one chunk of a part (the last one may be shorter).
19pub const CHUNK_BYTES: u64 = 256 * 1024;
20/// The name of the manifest inside the archive file. No part may have it.
21pub const MANIFEST_NAME: &str = "manifest.json";
22/// What the signature covers besides the manifest, so a signature made here cannot be read as one made for
23/// anything else the same key signs.
24pub const SIGN_DOMAIN: &[u8] = b"amx-agent-archive-v1\0";
25
26/// One file of the archive.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct Part {
30    pub path: String,
31    pub size: u64,
32    /// SHA-256 of the whole part, lowercase hex.
33    pub sha256: String,
34    /// SHA-256 of each chunk, in order, lowercase hex.
35    pub chunks: Vec<String>,
36}
37
38/// The agent the archive is of.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(deny_unknown_fields)]
41pub struct AgentInfo {
42    pub uid: String,
43    pub name: String,
44    pub slug: String,
45}
46
47/// The computer that wrote it.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct Source {
51    pub instance_id: String,
52    pub host_hint: String,
53    /// The version of AgentMux that wrote it.
54    pub app_version: String,
55    /// `windows`, `linux` or `macos`: the paths in the conversation refer to it.
56    pub os: String,
57}
58
59/// The signature of the manifest by the writing computer's instance key.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct Signature {
63    pub alg: String,
64    /// The signer's public key, standard base64. A reader says who signed; whether it trusts that key is its own
65    /// decision (a pinned computer, or not).
66    pub public_key: String,
67    /// The signature, standard base64.
68    pub value: String,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(deny_unknown_fields)]
73pub struct Manifest {
74    pub kind: String,
75    pub format: u32,
76    /// Milliseconds since the epoch.
77    pub created_at: i64,
78    pub agent: AgentInfo,
79    pub source: Source,
80    pub parts: Vec<Part>,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub signature: Option<Signature>,
83}
84
85impl Manifest {
86    /// The bytes the signature covers: the domain tag and the manifest as it is without its signature.
87    pub fn signed_bytes(&self) -> Vec<u8> {
88        let mut bare = self.clone();
89        bare.signature = None;
90        let mut out = SIGN_DOMAIN.to_vec();
91        out.extend(serde_json::to_vec(&bare).unwrap_or_default());
92        out
93    }
94
95    /// The part at `path`.
96    pub fn part(&self, path: &str) -> Option<&Part> {
97        self.parts.iter().find(|p| p.path == path)
98    }
99
100    /// The bytes of all parts, as the manifest declares them.
101    pub fn total_bytes(&self) -> u64 {
102        self.parts.iter().map(|p| p.size).sum()
103    }
104}
105
106/// Whether the manifest's signature verified.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum SignatureState {
109    /// No signature: the archive is from a computer that did not sign it, or was unsigned on purpose.
110    Unsigned,
111    /// A signature that verifies under the key it names. Whether that key is one the reader trusts is for the caller.
112    Valid { public_key: [u8; 32] },
113    /// A signature that does not verify, or is malformed. Never trusted.
114    Invalid,
115}
116
117/// The number of chunks a part of `size` bytes has.
118pub fn chunk_count(size: u64) -> u64 {
119    size.div_ceil(CHUNK_BYTES)
120}
121
122/// Whether `path` is a name a part may have: relative, `/`-separated, plain components, nothing a file system
123/// reads as something else (a parent, a drive, a device name, a trailing dot or space).
124pub fn valid_part_path(path: &str) -> bool {
125    if path.is_empty() || path.len() > 240 || path == MANIFEST_NAME {
126        return false;
127    }
128    if path.chars().any(|c| c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')) {
129        return false;
130    }
131    path.split('/').all(|part| {
132        if part.is_empty() || part == "." || part == ".." || part.ends_with('.') || part.ends_with(' ') || part.starts_with(' ') {
133            return false;
134        }
135        let stem = part.split('.').next().unwrap_or("").to_ascii_uppercase();
136        !matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$")
137            && !(stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
138    })
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn part_paths_are_plain_relative_names() {
147        for ok in ["agent.json", "memory/notes.md", "history/archive-1700.jsonl", "a/b/c.txt"] {
148            assert!(valid_part_path(ok), "{ok}");
149        }
150        for bad in [
151            "", "/abs", "../x", "a/../b", "a//b", "./a", "a\\b", "C:/x", "c:x", "a/", "con", "memory/NUL.txt", "lpt1", "a.", "a /b", "manifest.json", "x\u{0}y",
152            "a?b",
153        ] {
154            assert!(!valid_part_path(bad), "{bad:?}");
155        }
156    }
157
158    #[test]
159    fn a_part_of_one_byte_over_a_chunk_has_two_chunks() {
160        assert_eq!(chunk_count(0), 0);
161        assert_eq!(chunk_count(1), 1);
162        assert_eq!(chunk_count(CHUNK_BYTES), 1);
163        assert_eq!(chunk_count(CHUNK_BYTES + 1), 2);
164    }
165}