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
//! Cloud pattern library for recommending cloud-native architectural patterns.
//!
//! Provides a built-in set of cloud migration and modernization patterns,
//! with pattern matching against workload descriptions.

use super::traits::{Tool, ToolResult};
use crate::util::truncate_with_ellipsis;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::json;

/// A cloud architecture pattern with metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudPattern {
    pub name: String,
    pub description: String,
    pub cloud_providers: Vec<String>,
    pub use_case: String,
    pub example_iac: String,
    /// Keywords for matching against workload descriptions.
    keywords: Vec<String>,
}

/// Tool that suggests cloud patterns given a workload description.
pub struct CloudPatternsTool {
    patterns: Vec<CloudPattern>,
}

impl CloudPatternsTool {
    pub fn new() -> Self {
        Self {
            patterns: built_in_patterns(),
        }
    }
}

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

    fn description(&self) -> &str {
        "Cloud pattern library. Given a workload description, suggests applicable cloud-native \
         architectural patterns (containerization, serverless, database modernization, etc.)."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["match", "list"],
                    "description": "Action: 'match' to find patterns for a workload, 'list' to show all patterns."
                },
                "workload": {
                    "type": "string",
                    "description": "Description of the workload to match patterns against (required for 'match')."
                },
                "cloud": {
                    "type": "string",
                    "description": "Filter patterns by cloud provider (aws, azure, gcp). Optional."
                }
            },
            "required": ["action"]
        })
    }

    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
        let action = args
            .get("action")
            .and_then(|v| v.as_str())
            .unwrap_or_default();
        let workload = args
            .get("workload")
            .and_then(|v| v.as_str())
            .unwrap_or_default();
        let cloud_filter = args.get("cloud").and_then(|v| v.as_str());

        match action {
            "list" => {
                let filtered = self.filter_by_cloud(cloud_filter);
                let summaries: Vec<serde_json::Value> = filtered
                    .iter()
                    .map(|p| {
                        json!({
                            "name": p.name,
                            "description": p.description,
                            "cloud_providers": p.cloud_providers,
                            "use_case": p.use_case,
                        })
                    })
                    .collect();

                let output = json!({
                    "patterns_count": summaries.len(),
                    "patterns": summaries,
                });

                Ok(ToolResult {
                    success: true,
                    output: serde_json::to_string_pretty(&output)?,
                    error: None,
                })
            }
            "match" => {
                if workload.trim().is_empty() {
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some("'workload' parameter is required for 'match' action".into()),
                    });
                }

                let matched = self.match_patterns(workload, cloud_filter);

                let output = json!({
                    "workload_summary": truncate_with_ellipsis(workload, 200),
                    "matched_count": matched.len(),
                    "matched_patterns": matched,
                });

                Ok(ToolResult {
                    success: true,
                    output: serde_json::to_string_pretty(&output)?,
                    error: None,
                })
            }
            _ => Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!("Unknown action '{}'. Valid: match, list", action)),
            }),
        }
    }
}

impl CloudPatternsTool {
    fn filter_by_cloud(&self, cloud: Option<&str>) -> Vec<&CloudPattern> {
        match cloud {
            Some(c) => self
                .patterns
                .iter()
                .filter(|p| p.cloud_providers.iter().any(|cp| cp == c))
                .collect(),
            None => self.patterns.iter().collect(),
        }
    }

    fn match_patterns(&self, workload: &str, cloud: Option<&str>) -> Vec<serde_json::Value> {
        let lower = workload.to_lowercase();
        let candidates = self.filter_by_cloud(cloud);

        let mut scored: Vec<(&CloudPattern, usize)> = candidates
            .into_iter()
            .filter_map(|p| {
                let score: usize = p
                    .keywords
                    .iter()
                    .filter(|kw| lower.contains(kw.as_str()))
                    .count();
                if score > 0 { Some((p, score)) } else { None }
            })
            .collect();

        scored.sort_by(|a, b| b.1.cmp(&a.1));

        // Built-in IaC examples are AWS Terraform only; include them only when
        // the cloud filter is unset or explicitly "aws".
        let include_example = cloud.is_none() || cloud == Some("aws");

        scored
            .into_iter()
            .map(|(p, score)| {
                let mut entry = json!({
                    "name": p.name,
                    "description": p.description,
                    "cloud_providers": p.cloud_providers,
                    "use_case": p.use_case,
                    "relevance_score": score,
                });
                if include_example {
                    entry["example_iac"] = json!(p.example_iac);
                }
                entry
            })
            .collect()
    }
}

