zeroclawlabs 0.6.9

Zero overhead. Zero compromise. 100% Rust. The fastest, smallest AI assistant.
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
use super::traits::{Tool, ToolResult};
use crate::config::GoogleWorkspaceAllowedOperation;
use crate::security::SecurityPolicy;
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;

/// Default `gws` command execution time before kill (overridden by config).
const DEFAULT_GWS_TIMEOUT_SECS: u64 = 30;
/// Maximum output size in bytes (1MB).
const MAX_OUTPUT_BYTES: usize = 1_048_576;

use crate::config::DEFAULT_GWS_SERVICES;

/// Google Workspace CLI (`gws`) integration tool.
///
/// Wraps the `gws` CLI binary to give the agent structured access to
/// Google Workspace services (Drive, Gmail, Calendar, Sheets, etc.).
/// Requires `gws` to be installed and authenticated (`gws auth login`).
pub struct GoogleWorkspaceTool {
    security: Arc<SecurityPolicy>,
    allowed_services: Vec<String>,
    allowed_operations: Vec<GoogleWorkspaceAllowedOperation>,
    credentials_path: Option<String>,
    default_account: Option<String>,
    rate_limit_per_minute: u32,
    timeout_secs: u64,
    audit_log: bool,
}

impl GoogleWorkspaceTool {
    /// Create a new `GoogleWorkspaceTool`.
    ///
    /// If `allowed_services` is empty, the default service set is used.
    pub fn new(
        security: Arc<SecurityPolicy>,
        allowed_services: Vec<String>,
        allowed_operations: Vec<GoogleWorkspaceAllowedOperation>,
        credentials_path: Option<String>,
        default_account: Option<String>,
        rate_limit_per_minute: u32,
        timeout_secs: u64,
        audit_log: bool,
    ) -> Self {
        let services = if allowed_services.is_empty() {
            DEFAULT_GWS_SERVICES
                .iter()
                .map(|s| (*s).to_string())
                .collect()
        } else {
            allowed_services
                .into_iter()
                .map(|s| s.trim().to_string())
                .collect()
        };
        // Normalize stored operation fields at construction time so runtime
        // comparisons can use plain equality without repeated .trim() calls.
        let operations = allowed_operations
            .into_iter()
            .map(|op| GoogleWorkspaceAllowedOperation {
                service: op.service.trim().to_string(),
                resource: op.resource.trim().to_string(),
                sub_resource: op.sub_resource.as_deref().map(|s| s.trim().to_string()),
                methods: op.methods.iter().map(|m| m.trim().to_string()).collect(),
            })
            .collect();
        Self {
            security,
            allowed_services: services,
            allowed_operations: operations,
            credentials_path,
            default_account,
            rate_limit_per_minute,
            timeout_secs,
            audit_log,
        }
    }

    /// Build the positional `gws` arguments: `[service, resource, (sub_resource,)? method]`.
    fn positional_cmd_args(
        service: &str,
        resource: &str,
        sub_resource: Option<&str>,
        method: &str,
    ) -> Vec<String> {
        let mut args = vec![service.to_string(), resource.to_string()];
        if let Some(sub) = sub_resource {
            args.push(sub.to_string());
        }
        args.push(method.to_string());
        args
    }

    /// Build the `--page-all` and `--page-limit` flags from validated pagination inputs.
    /// `page_limit` alone (without `page_all`) caps page count; both together fetch all pages
    /// up to the limit.
    fn build_pagination_args(page_all: bool, page_limit: Option<u64>) -> Vec<String> {
        let mut args = Vec::new();
        if page_all {
            args.push("--page-all".into());
        }
        if page_all || page_limit.is_some() {
            args.push("--page-limit".into());
            args.push(page_limit.unwrap_or(10).to_string());
        }
        args
    }

    fn is_operation_allowed(
        &self,
        service: &str,
        resource: &str,
        sub_resource: Option<&str>,
        method: &str,
    ) -> bool {
        if self.allowed_operations.is_empty() {
            return true;
        }
        self.allowed_operations.iter().any(|operation| {
            operation.service == service
                && operation.resource == resource
                && operation.sub_resource.as_deref() == sub_resource
                && operation.methods.iter().any(|allowed| allowed == method)
        })
    }
}

