agentd 0.1.2

Agent daemon for secure capability execution with pluggable isolation backends
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
use anyhow::{Context, Result};
use jsonschema::{Draft, JSONSchema};
use serde_json::{json, Value};
use std::collections::HashMap;
use tracing::{debug, info, warn};

/// Schema validator for capability-specific intent validation
pub struct SchemaValidator {
    schemas: HashMap<String, JSONSchema>,
    schema_values: HashMap<String, Value>,
}

impl SchemaValidator {
    /// Create new schema validator with built-in capability schemas
    pub fn new() -> Result<Self> {
        let mut schemas = HashMap::new();

        // Load built-in schemas for supported capabilities
        schemas.insert("fs.read.v1".to_string(), create_fs_read_schema()?);
        schemas.insert("fs.write.v1".to_string(), create_fs_write_schema()?);
        schemas.insert("shell.exec.v1".to_string(), create_shell_exec_schema()?);

        info!(
            "Schema validator initialized with {} schemas",
            schemas.len()
        );
        Ok(Self {
            schemas,
            schema_values: HashMap::new(),
        })
    }

    /// Validate intent against capability schema
    pub fn validate_intent(&self, intent: &smith_protocol::Intent) -> Result<()> {
        if std::env::var("SMITH_EXECUTOR_SKIP_SCHEMA_VALIDATION").unwrap_or_default() == "1" {
            warn!(
                "Skipping schema validation for capability: {}",
                intent.capability
            );
            return Ok(());
        }

        let schema_key = match intent.capability {
            smith_protocol::Capability::FsReadV1 => "fs.read.v1",
            smith_protocol::Capability::HttpFetchV1 => {
                return Err(anyhow::anyhow!(
                    "http.fetch.v1 is removed from agentd; route this intent to the external http.fetch capability service"
                ));
            }
            smith_protocol::Capability::FsWriteV1 => "fs.write.v1",
            smith_protocol::Capability::GitCloneV1 => {
                return Err(anyhow::anyhow!(
                    "git.clone.v1 is deprecated; use shell.exec.v1 with the git CLI instead"
                ));
            }
            smith_protocol::Capability::ArchiveReadV1 => "archive.read.v1",
            smith_protocol::Capability::SqliteQueryV1 => "sqlite.query.v1",
            smith_protocol::Capability::BenchReportV1 => "bench.report.v1",
            smith_protocol::Capability::ShellExec => "shell.exec.v1",
            smith_protocol::Capability::HttpFetch => {
                return Err(anyhow::anyhow!(
                    "http.fetch.v1 is removed from agentd; route this intent to the external http.fetch capability service"
                ));
            }
        }
        .to_string();

        let schema = self
            .schemas
            .get(&schema_key)
            .ok_or_else(|| anyhow::anyhow!("No schema found for capability: {}", schema_key))?;

        debug!("Validating intent against schema: {}", schema_key);

        // Convert intent to JSON for validation
        let intent_value =
            serde_json::to_value(intent).context("Failed to serialize intent for validation")?;

        // Validate the entire intent structure
        let validation_result = schema.validate(&intent_value);
        match validation_result {
            Ok(_) => {
                debug!("Intent validation passed for: {}", schema_key);
                Ok(())
            }
            Err(errors) => {
                let error_messages: Vec<String> = errors
                    .into_iter()
                    .map(|error| format!("{} at {}", error, error.instance_path))
                    .collect();

                Err(anyhow::anyhow!(
                    "Schema validation failed for {}: {}",
                    schema_key,
                    error_messages.join(", ")
                ))
            }
        }
    }

