feat: add comprehensive SKILL.md skills and remove legacy instruments

## Skills Added - brainstorming: Structured requirements exploration before implementation - debugging: Systematic debugging methodology - tdd: Test-driven development workflow - code_review: Comprehensive code review checklist - git_workflow: Git branching and collaboration best practices - api_development: RESTful and GraphQL API design - docker_devops: Container and CI/CD best practices - database_design: Schema design and query optimization - prompt_engineering: LLM prompt crafting best practices - security_audit: OWASP-based security review - create_skill: Wizard for creating new skills easily ## Changes - Removed legacy instruments directory completely - Updated README, docs, and knowledge files to reference skills - Added skills_cli.py for easy skill management - All skills follow open SKILL.md standard (Anthropic) - Compatible with Claude Code, Cursor, Goose, Codex CLI, Copilot ## Usage - Skills auto-load into memory via vector database - Use `python -m python.helpers.skills_cli` for management - Create custom skills in skills/custom/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

TerminallyLazy committed Dec 26, 2025 at 07:38 UTC 672a7496107184000e932925c564e7c131182088
21 files changed +3798 -38
README.md
+1 -1
@@ -63,7 +63,7 @@ Agent Zero now supports **Projects** – isolated workspaces with their own prom
63 - Tool usage functionality has been developed from scratch to be the most compatible and reliable, even with very small models.
64 - **Default Tools:** Agent Zero includes tools like knowledge, code execution, and communication.
65 - **Creating Custom Tools:** Extend Agent Zero's functionality by creating your own custom tools.
66 -- **Instruments:** Instruments are a new type of tool that allow you to create custom functions and procedures that can be called by Agent Zero.
66 +- **Skills (SKILL.md Standard):** Skills are contextual expertise loaded dynamically when relevant. They use the open SKILL.md standard (developed by Anthropic), making them compatible with Claude Code, Cursor, Goose, OpenAI Codex CLI, and GitHub Copilot.
67
68 3. **Multi-agent Cooperation**
69
docs/usage.md
+1 -1
@@ -259,7 +259,7 @@ By default, Agent Zero backs up your most important data:
259 * **Memory System**: Agent memories and learned information
260 * **Chat History**: All your conversations and interactions
261 * **Configuration Files**: Settings, API keys, and system preferences
262 -* **Custom Instruments**: Any tools you've added or modified
262 +* **Custom Skills**: Any skills you've added or modified (SKILL.md format)
263 * **Uploaded Files**: Documents and files you've worked with
264
265 #### Customizing Backup Content
instruments/custom/.gitkeep
instruments/default/.DS_Store
Binary files a/instruments/default/.DS_Store and /dev/null differ
instruments/default/.gitkeep
instruments/default/yt_download/download_video.py deleted
-12
@@ -1,12 +0,0 @@
1 -import sys
2 -import yt_dlp # type: ignore
3 -
4 -if len(sys.argv) != 2:
5 - print("Usage: python3 download_video.py <url>")
6 - sys.exit(1)
7 -
8 -url = sys.argv[1]
9 -
10 -ydl_opts = {}
11 -with yt_dlp.YoutubeDL(ydl_opts) as ydl:
12 - ydl.download([url])
instruments/default/yt_download/yt_download.md deleted
-11
@@ -1,11 +0,0 @@
1 -# Problem
2 -Download a YouTube video
3 -# Solution
4 -1. If folder is specified, cd to it
5 -2. Run the shell script with your video URL:
6 -
7 -```bash
8 -bash /a0/instruments/default/yt_download/yt_download.sh <url>
9 -```
10 -3. Replace `<url>` with your video URL.
11 -4. The script will handle the installation of yt-dlp and the download process.
instruments/default/yt_download/yt_download.sh deleted
-10
@@ -1,10 +0,0 @@
1 -#!/bin/bash
2 -
3 -# Install yt-dlp and ffmpeg
4 -sudo apt-get update && sudo apt-get install -y yt-dlp ffmpeg
5 -
6 -# Install yt-dlp using pip
7 -pip install --upgrade yt-dlp
8 -
9 -# Call the Python script to download the video
10 -python3 /a0/instruments/default/yt_download/download_video.py "$1"
knowledge/default/main/about/installation.md
+3 -3
@@ -80,7 +80,7 @@ The following user guide provides instructions for installing and running Agent
80 - This directory will contain all your Agent Zero files, like the legacy root folder structure:
81 - `/memory` - Agent's memory and learned information
82 - `/knowledge` - Knowledge base
83 - - `/instruments` - Instruments and functions
83 + - `/skills` - Skills (SKILL.md standard)
84 - `/prompts` - Prompt files
85 - `/work_dir` - Working directory
86 - `.env` - Your API keys
@@ -301,12 +301,12 @@ For developers or users who need to run Agent Zero directly on their system,see
301 - To update to the new Docker runtime version, you might want to backup the following files and directories:
302 - `/memory` - Agent's memory
303 - `/knowledge` - Custom knowledge base (if you imported any custom knowledge files)
304 - - `/instruments` - Custom instruments and functions (if you created any custom)
304 + - `/skills` - Custom skills (if you created any custom SKILL.md files)
305 - `/tmp/settings.json` - Your Agent Zero settings
306 - `/tmp/chats/` - Your chat history
307 - Once you have saved these files and directories, you can proceed with the Docker runtime [installation instructions above](#windows-macos-and-linux-setup-guide) setup guide.
308 - Reach for the folder where you saved your data and copy it to the new Agent Zero folder set during the installation process.
309 -- Agent Zero will automatically detect your saved data and use it across memory, knowledge, instruments, prompts and settings.
309 +- Agent Zero will automatically detect your saved data and use it across memory, knowledge, skills, prompts and settings.
310
311 > [!IMPORTANT]
312 > If you have issues loading your settings, you can try to delete the `/tmp/settings.json` file and let Agent Zero generate a new one.
python/helpers/skills_cli.py new
+364
@@ -0,0 +1,364 @@
1 +#!/usr/bin/env python3
2 +"""
3 +Skills CLI - Easy skill management for Agent Zero
4 +
5 +Usage:
6 + python -m python.helpers.skills_cli list List all skills
7 + python -m python.helpers.skills_cli create <name> Create a new skill
8 + python -m python.helpers.skills_cli show <name> Show skill details
9 + python -m python.helpers.skills_cli validate <name> Validate a skill
10 + python -m python.helpers.skills_cli search <query> Search skills
11 +"""
12 +
13 +import argparse
14 +import os
15 +import sys
16 +import yaml
17 +import re
18 +from pathlib import Path
19 +from typing import Optional, List, Dict, Any
20 +from dataclasses import dataclass
21 +from datetime import datetime
22 +
23 +# Add parent directory to path for imports
24 +sys.path.insert(0, str(Path(__file__).parent.parent.parent))
25 +
26 +from python.helpers import files
27 +
28 +
29 +@dataclass
30 +class Skill:
31 + """Represents a skill loaded from SKILL.md"""
32 + name: str
33 + description: str
34 + path: Path
35 + version: str = "1.0.0"
36 + author: str = ""
37 + tags: List[str] = None
38 + trigger_patterns: List[str] = None
39 + content: str = ""
40 +
41 + def __post_init__(self):
42 + if self.tags is None:
43 + self.tags = []
44 + if self.trigger_patterns is None:
45 + self.trigger_patterns = []
46 +
47 +
48 +def get_skills_dirs() -> List[Path]:
49 + """Get all skill directories"""
50 + base = Path(files.get_abs_path("skills"))
51 + return [
52 + base / "builtin",
53 + base / "custom",
54 + base / "shared",
55 + ]
56 +
57 +
58 +def parse_skill_file(skill_path: Path) -> Optional[Skill]:
59 + """Parse a SKILL.md file and return a Skill object"""
60 + try:
61 + content = skill_path.read_text(encoding="utf-8")
62 +
63 + # Parse YAML frontmatter
64 + if content.startswith("---"):
65 + parts = content.split("---", 2)
66 + if len(parts) >= 3:
67 + frontmatter = yaml.safe_load(parts[1])
68 + body = parts[2].strip()
69 +
70 + return Skill(
71 + name=frontmatter.get("name", skill_path.parent.name),
72 + description=frontmatter.get("description", ""),
73 + path=skill_path.parent,
74 + version=frontmatter.get("version", "1.0.0"),
75 + author=frontmatter.get("author", ""),
76 + tags=frontmatter.get("tags", []),
77 + trigger_patterns=frontmatter.get("trigger_patterns", []),
78 + content=body,
79 + )
80 +
81 + return None
82 + except Exception as e:
83 + print(f"Error parsing {skill_path}: {e}")
84 + return None
85 +
86 +
87 +def list_skills() -> List[Skill]:
88 + """List all available skills"""
89 + skills = []
90 + for skills_dir in get_skills_dirs():
91 + if not skills_dir.exists():
92 + continue
93 + for skill_dir in skills_dir.iterdir():
94 + if skill_dir.is_dir():
95 + skill_file = skill_dir / "SKILL.md"
96 + if skill_file.exists():
97 + skill = parse_skill_file(skill_file)
98 + if skill:
99 + skills.append(skill)
100 + return skills
101 +
102 +
103 +def find_skill(name: str) -> Optional[Skill]:
104 + """Find a skill by name"""
105 + for skill in list_skills():
106 + if skill.name == name or skill.path.name == name:
107 + return skill
108 + return None
109 +
110 +
111 +def search_skills(query: str) -> List[Skill]:
112 + """Search skills by name, description, or tags"""
113 + query = query.lower()
114 + results = []
115 + for skill in list_skills():
116 + if (
117 + query in skill.name.lower()
118 + or query in skill.description.lower()
119 + or any(query in tag.lower() for tag in skill.tags)
120 + or any(query in trigger.lower() for trigger in skill.trigger_patterns)
121 + ):
122 + results.append(skill)
123 + return results
124 +
125 +
126 +def validate_skill(skill: Skill) -> List[str]:
127 + """Validate a skill and return list of issues"""
128 + issues = []
129 +
130 + # Required fields
131 + if not skill.name:
132 + issues.append("Missing required field: name")
133 + if not skill.description:
134 + issues.append("Missing required field: description")
135 +
136 + # Name format
137 + if skill.name and not re.match(r"^[a-z0-9_-]+$", skill.name):
138 + issues.append(f"Invalid name format: '{skill.name}' (use lowercase, hyphens, underscores)")
139 +
140 + # Description length
141 + if skill.description and len(skill.description) < 20:
142 + issues.append("Description is too short (minimum 20 characters)")
143 +
144 + # Content
145 + if len(skill.content) < 100:
146 + issues.append("Skill content is too short (minimum 100 characters)")
147 +
148 + # Check for associated files
149 + skill_dir = skill.path
150 + has_scripts = (skill_dir / "scripts").exists()
151 + has_docs = (skill_dir / "docs").exists()
152 +
153 + return issues
154 +
155 +
156 +def create_skill(name: str, description: str = "", author: str = "") -> Path:
157 + """Create a new skill from template"""
158 + # Use custom directory for user-created skills
159 + custom_dir = Path(files.get_abs_path("skills/custom"))
160 + custom_dir.mkdir(parents=True, exist_ok=True)
161 +
162 + skill_dir = custom_dir / name
163 + if skill_dir.exists():
164 + raise ValueError(f"Skill '{name}' already exists at {skill_dir}")
165 +
166 + # Create directory structure
167 + skill_dir.mkdir(parents=True)
168 + (skill_dir / "scripts").mkdir()
169 + (skill_dir / "docs").mkdir()
170 +
171 + # Create SKILL.md from template
172 + skill_content = f'''---
173 +name: "{name}"
174 +description: "{description or 'Description of what this skill does and when to use it'}"
175 +version: "1.0.0"
176 +author: "{author or 'Your Name'}"
177 +tags: ["custom"]
178 +trigger_patterns:
179 + - "{name}"
180 +---
181 +
182 +# {name.replace("-", " ").replace("_", " ").title()}
183 +
184 +## When to Use
185 +
186 +Describe when this skill should be activated.
187 +
188 +## Instructions
189 +
190 +Provide detailed instructions for the agent to follow.
191 +
192 +### Step 1: First Step
193 +
194 +Description of what to do first.
195 +
196 +### Step 2: Second Step
197 +
198 +Description of what to do next.
199 +
200 +## Examples
201 +
202 +**User**: "Example prompt that triggers this skill"
203 +
204 +**Agent Response**:
205 +> Example of how the agent should respond
206 +
207 +## Tips
208 +
209 +- Tip 1: Helpful guidance
210 +- Tip 2: More helpful guidance
211 +
212 +## Anti-Patterns
213 +
214 +- Don't do this
215 +- Avoid that
216 +'''
217 +
218 + skill_file = skill_dir / "SKILL.md"
219 + skill_file.write_text(skill_content, encoding="utf-8")
220 +
221 + # Create placeholder README in docs
222 + readme = skill_dir / "docs" / "README.md"
223 + readme.write_text(f"# {name}\n\nAdditional documentation for the {name} skill.\n")
224 +
225 + return skill_dir
226 +
227 +
228 +def print_skill_table(skills: List[Skill]):
229 + """Print skills in a formatted table"""
230 + if not skills:
231 + print("No skills found.")
232 + return
233 +
234 + # Calculate column widths
235 + name_width = max(len(s.name) for s in skills) + 2
236 + desc_width = 50
237 +
238 + # Print header
239 + print(f"\n{'Name':<{name_width}} {'Version':<10} {'Tags':<20} Description")
240 + print("-" * (name_width + 80))
241 +
242 + # Print skills
243 + for skill in skills:
244 + tags = ", ".join(skill.tags[:3])
245 + if len(skill.tags) > 3:
246 + tags += "..."
247 + desc = skill.description[:desc_width]
248 + if len(skill.description) > desc_width:
249 + desc += "..."
250 + print(f"{skill.name:<{name_width}} {skill.version:<10} {tags:<20} {desc}")
251 +
252 + print(f"\nTotal: {len(skills)} skills")
253 +
254 +
255 +def main():
256 + parser = argparse.ArgumentParser(
257 + description="Agent Zero Skills CLI",
258 + formatter_class=argparse.RawDescriptionHelpFormatter,
259 + epilog="""
260 +Examples:
261 + %(prog)s list List all skills
262 + %(prog)s create my-skill Create a new skill
263 + %(prog)s show brainstorming Show skill details
264 + %(prog)s validate my-skill Validate a skill
265 + %(prog)s search python Search for skills
266 + """
267 + )
268 +
269 + subparsers = parser.add_subparsers(dest="command", help="Available commands")
270 +
271 + # List command
272 + list_parser = subparsers.add_parser("list", help="List all skills")
273 + list_parser.add_argument("--tags", help="Filter by tags (comma-separated)")
274 +
275 + # Create command
276 + create_parser = subparsers.add_parser("create", help="Create a new skill")
277 + create_parser.add_argument("name", help="Skill name (lowercase, use hyphens)")
278 + create_parser.add_argument("-d", "--description", help="Skill description")
279 + create_parser.add_argument("-a", "--author", help="Author name")
280 +
281 + # Show command
282 + show_parser = subparsers.add_parser("show", help="Show skill details")
283 + show_parser.add_argument("name", help="Skill name")
284 +
285 + # Validate command
286 + validate_parser = subparsers.add_parser("validate", help="Validate a skill")
287 + validate_parser.add_argument("name", help="Skill name")
288 +
289 + # Search command
290 + search_parser = subparsers.add_parser("search", help="Search skills")
291 + search_parser.add_argument("query", help="Search query")
292 +
293 + args = parser.parse_args()
294 +
295 + if args.command == "list":
296 + skills = list_skills()
297 + if args.tags:
298 + filter_tags = [t.strip().lower() for t in args.tags.split(",")]
299 + skills = [s for s in skills if any(t in [tag.lower() for tag in s.tags] for t in filter_tags)]
300 + print_skill_table(skills)
301 +
302 + elif args.command == "create":
303 + try:
304 + skill_dir = create_skill(args.name, args.description, args.author)
305 + print(f"\n✅ Created skill at: {skill_dir}")
306 + print(f"\nNext steps:")
307 + print(f" 1. Edit {skill_dir / 'SKILL.md'} to add your instructions")
308 + print(f" 2. Add any helper scripts to {skill_dir / 'scripts'}/")
309 + print(f" 3. Run: python -m python.helpers.skills_cli validate {args.name}")
310 + except ValueError as e:
311 + print(f"\n❌ Error: {e}")
312 + sys.exit(1)
313 +
314 + elif args.command == "show":
315 + skill = find_skill(args.name)
316 + if skill:
317 + print(f"\n{'=' * 60}")
318 + print(f"Skill: {skill.name}")
319 + print(f"{'=' * 60}")
320 + print(f"Version: {skill.version}")
321 + print(f"Author: {skill.author or 'Unknown'}")
322 + print(f"Path: {skill.path}")
323 + print(f"Tags: {', '.join(skill.tags) if skill.tags else 'None'}")
324 + print(f"Triggers: {', '.join(skill.trigger_patterns) if skill.trigger_patterns else 'None'}")
325 + print(f"\nDescription:")
326 + print(f" {skill.description}")
327 + print(f"\nContent Preview (first 500 chars):")
328 + print("-" * 60)
329 + print(skill.content[:500])
330 + if len(skill.content) > 500:
331 + print("...")
332 + print("-" * 60)
333 + else:
334 + print(f"\n❌ Skill '{args.name}' not found")
335 + sys.exit(1)
336 +
337 + elif args.command == "validate":
338 + skill = find_skill(args.name)
339 + if skill:
340 + issues = validate_skill(skill)
341 + if issues:
342 + print(f"\n⚠️ Validation issues for '{args.name}':")
343 + for issue in issues:
344 + print(f" - {issue}")
345 + else:
346 + print(f"\n✅ Skill '{args.name}' is valid!")
347 + else:
348 + print(f"\n❌ Skill '{args.name}' not found")
349 + sys.exit(1)
350 +
351 + elif args.command == "search":
352 + results = search_skills(args.query)
353 + if results:
354 + print(f"\nSearch results for '{args.query}':")
355 + print_skill_table(results)
356 + else:
357 + print(f"\nNo skills found matching '{args.query}'")
358 +
359 + else:
360 + parser.print_help()
361 +
362 +
363 +if __name__ == "__main__":
364 + main()
skills/builtin/api_development/SKILL.md new
+385
@@ -0,0 +1,385 @@
1 +---
2 +name: "api_development"
3 +description: "Best practices for designing and implementing RESTful and GraphQL APIs. Use when building, designing, or reviewing APIs."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["api", "rest", "graphql", "design", "backend", "web"]
7 +trigger_patterns:
8 + - "api"
9 + - "endpoint"
10 + - "rest"
11 + - "graphql"
12 + - "http"
13 +---
14 +
15 +# API Development Skill
16 +
17 +Best practices for designing, implementing, and documenting APIs.
18 +
19 +## RESTful API Design
20 +
21 +### URL Structure
22 +
23 +```
24 +https://api.example.com/v1/resources/{id}/subresources
25 +```
26 +
27 +**Guidelines:**
28 +- Use nouns, not verbs: `/users` not `/getUsers`
29 +- Use plural nouns: `/users` not `/user`
30 +- Use kebab-case: `/user-profiles` not `/userProfiles`
31 +- Nest resources logically: `/users/{id}/orders`
32 +- Version your API: `/v1/`, `/v2/`
33 +
34 +### HTTP Methods
35 +
36 +| Method | Purpose | Example |
37 +|--------|---------|---------|
38 +| `GET` | Retrieve resource(s) | `GET /users/123` |
39 +| `POST` | Create resource | `POST /users` |
40 +| `PUT` | Replace resource | `PUT /users/123` |
41 +| `PATCH` | Partial update | `PATCH /users/123` |
42 +| `DELETE` | Remove resource | `DELETE /users/123` |
43 +
44 +### Status Codes
45 +
46 +| Code | Meaning | When to Use |
47 +|------|---------|-------------|
48 +| `200 OK` | Success | GET, PUT, PATCH success |
49 +| `201 Created` | Resource created | POST success |
50 +| `204 No Content` | Success, no body | DELETE success |
51 +| `400 Bad Request` | Invalid input | Validation failed |
52 +| `401 Unauthorized` | Not authenticated | Missing/invalid token |
53 +| `403 Forbidden` | Not authorized | Insufficient permissions |
54 +| `404 Not Found` | Resource not found | ID doesn't exist |
55 +| `409 Conflict` | Resource conflict | Duplicate entry |
56 +| `422 Unprocessable` | Semantic error | Valid syntax, invalid data |
57 +| `429 Too Many` | Rate limited | Exceeded request limit |
58 +| `500 Server Error` | Internal error | Unexpected failure |
59 +
60 +### Request/Response Format
61 +
62 +**Request:**
63 +```http
64 +POST /api/v1/users HTTP/1.1
65 +Content-Type: application/json
66 +Authorization: Bearer <token>
67 +
68 +{
69 + "email": "user@example.com",
70 + "name": "John Doe",
71 + "role": "user"
72 +}
73 +```
74 +
75 +**Success Response:**
76 +```json
77 +{
78 + "data": {
79 + "id": "123",
80 + "email": "user@example.com",
81 + "name": "John Doe",
82 + "role": "user",
83 + "created_at": "2024-01-15T10:30:00Z"
84 + },
85 + "meta": {
86 + "request_id": "abc-123"
87 + }
88 +}
89 +```
90 +
91 +**Error Response:**
92 +```json
93 +{
94 + "error": {
95 + "code": "VALIDATION_ERROR",
96 + "message": "Invalid input data",
97 + "details": [
98 + {
99 + "field": "email",
100 + "message": "Invalid email format"
101 + }
102 + ]
103 + },
104 + "meta": {
105 + "request_id": "abc-123"
106 + }
107 +}
108 +```
109 +
110 +### Pagination
111 +
112 +**Request:**
113 +```http
114 +GET /api/v1/users?page=2&per_page=20
115 +```
116 +
117 +**Response:**
118 +```json
119 +{
120 + "data": [...],
121 + "meta": {
122 + "current_page": 2,
123 + "per_page": 20,
124 + "total_pages": 10,
125 + "total_count": 195
126 + },
127 + "links": {
128 + "first": "/api/v1/users?page=1&per_page=20",
129 + "prev": "/api/v1/users?page=1&per_page=20",
130 + "next": "/api/v1/users?page=3&per_page=20",
131 + "last": "/api/v1/users?page=10&per_page=20"
132 + }
133 +}
134 +```
135 +
136 +### Filtering & Sorting
137 +
138 +```http
139 +# Filtering
140 +GET /api/v1/users?status=active&role=admin
141 +
142 +# Sorting
143 +GET /api/v1/users?sort=created_at&order=desc
144 +
145 +# Multiple sort fields
146 +GET /api/v1/users?sort=-created_at,name
147 +```
148 +
149 +### Field Selection
150 +
151 +```http
152 +GET /api/v1/users?fields=id,name,email
153 +```
154 +
155 +## Authentication
156 +
157 +### JWT (JSON Web Token)
158 +
159 +```javascript
160 +// Token structure
161 +{
162 + "header": {
163 + "alg": "HS256",
164 + "typ": "JWT"
165 + },
166 + "payload": {
167 + "sub": "user_123",
168 + "email": "user@example.com",
169 + "role": "admin",
170 + "iat": 1516239022,
171 + "exp": 1516242622
172 + },
173 + "signature": "..."
174 +}
175 +```
176 +
177 +**Implementation:**
178 +
179 +```python
180 +# Python example with PyJWT
181 +import jwt
182 +from datetime import datetime, timedelta
183 +
184 +def create_token(user_id: str, secret: str) -> str:
185 + payload = {
186 + "sub": user_id,
187 + "iat": datetime.utcnow(),
188 + "exp": datetime.utcnow() + timedelta(hours=1)
189 + }
190 + return jwt.encode(payload, secret, algorithm="HS256")
191 +
192 +def verify_token(token: str, secret: str) -> dict:
193 + try:
194 + return jwt.decode(token, secret, algorithms=["HS256"])
195 + except jwt.ExpiredSignatureError:
196 + raise AuthError("Token expired")
197 + except jwt.InvalidTokenError:
198 + raise AuthError("Invalid token")
199 +```
200 +
201 +### API Keys
202 +
203 +```http
204 +# Header
205 +Authorization: Api-Key <key>
206 +
207 +# Query param (less secure)
208 +GET /api/v1/resource?api_key=<key>
209 +```
210 +
211 +## Rate Limiting
212 +
213 +**Headers:**
214 +```http
215 +X-RateLimit-Limit: 1000
216 +X-RateLimit-Remaining: 999
217 +X-RateLimit-Reset: 1609459200
218 +```
219 +
220 +**Implementation:**
221 +```python
222 +from functools import wraps
223 +import time
224 +
225 +class RateLimiter:
226 + def __init__(self, max_requests: int, window_seconds: int):
227 + self.max_requests = max_requests
228 + self.window = window_seconds
229 + self.requests = {}
230 +
231 + def is_allowed(self, client_id: str) -> bool:
232 + now = time.time()
233 + window_start = now - self.window
234 +
235 + # Clean old requests
236 + self.requests[client_id] = [
237 + t for t in self.requests.get(client_id, [])
238 + if t > window_start
239 + ]
240 +
241 + if len(self.requests[client_id]) >= self.max_requests:
242 + return False
243 +
244 + self.requests[client_id].append(now)
245 + return True
246 +```
247 +
248 +## Input Validation
249 +
250 +```python
251 +from pydantic import BaseModel, EmailStr, validator
252 +
253 +class CreateUserRequest(BaseModel):
254 + email: EmailStr
255 + name: str
256 + age: int
257 +
258 + @validator('name')
259 + def name_not_empty(cls, v):
260 + if not v.strip():
261 + raise ValueError('Name cannot be empty')
262 + return v.strip()
263 +
264 + @validator('age')
265 + def age_valid(cls, v):
266 + if v < 0 or v > 150:
267 + raise ValueError('Age must be between 0 and 150')
268 + return v
269 +```
270 +
271 +## Error Handling
272 +
273 +```python
274 +class APIError(Exception):
275 + def __init__(self, code: str, message: str, status_code: int = 400):
276 + self.code = code
277 + self.message = message
278 + self.status_code = status_code
279 +
280 +@app.errorhandler(APIError)
281 +def handle_api_error(error):
282 + return jsonify({
283 + "error": {
284 + "code": error.code,
285 + "message": error.message
286 + }
287 + }), error.status_code
288 +
289 +# Usage
290 +raise APIError("USER_NOT_FOUND", "User with ID 123 not found", 404)
291 +```
292 +
293 +## API Documentation
294 +
295 +### OpenAPI/Swagger Example
296 +
297 +```yaml
298 +openapi: 3.0.0
299 +info:
300 + title: User API
301 + version: 1.0.0
302 +
303 +paths:
304 + /users:
305 + get:
306 + summary: List all users
307 + parameters:
308 + - name: page
309 + in: query
310 + schema:
311 + type: integer
312 + default: 1
313 + responses:
314 + '200':
315 + description: Successful response
316 + content:
317 + application/json:
318 + schema:
319 + $ref: '#/components/schemas/UserList'
320 + post:
321 + summary: Create a user
322 + requestBody:
323 + required: true
324 + content:
325 + application/json:
326 + schema:
327 + $ref: '#/components/schemas/CreateUser'
328 + responses:
329 + '201':
330 + description: User created
331 +
332 +components:
333 + schemas:
334 + User:
335 + type: object
336 + properties:
337 + id:
338 + type: string
339 + email:
340 + type: string
341 + name:
342 + type: string
343 +```
344 +
345 +## Security Checklist
346 +
347 +```markdown
348 +- [ ] Use HTTPS only
349 +- [ ] Validate all input
350 +- [ ] Sanitize output
351 +- [ ] Use parameterized queries
352 +- [ ] Implement rate limiting
353 +- [ ] Use secure headers (CORS, CSP)
354 +- [ ] Don't expose internal errors
355 +- [ ] Log security events
356 +- [ ] Rotate secrets regularly
357 +- [ ] Version your API
358 +```
359 +
360 +## Performance Tips
361 +
362 +1. **Use caching headers**
363 + ```http
364 + Cache-Control: max-age=3600
365 + ETag: "abc123"
366 + ```
367 +
368 +2. **Implement compression**
369 + ```http
370 + Accept-Encoding: gzip
371 + Content-Encoding: gzip
372 + ```
373 +
374 +3. **Use pagination** for large datasets
375 +
376 +4. **Implement field selection** to reduce payload
377 +
378 +5. **Consider async processing** for long operations
379 + ```json
380 + {
381 + "status": "processing",
382 + "job_id": "job_123",
383 + "check_url": "/api/v1/jobs/job_123"
384 + }
385 + ```
skills/builtin/brainstorming/SKILL.md new
+123
@@ -0,0 +1,123 @@
1 +---
2 +name: "brainstorming"
3 +description: "Structured brainstorming and requirements exploration before implementation. Use this BEFORE any creative work like building features, creating components, or adding functionality."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["planning", "design", "requirements", "architecture", "creative"]
7 +trigger_patterns:
8 + - "create"
9 + - "build"
10 + - "implement"
11 + - "add feature"
12 + - "design"
13 + - "develop"
14 +---
15 +
16 +# Brainstorming Skill
17 +
18 +**CRITICAL**: Use this skill BEFORE writing any implementation code. This ensures proper requirements exploration and design alignment.
19 +
20 +## When to Use
21 +
22 +Activate this skill when you encounter:
23 +- "Create a new feature..."
24 +- "Build a component that..."
25 +- "Implement X functionality..."
26 +- "Add support for..."
27 +- "Design a system that..."
28 +
29 +## The Brainstorming Process
30 +
31 +### Phase 1: Understanding Intent (5 questions max)
32 +
33 +Ask clarifying questions to understand:
34 +
35 +1. **Goal Clarity**: What specific outcome does the user want?
36 +2. **Context**: What existing code/systems does this interact with?
37 +3. **Constraints**: Are there performance, security, or compatibility requirements?
38 +4. **Edge Cases**: What happens in failure scenarios?
39 +5. **Success Criteria**: How will we know it's working correctly?
40 +
41 +### Phase 2: Design Options
42 +
43 +Present 2-3 implementation approaches with trade-offs:
44 +
45 +```markdown
46 +## Option A: [Name]
47 +**Approach**: Brief description
48 +**Pros**: List benefits
49 +**Cons**: List drawbacks
50 +**Best for**: When to choose this
51 +
52 +## Option B: [Name]
53 +**Approach**: Brief description
54 +**Pros**: List benefits
55 +**Cons**: List drawbacks
56 +**Best for**: When to choose this
57 +```
58 +
59 +### Phase 3: Technical Specification
60 +
61 +Once approach is chosen, document:
62 +
63 +1. **Files to Create/Modify**: List with brief description
64 +2. **Dependencies**: External packages or internal modules needed
65 +3. **Data Flow**: How data moves through the system
66 +4. **API Contracts**: Input/output specifications
67 +5. **Test Strategy**: How this will be tested
68 +
69 +### Phase 4: Implementation Plan
70 +
71 +Break down into ordered tasks:
72 +
73 +```markdown
74 +## Implementation Tasks
75 +1. [ ] Task 1 - Description
76 +2. [ ] Task 2 - Description (depends on 1)
77 +3. [ ] Task 3 - Description
78 +4. [ ] Task 4 - Integration testing
79 +```
80 +
81 +## Anti-Patterns to Avoid
82 +
83 +- **Jumping to Code**: Never start coding without understanding requirements
84 +- **Single Solution Bias**: Always consider at least 2 approaches
85 +- **Ignoring Context**: Always examine existing patterns in the codebase
86 +- **Over-Engineering**: Keep solutions proportional to the problem
87 +- **Under-Specifying**: Be specific enough that implementation is clear
88 +
89 +## Example Session
90 +
91 +**User**: "Add dark mode to the application"
92 +
93 +**Agent Response**:
94 +> Before implementing dark mode, let me understand your requirements:
95 +>
96 +> 1. **Scope**: Should this apply to the entire application or specific sections?
97 +> 2. **Toggle**: How should users switch modes? (button, system preference, both?)
98 +> 3. **Persistence**: Should the preference be saved across sessions?
99 +> 4. **Theming Approach**: Do you have existing CSS variables, or should we create a new theme system?
100 +> 5. **Transition**: Should there be smooth transitions when switching modes?
101 +
102 +## Output Format
103 +
104 +After brainstorming, provide a clear summary:
105 +
106 +```markdown
107 +## Summary: [Feature Name]
108 +
109 +### Chosen Approach
110 +[Brief description of selected approach]
111 +
112 +### Key Decisions
113 +- Decision 1: Rationale
114 +- Decision 2: Rationale
115 +
116 +### Implementation Tasks
117 +1. Task 1
118 +2. Task 2
119 +3. Task 3
120 +
121 +### Ready to Implement
122 +Confirm with user before proceeding to implementation.
123 +```
skills/builtin/code_review/SKILL.md new
+272
@@ -0,0 +1,272 @@
1 +---
2 +name: "code_review"
3 +description: "Comprehensive code review skill for analyzing code quality, identifying issues, and suggesting improvements. Use when reviewing PRs or checking code quality."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["review", "quality", "security", "best-practices", "pr"]
7 +trigger_patterns:
8 + - "review"
9 + - "check code"
10 + - "code quality"
11 + - "pull request"
12 + - "PR"
13 +---
14 +
15 +# Code Review Skill
16 +
17 +**Goal**: Provide actionable, constructive feedback that improves code quality.
18 +
19 +## Review Categories
20 +
21 +### 1. Correctness
22 +- Does the code do what it's supposed to?
23 +- Are there logic errors?
24 +- Are edge cases handled?
25 +
26 +### 2. Security
27 +- Input validation
28 +- Authentication/authorization
29 +- SQL injection, XSS prevention
30 +- Secrets exposure
31 +
32 +### 3. Performance
33 +- Algorithmic complexity
34 +- Database query efficiency
35 +- Memory usage
36 +- Caching opportunities
37 +
38 +### 4. Maintainability
39 +- Code readability
40 +- Naming conventions
41 +- Documentation
42 +- Single responsibility
43 +
44 +### 5. Testing
45 +- Test coverage
46 +- Test quality
47 +- Edge case testing
48 +
49 +## Review Process
50 +
51 +### Phase 1: Understand Context
52 +
53 +Before reviewing:
54 +1. What is the purpose of this change?
55 +2. What problem is it solving?
56 +3. What are the requirements?
57 +4. Are there related changes elsewhere?
58 +
59 +### Phase 2: High-Level Review
60 +
61 +Look at:
62 +1. **Architecture**: Does the approach make sense?
63 +2. **Design patterns**: Are appropriate patterns used?
64 +3. **File organization**: Is code in the right place?
65 +4. **Dependencies**: Are new dependencies justified?
66 +
67 +### Phase 3: Line-by-Line Review
68 +
69 +For each file:
70 +1. Read through understanding intent
71 +2. Check for issues in each category
72 +3. Note both problems and good practices
73 +
74 +### Phase 4: Provide Feedback
75 +
76 +Structure feedback clearly:
77 +
78 +```markdown
79 +## Review Summary
80 +
81 +### Must Fix (Blockers)
82 +- [ ] **Security**: SQL injection vulnerability in line 42
83 +- [ ] **Bug**: Off-by-one error in loop at line 78
84 +
85 +### Should Fix (Important)
86 +- [ ] **Performance**: N+1 query problem in user loader
87 +- [ ] **Maintainability**: Function too long (150+ lines)
88 +
89 +### Consider (Suggestions)
90 +- [ ] **Style**: Variable naming could be more descriptive
91 +- [ ] **Testing**: Add test for empty input case
92 +
93 +### Positives
94 +- Good use of error handling
95 +- Clear separation of concerns
96 +```
97 +
98 +## Code Smells to Watch For
99 +
100 +### Complexity
101 +- **Long methods**: > 20-30 lines
102 +- **Deep nesting**: > 3-4 levels
103 +- **Too many parameters**: > 4-5 params
104 +- **God classes**: Classes doing too much
105 +
106 +### Duplication
107 +- Copy-pasted code blocks
108 +- Similar logic in multiple places
109 +- Magic numbers repeated
110 +
111 +### Coupling
112 +- Tight coupling between modules
113 +- Circular dependencies
114 +- Inappropriate intimacy
115 +
116 +### Naming
117 +- Single-letter variables (except loops)
118 +- Misleading names
119 +- Inconsistent conventions
120 +
121 +## Security Checklist
122 +
123 +```markdown
124 +- [ ] Input validation on all user input
125 +- [ ] Parameterized queries (no string concatenation for SQL)
126 +- [ ] Output encoding (prevent XSS)
127 +- [ ] Authentication checked on protected routes
128 +- [ ] Authorization checked for resource access
129 +- [ ] Sensitive data not logged
130 +- [ ] Secrets not hardcoded
131 +- [ ] HTTPS enforced for sensitive data
132 +- [ ] Rate limiting on authentication endpoints
133 +- [ ] CORS properly configured
134 +```
135 +
136 +## Feedback Guidelines
137 +
138 +### Be Constructive
139 +```markdown
140 +# Bad
141 +"This code is terrible"
142 +
143 +# Good
144 +"This approach works, but consider using X for better
145 +performance because [specific reason]"
146 +```
147 +
148 +### Be Specific
149 +```markdown
150 +# Bad
151 +"Fix the naming"
152 +
153 +# Good
154 +"Rename `d` to `document_count` for clarity.
155 +Single-letter variables make the code harder to understand"
156 +```
157 +
158 +### Explain Why
159 +```markdown
160 +# Bad
161 +"Don't use global variables"
162 +
163 +# Good
164 +"Global variables can cause issues because:
165 +1. They make testing difficult
166 +2. They create hidden dependencies
167 +3. They can be modified from anywhere
168 +
169 +Consider passing this as a parameter instead."
170 +```
171 +
172 +### Offer Solutions
173 +```markdown
174 +# Instead of just:
175 +"This is inefficient"
176 +
177 +# Provide:
178 +"This is O(n²) due to the nested loops. Consider using
179 +a Set for the lookup to achieve O(n):
180 +
181 +```python
182 +seen = set(processed_ids)
183 +for item in items:
184 + if item.id in seen: # O(1) lookup
185 + continue
186 +```"
187 +```
188 +
189 +## Review Checklist Template
190 +
191 +```markdown
192 +## Code Review: [PR Title]
193 +
194 +### Context Understanding
195 +- [ ] I understand the purpose of this change
196 +- [ ] I've reviewed related documentation/tickets
197 +
198 +### Correctness
199 +- [ ] Logic is correct
200 +- [ ] Edge cases handled
201 +- [ ] Error handling appropriate
202 +
203 +### Security
204 +- [ ] No SQL injection vulnerabilities
205 +- [ ] No XSS vulnerabilities
206 +- [ ] Authentication/authorization correct
207 +- [ ] No secrets exposed
208 +
209 +### Performance
210 +- [ ] No obvious performance issues
211 +- [ ] Database queries efficient
212 +- [ ] No memory leaks
213 +
214 +### Maintainability
215 +- [ ] Code is readable
216 +- [ ] Functions are focused
217 +- [ ] Good naming
218 +- [ ] Appropriate comments
219 +
220 +### Testing
221 +- [ ] Adequate test coverage
222 +- [ ] Tests are meaningful
223 +- [ ] Edge cases tested
224 +
225 +### Verdict
226 +- [ ] Approved
227 +- [ ] Approved with comments
228 +- [ ] Request changes
229 +```
230 +
231 +## Example Review
232 +
233 +```markdown
234 +## Review: Add user registration endpoint
235 +
236 +### Summary
237 +Generally good implementation! A few security concerns to address.
238 +
239 +### Must Fix
240 +1. **Security (line 45)**: Password stored in plain text
241 + ```python
242 + # Current
243 + user.password = request.password
244 +
245 + # Fix
246 + user.password_hash = hash_password(request.password)
247 + ```
248 +
249 +2. **Validation (line 38)**: Email not validated
250 + Add email format validation before saving
251 +
252 +### Should Fix
253 +1. **Error Handling (line 52)**: Bare except catches too much
254 + ```python
255 + # Current
256 + except:
257 + return error_response()
258 +
259 + # Fix
260 + except ValidationError as e:
261 + return error_response(str(e))
262 + ```
263 +
264 +### Consider
265 +1. Add rate limiting to prevent spam registrations
266 +2. Send confirmation email async to improve response time
267 +
268 +### Positives
269 +- Good use of transactions
270 +- Clear API response structure
271 +- Comprehensive logging
272 +```
skills/builtin/create_skill/SKILL.md new
+298
@@ -0,0 +1,298 @@
1 +---
2 +name: "create_skill"
3 +description: "Wizard for creating new Agent Zero skills. Guides users through creating well-structured SKILL.md files. Use when users want to create custom skills."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["meta", "wizard", "creation", "tutorial", "skills"]
7 +trigger_patterns:
8 + - "create skill"
9 + - "new skill"
10 + - "make skill"
11 + - "add skill"
12 + - "skill wizard"
13 +---
14 +
15 +# Create Skill Wizard
16 +
17 +This skill helps you create new Agent Zero skills that follow the SKILL.md standard.
18 +
19 +## Quick Start
20 +
21 +To create a new skill, I'll guide you through these steps:
22 +
23 +1. **Name & Purpose** - What should this skill do?
24 +2. **Trigger Patterns** - When should this skill activate?
25 +3. **Content Structure** - What instructions should the agent follow?
26 +4. **Supporting Files** - Any scripts or templates needed?
27 +
28 +## SKILL.md Format
29 +
30 +Every skill needs a `SKILL.md` file with YAML frontmatter:
31 +
32 +```yaml
33 +---
34 +name: "skill-name"
35 +description: "Clear description of what this skill does and when to use it"
36 +version: "1.0.0"
37 +author: "Your Name"
38 +tags: ["category1", "category2"]
39 +trigger_patterns:
40 + - "keyword1"
41 + - "phrase that triggers this"
42 +---
43 +
44 +# Skill Title
45 +
46 +Your skill instructions go here...
47 +```
48 +
49 +## Required Fields
50 +
51 +| Field | Description | Example |
52 +|-------|-------------|---------|
53 +| `name` | Unique identifier (lowercase, hyphens) | `"code-review"` |
54 +| `description` | When/why to use this skill | `"Review code for quality and security issues"` |
55 +
56 +## Optional Fields
57 +
58 +| Field | Description | Example |
59 +|-------|-------------|---------|
60 +| `version` | Semantic version | `"1.0.0"` |
61 +| `author` | Creator name | `"Jane Developer"` |
62 +| `tags` | Categorization keywords | `["review", "quality"]` |
63 +| `trigger_patterns` | Words/phrases that activate skill | `["review", "check code"]` |
64 +| `allowed_tools` | Tools this skill can use | `["code_execution", "web_search"]` |
65 +
66 +## Skill Directory Structure
67 +
68 +```
69 +skills/
70 +└── custom/
71 + └── my-skill/
72 + ├── SKILL.md # Required: Main skill file
73 + ├── scripts/ # Optional: Helper scripts
74 + │ ├── helper.py
75 + │ └── process.sh
76 + ├── templates/ # Optional: Templates
77 + │ └── output.md
78 + └── docs/ # Optional: Additional docs
79 + └── examples.md
80 +```
81 +
82 +## Writing Good Skill Instructions
83 +
84 +### Be Specific and Actionable
85 +
86 +```markdown
87 +# Good
88 +When reviewing code:
89 +1. Check for security vulnerabilities
90 +2. Verify error handling
91 +3. Assess test coverage
92 +
93 +# Bad
94 +Review the code and make it better.
95 +```
96 +
97 +### Include Examples
98 +
99 +```markdown
100 +## Example Usage
101 +
102 +**User**: "Review my Python function for issues"
103 +
104 +**Agent Response**:
105 +> I'll review your function using the code review checklist:
106 +>
107 +> 1. **Security**: No user input validation detected
108 +> 2. **Error Handling**: Missing try-catch for file operations
109 +> 3. **Testing**: Function is testable but no tests found
110 +```
111 +
112 +### Provide Checklists
113 +
114 +```markdown
115 +## Review Checklist
116 +- [ ] Input validation present
117 +- [ ] Error handling complete
118 +- [ ] Tests included
119 +- [ ] Documentation updated
120 +```
121 +
122 +## Creating Your Skill: Step by Step
123 +
124 +### Step 1: Define Purpose
125 +
126 +Answer these questions:
127 +- What problem does this skill solve?
128 +- When should the agent use it?
129 +- What's the expected output?
130 +
131 +### Step 2: Choose a Name
132 +
133 +- Use lowercase letters and hyphens
134 +- Be descriptive but concise
135 +- Examples: `code-review`, `data-analysis`, `deploy-helper`
136 +
137 +### Step 3: Write Trigger Patterns
138 +
139 +List words/phrases that should activate this skill:
140 +
141 +```yaml
142 +trigger_patterns:
143 + - "review"
144 + - "check code"
145 + - "code quality"
146 + - "pull request"
147 +```
148 +
149 +### Step 4: Structure Your Content
150 +
151 +Organize with clear sections:
152 +
153 +```markdown
154 +# Skill Title
155 +
156 +## When to Use
157 +Describe the trigger conditions
158 +
159 +## The Process
160 +Step-by-step instructions
161 +
162 +## Examples
163 +Show sample interactions
164 +
165 +## Tips
166 +Additional guidance
167 +```
168 +
169 +### Step 5: Add Supporting Files (Optional)
170 +
171 +If your skill needs scripts or templates:
172 +
173 +```bash
174 +# Create directory structure
175 +mkdir -p skills/custom/my-skill/{scripts,templates,docs}
176 +```
177 +
178 +## Example: Complete Skill
179 +
180 +```yaml
181 +---
182 +name: "python-optimizer"
183 +description: "Optimize Python code for performance and readability. Use when asked to improve or optimize Python code."
184 +version: "1.0.0"
185 +author: "Agent Zero Team"
186 +tags: ["python", "optimization", "performance"]
187 +trigger_patterns:
188 + - "optimize python"
189 + - "improve performance"
190 + - "make faster"
191 + - "python optimization"
192 +---
193 +
194 +# Python Optimizer
195 +
196 +## When to Use
197 +Activate when user asks to optimize, improve, or speed up Python code.
198 +
199 +## Optimization Process
200 +
201 +### Step 1: Profile First
202 +Before optimizing, understand where time is spent:
203 +```python
204 +import cProfile
205 +cProfile.run('your_function()')
206 +```
207 +
208 +### Step 2: Common Optimizations
209 +
210 +1. **Use List Comprehensions**
211 + ```python
212 + # Slow
213 + result = []
214 + for x in data:
215 + result.append(x * 2)
216 +
217 + # Fast
218 + result = [x * 2 for x in data]
219 + ```
220 +
221 +2. **Use Sets for Lookups**
222 + ```python
223 + # Slow: O(n)
224 + if item in large_list:
225 +
226 + # Fast: O(1)
227 + if item in large_set:
228 + ```
229 +
230 +3. **Use Generators for Large Data**
231 + ```python
232 + # Memory-heavy
233 + data = [process(x) for x in huge_list]
234 +
235 + # Memory-efficient
236 + data = (process(x) for x in huge_list)
237 + ```
238 +
239 +### Step 3: Verify Improvement
240 +Always measure before and after:
241 +```python
242 +import time
243 +start = time.perf_counter()
244 +# code to measure
245 +elapsed = time.perf_counter() - start
246 +print(f"Took {elapsed:.4f} seconds")
247 +```
248 +
249 +## Anti-Patterns to Avoid
250 +- Premature optimization
251 +- Optimizing without profiling
252 +- Sacrificing readability for tiny gains
253 +```
254 +
255 +## Skill Installation
256 +
257 +### Local Installation
258 +
259 +1. Create skill directory:
260 + ```bash
261 + mkdir -p skills/custom/my-skill
262 + ```
263 +
264 +2. Create SKILL.md:
265 + ```bash
266 + touch skills/custom/my-skill/SKILL.md
267 + ```
268 +
269 +3. Add content and save
270 +
271 +4. Skills are automatically loaded on next agent initialization
272 +
273 +### Sharing Skills
274 +
275 +To share skills with others:
276 +
277 +1. Create a GitHub repository
278 +2. Include the skill directory structure
279 +3. Add a README with installation instructions
280 +4. Users can copy to their `skills/custom/` directory
281 +
282 +## Testing Your Skill
283 +
284 +After creating a skill:
285 +
286 +1. Start a new conversation
287 +2. Use one of your trigger patterns
288 +3. Verify the agent follows your instructions
289 +4. Iterate and improve based on results
290 +
291 +## Need Help?
292 +
293 +Use this skill by saying:
294 +- "Help me create a new skill for [purpose]"
295 +- "I want to create a skill that [does something]"
296 +- "Create a skill wizard for [task]"
297 +
298 +I'll guide you through each step!
skills/builtin/database_design/SKILL.md new
+335
@@ -0,0 +1,335 @@
1 +---
2 +name: "database_design"
3 +description: "Database design, schema optimization, and query best practices. Use when designing schemas, optimizing queries, or working with databases."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["database", "sql", "schema", "optimization", "postgresql", "mysql"]
7 +trigger_patterns:
8 + - "database"
9 + - "schema"
10 + - "sql"
11 + - "query"
12 + - "table"
13 + - "index"
14 +---
15 +
16 +# Database Design Skill
17 +
18 +Best practices for schema design, query optimization, and database management.
19 +
20 +## Schema Design Principles
21 +
22 +### Normalization
23 +
24 +**1NF (First Normal Form)**
25 +- Each column contains atomic values
26 +- No repeating groups
27 +
28 +**2NF (Second Normal Form)**
29 +- Meet 1NF
30 +- No partial dependencies (all non-key columns depend on the entire primary key)
31 +
32 +**3NF (Third Normal Form)**
33 +- Meet 2NF
34 +- No transitive dependencies (non-key columns don't depend on other non-key columns)
35 +
36 +### Example: Normalized Schema
37 +
38 +```sql
39 +-- Users table
40 +CREATE TABLE users (
41 + id SERIAL PRIMARY KEY,
42 + email VARCHAR(255) UNIQUE NOT NULL,
43 + name VARCHAR(100) NOT NULL,
44 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
45 + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
46 +);
47 +
48 +-- Addresses table (1:N relationship)
49 +CREATE TABLE addresses (
50 + id SERIAL PRIMARY KEY,
51 + user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
52 + street VARCHAR(255) NOT NULL,
53 + city VARCHAR(100) NOT NULL,
54 + country VARCHAR(100) NOT NULL,
55 + postal_code VARCHAR(20),
56 + is_primary BOOLEAN DEFAULT FALSE
57 +);
58 +
59 +-- Orders table
60 +CREATE TABLE orders (
61 + id SERIAL PRIMARY KEY,
62 + user_id INTEGER REFERENCES users(id),
63 + address_id INTEGER REFERENCES addresses(id),
64 + status VARCHAR(50) DEFAULT 'pending',
65 + total_amount DECIMAL(10, 2) NOT NULL,
66 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
67 +);
68 +
69 +-- Order items (N:N through junction table)
70 +CREATE TABLE order_items (
71 + id SERIAL PRIMARY KEY,
72 + order_id INTEGER REFERENCES orders(id) ON DELETE CASCADE,
73 + product_id INTEGER REFERENCES products(id),
74 + quantity INTEGER NOT NULL CHECK (quantity > 0),
75 + unit_price DECIMAL(10, 2) NOT NULL
76 +);
77 +```
78 +
79 +### When to Denormalize
80 +
81 +Consider denormalization for:
82 +- Read-heavy workloads
83 +- Frequently joined tables
84 +- Reporting/analytics queries
85 +
86 +```sql
87 +-- Denormalized order summary (materialized view)
88 +CREATE MATERIALIZED VIEW order_summaries AS
89 +SELECT
90 + o.id,
91 + o.created_at,
92 + u.name AS user_name,
93 + u.email AS user_email,
94 + a.city AS shipping_city,
95 + o.total_amount,
96 + COUNT(oi.id) AS item_count
97 +FROM orders o
98 +JOIN users u ON o.user_id = u.id
99 +JOIN addresses a ON o.address_id = a.id
100 +JOIN order_items oi ON o.id = oi.order_id
101 +GROUP BY o.id, u.name, u.email, a.city;
102 +
103 +-- Refresh periodically
104 +REFRESH MATERIALIZED VIEW order_summaries;
105 +```
106 +
107 +## Index Optimization
108 +
109 +### Index Types
110 +
111 +```sql
112 +-- B-tree (default, good for most cases)
113 +CREATE INDEX idx_users_email ON users(email);
114 +
115 +-- Composite index (order matters!)
116 +CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
117 +
118 +-- Partial index (for filtered queries)
119 +CREATE INDEX idx_active_users ON users(email) WHERE status = 'active';
120 +
121 +-- Expression index
122 +CREATE INDEX idx_users_lower_email ON users(LOWER(email));
123 +
124 +-- GIN index (for arrays, JSONB)
125 +CREATE INDEX idx_products_tags ON products USING GIN(tags);
126 +
127 +-- BRIN index (for large tables with natural ordering)
128 +CREATE INDEX idx_logs_timestamp ON logs USING BRIN(created_at);
129 +```
130 +
131 +### Index Guidelines
132 +
133 +```markdown
134 +## When to Add Indexes
135 +- [ ] Columns in WHERE clauses
136 +- [ ] Columns in JOIN conditions
137 +- [ ] Columns in ORDER BY
138 +- [ ] Foreign keys
139 +- [ ] Columns with high selectivity
140 +
141 +## When NOT to Add Indexes
142 +- [ ] Small tables (< 1000 rows)
143 +- [ ] Columns with low selectivity (boolean, status)
144 +- [ ] Tables with heavy write operations
145 +- [ ] Frequently updated columns
146 +```
147 +
148 +## Query Optimization
149 +
150 +### EXPLAIN ANALYZE
151 +
152 +```sql
153 +EXPLAIN ANALYZE
154 +SELECT u.name, COUNT(o.id) as order_count
155 +FROM users u
156 +LEFT JOIN orders o ON u.id = o.user_id
157 +WHERE u.created_at > '2024-01-01'
158 +GROUP BY u.id
159 +ORDER BY order_count DESC
160 +LIMIT 10;
161 +```
162 +
163 +### Common Optimizations
164 +
165 +**1. Use appropriate JOINs**
166 +```sql
167 +-- Bad: Subquery for each row
168 +SELECT *, (SELECT COUNT(*) FROM orders WHERE user_id = u.id)
169 +FROM users u;
170 +
171 +-- Good: Single JOIN
172 +SELECT u.*, COUNT(o.id) as order_count
173 +FROM users u
174 +LEFT JOIN orders o ON u.id = o.user_id
175 +GROUP BY u.id;
176 +```
177 +
178 +**2. Avoid SELECT ***
179 +```sql
180 +-- Bad
181 +SELECT * FROM users WHERE id = 1;
182 +
183 +-- Good
184 +SELECT id, name, email FROM users WHERE id = 1;
185 +```
186 +
187 +**3. Use LIMIT for pagination**
188 +```sql
189 +-- Offset pagination (slow for large offsets)
190 +SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 10000;
191 +
192 +-- Keyset pagination (faster)
193 +SELECT * FROM products WHERE id > 10000 ORDER BY id LIMIT 20;
194 +```
195 +
196 +**4. Batch operations**
197 +```sql
198 +-- Bad: Individual inserts
199 +INSERT INTO logs (message) VALUES ('log1');
200 +INSERT INTO logs (message) VALUES ('log2');
201 +
202 +-- Good: Batch insert
203 +INSERT INTO logs (message) VALUES ('log1'), ('log2'), ('log3');
204 +```
205 +
206 +## Common Patterns
207 +
208 +### Soft Delete
209 +
210 +```sql
211 +ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP;
212 +
213 +-- "Delete" a user
214 +UPDATE users SET deleted_at = CURRENT_TIMESTAMP WHERE id = 1;
215 +
216 +-- Query active users only
217 +SELECT * FROM users WHERE deleted_at IS NULL;
218 +
219 +-- Create view for convenience
220 +CREATE VIEW active_users AS
221 +SELECT * FROM users WHERE deleted_at IS NULL;
222 +```
223 +
224 +### Audit Trail
225 +
226 +```sql
227 +CREATE TABLE audit_log (
228 + id SERIAL PRIMARY KEY,
229 + table_name VARCHAR(100) NOT NULL,
230 + record_id INTEGER NOT NULL,
231 + action VARCHAR(10) NOT NULL, -- INSERT, UPDATE, DELETE
232 + old_data JSONB,
233 + new_data JSONB,
234 + changed_by INTEGER REFERENCES users(id),
235 + changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
236 +);
237 +
238 +-- Trigger function
239 +CREATE OR REPLACE FUNCTION audit_trigger()
240 +RETURNS TRIGGER AS $$
241 +BEGIN
242 + IF TG_OP = 'INSERT' THEN
243 + INSERT INTO audit_log (table_name, record_id, action, new_data)
244 + VALUES (TG_TABLE_NAME, NEW.id, 'INSERT', to_jsonb(NEW));
245 + ELSIF TG_OP = 'UPDATE' THEN
246 + INSERT INTO audit_log (table_name, record_id, action, old_data, new_data)
247 + VALUES (TG_TABLE_NAME, NEW.id, 'UPDATE', to_jsonb(OLD), to_jsonb(NEW));
248 + ELSIF TG_OP = 'DELETE' THEN
249 + INSERT INTO audit_log (table_name, record_id, action, old_data)
250 + VALUES (TG_TABLE_NAME, OLD.id, 'DELETE', to_jsonb(OLD));
251 + END IF;
252 + RETURN NEW;
253 +END;
254 +$$ LANGUAGE plpgsql;
255 +```
256 +
257 +### Full-Text Search
258 +
259 +```sql
260 +-- Add search column
261 +ALTER TABLE products ADD COLUMN search_vector tsvector;
262 +
263 +-- Update search vector
264 +UPDATE products SET search_vector =
265 + setweight(to_tsvector('english', name), 'A') ||
266 + setweight(to_tsvector('english', description), 'B');
267 +
268 +-- Create GIN index
269 +CREATE INDEX idx_products_search ON products USING GIN(search_vector);
270 +
271 +-- Search query
272 +SELECT * FROM products
273 +WHERE search_vector @@ plainto_tsquery('english', 'wireless headphones')
274 +ORDER BY ts_rank(search_vector, plainto_tsquery('english', 'wireless headphones')) DESC;
275 +```
276 +
277 +## Performance Checklist
278 +
279 +```markdown
280 +## Schema Design
281 +- [ ] Appropriate data types (don't use VARCHAR(255) for everything)
282 +- [ ] Proper constraints (NOT NULL, UNIQUE, CHECK)
283 +- [ ] Foreign keys with proper ON DELETE behavior
284 +- [ ] UUID vs SERIAL for primary keys (consider use case)
285 +
286 +## Indexes
287 +- [ ] Primary key indexes exist
288 +- [ ] Foreign keys are indexed
289 +- [ ] Frequently queried columns indexed
290 +- [ ] No unused indexes (check pg_stat_user_indexes)
291 +
292 +## Queries
293 +- [ ] No N+1 queries
294 +- [ ] Appropriate use of JOINs vs subqueries
295 +- [ ] LIMIT on unbounded queries
296 +- [ ] EXPLAIN ANALYZE on slow queries
297 +
298 +## Maintenance
299 +- [ ] Regular VACUUM and ANALYZE
300 +- [ ] Connection pooling configured
301 +- [ ] Query timeouts set
302 +- [ ] Slow query logging enabled
303 +```
304 +
305 +## Useful Queries
306 +
307 +```sql
308 +-- Find unused indexes
309 +SELECT
310 + schemaname || '.' || relname AS table,
311 + indexrelname AS index,
312 + pg_size_pretty(pg_relation_size(i.indexrelid)) AS index_size,
313 + idx_scan AS index_scans
314 +FROM pg_stat_user_indexes ui
315 +JOIN pg_index i ON ui.indexrelid = i.indexrelid
316 +WHERE idx_scan < 50
317 +ORDER BY pg_relation_size(i.indexrelid) DESC;
318 +
319 +-- Find slow queries (requires pg_stat_statements)
320 +SELECT
321 + query,
322 + calls,
323 + mean_exec_time,
324 + total_exec_time
325 +FROM pg_stat_statements
326 +ORDER BY mean_exec_time DESC
327 +LIMIT 10;
328 +
329 +-- Table sizes
330 +SELECT
331 + relname AS table,
332 + pg_size_pretty(pg_total_relation_size(relid)) AS total_size
333 +FROM pg_catalog.pg_statio_user_tables
334 +ORDER BY pg_total_relation_size(relid) DESC;
335 +```
skills/builtin/debugging/SKILL.md new
+179
@@ -0,0 +1,179 @@
1 +---
2 +name: "debugging"
3 +description: "Systematic debugging methodology for identifying and fixing bugs. Use when encountering errors, unexpected behavior, or test failures."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["debugging", "troubleshooting", "errors", "testing", "analysis"]
7 +trigger_patterns:
8 + - "error"
9 + - "bug"
10 + - "not working"
11 + - "fails"
12 + - "broken"
13 + - "fix"
14 + - "debug"
15 +---
16 +
17 +# Systematic Debugging Skill
18 +
19 +**CRITICAL**: Follow this systematic process. Never guess at fixes without understanding the root cause.
20 +
21 +## When to Use
22 +
23 +Activate this skill when you encounter:
24 +- Error messages or stack traces
25 +- Unexpected behavior
26 +- Test failures
27 +- Performance issues
28 +- "It was working before" scenarios
29 +
30 +## The Debugging Process
31 +
32 +### Phase 1: Reproduce the Issue
33 +
34 +**Goal**: Confirm you can consistently trigger the bug.
35 +
36 +1. **Document the steps** to reproduce
37 +2. **Identify the exact error** message or unexpected behavior
38 +3. **Note the environment**: OS, versions, configuration
39 +4. **Establish baseline**: When did it last work correctly?
40 +
41 +```markdown
42 +## Reproduction Steps
43 +1. Step 1
44 +2. Step 2
45 +3. Step 3
46 +Expected: [What should happen]
47 +Actual: [What actually happens]
48 +```
49 +
50 +### Phase 2: Gather Evidence
51 +
52 +**Goal**: Collect all relevant information before forming hypotheses.
53 +
54 +1. **Read the full error message** and stack trace
55 +2. **Check logs** at multiple levels (app, system, network)
56 +3. **Examine recent changes** (git diff, git log)
57 +4. **Review related code** paths
58 +5. **Check dependencies** and their versions
59 +
60 +```bash
61 +# Useful commands
62 +git log --oneline -20 # Recent commits
63 +git diff HEAD~5 # Recent changes
64 +cat /var/log/app.log # Application logs
65 +```
66 +
67 +### Phase 3: Form Hypotheses
68 +
69 +**Goal**: Generate multiple possible causes ranked by likelihood.
70 +
71 +List hypotheses in order of probability:
72 +
73 +```markdown
74 +## Hypotheses
75 +1. [Most likely] Description - Evidence supporting this
76 +2. [Likely] Description - Evidence supporting this
77 +3. [Possible] Description - Evidence supporting this
78 +```
79 +
80 +### Phase 4: Test Hypotheses
81 +
82 +**Goal**: Systematically eliminate possibilities.
83 +
84 +For each hypothesis:
85 +1. **Design a test** that would confirm or refute it
86 +2. **Execute the test** with minimal changes
87 +3. **Document results**
88 +4. **Move to next hypothesis** if not confirmed
89 +
90 +```markdown
91 +## Testing: Hypothesis 1
92 +Test: [What I'll do to test this]
93 +Result: [Confirmed/Refuted]
94 +Evidence: [What I observed]
95 +```
96 +
97 +### Phase 5: Implement Fix
98 +
99 +**Goal**: Fix the root cause, not just the symptom.
100 +
101 +1. **Isolate the fix**: Make the smallest change that fixes the issue
102 +2. **Verify the fix**: Confirm the original reproduction steps now pass
103 +3. **Check for regressions**: Ensure nothing else broke
104 +4. **Document the fix**: Explain what was wrong and why the fix works
105 +
106 +### Phase 6: Prevent Recurrence
107 +
108 +**Goal**: Stop this class of bug from happening again.
109 +
110 +1. **Add a test** that would have caught this bug
111 +2. **Consider defensive coding** (validation, error handling)
112 +3. **Update documentation** if needed
113 +4. **Share learnings** with team if relevant
114 +
115 +## Anti-Patterns to Avoid
116 +
117 +- **Random Changes**: Never make changes hoping something works
118 +- **Fix Symptoms**: Always find and fix the root cause
119 +- **Skip Reproduction**: Always confirm you can reproduce before fixing
120 +- **Single Hypothesis**: Consider multiple possibilities
121 +- **No Testing**: Always verify the fix works
122 +
123 +## Debugging Tools
124 +
125 +### For Python
126 +```python
127 +# Interactive debugging
128 +import pdb; pdb.set_trace()
129 +
130 +# Or using ipdb for better experience
131 +import ipdb; ipdb.set_trace()
132 +
133 +# Print debugging with context
134 +print(f"DEBUG: {variable=}, {type(variable)=}")
135 +```
136 +
137 +### For JavaScript
138 +```javascript
139 +// Debugger statement
140 +debugger;
141 +
142 +// Console logging with labels
143 +console.log({ variable, typeof: typeof variable });
144 +
145 +// Trace to see call stack
146 +console.trace("How did we get here?");
147 +```
148 +
149 +### General
150 +```bash
151 +# Check if process is running
152 +ps aux | grep <process>
153 +
154 +# Check port usage
155 +lsof -i :<port>
156 +
157 +# Watch file changes
158 +tail -f /path/to/log
159 +```
160 +
161 +## Example Session
162 +
163 +**User**: "The API endpoint returns 500 error"
164 +
165 +**Agent Response**:
166 +> Let me debug this systematically:
167 +>
168 +> ## Phase 1: Reproduction
169 +> - Which endpoint specifically?
170 +> - What request parameters are you sending?
171 +> - Does it fail consistently or intermittently?
172 +>
173 +> ## Phase 2: Gathering Evidence
174 +> Let me check:
175 +> 1. The server error logs
176 +> 2. Recent changes to this endpoint
177 +> 3. The full stack trace
178 +>
179 +> [Proceeds systematically through each phase]
skills/builtin/docker_devops/SKILL.md new
+394
@@ -0,0 +1,394 @@
1 +---
2 +name: "docker_devops"
3 +description: "Docker and DevOps best practices for containerization, orchestration, and CI/CD pipelines. Use when working with containers, deployments, or infrastructure."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["docker", "devops", "containers", "kubernetes", "ci-cd", "infrastructure"]
7 +trigger_patterns:
8 + - "docker"
9 + - "container"
10 + - "kubernetes"
11 + - "k8s"
12 + - "deploy"
13 + - "ci/cd"
14 + - "pipeline"
15 +---
16 +
17 +# Docker & DevOps Skill
18 +
19 +Best practices for containerization, orchestration, and deployment pipelines.
20 +
21 +## Docker Fundamentals
22 +
23 +### Dockerfile Best Practices
24 +
25 +```dockerfile
26 +# Use specific version tags
27 +FROM python:3.11-slim
28 +
29 +# Set working directory
30 +WORKDIR /app
31 +
32 +# Copy dependency files first (layer caching)
33 +COPY requirements.txt .
34 +
35 +# Install dependencies
36 +RUN pip install --no-cache-dir -r requirements.txt
37 +
38 +# Copy application code
39 +COPY . .
40 +
41 +# Use non-root user
42 +RUN useradd -m appuser && chown -R appuser:appuser /app
43 +USER appuser
44 +
45 +# Expose port
46 +EXPOSE 8000
47 +
48 +# Use exec form for CMD
49 +CMD ["python", "app.py"]
50 +```
51 +
52 +### Multi-Stage Builds
53 +
54 +```dockerfile
55 +# Build stage
56 +FROM node:18 AS builder
57 +WORKDIR /app
58 +COPY package*.json ./
59 +RUN npm ci
60 +COPY . .
61 +RUN npm run build
62 +
63 +# Production stage
64 +FROM nginx:alpine
65 +COPY --from=builder /app/dist /usr/share/nginx/html
66 +EXPOSE 80
67 +CMD ["nginx", "-g", "daemon off;"]
68 +```
69 +
70 +### Docker Compose
71 +
72 +```yaml
73 +version: '3.8'
74 +
75 +services:
76 + app:
77 + build:
78 + context: .
79 + dockerfile: Dockerfile
80 + ports:
81 + - "8000:8000"
82 + environment:
83 + - DATABASE_URL=postgresql://user:pass@db:5432/app
84 + depends_on:
85 + db:
86 + condition: service_healthy
87 + volumes:
88 + - ./app:/app
89 + healthcheck:
90 + test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
91 + interval: 30s
92 + timeout: 10s
93 + retries: 3
94 +
95 + db:
96 + image: postgres:15-alpine
97 + environment:
98 + POSTGRES_USER: user
99 + POSTGRES_PASSWORD: pass
100 + POSTGRES_DB: app
101 + volumes:
102 + - postgres_data:/var/lib/postgresql/data
103 + healthcheck:
104 + test: ["CMD-SHELL", "pg_isready -U user -d app"]
105 + interval: 10s
106 + timeout: 5s
107 + retries: 5
108 +
109 +volumes:
110 + postgres_data:
111 +```
112 +
113 +## Kubernetes Basics
114 +
115 +### Deployment
116 +
117 +```yaml
118 +apiVersion: apps/v1
119 +kind: Deployment
120 +metadata:
121 + name: myapp
122 + labels:
123 + app: myapp
124 +spec:
125 + replicas: 3
126 + selector:
127 + matchLabels:
128 + app: myapp
129 + template:
130 + metadata:
131 + labels:
132 + app: myapp
133 + spec:
134 + containers:
135 + - name: myapp
136 + image: myapp:1.0.0
137 + ports:
138 + - containerPort: 8000
139 + resources:
140 + requests:
141 + memory: "128Mi"
142 + cpu: "100m"
143 + limits:
144 + memory: "256Mi"
145 + cpu: "200m"
146 + livenessProbe:
147 + httpGet:
148 + path: /health
149 + port: 8000
150 + initialDelaySeconds: 30
151 + periodSeconds: 10
152 + readinessProbe:
153 + httpGet:
154 + path: /ready
155 + port: 8000
156 + initialDelaySeconds: 5
157 + periodSeconds: 5
158 +```
159 +
160 +### Service
161 +
162 +```yaml
163 +apiVersion: v1
164 +kind: Service
165 +metadata:
166 + name: myapp-service
167 +spec:
168 + selector:
169 + app: myapp
170 + ports:
171 + - port: 80
172 + targetPort: 8000
173 + type: ClusterIP
174 +```
175 +
176 +### Ingress
177 +
178 +```yaml
179 +apiVersion: networking.k8s.io/v1
180 +kind: Ingress
181 +metadata:
182 + name: myapp-ingress
183 + annotations:
184 + nginx.ingress.kubernetes.io/rewrite-target: /
185 +spec:
186 + rules:
187 + - host: myapp.example.com
188 + http:
189 + paths:
190 + - path: /
191 + pathType: Prefix
192 + backend:
193 + service:
194 + name: myapp-service
195 + port:
196 + number: 80
197 +```
198 +
199 +## CI/CD Pipelines
200 +
201 +### GitHub Actions
202 +
203 +```yaml
204 +name: CI/CD Pipeline
205 +
206 +on:
207 + push:
208 + branches: [main]
209 + pull_request:
210 + branches: [main]
211 +
212 +jobs:
213 + test:
214 + runs-on: ubuntu-latest
215 + steps:
216 + - uses: actions/checkout@v3
217 +
218 + - name: Set up Python
219 + uses: actions/setup-python@v4
220 + with:
221 + python-version: '3.11'
222 +
223 + - name: Install dependencies
224 + run: |
225 + pip install -r requirements.txt
226 + pip install pytest
227 +
228 + - name: Run tests
229 + run: pytest
230 +
231 + build:
232 + needs: test
233 + runs-on: ubuntu-latest
234 + steps:
235 + - uses: actions/checkout@v3
236 +
237 + - name: Build Docker image
238 + run: docker build -t myapp:${{ github.sha }} .
239 +
240 + - name: Login to Container Registry
241 + uses: docker/login-action@v2
242 + with:
243 + registry: ghcr.io
244 + username: ${{ github.actor }}
245 + password: ${{ secrets.GITHUB_TOKEN }}
246 +
247 + - name: Push image
248 + run: |
249 + docker tag myapp:${{ github.sha }} ghcr.io/${{ github.repository }}:${{ github.sha }}
250 + docker push ghcr.io/${{ github.repository }}:${{ github.sha }}
251 +
252 + deploy:
253 + needs: build
254 + if: github.ref == 'refs/heads/main'
255 + runs-on: ubuntu-latest
256 + steps:
257 + - name: Deploy to production
258 + run: |
259 + echo "Deploying ${{ github.sha }}"
260 + # kubectl set image deployment/myapp myapp=ghcr.io/${{ github.repository }}:${{ github.sha }}
261 +```
262 +
263 +### GitLab CI
264 +
265 +```yaml
266 +stages:
267 + - test
268 + - build
269 + - deploy
270 +
271 +variables:
272 + DOCKER_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
273 +
274 +test:
275 + stage: test
276 + image: python:3.11
277 + script:
278 + - pip install -r requirements.txt
279 + - pytest
280 +
281 +build:
282 + stage: build
283 + image: docker:latest
284 + services:
285 + - docker:dind
286 + script:
287 + - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
288 + - docker build -t $DOCKER_IMAGE .
289 + - docker push $DOCKER_IMAGE
290 +
291 +deploy:
292 + stage: deploy
293 + only:
294 + - main
295 + script:
296 + - kubectl set image deployment/myapp myapp=$DOCKER_IMAGE
297 +```
298 +
299 +## Useful Commands
300 +
301 +### Docker
302 +
303 +```bash
304 +# Build image
305 +docker build -t myapp:latest .
306 +
307 +# Run container
308 +docker run -d -p 8000:8000 --name myapp myapp:latest
309 +
310 +# View logs
311 +docker logs -f myapp
312 +
313 +# Execute in container
314 +docker exec -it myapp /bin/sh
315 +
316 +# Clean up
317 +docker system prune -a
318 +
319 +# List resources
320 +docker ps -a
321 +docker images
322 +docker volume ls
323 +docker network ls
324 +```
325 +
326 +### Kubernetes
327 +
328 +```bash
329 +# Get resources
330 +kubectl get pods
331 +kubectl get services
332 +kubectl get deployments
333 +
334 +# Describe resource
335 +kubectl describe pod <pod-name>
336 +
337 +# Logs
338 +kubectl logs -f <pod-name>
339 +
340 +# Execute in pod
341 +kubectl exec -it <pod-name> -- /bin/sh
342 +
343 +# Apply configuration
344 +kubectl apply -f deployment.yaml
345 +
346 +# Scale deployment
347 +kubectl scale deployment myapp --replicas=5
348 +
349 +# Rollback
350 +kubectl rollout undo deployment/myapp
351 +```
352 +
353 +## Security Checklist
354 +
355 +```markdown
356 +- [ ] Use specific image tags, not 'latest'
357 +- [ ] Run as non-root user
358 +- [ ] Scan images for vulnerabilities
359 +- [ ] Use secrets management (not env vars for sensitive data)
360 +- [ ] Limit container resources
361 +- [ ] Enable network policies
362 +- [ ] Use read-only file systems where possible
363 +- [ ] Implement pod security policies
364 +- [ ] Rotate credentials regularly
365 +```
366 +
367 +## Monitoring & Logging
368 +
369 +```yaml
370 +# Prometheus ServiceMonitor
371 +apiVersion: monitoring.coreos.com/v1
372 +kind: ServiceMonitor
373 +metadata:
374 + name: myapp
375 +spec:
376 + selector:
377 + matchLabels:
378 + app: myapp
379 + endpoints:
380 + - port: metrics
381 + interval: 30s
382 +```
383 +
384 +```yaml
385 +# Fluentd sidecar for logging
386 +containers:
387 +- name: myapp
388 + image: myapp:latest
389 +- name: fluentd
390 + image: fluent/fluentd:latest
391 + volumeMounts:
392 + - name: logs
393 + mountPath: /var/log/app
394 +```
skills/builtin/git_workflow/SKILL.md new
+357
@@ -0,0 +1,357 @@
1 +---
2 +name: "git_workflow"
3 +description: "Git workflow best practices for branching, committing, and collaboration. Use when working with version control."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["git", "version-control", "branching", "collaboration", "workflow"]
7 +trigger_patterns:
8 + - "git"
9 + - "commit"
10 + - "branch"
11 + - "merge"
12 + - "pull request"
13 +---
14 +
15 +# Git Workflow Skill
16 +
17 +Best practices for version control and team collaboration.
18 +
19 +## Branching Strategy
20 +
21 +### Branch Naming Convention
22 +
23 +```
24 +<type>/<ticket-id>-<short-description>
25 +```
26 +
27 +**Types:**
28 +- `feature/` - New features
29 +- `bugfix/` - Bug fixes
30 +- `hotfix/` - Urgent production fixes
31 +- `refactor/` - Code refactoring
32 +- `docs/` - Documentation updates
33 +- `test/` - Adding tests
34 +- `chore/` - Maintenance tasks
35 +
36 +**Examples:**
37 +```bash
38 +feature/PROJ-123-add-user-authentication
39 +bugfix/PROJ-456-fix-login-timeout
40 +hotfix/PROJ-789-critical-security-patch
41 +```
42 +
43 +### Branch Workflow
44 +
45 +```
46 +main (production)
47 + │
48 + ├── develop (integration)
49 + │ │
50 + │ ├── feature/add-login
51 + │ ├── feature/add-dashboard
52 + │ └── bugfix/fix-signup
53 + │
54 + └── hotfix/security-patch (urgent fixes from main)
55 +```
56 +
57 +## Commit Messages
58 +
59 +### Conventional Commits Format
60 +
61 +```
62 +<type>(<scope>): <description>
63 +
64 +[optional body]
65 +
66 +[optional footer(s)]
67 +```
68 +
69 +### Types
70 +
71 +| Type | Description |
72 +|------|-------------|
73 +| `feat` | New feature |
74 +| `fix` | Bug fix |
75 +| `docs` | Documentation |
76 +| `style` | Formatting (no code change) |
77 +| `refactor` | Code refactoring |
78 +| `test` | Adding tests |
79 +| `chore` | Maintenance |
80 +| `perf` | Performance improvement |
81 +| `ci` | CI/CD changes |
82 +
83 +### Examples
84 +
85 +```bash
86 +# Feature
87 +feat(auth): add JWT token refresh mechanism
88 +
89 +# Bug fix with ticket reference
90 +fix(api): resolve timeout issue on large payloads
91 +
92 +Closes #123
93 +
94 +# Breaking change
95 +feat(api)!: change user endpoint response format
96 +
97 +BREAKING CHANGE: User endpoint now returns nested
98 +address object instead of flat fields.
99 +
100 +# Multi-line with body
101 +refactor(database): optimize user query performance
102 +
103 +- Added composite index on (email, created_at)
104 +- Removed N+1 query in user loader
105 +- Cached frequently accessed user data
106 +
107 +Performance improved from 500ms to 50ms for user list.
108 +```
109 +
110 +## Common Workflows
111 +
112 +### Starting New Work
113 +
114 +```bash
115 +# 1. Update main branch
116 +git checkout main
117 +git pull origin main
118 +
119 +# 2. Create feature branch
120 +git checkout -b feature/PROJ-123-new-feature
121 +
122 +# 3. Make changes and commit
123 +git add .
124 +git commit -m "feat(module): add new functionality"
125 +
126 +# 4. Push and create PR
127 +git push -u origin feature/PROJ-123-new-feature
128 +```
129 +
130 +### Syncing with Main
131 +
132 +```bash
133 +# Option 1: Rebase (preferred for feature branches)
134 +git fetch origin
135 +git rebase origin/main
136 +
137 +# Option 2: Merge (when history preservation needed)
138 +git fetch origin
139 +git merge origin/main
140 +```
141 +
142 +### Interactive Rebase (Cleaning History)
143 +
144 +```bash
145 +# Squash last 3 commits
146 +git rebase -i HEAD~3
147 +
148 +# In editor, change 'pick' to 'squash' for commits to combine
149 +pick abc1234 feat: add login form
150 +squash def5678 fix: typo in form
151 +squash ghi9012 style: format code
152 +```
153 +
154 +### Undoing Changes
155 +
156 +```bash
157 +# Undo last commit (keep changes)
158 +git reset --soft HEAD~1
159 +
160 +# Undo last commit (discard changes)
161 +git reset --hard HEAD~1
162 +
163 +# Undo specific file changes
164 +git checkout -- path/to/file
165 +
166 +# Revert a pushed commit (safe)
167 +git revert <commit-hash>
168 +```
169 +
170 +### Stashing Work
171 +
172 +```bash
173 +# Save current changes
174 +git stash save "WIP: feature description"
175 +
176 +# List stashes
177 +git stash list
178 +
179 +# Apply most recent stash
180 +git stash pop
181 +
182 +# Apply specific stash
183 +git stash apply stash@{2}
184 +
185 +# Drop a stash
186 +git stash drop stash@{0}
187 +```
188 +
189 +## Pull Request Guidelines
190 +
191 +### Before Creating PR
192 +
193 +1. **Rebase on latest main**
194 + ```bash
195 + git fetch origin
196 + git rebase origin/main
197 + ```
198 +
199 +2. **Run tests locally**
200 + ```bash
201 + npm test # or your test command
202 + ```
203 +
204 +3. **Self-review your changes**
205 + ```bash
206 + git diff origin/main
207 + ```
208 +
209 +4. **Clean up commits**
210 + - Squash fixup commits
211 + - Write clear commit messages
212 +
213 +### PR Description Template
214 +
215 +```markdown
216 +## Summary
217 +Brief description of changes
218 +
219 +## Type of Change
220 +- [ ] Feature
221 +- [ ] Bug fix
222 +- [ ] Refactor
223 +- [ ] Documentation
224 +
225 +## Changes Made
226 +- Change 1
227 +- Change 2
228 +- Change 3
229 +
230 +## Testing Done
231 +- [ ] Unit tests pass
232 +- [ ] Integration tests pass
233 +- [ ] Manual testing completed
234 +
235 +## Screenshots (if applicable)
236 +[Add screenshots here]
237 +
238 +## Related Issues
239 +Closes #123
240 +```
241 +
242 +### PR Best Practices
243 +
244 +1. **Keep PRs Small**: < 400 lines ideally
245 +2. **One Concern Per PR**: Don't mix features
246 +3. **Descriptive Title**: Summarize the change
247 +4. **Link Issues**: Reference related tickets
248 +5. **Add Context**: Explain why, not just what
249 +6. **Request Reviews**: Tag appropriate reviewers
250 +
251 +## Resolving Conflicts
252 +
253 +### Step-by-Step
254 +
255 +```bash
256 +# 1. Update your branch
257 +git fetch origin
258 +
259 +# 2. Rebase on main
260 +git rebase origin/main
261 +
262 +# 3. When conflicts occur, Git will pause
263 +# Fix conflicts in your editor
264 +
265 +# 4. After fixing each file
266 +git add <fixed-file>
267 +
268 +# 5. Continue rebase
269 +git rebase --continue
270 +
271 +# 6. If too complex, abort and try merge instead
272 +git rebase --abort
273 +git merge origin/main
274 +```
275 +
276 +### Conflict Markers
277 +
278 +```
279 +<<<<<<< HEAD
280 +Your changes
281 +=======
282 +Their changes
283 +>>>>>>> branch-name
284 +```
285 +
286 +## Git Hooks
287 +
288 +### Pre-commit Hook Example
289 +
290 +```bash
291 +#!/bin/sh
292 +# .git/hooks/pre-commit
293 +
294 +# Run linter
295 +npm run lint
296 +if [ $? -ne 0 ]; then
297 + echo "Lint failed. Fix errors before committing."
298 + exit 1
299 +fi
300 +
301 +# Run tests
302 +npm test
303 +if [ $? -ne 0 ]; then
304 + echo "Tests failed. Fix tests before committing."
305 + exit 1
306 +fi
307 +```
308 +
309 +### Commit Message Hook
310 +
311 +```bash
312 +#!/bin/sh
313 +# .git/hooks/commit-msg
314 +
315 +# Enforce conventional commits
316 +commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}'
317 +
318 +if ! grep -qE "$commit_regex" "$1"; then
319 + echo "Invalid commit message format."
320 + echo "Use: <type>(<scope>): <description>"
321 + exit 1
322 +fi
323 +```
324 +
325 +## Useful Aliases
326 +
327 +Add to `~/.gitconfig`:
328 +
329 +```ini
330 +[alias]
331 + # Status
332 + s = status -sb
333 +
334 + # Logging
335 + lg = log --oneline --graph --all
336 + last = log -1 HEAD --stat
337 +
338 + # Branching
339 + co = checkout
340 + cob = checkout -b
341 + br = branch -v
342 +
343 + # Committing
344 + cm = commit -m
345 + amend = commit --amend --no-edit
346 +
347 + # Stashing
348 + sl = stash list
349 + sp = stash pop
350 +
351 + # Diffing
352 + d = diff
353 + dc = diff --cached
354 +
355 + # Cleanup
356 + cleanup = "!git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d"
357 +```
skills/builtin/prompt_engineering/SKILL.md new
+404
@@ -0,0 +1,404 @@
1 +---
2 +name: "prompt_engineering"
3 +description: "Best practices for crafting effective prompts for LLMs. Use when designing prompts, creating system messages, or optimizing AI interactions."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["prompts", "llm", "ai", "gpt", "claude", "optimization"]
7 +trigger_patterns:
8 + - "prompt"
9 + - "system message"
10 + - "llm"
11 + - "ai instruction"
12 + - "chatgpt"
13 + - "claude"
14 +---
15 +
16 +# Prompt Engineering Skill
17 +
18 +Best practices for designing effective prompts for Large Language Models.
19 +
20 +## Core Principles
21 +
22 +### 1. Be Specific and Clear
23 +
24 +```markdown
25 +# Bad
26 +"Write something about dogs"
27 +
28 +# Good
29 +"Write a 200-word article about the top 3 benefits of adopting
30 +a rescue dog. Include a brief introduction and conclusion.
31 +Use a friendly, conversational tone suitable for pet owners."
32 +```
33 +
34 +### 2. Provide Context
35 +
36 +```markdown
37 +# Bad
38 +"Fix this code"
39 +
40 +# Good
41 +"I have a Python function that should validate email addresses.
42 +Currently it accepts invalid emails like 'test@'.
43 +
44 +Current code:
45 +```python
46 +def validate_email(email):
47 + return '@' in email
48 +```
49 +
50 +Please fix this to properly validate email format."
51 +```
52 +
53 +### 3. Specify Output Format
54 +
55 +```markdown
56 +# Bad
57 +"List some programming languages"
58 +
59 +# Good
60 +"List 5 programming languages for web development.
61 +Format as a markdown table with columns:
62 +- Language name
63 +- Primary use case
64 +- Learning difficulty (Easy/Medium/Hard)"
65 +```
66 +
67 +## Prompt Patterns
68 +
69 +### Role Pattern
70 +
71 +Assign a specific persona to guide responses:
72 +
73 +```markdown
74 +You are a senior Python developer with 10 years of experience.
75 +You specialize in clean code, testing, and code reviews.
76 +When reviewing code, you:
77 +- Focus on readability and maintainability
78 +- Suggest improvements with explanations
79 +- Point out potential bugs or security issues
80 +
81 +Please review the following code:
82 +[code here]
83 +```
84 +
85 +### Chain of Thought
86 +
87 +Guide step-by-step reasoning:
88 +
89 +```markdown
90 +Solve this problem step by step:
91 +
92 +Problem: A store has 150 apples. They sell 30% on Monday,
93 +then receive a shipment of 50 apples on Tuesday.
94 +How many apples do they have now?
95 +
96 +Please show your work:
97 +1. Calculate apples sold on Monday
98 +2. Calculate remaining apples after Monday
99 +3. Add Tuesday's shipment
100 +4. State the final answer
101 +```
102 +
103 +### Few-Shot Learning
104 +
105 +Provide examples to establish patterns:
106 +
107 +```markdown
108 +Convert these sentences to formal English:
109 +
110 +Example 1:
111 +Casual: "gonna grab some coffee"
112 +Formal: "I am going to get some coffee."
113 +
114 +Example 2:
115 +Casual: "wanna come with?"
116 +Formal: "Would you like to accompany me?"
117 +
118 +Now convert:
119 +Casual: "lemme know if you're free"
120 +Formal:
121 +```
122 +
123 +### Template Pattern
124 +
125 +Create reusable structures:
126 +
127 +```markdown
128 +# Bug Report Template
129 +
130 +Please analyze this bug and provide:
131 +
132 +## Summary
133 +[One sentence description]
134 +
135 +## Root Cause
136 +[Technical explanation of why this bug occurs]
137 +
138 +## Impact
139 +[Who is affected and how]
140 +
141 +## Solution
142 +[Recommended fix with code example]
143 +
144 +## Prevention
145 +[How to prevent similar bugs in the future]
146 +
147 +---
148 +Bug to analyze:
149 +[user's bug description]
150 +```
151 +
152 +## System Prompts
153 +
154 +### Structure
155 +
156 +```markdown
157 +# [Role/Identity]
158 +You are [description of the assistant's role and expertise]
159 +
160 +# [Core Behaviors]
161 +You should always:
162 +- [Behavior 1]
163 +- [Behavior 2]
164 +
165 +You should never:
166 +- [Anti-pattern 1]
167 +- [Anti-pattern 2]
168 +
169 +# [Response Format]
170 +When responding:
171 +- [Format guideline 1]
172 +- [Format guideline 2]
173 +
174 +# [Examples] (optional)
175 +Here's an example of how to respond:
176 +[example interaction]
177 +```
178 +
179 +### Example System Prompt
180 +
181 +```markdown
182 +# Role
183 +You are a helpful coding assistant specializing in Python.
184 +You have expertise in data science, web development, and automation.
185 +
186 +# Core Behaviors
187 +Always:
188 +- Write clean, well-documented code
189 +- Explain your reasoning
190 +- Suggest tests for code you write
191 +- Consider edge cases
192 +
193 +Never:
194 +- Write code without explanation
195 +- Use deprecated libraries
196 +- Ignore security best practices
197 +- Make assumptions about requirements without clarifying
198 +
199 +# Response Format
200 +When writing code:
201 +1. Start with a brief explanation of the approach
202 +2. Write the code with comments
203 +3. Explain any complex parts
204 +4. Suggest how to test it
205 +
206 +When debugging:
207 +1. Identify the likely cause
208 +2. Explain why it happens
209 +3. Provide the fix
210 +4. Suggest how to prevent similar issues
211 +```
212 +
213 +## Optimization Techniques
214 +
215 +### Iterative Refinement
216 +
217 +```markdown
218 +# First attempt
219 +"Write a story"
220 +
221 +# After iteration 1: Add specifics
222 +"Write a 500-word short story about a robot"
223 +
224 +# After iteration 2: Add constraints
225 +"Write a 500-word short story about a robot
226 +learning to paint. Include dialogue."
227 +
228 +# After iteration 3: Add style
229 +"Write a 500-word short story about a robot
230 +learning to paint. Include dialogue. Write in
231 +a warm, hopeful tone similar to Studio Ghibli films."
232 +```
233 +
234 +### Decomposition
235 +
236 +Break complex tasks into steps:
237 +
238 +```markdown
239 +Instead of:
240 +"Create a complete e-commerce website"
241 +
242 +Use:
243 +"Let's build an e-commerce website step by step:
244 +
245 +Step 1: Define the data models we need for products,
246 +users, and orders. Show me the schema.
247 +
248 +[Wait for response]
249 +
250 +Step 2: Based on those models, create the API endpoints.
251 +
252 +[Wait for response]
253 +
254 +Step 3: Now let's build the product listing page..."
255 +```
256 +
257 +### Constraint Setting
258 +
259 +```markdown
260 +# Add boundaries for better results
261 +"Write a product description for a coffee maker.
262 +
263 +Constraints:
264 +- Maximum 100 words
265 +- Include 3 key features
266 +- End with a call to action
267 +- Don't use superlatives like 'best' or 'amazing'
268 +- Write at a 6th-grade reading level"
269 +```
270 +
271 +## Common Pitfalls
272 +
273 +### 1. Vague Instructions
274 +
275 +```markdown
276 +# Bad
277 +"Make it better"
278 +
279 +# Good
280 +"Improve the readability by:
281 +- Using shorter sentences (max 20 words)
282 +- Adding subheadings every 100-150 words
283 +- Replacing jargon with plain language"
284 +```
285 +
286 +### 2. Missing Context
287 +
288 +```markdown
289 +# Bad
290 +"Why isn't my code working?"
291 +
292 +# Good
293 +"My Python code throws a TypeError.
294 +Environment: Python 3.11, macOS
295 +Error message: TypeError: 'NoneType' object is not iterable
296 +Code:
297 +```python
298 +def process(items):
299 + for item in items:
300 + print(item)
301 +
302 +process(get_items()) # Error occurs here
303 +```
304 +The get_items() function should return a list."
305 +```
306 +
307 +### 3. Overloading
308 +
309 +```markdown
310 +# Bad (too many things at once)
311 +"Write a blog post about AI, make it SEO optimized,
312 +include code examples, add images, make it funny but professional,
313 +target beginners but also appeal to experts..."
314 +
315 +# Good (focused request)
316 +"Write a 500-word introduction to machine learning
317 +for complete beginners. Use simple analogies and
318 +avoid technical jargon. Include 3 real-world examples."
319 +```
320 +
321 +## Evaluation Checklist
322 +
323 +```markdown
324 +Before submitting a prompt, verify:
325 +
326 +## Clarity
327 +- [ ] Is the task clearly defined?
328 +- [ ] Are ambiguous terms explained?
329 +- [ ] Is the expected output format specified?
330 +
331 +## Context
332 +- [ ] Is relevant background provided?
333 +- [ ] Are constraints clearly stated?
334 +- [ ] Are examples included if needed?
335 +
336 +## Structure
337 +- [ ] Is the prompt well-organized?
338 +- [ ] Are complex tasks broken into steps?
339 +- [ ] Is there a clear order of operations?
340 +
341 +## Completeness
342 +- [ ] Does it include all necessary information?
343 +- [ ] Are edge cases considered?
344 +- [ ] Is the success criteria clear?
345 +```
346 +
347 +## Examples by Use Case
348 +
349 +### Code Generation
350 +
351 +```markdown
352 +Write a Python function that:
353 +- Takes a list of dictionaries representing users
354 +- Filters users older than 18
355 +- Sorts by last name alphabetically
356 +- Returns their email addresses
357 +
358 +Input example:
359 +[{"name": "John Doe", "age": 25, "email": "john@example.com"}]
360 +
361 +Requirements:
362 +- Include type hints
363 +- Add docstring
364 +- Handle empty list case
365 +- Include unit test
366 +```
367 +
368 +### Data Analysis
369 +
370 +```markdown
371 +Analyze this sales data and provide:
372 +
373 +1. Summary statistics (mean, median, std dev)
374 +2. Top 3 performing products
375 +3. Month-over-month growth rate
376 +4. Any anomalies or patterns
377 +
378 +Present findings in a markdown table.
379 +Include a brief executive summary (3-4 sentences).
380 +
381 +Data:
382 +[paste data here]
383 +```
384 +
385 +### Writing Assistance
386 +
387 +```markdown
388 +Help me improve this email to a client:
389 +
390 +Context: We need to delay the project by 2 weeks
391 +due to unexpected technical issues.
392 +
393 +Current draft:
394 +"Hi, the project will be late. Sorry about that."
395 +
396 +Goals:
397 +- Maintain professional relationship
398 +- Clearly explain the delay
399 +- Provide new timeline
400 +- Offer mitigation options
401 +
402 +Tone: Professional but warm
403 +Length: 150-200 words
404 +```
skills/builtin/security_audit/SKILL.md new
+453
@@ -0,0 +1,453 @@
1 +---
2 +name: "security_audit"
3 +description: "Security audit and vulnerability assessment skill. Use when reviewing code for security issues, hardening systems, or implementing security best practices."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["security", "audit", "vulnerability", "owasp", "hardening"]
7 +trigger_patterns:
8 + - "security"
9 + - "vulnerability"
10 + - "secure"
11 + - "audit"
12 + - "owasp"
13 + - "penetration"
14 +---
15 +
16 +# Security Audit Skill
17 +
18 +Comprehensive security review and vulnerability assessment guidance.
19 +
20 +## OWASP Top 10 Checklist
21 +
22 +### 1. Broken Access Control
23 +
24 +```markdown
25 +## Check for:
26 +- [ ] Direct object references (IDOR)
27 +- [ ] Missing function-level access control
28 +- [ ] Privilege escalation paths
29 +- [ ] Bypassing access control via URL manipulation
30 +
31 +## Example vulnerability:
32 +```python
33 +# Bad: No authorization check
34 +@app.get("/api/users/{user_id}")
35 +def get_user(user_id: int):
36 + return db.get_user(user_id) # Any user can access any other user!
37 +
38 +# Good: Verify authorization
39 +@app.get("/api/users/{user_id}")
40 +def get_user(user_id: int, current_user: User = Depends(get_current_user)):
41 + if current_user.id != user_id and not current_user.is_admin:
42 + raise HTTPException(403, "Not authorized")
43 + return db.get_user(user_id)
44 +```
45 +```
46 +
47 +### 2. Cryptographic Failures
48 +
49 +```markdown
50 +## Check for:
51 +- [ ] Sensitive data transmitted in plaintext
52 +- [ ] Weak encryption algorithms (MD5, SHA1 for passwords)
53 +- [ ] Hardcoded secrets
54 +- [ ] Insecure random number generation
55 +
56 +## Secure practices:
57 +```python
58 +# Password hashing
59 +from argon2 import PasswordHasher
60 +ph = PasswordHasher()
61 +hash = ph.hash("password")
62 +ph.verify(hash, "password") # Raises exception if invalid
63 +
64 +# Secure token generation
65 +import secrets
66 +token = secrets.token_urlsafe(32)
67 +
68 +# Never do this:
69 +import hashlib
70 +hash = hashlib.md5(password.encode()).hexdigest() # WEAK!
71 +```
72 +```
73 +
74 +### 3. Injection
75 +
76 +```markdown
77 +## Check for:
78 +- [ ] SQL injection
79 +- [ ] NoSQL injection
80 +- [ ] Command injection
81 +- [ ] LDAP injection
82 +- [ ] XPath injection
83 +
84 +## SQL Injection Prevention:
85 +```python
86 +# Bad: String concatenation
87 +cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
88 +
89 +# Good: Parameterized queries
90 +cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
91 +
92 +# Good: ORM with proper escaping
93 +User.query.filter_by(id=user_id).first()
94 +```
95 +
96 +## Command Injection Prevention:
97 +```python
98 +# Bad
99 +os.system(f"echo {user_input}")
100 +
101 +# Good: Use subprocess with list arguments
102 +subprocess.run(["echo", user_input], shell=False)
103 +
104 +# Better: Avoid shell commands with user input entirely
105 +```
106 +```
107 +
108 +### 4. Insecure Design
109 +
110 +```markdown
111 +## Check for:
112 +- [ ] Missing threat modeling
113 +- [ ] No rate limiting on sensitive operations
114 +- [ ] Lack of defense in depth
115 +- [ ] Missing business logic validation
116 +
117 +## Example:
118 +```python
119 +# Bad: No rate limiting on login
120 +@app.post("/login")
121 +def login(credentials: Credentials):
122 + return authenticate(credentials)
123 +
124 +# Good: Rate limited
125 +from slowapi import Limiter
126 +limiter = Limiter(key_func=get_remote_address)
127 +
128 +@app.post("/login")
129 +@limiter.limit("5/minute")
130 +def login(credentials: Credentials):
131 + return authenticate(credentials)
132 +```
133 +```
134 +
135 +### 5. Security Misconfiguration
136 +
137 +```markdown
138 +## Check for:
139 +- [ ] Default credentials in use
140 +- [ ] Unnecessary features enabled
141 +- [ ] Missing security headers
142 +- [ ] Verbose error messages in production
143 +- [ ] Outdated software
144 +
145 +## Security Headers:
146 +```python
147 +# Flask example
148 +@app.after_request
149 +def add_security_headers(response):
150 + response.headers['X-Content-Type-Options'] = 'nosniff'
151 + response.headers['X-Frame-Options'] = 'DENY'
152 + response.headers['X-XSS-Protection'] = '1; mode=block'
153 + response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
154 + response.headers['Content-Security-Policy'] = "default-src 'self'"
155 + return response
156 +```
157 +```
158 +
159 +### 6. Vulnerable Components
160 +
161 +```markdown
162 +## Check for:
163 +- [ ] Outdated dependencies
164 +- [ ] Known vulnerable packages
165 +- [ ] Unmaintained libraries
166 +
167 +## Tools:
168 +```bash
169 +# Python
170 +pip-audit
171 +safety check -r requirements.txt
172 +
173 +# JavaScript
174 +npm audit
175 +yarn audit
176 +
177 +# General
178 +snyk test
179 +```
180 +```
181 +
182 +### 7. Authentication Failures
183 +
184 +```markdown
185 +## Check for:
186 +- [ ] Weak password policies
187 +- [ ] Missing MFA option
188 +- [ ] Session fixation
189 +- [ ] Insecure session management
190 +
191 +## Secure Session Management:
192 +```python
193 +# Secure session configuration
194 +app.config.update(
195 + SESSION_COOKIE_SECURE=True, # HTTPS only
196 + SESSION_COOKIE_HTTPONLY=True, # No JavaScript access
197 + SESSION_COOKIE_SAMESITE='Lax', # CSRF protection
198 + PERMANENT_SESSION_LIFETIME=3600 # 1 hour timeout
199 +)
200 +
201 +# Regenerate session on login
202 +@app.route('/login', methods=['POST'])
203 +def login():
204 + if authenticate(request.form):
205 + session.regenerate() # Prevent session fixation
206 + session['user_id'] = user.id
207 +```
208 +```
209 +
210 +### 8. Data Integrity Failures
211 +
212 +```markdown
213 +## Check for:
214 +- [ ] Missing integrity checks on critical data
215 +- [ ] Insecure deserialization
216 +- [ ] Missing code signing
217 +
218 +## Secure Deserialization:
219 +```python
220 +# Bad: Pickle with untrusted data
221 +import pickle
222 +data = pickle.loads(untrusted_data) # DANGEROUS!
223 +
224 +# Good: Use safe serialization
225 +import json
226 +data = json.loads(untrusted_data)
227 +
228 +# If you must use pickle, sign and verify
229 +import hmac
230 +def safe_pickle_loads(data, key):
231 + signature = data[:32]
232 + pickled = data[32:]
233 + expected = hmac.new(key, pickled, 'sha256').digest()
234 + if not hmac.compare_digest(signature, expected):
235 + raise ValueError("Invalid signature")
236 + return pickle.loads(pickled)
237 +```
238 +```
239 +
240 +### 9. Logging & Monitoring Failures
241 +
242 +```markdown
243 +## Check for:
244 +- [ ] Sensitive data in logs
245 +- [ ] Missing audit logs
246 +- [ ] No alerting for security events
247 +- [ ] Logs not protected
248 +
249 +## Secure Logging:
250 +```python
251 +import logging
252 +
253 +# Configure secure logging
254 +logging.basicConfig(
255 + level=logging.INFO,
256 + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
257 +)
258 +
259 +# Sanitize sensitive data
260 +def sanitize_log(data):
261 + sensitive_keys = ['password', 'token', 'api_key', 'ssn']
262 + return {k: '***' if k in sensitive_keys else v for k, v in data.items()}
263 +
264 +# Log security events
265 +def log_security_event(event_type, details):
266 + logger.warning(f"SECURITY: {event_type} - {sanitize_log(details)}")
267 +```
268 +```
269 +
270 +### 10. Server-Side Request Forgery (SSRF)
271 +
272 +```markdown
273 +## Check for:
274 +- [ ] URL parameters used for server requests
275 +- [ ] Unvalidated redirects
276 +- [ ] Internal service exposure
277 +
278 +## Prevention:
279 +```python
280 +from urllib.parse import urlparse
281 +import ipaddress
282 +
283 +ALLOWED_HOSTS = ['api.example.com', 'cdn.example.com']
284 +BLOCKED_NETWORKS = [
285 + ipaddress.ip_network('10.0.0.0/8'),
286 + ipaddress.ip_network('172.16.0.0/12'),
287 + ipaddress.ip_network('192.168.0.0/16'),
288 + ipaddress.ip_network('127.0.0.0/8'),
289 +]
290 +
291 +def is_safe_url(url):
292 + try:
293 + parsed = urlparse(url)
294 +
295 + # Check allowed hosts
296 + if parsed.hostname not in ALLOWED_HOSTS:
297 + return False
298 +
299 + # Check not internal IP
300 + ip = ipaddress.ip_address(parsed.hostname)
301 + for network in BLOCKED_NETWORKS:
302 + if ip in network:
303 + return False
304 +
305 + return True
306 + except:
307 + return False
308 +```
309 +```
310 +
311 +## Security Audit Process
312 +
313 +### 1. Information Gathering
314 +
315 +```markdown
316 +- [ ] Identify all entry points (APIs, forms, file uploads)
317 +- [ ] Map authentication and authorization flows
318 +- [ ] Document data flows
319 +- [ ] List third-party integrations
320 +- [ ] Review infrastructure configuration
321 +```
322 +
323 +### 2. Automated Scanning
324 +
325 +```bash
326 +# Web application scanning
327 +nikto -h https://target.com
328 +nuclei -u https://target.com -t cves/
329 +
330 +# Dependency scanning
331 +npm audit
332 +pip-audit
333 +
334 +# Static analysis
335 +bandit -r ./src # Python
336 +semgrep --config auto ./src # Multi-language
337 +```
338 +
339 +### 3. Manual Testing
340 +
341 +```markdown
342 +## Input Validation
343 +- [ ] Test with SQL injection payloads
344 +- [ ] Test with XSS payloads
345 +- [ ] Test with path traversal (../)
346 +- [ ] Test file upload restrictions
347 +
348 +## Authentication
349 +- [ ] Test password reset flow
350 +- [ ] Test session timeout
351 +- [ ] Test concurrent session handling
352 +- [ ] Test remember me functionality
353 +
354 +## Authorization
355 +- [ ] Test horizontal privilege escalation
356 +- [ ] Test vertical privilege escalation
357 +- [ ] Test API endpoint permissions
358 +```
359 +
360 +### 4. Report Template
361 +
362 +```markdown
363 +# Security Audit Report
364 +
365 +## Executive Summary
366 +[Brief overview of findings]
367 +
368 +## Scope
369 +- Systems tested:
370 +- Testing period:
371 +- Methodology:
372 +
373 +## Findings
374 +
375 +### Critical
376 +| ID | Title | Impact | CVSS |
377 +|----|-------|--------|------|
378 +| C1 | SQL Injection in login | Data breach | 9.8 |
379 +
380 +### High
381 +[Similar table]
382 +
383 +### Medium
384 +[Similar table]
385 +
386 +### Low
387 +[Similar table]
388 +
389 +## Detailed Findings
390 +
391 +### C1: SQL Injection in Login Form
392 +
393 +**Description**: The login form is vulnerable to SQL injection...
394 +
395 +**Impact**: An attacker could bypass authentication and access any account...
396 +
397 +**Proof of Concept**:
398 +```
399 +Username: ' OR '1'='1
400 +Password: anything
401 +```
402 +
403 +**Recommendation**: Use parameterized queries...
404 +
405 +**References**:
406 +- CWE-89
407 +- OWASP SQL Injection
408 +```
409 +
410 +## Quick Reference
411 +
412 +### Input Validation
413 +
414 +```python
415 +import re
416 +from html import escape
417 +
418 +def sanitize_input(user_input: str) -> str:
419 + # Remove/escape HTML
420 + sanitized = escape(user_input)
421 +
422 + # Limit length
423 + sanitized = sanitized[:1000]
424 +
425 + # Remove null bytes
426 + sanitized = sanitized.replace('\x00', '')
427 +
428 + return sanitized
429 +
430 +def validate_email(email: str) -> bool:
431 + pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
432 + return bool(re.match(pattern, email))
433 +```
434 +
435 +### Environment Configuration
436 +
437 +```python
438 +# Never commit secrets!
439 +import os
440 +from dotenv import load_dotenv
441 +
442 +load_dotenv()
443 +
444 +DATABASE_URL = os.getenv('DATABASE_URL')
445 +SECRET_KEY = os.getenv('SECRET_KEY')
446 +API_KEY = os.getenv('API_KEY')
447 +
448 +# Verify all required env vars are set
449 +required = ['DATABASE_URL', 'SECRET_KEY', 'API_KEY']
450 +missing = [v for v in required if not os.getenv(v)]
451 +if missing:
452 + raise RuntimeError(f"Missing environment variables: {missing}")
453 +```
skills/builtin/tdd/SKILL.md new
+229
@@ -0,0 +1,229 @@
1 +---
2 +name: "tdd"
3 +description: "Test-Driven Development workflow. Write tests first, then implement code to make them pass. Use when implementing features or fixing bugs."
4 +version: "1.0.0"
5 +author: "Agent Zero Team"
6 +tags: ["testing", "tdd", "development", "quality", "best-practices"]
7 +trigger_patterns:
8 + - "test first"
9 + - "tdd"
10 + - "write tests"
11 + - "test-driven"
12 + - "unit test"
13 +---
14 +
15 +# Test-Driven Development (TDD) Skill
16 +
17 +**CRITICAL**: Write tests BEFORE writing implementation code. This ensures code is testable and meets requirements.
18 +
19 +## The TDD Cycle
20 +
21 +```
22 + ┌─────────────────────────────────────┐
23 + │ │
24 + │ RED → GREEN → REFACTOR → Repeat │
25 + │ │
26 + └─────────────────────────────────────┘
27 +```
28 +
29 +1. **RED**: Write a failing test that defines expected behavior
30 +2. **GREEN**: Write minimum code to make the test pass
31 +3. **REFACTOR**: Clean up while keeping tests green
32 +4. **Repeat**: Add next test case
33 +
34 +## When to Use
35 +
36 +Activate TDD when:
37 +- Implementing new features
38 +- Fixing bugs (write test that reproduces bug first)
39 +- Refactoring existing code
40 +- Adding edge case handling
41 +
42 +## The TDD Process
43 +
44 +### Phase 1: Understand Requirements
45 +
46 +Before writing any code:
47 +1. Clarify what the feature should do
48 +2. Identify inputs, outputs, and edge cases
49 +3. List test cases needed
50 +
51 +```markdown
52 +## Feature: [Name]
53 +### Happy Path Cases
54 +- [ ] Test case 1: Given X, when Y, then Z
55 +- [ ] Test case 2: Given A, when B, then C
56 +
57 +### Edge Cases
58 +- [ ] Empty input
59 +- [ ] Invalid input
60 +- [ ] Boundary values
61 +
62 +### Error Cases
63 +- [ ] What should happen when X fails?
64 +```
65 +
66 +### Phase 2: RED - Write Failing Test
67 +
68 +Write a test that:
69 +1. Describes the expected behavior
70 +2. Fails for the right reason (not implementation exists yet)
71 +3. Is simple and focused
72 +
73 +```python
74 +# Python example
75 +def test_calculate_total_with_discount():
76 + """Should apply 10% discount for orders over $100"""
77 + order = Order(items=[Item(price=150)])
78 +
79 + result = order.calculate_total()
80 +
81 + assert result == 135.00 # 150 - 10% = 135
82 +```
83 +
84 +```javascript
85 +// JavaScript example
86 +describe('calculateTotal', () => {
87 + it('should apply 10% discount for orders over $100', () => {
88 + const order = new Order([{ price: 150 }]);
89 +
90 + const result = order.calculateTotal();
91 +
92 + expect(result).toBe(135);
93 + });
94 +});
95 +```
96 +
97 +### Phase 3: GREEN - Make Test Pass
98 +
99 +Write the simplest code that makes the test pass:
100 +1. Don't over-engineer
101 +2. Don't add features the test doesn't require
102 +3. It's okay if code is ugly - we'll refactor next
103 +
104 +```python
105 +def calculate_total(self):
106 + total = sum(item.price for item in self.items)
107 + if total > 100:
108 + total = total * 0.9 # 10% discount
109 + return total
110 +```
111 +
112 +### Phase 4: REFACTOR - Clean Up
113 +
114 +Improve code quality while keeping tests green:
115 +1. Remove duplication
116 +2. Improve naming
117 +3. Extract methods if needed
118 +4. Run tests after each change
119 +
120 +```python
121 +DISCOUNT_THRESHOLD = 100
122 +DISCOUNT_RATE = 0.10
123 +
124 +def calculate_total(self):
125 + subtotal = self._calculate_subtotal()
126 + discount = self._calculate_discount(subtotal)
127 + return subtotal - discount
128 +
129 +def _calculate_subtotal(self):
130 + return sum(item.price for item in self.items)
131 +
132 +def _calculate_discount(self, subtotal):
133 + if subtotal > DISCOUNT_THRESHOLD:
134 + return subtotal * DISCOUNT_RATE
135 + return 0
136 +```
137 +
138 +### Phase 5: Repeat
139 +
140 +Add the next test case and repeat the cycle.
141 +
142 +## Test Patterns
143 +
144 +### Arrange-Act-Assert (AAA)
145 +
146 +```python
147 +def test_user_creation():
148 + # Arrange - set up test data
149 + user_data = {"name": "Alice", "email": "alice@example.com"}
150 +
151 + # Act - perform the action
152 + user = User.create(user_data)
153 +
154 + # Assert - verify the result
155 + assert user.name == "Alice"
156 + assert user.email == "alice@example.com"
157 +```
158 +
159 +### Given-When-Then (BDD style)
160 +
161 +```python
162 +def test_user_login():
163 + # Given a registered user
164 + user = create_user(email="test@example.com", password="secret")
165 +
166 + # When they attempt to login with correct credentials
167 + result = login(email="test@example.com", password="secret")
168 +
169 + # Then they should be authenticated
170 + assert result.success == True
171 + assert result.token is not None
172 +```
173 +
174 +## Common Test Types
175 +
176 +### Unit Tests
177 +- Test single functions/methods in isolation
178 +- Mock external dependencies
179 +- Fast execution
180 +
181 +### Integration Tests
182 +- Test multiple components together
183 +- Use real databases (test instances)
184 +- Slower but more realistic
185 +
186 +### End-to-End Tests
187 +- Test full user workflows
188 +- Run against complete system
189 +- Slowest but most comprehensive
190 +
191 +## Anti-Patterns to Avoid
192 +
193 +- **Test After**: Writing tests after implementation defeats the purpose
194 +- **Testing Implementation**: Test behavior, not implementation details
195 +- **Brittle Tests**: Tests shouldn't break when refactoring
196 +- **Skipping Refactor**: Technical debt accumulates without refactoring
197 +- **Too Many Mocks**: Over-mocking makes tests meaningless
198 +
199 +## Example TDD Session
200 +
201 +**User**: "Implement a password validator"
202 +
203 +**Agent Response**:
204 +> Let me implement this using TDD:
205 +>
206 +> ## Test Cases to Cover
207 +> 1. Password must be at least 8 characters
208 +> 2. Password must contain uppercase letter
209 +> 3. Password must contain number
210 +> 4. Password must contain special character
211 +>
212 +> ## RED: First Test
213 +> ```python
214 +> def test_rejects_short_password():
215 +> result = validate_password("short")
216 +> assert result.valid == False
217 +> assert "at least 8 characters" in result.errors
218 +> ```
219 +>
220 +> ## GREEN: Minimal Implementation
221 +> ```python
222 +> def validate_password(password):
223 +> errors = []
224 +> if len(password) < 8:
225 +> errors.append("Password must be at least 8 characters")
226 +> return ValidationResult(valid=len(errors) == 0, errors=errors)
227 +> ```
228 +>
229 +> [Continues with next test case...]