smith-protocol 0.1.2

Shared protocol definitions for agent execution system
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
//! Policy ABI Version Management for Smith Platform
//!
//! This module provides versioning and compatibility checking for capability bundles,
//! ensuring deterministic startup failures when ABI mismatches occur.

use serde::{Deserialize, Serialize};
use std::fmt;
use thiserror::Error;

/// Current supported Policy ABI version
/// This must be incremented when capability bundle schema changes in breaking ways
pub const CURRENT_POLICY_ABI_VERSION: u32 = 1;

/// Policy ABI version information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PolicyAbiVersion {
    /// Major version - incompatible changes
    pub major: u32,
    /// Minor version - backward compatible additions
    pub minor: u32,
    /// Patch version - bug fixes and clarifications
    pub patch: u32,
}

impl PolicyAbiVersion {
    /// Create a new PolicyAbiVersion
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Get the current supported ABI version
    pub fn current() -> Self {
        Self::new(CURRENT_POLICY_ABI_VERSION, 0, 0)
    }

    /// Check if this version is compatible with the current ABI
    pub fn is_compatible(&self) -> bool {
        self.major == CURRENT_POLICY_ABI_VERSION
    }

    /// Check if this version is exactly the current version
    pub fn is_current(&self) -> bool {
        *self == Self::current()
    }

    /// Convert to version string for display
    pub fn to_version_string(&self) -> String {
        format!("{}.{}.{}", self.major, self.minor, self.patch)
    }

    /// Parse from version string (e.g., "1.0.0")
    pub fn from_version_string(version: &str) -> Result<Self, PolicyAbiError> {
        let parts: Vec<&str> = version.split('.').collect();
        if parts.len() != 3 {
            return Err(PolicyAbiError::InvalidVersionFormat(version.to_string()));
        }

        let major = parts[0]
            .parse::<u32>()
            .map_err(|_| PolicyAbiError::InvalidVersionFormat(version.to_string()))?;
        let minor = parts[1]
            .parse::<u32>()
            .map_err(|_| PolicyAbiError::InvalidVersionFormat(version.to_string()))?;
        let patch = parts[2]
            .parse::<u32>()
            .map_err(|_| PolicyAbiError::InvalidVersionFormat(version.to_string()))?;

        Ok(Self::new(major, minor, patch))
    }
}

impl fmt::Display for PolicyAbiVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_version_string())
    }
}

/// Capability bundle header with ABI version information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityBundleHeader {
    /// ABI version of this bundle
    pub abi_version: PolicyAbiVersion,
    /// Bundle format version (separate from ABI)
    pub bundle_version: String,
    /// Bundle creation timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// SHA256 digest of bundle content (excluding header)
    pub content_digest: String,
    /// Bundle metadata
    pub metadata: CapabilityBundleMetadata,
}

/// Metadata about the capability bundle
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityBundleMetadata {
    /// Human-readable bundle name
    pub name: String,
    /// Bundle description
    pub description: Option<String>,
    /// Organization that created this bundle
    pub organization: Option<String>,
    /// Git commit hash when bundle was created
    pub git_commit: Option<String>,
    /// Build environment information
    pub build_info: Option<String>,
}

/// Policy ABI validation errors
#[derive(Debug, Error)]
pub enum PolicyAbiError {
    #[error(
        "Incompatible Policy ABI version: bundle={bundle_version}, supported={supported_version}"
    )]
    IncompatibleVersion {
        bundle_version: PolicyAbiVersion,
        supported_version: PolicyAbiVersion,
    },

    #[error("Invalid version format: {0}")]
    InvalidVersionFormat(String),

    #[error("Missing ABI version in capability bundle")]
    MissingAbiVersion,

    #[error("Capability bundle validation failed: {0}")]
    ValidationFailed(String),

    #[error("Capability bundle deserialization failed: {0}")]
    DeserializationFailed(String),
}

/// Policy ABI validator for startup checks
pub struct PolicyAbiValidator;

impl PolicyAbiValidator {
    /// Validate capability bundle ABI version on startup
    ///
    /// This function MUST be called during admission controller startup.
    /// It will return an error if the bundle ABI version is incompatible,
    /// causing deterministic startup failure.
    pub fn validate_startup_compatibility(
        bundle_json: &str,
    ) -> Result<CapabilityBundleHeader, PolicyAbiError> {
        // Parse just the header to check ABI version
        let bundle_value: serde_json::Value = serde_json::from_str(bundle_json)
            .map_err(|e| PolicyAbiError::DeserializationFailed(e.to_string()))?;

        // Extract ABI version from bundle
        let abi_version = Self::extract_abi_version(&bundle_value)?;

        // Check compatibility
        if !abi_version.is_compatible() {
            return Err(PolicyAbiError::IncompatibleVersion {
                bundle_version: abi_version.clone(),
                supported_version: PolicyAbiVersion::current(),
            });
        }

        // Parse full header if ABI is compatible
        let header: CapabilityBundleHeader = serde_json::from_value(
            bundle_value
                .get("header")
                .ok_or(PolicyAbiError::MissingAbiVersion)?
                .clone(),
        )
        .map_err(|e| PolicyAbiError::DeserializationFailed(e.to_string()))?;

        Ok(header)
    }