    /// Load schema from file (for external schemas)
    pub fn load_schema_from_file(
        &mut self,
        capability: &str,
        version: u32,
        schema_path: &std::path::Path,
    ) -> Result<()> {
        let schema_content = std::fs::read_to_string(schema_path)
            .with_context(|| format!("Failed to read schema file: {}", schema_path.display()))?;

        let schema_json: Value =
            serde_json::from_str(&schema_content).context("Failed to parse schema JSON")?;

        let schema_key = format!("{}.v{}", capability, version);

        // Create a static copy of the schema JSON to satisfy lifetime requirements
        let static_schema: &'static Value = Box::leak(Box::new(schema_json.clone()));

        let compiled_schema = JSONSchema::options()
            .with_draft(Draft::Draft7)
            .compile(static_schema)
            .context("Failed to compile JSON schema")?;

        self.schemas.insert(schema_key.clone(), compiled_schema);
        self.schema_values.insert(schema_key.clone(), schema_json);

        info!("Loaded external schema: {}", schema_key);
        Ok(())
    }

    /// Get list of supported capability schemas
    pub fn supported_capabilities(&self) -> Vec<String> {
        self.schemas.keys().cloned().collect()
    }

    /// Reload all schemas (useful for hot-reloading)
    pub fn reload_schemas(&mut self) -> Result<()> {
        warn!("Schema reloading not yet implemented");
        Ok(())
    }
}

fn build_intent_schema_value(
    capability_literal: &str,
    params_schema: Value,
    metadata_schema: Option<Value>,
) -> Value {
    let metadata = metadata_schema.unwrap_or_else(|| {
        json!({
            "type": "object",
            "additionalProperties": true
        })
    });

    json!({
        "$schema": "https://json-schema.org/draft/2019-09/schema",
        "type": "object",
        "required": [
            "id",
            "capability",
            "domain",
            "params",
            "created_at_ns",
            "ttl_ms",
            "nonce",
            "signer",
            "signature_b64",
            "metadata"
        ],
        "properties": {
            "id": {
                "type": "string",
                "format": "uuid",
                "description": "Unique intent identifier (UUIDv4 or UUIDv7)"
            },
            "capability": {
                "type": "string",
                "const": capability_literal,
                "description": "Capability identifier"
            },
            "domain": {
                "type": "string",
                "minLength": 1,
                "maxLength": 128,
                "description": "Intent routing domain"
            },
            "params": params_schema,
            "created_at_ns": {
                "type": "integer",
                "minimum": 0,
                "description": "Creation timestamp in nanoseconds"
            },
            "ttl_ms": {
                "type": "integer",
                "minimum": 1,
                "maximum": 600_000,
                "description": "Time-to-live in milliseconds"
            },
            "nonce": {
                "type": "string",
                "pattern": "^[A-Fa-f0-9]{16,64}$",
                "description": "Hex nonce for replay protection"
            },
            "signer": {
                "type": "string",
                "pattern": "^[A-Za-z0-9+/=]+$",
                "minLength": 43,
                "maxLength": 128,
                "description": "Base64-encoded Ed25519 public key"
            },
            "signature_b64": {
                "type": "string",
                "pattern": "^[A-Za-z0-9+/=]+$",
                "minLength": 43,
                "maxLength": 180,
                "description": "Base64-encoded signature"
            },
            "metadata": metadata
        },
        "additionalProperties": false
    })
}

/// Create JSON schema for fs.read.v1 capability
fn create_fs_read_schema() -> Result<JSONSchema> {
    use std::sync::OnceLock;
    static SCHEMA: OnceLock<Value> = OnceLock::new();

    let schema = SCHEMA.get_or_init(|| {
        let params_schema = json!({
            "type": "object",
            "required": ["path", "offset", "len"],
            "properties": {
                "path": {
                    "type": "string",
                    "pattern": "^/[^\\x00]*$",
                    "minLength": 1,
                    "maxLength": 4096,
                    "description": "Absolute file path within workspace"
                },
                "offset": {
                    "type": "integer",
                    "minimum": 0,
                    "description": "Byte offset to start reading from"
                },
                "len": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 1_048_576,
                    "description": "Number of bytes to read (max 1MB)"
                }
            },
            "additionalProperties": false
        });

        let metadata_schema = json!({
            "type": "object",
            "properties": {
                "resource": {
                    "type": "string",
                    "minLength": 1
                },
                "domain": {
                    "type": "string",
                    "minLength": 1
                }
            },
            "additionalProperties": true
        });

        build_intent_schema_value("fs.read.v1", params_schema, Some(metadata_schema))
    });

    JSONSchema::options()
        .with_draft(Draft::Draft7)
        .compile(schema)
        .context("Failed to compile fs.read.v1 schema")
}

