agents-opencode
Advanced tools
| --- | ||
| name: adr | ||
| description: >- | ||
| Document significant architectural decisions with context, options, trade-offs, | ||
| and rationale. Creates lightweight Architecture Decision Records (ADRs) stored | ||
| as version-controlled markdown files. | ||
| license: MIT | ||
| compatibility: opencode | ||
| metadata: | ||
| author: shahboura | ||
| version: "1.0.0" | ||
| audience: developers | ||
| workflow: documentation | ||
| --- | ||
| # ADR — Architecture Decision Records | ||
| ## What I do | ||
| - Guide creation of lightweight, version-controlled Architecture Decision Records | ||
| - Provide a structured template covering context, options, rationale, consequences | ||
| - Enforce naming conventions and review checklist for consistency | ||
| - Help teams document *why* decisions were made — not just *what* was decided | ||
| ## When to use me | ||
| Activate this skill when: | ||
| - Making architectural choices that affect multiple components or teams | ||
| - Choosing between technologies, frameworks, or libraries | ||
| - Changing core design patterns, data models, or system boundaries | ||
| - Making decisions with long-term impact or high reversal cost | ||
| - Documenting why an approach was explicitly rejected (negative decisions) | ||
| ## Key Rules | ||
| ### ADR Template Structure | ||
| Every ADR includes these sections in order: | ||
| 1. **Header block** — ADR number, title, status (Proposed / Accepted / Deprecated / | ||
| Superseded by ADR-XXX), date, deciders, and optional technical story link | ||
| 2. **Context** — the situation and forces at play: background, driving forces, and constraints (technical, business, time) | ||
| 3. **Decision** — a clear, concise statement: "We will [chosen approach]" | ||
| 4. **Rationale** — why this is the best choice given the context: pros, accepted cons, and why alternatives were rejected | ||
| 5. **Considered Options** — for each option: description, pros, cons, and verdict (Selected / Rejected / Could work but) | ||
| 6. **Implementation** — changes required, migration path (if replacing existing), testing strategy, and rollback plan | ||
| 7. **Consequences** — positive outcomes, negative trade-offs, and a risk table (Risk / Probability / Impact / Mitigation) | ||
| 8. **Follow-up Actions** — action items with owners, documentation updates, review scheduling | ||
| 9. **References** — links to docs, research, similar decisions, code examples | ||
| 10. **Footer** — review date and links to related ADRs | ||
| ### Naming Convention | ||
| Store ADRs under `docs/adr/` with zero-padded numbering and kebab-case slugs: | ||
| ``` | ||
| docs/adr/ | ||
| ├── 0001-record-architecture-decisions.md | ||
| ├── 0002-use-typescript-for-frontend.md | ||
| ├── 0003-adopt-clean-architecture.md | ||
| └── 0004-use-postgresql-for-database.md | ||
| ``` | ||
| ### When to Create an ADR | ||
| Create an ADR for decisions that are: | ||
| - **Cross-cutting** — impact spans multiple components, services, or teams | ||
| - **Sticky** — hard to reverse once implemented (data model, language, framework) | ||
| - **Significant** — involve substantial cost, risk, or architectural direction | ||
| - **Informative** — the *rejection* of a plausible option carries insight worth preserving | ||
| Skip ADRs for routine choices, trivial refactors, or decisions already captured in design docs or RFCs. | ||
| ## Validation Commands | ||
| Review each ADR against this checklist before marking it as Accepted: | ||
| - [ ] Clear problem statement — reader understands the context without prior knowledge | ||
| - [ ] Multiple options considered — at least two alternatives evaluated beyond the chosen one | ||
| - [ ] Trade-offs explicitly stated — pros and cons listed for each option with verdicts | ||
| - [ ] Implementation plan defined — concrete steps, not vague intentions | ||
| - [ ] Consequences documented — both positive outcomes and accepted negative trade-offs | ||
| - [ ] Risks identified with mitigations — risk table populated, not left empty | ||
| - [ ] References to supporting materials — links to docs, research, or prototypes | ||
| - [ ] Follow-up actions assigned — owners named, timeboxes set | ||
| - [ ] Status matches reality — Proposed for drafts, Accepted only after team approval | ||
| - [ ] Naming follows convention — zero-padded number, kebab-case slug under `docs/adr/` | ||
| --- | ||
| ADR files live alongside code in version control — the record is only useful if it stays in | ||
| sync with the decisions it describes. Review Accepted ADRs when revisiting the architecture | ||
| they govern; supersede (don't delete) when a decision is replaced. |
| --- | ||
| name: api-documentation | ||
| description: API documentation standards for REST, GraphQL, gRPC, WebSocket, and SDKs | ||
| license: MIT | ||
| compatibility: opencode | ||
| metadata: | ||
| author: shahboura | ||
| version: "1.0.0" | ||
| audience: developers | ||
| workflow: documentation | ||
| --- | ||
| ## What I do | ||
| - Guide discovery and extraction of API surfaces from code (REST, GraphQL, gRPC, WebSocket, SDKs) | ||
| - Define documentation structure for endpoints, authentication, parameters, responses, and errors | ||
| - Provide OpenAPI 3.0 and Markdown format conventions | ||
| - Enforce pagination, filtering, rate limiting, error codes, and changelog standards | ||
| ## When to use me | ||
| Use when generating API documentation from code, standardizing format across services, or reviewing docs for completeness. | ||
| ## Key Rules | ||
| ### Discovery Phase | ||
| Analyze the codebase for: | ||
| - **REST:** Route definitions, HTTP methods/paths, request/response schemas, auth, | ||
| query/path/body params, status codes, rate limiting, pagination | ||
| - **GraphQL:** Schema definitions (types, queries, mutations, subscriptions), resolvers, input types, validation, auth directives | ||
| - **gRPC:** Service definitions, message types, streaming patterns | ||
| - **WebSocket:** Event names, message schemas, connection lifecycle | ||
| - **SDKs:** Public classes and methods, function signatures, configuration options | ||
| ### Output Format Selection | ||
| - **OpenAPI 3.0** — REST APIs with tooling support | ||
| - **Markdown** — Human-readable, version-controlled docs | ||
| - **AsyncAPI** — Event-driven and WebSocket APIs | ||
| - **GraphQL SDL** — Self-documenting schema | ||
| - **JSDoc/TSDoc** — Inline code comments | ||
| ### REST API Endpoint Documentation Format | ||
| Each documented endpoint must include: HTTP method, path, summary, authentication requirement, and rate limit. | ||
| **Parameter tables use this structure:** | ||
| | Parameter | Type | Required | Default | Description | | ||
| |-----------|------|----------|---------|-------------| | ||
| Provide separate tables for query parameters, path parameters, headers, and request body fields. | ||
| **Requests include:** method, full path, headers (Authorization, Content-Type), and body when applicable. | ||
| **Responses include:** status code, description, and JSON body structure. Error responses documented in a separate table: | ||
| | Status | Code | Description | | ||
| |--------|------|-------------| | ||
| **Common error codes section** must cover at minimum: 400 (validation), 401 (unauthorized), 403 (forbidden), | ||
| 404 (not found), 429 (rate limit), 500 (internal). | ||
| ### OpenAPI 3.0 Structure | ||
| For machine-readable specs, use this minimal structure: | ||
| ```yaml | ||
| openapi: 3.0.0 | ||
| info: | ||
| title: {API Name} | ||
| version: {semver} | ||
| paths: | ||
| /resource: | ||
| get|post|put|delete: | ||
| summary: {description} | ||
| parameters: [...] | ||
| responses: | ||
| '{status}': | ||
| description: {description} | ||
| content: | ||
| application/json: | ||
| schema: | ||
| $ref: '#/components/schemas/{Model}' | ||
| components: | ||
| schemas: | ||
| {Model}: | ||
| type: object | ||
| properties: {...} | ||
| ``` | ||
| ### Pagination and Filtering | ||
| - Use `page` (integer, default 1) and `limit` (integer, document max value) query parameters | ||
| - Response includes a `meta` object: `{ page, limit, total, totalPages }` | ||
| - Rate limit headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` | ||
| - Filtering via query parameters matching field names | ||
| - Sorting via `sort` parameter: prefix with `-` for descending, comma-separated for multiple fields | ||
| - Document separate rate limits for authenticated vs unauthenticated access | ||
| ### Multi-Language Examples | ||
| Provide at minimum cURL, JavaScript (fetch), and Python (requests) examples for each endpoint category. | ||
| ### Changelog | ||
| Maintain versioned changelog entries with date, additions, deprecations, and breaking changes. | ||
| ## Validation Commands | ||
| After generation, verify each checklist item: | ||
| - [ ] All endpoints documented | ||
| - [ ] Request and response examples included for each endpoint | ||
| - [ ] Authentication clearly explained (method, token acquisition flow) | ||
| - [ ] Error codes and status codes documented in dedicated tables | ||
| - [ ] Rate limits and pagination conventions specified | ||
| - [ ] Multi-language example code present (cURL, JS, Python minimum) | ||
| - [ ] Changelog maintained with version dates | ||
| - [ ] OpenAPI spec validates against the 3.0 schema (if generated) |
| --- | ||
| name: refactoring | ||
| description: >- | ||
| Systematic refactoring plan creation — detect code smells, phase improvements | ||
| safely, and deliver a step-by-step rollout with success criteria. Language- | ||
| and framework-agnostic. | ||
| license: MIT | ||
| compatibility: opencode | ||
| metadata: | ||
| author: shahboura | ||
| version: "1.0.0" | ||
| audience: developers | ||
| workflow: development | ||
| --- | ||
| # Refactoring — structured improvement without behavior change | ||
| ## What I do | ||
| - Detect code smells: long methods, duplicate code, large classes, feature envy, | ||
| primitive obsession, and switch/if-else chains | ||
| - Produce a phased refactoring plan that preserves existing behavior | ||
| - Recommend applicable patterns for each problem area | ||
| - Define rollout steps, risk mitigations, and measurable success criteria | ||
| ## When to use me | ||
| Activate this skill when: | ||
| - Code shows duplication, high complexity, or poor separation of concerns | ||
| - A module or class has grown too large to maintain safely | ||
| - You need a safe, test-first improvement roadmap before touching production code | ||
| - Any request containing "refactor", "clean up", "reduce complexity", | ||
| "restructure", "break apart", or "eliminate duplication" | ||
| ## Key Rules | ||
| ### Refactoring Principles (always apply) | ||
| 1. **Preserve Behavior** — functionality stays the same; refactoring is not rewriting | ||
| 2. **Small Steps** — make tiny, verifiable changes so every commit is safe to revert | ||
| 3. **Test First** — ensure tests exist before refactoring; add missing coverage first | ||
| 4. **Commit Often** — each small change is its own checkpoint | ||
| 5. **Review Code** — get feedback early and often | ||
| ### Code Smell Detection | ||
| Before building the plan, scan the target area for: | ||
| | Smell | Signal | Typical Fix | | ||
| |---|---|---| | ||
| | Long methods/functions | >~30 lines or high cyclomatic complexity | Extract method | | ||
| | Duplicate code | Same logic in 2+ locations | Extract shared utility | | ||
| | Large classes | >~10 public methods or mixed concerns | Extract class / delegate | | ||
| | Feature envy | One class heavily accesses another's internals | Move method to data | | ||
| | Primitive obsession | Primitives used where domain types belong | Value object / domain type | | ||
| | Switch/if-else chains | Long conditional blocks, especially on type codes | Strategy or polymorphism | | ||
| ### Five-Phase Refactoring Plan | ||
| #### Phase 1 — Preparation (Safety First) | ||
| **Goal:** Build a safety net so changes can be verified. | ||
| - Add unit tests for every function/method in the target area | ||
| - Add integration tests for features that cross module boundaries | ||
| - Achieve ≥80% code coverage on the target area before touching production code | ||
| - Run the full suite and confirm all tests pass | ||
| #### Phase 2 — Extract & Simplify | ||
| **Goal:** Break down complex code into manageable, single-responsibility pieces. | ||
| - Extract helper functions: pull validation, calculation, persistence, and | ||
| notification out of monolithic functions | ||
| - Eliminate duplication: identify repeated patterns across files, extract to a | ||
| shared utility, update all call sites, and add dedicated tests | ||
| - Verify: run the full test suite after each extraction | ||
| #### Phase 3 — Improve Architecture | ||
| **Goal:** Better separation of concerns and testability. | ||
| - Introduce a service layer when controllers/functions directly access data | ||
| sources (Controllers → Services → Repositories / Functions → Services → Data) | ||
| - Replace large switch/if-else chains on type codes with the Strategy pattern | ||
| (interface + concrete implementations + lookup map) | ||
| - Move business logic close to the data it operates on (resolve feature envy) | ||
| - Verify: all existing tests still pass; add tests for new layers | ||
| #### Phase 4 — Performance Optimization | ||
| **Goal:** Improve performance without changing behavior. | ||
| - Identify N+1 query problems and add eager loading or batched fetches | ||
| - Add missing database indexes on join columns and common filter predicates | ||
| - Benchmark before and after each change; do not "optimize" without data | ||
| - Verify: behavior unchanged, performance metrics improved | ||
| #### Phase 5 — Final Cleanup | ||
| **Goal:** Polish and document. | ||
| - Rename ambiguous variables to domain-language names; remove abbreviations | ||
| - Add API documentation (JSDoc, XML doc comments, or equivalent) | ||
| - Update architecture documentation and record design decisions | ||
| - Verify: all tests pass, documentation is current | ||
| ### Common Refactoring Patterns | ||
| | Pattern | When to apply | | ||
| |---|---| | ||
| | **Extract Method** | A function does too many things or exceeds ~30 lines | | ||
| | **Extract Class** | A class has mixed concerns or too many public methods | | ||
| | **Rename** | Names are ambiguous, abbreviated, or misaligned with domain language | | ||
| | **Introduce Parameter Object** | Groups of related parameters appear in multiple signatures | | ||
| | **Replace Conditional with Polymorphism** | Switch/if-else chains on type codes drive behavior selection | | ||
| | **Simplify Conditional** | Nested if-else or complex boolean expressions reduce readability | | ||
| ### Rollout Plan | ||
| 1. **Feature branch** — `git checkout -b refactor/<area>`, make changes, push | ||
| 2. **Code review** — request review from 2+ team members, address all feedback | ||
| 3. **Staged rollout** — deploy to staging, run smoke tests, monitor for issues | ||
| 4. **Production with safety** — deploy behind a feature flag if possible, | ||
| gradually increase traffic, monitor metrics | ||
| 5. **Cleanup** — remove old code paths, update documentation, share learnings | ||
| ### Risk Assessment Format | ||
| | Risk | Impact | Mitigation | | ||
| |------|--------|------------| | ||
| | Breaking changes | High | Comprehensive test suite first | | ||
| | Performance regression | Medium | Benchmark before/after each phase | | ||
| | Merge conflicts | Low | Frequent rebasing, small PRs | | ||
| | Scope creep | Medium | Stick to phases; defer feature changes | | ||
| ### Success Criteria | ||
| After refactoring: | ||
| - [ ] All tests pass (100%) | ||
| - [ ] Code coverage ≥80% | ||
| - [ ] Cyclomatic complexity <10 per function | ||
| - [ ] No unremediated code duplication | ||
| - [ ] Performance improved or maintained (measured) | ||
| - [ ] Documentation updated | ||
| - [ ] Team reviewed and approved | ||
| ## Validation Commands | ||
| ```bash | ||
| # Manual verification checklist — no automated validation | ||
| # [ ] All five refactoring principles are observed in the plan | ||
| # [ ] Code smells catalogued with severity and fix recommendation | ||
| # [ ] Each phase has concrete, verifiable tasks (not "improve code") | ||
| # [ ] Rollout steps include staging gate before production | ||
| # [ ] Success criteria are measurable (not "code is better") | ||
| # [ ] The plan preserves existing behavior — no feature changes included | ||
| ``` |
| --- | ||
| name: security-audit | ||
| description: >- | ||
| Comprehensive security audit of code, infrastructure, dependencies, and | ||
| deployment practices. Covers authentication, injection prevention, data | ||
| protection, API security, secret management, and logging. | ||
| license: MIT | ||
| compatibility: opencode | ||
| metadata: | ||
| author: shahboura | ||
| version: "1.0.0" | ||
| audience: developers | ||
| workflow: code-review | ||
| --- | ||
| ## What I do | ||
| - Audit authentication & authorization (password hashing, MFA, sessions, RBAC, IDOR) | ||
| - Scan for injection vulnerabilities (SQL, XSS, command injection, path traversal) | ||
| - Review data protection at rest and in transit (encryption, TLS, sensitive data handling) | ||
| - Assess API surface security (rate limiting, CORS, query depth, pagination) | ||
| - Check dependency health (known CVEs, stale packages, license risks) | ||
| - Evaluate infrastructure hardening (containers, cloud IAM, firewall, SSH) | ||
| - Hunt hardcoded secrets and verify secret management hygiene | ||
| - Validate logging/monitoring for security events and anomaly detection | ||
| - Deliver a structured audit report with severity-graded findings and an action plan | ||
| ## When to use me | ||
| Activate this skill when: | ||
| - A user requests a security audit, security review, or vulnerability assessment | ||
| - A new feature, endpoint, or deployment surface is being introduced | ||
| - Pre-release hardening or compliance (GDPR, PCI-DSS, HIPAA, SOC 2) is needed | ||
| ## Key Rules | ||
| ### Audit Areas — Checklist | ||
| #### 1. Authentication & Authorization | ||
| **Authentication:** | ||
| - Passwords hashed with strong algorithm (bcrypt, Argon2) | ||
| - Multi-factor authentication available | ||
| - Session management secure (httpOnly, secure, sameSite cookies) | ||
| - Password length/complexity requirements enforced | ||
| - Account lockout after repeated failed attempts | ||
| - JWT tokens properly validated, signed, and rotated | ||
| - Token expiration implemented; refresh token rotation in place | ||
| **Authorization:** | ||
| - Role-based access control (RBAC) applied; least privilege enforced | ||
| - Authorization checked on every request | ||
| - Resource ownership verified — no IDOR (Insecure Direct Object References) | ||
| - Horizontal and vertical privilege escalation prevented | ||
| #### 2. Input Validation & Injection Prevention | ||
| - **SQL Injection:** Parameterized queries only — no string concatenation; ORM raw queries avoided | ||
| - **XSS:** Output encoding/escaping used; Content-Security-Policy header set; dangerous methods avoided (innerHTML, dangerouslySetInnerHTML) | ||
| - **Command Injection:** No shell commands built from user input; use safe APIs (execFile, not exec); allowlist validation | ||
| - **Path Traversal:** File paths validated; relative paths (../) blocked; files served from restricted directories | ||
| #### 3. Data Protection & Encryption | ||
| - **Data at rest:** PII/PCI data encrypted; encryption keys managed properly; database/file-system encryption enabled; backups encrypted | ||
| - **Data in transit:** HTTPS/TLS enforced everywhere; TLS 1.2+ required (1.0/1.1 disabled); strong cipher suites; HSTS header set | ||
| - **Sensitive data handling:** No secrets in logs, URLs, or query params; PCI-DSS/GDPR/CCPA compliance reviewed; secrets excluded from git | ||
| #### 4. API Security | ||
| - Rate limiting on all endpoints; CORS configured with explicit origins (no wildcard) | ||
| - API keys rotated regularly; versioned APIs with backward compatibility | ||
| - Request size limits enforced; GraphQL query depth limiting; REST pagination enforced | ||
| - Authentication required on all non-public endpoints | ||
| #### 5. Dependency Vulnerabilities | ||
| - Dependencies up to date; no known CVEs (npm audit, pip-audit, safety check) | ||
| - Automated scanning configured (Dependabot, Snyk, Renovate) | ||
| - Unused dependencies removed; licenses reviewed for compatibility | ||
| #### 6. Infrastructure Security | ||
| - **Servers:** Firewall restricts to required ports; SSH key-only auth (passwords disabled); root login disabled; automatic security updates enabled; unused services disabled | ||
| - **Containers:** Trusted base images; images scanned for CVEs; non-root user in containers; secrets excluded from image layers; minimal attack surface | ||
| - **Cloud:** IAM roles with least privilege; restrictive security groups; encryption at rest (S3, RDS); VPC properly configured; audit logging (CloudTrail) enabled; MFA on all accounts | ||
| #### 7. Secret Management | ||
| - No secrets in source code or config files; environment variables or secret manager used | ||
| - Secret management service in place (Vault, AWS Secrets Manager, Doppler) | ||
| - Secrets rotated regularly; git history cleaned of any leaked secrets; .env in .gitignore | ||
| - Pre-commit hooks or CI secret scanning active (TruffleHog, GitGuardian) | ||
| #### 8. Logging & Monitoring | ||
| - Security events logged (failed logins, permission denials, privilege changes) | ||
| - Logs centralized and monitored; anomaly detection configured | ||
| - Alerts for suspicious activity (brute force, unusual patterns, privilege escalation) | ||
| - Log retention policy defined; logs must not contain sensitive data | ||
| ### Security Headers Reference | ||
| Required HTTP response headers: | ||
| ```text | ||
| X-Frame-Options: DENY | ||
| X-Content-Type-Options: nosniff | ||
| Content-Security-Policy: default-src 'self' | ||
| Strict-Transport-Security: max-age=31536000; includeSubDomains | ||
| Referrer-Policy: strict-origin-when-cross-origin | ||
| ``` | ||
| TLS: require TLS 1.2+, disable 1.0/1.1, use strong cipher suites. | ||
| ### Report Template | ||
| ```markdown | ||
| # Security Audit Report | ||
| **Date:** YYYY-MM-DD | **Scope:** [What was audited] | ||
| **Overall Risk Level:** Critical / High / Medium / Low | ||
| ## Executive Summary | ||
| [High-level findings] | ||
| ## Critical Issues | ||
| ### [Issue Title] | ||
| - **Severity:** Critical | **Category:** [area] | **Location:** `path:line` | ||
| - **Description:** [What is wrong] | **Impact:** [What could happen] | ||
| - **Recommendation:** [How to fix] | ||
| ## High / Medium / Low Priority Issues | ||
| [Same format, tiered by severity] | ||
| ## Compliance | ||
| - [ ] GDPR [ ] PCI-DSS [ ] HIPAA [ ] SOC 2 | ||
| ## Action Items | ||
| | Issue | Priority | Owner | Due | Status | | ||
| |---|---|---|---| | ||
| ## Next Steps | ||
| 1. Fix critical issues immediately | ||
| 2. Schedule high-priority fixes | ||
| 3. Re-audit after remediation | ||
| 4. Implement continuous monitoring | ||
| ``` | ||
| ### Automated Tools | ||
| Integrate into CI/CD: | ||
| | Category | Tools | | ||
| |---|---| | ||
| | SAST (static analysis) | SonarQube, Semgrep, Checkmarx | | ||
| | DAST (dynamic testing) | OWASP ZAP, Burp Suite | | ||
| | Dependency scanning | Snyk, Dependabot, npm audit, pip-audit | | ||
| | Secret scanning | TruffleHog, GitGuardian | | ||
| | Container scanning | Trivy, Clair, Docker Scout | | ||
| ### Audit Commands | ||
| Run these during the audit: | ||
| ```bash | ||
| # Dependency vulnerability scans (by ecosystem) | ||
| npm audit # Node.js | ||
| pip-audit # Python | ||
| safety check # Python (alternative) | ||
| dotnet list package --vulnerable # .NET | ||
| go list -json -m all | nancy sleuth # Go | ||
| bundle audit # Ruby | ||
| # Secret scanning | ||
| trufflehog git file://. --only-verified | ||
| git grep -E 'password.*=.*["'"'"'].*["'"'"']' # Manual: hardcoded passwords | ||
| git grep -E 'api[_-]?key.*=.*["'"'"'].*["'"'"']' # Manual: API keys | ||
| # Infrastructure | ||
| docker scan <image> # Container CVE scan | ||
| trivy image <image> # Container scan (alternative) | ||
| ``` | ||
| ## Validation Commands | ||
| ```bash | ||
| # Manual verification checklist — no automated validation | ||
| # [ ] All 8 audit areas reviewed against checklist | ||
| # [ ] Auth: hashing algo, session config, RBAC, IDOR verified | ||
| # [ ] Injection: SQL, XSS, command injection, path traversal checked | ||
| # [ ] Data: TLS config, encryption at rest, sensitive data handling validated | ||
| # [ ] API: rate limiting, CORS, auth, size limits confirmed | ||
| # [ ] Dependencies: audit tool run, zero known CVEs | ||
| # [ ] Infrastructure: container non-root, SSH key-only, IAM least privilege | ||
| # [ ] Secrets + Logging: no hardcoded secrets, security events captured | ||
| # [ ] Report generated with severity-graded findings + action plan + compliance review | ||
| ``` |
@@ -75,28 +75,5 @@ --- | ||
| **At session start:** | ||
| 1. Read `AGENTS.md` for project context and recent activity | ||
| 2. Read `state/session-state.json` for active goals/risks (if present) | ||
| 3. Read `handoff/latest.md` for continuation context (if present) | ||
| 4. Review any prior content creation patterns and topics covered | ||
| **At task completion:** | ||
| 1. Update `state/session-state.json` with content decisions, risks, and next actions (if state file is in use). | ||
| 2. Generate or refresh handoff packet using project tooling when content workflow phase changed. | ||
| 3. Then update `AGENTS.md` with timestamped entry (latest first): | ||
| ```markdown | ||
| ### YYYY-MM-DD HH:MM - [Brief Task Description] | ||
| **Agent:** blogger | ||
| **Summary:** [What was created] | ||
| - Content type and topic | ||
| - Key sources and research findings | ||
| - Follow-up content ideas | ||
| ``` | ||
| **Format requirements:** | ||
| - Date/time format: `YYYY-MM-DD HH:MM` (to minute precision) | ||
| - Latest entries first (prepend, don't append) | ||
| - Keep entries concise (3-5 bullets max) | ||
| - File auto-prunes when exceeding 100KB | ||
| **Present update for approval before ending task.** | ||
| **At session start:** Read `AGENTS.md`, `state/session-state.json`, and `handoff/latest.md`. | ||
| **At task completion:** Refresh state, generate handoff packet, and log a concise | ||
| timestamped entry (3-5 bullets) to `AGENTS.md`. Present update for approval before ending. | ||
| Adopt the format from `AGENTS.md` if it exists. |
@@ -34,2 +34,3 @@ --- | ||
| "code-change-impact": "allow" | ||
| "refactoring": "allow" | ||
| task: | ||
@@ -143,28 +144,5 @@ "*": "deny" | ||
| **At session start:** | ||
| 1. Read `AGENTS.md` for project context and recent activity | ||
| 2. Read `state/session-state.json` for active goals/risks (if present) | ||
| 3. Read `handoff/latest.md` for continuation context (if present) | ||
| 4. Review any established patterns and conventions from prior sessions | ||
| **At task completion:** | ||
| 1. Update `state/session-state.json` with implementation decisions, open risks, and next actions. | ||
| 2. Generate or refresh handoff packet using project tooling when implementation phase meaningfully changed. | ||
| 3. Then update `AGENTS.md` with timestamped entry (latest first): | ||
| ```markdown | ||
| ### YYYY-MM-DD HH:MM - [Brief Task Description] | ||
| **Agent:** codebase | ||
| **Summary:** [What was implemented] | ||
| - Key implementation decisions and rationale | ||
| - Files created or modified | ||
| - Tests added or updated | ||
| ``` | ||
| **Format requirements:** | ||
| - Date/time format: `YYYY-MM-DD HH:MM` (to minute precision) | ||
| - Latest entries first (prepend, don't append) | ||
| - Keep entries concise (3-5 bullets max) | ||
| - Only log significant implementations (skip trivial edits) | ||
| **Present update for approval before ending task.** | ||
| **At session start:** Read `AGENTS.md`, `state/session-state.json`, and `handoff/latest.md`. | ||
| **At task completion:** Refresh state, generate handoff packet, and log a concise | ||
| timestamped entry (3-5 bullets) to `AGENTS.md`. Present update for approval before ending. | ||
| Adopt the format from `AGENTS.md` if it exists. |
@@ -20,2 +20,4 @@ --- | ||
| "agent-diagnostics": "allow" | ||
| "adr": "allow" | ||
| "api-documentation": "allow" | ||
| task: | ||
@@ -22,0 +24,0 @@ "*": "deny" |
@@ -77,6 +77,4 @@ --- | ||
| ### 1-on-1 Structure | ||
| 1. Personal check-in (5 min) — How are you feeling? Work-life balance? | ||
| 2. Their agenda (20 min) — What's on your mind? Blockers? Career development? | ||
| 3. Your items (10 min) — Feedback (both ways), context sharing, alignment | ||
| 4. Action items (5 min) — Next steps and follow-ups | ||
| See [Meeting Preparation](#meeting-preparation) below for the full 5-phase framework | ||
| with question templates and action-item tracking format. | ||
@@ -124,2 +122,59 @@ ### Difficult Feedback (SBI) | ||
| ## Meeting Preparation | ||
| ### 1-on-1 Meeting Structure (30-60 min) | ||
| Employee-driven with a 70/30 (them/you) ratio. Standard phases: | ||
| | Phase | Duration | Focus | | ||
| |-------|----------|-------| | ||
| | Check-in | 5-10 min | Personal well-being, energy levels, work-life balance | | ||
| | Their Topics | 15-20 min | Employee-led — blockers, ideas, concerns. Open with: "What's on your mind?" | | ||
| | Your Topics | 10-15 min | Specific feedback (positive + constructive) using SBI. Share org/team updates. | | ||
| | Career Development | 10-15 min | Goals progress, skills growth, stretch opportunities, 6-12 month aspirations | | ||
| | Action Items | 5 min | Clear next steps with owners and due dates | | ||
| ### Key Question Templates | ||
| Pick 2-3 per meeting: | ||
| 1. **"What's on your mind?"** — Open floor; their agenda comes first. | ||
| 2. **"What's energizing you? What's draining you?"** — Surfaces blockers and engagement signals. | ||
| 3. **"Where do you see yourself in 6-12 months?"** — Career trajectory and aspiration check. | ||
| 4. **"What feedback do you have for me?"** — Two-way trust builder; normalize upward feedback. | ||
| 5. **"How are you feeling about the team?"** — Uncovers dynamics, collaboration gaps, morale. | ||
| 6. **"What would make your job more enjoyable?"** — Engagement signal. **"Tell me more…"** — Go deeper on anything. | ||
| ### Action-Item Tracking | ||
| Document during the meeting and send summary same-day. Track over time for recurring themes and engagement trends. | ||
| **For Them:** | ||
| - [ ] [Action item] — Due: [Date] | ||
| **For You:** | ||
| - [ ] [Follow-up task] — Due: [Date] | ||
| **Joint:** | ||
| - [ ] [Collaboration item] — Due: [Date] | ||
| ### Post-Meeting Follow-Up | ||
| Send within 24 hours: | ||
| - **Summary:** 3-5 bullet recap of key discussion points | ||
| - **Action items:** Copied from above with owners and due dates | ||
| - **Next meeting:** Date/time, any prep needed | ||
| - **Tone:** Positive, forward-looking — focus on growth, not critique | ||
| ### Special Situations | ||
| **New hire / onboarding:** | ||
| Focus on belonging and clarity — "What's clear? What's confusing? Who should you meet?" | ||
| Check ramp-up progress against 30/60/90-day plan. Over-communicate culture norms. | ||
| **Performance concern:** | ||
| Be specific, not general — "The last two PRs had 5+ review cycles" not "Your code quality needs work." | ||
| Use SBI format. Co-create an improvement plan. Document expectations in writing. | ||
| **Promotion discussion:** | ||
| Review criteria together. Identify gaps between current and target level. | ||
| Co-create a development plan with measurable milestones. Be honest about timeline. | ||
| **Remote / distributed:** | ||
| Check for isolation, async communication friction, timezone burden, meeting fatigue. | ||
| ## Skill Activation Policy | ||
@@ -135,34 +190,14 @@ | ||
| ## Investigation tools | ||
| - Use `read`, `glob`, and `grep` for file and content exploration. | ||
| - Use `bash` only for git-history analysis (for example `git log`, `git shortlog`, `git blame`) and for running project scripts when delivery context requires it. | ||
| - Do not use `bash` for tasks already covered by `read`/`glob`/`write` (listing files, drafting docs, simple content operations). | ||
| - Use `read`, `glob`, `grep` for file exploration; `bash` only for git-history analysis and project scripts. Do not use `bash` for tasks covered by `read`/`glob`/`write`. | ||
| ## Workflow Cadence | ||
| 1. Clarify objective, stakeholders, and decision deadline. | ||
| 2. Choose framework (RACI / Eisenhower / Risk matrix) and draft options. | ||
| 3. Validate feasibility with team capacity and execution constraints. | ||
| 4. Produce communication-ready artifacts (update draft, talking points, next-step plan). | ||
| 2. Choose framework, draft options, validate feasibility. | ||
| 3. Produce communication-ready artifacts (talking points, next-step plan). | ||
| ## Context Persistence | ||
| **At session start:** | ||
| 1. Read `AGENTS.md` for project context and review existing EM-related documents. | ||
| 2. Read `state/session-state.json` for active goals/risks (if present). | ||
| 3. Read `handoff/latest.md` for continuation context (if present). | ||
| **At task completion:** | ||
| 1. Update `state/session-state.json` with key recommendations, risks, and next actions. | ||
| 2. Generate or refresh handoff packet using project tooling when advisory state changed. | ||
| 3. Then update `AGENTS.md` with timestamped entry (latest first, 3-5 bullets max): | ||
| ```markdown | ||
| ### YYYY-MM-DD HH:MM - [Brief Task Description] | ||
| **Agent:** em-advisor | ||
| **Summary:** [What was advised or created] | ||
| - Key decisions or recommendations made | ||
| - Documents created or modified | ||
| - Follow-up actions identified | ||
| ``` | ||
| Present update for approval before ending task. | ||
| **At session start:** Read `AGENTS.md`, `state/session-state.json`, and `handoff/latest.md`. | ||
| **At task completion:** Refresh state, generate handoff packet, and log a concise | ||
| timestamped entry (3-5 bullets) to `AGENTS.md`. Present update for approval before ending. | ||
| Adopt the format from `AGENTS.md` if it exists. |
@@ -38,2 +38,4 @@ --- | ||
| "code-change-impact": "allow" | ||
| "refactoring": "allow" | ||
| "legal-advisor": "allow" | ||
| task: | ||
@@ -61,22 +63,36 @@ "*": "deny" | ||
| **Planning Mode (Proposal Without Implementation):** | ||
| - Analyzing complex existing code before refactoring | ||
| - Risk assessment and architectural review | ||
| - Brainstorming solutions without immediate execution | ||
| - Creating detailed step-by-step plans for others to execute | ||
| - When you want a "second opinion" before committing to changes | ||
| **Planning Mode (Read-Only):** Risk assessment, architectural review, brainstorming, | ||
| creating step-by-step plans for others to execute. No code changes. | ||
| **Execution Mode (Full End-to-End):** | ||
| - Complex features requiring implementation + docs + review | ||
| - Multi-phase projects with dependencies | ||
| - Tasks spanning multiple domains (backend + frontend + docs) | ||
| - Refactoring projects affecting multiple modules | ||
| - Migration projects with validation steps | ||
| **Execution Mode (Full End-to-End):** Complex features, multi-phase projects, cross-domain | ||
| tasks, refactoring, migrations. Plans + coordinates specialized agents. | ||
| **Simple Implementation:** | ||
| - Use @codebase directly for straightforward feature requests | ||
| - Use @orchestrator when coordination across multiple agents is needed | ||
| - Defer full doc/lint validation (`npm run doctor`, `npm run lint:md`) to the final | ||
| integration phase. Run targeted checks (typecheck, test) during implementation phases. | ||
| - For single-file or single-domain changes, implement directly instead of delegating | ||
| to @codebase — avoids handoff context loss. Edits require per-file confirmation | ||
| (`edit: ask`), so the benefit is context preservation, not speed. | ||
| ### Implementation Routing | ||
| | Scope | Who implements | Why | | ||
| |---|---|---| | ||
| | Single file, small edit | Orchestrator directly | Handoff costs more than the task | | ||
| | Multi-file, same domain | Orchestrator directly | Keeps context, same skill applies | | ||
| | Multi-file, cross-domain | @codebase | Profile detection + multi-language validation | | ||
| | New project, unfamiliar stack | @codebase | Auto-detection saves setup time | | ||
| Note: this extends the delegation model. When direct implementation applies, | ||
| skip the @codebase handoff. For all other implementation work, follow the | ||
| canonical delegation path in the reference file (`implementation → @codebase`). | ||
| ### Profile Detection & Validation | ||
| When implementing directly, follow the @codebase agent's profile detection rules | ||
| (`.opencode/agents/codebase.md#Profile Detection`) and validation commands | ||
| (`.opencode/agents/codebase.md#Profile Validation Commands`). | ||
| Log detected profile at start: `Detected active profile: <profile>`. | ||
| ## Workflow | ||
@@ -159,2 +175,4 @@ | ||
| to assess blast radius before delegating implementation. | ||
| - Load `legal-advisor` for fast license checks on single-file dependency changes; | ||
| delegate to @legal-advisor agent for full compliance audits spanning multiple dependencies. | ||
@@ -185,1 +203,2 @@ ## Communication Style | ||
| timestamped entry (3-5 bullets) to `AGENTS.md`. Present update for approval before ending. | ||
| Adopt the format from `AGENTS.md` if it exists. |
@@ -32,2 +32,4 @@ --- | ||
| "agent-diagnostics": "allow" | ||
| "adr": "allow" | ||
| "refactoring": "allow" | ||
| task: | ||
@@ -186,28 +188,5 @@ "*": "deny" | ||
| **At session start:** | ||
| 1. Read `AGENTS.md` for project context and recent activity | ||
| 2. Read `state/session-state.json` for active goals/risks (if present) | ||
| 3. Read `handoff/latest.md` for continuation context (if present) | ||
| 4. Review prior planning decisions and patterns | ||
| **At task completion:** | ||
| 1. Refresh `state/session-state.json` with planning decisions, risks, and recommended next actions. | ||
| 2. Generate or refresh handoff packet using project tooling when plan state changed. | ||
| 3. Then update `AGENTS.md` with timestamped entry (latest first): | ||
| ```markdown | ||
| ### YYYY-MM-DD HH:MM - [Brief Task Description] | ||
| **Agent:** planner | ||
| **Summary:** [What was analyzed/planned] | ||
| - Key findings and recommendations | ||
| - Risks identified | ||
| - Recommended implementation sequence | ||
| ``` | ||
| **Format requirements:** | ||
| - Date/time format: `YYYY-MM-DD HH:MM` (to minute precision) | ||
| - Latest entries first (prepend, don't append) | ||
| - Keep entries concise (3-5 bullets max) | ||
| - File auto-prunes when exceeding 100KB | ||
| **Present update for approval before ending task.** | ||
| **At session start:** Read `AGENTS.md`, `state/session-state.json`, and `handoff/latest.md`. | ||
| **At task completion:** Refresh state, generate handoff packet, and log a concise | ||
| timestamped entry (3-5 bullets) to `AGENTS.md`. Present update for approval before ending. | ||
| Adopt the format from `AGENTS.md` if it exists. |
@@ -31,2 +31,3 @@ --- | ||
| "code-change-impact": "allow" | ||
| "security-audit": "allow" | ||
| task: | ||
@@ -33,0 +34,0 @@ "*": "deny" |
@@ -8,412 +8,6 @@ --- | ||
| # 1-on-1 Preparation Prompt | ||
| # 1-on-1 Preparation | ||
| Meeting scope: $ARGUMENTS | ||
| Prepare comprehensive talking points and structure for effective 1-on-1 meetings with team members, focusing on growth, feedback, and alignment. | ||
| ## Meeting Structure (30-60 minutes) | ||
| ### 1. Check-in (5-10 min) | ||
| Personal connection and current state | ||
| ### 2. Their Topics (15-20 min) | ||
| Employee-led discussion | ||
| ### 3. Your Topics (10-15 min) | ||
| Manager feedback and updates | ||
| ### 4. Career Development (10-15 min) | ||
| Growth and future planning | ||
| ### 5. Action Items (5 min) | ||
| Clear next steps | ||
| --- | ||
| ## Pre-Meeting Preparation | ||
| ### Review Before Meeting | ||
| - [ ] **Last 1-on-1 Notes** | ||
| - Outstanding action items | ||
| - Follow-ups promised | ||
| - Topics tabled for later | ||
| - [ ] **Recent Work** | ||
| - PRs/commits reviewed | ||
| - Projects completed/in-progress | ||
| - Collaboration patterns observed | ||
| - [ ] **Performance Data** | ||
| - Metrics/KPIs | ||
| - Feedback from peers | ||
| - Sprint contributions | ||
| - [ ] **Career Progress** | ||
| - Goals set | ||
| - Skills development | ||
| - Growth opportunities | ||
| ### Your Talking Points | ||
| **Positive Feedback (Specific Examples):** | ||
| 1. [Achievement/behavior] - Why it mattered | ||
| 2. [Good decision] - Impact on team/project | ||
| 3. [Growth observed] - Progress toward goals | ||
| **Constructive Feedback (Behavior-Based):** | ||
| 1. [Observation] - [Impact] - [Suggestion] | ||
| 2. [Pattern noticed] - [Effect] - [Support offered] | ||
| **Updates to Share:** | ||
| 1. Team/org changes | ||
| 2. Project priorities | ||
| 3. Strategic direction | ||
| **Questions to Ask:** | ||
| 1. What's energizing you right now? | ||
| 2. What's draining you? | ||
| 3. What support do you need from me? | ||
| --- | ||
| ## 1-on-1 Meeting Template | ||
| ```markdown | ||
| # 1-on-1: [Employee Name] - [Date] | ||
| **Frequency:** Weekly / Biweekly / Monthly | ||
| **Duration:** 30 / 60 minutes | ||
| **Location:** [Office / Video Call / Walking Meeting] | ||
| --- | ||
| ## Check-in (5-10 min) | ||
| ### How are you doing? | ||
| - Personal well-being | ||
| - Work-life balance | ||
| - Energy levels | ||
| - Any concerns? | ||
| **Notes:** | ||
| [Capture their response] | ||
| --- | ||
| ## Their Agenda (15-20 min) | ||
| **Give them space to drive the conversation** | ||
| ### Their Topics: | ||
| 1. [Topic they want to discuss] | ||
| 2. [Question they have] | ||
| 3. [Concern or idea] | ||
| **Discussion Notes:** | ||
| [Capture key points, decisions, action items] | ||
| **Active Listening:** | ||
| - Ask open-ended questions | ||
| - Probe deeper: "Tell me more about..." | ||
| - Reflect back: "What I'm hearing is..." | ||
| - Validate feelings: "That makes sense because..." | ||
| --- | ||
| ## Your Topics (10-15 min) | ||
| ### 1. Positive Feedback 🌟 | ||
| **[Specific Achievement/Behavior]** | ||
| - What: [Describe what they did] | ||
| - Impact: [Why it mattered - team, project, org] | ||
| - Appreciation: [Specific praise] | ||
| Example: | ||
| > "Your code review on the auth refactor PR was excellent. You caught the security issue with token expiration and provided a clear solution. This prevented a potential production bug and saved us debugging time. Really appreciate your thoroughness." | ||
| ### 2. Constructive Feedback 💭 | ||
| **[Area for Growth]** | ||
| - Observation: [Specific behavior, not personality] | ||
| - Impact: [How it affects work/team] | ||
| - Request: [What you'd like to see instead] | ||
| - Support: [How you'll help] | ||
| Example: | ||
| > "I've noticed in the last few standups, updates have been brief without mentioning blockers. This makes it hard for the team to help. Could you share more detail about what you're working on and any obstacles? Let's pair on your next update to find the right level of detail." | ||
| **Use SBI Model (Situation-Behavior-Impact):** | ||
| - Situation: When [specific context] | ||
| - Behavior: You [observable action] | ||
| - Impact: The effect was [consequence] | ||
| ### 3. Project/Team Updates 📢 | ||
| - [Update 1]: [Details and impact on their work] | ||
| - [Update 2]: [Context and expectations] | ||
| - [Priority change]: [Why and what it means] | ||
| --- | ||
| ## Career Development (10-15 min) | ||
| ### Goals Progress Review | ||
| **Current Quarter Goals:** | ||
| | Goal | Status | Progress Notes | | ||
| |------|--------|----------------| | ||
| | [Goal 1] | 🟢 On Track / 🟡 At Risk / 🔴 Blocked | [Notes] | | ||
| | [Goal 2] | 🟢 On Track / 🟡 At Risk / 🔴 Blocked | [Notes] | | ||
| | [Goal 3] | 🟢 On Track / 🟡 At Risk / 🔴 Blocked | [Notes] | | ||
| ### Skills Development | ||
| **What are you learning?** | ||
| - Technical skills: [Area they're improving] | ||
| - Soft skills: [Communication, leadership, etc.] | ||
| - Challenges faced: [Obstacles to growth] | ||
| **Growth Opportunities Discussed:** | ||
| - [Opportunity 1]: [Type: project, training, mentorship] | ||
| - [Opportunity 2]: [How it aligns with their goals] | ||
| - [Stretch assignment]: [Why now is the right time] | ||
| ### Career Aspirations | ||
| **Long-term Goals (6-12 months):** | ||
| - [Where they want to grow] | ||
| - [Skills they want to develop] | ||
| - [Role they're interested in] | ||
| **How I Can Help:** | ||
| - [Support you'll provide] | ||
| - [Resources you'll connect them with] | ||
| - [Visibility opportunities] | ||
| --- | ||
| ## Action Items | ||
| ### For Them: | ||
| - [ ] [Action item 1] - Due: [Date] | ||
| - [ ] [Action item 2] - Due: [Date] | ||
| - [ ] [Action item 3] - Due: [Date] | ||
| ### For You: | ||
| - [ ] [Follow-up task 1] - Due: [Date] | ||
| - [ ] [Connect them with X] - Due: [Date] | ||
| - [ ] [Review/approve Y] - Due: [Date] | ||
| ### Joint Actions: | ||
| - [ ] [Collaborate on Z] - Due: [Date] | ||
| --- | ||
| ## Topics for Next Time | ||
| - [Tabled topic 1] | ||
| - [Follow-up on X in 2 weeks] | ||
| - [Deep dive on Y next month] | ||
| --- | ||
| ## Key Takeaways | ||
| **Summary:** | ||
| [1-2 sentence summary of the meeting] | ||
| **Mood/Engagement:** | ||
| 😊 Energized | 😐 Neutral | 😟 Concerned | 🔥 Stressed | ||
| **Energy Level:** | ||
| 🟢 High | 🟡 Medium | 🔴 Low | ||
| **Overall Sentiment:** | ||
| [How they're feeling about work, team, projects] | ||
| --- | ||
| ## Private Manager Notes | ||
| [Observations, concerns, or context not shared with employee] | ||
| **Patterns to Watch:** | ||
| - [Behavior or trend] | ||
| **Coaching Plan:** | ||
| - [How you'll support their development] | ||
| **Career Path Considerations:** | ||
| - [Promotion readiness, lateral moves, etc.] | ||
| --- | ||
| **Next 1-on-1:** [Date/Time] | ||
| ``` | ||
| --- | ||
| ## Effective 1-on-1 Techniques | ||
| ### Do's ✅ | ||
| 1. **Be Present** | ||
| - No laptop (unless taking notes together) | ||
| - Turn off notifications | ||
| - Active listening | ||
| 2. **Let Them Lead** | ||
| - Ask: "What's on your mind?" | ||
| - Their agenda comes first | ||
| - Space for what matters to them | ||
| 3. **Focus on Growth** | ||
| - Discuss career goals | ||
| - Identify learning opportunities | ||
| - Celebrate progress | ||
| 4. **Give Specific Feedback** | ||
| - Use concrete examples | ||
| - Timely (recent events) | ||
| - Balanced (positive and constructive) | ||
| 5. **Follow Through** | ||
| - Track action items | ||
| - Do what you promise | ||
| - Accountability both ways | ||
| ### Don'ts ❌ | ||
| 1. **Don't Make it a Status Update** | ||
| - Use async tools for project updates | ||
| - 1-on-1s are for deeper conversations | ||
| 2. **Don't Dominate the Conversation** | ||
| - Aim for 70/30 (them/you) | ||
| - Ask questions, don't lecture | ||
| 3. **Don't Surprise Them** | ||
| - Performance feedback should be ongoing | ||
| - 1-on-1s aren't for first-time critiques | ||
| 4. **Don't Skip or Reschedule Lightly** | ||
| - Shows priority and respect | ||
| - Consistency builds trust | ||
| 5. **Don't Forget to Document** | ||
| - Shared notes maintain context | ||
| - Track progress over time | ||
| --- | ||
| ## Question Bank | ||
| ### Opening Questions | ||
| - "What's on your mind?" | ||
| - "What's been going well this week?" | ||
| - "What's been challenging?" | ||
| - "What can I do to support you better?" | ||
| ### Career Development | ||
| - "Where do you see yourself in 6-12 months?" | ||
| - "What skills do you want to develop?" | ||
| - "What project would you like to work on next?" | ||
| - "Who on the team do you want to learn from?" | ||
| ### Feedback & Growth | ||
| - "What feedback do you have for me?" | ||
| - "How can I be a better manager to you?" | ||
| - "What's one thing you'd change about how we work?" | ||
| - "What would make your job more enjoyable?" | ||
| ### Team Dynamics | ||
| - "How are you feeling about the team?" | ||
| - "Who would you like to collaborate with more?" | ||
| - "Any concerns about team dynamics?" | ||
| - "How can we improve our processes?" | ||
| ### Probing Deeper | ||
| - "Tell me more about that..." | ||
| - "What's behind that feeling?" | ||
| - "How does that impact you?" | ||
| - "What would success look like?" | ||
| --- | ||
| ## Follow-up Actions | ||
| ### After Meeting: | ||
| 1. **Send summary** (same day) | ||
| - Key decisions | ||
| - Action items | ||
| - Next meeting topics | ||
| 2. **Complete your action items** | ||
| - Don't wait until next 1-on-1 | ||
| - Update them on progress | ||
| 3. **Update private notes** | ||
| - Patterns observed | ||
| - Coaching strategies | ||
| - Career development plans | ||
| ### Track Over Time: | ||
| - Recurring themes | ||
| - Goal progress | ||
| - Engagement trends | ||
| - Growth trajectory | ||
| --- | ||
| ## Special Situations | ||
| ### Difficult Conversations | ||
| **Performance Issues:** | ||
| - Be direct but compassionate | ||
| - Focus on behavior, not person | ||
| - Offer clear path to improvement | ||
| - Document the conversation | ||
| **Personal Struggles:** | ||
| - Show empathy | ||
| - Offer resources (EAP, time off) | ||
| - Adjust expectations temporarily | ||
| - Follow up more frequently | ||
| **Conflict with Teammates:** | ||
| - Get both perspectives | ||
| - Focus on collaboration | ||
| - Facilitate resolution | ||
| - Follow up to ensure improvement | ||
| ### High Performers | ||
| - Challenge them with stretch goals | ||
| - Discuss promotion path | ||
| - Provide visibility opportunities | ||
| - Connect with senior leaders | ||
| ### Disengaged Employees | ||
| - Explore root causes | ||
| - Identify what would re-engage them | ||
| - Offer new challenges or changes | ||
| - Set clear expectations | ||
| --- | ||
| ## Success Metrics | ||
| **Effective 1-on-1s result in:** | ||
| - ✅ Increased engagement | ||
| - ✅ Clear career path | ||
| - ✅ Strong manager-report relationship | ||
| - ✅ Proactive problem-solving | ||
| - ✅ Continuous feedback loop | ||
| - ✅ Goal alignment | ||
| - ✅ Higher retention | ||
| Prepare for a 1-on-1 meeting. Use the meeting structure, question templates, | ||
| and action-item tracking format in the agent's Meeting Preparation section. | ||
| Scope: $ARGUMENTS |
@@ -8,366 +8,6 @@ --- | ||
| # API Documentation Generation | ||
| # API Documentation | ||
| Target scope: $ARGUMENTS | ||
| Generate detailed API documentation by analyzing the codebase and extracting API endpoints, parameters, and responses. | ||
| ## Step 1: Specify Documentation Scope | ||
| What to document: | ||
| - [ ] REST API endpoints | ||
| - [ ] GraphQL schema | ||
| - [ ] gRPC services | ||
| - [ ] WebSocket events | ||
| - [ ] Public libraries/SDKs | ||
| - [ ] CLI commands | ||
| ## Step 2: Discovery Phase | ||
| Analyze codebase for: | ||
| ### REST APIs | ||
| - Controller/route definitions | ||
| - HTTP methods and paths | ||
| - Request/response schemas | ||
| - Authentication requirements | ||
| - Query parameters, path parameters, body schemas | ||
| - Status codes and error responses | ||
| - Rate limiting and pagination | ||
| ### GraphQL | ||
| - Schema definitions (types, queries, mutations, subscriptions) | ||
| - Resolver implementations | ||
| - Input types and validation | ||
| - Authentication/authorization directives | ||
| ### Libraries/SDKs | ||
| - Public classes and methods | ||
| - Function signatures and types | ||
| - Usage examples | ||
| - Configuration options | ||
| ## Step 3: Choose Output Format | ||
| - **OpenAPI 3.0** (REST APIs) - Standard spec with tooling support | ||
| - **Markdown** (General docs) - Human-readable, version-controlled | ||
| - **AsyncAPI** (Event-driven) - For async/websocket APIs | ||
| - **JSDoc/TSDoc** (Code comments) - Inline documentation | ||
| - **GraphQL Schema** (SDL) - Self-documenting schema | ||
| ## Step 4: Generate Documentation | ||
| ### REST API Documentation Template | ||
| ```markdown | ||
| # [API Name] Documentation | ||
| ## Overview | ||
| [Brief description of the API and its purpose] | ||
| **Base URL:** `https://api.example.com/v1` | ||
| **Authentication:** [Bearer Token / API Key / OAuth2] | ||
| **Content-Type:** `application/json` | ||
| --- | ||
| ## Authentication | ||
| ### Bearer Token | ||
| Include token in Authorization header: | ||
| ``` | ||
| Authorization: Bearer <your_token> | ||
| ``` | ||
| **Get Token:** | ||
| ```bash | ||
| POST /auth/login | ||
| Content-Type: application/json | ||
| { | ||
| "email": "user@example.com", | ||
| "password": "your_password" | ||
| } | ||
| ``` | ||
| --- | ||
| ## Endpoints | ||
| ### `GET /users` | ||
| Retrieve a paginated list of users with optional filtering. | ||
| **Authentication:** Required | ||
| **Rate Limit:** 100 requests/minute | ||
| **Query Parameters:** | ||
| | Parameter | Type | Required | Default | Description | | ||
| |-----------|------|----------|---------|-------------| | ||
| | `page` | integer | No | 1 | Page number | | ||
| | `limit` | integer | No | 10 | Items per page (max: 100) | | ||
| | `role` | string | No | - | Filter by role: `admin`, `user`, `guest` | | ||
| | `search` | string | No | - | Search by name or email | | ||
| **Example Request:** | ||
| ```bash | ||
| GET /users?page=1&limit=20&role=admin | ||
| Authorization: Bearer <token> | ||
| ``` | ||
| **Response: 200 OK** | ||
| ```json | ||
| { | ||
| "data": [ | ||
| { | ||
| "id": 1, | ||
| "email": "admin@example.com", | ||
| "name": "Admin User", | ||
| "role": "admin", | ||
| "createdAt": "2025-01-15T10:30:00Z" | ||
| } | ||
| ], | ||
| "meta": { | ||
| "page": 1, | ||
| "limit": 20, | ||
| "total": 150, | ||
| "totalPages": 8 | ||
| } | ||
| } | ||
| ``` | ||
| **Error Responses:** | ||
| | Status | Description | | ||
| |--------|-------------| | ||
| | 401 | Unauthorized - Invalid or missing token | | ||
| | 403 | Forbidden - Insufficient permissions | | ||
| | 429 | Too Many Requests - Rate limit exceeded | | ||
| --- | ||
| ### `POST /users` | ||
| Create a new user account. | ||
| **Authentication:** Required (Admin only) | ||
| **Request Body:** | ||
| ```json | ||
| { | ||
| "email": "newuser@example.com", | ||
| "name": "New User", | ||
| "role": "user", | ||
| "password": "secure_password" | ||
| } | ||
| ``` | ||
| **Validation Rules:** | ||
| - `email`: Valid email format, unique | ||
| - `name`: 2-100 characters | ||
| - `role`: One of: `admin`, `user`, `guest` | ||
| - `password`: Minimum 8 characters | ||
| **Response: 201 Created** | ||
| ```json | ||
| { | ||
| "id": 151, | ||
| "email": "newuser@example.com", | ||
| "name": "New User", | ||
| "role": "user", | ||
| "createdAt": "2025-12-23T18:45:00Z" | ||
| } | ||
| ``` | ||
| **Error Response: 400 Bad Request** | ||
| ```json | ||
| { | ||
| "error": "Validation failed", | ||
| "details": [ | ||
| { | ||
| "field": "email", | ||
| "message": "Email already exists" | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
| --- | ||
| ### `GET /users/:id` | ||
| Retrieve a single user by ID. | ||
| **Authentication:** Required | ||
| **Path Parameters:** | ||
| - `id` (integer): User ID | ||
| **Response: 200 OK** | ||
| ```json | ||
| { | ||
| "id": 1, | ||
| "email": "user@example.com", | ||
| "name": "User Name", | ||
| "role": "user", | ||
| "createdAt": "2025-01-15T10:30:00Z", | ||
| "lastLogin": "2025-12-23T17:20:00Z" | ||
| } | ||
| ``` | ||
| **Error: 404 Not Found** | ||
| ```json | ||
| { | ||
| "error": "User not found", | ||
| "userId": 999 | ||
| } | ||
| ``` | ||
| --- | ||
| ## Common Error Codes | ||
| | Status | Code | Description | | ||
| |--------|------|-------------| | ||
| | 400 | `VALIDATION_ERROR` | Request validation failed | | ||
| | 401 | `UNAUTHORIZED` | Missing or invalid authentication | | ||
| | 403 | `FORBIDDEN` | Insufficient permissions | | ||
| | 404 | `NOT_FOUND` | Resource doesn't exist | | ||
| | 429 | `RATE_LIMIT_EXCEEDED` | Too many requests | | ||
| | 500 | `INTERNAL_ERROR` | Server error | | ||
| --- | ||
| ## Rate Limiting | ||
| All endpoints are rate-limited: | ||
| - **Authenticated:** 1000 requests/hour | ||
| - **Unauthenticated:** 100 requests/hour | ||
| Rate limit info in response headers: | ||
| ``` | ||
| X-RateLimit-Limit: 1000 | ||
| X-RateLimit-Remaining: 950 | ||
| X-RateLimit-Reset: 1640275200 | ||
| ``` | ||
| --- | ||
| ## Pagination | ||
| List endpoints support pagination: | ||
| - Use `page` and `limit` query parameters | ||
| - Response includes `meta` object with pagination details | ||
| **Example:** | ||
| ```bash | ||
| GET /users?page=2&limit=50 | ||
| ``` | ||
| --- | ||
| ## Filtering & Sorting | ||
| Use query parameters: | ||
| ```bash | ||
| GET /users?role=admin&sort=-createdAt&search=john | ||
| ``` | ||
| - Prefix with `-` for descending sort | ||
| - Multiple sort fields: `sort=role,-createdAt` | ||
| --- | ||
| ## Examples | ||
| ### cURL | ||
| ```bash | ||
| curl -X GET "https://api.example.com/v1/users?page=1&limit=10" \ | ||
| -H "Authorization: Bearer <token>" \ | ||
| -H "Content-Type: application/json" | ||
| ``` | ||
| ### JavaScript (fetch) | ||
| ```javascript | ||
| const response = await fetch('https://api.example.com/v1/users', { | ||
| headers: { | ||
| 'Authorization': `Bearer ${token}`, | ||
| 'Content-Type': 'application/json' | ||
| } | ||
| }); | ||
| const data = await response.json(); | ||
| ``` | ||
| ### Python (requests) | ||
| ```python | ||
| import requests | ||
| headers = { | ||
| 'Authorization': f'Bearer {token}', | ||
| 'Content-Type': 'application/json' | ||
| } | ||
| response = requests.get('https://api.example.com/v1/users', headers=headers) | ||
| data = response.json() | ||
| ``` | ||
| --- | ||
| ## Changelog | ||
| ### v1.1.0 (2025-12-23) | ||
| - Added filtering by role | ||
| - Increased rate limits for authenticated users | ||
| - Added `lastLogin` field to user response | ||
| ### v1.0.0 (2025-01-15) | ||
| - Initial API release | ||
| ``` | ||
| ## Step 5: Validation | ||
| After generation, verify: | ||
| - [ ] All endpoints documented | ||
| - [ ] Request/response examples included | ||
| - [ ] Authentication clearly explained | ||
| - [ ] Error codes documented | ||
| - [ ] Rate limits specified | ||
| - [ ] Example code in multiple languages | ||
| - [ ] Changelog maintained | ||
| ## OpenAPI Spec Alternative | ||
| For machine-readable format, generate OpenAPI 3.0: | ||
| ```yaml | ||
| openapi: 3.0.0 | ||
| info: | ||
| title: User Management API | ||
| version: 1.0.0 | ||
| paths: | ||
| /users: | ||
| get: | ||
| summary: List users | ||
| parameters: | ||
| - name: page | ||
| in: query | ||
| schema: | ||
| type: integer | ||
| responses: | ||
| '200': | ||
| description: Success | ||
| content: | ||
| application/json: | ||
| schema: | ||
| type: object | ||
| properties: | ||
| data: | ||
| type: array | ||
| items: | ||
| $ref: '#/components/schemas/User' | ||
| components: | ||
| schemas: | ||
| User: | ||
| type: object | ||
| properties: | ||
| id: | ||
| type: integer | ||
| email: | ||
| type: string | ||
| ``` | ||
| Generate API documentation. Load `api-documentation` skill for the full methodology | ||
| (discovery, endpoint format, OpenAPI structure, validation checklist). | ||
| Scope: $ARGUMENTS |
@@ -8,327 +8,6 @@ --- | ||
| # Architecture Decision Record (ADR) | ||
| # Architecture Decision Record | ||
| Decision scope: $ARGUMENTS | ||
| Document significant architectural decisions using the ADR format. This creates a historical record of why decisions were made. | ||
| ## ADR Template | ||
| ```markdown | ||
| # ADR-[NUMBER]: [Decision Title] | ||
| **Status:** [Proposed / Accepted / Deprecated / Superseded by ADR-XXX] | ||
| **Date:** YYYY-MM-DD | ||
| **Deciders:** [List of people involved] | ||
| **Technical Story:** [Link to issue/ticket if applicable] | ||
| ## Context | ||
| [Describe the situation and the forces at play. What is the issue we're trying to solve? What are the constraints? What factors influence the decision?] | ||
| ### Background | ||
| [Additional context about the problem domain, current architecture, or relevant history] | ||
| ### Driving Forces | ||
| - [Factor 1 influencing the decision] | ||
| - [Factor 2 influencing the decision] | ||
| - [Factor 3 influencing the decision] | ||
| ### Constraints | ||
| - [Constraint 1 that limits options] | ||
| - [Constraint 2 that limits options] | ||
| - [Technical/Business/Time constraints] | ||
| ## Decision | ||
| [State the decision clearly and concisely. What will we do?] | ||
| **We will [chosen approach]** | ||
| ## Rationale | ||
| [Explain why this decision was made. What makes this the best choice given the context?] | ||
| ### Pros of This Approach | ||
| - ✅ [Benefit 1] | ||
| - ✅ [Benefit 2] | ||
| - ✅ [Benefit 3] | ||
| ### Cons of This Approach | ||
| - ❌ [Drawback 1] - [Why we accept this] | ||
| - ❌ [Drawback 2] - [Why we accept this] | ||
| ### Why Not Alternatives? | ||
| [Brief explanation of why other options were rejected] | ||
| ## Considered Options | ||
| ### Option 1: [Alternative Approach] | ||
| **Description:** [What this approach would involve] | ||
| **Pros:** | ||
| - [Pro 1] | ||
| - [Pro 2] | ||
| **Cons:** | ||
| - [Con 1] | ||
| - [Con 2] | ||
| **Verdict:** ❌ Rejected because [reason] | ||
| --- | ||
| ### Option 2: [Another Alternative] | ||
| **Description:** [What this approach would involve] | ||
| **Pros:** | ||
| - [Pro 1] | ||
| - [Pro 2] | ||
| **Cons:** | ||
| - [Con 1] | ||
| - [Con 2] | ||
| **Verdict:** ⚠️ Could work but [reason for not choosing] | ||
| --- | ||
| ### Option 3: [Chosen Approach] ✅ | ||
| **Description:** [What this approach involves] | ||
| **Pros:** | ||
| - [Pro 1] | ||
| - [Pro 2] | ||
| - [Pro 3] | ||
| **Cons:** | ||
| - [Con 1] - [Mitigation] | ||
| - [Con 2] - [Mitigation] | ||
| **Verdict:** ✅ **Selected** - Best balance of [trade-offs] | ||
| ## Implementation | ||
| ### Changes Required | ||
| 1. [Specific change 1] | ||
| 2. [Specific change 2] | ||
| 3. [Specific change 3] | ||
| ### Migration Path | ||
| [If replacing existing architecture, how will we migrate?] | ||
| - Step 1: [Migration step] | ||
| - Step 2: [Migration step] | ||
| - Step 3: [Migration step] | ||
| ### Testing Strategy | ||
| - [How to validate the decision] | ||
| - [What tests need to be added] | ||
| - [Performance benchmarks if applicable] | ||
| ### Rollback Plan | ||
| [If the decision doesn't work out, how can we revert?] | ||
| ## Consequences | ||
| ### Positive Consequences | ||
| - [Expected benefit 1] | ||
| - [Expected benefit 2] | ||
| - [Expected benefit 3] | ||
| ### Negative Consequences | ||
| - [Accepted trade-off 1] | ||
| - [Accepted trade-off 2] | ||
| ### Risks | ||
| | Risk | Probability | Impact | Mitigation | | ||
| |------|------------|--------|------------| | ||
| | [Risk 1] | Low/Med/High | Low/Med/High | [How to address] | | ||
| | [Risk 2] | Low/Med/High | Low/Med/High | [How to address] | | ||
| ## Follow-up Actions | ||
| - [ ] [Action item 1 with owner] | ||
| - [ ] [Action item 2 with owner] | ||
| - [ ] [Action item 3 with owner] | ||
| - [ ] Document implementation in [location] | ||
| - [ ] Update team wiki/docs | ||
| - [ ] Schedule review after [timeframe] | ||
| ## References | ||
| - [Link to relevant documentation] | ||
| - [Link to research/blog posts] | ||
| - [Link to similar decisions in other projects] | ||
| - [Links to code examples or prototypes] | ||
| ## Notes | ||
| [Any additional notes, concerns, or discussion points] | ||
| --- | ||
| **Review Date:** [When should this decision be reviewed?] | ||
| **Related ADRs:** [Links to related ADRs] | ||
| ``` | ||
| ## Example ADRs | ||
| ### Example 1: State Management | ||
| ```markdown | ||
| # ADR-005: Use Redux Toolkit for State Management | ||
| **Status:** Accepted | ||
| **Date:** 2025-12-23 | ||
| **Deciders:** Frontend Team Lead, Senior Developer | ||
| **Technical Story:** [Issue #234] | ||
| ## Context | ||
| Our React application has grown complex with multiple features sharing state. Component prop drilling is becoming unmaintainable, and we need a scalable state management solution. | ||
| ### Constraints | ||
| - Must integrate with existing React 18 app | ||
| - Team familiar with React hooks | ||
| - Bundle size concerns (already at 500KB) | ||
| - Need TypeScript support | ||
| ## Decision | ||
| We will use **Redux Toolkit** for global state management. | ||
| ## Rationale | ||
| Redux Toolkit provides: | ||
| - ✅ Official Redux recommendation with modern APIs | ||
| - ✅ Built-in TypeScript support | ||
| - ✅ Simplified boilerplate with createSlice | ||
| - ✅ DevTools integration for debugging | ||
| - ✅ Team has prior Redux experience | ||
| ## Considered Options | ||
| ### Option 1: Redux Toolkit ✅ | ||
| **Selected** - Best balance of power, familiarity, and tooling | ||
| ### Option 2: Zustand | ||
| - Simpler API | ||
| - ❌ Less mature ecosystem, smaller community | ||
| ### Option 3: Context + useReducer | ||
| - No dependencies | ||
| - ❌ Doesn't scale well, no middleware support | ||
| ### Option 4: MobX | ||
| - Reactive programming model | ||
| - ❌ Team unfamiliar, different mental model | ||
| ## Implementation | ||
| 1. Install: `npm install @reduxjs/toolkit react-redux` | ||
| 2. Create store configuration | ||
| 3. Migrate authentication state first (pilot) | ||
| 4. Gradually migrate other features | ||
| ## Consequences | ||
| **Positive:** | ||
| - Centralized state management | ||
| - Better debugging with DevTools | ||
| - Standardized patterns across features | ||
| **Negative:** | ||
| - Adds 45KB to bundle (acceptable given constraints) | ||
| - Learning curve for junior devs (mitigation: training session) | ||
| ``` | ||
| ### Example 2: Database Choice | ||
| ```markdown | ||
| # ADR-012: Use PostgreSQL Instead of MongoDB | ||
| **Status:** Accepted | ||
| **Date:** 2025-12-15 | ||
| **Deciders:** Backend Team, DBA, CTO | ||
| ## Context | ||
| Choosing primary database for new e-commerce platform handling: | ||
| - User accounts & profiles | ||
| - Product catalog (10,000+ SKUs) | ||
| - Orders & transactions (ACID required) | ||
| - Inventory tracking (strong consistency needed) | ||
| ## Decision | ||
| We will use **PostgreSQL** as our primary database. | ||
| ## Rationale | ||
| - ✅ ACID compliance for transactions | ||
| - ✅ Strong consistency for inventory | ||
| - ✅ Mature indexing and query optimization | ||
| - ✅ JSON support for flexible fields | ||
| - ✅ Excellent tooling ecosystem | ||
| ## Considered Options | ||
| ### Option 1: PostgreSQL ✅ | ||
| **Selected** - Best for transactional data with consistency requirements | ||
| ### Option 2: MongoDB | ||
| - ❌ Eventual consistency problematic for inventory | ||
| - ❌ Transaction support still maturing | ||
| ### Option 3: MySQL | ||
| - Similar to PostgreSQL | ||
| - ❌ Weaker JSON support, less extensible | ||
| ## Implementation | ||
| - Use PostgreSQL 15 | ||
| - Hosted on AWS RDS with Multi-AZ | ||
| - Connection pooling via PgBouncer | ||
| - Migrations managed with Flyway | ||
| ## Consequences | ||
| **Positive:** | ||
| - Reliable transactions | ||
| - Rich query capabilities | ||
| - Strong community support | ||
| **Negative:** | ||
| - Vertical scaling limits (mitigation: read replicas) | ||
| - More rigid schema (mitigation: JSONB columns for flexibility) | ||
| ``` | ||
| ## When to Create an ADR | ||
| Create an ADR when: | ||
| - Making architectural choices affecting multiple components | ||
| - Choosing between technologies/frameworks | ||
| - Changing core design patterns | ||
| - Making decisions with long-term impact | ||
| - Documenting why we DIDN'T do something (important!) | ||
| ## ADR Naming Convention | ||
| ``` | ||
| docs/adr/ | ||
| ├── 0001-record-architecture-decisions.md | ||
| ├── 0002-use-typescript-for-frontend.md | ||
| ├── 0003-adopt-clean-architecture.md | ||
| └── 0004-use-postgresql-for-database.md | ||
| ``` | ||
| ## Review Checklist | ||
| - [ ] Clear problem statement | ||
| - [ ] Multiple options considered | ||
| - [ ] Trade-offs explicitly stated | ||
| - [ ] Implementation plan defined | ||
| - [ ] Consequences documented | ||
| - [ ] Risks identified with mitigations | ||
| - [ ] References to supporting materials | ||
| - [ ] Follow-up actions assigned | ||
| Document an architectural decision. Load `adr` skill for the full methodology | ||
| (ADR template structure, naming conventions, when-to-create guidance, review checklist). | ||
| Scope: $ARGUMENTS |
@@ -8,231 +8,6 @@ --- | ||
| # Code Review Prompt | ||
| # Code Review | ||
| Review scope: $ARGUMENTS | ||
| Perform a thorough code review of the selected code or recent changes, focusing on security, performance, maintainability, and best practices. | ||
| ## Review Checklist | ||
| ### 1. Security | ||
| - [ ] **Input validation**: All inputs sanitized and validated | ||
| - [ ] **SQL injection**: Parameterized queries used | ||
| - [ ] **XSS prevention**: Output properly escaped | ||
| - [ ] **Authentication**: Proper auth checks before sensitive operations | ||
| - [ ] **Authorization**: Role/permission checks implemented | ||
| - [ ] **Secrets management**: No hardcoded credentials or API keys | ||
| - [ ] **HTTPS/TLS**: Secure connections enforced | ||
| - [ ] **CSRF protection**: Tokens used for state-changing operations | ||
| - [ ] **Rate limiting**: Protection against abuse | ||
| - [ ] **Error handling**: No sensitive info leaked in errors | ||
| ### 2. Performance | ||
| - [ ] **Database queries**: Optimized, indexed, no N+1 problems | ||
| - [ ] **Caching**: Appropriate caching strategy | ||
| - [ ] **Async operations**: Non-blocking I/O used where applicable | ||
| - [ ] **Memory management**: No leaks, proper resource cleanup | ||
| - [ ] **Algorithm efficiency**: Optimal time/space complexity | ||
| - [ ] **Bundle size**: Minimal dependencies, tree-shaking applied | ||
| - [ ] **Lazy loading**: Large resources loaded on-demand | ||
| ### 3. Code Quality | ||
| - [ ] **Naming**: Clear, descriptive variable/function names | ||
| - [ ] **Functions**: Small, single-responsibility functions | ||
| - [ ] **DRY**: No code duplication | ||
| - [ ] **Comments**: Complex logic explained, not obvious code | ||
| - [ ] **Error handling**: Comprehensive try-catch, proper error types | ||
| - [ ] **Type safety**: Strong typing used (TypeScript, C#, etc.) | ||
| - [ ] **Null safety**: Proper null/undefined checks | ||
| ### 4. Testing | ||
| - [ ] **Unit tests**: Critical logic covered | ||
| - [ ] **Integration tests**: API endpoints tested | ||
| - [ ] **Edge cases**: Boundary conditions tested | ||
| - [ ] **Error cases**: Failure scenarios tested | ||
| - [ ] **Test isolation**: No shared state between tests | ||
| - [ ] **Mock appropriately**: External dependencies mocked | ||
| ### 5. Architecture & Design | ||
| - [ ] **SOLID principles**: Followed appropriately | ||
| - [ ] **Separation of concerns**: Clear layer boundaries | ||
| - [ ] **Dependency injection**: Loose coupling maintained | ||
| - [ ] **Scalability**: Design supports growth | ||
| - [ ] **Maintainability**: Easy to understand and modify | ||
| ### 6. Language-Specific | ||
| #### .NET/C# | ||
| - [ ] Async/await with CancellationToken | ||
| - [ ] IDisposable implemented for resources | ||
| - [ ] Nullable reference types used correctly | ||
| - [ ] No blocking calls in async code | ||
| - [ ] EF Core queries optimized (AsNoTracking, projections) | ||
| #### Python | ||
| - [ ] Type hints on all functions | ||
| - [ ] Context managers for resources | ||
| - [ ] PEP 8 compliance | ||
| - [ ] No circular imports | ||
| - [ ] Virtual environment documented | ||
| #### TypeScript/JavaScript | ||
| - [ ] Strict mode enabled | ||
| - [ ] No `any` types without justification | ||
| - [ ] Proper async/await usage | ||
| - [ ] Event listeners cleaned up | ||
| - [ ] Memory leaks prevented (subscriptions, timers) | ||
| ### 7. Documentation | ||
| - [ ] **API docs**: Public APIs documented | ||
| - [ ] **README**: Setup instructions clear | ||
| - [ ] **Inline comments**: Complex logic explained | ||
| - [ ] **Change log**: Breaking changes noted | ||
| ## Review Format | ||
| ### Summary | ||
| [Brief overview of what was reviewed] | ||
| **Overall Assessment:** ✅ Approved / ⚠️ Needs Minor Changes / ❌ Needs Major Changes | ||
| --- | ||
| ### Critical Issues 🔴 | ||
| Issues that MUST be fixed before merge: | ||
| 1. **[Security/Performance/Bug]**: [Issue description] | ||
| - **Location:** `file.ts:123` | ||
| - **Impact:** [What could go wrong] | ||
| - **Fix:** [Recommended solution] | ||
| --- | ||
| ### Important Issues 🟡 | ||
| Should be addressed but not blocking: | ||
| 1. **[Code Quality/Maintainability]**: [Issue description] | ||
| - **Location:** `file.py:45` | ||
| - **Suggestion:** [Improvement recommendation] | ||
| --- | ||
| ### Suggestions 🟢 | ||
| Nice-to-have improvements: | ||
| 1. **[Optimization/Refactor]**: [Suggestion] | ||
| - **Location:** `file.cs:78` | ||
| - **Benefit:** [Why this would help] | ||
| --- | ||
| ### Positive Highlights ⭐ | ||
| Things done well: | ||
| - Good separation of concerns in service layer | ||
| - Comprehensive error handling | ||
| - Clear naming conventions | ||
| - Well-structured tests | ||
| --- | ||
| ## Example Issues | ||
| ### Critical: SQL Injection Vulnerability 🔴 | ||
| ```python | ||
| # ❌ Bad: String interpolation | ||
| query = f"SELECT * FROM users WHERE email = '{email}'" | ||
| cursor.execute(query) | ||
| # ✅ Good: Parameterized query | ||
| query = "SELECT * FROM users WHERE email = %s" | ||
| cursor.execute(query, (email,)) | ||
| ``` | ||
| ### Important: N+1 Query Problem 🟡 | ||
| ```csharp | ||
| // ❌ Bad: Loads related data in loop | ||
| foreach (var user in users) | ||
| { | ||
| var posts = await context.Posts.Where(p => p.UserId == user.Id).ToListAsync(); | ||
| } | ||
| // ✅ Good: Eager loading | ||
| var users = await context.Users | ||
| .Include(u => u.Posts) | ||
| .ToListAsync(); | ||
| ``` | ||
| ### Suggestion: Extract Duplicate Logic 🟢 | ||
| ```typescript | ||
| // ❌ Duplicated validation logic | ||
| if (!email || !email.includes('@')) throw new Error('Invalid email'); | ||
| // ... same check repeated elsewhere | ||
| // ✅ Extract to utility function | ||
| function validateEmail(email: string): void { | ||
| if (!email || !email.includes('@')) { | ||
| throw new Error('Invalid email'); | ||
| } | ||
| } | ||
| ``` | ||
| --- | ||
| ## Security-Specific Checks | ||
| ### Authentication | ||
| ```typescript | ||
| // ❌ Bad: No auth check | ||
| app.delete('/users/:id', async (req, res) => { | ||
| await deleteUser(req.params.id); | ||
| }); | ||
| // ✅ Good: Auth middleware | ||
| app.delete('/users/:id', authenticateUser, authorizeAdmin, async (req, res) => { | ||
| await deleteUser(req.params.id); | ||
| }); | ||
| ``` | ||
| ### Input Validation | ||
| ```python | ||
| # ❌ Bad: No validation | ||
| def create_user(age: int): | ||
| user = User(age=age) | ||
| # ✅ Good: Validate constraints | ||
| def create_user(age: int): | ||
| if age < 0 or age > 150: | ||
| raise ValueError("Invalid age") | ||
| user = User(age=age) | ||
| ``` | ||
| ### Error Handling | ||
| ```csharp | ||
| // ❌ Bad: Leaks implementation details | ||
| catch (Exception ex) | ||
| { | ||
| return StatusCode(500, ex.Message); // Could expose DB structure | ||
| } | ||
| // ✅ Good: Generic error message, log details | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogError(ex, "Failed to create user"); | ||
| return StatusCode(500, "An error occurred"); | ||
| } | ||
| ``` | ||
| --- | ||
| ## Final Checklist | ||
| Before approving: | ||
| - [ ] No critical security issues | ||
| - [ ] No major performance problems | ||
| - [ ] Tests pass and cover new code | ||
| - [ ] Documentation updated | ||
| - [ ] No breaking changes without migration plan | ||
| - [ ] Code follows project conventions | ||
| - [ ] Ready for production deployment | ||
| **Recommendation:** [Approve / Request Changes / Reject] | ||
| Review the code. Use the agent's built-in review methodology (security, performance, | ||
| best practices). For structured blast-radius analysis, load `code-change-impact`. | ||
| Scope: $ARGUMENTS |
@@ -8,424 +8,5 @@ --- | ||
| # Create README Prompt | ||
| # Create README | ||
| README scope: $ARGUMENTS | ||
| Generate a complete, professional README.md file for the project based on codebase analysis. | ||
| ## README Structure | ||
| ```markdown | ||
| # [Project Name] | ||
| [Project tagline or one-sentence description] | ||
| [](https://opensource.org/licenses/MIT) | ||
| [](https://github.com/shahboura/agents-opencode/actions) | ||
| ## Overview | ||
| [2-3 paragraph description of what the project does, who it's for, and why it exists] | ||
| **Key Features:** | ||
| - 🚀 Feature 1 - Brief description | ||
| - 🔒 Feature 2 - Brief description | ||
| - 📊 Feature 3 - Brief description | ||
| - ⚡ Feature 4 - Brief description | ||
| ## Table of Contents | ||
| - [Getting Started](#getting-started) | ||
| - [Installation](#installation) | ||
| - [Usage](#usage) | ||
| - [Configuration](#configuration) | ||
| - [API Reference](#api-reference) | ||
| - [Development](#development) | ||
| - [Testing](#testing) | ||
| - [Deployment](#deployment) | ||
| - [Contributing](#contributing) | ||
| - [License](#license) | ||
| ## Getting Started | ||
| ### Prerequisites | ||
| - [Tool/Language] version X.X or higher | ||
| - [Database] (optional, for full features) | ||
| - [Other dependencies] | ||
| ### Quick Start | ||
| ```bash | ||
| # Clone the repository | ||
| git clone https://github.com/shahboura/agents-opencode.git | ||
| cd project-name | ||
| # Install dependencies | ||
| npm install # or pip install -r requirements.txt, dotnet restore, etc. | ||
| # Set up environment | ||
| cp .env.example .env | ||
| # Edit .env with your configuration | ||
| # Run the application | ||
| npm start # or python main.py, dotnet run, etc. | ||
| ``` | ||
| Visit `http://localhost:3000` to see the application. | ||
| ## Installation | ||
| ### Option 1: Local Development | ||
| #### For Node.js Projects | ||
| ```bash | ||
| npm install | ||
| npm run build | ||
| npm start | ||
| ``` | ||
| #### For Python Projects | ||
| ```bash | ||
| python -m venv venv | ||
| source venv/bin/activate # On Windows: venv\Scripts\activate | ||
| pip install -r requirements.txt | ||
| python main.py | ||
| ``` | ||
| #### For .NET Projects | ||
| ```bash | ||
| dotnet restore | ||
| dotnet build | ||
| dotnet run --project src/WebAPI | ||
| ``` | ||
| ### Option 2: Docker | ||
| ```bash | ||
| docker build -t project-name . | ||
| docker run -p 3000:3000 project-name | ||
| ``` | ||
| ### Option 3: Using Docker Compose | ||
| ```bash | ||
| docker-compose up -d | ||
| ``` | ||
| ## Usage | ||
| ### Basic Example | ||
| ```typescript | ||
| import { ExampleClass } from 'project-name'; | ||
| const instance = new ExampleClass({ | ||
| option1: 'value1', | ||
| option2: 'value2' | ||
| }); | ||
| const result = await instance.doSomething(); | ||
| console.log(result); | ||
| ``` | ||
| ### Advanced Example | ||
| ```typescript | ||
| // More complex usage scenario | ||
| const advanced = new ExampleClass({ | ||
| option1: 'value1', | ||
| option2: 'value2', | ||
| advanced: { | ||
| feature1: true, | ||
| feature2: 'custom' | ||
| } | ||
| }); | ||
| // With custom configuration | ||
| advanced.configure({ | ||
| timeout: 5000, | ||
| retries: 3 | ||
| }); | ||
| const result = await advanced.processData({ | ||
| input: 'data', | ||
| format: 'json' | ||
| }); | ||
| ``` | ||
| ### CLI Usage (if applicable) | ||
| ```bash | ||
| # List all commands | ||
| project-name --help | ||
| # Run specific command | ||
| project-name command --option value | ||
| # Examples | ||
| project-name generate --type model --name User | ||
| project-name deploy --environment production | ||
| ``` | ||
| ## Configuration | ||
| Configuration via environment variables or `.env` file: | ||
| | Variable | Description | Default | Required | | ||
| |----------|-------------|---------|----------| | ||
| | `DATABASE_URL` | Database connection string | - | Yes | | ||
| | `API_KEY` | External API key | - | Yes | | ||
| | `PORT` | Server port | 3000 | No | | ||
| | `LOG_LEVEL` | Logging level | info | No | | ||
| | `REDIS_URL` | Redis connection (optional) | - | No | | ||
| **Example `.env` file:** | ||
| ```env | ||
| DATABASE_URL=postgresql://user:pass@localhost:5432/dbname | ||
| API_KEY=your_api_key_here | ||
| PORT=3000 | ||
| LOG_LEVEL=debug | ||
| ``` | ||
| ## API Reference | ||
| ### REST API Endpoints | ||
| #### `GET /api/resource` | ||
| Retrieve a list of resources. | ||
| **Query Parameters:** | ||
| - `page` (number): Page number | ||
| - `limit` (number): Items per page | ||
| **Response:** | ||
| ```json | ||
| { | ||
| "data": [...], | ||
| "meta": { | ||
| "total": 100, | ||
| "page": 1 | ||
| } | ||
| } | ||
| ``` | ||
| #### `POST /api/resource` | ||
| Create a new resource. | ||
| **Request Body:** | ||
| ```json | ||
| { | ||
| "name": "Resource Name", | ||
| "type": "example" | ||
| } | ||
| ``` | ||
| **Response:** `201 Created` | ||
| See full API documentation (add link to your docs site) | ||
| ## Development | ||
| ### Project Structure | ||
| ``` | ||
| project-name/ | ||
| ├── src/ | ||
| │ ├── controllers/ # Route handlers | ||
| │ ├── services/ # Business logic | ||
| │ ├── models/ # Data models | ||
| │ └── utils/ # Utility functions | ||
| ├── tests/ # Test files | ||
| ├── docs/ # Documentation | ||
| ├── .env.example # Environment template | ||
| └── README.md # This file | ||
| ``` | ||
| ### Running in Development Mode | ||
| ```bash | ||
| npm run dev # Node.js with hot reload | ||
| # or | ||
| dotnet watch run # .NET with hot reload | ||
| # or | ||
| python main.py --dev # Python with auto-reload | ||
| ``` | ||
| ### Code Style | ||
| This project uses: | ||
| - **Linting:** ESLint / Pylint / RuboCop | ||
| - **Formatting:** Prettier / Black / dotnet format | ||
| - **Pre-commit hooks:** Husky / pre-commit | ||
| Run checks: | ||
| ```bash | ||
| npm run lint # Lint code | ||
| npm run format # Format code | ||
| npm run type-check # Type checking | ||
| ``` | ||
| ## Testing | ||
| ### Run All Tests | ||
| ```bash | ||
| npm test # Node.js/TypeScript | ||
| pytest # Python | ||
| dotnet test # .NET | ||
| go test ./... # Go | ||
| ``` | ||
| ### Run with Coverage | ||
| ```bash | ||
| npm run test:coverage | ||
| # or | ||
| pytest --cov=src --cov-report=html | ||
| # or | ||
| dotnet test /p:CollectCoverage=true | ||
| ``` | ||
| ### Test Structure | ||
| ``` | ||
| tests/ | ||
| ├── unit/ # Unit tests | ||
| ├── integration/ # Integration tests | ||
| └── e2e/ # End-to-end tests | ||
| ``` | ||
| ## Deployment | ||
| ### Environment Setup | ||
| 1. Set production environment variables | ||
| 2. Build the application | ||
| 3. Run database migrations | ||
| 4. Start the server | ||
| ### Deploy to Cloud Platforms | ||
| #### Heroku | ||
| ```bash | ||
| heroku create app-name | ||
| git push heroku main | ||
| heroku run npm run migrate | ||
| ``` | ||
| #### AWS/Azure/GCP | ||
| See deployment guide (add link to your deployment docs) | ||
| #### Docker Production | ||
| ```bash | ||
| docker build -t project-name:latest . | ||
| docker run -d -p 80:3000 \ | ||
| -e DATABASE_URL=$DATABASE_URL \ | ||
| project-name:latest | ||
| ``` | ||
| ## Contributing | ||
| Contributions are welcome! Please follow these guidelines: | ||
| 1. Fork the repository | ||
| 2. Create a feature branch (`git checkout -b feature/amazing-feature`) | ||
| 3. Commit your changes (`git commit -m 'feat: add amazing feature'`) | ||
| 4. Push to the branch (`git push origin feature/amazing-feature`) | ||
| 5. Open a Pull Request | ||
| **Please ensure:** | ||
| - All tests pass | ||
| - Code is linted and formatted | ||
| - Documentation is updated | ||
| - Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) | ||
| <!-- Update these template links with actual project files --> | ||
| See CONTRIBUTING.md for detailed guidelines. | ||
| ## License | ||
| This project is licensed under the MIT License - see https://opensource.org/licenses/MIT for details. | ||
| ## Support | ||
| <!-- Update these template links with actual project documentation --> | ||
| - 📖 [Documentation](https://docs.example.com) | ||
| - 💬 [Discord Community](https://discord.gg/example) | ||
| - 🐛 [Issue Tracker](https://github.com/shahboura/agents-opencode/issues) | ||
| - 📧 Email: support@example.com | ||
| ## Acknowledgments | ||
| - Thanks to [contributor] for [contribution] | ||
| - Built with [tool/library] | ||
| - Inspired by [project] | ||
| --- | ||
| **Made with ❤️ by [Your Name/Organization]** | ||
| ``` | ||
| ## Content Guidelines | ||
| ### Overview Section | ||
| - Clear value proposition in first paragraph | ||
| - Explain the "why" - what problem does it solve? | ||
| - Target audience identification | ||
| - Key differentiators | ||
| ### Installation Section | ||
| - Multiple installation methods | ||
| - Platform-specific instructions (Windows, macOS, Linux) | ||
| - Common issues and troubleshooting | ||
| - Verification steps | ||
| ### Usage Section | ||
| - Start simple, then show advanced | ||
| - Real-world examples | ||
| - Common use cases | ||
| - Best practices | ||
| ### Configuration Section | ||
| - All environment variables documented | ||
| - Required vs optional clearly marked | ||
| - Security considerations noted | ||
| - Example configurations provided | ||
| ### API Reference | ||
| - Brief overview with link to detailed docs | ||
| - Most common endpoints documented | ||
| - Request/response examples | ||
| - Error handling | ||
| ### Development Section | ||
| - How to set up dev environment | ||
| - Code organization explained | ||
| - Development workflow | ||
| - Testing approach | ||
| ## Best Practices | ||
| 1. **Keep it scannable**: Use headers, lists, and tables | ||
| 2. **Show, don't just tell**: Include code examples | ||
| 3. **Be concise**: Link to detailed docs instead of dumping everything | ||
| 4. **Stay updated**: Include version info and last updated date | ||
| 5. **Be welcoming**: Friendly tone, assume no prior knowledge | ||
| 6. **Add badges**: Build status, coverage, version, license | ||
| 7. **Include visuals**: Screenshots, diagrams, GIFs of key features | ||
| ## Checklist | ||
| After generating README, verify: | ||
| - [ ] Clear project description | ||
| - [ ] Installation instructions work | ||
| - [ ] Usage examples run without errors | ||
| - [ ] All links are valid | ||
| - [ ] Configuration options documented | ||
| - [ ] Development setup explained | ||
| - [ ] Testing instructions included | ||
| - [ ] Contributing guidelines present | ||
| - [ ] License specified | ||
| - [ ] Contact/support information provided | ||
| Generate a README.md for the project. Load `project-bootstrap` skill for the | ||
| template structure and section best practices. Scope: $ARGUMENTS |
@@ -8,239 +8,5 @@ --- | ||
| # Generate Tests Prompt | ||
| # Generate Tests | ||
| Test target: $ARGUMENTS | ||
| Generate unit tests for the selected code following these guidelines: | ||
| ## 1. Test Framework Detection | ||
| Auto-detect based on project: | ||
| - **.NET**: Use xUnit + Moq + FluentAssertions | ||
| - **Python**: Use pytest + pytest-mock | ||
| - **TypeScript**: Use Jest or Vitest | ||
| - **Go**: Use standard testing package + testify | ||
| - **Generic**: Suggest appropriate framework | ||
| ## 2. Test Coverage Requirements | ||
| Generate tests for: | ||
| - ✅ Happy path scenarios | ||
| - ✅ Edge cases and boundary conditions | ||
| - ✅ Error handling and exceptions | ||
| - ✅ Null/undefined/empty inputs | ||
| - ✅ Integration points (mocked) | ||
| - ✅ Concurrent/async scenarios if applicable | ||
| ## 3. Test Structure | ||
| Use **Arrange-Act-Assert** pattern: | ||
| ``` | ||
| // Arrange: Set up test data and mocks | ||
| // Act: Execute the code under test | ||
| // Assert: Verify expected outcomes | ||
| ``` | ||
| **Best Practices:** | ||
| - Clear, descriptive test names (describe what's being tested) | ||
| - One logical assertion per test | ||
| - Proper setup and teardown | ||
| - Isolated tests (no shared state) | ||
| ## 4. Code Quality Standards | ||
| - Follow project naming conventions | ||
| - Add comments only for complex scenarios | ||
| - Group related tests in classes/describe blocks | ||
| - Maintain DRY in test setup (use fixtures/helpers) | ||
| - Fast execution (mock external I/O) | ||
| ## 5. Test Examples by Language | ||
| ### .NET (xUnit) | ||
| ```csharp | ||
| public class UserServiceTests | ||
| { | ||
| private readonly Mock<IUserRepository> _mockRepo; | ||
| private readonly UserService _sut; | ||
| public UserServiceTests() | ||
| { | ||
| _mockRepo = new Mock<IUserRepository>(); | ||
| _sut = new UserService(_mockRepo.Object); | ||
| } | ||
| [Fact] | ||
| public async Task GetUserAsync_ValidId_ReturnsUser() | ||
| { | ||
| // Arrange | ||
| var expected = new User { Id = 1, Email = "test@example.com" }; | ||
| _mockRepo.Setup(r => r.GetByIdAsync(1, default)) | ||
| .ReturnsAsync(expected); | ||
| // Act | ||
| var result = await _sut.GetUserAsync(1, default); | ||
| // Assert | ||
| result.Should().NotBeNull(); | ||
| result.Email.Should().Be(expected.Email); | ||
| } | ||
| [Fact] | ||
| public async Task GetUserAsync_InvalidId_ReturnsNull() | ||
| { | ||
| // Arrange | ||
| _mockRepo.Setup(r => r.GetByIdAsync(999, default)) | ||
| .ReturnsAsync((User)null); | ||
| // Act | ||
| var result = await _sut.GetUserAsync(999, default); | ||
| // Assert | ||
| result.Should().BeNull(); | ||
| } | ||
| } | ||
| ``` | ||
| ### Python (pytest) | ||
| ```python | ||
| import pytest | ||
| from unittest.mock import Mock, AsyncMock | ||
| @pytest.fixture | ||
| def user_service(mocker): | ||
| """Create user service with mocked dependencies.""" | ||
| mock_repo = mocker.Mock() | ||
| return UserService(repository=mock_repo) | ||
| def test_get_user_valid_id_returns_user(user_service): | ||
| """Test that get_user returns user for valid ID.""" | ||
| # Arrange | ||
| expected = User(id=1, email="test@example.com") | ||
| user_service.repository.get_by_id.return_value = expected | ||
| # Act | ||
| result = user_service.get_user(1) | ||
| # Assert | ||
| assert result is not None | ||
| assert result.email == expected.email | ||
| def test_get_user_invalid_id_returns_none(user_service): | ||
| """Test that get_user returns None for invalid ID.""" | ||
| # Arrange | ||
| user_service.repository.get_by_id.return_value = None | ||
| # Act | ||
| result = user_service.get_user(999) | ||
| # Assert | ||
| assert result is None | ||
| @pytest.mark.asyncio | ||
| async def test_fetch_user_async_success(user_service): | ||
| """Test async user fetch succeeds.""" | ||
| # Arrange | ||
| user_service.repository.fetch = AsyncMock(return_value={"id": 1}) | ||
| # Act | ||
| result = await user_service.fetch_user(1) | ||
| # Assert | ||
| assert result["id"] == 1 | ||
| ``` | ||
| ### TypeScript (Jest/Vitest) | ||
| ```typescript | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
| import { UserService } from './UserService'; | ||
| import type { UserRepository } from './UserRepository'; | ||
| describe('UserService', () => { | ||
| let userService: UserService; | ||
| let mockRepo: jest.Mocked<UserRepository>; | ||
| beforeEach(() => { | ||
| mockRepo = { | ||
| getById: vi.fn(), | ||
| create: vi.fn(), | ||
| } as jest.Mocked<UserRepository>; | ||
| userService = new UserService(mockRepo); | ||
| }); | ||
| it('should return user for valid ID', async () => { | ||
| // Arrange | ||
| const expected = { id: 1, email: 'test@example.com' }; | ||
| mockRepo.getById.mockResolvedValue(expected); | ||
| // Act | ||
| const result = await userService.getUser(1); | ||
| // Assert | ||
| expect(result).toEqual(expected); | ||
| expect(mockRepo.getById).toHaveBeenCalledWith(1); | ||
| }); | ||
| it('should return null for invalid ID', async () => { | ||
| // Arrange | ||
| mockRepo.getById.mockResolvedValue(null); | ||
| // Act | ||
| const result = await userService.getUser(999); | ||
| // Assert | ||
| expect(result).toBeNull(); | ||
| }); | ||
| }); | ||
| ``` | ||
| ## 6. After Test Generation | ||
| 1. **Run tests** to verify they pass | ||
| 2. **Report coverage** percentage if tooling available | ||
| 3. **Suggest additional scenarios** not covered | ||
| 4. **Identify flaky tests** (timing, ordering dependencies) | ||
| ## 7. Common Test Patterns | ||
| ### Testing Error Handling | ||
| ```typescript | ||
| it('should throw error for invalid input', () => { | ||
| expect(() => service.process(null)).toThrow('Invalid input'); | ||
| }); | ||
| ``` | ||
| ### Testing Async Operations | ||
| ```python | ||
| @pytest.mark.asyncio | ||
| async def test_concurrent_requests(): | ||
| results = await asyncio.gather( | ||
| service.fetch(1), | ||
| service.fetch(2) | ||
| ) | ||
| assert len(results) == 2 | ||
| ``` | ||
| ### Parameterized Tests | ||
| ```csharp | ||
| [Theory] | ||
| [InlineData(0, false)] | ||
| [InlineData(1, true)] | ||
| [InlineData(100, true)] | ||
| public void IsPositive_ReturnsExpected(int input, bool expected) | ||
| { | ||
| var result = MathHelper.IsPositive(input); | ||
| result.Should().Be(expected); | ||
| } | ||
| ``` | ||
| ## Output Checklist | ||
| After generating tests, confirm: | ||
| - [ ] All public methods have test coverage | ||
| - [ ] Edge cases identified and tested | ||
| - [ ] Error paths tested | ||
| - [ ] Mocks properly configured | ||
| - [ ] Tests are isolated and repeatable | ||
| - [ ] Test names clearly describe what's tested | ||
| - [ ] All tests pass when run | ||
| Generate unit tests. Detect the project profile and use the agent's profile-based | ||
| test framework (pytest, jest, go test, dotnet test, etc.). Scope: $ARGUMENTS |
@@ -8,453 +8,6 @@ --- | ||
| # Refactoring Plan Prompt | ||
| # Refactoring Plan | ||
| Refactor target: $ARGUMENTS | ||
| Create a comprehensive refactoring plan that improves code quality, maintainability, and performance while preserving existing behavior. | ||
| ## Step 1: Identify Refactoring Goals | ||
| What needs improvement: | ||
| - [ ] **Code duplication** - Extract common logic | ||
| - [ ] **Complex functions** - Break into smaller pieces | ||
| - [ ] **Poor naming** - Improve clarity | ||
| - [ ] **Tight coupling** - Introduce abstractions | ||
| - [ ] **Missing tests** - Add test coverage | ||
| - [ ] **Performance** - Optimize hot paths | ||
| - [ ] **Technical debt** - Address known issues | ||
| - [ ] **Design patterns** - Apply appropriate patterns | ||
| ## Step 2: Analyze Current State | ||
| ### Code Smells Detected | ||
| 1. **Long Methods/Functions** | ||
| - [Function name]: [Line count] lines, [complexity score] | ||
| - Does too much: [list responsibilities] | ||
| 2. **Duplicate Code** | ||
| - Pattern: [Description of repeated code] | ||
| - Locations: [file1:line], [file2:line], [file3:line] | ||
| 3. **Large Classes** | ||
| - [Class name]: [methods/properties count] | ||
| - Responsibilities: [list of mixed concerns] | ||
| 4. **Feature Envy** | ||
| - [Class A] heavily uses methods from [Class B] | ||
| - Suggests: Move logic closer to data | ||
| 5. **Primitive Obsession** | ||
| - Using primitives instead of domain objects | ||
| - Example: Email as string vs Email value object | ||
| 6. **Switch/If-Else Chains** | ||
| - [Location]: Large conditional logic | ||
| - Better as: Strategy pattern or polymorphism | ||
| ## Step 3: Create Refactoring Plan | ||
| ```markdown | ||
| # Refactoring Plan: [Area/Feature Name] | ||
| ## Overview | ||
| [What we're refactoring and why] | ||
| ## Current Problems | ||
| 1. [Problem 1 with impact] | ||
| 2. [Problem 2 with impact] | ||
| 3. [Problem 3 with impact] | ||
| ## Goals | ||
| - [ ] Reduce complexity (Cyclomatic complexity < 10) | ||
| - [ ] Eliminate code duplication | ||
| - [ ] Improve testability | ||
| - [ ] Better separation of concerns | ||
| - [ ] Maintain backward compatibility | ||
| ## Risk Assessment | ||
| **Risk Level:** Low / Medium / High | ||
| - Breaking changes: [Yes/No - Details] | ||
| - Test coverage: [Current %] → [Target %] | ||
| - Deployment risk: [Assessment] | ||
| --- | ||
| ## Refactoring Steps | ||
| ### Phase 1: Preparation (Safety First) | ||
| **Goal:** Ensure safe refactoring with tests | ||
| #### Step 1: Add Missing Tests | ||
| **Why:** Prevent regressions during refactoring | ||
| **Tasks:** | ||
| - [ ] Add unit tests for [Function A] | ||
| - [ ] Add integration tests for [Feature B] | ||
| - [ ] Achieve 80%+ code coverage on target area | ||
| **Estimated time:** 2-3 days | ||
| --- | ||
| ### Phase 2: Extract & Simplify | ||
| **Goal:** Break down complex code into manageable pieces | ||
| #### Step 2: Extract Helper Functions | ||
| **Before:** | ||
| ```typescript | ||
| function processOrder(order: Order) { | ||
| // 200 lines of code doing everything | ||
| // validation, calculation, persistence, notification | ||
| } | ||
| ``` | ||
| **After:** | ||
| ```typescript | ||
| function processOrder(order: Order) { | ||
| validateOrder(order); | ||
| const total = calculateTotal(order); | ||
| saveOrder(order); | ||
| notifyCustomer(order); | ||
| } | ||
| function validateOrder(order: Order) { /* ... */ } | ||
| function calculateTotal(order: Order): number { /* ... */ } | ||
| function saveOrder(order: Order): void { /* ... */ } | ||
| function notifyCustomer(order: Order): void { /* ... */ } | ||
| ``` | ||
| **Benefits:** | ||
| - ✅ Each function has single responsibility | ||
| - ✅ Easier to test individually | ||
| - ✅ More readable and maintainable | ||
| **Tasks:** | ||
| - [ ] Extract validation logic | ||
| - [ ] Extract calculation logic | ||
| - [ ] Extract persistence logic | ||
| - [ ] Extract notification logic | ||
| - [ ] Update tests | ||
| **Estimated time:** 1 day | ||
| --- | ||
| #### Step 3: Eliminate Code Duplication | ||
| **Duplicate pattern found in:** | ||
| - `services/userService.ts:45` | ||
| - `services/adminService.ts:78` | ||
| - `services/guestService.ts:123` | ||
| **Solution:** Extract to shared utility | ||
| **Before:** | ||
| ```typescript | ||
| // Repeated in 3 places | ||
| const email = input.trim().toLowerCase(); | ||
| if (!email.includes('@') || email.length < 5) { | ||
| throw new Error('Invalid email'); | ||
| } | ||
| ``` | ||
| **After:** | ||
| ```typescript | ||
| // Shared utility | ||
| function validateEmail(email: string): string { | ||
| const normalized = email.trim().toLowerCase(); | ||
| if (!normalized.includes('@') || normalized.length < 5) { | ||
| throw new Error('Invalid email'); | ||
| } | ||
| return normalized; | ||
| } | ||
| // Usage | ||
| const email = validateEmail(input); | ||
| ``` | ||
| **Tasks:** | ||
| - [ ] Create `src/utils/validation.ts` | ||
| - [ ] Extract email validation | ||
| - [ ] Update all 3 call sites | ||
| - [ ] Add tests for utility | ||
| **Estimated time:** 0.5 days | ||
| --- | ||
| ### Phase 3: Improve Architecture | ||
| **Goal:** Better separation of concerns and testability | ||
| #### Step 4: Introduce Service Layer | ||
| **Current:** Controllers directly access database | ||
| **Target:** Controllers → Services → Repositories | ||
| **Changes:** | ||
| ``` | ||
| Before: | ||
| ├── controllers/ | ||
| │ └── userController.ts (200 lines, does everything) | ||
| After: | ||
| ├── controllers/ | ||
| │ └── userController.ts (50 lines, route handling only) | ||
| ├── services/ | ||
| │ └── userService.ts (business logic) | ||
| └── repositories/ | ||
| └── userRepository.ts (data access) | ||
| ``` | ||
| **Tasks:** | ||
| - [ ] Create `UserService` class | ||
| - [ ] Move business logic from controller | ||
| - [ ] Create `UserRepository` interface | ||
| - [ ] Implement repository | ||
| - [ ] Update controller to use service | ||
| - [ ] Add service tests | ||
| - [ ] Add repository tests | ||
| **Estimated time:** 2 days | ||
| --- | ||
| #### Step 5: Apply Strategy Pattern | ||
| **Problem:** Large switch statement for payment processing | ||
| **Before:** | ||
| ```typescript | ||
| function processPayment(type: string, amount: number) { | ||
| switch(type) { | ||
| case 'credit': /* 50 lines */ break; | ||
| case 'debit': /* 50 lines */ break; | ||
| case 'paypal': /* 50 lines */ break; | ||
| // 5 more cases... | ||
| } | ||
| } | ||
| ``` | ||
| **After:** | ||
| ```typescript | ||
| interface PaymentStrategy { | ||
| process(amount: number): Promise<PaymentResult>; | ||
| } | ||
| class CreditCardPayment implements PaymentStrategy { /* ... */ } | ||
| class DebitCardPayment implements PaymentStrategy { /* ... */ } | ||
| class PayPalPayment implements PaymentStrategy { /* ... */ } | ||
| const strategies = { | ||
| credit: new CreditCardPayment(), | ||
| debit: new DebitCardPayment(), | ||
| paypal: new PayPalPayment(), | ||
| }; | ||
| function processPayment(type: string, amount: number) { | ||
| const strategy = strategies[type]; | ||
| return strategy.process(amount); | ||
| } | ||
| ``` | ||
| **Benefits:** | ||
| - ✅ Open/Closed principle - easy to add new payment types | ||
| - ✅ Each strategy isolated and testable | ||
| - ✅ Eliminates conditional complexity | ||
| **Tasks:** | ||
| - [ ] Create `PaymentStrategy` interface | ||
| - [ ] Implement concrete strategies | ||
| - [ ] Refactor processPayment | ||
| - [ ] Add tests for each strategy | ||
| - [ ] Update documentation | ||
| **Estimated time:** 3 days | ||
| --- | ||
| ### Phase 4: Performance Optimization | ||
| **Goal:** Improve performance without changing behavior | ||
| #### Step 6: Optimize Database Queries | ||
| **Problem:** N+1 query problem | ||
| **Before:** | ||
| ```typescript | ||
| const users = await db.query('SELECT * FROM users'); | ||
| for (const user of users) { | ||
| user.posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]); | ||
| } | ||
| ``` | ||
| **After:** | ||
| ```typescript | ||
| const users = await db.query(` | ||
| SELECT u.*, p.* | ||
| FROM users u | ||
| LEFT JOIN posts p ON p.user_id = u.id | ||
| `); | ||
| // Map results to user objects with posts | ||
| ``` | ||
| **Expected improvement:** 100ms → 10ms for 100 users | ||
| **Tasks:** | ||
| - [ ] Identify N+1 queries | ||
| - [ ] Add eager loading | ||
| - [ ] Add database indexes | ||
| - [ ] Benchmark before/after | ||
| - [ ] Update documentation | ||
| **Estimated time:** 1 day | ||
| --- | ||
| ### Phase 5: Final Cleanup | ||
| **Goal:** Polish and document | ||
| #### Step 7: Improve Naming | ||
| - Rename ambiguous variables | ||
| - Use domain language consistently | ||
| - Remove abbreviations | ||
| #### Step 8: Add Documentation | ||
| - [ ] Update README with new architecture | ||
| - [ ] Add JSDoc/XML comments to public APIs | ||
| - [ ] Create architecture diagram | ||
| - [ ] Document design decisions (ADR) | ||
| **Estimated time:** 1 day | ||
| --- | ||
| ## Testing Strategy | ||
| ### During Refactoring | ||
| 1. Run tests after each small change | ||
| 2. Use git commits as checkpoints | ||
| 3. Never commit failing tests | ||
| ### Validation | ||
| - [ ] All existing tests pass | ||
| - [ ] New tests for refactored code | ||
| - [ ] Integration tests still pass | ||
| - [ ] Performance benchmarks meet targets | ||
| - [ ] No regressions in functionality | ||
| ### Test Coverage Goals | ||
| - Before: [Current %] | ||
| - After: [Target %] (minimum 80%) | ||
| --- | ||
| ## Rollout Plan | ||
| ### Step 1: Refactor in Feature Branch | ||
| ```bash | ||
| git checkout -b refactor/user-service | ||
| # Make changes | ||
| git push origin refactor/user-service | ||
| ``` | ||
| ### Step 2: Code Review | ||
| - Request review from 2+ team members | ||
| - Address feedback | ||
| - Ensure all checks pass | ||
| ### Step 3: Gradual Rollout | ||
| - Deploy to staging | ||
| - Run smoke tests | ||
| - Monitor for issues | ||
| - Deploy to production with feature flag | ||
| - Gradually increase traffic | ||
| - Monitor metrics | ||
| ### Step 4: Cleanup | ||
| - Remove old code paths | ||
| - Update documentation | ||
| - Share learnings with team | ||
| --- | ||
| ## Success Criteria | ||
| After refactoring: | ||
| - [ ] All tests pass (100%) | ||
| - [ ] Code coverage ≥ 80% | ||
| - [ ] Cyclomatic complexity < 10 per function | ||
| - [ ] No code duplication | ||
| - [ ] Performance improved or maintained | ||
| - [ ] Documentation updated | ||
| - [ ] Team reviewed and approved | ||
| --- | ||
| ## Risks & Mitigations | ||
| | Risk | Impact | Mitigation | | ||
| |------|--------|------------| | ||
| | Breaking changes | High | Comprehensive test suite first | | ||
| | Performance regression | Medium | Benchmark before/after | | ||
| | Merge conflicts | Low | Frequent rebasing, small PRs | | ||
| | Extended timeline | Medium | Break into smaller phases | | ||
| --- | ||
| ## Estimated Timeline | ||
| | Phase | Duration | Dependencies | | ||
| |-------|----------|--------------| | ||
| | Phase 1: Preparation | 2-3 days | None | | ||
| | Phase 2: Extract & Simplify | 2 days | Phase 1 | | ||
| | Phase 3: Architecture | 5 days | Phase 2 | | ||
| | Phase 4: Performance | 1 day | Phase 3 | | ||
| | Phase 5: Cleanup | 1 day | Phase 4 | | ||
| | **Total** | **11-12 days** | | | ||
| --- | ||
| ## Follow-up Actions | ||
| After refactoring: | ||
| - [ ] Schedule retrospective | ||
| - [ ] Document patterns for team | ||
| - [ ] Identify other areas needing refactoring | ||
| - [ ] Update coding standards | ||
| - [ ] Share lessons learned | ||
| ``` | ||
| ## Refactoring Principles | ||
| 1. **Preserve Behavior:** Functionality stays the same | ||
| 2. **Small Steps:** Make tiny, verifiable changes | ||
| 3. **Test First:** Ensure tests exist before refactoring | ||
| 4. **Commit Often:** Each small change is a commit | ||
| 5. **Review Code:** Get feedback early and often | ||
| ## Common Refactoring Patterns | ||
| ### Extract Method | ||
| Break large functions into smaller ones | ||
| ### Extract Class | ||
| Move related methods to new class | ||
| ### Rename | ||
| Improve clarity of names | ||
| ### Introduce Parameter Object | ||
| Group related parameters | ||
| ### Replace Conditional with Polymorphism | ||
| Use strategy/factory patterns | ||
| ### Simplify Conditional | ||
| Reduce nested if-else | ||
| ## Checklist Before Starting | ||
| - [ ] Team agreement on goals | ||
| - [ ] Adequate test coverage | ||
| - [ ] Time allocated in sprint | ||
| - [ ] Backup/rollback plan ready | ||
| - [ ] Stakeholders informed | ||
| Create a refactoring plan. Load `refactoring` skill for the full methodology | ||
| (5-phase plan, code smell detection, common patterns, rollout strategy). | ||
| Scope: $ARGUMENTS |
@@ -8,507 +8,6 @@ --- | ||
| # Security Audit Prompt | ||
| # Security Audit | ||
| Audit scope: $ARGUMENTS | ||
| Conduct a thorough security review of the codebase, infrastructure, and deployment practices to identify vulnerabilities and security risks. | ||
| ## Audit Scope | ||
| ### Areas to Review | ||
| - [ ] **Authentication & Authorization** | ||
| - [ ] **Input Validation & Sanitization** | ||
| - [ ] **Data Protection & Encryption** | ||
| - [ ] **API Security** | ||
| - [ ] **Dependency Vulnerabilities** | ||
| - [ ] **Infrastructure Security** | ||
| - [ ] **Secret Management** | ||
| - [ ] **Logging & Monitoring** | ||
| --- | ||
| ## Security Checklist | ||
| ### 1. Authentication & Authorization | ||
| #### Authentication | ||
| - [ ] Passwords hashed with strong algorithm (bcrypt, Argon2) | ||
| - [ ] Multi-factor authentication (MFA) available | ||
| - [ ] Session management secure (httpOnly, secure, sameSite cookies) | ||
| - [ ] Password requirements enforced (length, complexity) | ||
| - [ ] Account lockout after failed attempts | ||
| - [ ] JWT tokens properly validated and signed | ||
| - [ ] Token expiration implemented | ||
| - [ ] Refresh token rotation | ||
| **Common Vulnerabilities:** | ||
| ```typescript | ||
| // ❌ Bad: Weak password hashing | ||
| const hash = md5(password); // MD5 is broken | ||
| // ✅ Good: Strong password hashing | ||
| import bcrypt from 'bcrypt'; | ||
| const hash = await bcrypt.hash(password, 12); | ||
| // ❌ Bad: JWT without expiration | ||
| const token = jwt.sign({ userId }, SECRET); | ||
| // ✅ Good: JWT with expiration | ||
| const token = jwt.sign({ userId }, SECRET, { expiresIn: '15m' }); | ||
| ``` | ||
| #### Authorization | ||
| - [ ] Role-based access control (RBAC) implemented | ||
| - [ ] Principle of least privilege applied | ||
| - [ ] Authorization checked on every request | ||
| - [ ] Resource ownership verified | ||
| - [ ] No insecure direct object references (IDOR) | ||
| - [ ] Horizontal privilege escalation prevented | ||
| - [ ] Vertical privilege escalation prevented | ||
| **IDOR Example:** | ||
| ```typescript | ||
| // ❌ Bad: No ownership check | ||
| app.get('/api/orders/:id', async (req, res) => { | ||
| const order = await db.orders.findById(req.params.id); | ||
| res.json(order); // Any user can access any order! | ||
| }); | ||
| // ✅ Good: Verify ownership | ||
| app.get('/api/orders/:id', authenticateUser, async (req, res) => { | ||
| const order = await db.orders.findById(req.params.id); | ||
| if (order.userId !== req.user.id && req.user.role !== 'admin') { | ||
| return res.status(403).json({ error: 'Forbidden' }); | ||
| } | ||
| res.json(order); | ||
| }); | ||
| ``` | ||
| --- | ||
| ### 2. Input Validation & Injection Prevention | ||
| #### SQL Injection | ||
| - [ ] Parameterized queries used (no string concatenation) | ||
| - [ ] ORM used correctly (avoid raw queries) | ||
| - [ ] Stored procedures parameterized | ||
| - [ ] Input validation on all user data | ||
| **Examples:** | ||
| ```python | ||
| # ❌ Bad: SQL Injection vulnerability | ||
| query = f"SELECT * FROM users WHERE email = '{email}'" | ||
| cursor.execute(query) | ||
| # ✅ Good: Parameterized query | ||
| query = "SELECT * FROM users WHERE email = %s" | ||
| cursor.execute(query, (email,)) | ||
| # ❌ Bad: ORM with string interpolation | ||
| User.objects.raw(f"SELECT * FROM users WHERE name = '{name}'") | ||
| # ✅ Good: ORM with parameters | ||
| User.objects.filter(name=name) | ||
| ``` | ||
| #### XSS (Cross-Site Scripting) | ||
| - [ ] Output encoding/escaping implemented | ||
| - [ ] Content-Security-Policy header set | ||
| - [ ] User input sanitized before display | ||
| - [ ] React/Vue auto-escaping utilized | ||
| - [ ] Dangerous methods avoided (innerHTML, dangerouslySetInnerHTML) | ||
| ```typescript | ||
| // ❌ Bad: XSS vulnerability | ||
| element.innerHTML = userInput; | ||
| // ✅ Good: Safe text insertion | ||
| element.textContent = userInput; | ||
| // ❌ Bad: React XSS | ||
| <div dangerouslySetInnerHTML={{ __html: userInput }} /> | ||
| // ✅ Good: React auto-escapes | ||
| <div>{userInput}</div> | ||
| ``` | ||
| #### Command Injection | ||
| - [ ] No shell commands with user input | ||
| - [ ] If required, use safe APIs (child_process.execFile, not exec) | ||
| - [ ] Input validated against allowlist | ||
| ```javascript | ||
| // ❌ Bad: Command injection | ||
| exec(`rm -rf ${userInput}`); | ||
| // ✅ Good: Use safe APIs with validation | ||
| import { execFile } from 'child_process'; | ||
| const allowedCommands = ['backup', 'restore']; | ||
| if (allowedCommands.includes(command)) { | ||
| execFile('safe-script.sh', [command]); | ||
| } | ||
| ``` | ||
| #### Path Traversal | ||
| - [ ] File paths validated | ||
| - [ ] Relative paths blocked (../) | ||
| - [ ] Files served from restricted directory | ||
| ```python | ||
| # ❌ Bad: Path traversal | ||
| filename = request.args.get('file') | ||
| with open(f'/uploads/{filename}') as f: | ||
| return f.read() | ||
| # ✅ Good: Validate and sanitize | ||
| import os | ||
| filename = os.path.basename(request.args.get('file')) | ||
| safe_path = os.path.join('/uploads', filename) | ||
| if safe_path.startswith('/uploads/'): | ||
| with open(safe_path) as f: | ||
| return f.read() | ||
| ``` | ||
| --- | ||
| ### 3. Data Protection & Encryption | ||
| #### Data at Rest | ||
| - [ ] Sensitive data encrypted (PII, PCI data) | ||
| - [ ] Encryption keys properly managed | ||
| - [ ] Database encryption enabled | ||
| - [ ] File system encryption (where applicable) | ||
| - [ ] Backups encrypted | ||
| #### Data in Transit | ||
| - [ ] HTTPS/TLS enforced everywhere | ||
| - [ ] TLS 1.2+ required (TLS 1.0/1.1 disabled) | ||
| - [ ] Strong cipher suites configured | ||
| - [ ] Certificate validation enabled | ||
| - [ ] HSTS header set | ||
| ```nginx | ||
| # Nginx HTTPS configuration | ||
| ssl_protocols TLSv1.2 TLSv1.3; | ||
| ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; | ||
| ssl_prefer_server_ciphers on; | ||
| add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; | ||
| ``` | ||
| #### Sensitive Data Handling | ||
| - [ ] No sensitive data in logs | ||
| - [ ] No sensitive data in URLs/query params | ||
| - [ ] Credit cards handled per PCI-DSS | ||
| - [ ] Personal data complies with GDPR/CCPA | ||
| - [ ] Secrets not committed to git | ||
| ```typescript | ||
| // ❌ Bad: Logging sensitive data | ||
| logger.info('User login', { email, password }); | ||
| // ✅ Good: Sanitized logging | ||
| logger.info('User login', { email }); | ||
| // ❌ Bad: Sensitive data in URL | ||
| fetch(`/api/reset-password?token=${resetToken}`); | ||
| // ✅ Good: Sensitive data in body/header | ||
| fetch('/api/reset-password', { | ||
| method: 'POST', | ||
| headers: { 'Authorization': `Bearer ${resetToken}` } | ||
| }); | ||
| ``` | ||
| --- | ||
| ### 4. API Security | ||
| - [ ] Rate limiting implemented | ||
| - [ ] CORS configured (not wildcard *) | ||
| - [ ] API keys rotated regularly | ||
| - [ ] Versioned APIs (backward compatibility) | ||
| - [ ] Request size limits enforced | ||
| - [ ] GraphQL query depth limiting | ||
| - [ ] REST pagination enforced | ||
| ```typescript | ||
| // Rate limiting | ||
| import rateLimit from 'express-rate-limit'; | ||
| const limiter = rateLimit({ | ||
| windowMs: 15 * 60 * 1000, // 15 minutes | ||
| max: 100, // limit each IP to 100 requests per windowMs | ||
| message: 'Too many requests' | ||
| }); | ||
| app.use('/api/', limiter); | ||
| // CORS configuration | ||
| app.use(cors({ | ||
| origin: ['https://example.com', 'https://app.example.com'], | ||
| credentials: true | ||
| })); | ||
| // Request size limits | ||
| app.use(express.json({ limit: '10kb' })); | ||
| ``` | ||
| --- | ||
| ### 5. Dependency Vulnerabilities | ||
| - [ ] Dependencies up to date | ||
| - [ ] No known vulnerabilities (npm audit, pip check) | ||
| - [ ] Automated dependency scanning (Dependabot, Snyk) | ||
| - [ ] Unused dependencies removed | ||
| - [ ] Licenses reviewed | ||
| **Run Security Audits:** | ||
| ```bash | ||
| # Node.js | ||
| npm audit | ||
| npm audit fix | ||
| # Python | ||
| pip-audit | ||
| safety check | ||
| # .NET | ||
| dotnet list package --vulnerable | ||
| # Go | ||
| go list -json -m all | nancy sleuth | ||
| ``` | ||
| --- | ||
| ### 6. Infrastructure Security | ||
| #### Server Configuration | ||
| - [ ] Firewall configured (only required ports open) | ||
| - [ ] SSH key-based auth (passwords disabled) | ||
| - [ ] Root login disabled | ||
| - [ ] Automatic security updates enabled | ||
| - [ ] Unnecessary services disabled | ||
| - [ ] File permissions restrictive | ||
| #### Container Security | ||
| - [ ] Base images from trusted sources | ||
| - [ ] Images scanned for vulnerabilities | ||
| - [ ] Non-root user in containers | ||
| - [ ] Secrets not in images | ||
| - [ ] Minimal image size (fewer attack surfaces) | ||
| ```dockerfile | ||
| # ❌ Bad: Running as root | ||
| FROM node:18 | ||
| COPY . /app | ||
| CMD ["node", "server.js"] | ||
| # ✅ Good: Non-root user | ||
| FROM node:18 | ||
| RUN groupadd -r appuser && useradd -r -g appuser appuser | ||
| COPY --chown=appuser:appuser . /app | ||
| USER appuser | ||
| CMD ["node", "server.js"] | ||
| ``` | ||
| #### Cloud Security | ||
| - [ ] IAM roles with least privilege | ||
| - [ ] Security groups restrictive | ||
| - [ ] Encryption at rest enabled (S3, RDS, etc.) | ||
| - [ ] VPC configured properly | ||
| - [ ] CloudTrail/audit logging enabled | ||
| - [ ] Multi-factor auth on cloud accounts | ||
| --- | ||
| ### 7. Secret Management | ||
| - [ ] No secrets in code or config files | ||
| - [ ] Environment variables used | ||
| - [ ] Secret management service (Vault, AWS Secrets Manager) | ||
| - [ ] Secrets rotated regularly | ||
| - [ ] Git history cleaned of secrets | ||
| - [ ] .env files in .gitignore | ||
| **Check for leaked secrets:** | ||
| ```bash | ||
| # Scan git history for secrets | ||
| trufflehog git file://. --only-verified | ||
| # Scan for common patterns | ||
| git grep -E 'password.*=.*["|'\''].*["|'\'']' | ||
| git grep -E 'api[_-]?key.*=.*["|'\''].*["|'\'']' | ||
| ``` | ||
| ```typescript | ||
| // ❌ Bad: Hardcoded secrets | ||
| const apiKey = 'sk_live_abc123xyz'; | ||
| // ✅ Good: Environment variables | ||
| const apiKey = process.env.API_KEY; | ||
| if (!apiKey) { | ||
| throw new Error('API_KEY not configured'); | ||
| } | ||
| ``` | ||
| --- | ||
| ### 8. Logging & Monitoring | ||
| - [ ] Security events logged (failed logins, permission denials) | ||
| - [ ] Logs centralized and monitored | ||
| - [ ] Anomaly detection configured | ||
| - [ ] Alerts for suspicious activity | ||
| - [ ] Log retention policy defined | ||
| - [ ] Logs don't contain sensitive data | ||
| ```typescript | ||
| // Security event logging | ||
| logger.warn('Failed login attempt', { | ||
| email: email, | ||
| ip: req.ip, | ||
| timestamp: new Date(), | ||
| userAgent: req.headers['user-agent'] | ||
| }); | ||
| // Monitoring alerts | ||
| if (failedLoginCount > 5) { | ||
| alerting.notify('Possible brute force attack', { | ||
| ip: req.ip, | ||
| attempts: failedLoginCount | ||
| }); | ||
| } | ||
| ``` | ||
| --- | ||
| ## Security Headers | ||
| Ensure these headers are set: | ||
| ```javascript | ||
| app.use((req, res, next) => { | ||
| // Prevent clickjacking | ||
| res.setHeader('X-Frame-Options', 'DENY'); | ||
| // XSS protection | ||
| res.setHeader('X-Content-Type-Options', 'nosniff'); | ||
| // CSP | ||
| res.setHeader('Content-Security-Policy', "default-src 'self'"); | ||
| // HSTS | ||
| res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); | ||
| // Referrer policy | ||
| res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); | ||
| next(); | ||
| }); | ||
| ``` | ||
| --- | ||
| ## Security Audit Report Template | ||
| ```markdown | ||
| # Security Audit Report | ||
| **Date:** YYYY-MM-DD | ||
| **Auditor:** [Name] | ||
| **Scope:** [What was audited] | ||
| ## Executive Summary | ||
| [High-level findings and risk assessment] | ||
| **Overall Risk Level:** 🔴 High / 🟡 Medium / 🟢 Low | ||
| ## Critical Issues 🔴 | ||
| ### 1. [Issue Title] | ||
| **Severity:** Critical | ||
| **Category:** [Authentication/Authorization/Injection/etc.] | ||
| **Location:** `file.ts:123` | ||
| **Description:** [What's wrong] | ||
| **Impact:** [What could happen] | ||
| **Reproduction:** | ||
| 1. Step 1 | ||
| 2. Step 2 | ||
| 3. Exploit occurs | ||
| **Recommendation:** [How to fix] | ||
| **Priority:** Fix immediately | ||
| --- | ||
| ## High Priority Issues 🟡 | ||
| [Similar format] | ||
| --- | ||
| ## Medium Priority Issues 🟠 | ||
| [Similar format] | ||
| --- | ||
| ## Low Priority / Recommendations 🟢 | ||
| [Similar format] | ||
| --- | ||
| ## Compliance | ||
| - [ ] GDPR compliant | ||
| - [ ] PCI-DSS compliant (if handling cards) | ||
| - [ ] HIPAA compliant (if handling health data) | ||
| - [ ] SOC 2 requirements met | ||
| --- | ||
| ## Action Items | ||
| | Issue | Priority | Owner | Due Date | Status | | ||
| |-------|----------|-------|----------|--------| | ||
| | Fix SQL injection | Critical | Dev Team | YYYY-MM-DD | 🔴 Open | | ||
| | Add rate limiting | High | Backend | YYYY-MM-DD | 🟡 In Progress | | ||
| | Update dependencies | Medium | DevOps | YYYY-MM-DD | 🟢 Completed | | ||
| --- | ||
| ## Next Steps | ||
| 1. Address all critical issues immediately | ||
| 2. Schedule fixes for high priority items | ||
| 3. Re-audit after fixes applied | ||
| 4. Implement continuous security monitoring | ||
| --- | ||
| **Next Audit Date:** [Schedule follow-up] | ||
| ``` | ||
| ## Automated Security Tools | ||
| Integrate these tools: | ||
| - **SAST:** SonarQube, Semgrep, Checkmarx | ||
| - **DAST:** OWASP ZAP, Burp Suite | ||
| - **Dependency Scanning:** Snyk, Dependabot | ||
| - **Secret Scanning:** TruffleHog, GitGuardian | ||
| - **Container Scanning:** Trivy, Clair | ||
| ## Checklist Summary | ||
| After audit, verify: | ||
| - [ ] All critical vulnerabilities documented | ||
| - [ ] Action items assigned with deadlines | ||
| - [ ] Compliance requirements reviewed | ||
| - [ ] Security improvements prioritized | ||
| - [ ] Re-audit scheduled | ||
| Run a comprehensive security audit. Load `security-audit` skill for the full methodology | ||
| (audit checklist across 8 areas, report template, automated tool recommendations). | ||
| Scope: $ARGUMENTS |
@@ -16,10 +16,4 @@ --- | ||
| public class UserService { | ||
| private final UserRepository userRepository; | ||
| private final PasswordEncoder passwordEncoder; | ||
| public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { | ||
| this.userRepository = userRepository; | ||
| this.passwordEncoder = passwordEncoder; | ||
| } | ||
| public UserService(UserRepository userRepository) { this.userRepository = userRepository; } | ||
| } | ||
@@ -31,7 +25,4 @@ ``` | ||
| ```java | ||
| // ❌ Bad | ||
| @Autowired | ||
| private UserRepository userRepository; | ||
| // ✅ Good - Constructor injection | ||
| // ❌ Bad: @Autowired private UserRepository repo; | ||
| // ✅ Good: constructor injection (above) | ||
| ``` | ||
@@ -42,20 +33,7 @@ | ||
| ```java | ||
| @Entity | ||
| @Table(name = "users") | ||
| @Entity @Table(name = "users") | ||
| public class User { | ||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
| @Column(nullable = false, unique = true) | ||
| private String email; | ||
| @Column(nullable = false) | ||
| private String password; | ||
| @CreationTimestamp | ||
| private LocalDateTime createdAt; | ||
| // Constructors, getters, setters | ||
| @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; | ||
| @Column(nullable = false, unique = true) private String email; | ||
| @CreationTimestamp private LocalDateTime createdAt; | ||
| } | ||
@@ -114,21 +92,11 @@ ``` | ||
| public class GlobalExceptionHandler { | ||
| @ExceptionHandler(UserNotFoundException.class) | ||
| public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) { | ||
| return ResponseEntity.status(HttpStatus.NOT_FOUND) | ||
| .body(new ErrorResponse("User not found", ex.getMessage())); | ||
| public ResponseEntity<ErrorResponse> handleNotFound(UserNotFoundException ex) { | ||
| return ResponseEntity.status(NOT_FOUND).body(new ErrorResponse("Not found", ex.getMessage())); | ||
| } | ||
| @ExceptionHandler(MethodArgumentNotValidException.class) | ||
| public ResponseEntity<ErrorResponse> handleValidationErrors(MethodArgumentNotValidException ex) { | ||
| Map<String, String> errors = ex.getBindingResult() | ||
| .getFieldErrors() | ||
| .stream() | ||
| .collect(Collectors.toMap( | ||
| FieldError::getField, | ||
| FieldError::getDefaultMessage | ||
| )); | ||
| return ResponseEntity.badRequest() | ||
| .body(new ErrorResponse("Validation failed", errors)); | ||
| public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) { | ||
| var errors = ex.getBindingResult().getFieldErrors().stream() | ||
| .collect(toMap(FieldError::getField, FieldError::getDefaultMessage)); | ||
| return ResponseEntity.badRequest().body(new ErrorResponse("Validation failed", errors)); | ||
| } | ||
@@ -135,0 +103,0 @@ } |
@@ -38,46 +38,17 @@ --- | ||
| **@codebase** - Use for: | ||
| - Feature implementation | ||
| - Bug fixes | ||
| - Code refactoring | ||
| - Test creation | ||
| **@codebase** — Feature implementation, bug fixes, refactoring, test creation. Use for cross-domain or unfamiliar-stack work (multi-language validation, auto-detection). For single-file/single-domain changes, orchestrator may implement directly — see Implementation Routing in the orchestrator agent. | ||
| **@docs** - Use for: | ||
| - README updates | ||
| - API documentation | ||
| - Architecture docs | ||
| - User guides | ||
| **@docs** — README updates, API documentation, architecture docs, user guides. | ||
| **@review** - Use for: | ||
| - Security audits | ||
| - Performance reviews | ||
| - Code quality checks | ||
| - Best practices validation | ||
| **@review** — Security audits, performance reviews, code quality checks, best practices validation. | ||
| **@planner** - Use for: | ||
| - Read-only codebase analysis | ||
| - Detailed implementation planning | ||
| - Risk assessment before implementation | ||
| **@planner** — Read-only codebase analysis, detailed implementation planning, risk assessment before implementation. | ||
| **@em-advisor** - Use for: | ||
| - Engineering leadership guidance | ||
| - Stakeholder communication strategy | ||
| - Team execution and prioritization support | ||
| **@em-advisor** — Engineering leadership guidance, stakeholder communication, team execution and prioritization. | ||
| **@blogger** - Use for: | ||
| - Blog post creation | ||
| - YouTube script writing | ||
| - Podcast outline brainstorming | ||
| **@blogger** — Blog post creation, YouTube scripts, podcast outlines. | ||
| **@brutal-critic** - Use for: | ||
| - Content quality reviews | ||
| - Framework-based scoring | ||
| - Pre-publish validation | ||
| **@brutal-critic** — Content quality reviews, framework-based scoring, pre-publish validation. | ||
| **@legal-advisor** - Use for: | ||
| - Legal research across jurisdictions | ||
| - Regulatory compliance analysis | ||
| - License auditing and open-source compliance | ||
| - Data privacy and export control review | ||
| - Contract and agreement evaluation | ||
| **@legal-advisor** — Legal research, regulatory compliance, license auditing, data privacy, export control, contract evaluation. | ||
@@ -84,0 +55,0 @@ ## Coordination Patterns |
@@ -16,3 +16,3 @@ import type { Plugin } from "@opencode-ai/plugin"; | ||
| level: "info", | ||
| message: `Agents Opencode v${PACKAGE_VERSION} loaded — 9 agents, 19 skills, 14 commands available`, | ||
| message: `Agents Opencode v${PACKAGE_VERSION} loaded — 9 agents, 23 skills, 16 commands available`, | ||
| }, | ||
@@ -42,4 +42,4 @@ }); | ||
| Active skills: 19 language/domain/utility skill packs loadable via skill tool. | ||
| Active commands: 14 slash commands (type / to see autocomplete). | ||
| Active skills: 23 language/domain/utility skill packs loadable via skill tool. | ||
| Active commands: 16 slash commands (type / to see autocomplete). | ||
@@ -46,0 +46,0 @@ Memory: state/session-state.json and handoff/latest.md preserve working state. |
@@ -18,10 +18,13 @@ --- | ||
| A fix is "done" only when you know what it touched *besides* the thing you were | ||
| fixing. This skill traces reverse dependencies, hunts silent behavioral ripples, | ||
| runs the project's own verification commands, and delivers a verdict. | ||
| ## What I do | ||
| - Trace reverse dependencies from a changed symbol to every caller, importer, and consumer | ||
| - Hunt silent behavioral ripples the compiler can't catch | ||
| - Run the project's own typecheck, build, test, and lint to prove nothing broke | ||
| - Deliver a structured verdict: SAFE, SAFE WITH CAVEATS, or IMPACT FOUND | ||
| Run it against the VCS diff — it adapts to whatever language and tooling the | ||
| repo uses by discovering the project's conventions first. | ||
| ## When to Activate | ||
| ## When to use me | ||
@@ -162,2 +165,14 @@ Activate this skill when: | ||
| ## Validation Commands | ||
| ```bash | ||
| # Manual verification checklist — no automated validation | ||
| # [ ] Coupling class assigned to every changed file | ||
| # [ ] Reverse-dependency grep run for each changed symbol | ||
| # [ ] Four silent-risk categories checked against impacted sites | ||
| # [ ] Typecheck + build + targeted tests pass | ||
| # [ ] Verdict matches evidence (SAFE / SAFE WITH CAVEATS / IMPACT FOUND) | ||
| # [ ] Residual checklist populated if anything unverifiable | ||
| ``` | ||
| ## Quick Reference | ||
@@ -164,0 +179,0 @@ |
| --- | ||
| name: project-bootstrap | ||
| description: Create baseline OpenCode project context and AGENTS.md scaffold | ||
| description: Create baseline OpenCode project context, AGENTS.md scaffold, and README.md | ||
| license: MIT | ||
@@ -15,2 +15,3 @@ compatibility: opencode | ||
| - Create a minimal `AGENTS.md` if missing | ||
| - Generate a structured `README.md` for new or existing projects | ||
| - Add a short project context template | ||
@@ -20,13 +21,55 @@ - Explain how to update context over time | ||
| ## When to use me | ||
| Use this when starting a new project or when `AGENTS.md` is missing. | ||
| Use this when starting a new project or when `AGENTS.md` or `README.md` is missing. | ||
| Ask clarifying questions about tech stack and standards before writing. | ||
| ## Key Rules | ||
| ### AGENTS.md | ||
| - Keep the template short and practical | ||
| - Prefer bullet points over long paragraphs | ||
| - Include a brief "Milestones" section placeholder | ||
| - Include these standard sections: | ||
| - **Project Structure** — `.opencode/`, `docs/`, key directories | ||
| - **Language & Domain Skills** — available skill list | ||
| - **Agent Usage** — primary agents and subagents | ||
| - **Quality Requirements** — lint, test, typecheck standards | ||
| - **Context Persistence Format** — canonical milestone entry template (see below) | ||
| - **Milestones** — placeholder for timestamped entries | ||
| - Ask about tech stack and conventions before generating content | ||
| - Do not add language-specific rules; those belong in skills | ||
| - Respect repository scope decisions (if policy is core-only, do not suggest optional skill packs by default) | ||
| - Context Persistence Format template: | ||
| ``` | ||
| ### YYYY-MM-DD HH:MM - [Brief Task Description] | ||
| **Agent:** [agent-name] | ||
| **Summary:** [What was done] | ||
| - Key decisions, files changed, patterns used | ||
| - Lessons learned for future sessions | ||
| Format: date to minute precision, latest first (prepend), 3-5 bullets max, | ||
| skip trivial edits, auto-prunes at 100KB. | ||
| ``` | ||
| ### README Creation | ||
| Include these standard sections where applicable: | ||
| **Overview** — Clear value proposition in first paragraph, target audience, key differentiators. | ||
| **Getting Started** — Prerequisites, quick-start commands, verification steps. | ||
| **Installation** — Multiple methods (local dev, Docker, platform-specific), common issues. | ||
| **Usage** — Start simple, then show advanced; real-world examples; common use cases. | ||
| **Configuration** — All env vars documented; required vs optional marked; security considerations. | ||
| **API Reference** — Most common endpoints with request/response examples; link to full docs. | ||
| **Development** — Dev environment setup, code organization, workflow, testing approach. | ||
| **Testing** — How to run tests, coverage targets, test structure (unit/integration/e2e). | ||
| **Deployment** — Environment setup, build steps, platform guides (Heroku, Docker, cloud). | ||
| **Contributing** — Branch naming, commit conventions, PR process, code standards. | ||
| **License** — SPDX identifier and link. | ||
| **Support** — Documentation link, community channel, issue tracker, contact info. | ||
| Best practices: | ||
| - Keep it scannable with headers, lists, and tables | ||
| - Show, don't just tell — include real code examples | ||
| - Be concise — link to detailed docs instead of dumping everything | ||
| - Add badges (build status, coverage, version, license) | ||
| - Be welcoming — assume no prior knowledge, use a friendly tone | ||
| ## Validation Commands | ||
@@ -37,2 +80,6 @@ ```bash | ||
| # [ ] Structure matches repository conventions | ||
| # [ ] README.md has clear project description | ||
| # [ ] Installation instructions are tested and verifiable | ||
| # [ ] All links are valid | ||
| # [ ] License and support/contact info present | ||
| ``` |
+1
-1
| { | ||
| "name": "agents-opencode", | ||
| "version": "2.2.0", | ||
| "version": "2.3.0", | ||
| "description": "OpenCode Agents: Intelligent AI assistants for software development. Features 9 specialized agents (including legal-advisor for license auditing and compliance), 14 coding standards, automated code review, documentation generation, OpenCode plugin compatibility, and cross-platform installation. Supports .NET, Python, TypeScript, Flutter, Go, Java, Node.js, React, Ruby, and Rust with plan-first execution and context-aware assistance.", | ||
@@ -5,0 +5,0 @@ "files": [ |
106
3.92%318365
-11.27%