    /// Extract ABI version from bundle JSON
    fn extract_abi_version(
        bundle_value: &serde_json::Value,
    ) -> Result<PolicyAbiVersion, PolicyAbiError> {
        let header = bundle_value
            .get("header")
            .ok_or(PolicyAbiError::MissingAbiVersion)?;

        let abi_version: PolicyAbiVersion = serde_json::from_value(
            header
                .get("abi_version")
                .ok_or(PolicyAbiError::MissingAbiVersion)?
                .clone(),
        )
        .map_err(|e| PolicyAbiError::DeserializationFailed(e.to_string()))?;

        Ok(abi_version)
    }

    /// Generate ABI change detection hash for CI validation
    ///
    /// This hash should be stored in CI and compared against new builds
    /// to detect breaking ABI changes.
    pub fn generate_abi_hash() -> String {
        use sha2::{Digest, Sha256};

        // Create deterministic representation of current ABI
        let abi_repr = format!(
            "POLICY_ABI_V{}_CURRENT_VERSION_{}_FIELDS_{}",
            CURRENT_POLICY_ABI_VERSION,
            PolicyAbiVersion::current().to_version_string(),
            "header,abi_version,bundle_version,created_at,content_digest,metadata"
        );

        let mut hasher = Sha256::new();
        hasher.update(abi_repr.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// Validate that a capability bundle schema hasn't changed in breaking ways
    pub fn validate_abi_stability(old_hash: &str, new_hash: &str) -> Result<(), PolicyAbiError> {
        if old_hash != new_hash {
            return Err(PolicyAbiError::ValidationFailed(format!(
                "ABI hash mismatch: expected {} but got {}. This indicates a breaking change to the Policy ABI.",
                old_hash, new_hash
            )));
        }
        Ok(())
    }
}

/// Helper trait for capability bundle validation
pub trait CapabilityBundleValidation {
    /// Validate ABI compatibility during bundle loading
    fn validate_abi_compatibility(&self) -> Result<(), PolicyAbiError>;
}

// Implementation for any type that can provide capability bundle JSON
impl CapabilityBundleValidation for String {
    fn validate_abi_compatibility(&self) -> Result<(), PolicyAbiError> {
        PolicyAbiValidator::validate_startup_compatibility(self)?;
        Ok(())
    }
}

impl CapabilityBundleValidation for &str {
    fn validate_abi_compatibility(&self) -> Result<(), PolicyAbiError> {
        PolicyAbiValidator::validate_startup_compatibility(self)?;
        Ok(())
    }
}

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

    #[test]
    fn test_policy_abi_version_creation() {
        let version = PolicyAbiVersion::new(1, 2, 3);
        assert_eq!(version.major, 1);
        assert_eq!(version.minor, 2);
        assert_eq!(version.patch, 3);
        assert_eq!(version.to_version_string(), "1.2.3");
    }

    #[test]
    fn test_current_version() {
        let current = PolicyAbiVersion::current();
        assert_eq!(current.major, CURRENT_POLICY_ABI_VERSION);
        assert_eq!(current.minor, 0);
        assert_eq!(current.patch, 0);
    }

    #[test]
    fn test_version_compatibility() {
        let current = PolicyAbiVersion::current();
        assert!(current.is_compatible());
        assert!(current.is_current());

        let incompatible = PolicyAbiVersion::new(CURRENT_POLICY_ABI_VERSION + 1, 0, 0);
        assert!(!incompatible.is_compatible());
        assert!(!incompatible.is_current());

        let older_compatible = PolicyAbiVersion::new(CURRENT_POLICY_ABI_VERSION, 1, 5);
        assert!(older_compatible.is_compatible());
        assert!(!older_compatible.is_current());
    }

    #[test]
    fn test_version_string_parsing() {
        let version = PolicyAbiVersion::from_version_string("2.1.5").unwrap();
        assert_eq!(version.major, 2);
        assert_eq!(version.minor, 1);
        assert_eq!(version.patch, 5);

        // Test invalid formats
        assert!(PolicyAbiVersion::from_version_string("1.2").is_err());
        assert!(PolicyAbiVersion::from_version_string("invalid").is_err());
        assert!(PolicyAbiVersion::from_version_string("1.x.3").is_err());
    }

    #[test]
    fn test_compatible_bundle_validation() {
        let current_version = PolicyAbiVersion::current();
        let bundle_json = json!({
            "header": {
                "abi_version": current_version,
                "bundle_version": "1.0.0",
                "created_at": "2024-01-01T00:00:00Z",
                "content_digest": "abc123",
                "metadata": {
                    "name": "test-bundle",
                    "description": "Test capability bundle",
                    "organization": "Smith Team",
                    "git_commit": "abc123",
                    "build_info": "test-build"
                }
            },
            "atoms": {},
            "macros": {},
            "playbooks": {}
        })
        .to_string();

        let result = PolicyAbiValidator::validate_startup_compatibility(&bundle_json);
        assert!(result.is_ok());

        let header = result.unwrap();
        assert_eq!(header.abi_version, current_version);
        assert_eq!(header.metadata.name, "test-bundle");
    }

    #[test]
    fn test_incompatible_bundle_validation() {
        let incompatible_version = PolicyAbiVersion::new(CURRENT_POLICY_ABI_VERSION + 1, 0, 0);
        let bundle_json = json!({
            "header": {
                "abi_version": incompatible_version,
                "bundle_version": "2.0.0",
                "created_at": "2024-01-01T00:00:00Z",
                "content_digest": "def456",
                "metadata": {
                    "name": "future-bundle"
                }
            }
        })
        .to_string();

        let result = PolicyAbiValidator::validate_startup_compatibility(&bundle_json);
        assert!(result.is_err());

        match result.unwrap_err() {
            PolicyAbiError::IncompatibleVersion {
                bundle_version,
                supported_version,
            } => {
                assert_eq!(bundle_version, incompatible_version);
                assert_eq!(supported_version, PolicyAbiVersion::current());
            }
            _ => panic!("Expected IncompatibleVersion error"),
        }
    }

    #[test]
    fn test_missing_abi_version() {
        let bundle_json = json!({
            "header": {
                "bundle_version": "1.0.0"
                // Missing abi_version
            }
        })
        .to_string();

        let result = PolicyAbiValidator::validate_startup_compatibility(&bundle_json);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PolicyAbiError::MissingAbiVersion
        ));
    }

    #[test]
    fn test_abi_hash_generation() {
        let hash1 = PolicyAbiValidator::generate_abi_hash();
        let hash2 = PolicyAbiValidator::generate_abi_hash();

        // Hash should be deterministic
        assert_eq!(hash1, hash2);

        // Hash should be valid SHA256 (64 hex chars)
        assert_eq!(hash1.len(), 64);
        assert!(hash1.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_abi_stability_validation() {
        let hash = "abc123def456";

        // Same hash should validate
        assert!(PolicyAbiValidator::validate_abi_stability(hash, hash).is_ok());

        // Different hash should fail
        let result = PolicyAbiValidator::validate_abi_stability(hash, "different");
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PolicyAbiError::ValidationFailed(_)
        ));
    }

    #[test]
    fn test_bundle_validation_trait() {
        let current_version = PolicyAbiVersion::current();
        let bundle_json = json!({
            "header": {
                "abi_version": current_version,
                "bundle_version": "1.0.0",
                "created_at": "2024-01-01T00:00:00Z",
                "content_digest": "test123",
                "metadata": {
                    "name": "trait-test-bundle"
                }
            }
        })
        .to_string();

        // Test trait implementation
        assert!(bundle_json.validate_abi_compatibility().is_ok());
        assert!(bundle_json.as_str().validate_abi_compatibility().is_ok());
    }

    #[test]
    fn test_capability_bundle_header_serialization() {
        let header = CapabilityBundleHeader {
            abi_version: PolicyAbiVersion::current(),
            bundle_version: "1.0.0".to_string(),
            created_at: chrono::Utc::now(),
            content_digest: "test-digest".to_string(),
            metadata: CapabilityBundleMetadata {
                name: "test-bundle".to_string(),
                description: Some("Test description".to_string()),
                organization: Some("Smith Team".to_string()),
                git_commit: Some("abc123".to_string()),
                build_info: Some("test-build".to_string()),
            },
        };

        // Test serialization roundtrip
        let json = serde_json::to_string(&header).unwrap();
        let deserialized: CapabilityBundleHeader = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.abi_version, header.abi_version);
        assert_eq!(deserialized.bundle_version, header.bundle_version);
        assert_eq!(deserialized.metadata.name, header.metadata.name);
    }
}