/// Create JSON schema for fs.write.v1 capability
fn create_fs_write_schema() -> Result<JSONSchema> {
    use std::sync::OnceLock;
    static SCHEMA: OnceLock<Value> = OnceLock::new();

    let schema = SCHEMA.get_or_init(|| {
        let params_schema = json!({
            "type": "object",
            "required": ["path", "content"],
            "properties": {
                "path": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 4096,
                    "description": "Target file path"
                },
                "content": {
                    "description": "String content or base64 object",
                    "oneOf": [
                        {
                            "type": "string",
                            "maxLength": 1_048_576
                        },
                        {
                            "type": "object",
                            "required": ["data", "encoding"],
                            "properties": {
                                "data": { "type": "string", "minLength": 1 },
                                "encoding": { "type": "string", "enum": ["base64"] }
                            },
                            "additionalProperties": false
                        }
                    ]
                },
                "mode": {
                    "type": "string",
                    "enum": ["create", "write", "overwrite", "append"],
                    "default": "write",
                    "description": "Write mode"
                },
                "permissions": {
                    "type": "string",
                    "pattern": "^[0-7]{3,4}$",
                    "description": "Unix file permissions in octal"
                }
            },
            "additionalProperties": false
        });

        build_intent_schema_value("fs.write.v1", params_schema, None)
    });

    JSONSchema::options()
        .with_draft(Draft::Draft7)
        .compile(schema)
        .context("Failed to compile fs.write.v1 schema")
}

/// Create JSON schema for http.fetch.v1 capability
fn create_http_fetch_schema() -> Result<JSONSchema> {
    use std::sync::OnceLock;
    static SCHEMA: OnceLock<Value> = OnceLock::new();

    let schema = SCHEMA.get_or_init(|| {
        let params_schema = json!({
            "type": "object",
            "required": ["url"],
            "properties": {
                "url": {
                    "type": "string",
                    "pattern": "^https://.+$",
                    "minLength": 8,
                    "maxLength": 2048,
                    "description": "HTTPS URL to fetch"
                },
                "method": {
                    "type": "string",
                    "enum": ["GET", "HEAD"],
                    "default": "GET",
                    "description": "HTTP method"
                },
                "headers": {
                    "type": "object",
                    "patternProperties": {
                        "^(Accept|Accept-Encoding|Accept-Language|Cache-Control|If-None-Match|User-Agent)$": {
                            "type": "string",
                            "maxLength": 1024
                        }
                    },
                    "additionalProperties": false,
                    "maxProperties": 10,
                    "description": "Allowed HTTP headers"
                },
                "timeout_ms": {
                    "type": "integer",
                    "minimum": 50,
                    "maximum": 30_000,
                    "default": 5_000,
                    "description": "Request timeout in milliseconds"
                }
            },
            "additionalProperties": false
        });

        build_intent_schema_value("http.fetch.v1", params_schema, None)
    });

    JSONSchema::options()
        .with_draft(Draft::Draft7)
        .compile(schema)
        .context("Failed to compile http.fetch.v1 schema")
}

