Browse Source

feat(skills): Rewrite security-ops as orchestrator, add skill preloading

Upgrade security-ops from a 182-line reference dump to a ~350-line
orchestrator (following perf-ops and git-ops patterns) with three
parallel audit agents (dependency, SAST, auth/config), T1/T2/T3 safety
tiers, OWASP-mapped report format, and remediation preflight. Extract
reference material into a new audit-quickref.md (OWASP table, input
validation, output encoding, auth checklist, secrets rules).

Add context preloading to six dispatching skills so agents receive
relevant reference files at dispatch time rather than on first tool
call:
- review: preloads security-ops + testing-ops, model sonnet
- testgen: preloads security-ops + testing-ops, model sonnet
- perf-ops: preloads cpu-memory-profiling.md + load-testing.md + postgres-ops
- git-ops: preloads ci-cd-ops for release/PR dispatch paths
- techdebt: scanner prompts preload security-ops + refactor-ops
- explain: preloads debug-ops, model sonnet

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
0xDarkMatter 3 weeks ago
parent
commit
f5a9609ffe

+ 5 - 0
skills/explain/SKILL.md

@@ -43,6 +43,7 @@ $ARGUMENTS
     |     +- .sql/migrations -> postgres-expert
     |     +- agents/skills/commands -> claude-architect
     |     +- Default -> general-purpose
+    |     +- All experts preload: debug-ops (systematic analysis)
     |
     +-> Step 4: Generate Explanation
     |     +- Structured markdown with sections
@@ -131,7 +132,11 @@ Determine the best expert based on file extension and content:
 **Invoke via Task tool:**
 ```
 Task tool with subagent_type: "[detected]-expert"
+model: "sonnet"
 Prompt includes:
+  - Skill preloading (domain knowledge):
+    "First, read this file for systematic analysis methodology:
+     - Read: skills/debug-ops/SKILL.md"
   - File content
   - Related files found
   - Project conventions

+ 4 - 0
skills/git-ops/SKILL.md

@@ -84,6 +84,10 @@ Gather relevant context, then dispatch to `git-agent` (background, Sonnet).
 ```
 You are the git-agent handling a Tier 2 (safe write) operation.
 
+## Domain Knowledge
+For release or PR operations, read CI context first:
+- Read: skills/ci-cd-ops/SKILL.md (release workflows, PR conventions)
+
 ## Context
 - Current branch: {branch}
 - Repository: {repo info}

+ 10 - 0
skills/perf-ops/SKILL.md

@@ -99,6 +99,16 @@ You are handling a performance profiling task dispatched by the perf-ops orchest
 - Process/file: {target application or endpoint}
 - Expected workload: {how to generate representative load if needed}
 
+## Domain Knowledge
+Before starting, read the relevant profiling reference for this language:
+- Read: skills/perf-ops/references/cpu-memory-profiling.md
+
+For load testing tasks, also read:
+- Read: skills/perf-ops/references/load-testing.md
+
+For database profiling, also read:
+- Read: skills/postgres-ops/SKILL.md (if PostgreSQL)
+
 ## Instructions
 1. Run the appropriate profiler for this language and symptom
 2. Collect sufficient samples (minimum 30 seconds for CPU, multiple snapshots for memory)

+ 16 - 1
skills/review/SKILL.md

@@ -40,7 +40,8 @@ review [target] [--focus] [--depth]
     │     ├─ Vue → vue-expert
     │     ├─ SQL/migrations → postgres-expert
     │     ├─ Claude extensions → claude-architect
-    │     └─ Multi-domain → parallel expert dispatch
+    │     ├─ Multi-domain → parallel expert dispatch
+    │     └─ All experts preload: security-ops + testing-ops context
     ├─→ Step 5: Generate Review
     │     ├─ Severity: CRITICAL / WARNING / SUGGESTION / PRAISE
