Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:41:39 +08:00
commit 2652dfae0d
18 changed files with 5608 additions and 0 deletions

242
commands/approve.md Normal file
View File

@@ -0,0 +1,242 @@
---
name: approve
description: Review and approve important code changes (API, schema, security) before automatic commit. Critical decision point for quality assurance.
model: claude-opus-4-1
---
# Approve Command
**Command Type**: Critical Decision Point
**When to Use**: Review and approve important changes before commit
## Purpose
The `/approve` command is used for manual review of important changes, especially API changes, schema modifications, major refactoring, and other changes requiring explicit approval.
## When to Use
### Required Use Cases for /approve:
1. **API Changes**
- Add/modify public API endpoints
- Change API request/response schemas
- API version upgrades
2. **Database Schema Changes**
- Add/modify table schemas
- Database migration scripts
- Index changes
3. **Major Refactoring**
- Architecture pattern changes
- Core module rewrites
- Major dependency version upgrades
4. **Security Changes**
- Authentication/authorization mechanism modifications
- Password handling logic changes
- Security configuration adjustments
5. **Performance-Critical Changes**
- Cache strategy changes
- Database query optimizations
- Load balancing configuration
### Cases Where /approve is NOT Required:
- Minor bug fixes
- Code comment updates
- Unit test additions
- Documentation updates
- Style adjustments
## Usage
```bash
# Basic usage
/approve
# System will display changes awaiting review
# You need to:
# 1. Review change details
# 2. Decide to approve or reject
# 3. (Optional) Provide review comments
```
## Workflow Integration
### Trigger Point
`@agent-reviewer` automatically prompts for manual review when important changes are detected:
```markdown
🔍 Important Change Detected
**Change Type**: API Schema Modification
**Impact Scope**: POST /auth/login
Manual review required, please run: /approve
```
### Review Process
```mermaid
graph LR
A[@agent-coder<br/>Complete Implementation] --> B[@agent-reviewer<br/>Automatic Review]
B --> C{Important<br/>Change<br/>Detected?}
C -->|Yes| D[🛑 Pause]
C -->|No| F[✅ Auto Commit]
D --> E[/approve<br/>Manual Review]
E --> G{Approved?}
G -->|Approved| H[@agent-reviewer<br/>Complete Commit]
G -->|Rejected| I[@agent-coder<br/>Modify]
I --> B
```
### Review Options
After running `/approve`, you'll see:
```markdown
## Changes Awaiting Review
**Task**: LIN-123 - User Authentication API
**Change Type**: API Schema Modification
### Change Summary
**Modified Files**:
- src/routes/auth.routes.ts
- src/schemas/auth.schema.ts
- docs/api/auth.openapi.yaml
**API Changes**:
```diff
POST /auth/login
- Request: { email, password }
+ Request: { email, password, deviceId }
- Response: { accessToken, refreshToken }
+ Response: { accessToken, refreshToken, sessionId }
```
**Impact Analysis**:
- Breaking Change: ❌ No (backward compatible)
- Frontend Adjustment Needed: ✅ Yes (add deviceId field)
- Documentation Update Needed: ✅ Yes (completed)
---
**Options**:
A) ✅ Approve and commit
B) ❌ Reject with feedback
C) 🔍 View detailed diff
D) 📝 Add review notes and approve
Please select (A/B/C/D):
```
## Response Examples
### Option A: Approve and Commit
```markdown
✅ Changes Approved
@agent-reviewer will execute the following operations:
1. Mark review as passed
2. Create git commit
3. Update task status
Commit message:
feat(LIN-123): add device tracking to auth API
- Add deviceId to login request
- Return sessionId in login response
- Update API documentation
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Reviewed-By: [Your Name]
```
### Option B: Reject with Feedback
```markdown
❌ Changes Rejected
**Review Feedback**:
The deviceId field should be optional, not mandatory.
Suggested schema adjustment:
```typescript
{
email: string;
password: string;
deviceId?: string; // optional
}
```
Task has been marked for modification, @agent-coder will be notified.
```
### Option C: View Detailed Diff
Displays complete git diff output
### Option D: Add Review Notes and Approve
```markdown
**Review Notes**:
API changes confirmed, but note:
1. Frontend team needs to synchronize updates
2. Legacy mobile app may need backward compatibility handling
3. Recommend notifying users to upgrade in next sprint
Please enter additional review notes (press Enter to complete):
> [Your notes here]
✅ Approved with review notes recorded
```
## Integration with Agent Workspace
Review records are written to the agent workspace:
```javascript
// Approval record written to .agents/tasks/LIN-123/approve.md
const approvalRecord = {
approved_at: new Date().toISOString(),
approved_by: 'human',
change_type: 'api_schema',
decision: 'approved',
notes: 'Confirmed with frontend team, backward compatible'
};
task.writeAgentOutput('approve', JSON.stringify(approvalRecord, null, 2));
```
## Best Practices
1. **Carefully Review Impact Analysis**: Confirm if breaking changes exist
2. **Verify Test Coverage**: Important changes must have comprehensive tests
3. **Check Documentation Sync**: API changes must update documentation
4. **Consider Backward Compatibility**: Assess impact on existing clients
5. **Document Review Feedback**: Leave review records for future reference
## Key Constraints
- **Only Human**: This command is for human use only, agents cannot execute it
- **Blocking**: Task will pause until review is complete
- **Required for Critical Changes**: Important changes must go through this process
- **Audit Trail**: All review records are preserved
## References
- @~/.claude/workflow.md - Complete workflow
- @~/.claude/agents/reviewer.md - Reviewer agent
- @~/.claude/CLAUDE.md - Global configuration

195
commands/git-commit.md Normal file
View File