/// Create JSON schema for shell.exec capability
fn create_shell_exec_schema() -> Result<JSONSchema> {
    use std::sync::OnceLock;
    static SCHEMA: OnceLock<Value> = OnceLock::new();

    let schema = SCHEMA.get_or_init(|| {
        let params_schema = json!({
            "type": "object",
            "required": ["command", "timeout_ms"],
            "properties": {
                "command": {
                    "type": "string",
                    "minLength": 1,
                    "maxLength": 4096,
                    "description": "Command to execute"
                },
                "timeout_ms": {
                    "type": "integer",
                    "minimum": 1_000,
                    "maximum": 120_000,
                    "description": "Execution timeout in milliseconds"
                }
            },
            "additionalProperties": false
        });

        build_intent_schema_value("shell.exec.v1", params_schema, None)
    });

    JSONSchema::options()
        .with_draft(Draft::Draft7)
        .compile(schema)
        .context("Failed to compile shell.exec.v1 schema")
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;
    use std::str::FromStr;

    const SAMPLE_SIGNER: &str = "R4Yg1nuVvLWIjxb6dtUI+Ck7o/Ec9X3YeWDlGfyacds=";
    const SAMPLE_SIGNATURE: &str =
        "tyM+jVG1cpMLvvIddTEJ+ANJcLotaTDfHx/3xRJA62npYXrZ6t8afqwLe0upObPeciAxU3Pf+nzcJGT+7hWWAg==";

    fn create_valid_fs_read_intent() -> smith_protocol::Intent {
        let mut metadata = HashMap::new();
        metadata.insert("resource".to_string(), json!("/srv/logs/app.log"));
        metadata.insert("domain".to_string(), json!("test"));

        smith_protocol::Intent {
            id: "b1e8f5c4-7b20-4c78-9e93-7a8a2ef7a6ec".to_string(),
            capability: smith_protocol::Capability::FsReadV1,
            domain: "test".to_string(),
            params: json!({
                "path": "/srv/logs/app.log",
                "offset": 0,
                "len": 4096
            }),
            created_at_ns: 1735412345678000000,
            ttl_ms: 60000,
            nonce: "c1f4a19a8e6f1d0b2c3d4e5f6a7b8c9d".to_string(),
            signer: SAMPLE_SIGNER.to_string(),
            signature_b64: SAMPLE_SIGNATURE.to_string(),
            metadata,
        }
    }

    fn create_valid_http_fetch_intent() -> smith_protocol::Intent {
        smith_protocol::Intent {
            id: "a2e8f5c4-7b20-4c78-9e93-7a8a2ef7a6ec".to_string(),
            capability: smith_protocol::Capability::HttpFetchV1,
            domain: "test".to_string(),
            params: json!({
                "url": "https://api.example.com/data",
                "method": "GET",
                "headers": {
                    "Accept": "application/json",
                    "User-Agent": "Smith-Executor/1.0"
                },
                "timeout_ms": 5000
            }),
            created_at_ns: 1735412345678000000,
            ttl_ms: 60000,
            nonce: "d1f4a19a8e6f1d0b2c3d4e5f6a7b8c9e".to_string(),
            signer: SAMPLE_SIGNER.to_string(),
            signature_b64: SAMPLE_SIGNATURE.to_string(),
            metadata: HashMap::new(),
        }
    }

    fn create_valid_fs_write_intent() -> smith_protocol::Intent {
        use std::collections::HashMap;
        smith_protocol::Intent {
            id: "f3e8f5c4-7b20-4c78-9e93-7a8a2ef7a6ec".to_string(),
            capability: smith_protocol::Capability::FsWriteV1,
            domain: "tenant-a".to_string(),
            params: json!({
                "path": "/srv/output/report.txt",
                "content": "hello world",
                "mode": "overwrite",
                "permissions": "644"
            }),
            created_at_ns: 1735412345678000000,
            ttl_ms: 60_000,
            nonce: "e1f4a19a8e6f1d0b2c3d4e5f6a7b8c9f".to_string(),
            signer: SAMPLE_SIGNER.to_string(),
            signature_b64: SAMPLE_SIGNATURE.to_string(),
            metadata: HashMap::new(),
        }
    }

    fn create_valid_shell_exec_intent() -> smith_protocol::Intent {
        smith_protocol::Intent {
            id: "c3a9c2e1-9a76-46cf-8f8b-8fb2d1c1a111".to_string(),
            capability: smith_protocol::Capability::ShellExec,
            domain: "test".to_string(),
            params: json!({
                "command": "echo hello",
                "timeout_ms": 10_000
            }),
            created_at_ns: 1735412345678000000,
            ttl_ms: 60_000,
            nonce: "e1f4a19a8e6f1d0b2c3d4e5f6a7b8c9f".to_string(),
            signer: SAMPLE_SIGNER.to_string(),
            signature_b64: SAMPLE_SIGNATURE.to_string(),
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_schema_validator_creation() {
        let validator = SchemaValidator::new().unwrap();
        let capabilities = validator.supported_capabilities();

        assert!(capabilities.contains(&"fs.read.v1".to_string()));
        assert!(capabilities.contains(&"fs.write.v1".to_string()));
        assert!(capabilities.contains(&"shell.exec.v1".to_string()));
        assert_eq!(capabilities.len(), 3);
    }

    #[test]
    fn test_valid_fs_write_intent() {
        let validator = SchemaValidator::new().unwrap();
        let intent = create_valid_fs_write_intent();
        let result = validator.validate_intent(&intent);
        assert!(
            result.is_ok(),
            "Valid fs.write intent should pass validation: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_valid_fs_read_intent() {
        let validator = SchemaValidator::new().unwrap();
        let intent = create_valid_fs_read_intent();

        let result = validator.validate_intent(&intent);
        if let Err(ref error) = result {
            println!("Validation failed: {}", error);
        }
        assert!(
            result.is_ok(),
            "Valid fs.read intent should pass validation: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_http_fetch_capability_is_removed() {
        let validator = SchemaValidator::new().unwrap();
        let intent = create_valid_http_fetch_intent();

        let error = validator.validate_intent(&intent).unwrap_err().to_string();
        assert!(error.contains("removed from agentd"));
        assert!(error.contains("external http.fetch capability service"));
    }

    #[test]
    fn test_invalid_capability() {
        // Test that invalid capability strings fail to parse
        let result = smith_protocol::Capability::from_str("unknown.cap");
        assert!(result.is_err(), "Unknown capability should fail to parse");
    }

    #[test]
    fn test_git_clone_capability_is_deprecated() {
        let validator = SchemaValidator::new().unwrap();
        let intent = smith_protocol::Intent {
            id: "d3a9c2e1-9a76-46cf-8f8b-8fb2d1c1a112".to_string(),
            capability: smith_protocol::Capability::GitCloneV1,
            domain: "test".to_string(),
            params: json!({
                "repository_url": "https://github.com/example/repo.git"
            }),
            created_at_ns: 1735412345678000000,
            ttl_ms: 60_000,
            nonce: "f1f4a19a8e6f1d0b2c3d4e5f6a7b8c9e".to_string(),
            signer: SAMPLE_SIGNER.to_string(),
            signature_b64: SAMPLE_SIGNATURE.to_string(),
            metadata: HashMap::new(),
        };

        let error = validator.validate_intent(&intent).unwrap_err().to_string();
        assert!(error.contains("deprecated"));
        assert!(error.contains("shell.exec.v1"));
    }

    #[test]
    fn test_fs_read_invalid_path() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();

        // Make path invalid (relative path)
        intent.params = json!({
            "path": "./relative/path",
            "offset": 0,
            "len": 4096
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Relative path should fail validation");
    }

    #[test]
    fn test_fs_read_invalid_params() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();

        // Make len too large
        intent.params = json!({
            "path": "/srv/logs/app.log",
            "offset": 0,
            "len": 2048576  // > 1MB limit
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Oversized len should fail validation");
    }

    #[test]
    fn test_http_fetch_invalid_url() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();

        // Make URL invalid (not HTTPS)
        intent.params = json!({
            "url": "http://api.example.com/data",
            "method": "GET",
            "headers": {
                "Accept": "application/json",
                "User-Agent": "Smith-Executor/1.0"
            },
            "timeout_ms": 5000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "HTTP URL should fail validation (must be HTTPS)"
        );
    }

    #[test]
    fn test_http_fetch_invalid_headers() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();

        // Add disallowed header
        intent.params = json!({
            "url": "https://api.example.com/data",
            "method": "GET",
            "headers": {
                "Accept": "application/json",
                "User-Agent": "Smith-Executor/1.0",
                "Authorization": "Bearer token"  // This should be disallowed
            },
            "timeout_ms": 5000
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Disallowed headers should fail validation");
    }

    #[test]
    fn test_missing_required_field() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();

        // Remove required field by setting it to empty
        intent.signature_b64 = "".to_string();

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Missing signature should fail validation");
    }

    #[test]
    fn test_invalid_nonce_format() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();

        // Make nonce invalid (wrong length)
        intent.nonce = "tooshort".to_string();

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "Invalid nonce format should fail validation"
        );
    }

    #[test]
    fn test_valid_shell_exec_intent() {
        let validator = SchemaValidator::new().unwrap();
        let intent = create_valid_shell_exec_intent();

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_ok(),
            "Valid shell.exec intent should pass validation: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_shell_exec_missing_command() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_shell_exec_intent();
        intent.params = json!({
            "timeout_ms": 10_000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "Shell exec intent without command should fail validation"
        );
    }

    #[test]
    fn test_shell_exec_timeout_too_low() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_shell_exec_intent();
        intent.params = json!({
            "command": "echo test",
            "timeout_ms": 500  // Below minimum of 1000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "Shell exec intent with timeout below minimum should fail"
        );
    }

    #[test]
    fn test_shell_exec_timeout_too_high() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_shell_exec_intent();
        intent.params = json!({
            "command": "echo test",
            "timeout_ms": 200_000  // Above maximum of 120_000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "Shell exec intent with timeout above maximum should fail"
        );
    }

    #[test]
    fn test_shell_exec_empty_command() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_shell_exec_intent();
        intent.params = json!({
            "command": "",  // Empty command
            "timeout_ms": 10_000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "Shell exec intent with empty command should fail"
        );
    }

    #[test]
    fn test_supported_capabilities_returns_three() {
        let validator = SchemaValidator::new().unwrap();
        let caps = validator.supported_capabilities();
        assert_eq!(caps.len(), 3);
    }

    #[test]
    fn test_reload_schemas_succeeds() {
        let mut validator = SchemaValidator::new().unwrap();
        let result = validator.reload_schemas();
        assert!(result.is_ok(), "Reload schemas should succeed");
    }

    #[test]
    fn test_http_fetch_timeout_at_min_boundary() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "timeout_ms": 50  // Exactly at minimum
        });

        let result = validator.validate_intent(&intent);
        // Should pass (50 is the minimum)
        if let Err(ref e) = result {
            // May fail due to missing other fields, check the error
            println!("Validation error: {}", e);
        }
    }

    #[test]
    fn test_http_fetch_timeout_at_max_boundary() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "timeout_ms": 30000  // Exactly at maximum
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "http.fetch is no longer supported by agentd"
        );
    }

    #[test]
    fn test_http_fetch_timeout_below_min() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "timeout_ms": 49  // Below minimum of 50
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "HTTP fetch with timeout below minimum should fail"
        );
    }

    #[test]
    fn test_http_fetch_timeout_above_max() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "timeout_ms": 30001  // Above maximum of 30000
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "HTTP fetch with timeout above maximum should fail"
        );
    }

    #[test]
    fn test_fs_read_offset_negative() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.params = json!({
            "path": "/srv/logs/app.log",
            "offset": -1,  // Negative offset not allowed
            "len": 4096
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "FS read with negative offset should fail");
    }

    #[test]
    fn test_fs_read_len_zero() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.params = json!({
            "path": "/srv/logs/app.log",
            "offset": 0,
            "len": 0  // Zero len not allowed (minimum is 1)
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "FS read with zero len should fail");
    }

    #[test]
    fn test_fs_read_len_at_max() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.params = json!({
            "path": "/srv/logs/app.log",
            "offset": 0,
            "len": 1_048_576  // Exactly at 1MB max
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_ok(),
            "FS read with len at max should pass: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_intent_ttl_too_high() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.ttl_ms = 700_000; // Above 600_000 maximum

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Intent with TTL above maximum should fail");
    }

    #[test]
    fn test_intent_ttl_at_max() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.ttl_ms = 600_000; // Exactly at maximum

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_ok(),
            "Intent with TTL at max should pass: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_intent_domain_empty() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.domain = String::new(); // Empty domain

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Intent with empty domain should fail");
    }

    #[test]
    fn test_intent_domain_too_long() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.domain = "a".repeat(129); // Above 128 max

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Intent with domain too long should fail");
    }

    #[test]
    fn test_http_fetch_method_head() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "method": "HEAD"
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "http.fetch is no longer supported by agentd"
        );
    }

    #[test]
    fn test_http_fetch_method_post_invalid() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        intent.params = json!({
            "url": "https://api.example.com/data",
            "method": "POST"  // Not allowed (only GET and HEAD)
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "HTTP fetch with POST method should fail");
    }

    #[test]
    fn test_http_fetch_url_too_long() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_http_fetch_intent();
        let long_path = "a".repeat(2049); // Above 2048 max
        intent.params = json!({
            "url": format!("https://api.example.com/{}", long_path),
        });

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "HTTP fetch with URL too long should fail");
    }

    #[test]
    fn test_nonce_too_long() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.nonce = "a".repeat(65); // Above 64 max

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Intent with nonce too long should fail");
    }

    #[test]
    fn test_nonce_non_hex() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.nonce = "ghijklmnopqrstuvwxyz".to_string(); // Non-hex chars

        let result = validator.validate_intent(&intent);
        assert!(result.is_err(), "Intent with non-hex nonce should fail");
    }

    #[test]
    fn test_fs_read_path_with_null_byte() {
        let validator = SchemaValidator::new().unwrap();
        let mut intent = create_valid_fs_read_intent();
        intent.params = json!({
            "path": "/srv/logs/app\x00.log",  // Contains null byte
            "offset": 0,
            "len": 4096
        });

        let result = validator.validate_intent(&intent);
        assert!(
            result.is_err(),
            "FS read with null byte in path should fail"
        );
    }

    #[test]
    fn test_build_intent_schema_value_without_metadata() {
        let params_schema = json!({
            "type": "object",
            "properties": {
                "test": { "type": "string" }
            }
        });

        let schema = build_intent_schema_value("test.cap.v1", params_schema.clone(), None);

        // Should have default metadata schema
        assert!(schema["properties"]["metadata"]["type"] == "object");
        assert!(schema["properties"]["metadata"]["additionalProperties"] == true);
    }

    #[test]
    fn test_build_intent_schema_value_with_custom_metadata() {
        let params_schema = json!({
            "type": "object"
        });

        let metadata_schema = json!({
            "type": "object",
            "properties": {
                "custom_field": { "type": "string" }
            },
            "additionalProperties": false
        });

        let schema =
            build_intent_schema_value("test.cap.v1", params_schema, Some(metadata_schema.clone()));

        // Should use custom metadata schema
        assert!(schema["properties"]["metadata"]["additionalProperties"] == false);
    }

    #[test]
    fn test_load_schema_from_file_nonexistent() {
        let mut validator = SchemaValidator::new().unwrap();
        let result = validator.load_schema_from_file(
            "test",
            1,
            std::path::Path::new("/nonexistent/schema.json"),
        );

        assert!(
            result.is_err(),
            "Loading nonexistent schema file should fail"
        );
    }
}