#[async_trait]
impl Tool for GoogleWorkspaceTool {
    fn name(&self) -> &str {
        "google_workspace"
    }

    fn description(&self) -> &str {
        "Interact with Google Workspace services (Drive, Gmail, Calendar, Sheets, Docs, etc.) \
         via the gws CLI. Requires gws to be installed and authenticated."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "service": {
                    "type": "string",
                    "description": "Google Workspace service (e.g. drive, gmail, calendar, sheets, docs, slides, tasks, people, chat, classroom, forms, keep, meet, events)"
                },
                "resource": {
                    "type": "string",
                    "description": "Service resource (e.g. files, messages, events, spreadsheets)"
                },
                "method": {
                    "type": "string",
                    "description": "Method to call on the resource (e.g. list, get, create, update, delete)"
                },
                "sub_resource": {
                    "type": "string",
                    "description": "Optional sub-resource for nested operations"
                },
                "params": {
                    "type": "object",
                    "description": "URL/query parameters as key-value pairs (passed as --params JSON)"
                },
                "body": {
                    "type": "object",
                    "description": "Request body for POST/PATCH/PUT operations (passed as --json JSON)"
                },
                "format": {
                    "type": "string",
                    "enum": ["json", "table", "yaml", "csv"],
                    "description": "Output format (default: json)"
                },
                "page_all": {
                    "type": "boolean",
                    "description": "Auto-paginate through all results"
                },
                "page_limit": {
                    "type": "integer",
                    "description": "Max pages to fetch when using page_all (default: 10)"
                }
            },
            "required": ["service", "resource", "method"]
        })
    }

    /// Execute a Google Workspace CLI command with input validation and security enforcement.
    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
        let service = args
            .get("service")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'service' parameter"))?;
        let resource = args
            .get("resource")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'resource' parameter"))?;
        let method = args
            .get("method")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'method' parameter"))?;

        // Extract and validate sub_resource early so the allowlist check can account for it.
        let sub_resource: Option<&str> = if let Some(sub_resource_value) = args.get("sub_resource")
        {
            let s = match sub_resource_value.as_str() {
                Some(s) => s,
                None => {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some("'sub_resource' must be a string".into()),
                    });
                }
            };
            if !s
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
            {
                return Ok(ToolResult {
                    success: false,
                    output: String::new(),
                    error: Some(
                        "Invalid characters in 'sub_resource': only lowercase alphanumeric, underscore, and hyphen are allowed"
                            .into(),
                    ),
                });
            }
            Some(s)
        } else {
            None
        };

        // Security checks
        if self.security.is_rate_limited() {
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some("Rate limit exceeded: too many actions in the last hour".into()),
            });
        }

        // Validate service is in the allowlist
        if !self.allowed_services.iter().any(|s| s == service) {
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!(
                    "Service '{service}' is not in the allowed services list. \
                     Allowed: {}",
                    self.allowed_services.join(", ")
                )),
            });
        }

        if !self.is_operation_allowed(service, resource, sub_resource, method) {
            let op_path = match sub_resource {
                Some(sub) => format!("{service}/{resource}/{sub}/{method}"),
                None => format!("{service}/{resource}/{method}"),
            };
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!(
                    "Operation '{op_path}' is not in the allowed operations list"
                )),
            });
        }

        // Validate inputs contain no shell metacharacters
        for (label, value) in [
            ("service", service),
            ("resource", resource),
            ("method", method),
        ] {
            if !value
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
            {
                return Ok(ToolResult {
                    success: false,
                    output: String::new(),
                    error: Some(format!(
                        "Invalid characters in '{label}': only lowercase alphanumeric, underscore, and hyphen are allowed"
                    )),
                });
            }
        }

        // Build the gws command — validate all optional fields before consuming budget
        let mut cmd_args = Self::positional_cmd_args(service, resource, sub_resource, method);

        if let Some(params) = args.get("params") {
            if !params.is_object() {
                return Ok(ToolResult {
                    success: false,
                    output: String::new(),
                    error: Some("'params' must be an object".into()),
                });
            }
            cmd_args.push("--params".into());
            cmd_args.push(params.to_string());
        }

        if let Some(body) = args.get("body") {
            if !body.is_object() {
                return Ok(ToolResult {
                    success: false,
                    output: String::new(),
                    error: Some("'body' must be an object".into()),
                });
            }
            cmd_args.push("--json".into());
            cmd_args.push(body.to_string());
        }

        if let Some(format_value) = args.get("format") {
            let format = match format_value.as_str() {
                Some(s) => s,
                None => {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some("'format' must be a string".into()),
                    });
                }
            };
            match format {
                "json" | "table" | "yaml" | "csv" => {
                    cmd_args.push("--format".into());
                    cmd_args.push(format.to_string());
                }
                _ => {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some(format!(
                            "Invalid format '{format}': must be json, table, yaml, or csv"
                        )),
                    });
                }
            }
        }

        let page_all = match args.get("page_all") {
            Some(v) => match v.as_bool() {
                Some(b) => b,
                None => {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some("'page_all' must be a boolean".into()),
                    });
                }
            },
            None => false,
        };
        let page_limit = match args.get("page_limit") {
            Some(v) => match v.as_u64() {
                Some(n) => Some(n),
                None => {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some("'page_limit' must be a non-negative integer".into()),
                    });
                }
            },
            None => None,
        };
        cmd_args.extend(Self::build_pagination_args(page_all, page_limit));

        // Charge action budget only after all validation passes
        if !self.security.record_action() {
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some("Rate limit exceeded: action budget exhausted".into()),
            });
        }

        let mut cmd = tokio::process::Command::new("gws");
        cmd.args(&cmd_args);
        cmd.env_clear();
        // gws needs PATH to find itself and HOME/APPDATA for credential storage
        for key in &["PATH", "HOME", "APPDATA", "USERPROFILE", "LANG", "TERM"] {
            if let Ok(val) = std::env::var(key) {
                cmd.env(key, val);
            }
        }

        // Apply credential path if configured
        if let Some(ref creds) = self.credentials_path {
            cmd.env("GOOGLE_APPLICATION_CREDENTIALS", creds);
        }

        // Apply default account if configured
        if let Some(ref account) = self.default_account {
            cmd.args(["--account", account]);
        }

        if self.audit_log {
            tracing::info!(
                tool = "google_workspace",
                service = service,
                resource = resource,
                sub_resource = sub_resource.unwrap_or(""),
                method = method,
                "gws audit: executing API call"
            );
        }

        let result =
            tokio::time::timeout(Duration::from_secs(self.timeout_secs), cmd.output()).await;

        match result {
            Ok(Ok(output)) => {
                let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();

                if stdout.len() > MAX_OUTPUT_BYTES {
                    // Find a valid char boundary at or before MAX_OUTPUT_BYTES
                    let mut boundary = MAX_OUTPUT_BYTES;
                    while boundary > 0 && !stdout.is_char_boundary(boundary) {
                        boundary -= 1;
                    }
                    stdout.truncate(boundary);
                    stdout.push_str("\n... [output truncated at 1MB]");
                }
                if stderr.len() > MAX_OUTPUT_BYTES {
                    let mut boundary = MAX_OUTPUT_BYTES;
                    while boundary > 0 && !stderr.is_char_boundary(boundary) {
                        boundary -= 1;
                    }
                    stderr.truncate(boundary);
                    stderr.push_str("\n... [stderr truncated at 1MB]");
                }

                Ok(ToolResult {
                    success: output.status.success(),
                    output: stdout,
                    error: if stderr.is_empty() {
                        None
                    } else {
                        Some(stderr)
                    },
                })
            }
            Ok(Err(e)) => Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!(
                    "Failed to execute gws: {e}. Is gws installed? Run: npm install -g @googleworkspace/cli"
                )),
            }),
            Err(_) => Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!(
                    "gws command timed out after {}s and was killed",
                    self.timeout_secs
                )),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::security::{AutonomyLevel, SecurityPolicy};

    fn test_security() -> Arc<SecurityPolicy> {
        Arc::new(SecurityPolicy {
            autonomy: AutonomyLevel::Full,
            workspace_dir: std::env::temp_dir(),
            ..SecurityPolicy::default()
        })
    }

    #[test]
    fn tool_name() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        assert_eq!(tool.name(), "google_workspace");
    }

    #[test]
    fn tool_description_non_empty() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        assert!(!tool.description().is_empty());
    }

    #[test]
    fn tool_schema_has_required_fields() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let schema = tool.parameters_schema();
        assert!(schema["properties"]["service"].is_object());
        assert!(schema["properties"]["resource"].is_object());
        assert!(schema["properties"]["method"].is_object());
        let required = schema["required"]
            .as_array()
            .expect("required should be an array");
        assert!(required.contains(&json!("service")));
        assert!(required.contains(&json!("resource")));
        assert!(required.contains(&json!("method")));
    }

    #[test]
    fn default_allowed_services_populated() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        assert!(!tool.allowed_services.is_empty());
        assert!(tool.allowed_services.contains(&"drive".to_string()));
        assert!(tool.allowed_services.contains(&"gmail".to_string()));
        assert!(tool.allowed_services.contains(&"calendar".to_string()));
    }

    #[test]
    fn custom_allowed_services_override_defaults() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["drive".into(), "sheets".into()],
            vec![],
            None,
            None,
            60,
            30,
            false,
        );
        assert_eq!(tool.allowed_services.len(), 2);
        assert!(tool.allowed_services.contains(&"drive".to_string()));
        assert!(tool.allowed_services.contains(&"sheets".to_string()));
        assert!(!tool.allowed_services.contains(&"gmail".to_string()));
    }

    #[tokio::test]
    async fn rejects_disallowed_service() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["drive".into()],
            vec![],
            None,
            None,
            60,
            30,
            false,
        );
        let result = tool
            .execute(json!({
                "service": "gmail",
                "resource": "users",
                "method": "list"
            }))
            .await
            .expect("disallowed service should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("not in the allowed")
        );
    }

    #[tokio::test]
    async fn rejects_shell_injection_in_service() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["drive; rm -rf /".into()],
            vec![],
            None,
            None,
            60,
            30,
            false,
        );
        let result = tool
            .execute(json!({
                "service": "drive; rm -rf /",
                "resource": "files",
                "method": "list"
            }))
            .await
            .expect("shell injection should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("Invalid characters")
        );
    }

    #[tokio::test]
    async fn rejects_shell_injection_in_resource() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files$(whoami)",
                "method": "list"
            }))
            .await
            .expect("shell injection should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("Invalid characters")
        );
    }

    #[tokio::test]
    async fn rejects_invalid_format() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list",
                "format": "xml"
            }))
            .await
            .expect("invalid format should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("Invalid format")
        );
    }

    #[tokio::test]
    async fn rejects_wrong_type_params() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list",
                "params": "not_an_object"
            }))
            .await
            .expect("wrong type params should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("'params' must be an object")
        );
    }

    #[tokio::test]
    async fn rejects_wrong_type_body() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "create",
                "body": "not_an_object"
            }))
            .await
            .expect("wrong type body should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("'body' must be an object")
        );
    }

    #[tokio::test]
    async fn rejects_wrong_type_page_all() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list",
                "page_all": "yes"
            }))
            .await
            .expect("wrong type page_all should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("'page_all' must be a boolean")
        );
    }

    #[tokio::test]
    async fn rejects_wrong_type_page_limit() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list",
                "page_limit": "ten"
            }))
            .await
            .expect("wrong type page_limit should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("'page_limit' must be a non-negative integer")
        );
    }

    #[tokio::test]
    async fn rejects_wrong_type_sub_resource() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list",
                "sub_resource": 123
            }))
            .await
            .expect("wrong type sub_resource should return a result");
        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("'sub_resource' must be a string")
        );
    }

    #[tokio::test]
    async fn missing_required_param_returns_error() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        let result = tool.execute(json!({"service": "drive"})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn rate_limited_returns_error() {
        let security = Arc::new(SecurityPolicy {
            autonomy: AutonomyLevel::Full,
            max_actions_per_hour: 0,
            workspace_dir: std::env::temp_dir(),
            ..SecurityPolicy::default()
        });
        let tool = GoogleWorkspaceTool::new(security, vec![], vec![], None, None, 60, 30, false);
        let result = tool
            .execute(json!({
                "service": "drive",
                "resource": "files",
                "method": "list"
            }))
            .await
            .expect("rate-limited should return a result");
        assert!(!result.success);
        assert!(result.error.as_deref().unwrap_or("").contains("Rate limit"));
    }

    #[test]
    fn gws_timeout_is_reasonable() {
        assert_eq!(DEFAULT_GWS_TIMEOUT_SECS, 30);
    }

    #[test]
    fn operation_allowlist_defaults_to_allow_all() {
        let tool =
            GoogleWorkspaceTool::new(test_security(), vec![], vec![], None, None, 60, 30, false);
        // Empty allowlist: everything passes regardless of sub_resource
        assert!(tool.is_operation_allowed("gmail", "users", Some("messages"), "send"));
        assert!(tool.is_operation_allowed("drive", "files", None, "list"));
    }

    #[test]
    fn operation_allowlist_matches_gmail_sub_resource_shape() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["gmail".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: "gmail".into(),
                resource: "users".into(),
                sub_resource: Some("drafts".into()),
                methods: vec!["create".into(), "update".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        // Exact match: allowed
        assert!(tool.is_operation_allowed("gmail", "users", Some("drafts"), "create"));
        assert!(tool.is_operation_allowed("gmail", "users", Some("drafts"), "update"));
        // Send not in methods: denied
        assert!(!tool.is_operation_allowed("gmail", "users", Some("drafts"), "send"));
        // Different sub_resource: denied
        assert!(!tool.is_operation_allowed("gmail", "users", Some("messages"), "list"));
        // No sub_resource when entry requires one: denied
        assert!(!tool.is_operation_allowed("gmail", "users", None, "create"));
    }

    #[test]
    fn operation_allowlist_matches_drive_3_segment_shape() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["drive".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: "drive".into(),
                resource: "files".into(),
                sub_resource: None,
                methods: vec!["list".into(), "get".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        assert!(tool.is_operation_allowed("drive", "files", None, "list"));
        assert!(tool.is_operation_allowed("drive", "files", None, "get"));
        // Delete not in methods: denied
        assert!(!tool.is_operation_allowed("drive", "files", None, "delete"));
        // Entry has no sub_resource; call with sub_resource must not match
        assert!(!tool.is_operation_allowed("drive", "files", Some("permissions"), "list"));
    }

    #[tokio::test]
    async fn rejects_disallowed_operation() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["gmail".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: "gmail".into(),
                resource: "users".into(),
                sub_resource: Some("drafts".into()),
                methods: vec!["create".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        // send is not in the allowed methods list
        let result = tool
            .execute(json!({
                "service": "gmail",
                "resource": "users",
                "sub_resource": "drafts",
                "method": "send"
            }))
            .await
            .expect("disallowed operation should return a result");

        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("allowed operations list")
        );
    }

    #[tokio::test]
    async fn rejects_operation_with_unlisted_sub_resource() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["gmail".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: "gmail".into(),
                resource: "users".into(),
                sub_resource: Some("drafts".into()),
                methods: vec!["create".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        // messages is not in the allowlist (only drafts is)
        let result = tool
            .execute(json!({
                "service": "gmail",
                "resource": "users",
                "sub_resource": "messages",
                "method": "send"
            }))
            .await
            .expect("unlisted sub_resource should return a result");

        assert!(!result.success);
        assert!(
            result
                .error
                .as_deref()
                .unwrap_or("")
                .contains("allowed operations list")
        );
    }

    // ── cmd_args ordering ────────────────────────────────────

    #[test]
    fn cmd_args_3_segment_shape_drive() {
        // Drive uses gws <service> <resource> <method> — no sub_resource.
        let args = GoogleWorkspaceTool::positional_cmd_args("drive", "files", None, "list");
        assert_eq!(args, vec!["drive", "files", "list"]);
    }

    #[test]
    fn cmd_args_4_segment_shape_gmail() {
        // Gmail uses gws <service> <resource> <sub_resource> <method>.
        let args =
            GoogleWorkspaceTool::positional_cmd_args("gmail", "users", Some("messages"), "list");
        assert_eq!(args, vec!["gmail", "users", "messages", "list"]);
    }

    #[test]
    fn cmd_args_sub_resource_precedes_method() {
        // sub_resource must come before method in the positional args.
        let args =
            GoogleWorkspaceTool::positional_cmd_args("gmail", "users", Some("drafts"), "create");
        let sub_idx = args.iter().position(|a| a == "drafts").unwrap();
        let method_idx = args.iter().position(|a| a == "create").unwrap();
        assert!(sub_idx < method_idx, "sub_resource must precede method");
    }

    // ── denial error message ─────────────────────────────────

    #[tokio::test]
    async fn denial_error_includes_sub_resource_when_present() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["gmail".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: "gmail".into(),
                resource: "users".into(),
                sub_resource: Some("drafts".into()),
                methods: vec!["create".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        let result = tool
            .execute(json!({
                "service": "gmail",
                "resource": "users",
                "sub_resource": "messages",
                "method": "send"
            }))
            .await
            .expect("denied operation should return a result");

        let error = result.error.as_deref().unwrap_or("");
        // Error must include sub_resource so the operator can distinguish
        // gmail/users/messages/send from gmail/users/drafts/send.
        assert!(
            error.contains("gmail/users/messages/send"),
            "expected full 4-segment path in error, got: {error}"
        );
    }

    // ── whitespace normalization ─────────────────────────────

    #[test]
    fn allowed_operations_config_values_trimmed_at_construction() {
        let tool = GoogleWorkspaceTool::new(
            test_security(),
            vec!["gmail".into()],
            vec![GoogleWorkspaceAllowedOperation {
                service: " gmail ".into(), // leading/trailing whitespace
                resource: " users ".into(),
                sub_resource: Some(" drafts ".into()),
                methods: vec![" create ".into()],
            }],
            None,
            None,
            60,
            30,
            false,
        );

        // After construction, stored values are trimmed and plain equality works.
        assert!(tool.is_operation_allowed("gmail", "users", Some("drafts"), "create"));
        assert!(!tool.is_operation_allowed("gmail", "users", Some(" drafts "), "create"));
    }

    // ── page_limit / page_all flag building ─────────────────

    #[test]
    fn pagination_page_limit_alone_appends_limit_without_page_all() {
        // page_limit without page_all caps page count without requesting all pages.
        let flags = GoogleWorkspaceTool::build_pagination_args(false, Some(5));
        assert!(flags.contains(&"--page-limit".to_string()));
        assert!(!flags.contains(&"--page-all".to_string()));
        let limit_idx = flags.iter().position(|f| f == "--page-limit").unwrap();
        assert_eq!(flags[limit_idx + 1], "5");
    }

    #[test]
    fn pagination_page_all_without_limit_uses_default() {
        let flags = GoogleWorkspaceTool::build_pagination_args(true, None);
        assert!(flags.contains(&"--page-all".to_string()));
        assert!(flags.contains(&"--page-limit".to_string()));
        let limit_idx = flags.iter().position(|f| f == "--page-limit").unwrap();
        assert_eq!(flags[limit_idx + 1], "10"); // default cap
    }

    #[test]
    fn pagination_page_all_with_limit_appends_both() {
        let flags = GoogleWorkspaceTool::build_pagination_args(true, Some(20));
        assert!(flags.contains(&"--page-all".to_string()));
        let limit_idx = flags.iter().position(|f| f == "--page-limit").unwrap();
        assert_eq!(flags[limit_idx + 1], "20");
    }

    #[test]
    fn pagination_neither_appends_nothing() {
        let flags = GoogleWorkspaceTool::build_pagination_args(false, None);
        assert!(flags.is_empty());
    }
}