@@ -0,0 +1,195 @@
---
name: git-commit
description: Manual git commit creation for emergency situations. Creates conventional commit messages with proper attribution.
model: claude-haiku-4-5
---
# Git Commit Mode
Switch to Git Commit mode for automated git commit creation with conventional commit message format.
## Description
In Git Commit mode, I function as an automated git commit manager that analyzes current changes, generates appropriate conventional commit messages following commitizen (git-cz) format without emojis, and ensures all pre-commit hooks pass successfully.
## Core Responsibilities
- **Change Analysis**: Analyze all staged and unstaged changes in the current repository
- **Conventional Commit Messages**: Generate commit messages following the conventional commits specification
- **Pre-commit Hook Handling**: Ensure all pre-commit hooks pass and handle any automatic changes
- **Commit History Review**: Review recent commit history to maintain consistency with project's commit style
- **Staging Management**: Properly stage relevant files before committing
## Key Constraints
- **Conventional Commits Only**: All commit messages must follow `<type>[optional scope]: <description>` format
- **No Emojis**: Do not include emojis in commit messages (unlike some git-cz configurations)
- **Pre-commit Compliance**: Must ensure all pre-commit hooks pass before finalizing commits
- **No Force Operations**: Never use force push or force commit operations
- **Staged Changes Focus**: Only commit staged changes unless explicitly instructed otherwise
## Communication Style
- **Tone**: Direct, factual, version-control-oriented communication
- **Approach**: Systematic analysis of changes with clear commit rationale
## Conventional Commit Types
- **feat**: A new feature
- **fix**: A bug fix
- **docs**: Documentation only changes
- **style**: Changes that do not affect the meaning of the code (white-space, formatting, etc)
- **refactor**: A code change that neither fixes a bug nor adds a feature
- **perf**: A code change that improves performance
- **test**: Adding missing tests or correcting existing tests
- **build**: Changes that affect the build system or external dependencies
- **ci**: Changes to CI configuration files and scripts
- **chore**: Other changes that don't modify src or test files
- **revert**: Reverts a previous commit
## Git Commit Process
### 1. Change Analysis Phase
```bash
# Check current git status
git status
# View diff content
git diff
git diff --staged
# Review recent commit history to understand project commit style
git log --oneline -10
```
### 2. Pre-processing Phase
- [ ] Identify all untracked files
- [ ] Analyze modified but unstaged changes
- [ ] Check staged changes
- [ ] Confirm no sensitive information should be committed
### 3. Message Generation Phase
- [ ] Select appropriate conventional commit type based on change type
- [ ] Determine optional scope based on change range
- [ ] Write concise and clear description
- [ ] Ensure message follows project commit style
### 4. Commit Execution Phase
```bash
# Stage relevant files
git add [files]
# Create commit (using HEREDOC to ensure proper formatting)
git commit -m "$(cat <<'EOF'
<type>[optional scope]: <description>
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
# Check commit status
git status
```
### 5. Pre-commit Handling
- [ ] If pre-commit hook fails, analyze failure reason
- [ ] If formatting or auto-correction, re-commit including these changes
- [ ] Retry at most once, report to user if still failing
## Example Usage
**Input:**
```
/git-commit
User: Please create a commit for the current changes.
```
**Response:**
```
Current Mode: Git Commit (Automated Git Commit Management)
## Analyzing Current Change Status
Checking git status and change content...
**Git Status Summary:**
- 3 files modified: src/auth/token.service.ts, tests/auth/token.test.ts, README.md
- 1 new file: src/auth/types.ts
- 0 files staged
**Change Analysis:**
1. `src/auth/token.service.ts`: Add JWT token generation and validation functionality
2. `tests/auth/token.test.ts`: Add unit tests for token service
3. `src/auth/types.ts`: Add authentication-related type definitions
4. `README.md`: Update project description, add authentication module documentation
**Recent Commit Style:**
- `feat(auth): implement user login endpoint`
- `fix(db): resolve connection timeout issue`
- `docs: update API documentation`
## Generate Conventional Commit Message
**Suggested commit type:** `feat`
**Suggested scope:** `auth`
**Suggested description:** `implement JWT token service with validation`
## Execute Git Commit
Staging relevant files and creating commit...
```bash
git add src/auth/token.service.ts src/auth/types.ts tests/auth/token.test.ts README.md
```
Creating commit...
```bash
git commit -m "$(cat <<'EOF'
feat(auth): implement JWT token service with validation
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
EOF
)"
```
## Pre-commit Hook Check
✅ Pre-commit hooks executed successfully
✅ Code formatting check passed
✅ Tests executed successfully
✅ Linting check passed
## Commit Result
✅ Commit created successfully: `feat(auth): implement JWT token service with validation`
✅ File changes recorded: 4 files
✅ Working directory status: clean
Commit complete! Current branch updated.
```
**Pre-commit Hook Failure Example:**
```
⚠️ Pre-commit Hook Failed
Detected that pre-commit hook made automatic corrections to files:
- src/auth/token.service.ts: Code formatting adjustments
- tests/auth/token.test.ts: Import ordering adjustments
Recreating commit to include these automatic corrections...
✅ Retry commit successful: `feat(auth): implement JWT token service with validation`
All pre-commit checks now passed.
```
## Error Handling
If any of the following situations occur, user will be notified:
- Git repository does not exist
- No changes to commit
- Pre-commit hook consecutive failures
- Sensitive information detection warning
- Git operation permission issues

613
commands/help.md Normal file
View File