@@ -159,7 +160,12 @@ cat .github/workflows/*.yml 2>/dev/null | grep -E "eslint|prettier|pylint|ruff"
 **Invoke via Task tool:**
 ```
 Task tool with subagent_type: "[detected]-expert"
+model: "sonnet"
 Prompt includes:
+  - Skill preloading (domain knowledge):
+    "First, read these files for review context:
+     - Read: skills/security-ops/references/owasp-detailed.md
+     - Read: skills/testing-ops/SKILL.md"
   - Diff content
   - Project conventions from AGENTS.md
   - Linting config summaries
@@ -167,6 +173,15 @@ Prompt includes:
   - Request for structured review output
 ```
 
+**Language-specific preloads** (append to the preloading section above):
+
+| Expert | Additional Preload | Why |
+|--------|-------------------|-----|
+| python-expert | `skills/python-pytest-ops/SKILL.md` | Python test patterns for coverage review |
+| go-expert | `skills/go-ops/SKILL.md` | Go idioms, concurrency gotchas |
+| rust-expert | `skills/rust-ops/SKILL.md` | Ownership patterns, unsafe review |
+| typescript-expert | `skills/typescript-ops/SKILL.md` | Type safety patterns |
+
 ### Step 5: Generate Review
 
 The expert produces a structured review:

+ 306 - 138
skills/security-ops/SKILL.md

@@ -1,182 +1,350 @@
 ---
 name: security-ops
-description: "Security patterns and OWASP guidelines. Triggers on: security review, OWASP, XSS, SQL injection, CSRF, authentication, authorization, secrets management, input validation, secure coding."
-compatibility: "Language-agnostic patterns with framework-specific examples in references."
-allowed-tools: "Read Write Bash Grep"
+description: "Security audit orchestrator - parallel dependency scanning, SAST pattern detection, auth/config review. Dispatches 3 audit agents simultaneously, consolidates into OWASP-mapped severity report. Triggers on: security review, security audit, OWASP, XSS, SQL injection, CSRF, authentication, authorization, secrets management, input validation, secure coding, vulnerability scan, dependency audit."
+allowed-tools: "Read Edit Write Bash Glob Grep Agent TaskCreate TaskUpdate"
+related-skills: [auth-ops, testing-ops, debug-ops, monitoring-ops]
 ---
 
-# Security Patterns
+# Security Operations
 
-Essential security patterns for web applications.
+Orchestrator for security auditing. Detects project stack inline, dispatches three parallel audit agents (dependency, SAST, auth/config review), consolidates into a severity-ranked OWASP-mapped report.
 
-## OWASP Top 10 Quick Reference
+## Architecture
 
-| Rank | Vulnerability | Prevention |
-|------|--------------|------------|
-| A01 | Broken Access Control | Check permissions server-side, deny by default |
-| A02 | Cryptographic Failures | Use TLS, hash passwords, encrypt sensitive data |
-| A03 | Injection | Parameterized queries, validate input |
-| A04 | Insecure Design | Threat modeling, secure defaults |
-| A05 | Security Misconfiguration | Harden configs, disable unused features |
-| A06 | Vulnerable Components | Update dependencies, audit regularly |
-| A07 | Auth Failures | MFA, rate limiting, secure session management |
-| A08 | Data Integrity Failures | Verify signatures, use trusted sources |
-| A09 | Logging Failures | Log security events, protect logs |
-| A10 | SSRF | Validate URLs, allowlist destinations |
+```
+User requests security audit or mentions security concern
+    |
+    +---> T1: Detect (inline, fast)
+    |       +---> Identify languages/frameworks in project
+    |       +---> Check installed audit tools
+    |       +---> Determine scope (changed files vs full codebase)
+    |       +---> Present: detection summary + recommended audit
+    |
+    +---> T2: Audit (3 parallel agents, background)
+    |       +---> Agent 1: Dependency Audit
+    |       |       +---> Run pip-audit, npm audit, govulncheck, cargo audit, trivy
+    |       |       +---> Report: CVE IDs, severity, affected + fix versions
+    |       |
+    |       +---> Agent 2: Code Pattern Scan (SAST)
+    |       |       +---> Hardcoded secrets, injection, XSS, eval, shell, weak crypto
+    |       |       +---> Report: file:line, pattern, severity, fix suggestion
+    |       |
+    |       +---> Agent 3: Auth & Config Review
+    |       |       +---> Session, CSRF, CORS, CSP, JWT, OAuth, rate limiting, env vars
+    |       |       +---> Report: finding, severity, OWASP category, remediation
+    |       |
+    |       +---> Consolidate: deduplicate, rank by severity, map to OWASP Top 10
+    |
+    +---> T3: Remediate (dispatch to language expert, foreground + confirm)
+            +---> Expert proposes specific fixes
+            +---> Preflight: what changes, security impact, risk of breaking
+            +---> User confirms
+            +---> Apply fixes
+```
+
+## Safety Tiers
+
+| Operation | Tier | Execution |
+|-----------|------|-----------|
+| Detect languages/frameworks | T1 | Inline |
+| Check installed audit tools | T1 | Inline |
+| Determine scope (changed vs all) | T1 | Inline |
+| Dependency vulnerability scan | T2 | Agent 1 (bg) |
+| Code pattern scan (SAST) | T2 | Agent 2 (bg) |
+| Auth & config review | T2 | Agent 3 (bg) |
+| Consolidate findings | T2 | Inline (after agents return) |
+| Fix vulnerability in code | T3 | Expert agent + confirm |
+| Update vulnerable dependency | T3 | Expert agent + confirm |
+| Add security headers | T3 | Expert agent + confirm |
+
+## T1: Detect - Run Inline
+
+| Check | Command / Method |
+|-------|-----------------|
+| Python project | Check for `requirements.txt`, `pyproject.toml`, `Pipfile` |
+| Node.js project | Check for `package.json`, `package-lock.json` |
+| Go project | Check for `go.mod` |
+| Rust project | Check for `Cargo.toml` |
+| Docker | Check for `Dockerfile`, `docker-compose.yml` |
+| pip-audit available | `which pip-audit 2>/dev/null` |
+| npm audit available | `which npm 2>/dev/null` |
+| govulncheck available | `which govulncheck 2>/dev/null` |
+| cargo-audit available | `which cargo-audit 2>/dev/null` |
+| trivy available | `which trivy 2>/dev/null` |
+| Scope: changed files | `git diff --name-only HEAD` |
+| Scope: full codebase | `fd -e py -e js -e ts -e go -e rs` |
+
+## T2: Audit - Dispatch 3 Parallel Agents
+
+All audit agents use `model="sonnet"`, `run_in_background=True`. All are **read-only** - instruct them explicitly to never edit files.
+
+### Agent 1: Dependency Audit
 
-## Input Validation
+```
+You are a security dependency auditor. Your job is to find vulnerable dependencies.
+
+## Domain Knowledge
+First, read this script for audit commands:
+- Read: skills/security-ops/scripts/dependency-audit.sh
+
+## Scope
+- Languages detected: {languages from T1}
+- Audit tools available: {tools from T1}
+
+## Instructions
+1. Run the appropriate audit tool for each detected language:
+   - Python: `pip-audit` or `safety check`
+   - Node.js: `npm audit --audit-level=moderate`
+   - Go: `govulncheck ./...`
+   - Rust: `cargo audit`
+   - Docker: `trivy config Dockerfile`
+2. For each vulnerability found, report:
+   - Package name and version
+   - CVE ID (if available)
+   - Severity (Critical/High/Medium/Low)
+   - Fixed version (if available)
+   - Brief description
+3. If an audit tool is not installed, note which tool is missing and what command installs it
+
+IMPORTANT: Do NOT edit any files. This is a read-only audit.
+
+## Output Format
+Report findings as a severity-ranked table.
+```
 
-```python
-# WRONG - Trust user input
-def search(query):
-    return db.execute(f"SELECT * FROM users WHERE name = '{query}'")
+### Agent 2: Code Pattern Scan (SAST)
 
-# CORRECT - Parameterized query
-def search(query):
-    return db.execute("SELECT * FROM users WHERE name = ?", [query])
+```
+You are a security code scanner. Your job is to find vulnerability patterns in source code.
+
+## Domain Knowledge
+First, read these files for scan patterns and OWASP context:
+- Read: skills/security-ops/scripts/security-scan.sh
+- Read: skills/security-ops/references/owasp-detailed.md
+
+## Scope
+- Files to scan: {scope from T1 - changed files or full codebase}
+- Languages: {languages from T1}
+
+## Scan Categories
+For each language detected, search for these patterns using ripgrep:
+
+**Injection (OWASP A03):**
+- SQL injection: f-strings/format in execute(), string concatenation in queries
+- Command injection: os.system(), subprocess with shell=True, exec(), eval()
+- XSS: innerHTML assignment, document.write(), dangerouslySetInnerHTML without sanitization
+
+**Hardcoded Secrets (OWASP A02):**
+- API keys, passwords, tokens assigned as string literals
+- .env files tracked in git
+- Private keys in source
+
+**Insecure Crypto (OWASP A02):**
+- MD5 or SHA1 for passwords (use bcrypt/argon2)
+- ECB mode encryption
+- Hardcoded encryption keys
+
+**Insecure Deserialization (OWASP A08):**
+- pickle.loads on untrusted data (Python)
+- JSON.parse without validation
+- yaml.load without SafeLoader
+
+## Instructions
+1. Use `rg` (ripgrep) for pattern matching across the codebase
+2. Use `ast-grep` for structural patterns if available
+3. For each finding, report: file:line, pattern matched, OWASP category, severity, fix suggestion
+4. Distinguish between confirmed issues and potential false positives
+
+IMPORTANT: Do NOT edit any files. This is a read-only scan.
+
+## Output Format
+Group findings by OWASP category, sorted by severity within each group.
 ```
 
-### Validation Rules
+### Agent 3: Auth & Config Review
+
 ```
-Always validate:
-- Type (string, int, email format)
-- Length (min/max bounds)
-- Range (numeric bounds)
-- Format (regex for patterns)
-- Allowlist (known good values)
-
-Never trust:
-- URL parameters
-- Form data
-- HTTP headers
-- Cookies
-- File uploads
+You are a security reviewer specializing in authentication, authorization, and security configuration.
+
+## Domain Knowledge
+First, read these files for auth patterns and header requirements:
+- Read: skills/security-ops/references/auth-patterns.md
+- Read: skills/security-ops/references/secure-headers.md
+
+## Scope
+- Files to review: {scope from T1}
+- Framework: {detected framework}
+
+## Review Checklist
+
+**Authentication (OWASP A07):**
+- Password hashing: bcrypt/argon2 with cost factor 12+?
+- Session tokens: cryptographically random, sufficient length?
+- Cookie flags: HttpOnly, Secure, SameSite set?
+- Rate limiting on login endpoints?
+- Account lockout after failed attempts?
+- MFA support for sensitive operations?
+
+**Authorization (OWASP A01):**
+- Server-side permission checks on all endpoints?
+- Default deny policy?
+- IDOR protection (verify ownership before access)?
+- Role-based or attribute-based access control?
+
+**Security Configuration (OWASP A05):**
+- CSP header configured?
+- HSTS enabled with appropriate max-age?
+- X-Frame-Options or frame-ancestors in CSP?
+- CORS policy restrictive (not wildcard)?
+- Debug mode disabled in production config?
+- Error messages don't leak internal details?
+
+**Session Management:**
+- Session timeout configured?
+- Session invalidation on logout?
+- Session regeneration on privilege change?
+- Tokens not exposed in URLs?
+
+## Instructions
+1. Read auth-related files (login, session, middleware, config)
+2. Check each item on the review checklist
+3. For each finding: describe the issue, rate severity, cite OWASP category, suggest fix
+4. Note items that pass as well as items that fail
+
+IMPORTANT: Do NOT edit any files. This is a read-only review.
+
+## Output Format
+Checklist-style report with PASS/FAIL/N-A for each item, findings grouped by category.
 ```
 
-## Output Encoding
+### Consolidation
 
-```javascript
-// WRONG - Direct HTML insertion
-element.innerHTML = userInput;
+After all 3 agents return, consolidate inline:
 
-// CORRECT - Text content (auto-escapes)
-element.textContent = userInput;
+1. **Deduplicate** - Remove findings that appear in multiple agents (e.g., hardcoded secret found by both Agent 1 and Agent 2)
+2. **Rank by severity:**
+   - **Critical:** Remote code execution, SQL injection, exposed secrets in production
+   - **High:** XSS, broken auth, missing access control, known CVE with exploit
+   - **Medium:** Weak crypto, missing security headers, insecure defaults
+   - **Low:** Informational, best practice suggestions, TODO items
+3. **Map to OWASP Top 10** - Tag each finding with its OWASP category
+4. **Generate report** (see Report Format below)
 
-// CORRECT - Template with escaping
-render(`<div>${escapeHtml(userInput)}</div>`);
-```
+## T3: Remediate - Expert Dispatch with Confirmation
 
-### Encoding by Context
-| Context | Encoding |
-|---------|----------|
-| HTML body | HTML entity encode |
-| HTML attribute | Attribute encode + quote |
-| JavaScript | JS encode |
-| URL parameter | URL encode |
-| CSS | CSS encode |
+When user wants to fix findings, dispatch to the appropriate language expert.
 
-## Authentication
+**Language routing (same as perf-ops):**
 
-```python
-# Password hashing (use bcrypt, argon2, or scrypt)
-import bcrypt
+| Finding Type | Expert Agent |
+|-------------|-------------|
+| Python vulnerability | python-expert |
+| Node.js/JS vulnerability | javascript-expert |
+| TypeScript vulnerability | typescript-expert |
+| Go vulnerability | go-expert |
+| Rust vulnerability | rust-expert |
+| SQL injection / DB security | postgres-expert |
+| General / config / headers | general-purpose |
 
-def hash_password(password: str) -> bytes:
-    return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
+**Dispatch template (T3 preflight):**
 
-def verify_password(password: str, hashed: bytes) -> bool:
-    return bcrypt.checkpw(password.encode(), hashed)
 ```
+You are handling a security remediation dispatched by the security-ops orchestrator.
+
+## Domain Knowledge
+First, read for context:
+- Read: skills/security-ops/references/owasp-detailed.md
 
-### Auth Checklist
-- [ ] Hash passwords with bcrypt/argon2 (cost factor 12+)
-- [ ] Implement rate limiting on login
-- [ ] Use secure session tokens (random, long)
-- [ ] Set secure cookie flags (HttpOnly, Secure, SameSite)
-- [ ] Implement account lockout after failed attempts
-- [ ] Support MFA for sensitive operations
-
-## Authorization
-
-```python
-# WRONG - Check only authentication
-@login_required
-def delete_post(post_id):
-    post = Post.get(post_id)
-    post.delete()
-
-# CORRECT - Check authorization
-@login_required
-def delete_post(post_id):
-    post = Post.get(post_id)
-    if post.author_id != current_user.id and not current_user.is_admin:
-        raise Forbidden("Not authorized to delete this post")
-    post.delete()
+## Finding to Fix
+{specific finding from audit report}
+
+IMPORTANT: Do NOT apply changes yet. Produce a Preflight Report:
+1. Exactly what code/config changes you will make
+2. Security impact of the fix
+3. Risk of breaking existing functionality
+4. How to verify the fix works
+5. How to revert if the fix causes issues
 ```
 
-## Secrets Management
+After user confirms, re-dispatch with execute authority.
 
-```bash
-# WRONG - Hardcoded secrets
-API_KEY = "sk-1234567890abcdef"
+## Report Format
 
-# CORRECT - Environment variables
-API_KEY = os.environ["API_KEY"]
+```markdown
+# Security Audit Report
 
-# BETTER - Secrets manager
-API_KEY = secrets_client.get_secret("api-key")
-```
+**Scope:** {X files changed | Full codebase}
+**Languages:** {detected}
+**Scan Time:** {duration}
 
-### Secret Handling Rules
-```
-DO:
-- Use environment variables or secrets manager
-- Rotate secrets regularly
-- Use different secrets per environment
-- Audit secret access
-
-DON'T:
-- Commit secrets to git
-- Log secrets
-- Include secrets in error messages
-- Share secrets in plain text
-```
+## Summary
 
-## Security Headers
+| Category | Findings | Critical | High | Medium | Low |
+|----------|----------|----------|------|--------|-----|
+| Dependencies | X | X | X | X | X |
+| Code Patterns | X | X | X | X | X |
+| Auth & Config | X | X | X | X | X |
 
-```
-Content-Security-Policy: default-src 'self'; script-src 'self'
-X-Content-Type-Options: nosniff
-X-Frame-Options: DENY
-Strict-Transport-Security: max-age=31536000; includeSubDomains
-Referrer-Policy: strict-origin-when-cross-origin
-Permissions-Policy: geolocation=(), camera=()
+## Critical Findings
+{details with file:line, OWASP mapping, fix suggestion}
+
+## High Findings
+{details}
+
+## Medium Findings
+{details}
+
+## Low Findings
+{details}
+
+## Passed Checks
+{items that passed the auth/config review}
 ```
 
-## Quick Security Audit
+## Fallback: When Agents Are Unavailable
 
-```bash
-# Find hardcoded secrets
-rg -i "(password|secret|api_key|token)\s*=\s*['\"][^'\"]+['\"]" --type py
+If agent dispatch fails, fall back to inline scanning:
 
-# Find SQL injection risks
-rg "execute\(f['\"]|format\(" --type py
+1. Run `scripts/dependency-audit.sh` directly via Bash
+2. Run `scripts/security-scan.sh` directly via Bash
+3. Manually check auth patterns using ripgrep
+4. Present combined results (less structured than agent-based audit)
 
-# Find eval/exec usage
-rg "\b(eval|exec)\s*\(" --type py
+## Quick Reference
 
-# Check for TODO security items
-rg -i "TODO.*security|FIXME.*security"
-```
+| Task | Tier | Execution |
+|------|------|-----------|
+| Detect project stack | T1 | Inline |
+| Check audit tools | T1 | Inline |
+| Dependency scan | T2 | Agent 1 (bg) |
+| Code pattern scan | T2 | Agent 2 (bg) |
+| Auth & config review | T2 | Agent 3 (bg) |
+| Consolidate report | T2 | Inline |
+| Fix vulnerability | T3 | Expert + confirm |
+| Update dependency | T3 | Expert + confirm |
 
-## Additional Resources
+## Reference Files
 
-- `./references/owasp-detailed.md` - Full OWASP Top 10 details
-- `./references/auth-patterns.md` - JWT, OAuth, session management
-- `./references/crypto-patterns.md` - Encryption, hashing, signatures
-- `./references/secure-headers.md` - HTTP security headers guide
+| File | Contents |
+|------|----------|
+| `references/audit-quickref.md` | OWASP table, input validation, output encoding, auth checklist, secrets rules |
+| `references/owasp-detailed.md` | Full OWASP Top 10 with examples and prevention strategies |
+| `references/auth-patterns.md` | JWT, OAuth2, session management, bcrypt, argon2, MFA |
+| `references/crypto-patterns.md` | AES-GCM, RSA, key management, hashing, digital signatures |
+| `references/secure-headers.md` | CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy |
 
 ## Scripts
 
-- `./scripts/security-scan.sh` - Quick security grep patterns
-- `./scripts/dependency-audit.sh` - Check for vulnerable dependencies
+| Script | Purpose |
+|--------|---------|
+| `scripts/dependency-audit.sh` | Multi-language dependency vulnerability scanner |
+| `scripts/security-scan.sh` | ripgrep-based code pattern security scanner |
+
+## See Also
+
+| Skill | When to Combine |
+|-------|----------------|
+| `auth-ops` | Deep authentication/authorization implementation patterns |
+| `testing-ops` | Security-focused test case generation |
+| `monitoring-ops` | Security event logging and alerting |
+| `debug-ops` | Investigating security incidents |

+ 163 - 0
skills/security-ops/references/audit-quickref.md

@@ -0,0 +1,163 @@
+# Security Audit Quick Reference
+
+Essential security patterns for rapid triage during code review and audit.
+
+## OWASP Top 10 Quick Reference
+
+| Rank | Vulnerability | Prevention |
+|------|--------------|------------|
+| A01 | Broken Access Control | Check permissions server-side, deny by default |
+| A02 | Cryptographic Failures | Use TLS, hash passwords, encrypt sensitive data |
+| A03 | Injection | Parameterized queries, validate input |
+| A04 | Insecure Design | Threat modeling, secure defaults |
+| A05 | Security Misconfiguration | Harden configs, disable unused features |
+| A06 | Vulnerable Components | Update dependencies, audit regularly |
+| A07 | Auth Failures | MFA, rate limiting, secure session management |
+| A08 | Data Integrity Failures | Verify signatures, use trusted sources |
+| A09 | Logging Failures | Log security events, protect logs |
+| A10 | SSRF | Validate URLs, allowlist destinations |
+
+## Input Validation
+
+```python
+# WRONG - Trust user input
+def search(query):
+    return db.execute(f"SELECT * FROM users WHERE name = '{query}'")
+
+# CORRECT - Parameterized query
+def search(query):
+    return db.execute("SELECT * FROM users WHERE name = ?", [query])
+```
+
+### Validation Rules
+```
+Always validate:
+- Type (string, int, email format)
+- Length (min/max bounds)
+- Range (numeric bounds)
+- Format (regex for patterns)
+- Allowlist (known good values)
+
+Never trust:
+- URL parameters
+- Form data
+- HTTP headers
+- Cookies
+- File uploads
+```
+
+## Output Encoding
+
+```javascript
+// WRONG - Direct HTML insertion
+element.innerHTML = userInput;
+
+// CORRECT - Text content (auto-escapes)
+element.textContent = userInput;
+
+// CORRECT - Template with escaping
+render(`<div>${escapeHtml(userInput)}</div>`);
+```
+
+### Encoding by Context
+| Context | Encoding |
+|---------|----------|
+| HTML body | HTML entity encode |
+| HTML attribute | Attribute encode + quote |
+| JavaScript | JS encode |
+| URL parameter | URL encode |
+| CSS | CSS encode |
+
+## Authentication
+
+```python
+# Password hashing (use bcrypt, argon2, or scrypt)
+import bcrypt
+
+def hash_password(password: str) -> bytes:
+    return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
+
+def verify_password(password: str, hashed: bytes) -> bool:
+    return bcrypt.checkpw(password.encode(), hashed)
+```
+
+### Auth Checklist
+- [ ] Hash passwords with bcrypt/argon2 (cost factor 12+)
+- [ ] Implement rate limiting on login
+- [ ] Use secure session tokens (random, long)
+- [ ] Set secure cookie flags (HttpOnly, Secure, SameSite)
+- [ ] Implement account lockout after failed attempts
+- [ ] Support MFA for sensitive operations
+
+## Authorization
+
+```python
+# WRONG - Check only authentication
+@login_required
+def delete_post(post_id):
+    post = Post.get(post_id)
+    post.delete()
+
+# CORRECT - Check authorization
+@login_required
+def delete_post(post_id):
+    post = Post.get(post_id)
+    if post.author_id != current_user.id and not current_user.is_admin:
+        raise Forbidden("Not authorized to delete this post")
+    post.delete()
+```
+
+## Secrets Management
+
+```bash
+# WRONG - Hardcoded secrets
+API_KEY = "sk-1234567890abcdef"
+
+# CORRECT - Environment variables
+API_KEY = os.environ["API_KEY"]
+
+# BETTER - Secrets manager
+API_KEY = secrets_client.get_secret("api-key")
+```
+
+### Secret Handling Rules
+```
+DO:
+- Use environment variables or secrets manager
+- Rotate secrets regularly
+- Use different secrets per environment
+- Audit secret access
+
+DON'T:
+- Commit secrets to git
+- Log secrets
+- Include secrets in error messages
+- Share secrets in plain text
+```
+
+## Security Headers
+
+```
+Content-Security-Policy: default-src 'self'; script-src 'self'
+X-Content-Type-Options: nosniff
+X-Frame-Options: DENY
+Strict-Transport-Security: max-age=31536000; includeSubDomains
+Referrer-Policy: strict-origin-when-cross-origin
+Permissions-Policy: geolocation=(), camera=()
+```
+
+## Quick Grep Patterns
+
+```bash
+# Find hardcoded secrets
+rg -i "(password|secret|api_key|token)\s*=\s*['\"][^'\"]+['\"]" --type py
+
+# Find SQL injection risks
+rg "execute\(f['\"]|format\(" --type py
+
+# Find eval/exec usage
+rg "\b(eval|exec)\s*\(" --type py
+
+# Check for TODO security items
+rg -i "TODO.*security|FIXME.*security"
+```

+ 5 - 0
skills/techdebt/SKILL.md

@@ -95,6 +95,11 @@ Launch 4 subagents simultaneously (or subset if category specified):
 ```
 Scan {scope} for {category} issues.
 
+## Domain Knowledge
+Before scanning, read the relevant skill for deeper patterns:
+- Security scanner: Read skills/security-ops/references/owasp-detailed.md
+- Complexity scanner: Read skills/refactor-ops/SKILL.md
+
 Scope: {file_list or "entire codebase"}
 Language: {detected from file extensions}
 Focus: {category-specific patterns}

+ 13 - 0
skills/testgen/SKILL.md

@@ -153,13 +153,26 @@ src/auth.rs → src/auth.rs (mod tests { ... })            # inline tests
 **Invoke via Task tool:**
 ```
 Task tool with subagent_type: "[detected]-expert"
+model: "sonnet"
 Prompt includes:
+  - Skill preloading (domain knowledge):
+    "First, read these files for testing context:
+     - Read: skills/security-ops/references/owasp-detailed.md
+     - Read: skills/testing-ops/SKILL.md"
   - Source file content
   - Function signatures to test
   - Detected framework and conventions
   - Requested test type and focus
 ```
 
+**Language-specific preloads** (append to the preloading section above):
+
+| Expert | Additional Preload | Why |
+|--------|-------------------|-----|
+| python-expert | `skills/python-pytest-ops/SKILL.md` | Fixtures, marks, parametrize, async testing |
+| go-expert | `skills/go-ops/SKILL.md` | Table-driven tests, benchmarks, testify |
+| rust-expert | `skills/rust-ops/SKILL.md` | Property testing, criterion, proptest |
+
 ### Step 5: Generate Tests
 
 **Test categories based on --focus:**