fn built_in_patterns() -> Vec<CloudPattern> {
    vec![
        CloudPattern {
            name: "containerization".into(),
            description: "Package applications into containers for portability and consistent deployment.".into(),
            cloud_providers: vec!["aws".into(), "azure".into(), "gcp".into()],
            use_case: "Modernizing monolithic applications, improving deployment consistency, enabling microservices.".into(),
            example_iac: r#"# Terraform ECS Fargate example
resource "aws_ecs_cluster" "main" {
  name = "app-cluster"
}
resource "aws_ecs_service" "app" {
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.app.arn
  launch_type     = "FARGATE"
  desired_count   = 2
}"#.into(),
            keywords: vec!["container".into(), "docker".into(), "monolith".into(), "microservice".into(), "ecs".into(), "aks".into(), "gke".into(), "kubernetes".into(), "k8s".into()],
        },
        CloudPattern {
            name: "serverless_migration".into(),
            description: "Migrate event-driven or periodic workloads to serverless compute.".into(),
            cloud_providers: vec!["aws".into(), "azure".into(), "gcp".into()],
            use_case: "Batch jobs, API backends, event processing, cron tasks with variable load.".into(),
            example_iac: r#"# Terraform Lambda example
resource "aws_lambda_function" "handler" {
  function_name = "event-handler"
  runtime       = "python3.12"
  handler       = "main.handler"
  filename      = "handler.zip"
  memory_size   = 256
  timeout       = 30
}"#.into(),
            keywords: vec!["serverless".into(), "lambda".into(), "function".into(), "event".into(), "batch".into(), "cron".into(), "api".into(), "webhook".into()],
        },
        CloudPattern {
            name: "database_modernization".into(),
            description: "Migrate self-managed databases to cloud-managed services for reduced ops overhead.".into(),
            cloud_providers: vec!["aws".into(), "azure".into(), "gcp".into()],
            use_case: "Self-managed MySQL/PostgreSQL/SQL Server migration, NoSQL adoption, read replica scaling.".into(),
            example_iac: r#"# Terraform RDS example
resource "aws_db_instance" "main" {
  engine               = "postgres"
  engine_version       = "15"
  instance_class       = "db.t3.medium"
  allocated_storage    = 100
  multi_az             = true
  backup_retention_period = 7
  storage_encrypted    = true
}"#.into(),
            keywords: vec!["database".into(), "mysql".into(), "postgres".into(), "sql".into(), "rds".into(), "nosql".into(), "dynamo".into(), "mongodb".into(), "migration".into()],
        },
        CloudPattern {
            name: "api_gateway".into(),
            description: "Centralize API management with rate limiting, auth, and routing.".into(),
            cloud_providers: vec!["aws".into(), "azure".into(), "gcp".into()],
            use_case: "Public API exposure, microservice routing, API versioning, throttling.".into(),
            example_iac: r#"# Terraform API Gateway example
resource "aws_apigatewayv2_api" "main" {
  name          = "app-api"
  protocol_type = "HTTP"
}
resource "aws_apigatewayv2_stage" "prod" {
  api_id      = aws_apigatewayv2_api.main.id
  name        = "prod"
  auto_deploy = true
}"#.into(),
            keywords: vec!["api".into(), "gateway".into(), "rest".into(), "graphql".into(), "routing".into(), "rate limit".into(), "throttl".into()],
        },
        CloudPattern {
            name: "service_mesh".into(),
            description: "Implement service mesh for observability, traffic management, and security between microservices.".into(),
            cloud_providers: vec!["aws".into(), "azure".into(), "gcp".into()],
            use_case: "Microservice communication, mTLS, traffic splitting, canary deployments.".into(),
            example_iac: r#"# AWS App Mesh example
resource "aws_appmesh_mesh" "main" {
  name = "app-mesh"
}
resource "aws_appmesh_virtual_service" "app" {
  name      = "app.local"
  mesh_name = aws_appmesh_mesh.main.name
}"#.into(),
            keywords: vec!["mesh".into(), "istio".into(), "envoy".into(), "sidecar".into(), "mtls".into(), "canary".into(), "traffic".into(), "microservice".into()],
        },
    ]
}

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

    #[test]
    fn built_in_patterns_are_populated() {
        let patterns = built_in_patterns();
        assert_eq!(patterns.len(), 5);
        let names: Vec<&str> = patterns.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"containerization"));
        assert!(names.contains(&"serverless_migration"));
        assert!(names.contains(&"database_modernization"));
        assert!(names.contains(&"api_gateway"));
        assert!(names.contains(&"service_mesh"));
    }

    #[tokio::test]
    async fn match_returns_containerization_for_monolith() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "match",
                "workload": "We have a monolith Java application running on VMs that we want to containerize."
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("containerization"));
    }

    #[tokio::test]
    async fn match_returns_serverless_for_batch_workload() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "match",
                "workload": "Batch processing cron jobs that handle event data"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("serverless_migration"));
    }

    #[tokio::test]
    async fn match_filters_by_cloud_provider() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "match",
                "workload": "Container deployment with Kubernetes",
                "cloud": "aws"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("containerization"));
    }

    #[tokio::test]
    async fn list_returns_all_patterns() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "list"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("\"patterns_count\": 5"));
    }

    #[tokio::test]
    async fn match_with_empty_workload_returns_error() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "match",
                "workload": ""
            }))
            .await
            .unwrap();

        assert!(!result.success);
        assert!(result.error.is_some());
    }

    #[tokio::test]
    async fn match_database_workload_finds_db_modernization() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "match",
                "workload": "Self-hosted PostgreSQL database needs migration to managed service"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("database_modernization"));
    }

    #[test]
    fn pattern_matching_scores_correctly() {
        let tool = CloudPatternsTool::new();
        let matches =
            tool.match_patterns("microservice container docker kubernetes deployment", None);
        // containerization should rank highest (most keyword matches)
        assert!(!matches.is_empty());
        assert_eq!(matches[0]["name"], "containerization");
    }

    #[tokio::test]
    async fn unknown_action_returns_error() {
        let tool = CloudPatternsTool::new();
        let result = tool
            .execute(json!({
                "action": "deploy"
            }))
            .await
            .unwrap();

        assert!(!result.success);
        assert!(result.error.unwrap().contains("Unknown action"));
    }
}