@@ -0,0 +1,613 @@
---
name: help
description: Comprehensive guide to Agent-First workflow including all 9 agents, 6 commands, best practices, and workflow examples
model: claude-haiku-4-5
---
# Agent-First Workflow - Complete Guide
## 🎯 Quick Overview
The **Agent-First Workflow** is a collaborative development system where:
- **Humans** make critical decisions via 2 commands (`/po`, `/techlead`)
- **Agents** autonomously execute complex work
- **Quality** is built-in with automated code review and git commits
## 📊 Workflow Diagram
```
/po (Define Requirements)
/techlead (Architecture Decisions)
@agent-planner (Task Breakdown + PRD)
@agent-coder (TDD Implementation)
@agent-reviewer (Code Review + Auto Commit)
@agent-pm (Project Management)
@agent-retro (Retrospective Analysis)
```
**Error Path**:
- `@agent-debugger` → diagnoses issues → hands off to `@agent-coder`
**Optimization Path**:
- `@agent-optimizer` → optimizes code → hands off to `@agent-reviewer`
---
## 🚀 Getting Started (3 Steps)
### Step 1: Initialize Agent Workspace
In your project root, run:
```bash
/init-agents
```
This creates:
- `.agents/` directory structure
- Task management configuration (Linear/GitHub/Jira/Local)
- Helper library and state definitions
### Step 2: Define Your Requirements
```bash
/po "Your feature description"
```
Example:
```bash
/po "Implement user authentication with JWT and refresh tokens"
```
**You decide**:
- Feature scope and acceptance criteria
- Priority and timeline
- Success metrics
### Step 3: Architecture Decisions (Optional but Recommended)
```bash
/techlead
```
**You decide**:
- Technology stack
- Architecture patterns
- Integration points
- Risk assessment
**Result**: Everything else happens automatically!
---
## 🎮 Commands (Critical Decision Points)
### `/po` - Product Owner
**When**: Project start or new feature planning
**Input**: Feature description and requirements
**Output**: Automatically triggers task breakdown
Example:
```bash
/po "Implement OAuth2 social login integration"
```
### `/techlead` - Technology Decisions
**When**: Major architectural or technology changes
**Input**: Tech stack and architecture preferences
**Output**: Architecture-informed task planning
### `/approve` - Review Important Changes
**When**: API changes, schema modifications, security updates
**Input**: Review and approve/reject changes
**Output**: Automatic commit after approval
### `/git-commit` - Manual Commit (Emergency)
**When**: Manual intervention needed
**Input**: Commit message
**Output**: Direct git commit
### `/init-agents` - Initialize Workspace
**When**: New project setup
**Execution**: Sets up complete agent infrastructure
---
## 🤖 Agents (Autonomous Execution)
### 1. @agent-planner
**Role**: Task Breakdown & PRD Generation
**Trigger**: After `/po` and `/techlead` commands
**Output**: Detailed PRD with task breakdown
**Handoff**: → `@agent-coder`
**Responsibilities**:
- Analyze requirements
- Create detailed PRD (Product Requirements Document)
- Break down into subtasks
- Estimate complexity (Fibonacci scale)
**Sample Output** (planner.md):
```markdown
# PRD: User Authentication
## Requirements
- JWT token generation
- Refresh token mechanism
- Rate limiting
## Task Breakdown
- [ ] Token service (3 points)
- [ ] Auth middleware (2 points)
- [ ] Rate limiting (2 points)
- [ ] Tests (1 point)
Total Complexity: 8 points
```
### 2. @agent-coder
**Role**: TDD Implementation
**Trigger**: After planner completes
**Output**: Tested, working code
**Handoff**: → `@agent-reviewer`
**Responsibilities**:
- Write tests first (TDD approach)
- Implement features
- Ensure tests pass
- Document code inline
**Best For**:
- Feature implementation
- Bug fixes
- Refactoring
**Sample Output** (coder.md):
```markdown
# Implementation Progress
## Completed Tasks
- ✅ Token service (2500 tokens)
- ✅ Auth middleware (1800 tokens)
- ✅ All tests passing
## Remaining
- [ ] Integration tests
Total tokens used: 4300
```
### 3. @agent-reviewer
**Role**: Code Quality Review + Git Commit Authority
**Trigger**: After coder completes
**Output**: Approved code with commit
**Handoff**: → `@agent-pm`
**Responsibilities**:
- Review code quality
- Verify test coverage
- Check documentation
- **Auto commit** approved code
- Enforce coding standards
**Approval Criteria**:
- All tests passing
- Code quality standards met
- Documentation complete
- Security review passed
### 4. @agent-debugger
**Role**: Error Diagnosis & Troubleshooting
**Trigger**: Manual call when issues arise
**Output**: Identified root cause & fix
**Handoff**: → `@agent-coder`
**Responsibilities**:
- Diagnose errors systematically
- Identify root causes
- Suggest fixes
- Prevent recurring issues
**Usage**:
```bash
@agent-debugger "Fix login 500 error"
# → Diagnoses issue
# → Hands to @agent-coder for fix
# → @agent-reviewer reviews
# → Auto commit
```
### 5. @agent-optimizer
**Role**: Performance Optimization
**Trigger**: Manual call for performance improvements
**Output**: Optimized code
**Handoff**: → `@agent-reviewer`
**Responsibilities**:
- Identify performance bottlenecks
- Optimize algorithms
- Reduce resource usage
- Maintain functionality
**Optimization Targets**:
- Response time
- Memory usage
- Database queries
- Code complexity
### 6. @agent-doc
**Role**: Documentation Generation
**Trigger**: After code is reviewed
**Output**: Complete documentation
**Handoff**: Completes independently
**Responsibilities**:
- Generate API documentation
- Create user guides
- Update README
- Add code comments
**Generates**:
- API reference
- Usage examples
- Architecture diagrams
- Troubleshooting guides
### 7. @agent-devops
**Role**: Deployment Configuration
**Trigger**: After code review
**Output**: Deployment-ready config
**Handoff**: Completes independently
**Responsibilities**:
- Prepare deployment configurations
- Set up CI/CD pipelines
- Configure environment variables
- Create deployment scripts
**Handles**:
- Docker/container setup
- Infrastructure as Code
- Deployment automation
- Environment management
### 8. @agent-pm
**Role**: Project Management & Completion
**Trigger**: After code review + commit
**Output**: Project status report
**Handoff**: → `@agent-retro`
**Responsibilities**:
- Update task management system
- Track project progress
- Coordinate agent handoffs
- Trigger retrospective analysis
**Integration**:
- Linear issue updates
- GitHub milestone tracking
- Progress reporting
- Capacity planning
### 9. @agent-retro
**Role**: Retrospective Analysis & Learning
**Trigger**: After task completion
**Output**: Insights and improvements
**Handoff**: Updates PM with findings
**Responsibilities**:
- Analyze estimation accuracy
- Calculate actual complexity
- Identify lessons learned
- Improve future predictions
**Generates**:
```markdown
# Retrospective Analysis - LIN-123
## Estimation Accuracy
- Estimated: 8 points
- Actual: 10 points
- Accuracy: 80%
## Lessons Learned
- Auth implementation more complex than expected
- Token management requires more edge cases
## Recommendations
- Add 20% buffer for auth tasks in future
- Create auth helper library for reuse
```
---
## 🔄 Complete Workflow Example
### Scenario: Implement Payment Processing
```bash
# Step 1: Define Requirements
/po "Implement Stripe payment processing with webhook support"
# Step 2: Technology Decisions
/techlead
# → User selects: Node.js, Express, Stripe API, PostgreSQL
# Step 3-7: Fully Automated
# @agent-planner
# ↓ Creates PRD with 4-5 subtasks
# @agent-coder
# ↓ Implements payment service (TDD)
# @agent-reviewer
# ↓ Reviews and commits
# @agent-pm
# ↓ Updates Linear issue
# @agent-retro
# ↓ Analyzes and reports
# Result: Feature complete with commit history!
```
---
## 📚 Task Management Integration
### Supported Systems
**Local Files**:
- Tasks in `.agents/tasks/`
- No external dependency
- Best for solo projects
**Linear**:
- Full MCP integration
- Status synchronization
- Team collaboration
**GitHub Issues**:
- Native integration
- Automatic linking
- Built-in CI/CD
**Jira**:
- API-based sync
- Enterprise support
- Sprint tracking
### Configuration
During `/init-agents`, choose your system:
```
Choose task management:
A) Local files
B) Linear
C) GitHub Issues
D) Jira
```
---
## 🏗️ Workspace Structure
After `/init-agents`, your project has:
```
.agents/
├── package.json # Dependencies (yaml)
├── config.yml # Configuration
├── states.yml # State definitions
├── lib.js # Helper library
├── tasks/ # Task data (gitignored)
│ ├── LIN-123.json # Task state
│ └── LIN-123/
│ ├── planner.md # Planner output
│ ├── coder.md # Coder output
│ └── reviewer.md # Review results
└── retro/ # Retrospectives (gitignored)
```
---
## 📊 Complexity Estimation (Fibonacci Scale)
Tasks are estimated using token consumption, not human hours:
| Points | Tokens | Description |
|--------|--------|-------------|
| 1 | 1,000 | Trivial task |
| 2 | 2,000 | Simple feature |
| 3 | 3,000 | Basic feature |
| 5 | 5,000 | Medium feature |
| 8 | 8,000 | Complex feature |
| 13 | 13,000 | Very complex |
| 21 | 21,000 | Large feature set |
**Key Principle**: Let `@agent-retro` improve estimates based on actual usage.
---
## 🛡️ Error Handling & Protection
### Automatic Escalation
When an agent encounters issues:
1. **Retry up to 3 times** for transient errors
2. **Fallback strategy** for known issues
3. **Escalate to human** if unresolvable
Example:
```bash
# Agent tries 3 times, then alerts:
🚨 Agent needs help: Test failures after 3 retries
Current state:
- Stashed changes: stash@{0}
- Diagnostic: .agents/tasks/LIN-123/coder.md
Options:
A) Review failure details
B) Manually fix issue
C) Adjust requirements
```
### State Preservation
- Git stashes are created before risky operations
- Checkpoints saved between agent handoffs
- Complete audit trail in task JSON
---
## 🎓 Best Practices
### 1. Agent-First Priority
**Use Agents for**:
- ✅ Complex multi-step tasks
- ✅ Automation and repetition
- ✅ Consistent quality
**Use Commands for**:
- ✅ Critical decisions only
- ✅ Direction-setting
- ✅ Approval gates
### 2. Complexity Estimation
- Based on token consumption, not guesses
- Let `@agent-retro` continuously improve
- Use historical data for better predictions
### 3. Workspace Maintenance
```bash
# Check workspace size
du -sh .agents/
# View task status
cat .agents/tasks/LIN-123.json | jq
# View agent output
cat .agents/tasks/LIN-123/coder.md
# Clean old tasks (90+ days)
node -e "require('./.agents/lib').AgentTask.cleanup(90)"
```
### 4. Git Workflow
Only 2 entities can commit:
-`@agent-reviewer` - after review
-`/git-commit` - manual (emergency only)
**Commit Format**:
```
feat(LIN-123): implement payment processing
Add Stripe integration with webhook support
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
```
---
## 🚦 Workflow Variations
### Quick Feature Development
```bash
/po "Feature: Add dark mode toggle"
# → Auto-completes in 1-2 passes
```
### Bug Fix with Investigation
```bash
@agent-debugger "Fix: Memory leak in user session"
# → Diagnosis → Fix → Review → Commit
```
### Performance Optimization
```bash
@agent-optimizer "Reduce API response time by 50%"
# → Analysis → Optimization → Testing → Commit
```
### Documentation Update
```bash
@agent-doc "Generate API docs for new endpoints"
# → Analyzes code → Generates docs
```
---
## 📖 Learning Resources
### Documentation
Inside this plugin:
- `docs/workflow.md` - Complete workflow overview
- `docs/agent-workspace-guide.md` - Technical implementation guide
- `commands/` directory - Individual command details
- `agents/` directory - Agent specifications
### Quick References
**Initialize workspace**:
```bash
/init-agents
```
**View workspace guide**:
See plugin's `docs/agent-workspace-guide.md`
**Check agent status**:
```bash
cat .agents/tasks/LIN-123.json | jq
```
---
## ❓ FAQ
**Q: Do I need to run all commands?**
A: No! Start with `/po`, optionally use `/techlead`, then agents handle the rest.
**Q: Can I use this without task management?**
A: Yes! Choose "Local files" during `/init-agents` setup.
**Q: What if an agent fails?**
A: It escalates with full context. You can then manually fix or adjust requirements.
**Q: How do I monitor progress?**
A: Check `.agents/tasks/` directory - each task shows all agent outputs.
**Q: Can agents commit code?**
A: Only `@agent-reviewer` can commit. Other agents create code, reviewer approves.
---
## 🔗 Related Resources
- Full documentation: See `docs/` directory
- Individual agents: See `agents/` directory
- Command details: See `commands/` directory
- Workspace setup: Run `/init-agents`
---
**Version**: 1.0
**Last Updated**: 2025-10-16
**Status**: Production Ready
Need more details? Check the comprehensive guides in the `docs/` directory!

610
commands/init-agents.md Normal file
View File

@@ -0,0 +1,610 @@
---
name: init-agents
description: Initialize Agent-First workflow structure in the current project. Sets up agent workspace, task management, and configuration.
model: claude-haiku-4-5
---
# Init Agents Workspace
Initialize Agent-First workflow structure in the current project.
## What this command does
1. Creates `.agents/` directory structure
2. **Configures task management system** (Linear/GitHub Issues/Jira/Local)
3. Initializes state definitions
4. Configures gitignore rules
5. Creates agent helper library
## Usage
Run this command in any project root to set up the agent workspace.
**IMPORTANT**: This command will ask you to configure the task management system for this project.
---
Please initialize the Agent-First workflow structure in the current project with the following setup:
## Step 0: Configuration
### Package Manager Selection
**First, ask the user which package manager they prefer:**
```
📦 Package Manager Setup
Which JavaScript package manager do you prefer for this project?
A) npm (Node.js default)
B) pnpm (Fast, disk-efficient)
C) bun (Ultra-fast, modern)
Please select (A/B/C):
```
**Store the selection for later use in dependency installation.**
### Task Management System Configuration
**Then, ask the user:**
```
🔧 Task Management System Setup
Which task management system does this project use?
A) Linear (with MCP integration)
B) GitHub Issues
C) Jira
D) Local files (.agents/tasks/)
E) Other
Please select (A/B/C/D/E):
```
**Based on user selection, collect required information:**
### If Linear (A):
```
Linear Configuration:
- Team ID or name: _______________
- API Key (optional, for MCP): _______________
- Workspace: _______________
```
### If GitHub Issues (B):
```
GitHub Configuration:
- Repository: _______________
- Owner: _______________
```
### If Jira (C):
```
Jira Configuration:
- Project Key: _______________
- Site URL: _______________
```
**Note on Jira Integration**: This project uses Atlassian CLI (acli) for direct Jira management.
After `/init-agents` completes, ensure you have installed and authenticated Atlassian CLI:
1. Install ACLI: https://developer.atlassian.com/cloud/acli/guides/install-acli/
2. Authenticate with OAuth:
```bash
acli jira auth
```
Follow the browser OAuth flow to complete authentication.
3. Verify connection:
```bash
acli jira workspace list
```
See `jira_cli_integration.md` for detailed usage in agent workflows.
### If Local (D):
```
Local Task Management:
✅ Tasks will be stored in .agents/tasks/
✅ No external integration needed
```
**Create `CLAUDE.md` in project root with STABLE configuration only:**
```markdown
# Project Configuration
## Task Management System
**System**: [Linear/GitHub/Jira/Local]
**Configuration**:
- [Key configuration details based on selection]
## Agent Workspace
Location: `.agents/`
See @.agents/README.md for usage guide.
```
---
## 1. Create Directory Structure
```bash
mkdir -p .agents/tasks
mkdir -p .agents/retro
```
## 2. Install Dependencies
**Based on user's package manager selection, run the appropriate command:**
### If npm (A):
```bash
cd .agents
npm init -y
npm install yaml
cd ..
```
### If pnpm (B):
```bash
cd .agents
pnpm init
pnpm add yaml
cd ..
```
### If bun (C):
```bash
cd .agents
bun init -y
# Remove "type": "module" to use CommonJS (lib.js uses require/module.exports)
sed -i.bak '/"type": "module"/d' package.json && rm package.json.bak
bun add yaml
cd ..
```
**Note**: Bun init defaults to ESM (`"type": "module"`), but lib.js uses CommonJS format. The sed command removes this field to ensure compatibility.
**This creates:**
- `.agents/package.json` - Dependency manifest
- `.agents/node_modules/` - Installed packages (will be gitignored)
- `.agents/package-lock.json` / `pnpm-lock.yaml` / `bun.lockb` - Lock file
## 3. Create Agent Config (.agents/config.yml)
```yaml
# Agent Workspace Configuration
# This file contains DYNAMIC state and runtime information
workspace:
version: "1.0.0"
initialized_at: "[CURRENT_TIMESTAMP]"
location: ".agents/"
task_management:
system: "[Linear/GitHub/Jira/Local]"
# Configuration details are stored in project root CLAUDE.md
# This section tracks runtime state only
runtime:
last_cleanup: null
total_tasks_created: 0
total_tasks_completed: 0
```
## 4. Create State Definitions (.agents/states.yml)
```yaml
# Agent Task States Definition
task_states:
pending:
description: "Task created, waiting to start"
next_states: ["in_progress", "blocked", "cancelled"]
in_progress:
description: "Task in progress"
next_states: ["completed", "blocked", "failed"]
blocked:
description: "Task blocked, requires human intervention"
next_states: ["in_progress", "cancelled"]
completed:
description: "Task completed"
next_states: []
failed:
description: "Task failed, cannot complete"
next_states: ["pending", "cancelled"]
cancelled:
description: "Task cancelled"
next_states: []
agent_states:
idle:
description: "Agent idle, waiting for tasks"
working:
description: "Agent working"
completed:
description: "Agent completed its part"
blocked:
description: "Agent encountered issues, cannot continue"
skipped:
description: "Agent skipped"
complexity_scale:
values: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
token_estimates:
1: 1000
2: 2000
3: 3000
5: 5000
8: 8000
13: 13000
21: 21000
34: 34000
55: 55000
89: 89000
```
## 5. Create Agent Helper Library (.agents/lib.js)
```javascript
const fs = require('fs');
const path = require('path');
const yaml = require('yaml');
class AgentTask {
constructor(taskId) {
this.taskId = taskId;
this.jsonPath = `.agents/tasks/${taskId}.json`;
this.dirPath = `.agents/tasks/${taskId}`;
}
// Load task
load() {
if (!fs.existsSync(this.jsonPath)) {
throw new Error(`Task ${this.taskId} not found`);
}
return JSON.parse(fs.readFileSync(this.jsonPath, 'utf8'));
}
// Save task
save(task) {
fs.writeFileSync(this.jsonPath, JSON.stringify(task, null, 2));
}
// Create new task
static create(taskId, title, complexity = 5) {
const states = yaml.parse(fs.readFileSync('.agents/states.yml', 'utf8'));
const estimatedTokens = states.complexity_scale.token_estimates[complexity];
const task = {
task_id: taskId,
title: title,
status: 'pending',
current_agent: null,
complexity: {
estimated: complexity,
estimated_tokens: estimatedTokens,
actual: null,
actual_tokens: null
},
agents: {},
metadata: {
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}
};
const jsonPath = `.agents/tasks/${taskId}.json`;
const dirPath = `.agents/tasks/${taskId}`;
fs.writeFileSync(jsonPath, JSON.stringify(task, null, 2));
fs.mkdirSync(dirPath, { recursive: true });
return new AgentTask(taskId);
}
// Set complexity
setComplexity(complexity, estimatedTokens = null) {
const task = this.load();
task.complexity.estimated = complexity;
if (estimatedTokens) {
task.complexity.estimated_tokens = estimatedTokens;
} else {
const states = yaml.parse(fs.readFileSync('.agents/states.yml', 'utf8'));
task.complexity.estimated_tokens = states.complexity_scale.token_estimates[complexity];
}
task.metadata.updated_at = new Date().toISOString();
this.save(task);
}
// Update agent status
updateAgent(agentName, data) {
const task = this.load();
if (!task.agents[agentName]) {
task.agents[agentName] = {};
}
Object.assign(task.agents[agentName], data);
if (data.status === 'working' && !task.agents[agentName].started_at) {
task.agents[agentName].started_at = new Date().toISOString();
}
if (data.status === 'completed' && !task.agents[agentName].completed_at) {
task.agents[agentName].completed_at = new Date().toISOString();
}
if (data.handoff_to) {
task.current_agent = data.handoff_to;
}
task.metadata.updated_at = new Date().toISOString();
this.save(task);
}
// Write agent output to markdown
writeAgentOutput(agentName, content) {
fs.mkdirSync(this.dirPath, { recursive: true });
const outputPath = path.join(this.dirPath, `${agentName}.md`);
fs.writeFileSync(outputPath, content);
const task = this.load();
if (!task.agents[agentName]) {
task.agents[agentName] = {};
}
task.agents[agentName].output_file = `${agentName}.md`;
task.metadata.updated_at = new Date().toISOString();
this.save(task);
}
// Append to agent output
appendAgentOutput(agentName, content) {
const outputPath = path.join(this.dirPath, `${agentName}.md`);
fs.appendFileSync(outputPath, '\n' + content);
}
// Read agent output
readAgentOutput(agentName) {
const outputPath = path.join(this.dirPath, `${agentName}.md`);
if (!fs.existsSync(outputPath)) return null;
return fs.readFileSync(outputPath, 'utf8');
}
// Mark task as completed
complete() {
const task = this.load();
task.status = 'completed';
task.current_agent = null;
task.metadata.updated_at = new Date().toISOString();
// Calculate actual complexity
let totalTokens = 0;
Object.values(task.agents).forEach(agent => {
if (agent.tokens_used) {
totalTokens += agent.tokens_used;
}
});
task.complexity.actual_tokens = totalTokens;
task.complexity.actual = this.mapToFibonacci(totalTokens);
this.save(task);
}
// Map tokens to Fibonacci scale
mapToFibonacci(tokens) {
const states = yaml.parse(fs.readFileSync('.agents/states.yml', 'utf8'));
const scale = states.complexity_scale.values;
const estimates = states.complexity_scale.token_estimates;
for (let i = scale.length - 1; i >= 0; i--) {
if (tokens >= estimates[scale[i]]) {
return scale[i];
}
}
return scale[0];
}
// Find tasks for specific agent
static findMyTasks(agentName) {
const tasksDir = '.agents/tasks';
if (!fs.existsSync(tasksDir)) return [];
return fs.readdirSync(tasksDir)
.filter(f => f.endsWith('.json'))
.map(f => {
const task = JSON.parse(fs.readFileSync(path.join(tasksDir, f), 'utf8'));
return task;
})
.filter(t => t.current_agent === agentName && t.status === 'in_progress');
}
// Cleanup old tasks
static cleanup(daysOld = 90) {
const tasksDir = '.agents/tasks';
const now = Date.now();
const cutoff = daysOld * 24 * 60 * 60 * 1000;
let cleaned = 0;
fs.readdirSync(tasksDir).forEach(file => {
if (!file.endsWith('.json')) return;
const filePath = path.join(tasksDir, file);
const task = JSON.parse(fs.readFileSync(filePath, 'utf8'));
if (!['completed', 'cancelled'].includes(task.status)) return;
const stats = fs.statSync(filePath);
const age = now - stats.mtimeMs;
if (age > cutoff) {
fs.unlinkSync(filePath);
const taskDir = path.join(tasksDir, task.task_id);
if (fs.existsSync(taskDir)) {
fs.rmSync(taskDir, { recursive: true });
}
cleaned++;
}
});
return cleaned;
}
}
module.exports = { AgentTask };
```
## 6. Update .gitignore
Add the following rules to `.gitignore`:
```
# Agent Workspace - Local state and dependencies
.agents/tasks/
.agents/retro/
.agents/node_modules/
.agents/package-lock.json
.agents/pnpm-lock.yaml
.agents/bun.lockb
# Keep these files in version control:
# .agents/package.json
# .agents/config.yml
# .agents/states.yml
# .agents/lib.js
# .agents/README.md
```
## 7. Create README (.agents/README.md)
```markdown
# Agent Workspace
This directory contains the Agent-First workflow workspace for this project.
## Structure
- `package.json` - **Dependencies** (yaml package)
- `node_modules/` - **Installed packages** (gitignored)
- `config.yml` - **Dynamic configuration** (initialization time, runtime stats)
- `states.yml` - **State definitions** (task states, agent states, complexity scale)
- `lib.js` - **Agent helper library** (AgentTask class)
- `tasks/` - **Active tasks** (JSON + markdown details, gitignored)
- `{task-id}.json` - Task state and metadata
- `{task-id}/` - Detailed agent outputs
- `planner.md` - Planning documents
- `coder.md` - Implementation logs
- `reviewer.md` - Review results
- `retro.md` - Retrospective analysis
- `retro/` - **Retrospective analysis reports** (gitignored)
## Setup
### First Time Setup
After running `/init-agents`, dependencies are automatically installed. If you clone this repo:
\`\`\`bash
cd .agents
npm install # or: pnpm install / bun install
\`\`\`
## Task Lifecycle
1. **Create**: `AgentTask.create(taskId, title, complexity)`
2. **Work**: Agents update status and write outputs
3. **Complete**: Mark as done, calculate actual complexity
4. **Cleanup**: Auto-delete after 90 days (based on file mtime)
## Usage Examples
### Create a task
\`\`\`javascript
const { AgentTask } = require('./.agents/lib');
const task = AgentTask.create('LIN-123', 'Implement auth API', 8);
\`\`\`
### Agent updates status
\`\`\`javascript
task.updateAgent('planner', {
status: 'completed',
tokens_used: 1200,
handoff_to: 'coder'
});
\`\`\`
### Write detailed output
\`\`\`javascript
task.writeAgentOutput('planner', \`
# Planning Document
## Requirements
...
\`);
\`\`\`
### Find my tasks
\`\`\`javascript
const myTasks = AgentTask.findMyTasks('coder');
\`\`\`
### Cleanup old tasks
\`\`\`javascript
const cleaned = AgentTask.cleanup(90); // 90 days
console.log(\`Cleaned \${cleaned} old tasks\`);
\`\`\`
## States
Check `states.yml` for:
- Task states (pending, in_progress, blocked, completed, failed, cancelled)
- Agent states (idle, working, completed, blocked, skipped)
- Complexity scale (Fibonacci: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
## Maintenance
Tasks are automatically cleaned up 90 days after completion based on file modification time. No archive directory needed.
```
## Summary
After running this command, your project will have:
✅ **`CLAUDE.md`** - Stable configuration (Task Management System setup)
✅ **`.agents/package.json`** - Dependency manifest (yaml package)
✅ **`.agents/node_modules/`** - Installed packages (gitignored)
✅ **`.agents/config.yml`** - Dynamic state (initialization time, runtime stats)
✅ **`.agents/states.yml`** - State definitions and complexity scale
✅ **`.agents/lib.js`** - Agent helper library
✅ **`.agents/README.md`** - Usage documentation
✅ **`.gitignore`** - Updated to exclude runtime files and dependencies
The workspace is now ready for Agent-First development!
## File Organization Principle
- **`CLAUDE.md`**: Stable configuration that rarely changes (task management type, API connections)
- **`.agents/config.yml`**: Dynamic state that changes during runtime (timestamps, counters)
- **`.agents/states.yml`**: Shared state definitions (task states, complexity scale)
- **`.agents/tasks/`**: Active task data (automatically cleaned after 90 days)
## Next Steps
1. **Understand the workflow**: Read @~/.claude/workflow.md for the complete Agent-First workflow
2. **Technical details**: See @~/.claude/agent-workspace-guide.md for API usage and examples
3. **Start using agents**: Begin with `/product_owner` or `/techlead` commands
## References
- @~/.claude/workflow.md - Complete Agent-First workflow overview
- @~/.claude/agent-workspace-guide.md - Technical implementation guide
- @~/.claude/CLAUDE.md - Global configuration and preferences

67
commands/po.md Normal file
View File

@@ -0,0 +1,67 @@
---
name: po
description: Product Owner mode for defining requirements and features. Sets product vision and acceptance criteria for the development team.
model: claude-opus-4-1
---
# Mode: Product Owner
## Persona
You are the Product Owner, the visionary voice of the customer and the ultimate authority on the product's features and functionality. Your primary responsibility is to create and maintain a clear, compelling product vision and to ensure that the development team is building the right product to meet user needs and achieve product-market fit. You are obsessed with user experience, product quality, and delivering value. You bridge the gap between stakeholders and the development team, translating high-level goals into actionable user stories.
## Rules
1. **User-Centric Focus**: All decisions must be justified by their value to the end-user. Your mantra is "What problem does this solve for the user?"
2. **Product Vision Guardian**: You own the product backlog and are responsible for prioritizing it based on user feedback, market research, and strategic product goals. You must be able to clearly articulate the "why" behind every feature.
3. **Clarity and Specificity**: Your requests to the development team must be in the form of well-defined user stories or feature requirements. Avoid ambiguity.
4. **No Business Jargon**: Frame requests in terms of product value and user impact, not ROI, revenue, or market share. The focus is on building a great product, and the business success will follow.
5. **Quality Advocate**: You have the final say on whether a feature meets the acceptance criteria. You will work closely with the `QA` mode to define test cases and ensure the final product is polished and bug-free.
6. **Iterative Approach**: Embrace agile principles. Be prepared to inspect the work, adapt the plan, and make tough decisions about what to build next, what to change, and what to cut.
7. **Collaboration, Not Dictation**: While you have the final say on "what" gets built, you will collaborate with the `TechLead` and `Coder` on the "how." Respect their technical expertise.
8. **Explicit Delegation**: As the entry point of the workflow, your final output must be a clear and actionable handoff to the next agent, which is the `Tech Lead`. You must frame your request as a directive to the `Tech Lead`.
## Interaction Workflow & Delegation
As the starting point for the development process, your primary role is to define the "what" and "why" and then formally hand off the task to the `Tech Lead` to begin the strategic planning. You must ensure the entire team understands and follows the established workflow.
### Core Development Workflow
The entire development process follows this workflow. You are responsible for initiating it.
```mermaid
flowchart TD
A[Product Owner<br/>Requirements Definition] --> B[Tech Lead<br/>Strategic Planning & Analysis]
B --> C[Planner<br/>Technical Task Breakdown]
C --> D[Coder<br/>Code Implementation]
D --> E[QA<br/>Quality & Security Checks]
E --> F[Refactor<br/>Performance Optimization]
F --> G[Documentation<br/>Documentation Updates]
G --> H[DevOps<br/>Deployment Preparation]
H --> I[Release<br/>Pre-Release Final Validation]
I --> A
style A fill:#ffcdd2
style B fill:#e1f5fe
style C fill:#f3e5f5
style D fill:#e8f5e8
style E fill:#fff3e0
style F fill:#fce4ec
style G fill:#f1f8e9
style H fill:#fff8e1
style I fill:#e0f2f1
```
### Your Role in the Workflow
1. **Initiation**: You receive a high-level goal.
2. **Define Vision & Scope**: You articulate the product vision, target users, key problems to solve, and initial feature ideas, referencing the workflow chart to set expectations.
3. **Formal Handoff**: You conclude your analysis with an explicit command to the `Tech Lead`. This ensures the workflow is correctly initiated.
**Example Handoff Command:**
```
/techlead Based on the product vision I've outlined and the established workflow, please analyze the requirements, propose a technical strategy, and identify potential risks. Once your analysis is complete, hand off the plan to the Planner for task breakdown.
```
This structure ensures that your vision is directly translated into a strategic technical plan by the designated next agent in the chain.

91
commands/techlead.md Normal file
View File

@@ -0,0 +1,91 @@
---
name: techlead
description: Tech Lead mode for strategic planning and requirement analysis. Makes architectural decisions and technology selections.
model: claude-opus-4-1
---
# Tech Lead Mode
Switch to Tech Lead mode for high-level strategic planning and requirement analysis.
## Description
In Tech Lead mode, I function as a technical leader focused on analyzing project requirements, creating execution plans, and breaking down initiatives into manageable tasks. This mode emphasizes strategic planning and requirement clarification without any code implementation.
## Core Responsibilities
- **Requirements Analysis**: Thoroughly analyze project requirements and available resources
- **Strategic Planning**: Create actionable execution plans and roadmaps
- **Task Breakdown**: Decompose large initiatives into manageable, well-defined tasks
- **System Integration**: Present plans in Markdown for review, then assist with creating entries in task management systems (e.g., Jira/Linear) upon confirmation.
- **Resource Planning**: Allocate resources and estimate timelines
## Key Constraints
- **No Code Changes**: Strictly no code modification or system changes.
- **Planning Focus**: Pure strategic planning and guidance.
- **Focused Scope**: Concentrate on the user's immediate request, avoiding over-engineering.
- **Output Format**: Initial deliverables are in Markdown format. Integration with task management systems is a secondary step.
## Communication Style
- **Tone**: Direct, factual, task-oriented communication
- **Approach**: Eliminate emotional language, focus on current tasks
## Expected Deliverables
- Execution roadmaps with clear milestones, using Mermaid charts for visualization.
- Detailed task breakdowns with dependencies.
- Resource allocation plans.
- Estimate task complexity using Fibonacci numbers (based on repository state and user-provided context, excluding human factors).
## Example Usage
**Input:**
```
/techlead
User: We need to implement a new user authentication system for our web application.
```
**Response:**
```
Current Mode: Tech Lead
Project Requirements Analysis:
- Objective: Implement new user authentication system
- Scope: Web application
- Priority: High
Execution Roadmap:
```mermaid
gantt
title User Authentication System Implementation Roadmap
dateFormat YYYY-MM-DD
section Planning Phase
Requirements Analysis :done, req, 2024-01-01, 2024-01-03
Technology Selection :done, tech, after req, 2d
Architecture Design :arch, after tech, 3d
section Development Phase
Backend API Development :backend, after arch, 1w
Frontend Integration :frontend, after backend, 5d
section Testing & Deployment
Integration Testing :test, after frontend, 3d
Production Deployment :deploy, after test, 2d
```
Task Breakdown:
1. **Requirements Clarification** - Confirm authentication method (JWT/OAuth/Multi-factor)
2. **Technology Selection** - Choose authentication framework and database solution
3. **Architecture Design** - Design authentication flow and security mechanisms
4. **API Development** - Implement authentication-related API endpoints
5. **Frontend Integration** - Develop login/registration interfaces
6. **Testing & Validation** - Comprehensive authentication flow testing
7. **Production Deployment** - Deploy to production environment
```
Plan Confirmation:
- Please confirm if the above plan meets your requirements.
- Would you like assistance creating these tasks in your task management system (such as Linear or Jira)?