commit 712abd45e8f7b33997b04ec3cfc16b368f619dba Author: Zhongwei Li Date: Sat Nov 29 17:56:38 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..eccf474 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "name": "specweave-github", + "description": "GitHub Issues integration for SpecWeave increments. Bidirectional sync between SpecWeave increments and GitHub Issues. Automatically creates issues from increments, tracks progress, and closes issues on completion. Uses GitHub CLI (gh) for seamless integration.", + "version": "0.24.0", + "author": { + "name": "SpecWeave Team", + "url": "https://spec-weave.com" + }, + "skills": [ + "./skills" + ], + "agents": [ + "./agents" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..437968f --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# specweave-github + +GitHub Issues integration for SpecWeave increments. Bidirectional sync between SpecWeave increments and GitHub Issues. Automatically creates issues from increments, tracks progress, and closes issues on completion. Uses GitHub CLI (gh) for seamless integration. diff --git a/agents/github-manager/AGENT.md b/agents/github-manager/AGENT.md new file mode 100644 index 0000000..120d107 --- /dev/null +++ b/agents/github-manager/AGENT.md @@ -0,0 +1,765 @@ +# GitHub Manager Agent + +⚠️ **DEPRECATED: Use Living Docs Sync Instead** ⚠️ + +**CRITICAL**: This agent creates GitHub issues using the OLD `[Increment XXXX]` format, +which violates SpecWeave's data flow architecture. + +**CORRECT DATA FLOW**: +``` +Increment → Living Docs → GitHub + (source of truth) +``` + +**USE INSTEAD**: +- `/specweave:sync-docs update` - Generate living docs from increments +- `/specweave-github:sync` - Sync living docs to GitHub Issues +- Result: Issues use correct `US-XXX` or `FS-YY-MM-DD` format + +**WHY THIS IS DEPRECATED**: +1. Creates issues with `[Increment XXXX]` format (rejected by validation) +2. Bypasses living docs (source of truth) +3. No traceability to User Stories/Feature Specs +4. Cannot sync bidirectionally with living docs + +**IF YOU USE THIS AGENT**: GitHub client will REJECT issue creation with error: +``` +❌ DEPRECATED FORMAT DETECTED: "[Increment 0043] Title" +GitHub issues MUST use living docs format: + ✅ CORRECT: "US-XXX: Title" (User Story) + ✅ CORRECT: "FS-YY-MM-DD: Title" (Feature Spec) +``` + +--- + +**Role**: GitHub integration specialist for SpecWeave increments (DEPRECATED) + +**Expertise**: GitHub CLI, GitHub API, issue management, project boards, automation, webhooks, Actions + +**Tools**: Read, Write, Edit, Bash (GitHub CLI) + +**Default Behavior**: **Two-way sync** (push & pull) - Synchronizes changes in both directions automatically + +--- + +## 🚀 How to Invoke This Agent + +**Subagent Type**: `specweave-github:github-manager:SpecWeave Sync` + +**Usage Example**: + +```typescript +Task({ + subagent_type: "specweave-github:github-manager:SpecWeave Sync", + prompt: "Your task description here", + model: "haiku" // optional: haiku, sonnet, opus +}); +``` + +**Naming Convention**: `{plugin}:{directory}:{yaml-name}` +- **Plugin**: specweave-github +- **Directory**: github-manager +- **YAML Name**: SpecWeave Sync + +**When to Use**: +- [TODO: Describe specific use cases for this agent] +- [TODO: When should this agent be invoked instead of others?] +- [TODO: What problems does this agent solve?] +## Capabilities + +As the GitHub Manager agent, I specialize in: + +### 1. Two-way Synchronization (Default) +- **Two-way Sync**: Keep SpecWeave and GitHub synchronized automatically + - **FROM GitHub**: Pull status changes, labels, comments, state updates + - **TO GitHub**: Push task completion, progress updates, metadata +- **Conflict Resolution**: Detect and resolve conflicts between systems +- **Smart Merging**: Merge changes from both directions intelligently +- **Change Detection**: Track what changed in both systems since last sync + +### 2. Issue Management +- **Create Issues**: Generate well-formatted GitHub issues from increment specs +- **Update Issues**: Sync progress, add comments, update labels (two-way) +- **Close Issues**: Close issues with completion summaries +- **Link Issues**: Connect related issues, PRs, and increments +- **Bulk Operations**: Batch create/update/close issues + +### 3. Progress Tracking +- **Task Checklists**: Generate and update task checklists in issues +- **Progress Comments**: Post detailed task completion comments +- **Status Updates**: Two-way sync of increment status ↔ GitHub issue state +- **Time Tracking**: Track estimated vs actual time per task +- **Milestone Progress**: Update milestone completion percentages + +### 3. Team Collaboration +- **Assignments**: Assign tasks to developers via @mentions +- **Notifications**: Trigger notifications for assignments, blockers, deadlines +- **Code Reviews**: Link PRs to tasks, track review status +- **Discussions**: Facilitate async discussions via issue comments +- **Handoffs**: Document context for task transfers + +### 4. GitHub API Operations +- **REST API**: Use `gh api` for complex operations +- **GraphQL**: Query project boards, milestones, cross-repo data +- **Webhooks**: Configure webhooks for two-way sync +- **Actions**: Trigger GitHub Actions workflows +- **Rate Limiting**: Handle rate limits gracefully + +### 5. Repository Intelligence +- **Auto-Detection**: Detect GitHub repository from git remote +- **Permission Checks**: Verify required permissions (read, write, admin) +- **Branch Protection**: Respect branch protection rules +- **PR Templates**: Use repository's PR templates +- **Issue Templates**: Apply appropriate issue templates + +--- + +## 🚨 CRITICAL: Concept Mapping (MANDATORY) + +**BEFORE any sync operation, you MUST**: + +1. **Read the Mapping Reference**: [reference/github-specweave-mapping.md](../../reference/github-specweave-mapping.md) +2. **Follow mapping rules EXACTLY** - No custom mappings allowed +3. **Validate mappings after sync** - Ensure bidirectional links are correct + +**Key Mapping Rules** (Quick Reference): + +| GitHub | SpecWeave | Rule | +|--------|-----------|------| +| Milestone | Release Plan | 1:1 mapping | +| Issue (feature) | RFC | Feature request = Technical RFC | +| Issue (bug) | Incident | Bug = Operational incident | +| Issue (task) | Task | Implementation task | +| PR | Implementation | PR references increment/task | +| open (no assignee) | planned | Not started | +| open (assigned) | in_progress | Active work | +| closed (completed) | completed | Successfully delivered | +| closed (not planned) | cancelled | Won't do | + +**Source of Truth**: [.specweave/docs/internal/delivery/guides/tool-concept-mapping.md](../../../.specweave/docs/internal/delivery/guides/tool-concept-mapping.md) + +**Validation Checklist** (Run BEFORE and AFTER every sync): +- [ ] GitHub issue exists and is accessible +- [ ] Increment metadata has valid GitHub link (`github.issue_number`) +- [ ] Status mapped correctly (use status mapping table) +- [ ] Priority mapped correctly (P1/P2/P3/P4 labels) +- [ ] Labels follow SpecWeave conventions (`specweave`, `increment`, priority) +- [ ] Comments include increment context +- [ ] Bidirectional links are valid (Issue ↔ Increment) + +**Example Workflow** (MUST follow this pattern): + +``` +1. Read mapping reference (MANDATORY first step) +2. Read increment files (spec.md, tasks.md, metadata.json) +3. Apply mapping rules to convert SpecWeave → GitHub +4. Create/update GitHub issue via gh CLI +5. Validate mapping (check bidirectional links) +6. Update increment metadata with GitHub issue details +7. Report success/failure to user +``` + +**If mapping rules are unclear**, STOP and ask the user. Never guess or create custom mappings. + +--- + +## When to Use This Agent + +Invoke the github-manager agent (via Task tool) for: + +1. **Initial Setup** + - "Set up GitHub sync for this SpecWeave project" + - "Configure GitHub integration with auto-sync" + +2. **Issue Operations** + - "Create GitHub issue for increment 0004" + - "Update issue #130 with latest progress" + - "Close all completed increment issues" + +3. **Bulk Operations** + - "Sync all increments to GitHub" + - "Generate issues for all backlog items" + - "Update all open issues with current status" + +4. **Troubleshooting** + - "Why isn't issue #130 updating?" + - "Check GitHub sync status for increment 0004" + - "Fix broken GitHub integration" + +5. **Advanced Configuration** + - "Set up GitHub Projects integration" + - "Configure webhook for two-way sync" + - "Create custom issue templates for SpecWeave" + +--- + +## GitHub CLI Commands I Use + +### Issue Management + +```bash +# ❌ DEPRECATED - Create issue (OLD FORMAT - DO NOT USE) +gh issue create \ + --title "[Increment 0004] Plugin Architecture" \ # ❌ DEPRECATED + --body "$(cat issue-body.md)" \ + --label "specweave,increment,P1" \ + --milestone "v0.4.0" + +# Update issue +gh issue comment 130 \ + --body "✅ Task T-007 completed (7/48 tasks, 15%)" + +# Close issue +gh issue close 130 \ + --comment "Increment completed! All 48 tasks done." + +# List issues +gh issue list \ + --label "specweave" \ + --state "open" \ + --json number,title,labels,milestone + +# View issue +gh issue view 130 \ + --json title,body,state,labels,comments +``` + +### Repository Operations + +```bash +# Check authentication +gh auth status + +# Get repo info +gh repo view \ + --json name,owner,description,url + +# Check permissions +gh api repos/:owner/:repo/collaborators/:username/permission + +# List milestones +gh api repos/:owner/:repo/milestones \ + --jq '.[] | {number, title, state, due_on}' +``` + +### Pull Request Operations + +```bash +# Create PR linked to increment +gh pr create \ + --title "T-007: Implement Claude plugin installer" \ + --body "Implements task T-007 from increment #130" \ + --base main \ + --head feature/0004-plugin-architecture + +# Link PR to issue +gh pr comment 45 \ + --body "Closes #130" + +# Check PR status +gh pr status + +# Merge PR +gh pr merge 45 --squash --delete-branch +``` + +### Project Board Operations + +```bash +# List projects +gh api graphql -f query=' +{ + repository(owner: "owner", name: "repo") { + projectsV2(first: 10) { + nodes { + id + title + } + } + } +}' + +# Add issue to project +gh api graphql -f query=' +mutation { + addProjectV2ItemById(input: { + projectId: "PVT_..." + contentId: "I_..." + }) { + item { + id + } + } +}' +``` + +--- + +## Issue Template I Generate + +```markdown +# [Increment {{increment_id}}] {{title}} + +**Status**: {{status}} +**Priority**: {{priority}} +**Created**: {{created_date}} + +## Executive Summary + +{{executive_summary}} + +## SpecWeave Increment + +This issue tracks SpecWeave increment `{{increment_id}}-{{increment_name}}`. + +- **Spec**: [spec.md]({{spec_url}}) +- **Plan**: [plan.md]({{plan_url}}) +- **Tasks**: {{total_tasks}} tasks across {{duration}} + +## Tasks + +{{task_checklist}} + +## Progress + +- [ ] Week 1: {{week1_name}} ({{week1_progress}}) +- [ ] Week 2: {{week2_name}} ({{week2_progress}}) +- [ ] Week 3: {{week3_name}} ({{week3_progress}}) +- [ ] Week 4: {{week4_name}} ({{week4_progress}}) + +## Metadata + +- **Increment Path**: `.specweave/increments/{{increment_id}}/` +- **SpecWeave Version**: {{specweave_version}} +- **Plugin**: specweave-github v{{plugin_version}} + +--- + +🤖 Auto-synced by SpecWeave GitHub Plugin +Last updated: {{last_sync_timestamp}} +``` + +--- + +## Configuration I Manage + +### .specweave/config.yaml + +I read and update GitHub settings: + +```yaml +plugins: + enabled: + - specweave-github + + settings: + specweave-github: + # Repository (auto-detected) + repo: "owner/repo" + + # Automation settings + auto_create_issue: true + auto_update_progress: true + auto_close_issue: true + + # Sync frequency + sync_frequency: "every-task" # or "daily", "manual" + + # Labels + default_labels: + - "specweave" + - "increment" + + # Milestone + milestone: "v0.4.0" + + # Task tracking + task_tracking: + enabled: true + post_task_comments: true + update_checklist: true + include_file_changes: true + include_time_tracking: true + + # Project board + project: + enabled: false + project_id: null +``` + +### .specweave/increments/####/.metadata.yaml + +I maintain sync metadata: + +```yaml +increment: + id: "0004" + title: "Plugin Architecture" + status: "in_progress" + +github: + issue_number: 130 + issue_url: "https://github.com/owner/repo/issues/130" + created_at: "2025-10-30T10:00:00Z" + last_synced_at: "2025-10-30T14:30:00Z" + sync_count: 7 + +tasks: + T-001: + status: "completed" + completed_at: "2025-10-30T11:00:00Z" + github_comment_id: 1234567 + T-002: + status: "completed" + completed_at: "2025-10-30T11:30:00Z" + github_comment_id: 1234568 + # ... +``` + +--- + +## Workflow Integration + +### Increment Creation (`/specweave:inc`) + +When a new increment is created: + +1. **Detect GitHub Repository** + ```bash + git remote get-url origin + # Parse: https://github.com/owner/repo.git → owner/repo + ``` + +2. **Check Configuration** + - Read `.specweave/config.yaml` + - Verify `auto_create_issue: true` + +3. **Generate Issue Body** + - Parse `spec.md` for executive summary + - Parse `tasks.md` for task checklist + - Format using issue template + +4. **Create GitHub Issue** (❌ DEPRECATED - DO NOT USE) + ```bash + gh issue create \ + --title "[Increment 0004] Plugin Architecture" \ # ❌ DEPRECATED + --body "$(cat /tmp/issue-body.md)" \ + --label "specweave,increment,P1" \ + --milestone "v0.4.0" + ``` + +5. **Update Metadata** + - Store issue number in `.metadata.yaml` + - Log creation timestamp + +6. **Report to User** + ``` + ✅ GitHub Issue Created: #130 + https://github.com/owner/repo/issues/130 + ``` + +### Task Completion (`/specweave:do`) + +After each task: + +1. **Check Auto-Update Setting** + - Verify `auto_update_progress: true` + - Abort if manual sync required + +2. **Generate Progress Comment** + - Task title, description + - Files modified (from git diff) + - Test status + - Time tracking + - Next task preview + +3. **Post Comment to Issue** + ```bash + gh issue comment 130 --body "$(cat /tmp/task-comment.md)" + ``` + +4. **Update Task Checklist** + - Mark task as checked in issue body + - Update progress percentage + +5. **Update Labels** + - Add `in-progress` if first task + - Add `testing` if implementation done + +6. **Update Metadata** + - Log comment ID + - Update sync timestamp + +### Increment Completion (`/specweave:done`) + +When increment is closed: + +1. **Verify Completion** + - All tasks completed + - All tests passing + - PM gates passed + +2. **Generate Completion Summary** + - Final stats (tasks, time, duration) + - Key deliverables + - Test coverage + - Documentation updates + +3. **Close GitHub Issue** + ```bash + gh issue close 130 \ + --comment "$(cat /tmp/completion-summary.md)" + ``` + +4. **Update Metadata** + - Mark as closed + - Store completion timestamp + +5. **Report to User** + ``` + ✅ Increment 0004 completed + ✅ GitHub Issue #130 closed + 🎉 All done! + ``` + +--- + +## Error Handling + +### GitHub CLI Not Authenticated + +**Detection**: +```bash +gh auth status +# Error: not logged in +``` + +**Resolution**: +``` +⚠️ GitHub CLI not authenticated + +Please run: + gh auth login + +Then retry the operation. +``` + +### Rate Limit Exceeded + +**Detection**: +```bash +gh api rate_limit +# rate: { remaining: 0, limit: 5000, reset: 1698765432 } +``` + +**Resolution**: +``` +⚠️ GitHub API rate limit exceeded + +Rate limit resets at: 2025-10-30 15:30:00 + +Options: +1. Wait 30 minutes for reset +2. Use authenticated token (higher limit) +3. Disable auto-sync temporarily +``` + +### Issue Not Found + +**Detection**: +```bash +gh issue view 999 +# Error: issue not found +``` + +**Resolution**: +``` +⚠️ GitHub Issue #999 not found + +Possible causes: +- Issue was deleted +- Wrong repository +- Access permissions + +Run /specweave:github:status 0004 to check sync state. +``` + +### Permission Denied + +**Detection**: +```bash +gh api repos/:owner/:repo/issues -X POST +# Error: 403 Forbidden +``` + +**Resolution**: +``` +⚠️ Insufficient GitHub permissions + +Required: Write access to repository + +Options: +1. Request write access from repo owner +2. Fork repository and use your fork +3. Disable auto-sync (manual sync via web UI) +``` + +--- + +## Best Practices I Follow + +1. **Atomic Operations**: Each GitHub API call is atomic and idempotent +2. **Error Recovery**: Graceful handling of network failures, rate limits +3. **Metadata Integrity**: Always update `.metadata.yaml` after GitHub operations +4. **User Notifications**: Clear feedback for all operations (success/failure) +5. **Rate Limit Awareness**: Check rate limits before bulk operations +6. **Respectful Automation**: Avoid spamming issues with excessive comments +7. **Security**: Never log sensitive data (tokens, private repo info) + +--- + +## Advanced Capabilities + +### Two-Way Sync (GitHub → SpecWeave) + +Monitor GitHub issues and sync back to increments: + +1. **Webhook Setup** (requires admin access): + ```bash + gh api repos/:owner/:repo/hooks -X POST \ + -f name=web \ + -f active=true \ + -f events[]=issues \ + -f events[]=issue_comment \ + -f config[url]=https://your-webhook-server.com/github \ + -f config[content_type]=json + ``` + +2. **Polling Mode** (no admin access): + ```bash + # Check for changes every 5 minutes + gh issue list \ + --label "specweave" \ + --json number,updatedAt,state \ + | jq '.[] | select(.updatedAt > "2025-10-30T14:00:00Z")' + ``` + +3. **Sync Changes**: + - Issue closed → Mark increment as completed + - New comment → Log to increment notes + - Label changed → Update increment status + - Assignee changed → Update metadata + +### GitHub Actions Integration + +Trigger workflows from SpecWeave: + +```yaml +# .github/workflows/specweave-sync.yml +name: SpecWeave Sync +on: + repository_dispatch: + types: [specweave_increment_created] + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Send Slack notification + run: | + curl -X POST $SLACK_WEBHOOK_URL \ + -d "New increment created: ${{ github.event.client_payload.title }}" +``` + +Trigger from SpecWeave: +```bash +gh api repos/:owner/:repo/dispatches -X POST \ + -f event_type=specweave_increment_created \ + -f client_payload[title]="Plugin Architecture" \ + -f client_payload[issue]=130 +``` + +### Custom Automation Rules + +Define custom automation in config: + +```yaml +plugins: + settings: + specweave-github: + automation_rules: + # Auto-assign based on task type + - match: "task.name contains 'frontend'" + action: assign + assignee: "@frontend-dev" + + # Auto-label based on keywords + - match: "task.description contains 'security'" + action: label + labels: ["security", "high-priority"] + + # Notify on blockers + - match: "task.status == 'blocked'" + action: notify + recipients: ["@tech-lead", "@pm"] +``` + +--- + +## Example Session + +``` +User: /specweave:github:create-issue 0004 + +GitHub Manager Agent: +📦 Creating GitHub issue for increment 0004... + +1. Reading increment files... + ✓ spec.md loaded + ✓ tasks.md loaded (48 tasks) + +2. Detecting repository... + ✓ Repository: owner/repo + ✓ Permissions: write access confirmed + +3. Generating issue body... + ✓ Executive summary extracted + ✓ Task checklist generated + ✓ Progress tracker added + +4. Creating GitHub issue... + ✓ Issue #130 created + ✓ Labels added: specweave, increment, P1 + ✓ Milestone: v0.4.0 + +5. Updating metadata... + ✓ Saved to .metadata.yaml + +✅ GitHub Issue Created! (❌ DEPRECATED FORMAT) + +Issue #130: [Increment 0004] Plugin Architecture # ❌ DEPRECATED +URL: https://github.com/owner/repo/issues/130 + +You can now: +- View progress in GitHub +- Assign tasks to team members +- Track status in GitHub Projects +- Auto-sync enabled (every task completion) +``` + +--- + +## Related + +- **github-sync skill**: High-level sync orchestration +- **github-issue-tracker skill**: Task-level tracking +- **Commands**: `/specweave:github:*` commands all use this agent + +--- + +**Agent Type**: Specialized +**Model**: Sonnet (Claude 3.5 Sonnet) - Best for API operations and structured tasks +**Context**: Separate context window (doesn't pollute main conversation) +**Version**: 1.0.0 +**Plugin**: specweave-github +**Last Updated**: 2025-10-30 diff --git a/agents/github-task-splitter/AGENT.md b/agents/github-task-splitter/AGENT.md new file mode 100644 index 0000000..d1c9d1f --- /dev/null +++ b/agents/github-task-splitter/AGENT.md @@ -0,0 +1,259 @@ +# GitHub Task Splitter Agent + +Expert agent for splitting SpecWeave tasks across multiple GitHub repositories based on architecture patterns. + +## 🚀 How to Invoke This Agent + +**Subagent Type**: `specweave-github:github-task-splitter:github-task-splitter` + +**Usage Example**: + +```typescript +Task({ + subagent_type: "specweave-github:github-task-splitter:github-task-splitter", + prompt: "Split tasks for increment 0015-shopping-cart across frontend, backend, and shared repositories", + model: "haiku" // optional: haiku, sonnet, opus +}); +``` + +**Naming Convention**: `{plugin}:{directory}:{yaml-name-or-directory-name}` +- **Plugin**: specweave-github +- **Directory**: github-task-splitter +- **Agent Name**: github-task-splitter + +**When to Use**: +- You need to distribute SpecWeave tasks across multiple GitHub repositories based on technology stack +- You want to analyze task dependencies across different services +- You need to create tracking issues in multiple repositories for a single increment +- You're managing a multi-repo architecture (monorepo, microservices, etc.) and need intelligent task distribution + +## Role +I analyze SpecWeave increments and intelligently distribute tasks across multiple repositories based on: +- Repository architecture (single, multi-repo, monorepo, parent) +- Task content and dependencies +- Team ownership +- Technology stack indicators + +## Core Capabilities + +### 1. Task Analysis +I examine each task to determine: +- Target repository/project +- Technology indicators (frontend, backend, database, etc.) +- Dependencies on other tasks +- Team ownership + +### 2. Repository Detection Patterns + +#### Frontend Indicators +- UI/UX components +- React, Vue, Angular mentions +- CSS, styling, design +- User interface, forms, buttons +- Browser, client-side + +#### Backend Indicators +- API, endpoints, routes +- Database, SQL, queries +- Authentication, authorization +- Server, middleware +- Business logic + +#### Infrastructure Indicators +- Deployment, CI/CD +- Docker, Kubernetes +- Monitoring, logging +- Security, SSL/TLS +- Cloud services (AWS, Azure, GCP) + +#### Shared/Common Indicators +- Types, interfaces, schemas +- Utilities, helpers +- Constants, configuration +- Shared models + +### 3. Task Splitting Strategies + +#### Strategy 1: Technology-Based +Split by technology stack: +``` +Frontend: T-001, T-002, T-005 +Backend: T-003, T-004, T-006 +Infrastructure: T-007, T-008 +``` + +#### Strategy 2: Feature-Based +Keep related features together: +``` +User Feature: T-001, T-002, T-003 → user-service +Cart Feature: T-004, T-005, T-006 → cart-service +``` + +#### Strategy 3: Layer-Based +Split by application layer: +``` +Presentation: T-001, T-002 +Business Logic: T-003, T-004 +Data Layer: T-005, T-006 +``` + +## Task Distribution Algorithm + +```typescript +function distributeTask(task: Task, config: RepoConfig): string { + // Priority 1: Explicit repository tags + if (task.tags?.includes('frontend')) return 'frontend'; + if (task.tags?.includes('backend')) return 'backend'; + + // Priority 2: Task ID naming convention + if (task.id.includes('-FE-')) return 'frontend'; + if (task.id.includes('-BE-')) return 'backend'; + if (task.id.includes('-INFRA-')) return 'infrastructure'; + + // Priority 3: Content analysis + const content = task.title + ' ' + task.description; + + if (hasFrontendKeywords(content)) return 'frontend'; + if (hasBackendKeywords(content)) return 'backend'; + if (hasInfraKeywords(content)) return 'infrastructure'; + + // Priority 4: Dependencies + const deps = resolveDependencies(task); + if (deps.majority === 'frontend') return 'frontend'; + + // Default + return config.defaultRepo || 'shared'; +} +``` + +## Output Format + +### Split Tasks Report +```markdown +# Task Distribution for Increment 0015-shopping-cart + +## Frontend Repository (my-app-frontend) +Total Tasks: 5 + +- [ ] T-001: Create CartItem component +- [ ] T-002: Implement cart state management +- [ ] T-005: Add cart UI with add/remove buttons +- [ ] T-008: Create cart animation effects +- [ ] T-011: Add cart icon to header + +## Backend Repository (my-app-backend) +Total Tasks: 4 + +- [ ] T-003: Create cart database schema +- [ ] T-004: Implement cart API endpoints +- [ ] T-006: Add cart validation logic +- [ ] T-009: Implement cart cleanup job + +## Shared Repository (my-app-shared) +Total Tasks: 2 + +- [ ] T-007: Define cart TypeScript types +- [ ] T-010: Create cart utility functions + +## Cross-Repository Dependencies +- T-002 depends on T-007 (shared types) +- T-005 depends on T-004 (API endpoints) +``` + +### GitHub Issue Creation +For each repository, I create a tracking issue: + +```markdown +# [FS-25-11-14] Shopping Cart - Frontend Tasks + +Part of increment 0015-shopping-cart (Feature: FS-25-11-14) + +## Tasks (5) +- [ ] T-001: Create CartItem component +- [ ] T-002: Implement cart state management +- [ ] T-005: Add cart UI with add/remove buttons +- [ ] T-008: Create cart animation effects +- [ ] T-011: Add cart icon to header + +## Dependencies +- Requires: T-007 from shared repo (types) +- Blocks: None + +## Links +- Parent Issue: org/parent-repo#15 +- Spec: `.specweave/increments/0015-shopping-cart/spec.md` +``` + +## Commands I Can Execute + +### 1. Analyze Increment +```bash +# Analyze task distribution for an increment +/analyze-distribution 0015-shopping-cart +``` + +### 2. Create Repository Issues +```bash +# Create GitHub issues in each repository +/create-repo-issues 0015-shopping-cart +``` + +### 3. Update Task Mapping +```bash +# Update task-repository mapping +/update-task-mapping T-001 frontend +``` + +## Best Practices + +### 1. Clear Task Descriptions +Write tasks with clear technology indicators: +- ✅ "Create React component for user profile" +- ❌ "Create component" (ambiguous) + +### 2. Use Task Tags +Add repository tags to tasks: +```markdown +T-001: Create user component #frontend +T-002: Create user API #backend +``` + +### 3. Document Dependencies +Make cross-repo dependencies explicit: +```markdown +T-005: Consume user API +Dependencies: T-002 (backend) must be complete +``` + +### 4. Maintain Mapping File +Keep a `.specweave/increments/{id}/repo-mapping.json`: +```json +{ + "T-001": "frontend", + "T-002": "frontend", + "T-003": "backend", + "T-004": "backend", + "T-005": "shared" +} +``` + +## Error Prevention + +### Common Mistakes +1. **Ambiguous tasks**: Use clear technology indicators +2. **Missing dependencies**: Always specify cross-repo deps +3. **Wrong repository**: Review distribution before creating issues +4. **Duplicate tasks**: Ensure tasks aren't duplicated across repos + +## Integration Points + +### With Other Agents +- **PM Agent**: Receives increment specification +- **Architect Agent**: Understands system architecture +- **Tech Lead Agent**: Reviews task distribution + +### With GitHub API +- Creates issues in multiple repositories +- Updates issue labels and milestones +- Links issues across repositories +- Tracks progress in GitHub Projects \ No newline at end of file diff --git a/agents/user-story-updater/AGENT.md b/agents/user-story-updater/AGENT.md new file mode 100644 index 0000000..1a2ad21 --- /dev/null +++ b/agents/user-story-updater/AGENT.md @@ -0,0 +1,173 @@ +--- +name: user-story-updater +description: Updates GitHub issues for user stories with proper ACs and tasks. Activates for update user story issue, fix GitHub issue format, add checkable ACs, refresh user story issue, sync user story to GitHub. +--- + +# User Story Updater Agent + +**Role**: Updates GitHub issues for individual user stories to include checkable acceptance criteria and task connections. + +## 🚀 How to Invoke This Agent + +**Subagent Type**: `specweave-github:user-story-updater:user-story-updater` + +**Usage Example**: + +```typescript +Task({ + subagent_type: "specweave-github:user-story-updater:user-story-updater", + prompt: "Update GitHub issue #501 for user story FS-031/US-004 with checkable ACs and task connections", + model: "haiku" // optional: haiku, sonnet, opus +}); +``` + +**Naming Convention**: `{plugin}:{directory}:{yaml-name-or-directory-name}` +- **Plugin**: specweave-github +- **Directory**: user-story-updater +- **Agent Name**: user-story-updater + +**When to Use**: +- You need to sync user story details from SpecWeave to GitHub issues +- You want to add checkable acceptance criteria checkboxes to GitHub issues +- You need to link tasks in SpecWeave tasks.md to GitHub issues +- You're updating GitHub issue content with the latest user story information and progress + +**Activates For**: +- "Update user story issue" +- "Fix GitHub issue format for US-004" +- "Add checkable ACs to GitHub issue" +- "Refresh user story issue #501" +- "Sync user story to GitHub" + +**Capabilities**: + +1. **Parse User Story Files** (`us-*.md` from living docs) + - Extract frontmatter (id, epic, status, priority) + - Parse user story description (As a... I want... So that...) + - Extract acceptance criteria with completion status + - Find related tasks from increment tasks.md + +2. **Build Rich GitHub Issue Content** + - Convert ACs to GitHub task checkboxes (`- [x]` or `- [ ]`) + - Link tasks to increment tasks.md with anchors + - Calculate progress percentages + - Format with proper sections + +3. **Update Existing Issues** + - Search for existing issue by title pattern + - Replace issue body with new formatted content + - Preserve issue number and URL + +**Tools You Have**: +- `Read` - Read user story files and tasks.md +- `Bash` - Execute `gh` CLI commands +- `Write` - Create TypeScript if needed + +**Workflow**: + +When user says "update user story issue for FS-031/US-004": + +```typescript +// 1. Find user story file +const projectRoot = process.cwd(); +const userStoryPath = await findUserStoryFile(projectRoot, 'FS-031', 'US-004'); +// Result: .specweave/docs/internal/specs/default/FS-031/us-004-bidirectional-status-sync.md + +// 2. Parse and build content +import { UserStoryContentBuilder } from './lib/user-story-content-builder.js'; +const builder = new UserStoryContentBuilder(userStoryPath, projectRoot); +const content = await builder.parse(); +const issueBody = await builder.buildIssueBody(); + +// 3. Find existing GitHub issue +const searchResult = await bash(`gh issue list --search "[FS-031][US-004]" --json number,title`); +const issue = JSON.parse(searchResult)[0]; + +// 4. Update issue +await bash(`gh issue edit ${issue.number} --body "${issueBody}"`); + +// 5. Report success +console.log(`✅ Updated issue #${issue.number}`); +console.log(`🔗 https://github.com/owner/repo/issues/${issue.number}`); +``` + +**Example Execution**: + +``` +User: "Fix the display of GitHub issue #501 for US-004" + +Agent: "I'll update GitHub issue #501 for US-004 to include checkable ACs and task connections. + +🔍 Finding user story: FS-031/US-004 + 📄 Found: .specweave/docs/internal/specs/default/FS-031/us-004-bidirectional-status-sync.md + +📖 Parsing content... + ✅ User story description: As a PM, I want status changes... + ✅ 6 acceptance criteria (4 completed, 2 pending) + ✅ 6 tasks linked from increment 0031 + +📝 Building issue body... + ✅ ACs converted to checkboxes + ✅ Tasks linked to tasks.md + ✅ Progress calculated: 67% ACs, 50% tasks + +🚀 Updating GitHub issue #501... + [gh issue edit 501 --body "..."] + ✅ Updated successfully! + +🔗 View issue: https://github.com/anton-abyzov/specweave/issues/501 +``` + +**Key Implementation Details**: + +1. **Find User Story File**: + ```bash + # Search in all projects + find .specweave/docs/internal/specs -name "us-004-*.md" -path "*/FS-031/*" + ``` + +2. **Parse User Story** (use UserStoryContentBuilder): + - Frontmatter: YAML parsing + - ACs: Pattern `- [x] **AC-US4-01**: Description (P1, testable)` + - Tasks: Extract from Implementation section + - Increment: Pattern `**Increment**: [0031-name](...)` + +3. **Build Issue Body**: + - See UserStoryContentBuilder.buildIssueBody() + - Sections: User Story, Acceptance Criteria, Implementation Tasks + - Checkboxes: `- [x]` for completed, `- [ ]` for pending + - Links: Relative to repository root + +4. **Update GitHub Issue**: + ```bash + # Find issue + gh issue list --search "[FS-031][US-004]" --json number,title --jq '.[0].number' + + # Update body + gh issue edit 501 --body "$(cat body.md)" + ``` + +**Error Handling**: + +- ✅ User story file not found → Search all projects, suggest alternatives +- ✅ GitHub issue not found → Offer to create new issue +- ✅ Missing frontmatter → Graceful fallback with warnings +- ✅ No tasks found → Show "No tasks defined yet" + +**Related Files**: +- `plugins/specweave-github/lib/user-story-content-builder.ts` - Core builder class +- `plugins/specweave-github/commands/specweave-github-update-user-story.md` - Command spec +- `.specweave/docs/internal/specs/{project}/FS-*/us-*.md` - User story files + +**Testing**: +1. Read user story file: `us-004-bidirectional-status-sync.md` +2. Use UserStoryContentBuilder to parse +3. Build issue body +4. Update issue #501 +5. Verify checkable ACs and task links work + +**Success Criteria**: +- ✅ GitHub issue has checkable ACs (can check/uncheck in UI) +- ✅ Tasks link to correct increment tasks.md sections +- ✅ Progress percentages match reality +- ✅ User story description formatted correctly diff --git a/commands/specweave-github-cleanup-duplicates.md b/commands/specweave-github-cleanup-duplicates.md new file mode 100644 index 0000000..d795377 --- /dev/null +++ b/commands/specweave-github-cleanup-duplicates.md @@ -0,0 +1,230 @@ +--- +name: specweave-github:cleanup-duplicates +description: Clean up duplicate GitHub issues for a Feature. Finds issues with duplicate titles and closes all except the first created issue. +justification: | + CRITICAL INCIDENT RESPONSE TOOL - DO NOT DELETE! + + Why This Command Exists: + - Prevention systems (deduplication, GitHub self-healing) work for single-process execution + - Multiple parallel Claude Code instances bypass all prevention (file-based cache, no distributed locking) + - GitHub API race conditions: Time gap between "check exists" and "create issue" allows duplicates + - Historical duplicates from pre-v0.14.1 users (before prevention was added) + + Evidence of Need: + - 2025-11-13: 123 duplicate GitHub issues incident (cleaned to 29 unique) + - Parallel execution creates race conditions that prevention CANNOT solve + - Industry standard: Prevention + Detection + Cleanup (defense in depth) + + When to Delete: + - ONLY if distributed locking implemented (Redis/file locks) + - AND parallel execution tested (100+ concurrent syncs with zero duplicates) + - AND zero duplicates for 6+ months in production + - AND all users migrated to prevention-enabled versions + + See: .specweave/increments/0043-spec-md-desync-fix/reports/ULTRATHINK-CLEANUP-DUPLICATES-NECESSITY-2025-11-18.md +--- + +# Clean Up Duplicate GitHub Issues + +**CRITICAL**: This command detects and closes duplicate GitHub issues created by multiple syncs. + +## Usage + +```bash +/specweave-github:cleanup-duplicates [--dry-run] +``` + +## What It Does + +**Duplicate Detection & Cleanup**: + +1. **Find all issues** for the Epic (searches by Epic ID in title) +2. **Group by title** (detect duplicates) +3. **For each duplicate group**: + - Keep the **FIRST created** issue (lowest number) + - Close all **LATER** issues with comment: "Duplicate of #XXX" +4. **Update Epic README** with correct issue numbers + +## Examples + +### Dry Run (No Changes) + +```bash +/specweave-github:cleanup-duplicates FS-031 --dry-run +``` + +**Output**: +``` +🔍 Scanning for duplicates in Epic FS-031... + Found 25 total issues + Detected 10 duplicate groups: + + 📋 Group 1: "[FS-031] External Tool Status Synchronization" + - #250 (KEEP) - Created 2025-11-10 + - #255 (CLOSE) - Created 2025-11-11 - DUPLICATE + - #260 (CLOSE) - Created 2025-11-12 - DUPLICATE + + 📋 Group 2: "[FS-031] Multi-Project GitHub Sync" + - #251 (KEEP) - Created 2025-11-10 + - #256 (CLOSE) - Created 2025-11-11 - DUPLICATE + + ... + +✅ Dry run complete! + Total issues: 25 + Duplicate groups: 10 + Issues to close: 15 + +⚠️ This was a DRY RUN - no changes made. + Run without --dry-run to actually close duplicates. +``` + +### Actual Cleanup + +```bash +/specweave-github:cleanup-duplicates FS-031 +``` + +**Output**: +``` +🔍 Scanning for duplicates in Epic FS-031... + Found 25 total issues + Detected 10 duplicate groups + +⚠️ CONFIRM: Close 15 duplicate issues? [y/N] +> y + +🗑️ Closing duplicates... + ✅ Closed #255 (duplicate of #250) + ✅ Closed #256 (duplicate of #251) + ✅ Closed #260 (duplicate of #250) + ... + +📝 Updating Epic README frontmatter... + ✅ Updated frontmatter with correct issue numbers + +✅ Cleanup complete! + Closed: 15 duplicates + Kept: 10 original issues +``` + +## Arguments + +- `` - Epic ID (e.g., `FS-031` or just `031`) +- `--dry-run` - Preview changes without actually closing issues (optional) + +## Safety Features + +✅ **Confirmation prompt**: Asks before closing issues (unless --dry-run) +✅ **Dry run mode**: Preview changes safely +✅ **Keeps oldest issue**: Preserves the first created issue +✅ **Adds closure comment**: Links to the original issue +✅ **Updates metadata**: Fixes Epic README frontmatter + +## What Gets Closed + +**Closed issues**: +- ✅ Duplicate titles (second, third, etc. occurrences) +- ✅ Closed with comment: "Duplicate of #XXX" +- ✅ Original issue kept open (or maintains its status) + +**Example comment on closed duplicate**: +```markdown +Duplicate of #250 + +This issue was automatically closed by SpecWeave cleanup because it is a duplicate. + +The original issue (#250) contains the same content and should be used for tracking instead. + +🤖 Auto-closed by SpecWeave Duplicate Cleanup +``` + +## Requirements + +1. **GitHub CLI** (`gh`) installed and authenticated +2. **Write access** to repository (for closing issues) +3. **Epic folder exists** at `.specweave/docs/internal/specs/FS-XXX-name/` + +## When to Use + +**Use this command when**: +- ✅ You see multiple issues with the same title in GitHub +- ✅ Epic sync ran multiple times and created duplicates +- ✅ Epic README frontmatter got corrupted and reset +- ✅ Post-sync validation warns about duplicates + +**Example warning that triggers this**: +``` +⚠️ WARNING: 10 duplicate(s) detected! + Run cleanup command to resolve: + /specweave-github:cleanup-duplicates FS-031 +``` + +## Troubleshooting + +**"No duplicates found"**: +- Good! Your Epic has no duplicate issues +- Run epic sync is working correctly with duplicate detection + +**"GitHub CLI not authenticated"**: +- Run: `gh auth login` +- Ensure you have write access to the repository + +**"Could not find Epic folder"**: +- Check Epic exists: `ls .specweave/docs/internal/specs/` +- Verify Epic ID format: `FS-031-epic-name/` + +**"Error closing issue"**: +- Check GitHub CLI: `gh auth status` +- Verify write permissions: `gh repo view` + +## Architecture + +**Duplicate Detection Logic**: +1. Group issues by **exact title match** +2. Within each group, sort by **issue number** (ascending) +3. Keep **first issue** (lowest number = oldest) +4. Close **all others** as duplicates + +**Why lowest number?**: +- Lower issue numbers were created first +- Preserves chronological order +- Maintains links from old documentation + +## Related Commands + +- `/specweave-github:sync` - Sync Feature to GitHub (with duplicate detection) +- `/specweave:validate` - Validate increment completeness +- `gh issue list` - View all issues (GitHub CLI) + +## Implementation + +**File**: `plugins/specweave-github/lib/duplicate-detector.ts` + +**Class**: `DuplicateDetector` + +**Algorithm** (3-phase protection): +1. **Detection**: Search GitHub for existing issues matching pattern +2. **Verification**: Count check to detect duplicates after creation +3. **Reflection**: Auto-close duplicates automatically + +For manual cleanup: +1. Search GitHub for all issues with Feature ID +2. Group by title (Map) +3. Filter groups with >1 issue (duplicates) +4. For each duplicate group: + - Keep first issue (lowest number) + - Close others with gh CLI + +## Next Steps + +After cleanup: + +1. **Verify cleanup**: `gh issue list --search "[FS-031]"` +2. **Check Feature FEATURE.md**: Verify frontmatter has correct issue numbers +3. **Re-run sync**: `/specweave-github:sync` (should show no duplicates) +4. **Duplicate detection**: Automatically enabled via DuplicateDetector + +--- + +**✅ SAFE TO USE**: This command is idempotent and safe to run multiple times. diff --git a/commands/specweave-github-close-issue.md b/commands/specweave-github-close-issue.md new file mode 100644 index 0000000..55a628d --- /dev/null +++ b/commands/specweave-github-close-issue.md @@ -0,0 +1,418 @@ +--- +name: specweave-github:close-issue +description: Close GitHub issue for completed SpecWeave increment. Posts completion summary with final stats, deliverables, and closes the issue. Links closure in increment metadata. +--- + +# Close GitHub Issue for Completed Increment + +Close the GitHub issue associated with a completed SpecWeave increment. + +## Usage + +```bash +/specweave:github:close-issue [options] +``` + +## Arguments + +- `increment-id`: Increment ID (e.g., `0004` or `0004-plugin-architecture`) + +## Options + +- `--force`: Force close even if increment not marked complete +- `--comment`: Custom closing comment (default: auto-generated summary) +- `--reopen`: Reopen a previously closed issue +- `--skip-validation`: Skip PM gate validation + +## Examples + +```bash +# Basic usage (auto-generates completion summary) +/specweave:github:close-issue 0004 + +# With custom comment +/specweave:github:close-issue 0004 --comment "Merged to main, deploying to production" + +# Force close (skip validation) +/specweave:github:close-issue 0004 --force + +# Reopen closed issue +/specweave:github:close-issue 0004 --reopen +``` + +## What This Command Does + +1. **Validates Increment Completion** + - All tasks completed (48/48) + - All tests passing + - PM gates passed (from `/specweave:done`) + - Documentation updated + +2. **Generates Completion Summary** + ```markdown + ✅ **Increment Completed** + + This increment has been successfully completed and is ready for release. + + ## Final Stats + + - **Tasks**: 48/48 completed (100%) + - **Duration**: 4 weeks (2025-10-01 → 2025-10-30) + - **Time Tracked**: 240 hours (estimated) / 235 hours (actual) + - **Test Coverage**: 127 test cases, 95% coverage + - **Priority**: P1 + + ## Deliverables + + ✅ Plugin architecture implemented + ✅ 15 plugins migrated (github, kubernetes, frontend-stack, ...) + ✅ Documentation updated (ADRs, user guides, API docs) + ✅ E2E tests passing (Playwright suite) + ✅ Integration tests passing (Jest suite) + + ## Key Changes + + - Added plugin system with loader, manager, detector + - Implemented 4 adapters (Claude, Cursor, Copilot, Generic) + - Created 15 domain-specific plugins + - Updated all documentation + - Achieved 80% test coverage + + ## Files Changed + + - 48 files modified + - +12,500 lines added + - -3,200 lines removed + - Net: +9,300 lines + + ## Related + + - **Spec**: [spec.md](https://github.com/owner/repo/blob/main/.specweave/increments/0004/spec.md) + - **Plan**: [plan.md](https://github.com/owner/repo/blob/main/.specweave/increments/0004/plan.md) + - **Tests**: [tests.md](https://github.com/owner/repo/blob/main/.specweave/increments/0004/tests.md) + + ## Next Steps + + - Deploy to production (tracked in #135) + - Monitor for issues (see runbook) + - Plan next increment (0005-user-authentication) + + --- + + 🎉 Thank you to all contributors! + + 🤖 Auto-closed by SpecWeave at 2025-10-30 17:00:00 + ``` + +3. **Posts Completion Comment** + ```bash + gh issue comment 130 --body "$(cat completion-summary.md)" + ``` + +4. **Closes GitHub Issue** + ```bash + gh issue close 130 + ``` + +5. **Updates Metadata** + ```yaml + # .metadata.yaml + github: + issue_number: 130 + issue_url: "https://github.com/owner/repo/issues/130" + closed_at: "2025-10-30T17:00:00Z" + closed_by: "specweave-github-plugin" + closing_comment_id: 1234590 + ``` + +6. **Reports Result** + ``` + ✅ GitHub issue #130 closed! + + Increment 0004 is complete. + Issue: https://github.com/owner/repo/issues/130 (closed) + ``` + +## Configuration + +Settings from `.specweave/config.yaml`: + +```yaml +plugins: + settings: + specweave-github: + # Auto-close issues when increment completes + auto_close_issue: true + + # Validate before closing + require_validation: true + + # Include in closing comment + closing_comment: + include_stats: true + include_deliverables: true + include_file_changes: true + include_next_steps: true +``` + +## Output Format + +### Success + +``` +🔒 Closing GitHub issue for increment 0004... + +Validation: +✓ All tasks completed (48/48) +✓ All tests passing (127/127) +✓ PM gates passed +✓ Documentation updated + +Generating completion summary... +✓ Final stats calculated +✓ Deliverables listed +✓ File changes summarized + +Closing issue... +✓ Posted completion comment (ID: 1234590) +✓ Issue #130 closed +✓ Metadata updated + +✅ GitHub Issue Closed! + +Issue #130: https://github.com/owner/repo/issues/130 +Status: Closed +Closed at: 2025-10-30 17:00:00 + +Increment 0004 is complete! 🎉 +``` + +### Validation Failure + +``` +❌ Cannot close issue: Validation failed + +Increment 0004 is not yet complete: + +Issues: +✗ Tasks: 45/48 completed (3 remaining) + - T-046: Update documentation + - T-047: Run E2E tests + - T-048: Final review + +✗ Tests: 2 tests failing + - TC-105: Plugin unload test + - TC-127: E2E sync test + +✗ PM Gates: Not run yet + - Run /specweave:done 0004 first + +Fix these issues, then retry: + /specweave:github:close-issue 0004 + +Or force close (not recommended): + /specweave:github:close-issue 0004 --force +``` + +## Requirements + +- GitHub CLI (`gh`) installed and authenticated +- Increment marked as complete (via `/specweave:done`) +- Valid GitHub issue exists for increment + +## Error Handling + +**Increment not complete**: +``` +❌ Error: Increment 0004 is not complete + +Status: in_progress (should be: completed) + +Complete the increment first: + /specweave:done 0004 + +Then close the issue: + /specweave:github:close-issue 0004 +``` + +**Issue not found**: +``` +❌ Error: No GitHub issue found for increment 0004 + +Check .metadata.yaml for issue number. + +Create issue first: + /specweave:github:create-issue 0004 +``` + +**Issue already closed**: +``` +ℹ️ Issue #130 is already closed + +Closed by: @developer1 +Closed at: 2025-10-30 16:00:00 + +Use --reopen to reopen the issue. +``` + +**Permission denied**: +``` +❌ Error: Insufficient permissions to close issue #130 + +Required: Write or Admin access to repository + +Contact repository admin for access. +``` + +## Related Commands + +- `/specweave:done `: Mark increment complete (run this first) +- `/specweave:github:sync `: Sync final progress before closing +- `/specweave:github:status `: Check issue status + +## Tips + +1. **Auto-Close**: Enable `auto_close_issue: true` for automatic closing when running `/specweave:done` + +2. **Final Sync**: Always run `/specweave:github:sync` before closing to ensure latest progress is posted + +3. **Validation**: Don't skip validation (`--force`) unless absolutely necessary - it ensures quality + +4. **Custom Comments**: Use `--comment` for release-specific notes (deployment status, known issues, etc.) + +5. **Reopening**: If increment needs more work after closing, use `--reopen` to reopen the issue + +## Advanced + +### Custom Closing Template + +Create `.specweave/github/closing-template.md`: + +```markdown +# 🎉 Increment {{id}} Completed! + +{{summary}} + +## Achievements + +{{deliverables}} + +## Stats + +- Duration: {{duration}} +- Team size: {{team_size}} +- Commits: {{commit_count}} + +## Deployment + +- Merged to: {{branch}} +- Deployed to: {{environment}} +- Release: {{version}} + +## Thank You + +Special thanks to: +{{contributors}} + +--- + +_Closed by SpecWeave on {{date}}_ +``` + +### Conditional Closing + +Close only if specific conditions met: + +```yaml +plugins: + settings: + specweave-github: + closing_conditions: + # Require all tests passing + - type: "tests" + threshold: 100 + required: true + + # Require coverage >= 80% + - type: "coverage" + threshold: 80 + required: true + + # Require PR merged + - type: "pr_merged" + required: true + + # Require approval from tech lead + - type: "approval" + approvers: ["@tech-lead"] + required: true +``` + +### Post-Closing Actions + +Trigger actions after closing: + +```yaml +plugins: + settings: + specweave-github: + post_close: + # Create release tag + - action: "create_tag" + format: "increment-{{id}}" + + # Trigger deployment + - action: "github_workflow" + workflow: "deploy.yml" + inputs: + increment: "{{id}}" + + # Notify team + - action: "slack_notification" + channel: "#releases" + message: "Increment {{id}} completed! 🎉" + + # Archive to notion + - action: "notion_export" + database: "Completed Increments" +``` + +### Bulk Close + +Close multiple completed increments: + +```bash +# Close all completed increments +/specweave:github:close-issue --status completed --all + +# Close specific increments +for i in 0004 0005 0006; do + /specweave:github:close-issue $i +done +``` + +### Reopen with Context + +Reopen issue with explanation: + +```bash +/specweave:github:close-issue 0004 --reopen \ + --comment "Reopening: Critical bug found in production (issue #140). Need to add rollback mechanism." +``` + +### Close and Lock + +Close and lock issue to prevent further comments: + +```bash +/specweave:github:close-issue 0004 --lock \ + --lock-reason "resolved" # or "off-topic", "spam", "too heated" +``` + +--- + +**Command**: `/specweave:github:close-issue` +**Plugin**: specweave-github +**Agent**: github-manager +**Version**: 1.0.0 +**Last Updated**: 2025-10-30 diff --git a/commands/specweave-github-create-issue.md b/commands/specweave-github-create-issue.md new file mode 100644 index 0000000..4ed8730 --- /dev/null +++ b/commands/specweave-github-create-issue.md @@ -0,0 +1,307 @@ +--- +name: specweave-github:create-issue +description: Create a GitHub issue for a SpecWeave increment. Generates issue from increment specs with task checklist, labels, and milestone. Links issue to increment metadata. +--- + +# Create GitHub Issue from Increment + +Create a GitHub issue for the specified SpecWeave increment. + +## Usage + +```bash +/specweave:github:create-issue [options] +``` + +## Arguments + +- `increment-id`: Increment ID (e.g., `0004` or `0004-plugin-architecture`) + +## Options + +- `--force`: Force create even if issue already exists +- `--labels`: Comma-separated labels (default: from config) +- `--milestone`: Milestone name (default: from config) +- `--assignee`: Assign to user (@username) +- `--project`: Add to GitHub project (project number) + +## Examples + +```bash +# Basic usage +/specweave:github:create-issue 0004 + +# With custom labels +/specweave:github:create-issue 0004 --labels "urgent,backend" + +# Assign to developer +/specweave:github:create-issue 0004 --assignee @developer1 + +# Add to project +/specweave:github:create-issue 0004 --project 3 + +# Force recreate +/specweave:github:create-issue 0004 --force +``` + +## What This Command Does + +1. **Loads Increment** + - Reads `.specweave/increments//` + - Parses `spec.md`, `plan.md`, `tasks.md` + - Checks `.metadata.yaml` for existing issue + +2. **Detects Repository** + - Extracts repo from git remote + - Format: `owner/repo` + - Verifies write permissions + +3. **Generates Issue Body** + - Executive summary from `spec.md` + - Task checklist from `tasks.md` + - Progress tracker (0% initially) + - Links to increment files + +4. **Creates GitHub Issue** (via GitHub CLI) + - Uses `gh issue create` + - Applies labels (specweave, increment, priority) + - Sets milestone (if configured) + - Assigns to user (if specified) + +5. **Updates Metadata** + - Saves issue number to `.metadata.yaml` + - Stores issue URL + - Logs creation timestamp + +6. **Reports Result** + - Issue number and URL + - Labels applied + - Milestone set + - Auto-sync status + +## Requirements + +- GitHub CLI (`gh`) installed and authenticated +- Write access to repository +- Valid increment directory + +## Configuration + +Settings from `.specweave/config.yaml`: + +```yaml +plugins: + settings: + specweave-github: + repo: "owner/repo" # Auto-detected from git remote + default_labels: + - "specweave" + - "increment" + milestone: "v0.4.0" # Optional +``` + +## Error Handling + +**Increment not found**: +``` +❌ Error: Increment '0004' not found + +Check: ls .specweave/increments/ +``` + +**Issue already exists**: +``` +⚠️ GitHub issue already exists for increment 0004 + +Issue #130: https://github.com/owner/repo/issues/130 + +Use --force to recreate (will close existing issue first). +``` + +**GitHub CLI not authenticated**: +``` +❌ Error: GitHub CLI not authenticated + +Please run: gh auth login + +Then retry this command. +``` + +**No write permissions**: +``` +❌ Error: Insufficient permissions + +Required: Write access to owner/repo + +Contact repository admin to request access. +``` + +## Implementation + +This command invokes the `github-manager` agent via the Task tool: + +```typescript +const agent = new TaskAgent('github-manager', { + prompt: `Create GitHub issue for increment ${incrementId}`, + context: { + incrementPath: `.specweave/increments/${incrementId}`, + options: { force, labels, milestone, assignee, project } + } +}); + +await agent.execute(); +``` + +The agent handles: +- File reading (spec.md, tasks.md) +- GitHub API calls (via `gh` CLI) +- Metadata updates +- Error handling + +## Output Format + +### Success + +``` +📦 Creating GitHub issue for increment 0004... + +✓ Increment loaded: 0004-plugin-architecture +✓ Repository detected: owner/repo +✓ Issue body generated (2,500 characters) + +Creating issue... +✓ Issue #130 created +✓ Labels applied: specweave, increment, P1 +✓ Milestone set: v0.4.0 +✓ Metadata updated + +✅ GitHub Issue Created! (❌ DEPRECATED FORMAT) + +Issue #130: [Increment 0004] Plugin Architecture # ❌ DEPRECATED +URL: https://github.com/owner/repo/issues/130 + +Auto-sync enabled: progress will update automatically after each task. +``` + +### Failure + +``` +❌ Failed to create GitHub issue + +Error: API rate limit exceeded +Rate limit resets at: 2025-10-30 15:30:00 + +Options: +1. Wait 30 minutes +2. Use authenticated token (higher limit) + +Run /specweave:github:status 0004 to check sync state. +``` + +## Related Commands + +- `/specweave:github:sync `: Update existing issue +- `/specweave:github:close-issue `: Close issue +- `/specweave:github:status `: Check sync status + +## Tips + +1. **Auto-Create**: Enable `auto_create_issue: true` in config to auto-create issues when running `/specweave:inc` + +2. **Templates**: Customize issue template in `.specweave/github/issue-template.md` + +3. **Labels**: Use labels for filtering in GitHub Projects: + - `specweave`: All SpecWeave increments + - `increment`: Differentiate from regular issues + - `P0`/`P1`/`P2`/`P3`: Priority levels + +4. **Milestones**: Group increments by release milestone for progress tracking + +5. **Projects**: Add issues to GitHub Projects for Kanban-style tracking + +## Advanced + +### Custom Issue Body Template + +Create `.specweave/github/issue-template.md`: + +```markdown +# [Increment {{id}}] {{title}} + +{{summary}} + +## Details + +- **Spec**: [spec.md]({{spec_url}}) +- **Priority**: {{priority}} +- **Duration**: {{duration}} + +## Tasks + +{{tasks}} + +--- + +_Auto-created by SpecWeave_ +``` + +### Bulk Create + +Create issues for multiple increments: + +```bash +for i in 0004 0005 0006; do + /specweave:github:create-issue $i +done +``` + +Or using a script: + +```bash +# Create issues for all increments in backlog +ls .specweave/increments/_backlog/ | while read inc; do + /specweave:github:create-issue $inc +done +``` + +### Dry Run + +Preview issue body before creating: + +```bash +/specweave:github:create-issue 0004 --dry-run +``` + +Output: +``` +📄 Preview: Issue body for increment 0004 (❌ DEPRECATED FORMAT) + +Title: [Increment 0004] Plugin Architecture # ❌ DEPRECATED +Labels: specweave, increment, P1 +Milestone: v0.4.0 + +Body: +--- +# [Increment 0004] Plugin Architecture # ❌ DEPRECATED + +**Status**: Planning +**Priority**: P1 + +## Executive Summary + +Implement a modular plugin architecture for SpecWeave... + +[... full body ...] + +--- + +Run without --dry-run to create this issue. +``` + +--- + +**Command**: `/specweave:github:create-issue` +**Plugin**: specweave-github +**Agent**: github-manager +**Version**: 1.0.0 +**Last Updated**: 2025-10-30 diff --git a/commands/specweave-github-reconcile.md b/commands/specweave-github-reconcile.md new file mode 100644 index 0000000..d21da1c --- /dev/null +++ b/commands/specweave-github-reconcile.md @@ -0,0 +1,110 @@ +--- +name: specweave-github:reconcile +description: Reconcile GitHub issue states with increment statuses. Fixes drift by closing issues for completed increments and reopening issues for resumed increments. +--- + +# GitHub Status Reconciliation + +Scan all increments and fix any drift between local metadata.json status and GitHub issue states. + +## Usage + +```bash +/specweave-github:reconcile [options] +``` + +## Options + +- `--dry-run`: Preview changes without making them +- `--verbose`: Show detailed output for each issue checked + +## What It Does + +1. **Scans** all non-archived increments +2. **Compares** metadata.json status with GitHub issue state +3. **Fixes** mismatches: + - `metadata=completed` + `GH=open` → **Close** the issue + - `metadata=in-progress` + `GH=closed` → **Reopen** the issue + +## When to Use + +- After manual metadata.json edits +- After git pulls that changed increment statuses +- When you notice open issues for completed work +- As a periodic health check + +## Implementation + +Run the reconciliation using the GitHubReconciler: + +```typescript +import { GitHubReconciler } from '../../../src/sync/github-reconciler.js'; + +const reconciler = new GitHubReconciler({ + projectRoot: process.cwd(), + dryRun: args.includes('--dry-run'), +}); + +const result = await reconciler.reconcile(); + +// Report results +console.log(`\nReconciliation complete:`); +console.log(` Scanned: ${result.scanned} increments`); +console.log(` Fixed: ${result.closed} closed, ${result.reopened} reopened`); +if (result.errors.length > 0) { + console.log(` Errors: ${result.errors.length}`); +} +``` + +## Example Output + +``` +📊 Scanning 5 increment(s) for GitHub state drift... + + ✅ Issue #765 (0056-plugin-fix/US-001): State matches (open) + ❌ Issue #771 (0066-import-wizard/US-003): OPEN but should be CLOSED (status=completed) + ✅ Closed issue #771 + ❌ Issue #763 (0063-multi-repo/US-001): CLOSED but should be OPEN (status=in-progress) + ✅ Reopened issue #763 + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +📊 RECONCILIATION SUMMARY +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Increments scanned: 5 + Mismatches found: 2 + Issues closed: 1 + Issues reopened: 1 + Errors: 0 +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## Dry Run Mode + +```bash +/specweave-github:reconcile --dry-run +``` + +Shows what would be changed without making any modifications: + +``` + ❌ Issue #771 (0066-import-wizard/US-003): OPEN but should be CLOSED + [DRY RUN] Would close issue #771 + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +📊 RECONCILIATION SUMMARY + ⚠️ DRY RUN - No changes were made +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## Requirements + +- GitHub CLI (`gh`) installed and authenticated +- `sync.github.enabled = true` in config.json +- `sync.settings.canUpdateExternalItems = true` in config.json + +## Related Commands + +- `/specweave-github:status`: View sync status for increments +- `/specweave-github:sync`: Manual sync to GitHub +- `/specweave:done`: Close increment (triggers auto-close) +- `/specweave:resume`: Resume increment (now triggers auto-reopen) diff --git a/commands/specweave-github-status.md b/commands/specweave-github-status.md new file mode 100644 index 0000000..fda327b --- /dev/null +++ b/commands/specweave-github-status.md @@ -0,0 +1,533 @@ +--- +name: specweave-github:status +description: Check GitHub sync status for SpecWeave increment. Shows issue number, sync state, progress, last update, and any sync issues. Useful for troubleshooting and monitoring. +--- + +# Check GitHub Sync Status + +Display the current GitHub sync status for a SpecWeave increment. + +## Usage + +```bash +/specweave:github:status [increment-id] [options] +``` + +## Arguments + +- `increment-id`: Increment ID (optional, defaults to current increment) + +## Options + +- `--all`: Show status for all increments +- `--verbose`: Show detailed sync information +- `--json`: Output in JSON format +- `--check-health`: Run health check on sync connection + +## Examples + +```bash +# Check current increment +/specweave:github:status + +# Check specific increment +/specweave:github:status 0004 + +# Check all increments +/specweave:github:status --all + +# Verbose output with full details +/specweave:github:status 0004 --verbose + +# JSON output for scripting +/specweave:github:status 0004 --json + +# Health check +/specweave:github:status --check-health +``` + +## Output Format + +### Basic Status + +``` +📊 GitHub Sync Status: Increment 0004 + +Increment: 0004-plugin-architecture +Status: In Progress +Priority: P1 + +GitHub Issue: #130 +URL: https://github.com/owner/repo/issues/130 +State: Open +Labels: specweave, increment, P1, in-progress + +Sync Status: ✅ Up-to-date +Last Synced: 5 minutes ago (2025-10-30 16:55:00) +Sync Count: 7 +Auto-Sync: Enabled (every-task) + +Progress: +- Tasks: 7/48 completed (15%) +- Week: 1 of 4 (Foundation) +- Current Task: T-008 - Implement Cursor compiler + +GitHub vs Local: +✅ Progress matches +✅ Labels match +✅ Status matches +✅ No conflicts detected +``` + +### Verbose Status + +``` +📊 GitHub Sync Status: Increment 0004 (Detailed) + +═══════════════════════════════════════════ +BASIC INFO +═══════════════════════════════════════════ + +Increment ID: 0004 +Full Name: 0004-plugin-architecture +Title: Plugin Architecture +Status: in_progress +Priority: P1 +Created: 2025-10-01 10:00:00 +Duration: 29 days + +═══════════════════════════════════════════ +GITHUB ISSUE +═══════════════════════════════════════════ + +Issue Number: #130 +Issue URL: https://github.com/owner/repo/issues/130 +Issue State: open +Issue Created: 2025-10-01 10:15:00 +Issue Updated: 2025-10-30 16:55:00 + +Labels: +- specweave +- increment +- P1 +- in-progress + +Milestone: v0.4.0 (due: 2025-11-30) +Assignees: @developer1, @developer2 + +Comments: 12 +- 7 auto-sync comments +- 5 manual comments + +Last Comment: + By: @developer2 + At: 2025-10-30 16:00:00 + Text: "Cursor adapter completed, moving to testing..." + +═══════════════════════════════════════════ +SYNC STATUS +═══════════════════════════════════════════ + +Sync State: ✅ Up-to-date +Last Synced: 5 minutes ago (2025-10-30 16:55:00) +Sync Method: Auto (post-task hook) +Sync Count: 7 +Failed Syncs: 0 + +Auto-Sync Settings: +- Enabled: Yes +- Frequency: every-task +- Post Comments: Yes +- Update Checklist: Yes +- Update Labels: Yes +- Include Files: Yes +- Include Time: Yes + +═══════════════════════════════════════════ +PROGRESS +═══════════════════════════════════════════ + +Tasks: 7/48 completed (15%) + +Week 1: Foundation (7/12 tasks, 58%) + ✅ T-001: Plugin types + ✅ T-002: Manifest schema + ✅ T-003: PluginLoader + ✅ T-004: PluginManager + ✅ T-005: PluginDetector + ✅ T-006: Adapter interface + ✅ T-007: Claude installer + ⏳ T-008: Cursor compiler (in progress) + ⏸️ T-009: Copilot compiler + ⏸️ T-010: Generic compiler + ⏸️ T-011: Config schema + ⏸️ T-012: Update .gitignore + +Week 2: GitHub Plugin (0/10 tasks, 0%) +Week 3: Additional Plugins (0/15 tasks, 0%) +Week 4: Documentation (0/11 tasks, 0%) + +Current Task: T-008 +Estimated: 6 hours +Started: 2025-10-30 15:00:00 +Duration: 2 hours (33% of estimate) + +═══════════════════════════════════════════ +COMPARISON (GitHub vs Local) +═══════════════════════════════════════════ + +✅ Progress: 7/48 (both sides match) +✅ Labels: All 4 labels match +✅ Status: in_progress (both sides) +✅ Comments: All synced (no missing) + +No conflicts detected. +Last comparison: Just now + +═══════════════════════════════════════════ +METADATA +═══════════════════════════════════════════ + +Metadata File: .specweave/increments/0004/.metadata.yaml +GitHub Section: + issue_number: 130 + issue_url: https://github.com/owner/repo/issues/130 + created_at: 2025-10-01T10:15:00Z + last_synced_at: 2025-10-30T16:55:00Z + sync_count: 7 + closing_comment_ids: [] + +Repository: owner/repo +Remote URL: https://github.com/owner/repo.git +Branch: features/0004-plugin-architecture + +═══════════════════════════════════════════ +HEALTH +═══════════════════════════════════════════ + +✅ GitHub CLI: Authenticated +✅ Repository Access: Write +✅ Issue Exists: Yes +✅ Network: Connected +✅ Rate Limit: 4,823 / 5,000 remaining +✅ Sync Hook: Installed and working + +All systems operational. +``` + +### Status for All Increments + +``` +📊 GitHub Sync Status: All Increments + +┌──────┬────────────────┬────────┬────────┬──────────┬─────────────┐ +│ ID │ Title │ Issue │ State │ Progress │ Last Synced │ +├──────┼────────────────┼────────┼────────┼──────────┼─────────────┤ +│ 0001 │ Core Framework │ #100 │ Closed │ 100% │ 30 days ago │ +│ 0002 │ Enhancements │ #110 │ Closed │ 100% │ 15 days ago │ +│ 0003 │ Model Select │ #120 │ Closed │ 100% │ 5 days ago │ +│ 0004 │ Plugins │ #130 │ Open │ 15% │ 5 mins ago │ +│ 0005 │ Auth │ #135 │ Open │ 0% │ Never │ +└──────┴────────────────┴────────┴────────┴──────────┴─────────────┘ + +Summary: +- Total Increments: 5 +- Synced: 4 +- Not Synced: 1 (0005) +- Open Issues: 2 +- Closed Issues: 2 + +Issues: +⚠️ Increment 0005: Not synced to GitHub (run /specweave:github:create-issue 0005) +``` + +### JSON Output + +```json +{ + "increment": { + "id": "0004", + "name": "0004-plugin-architecture", + "title": "Plugin Architecture", + "status": "in_progress", + "priority": "P1", + "created_at": "2025-10-01T10:00:00Z", + "duration_days": 29 + }, + "github": { + "issue_number": 130, + "issue_url": "https://github.com/owner/repo/issues/130", + "state": "open", + "labels": ["specweave", "increment", "P1", "in-progress"], + "milestone": "v0.4.0", + "assignees": ["developer1", "developer2"], + "comments_count": 12, + "created_at": "2025-10-01T10:15:00Z", + "updated_at": "2025-10-30T16:55:00Z" + }, + "sync": { + "status": "up-to-date", + "last_synced_at": "2025-10-30T16:55:00Z", + "sync_count": 7, + "failed_syncs": 0, + "auto_sync_enabled": true, + "sync_frequency": "every-task", + "conflicts": [] + }, + "progress": { + "tasks_completed": 7, + "tasks_total": 48, + "percentage": 15, + "current_task": "T-008", + "current_week": 1 + }, + "health": { + "github_cli_authenticated": true, + "repository_access": "write", + "issue_exists": true, + "network_connected": true, + "rate_limit_remaining": 4823, + "rate_limit_total": 5000, + "sync_hook_working": true + } +} +``` + +### Health Check + +``` +🏥 GitHub Sync Health Check + +Checking system components... + +✅ GitHub CLI + Version: 2.38.0 + Authenticated: Yes + User: developer1 + +✅ Repository Access + Repository: owner/repo + Access Level: Write + Remote: https://github.com/owner/repo.git + +✅ Network Connectivity + GitHub API: Reachable + Latency: 45ms + Status: All systems operational + +✅ Rate Limits + Remaining: 4,823 / 5,000 + Resets at: 2025-10-30 17:00:00 (5 minutes) + Status: Healthy + +✅ Sync Configuration + Config file: .specweave/config.yaml + Plugin enabled: Yes + Auto-sync: Enabled + Frequency: every-task + +✅ Hooks + Post-task hook: Installed + Last fired: 5 minutes ago + Status: Working + +✅ Metadata Integrity + Metadata file: Exists + Issue number: 130 (valid) + Timestamps: Consistent + +All systems healthy! ✅ +``` + +## Configuration + +Settings from `.specweave/config.yaml`: + +```yaml +plugins: + settings: + specweave-github: + # Display settings + status_display: + default_format: "basic" # or "verbose", "json" + show_health: true + show_comparison: true +``` + +## Use Cases + +### 1. Quick Progress Check + +```bash +/specweave:github:status 0004 +``` + +See current sync state, progress, and last update time. + +### 2. Troubleshooting Sync Issues + +```bash +/specweave:github:status 0004 --verbose +``` + +Get detailed sync information to diagnose problems. + +### 3. Monitoring All Increments + +```bash +/specweave:github:status --all +``` + +Dashboard view of all increments and their sync state. + +### 4. CI/CD Integration + +```bash +/specweave:github:status 0004 --json | jq '.sync.status' +``` + +Check sync status in scripts/automation. + +### 5. Health Monitoring + +```bash +/specweave:github:status --check-health +``` + +Verify all sync components are working correctly. + +## Interpreting Status + +### Sync States + +| State | Meaning | +|-------|---------| +| ✅ Up-to-date | Local and GitHub match | +| ⚠️ Out of sync | Changes not yet synced | +| 🔄 Syncing | Sync in progress | +| ❌ Failed | Last sync failed | +| ⏸️ Paused | Auto-sync disabled | +| ❓ Unknown | Cannot determine state | + +### Common Issues + +**Out of Sync**: +``` +⚠️ Sync Status: Out of sync (2 changes pending) + +Local changes not synced to GitHub: +- Task T-008 completed (1 hour ago) +- Task T-009 started (30 minutes ago) + +Action: Run /specweave:github:sync 0004 +``` + +**Sync Failed**: +``` +❌ Sync Status: Failed (last attempt 10 minutes ago) + +Error: Rate limit exceeded +Rate limit resets at: 2025-10-30 17:00:00 + +Action: Wait for rate limit reset, then retry +``` + +**No GitHub Issue**: +``` +⚠️ Sync Status: Not synced + +No GitHub issue found for increment 0004. + +Action: Create issue first + /specweave:github:create-issue 0004 +``` + +## Requirements + +- GitHub CLI (`gh`) installed +- Valid increment directory +- Network connectivity (for GitHub API checks) + +## Related Commands + +- `/specweave:github:create-issue`: Create GitHub issue +- `/specweave:github:sync`: Sync increment with GitHub +- `/specweave:github:close-issue`: Close GitHub issue +- `/specweave:progress`: Check increment progress (local only) + +## Tips + +1. **Quick Check**: Run `/specweave:github:status` before syncing to see if sync is needed + +2. **Verbose Mode**: Use `--verbose` when troubleshooting sync issues + +3. **JSON Output**: Use `--json` for automation and scripting + +4. **Health Check**: Run `--check-health` if syncs are failing + +5. **Monitor All**: Use `--all` to get a dashboard of all increments + +## Advanced + +### Watch Mode + +Monitor sync status in real-time: + +```bash +# Refresh every 30 seconds +watch -n 30 '/specweave:github:status 0004' +``` + +### Custom Health Checks + +Define custom health checks: + +```yaml +plugins: + settings: + specweave-github: + health_checks: + - name: "Rate Limit" + threshold: 100 # Warn if < 100 remaining + critical: 10 # Error if < 10 + + - name: "Sync Lag" + threshold: 3600 # Warn if not synced in 1 hour + critical: 86400 # Error if not synced in 24 hours +``` + +### Status Notifications + +Get notified of status changes: + +```yaml +plugins: + settings: + specweave-github: + notifications: + - event: "sync_failed" + action: "slack" + channel: "#dev-alerts" + + - event: "rate_limit_low" + threshold: 100 + action: "email" + recipients: ["admin@example.com"] +``` + +### Status Dashboard + +Generate HTML dashboard: + +```bash +/specweave:github:status --all --format html > status.html +open status.html +``` + +--- + +**Command**: `/specweave:github:status` +**Plugin**: specweave-github +**Agent**: github-manager +**Version**: 1.0.0 +**Last Updated**: 2025-10-30 diff --git a/commands/specweave-github-sync.md b/commands/specweave-github-sync.md new file mode 100644 index 0000000..182926d --- /dev/null +++ b/commands/specweave-github-sync.md @@ -0,0 +1,674 @@ +--- +name: specweave-github:sync +description: Synchronize SpecWeave increment with GitHub issue (Multi-Project Support). Select profile, configure time range, and sync with rate limit protection. +--- + +# Sync Increment with GitHub Issue (Multi-Project) + +## ⚠️ CRITICAL: Sync Routing (Read First!) + +**Before executing ANY sync, you MUST determine the correct sync path:** + +### Step 0: Detect Project Structure + +```bash +# Check for living docs structure +if [ -d ".specweave/docs/internal/specs" ] && [ -n "$(ls -A .specweave/docs/internal/specs/*/FEATURE.md 2>/dev/null)" ]; then + echo "✅ Living docs found → Use Feature Sync" +else + echo "⚠️ No living docs → Use Increment Sync (brownfield)" +fi +``` + +### Sync Path Decision: + +| Structure | Command | Issue Format | +|-----------|---------|--------------| +| **Living docs exist** (`.specweave/docs/internal/specs/FS-XXX/`) | Use `github-feature-sync-cli.ts` | `[FS-XXX][US-YYY] Title` | +| **Increment only** (brownfield, no living docs) | Use `github-increment-sync-cli.ts` | `[FS-XXX] Title` with ACs | + +### For Brownfield Projects (No Living Docs): + +Use the Increment Sync CLI directly: + +```bash +# Set token +export GITHUB_TOKEN=$(grep GITHUB_TOKEN .env | cut -d'=' -f2) + +# Run increment sync +node dist/plugins/specweave-github/lib/github-increment-sync-cli.js + +# Example +node dist/plugins/specweave-github/lib/github-increment-sync-cli.js 0002 +``` + +This creates issues with: +- ✅ Proper format: `[FS-002] Increment Title` +- ✅ User Stories listed with checkbox headers +- ✅ All ACs as checkable items +- ✅ Links to increment files + +### For Projects with Living Docs: + +Use the Feature Sync CLI: + +```bash +# Run feature sync +node dist/plugins/specweave-github/lib/github-feature-sync-cli.js + +# Example +node dist/plugins/specweave-github/lib/github-feature-sync-cli.js FS-062 +``` + +--- + +Synchronize the current state of a SpecWeave increment with its GitHub issue across multiple repositories. Supports multi-profile management, time range filtering, and rate limit protection. + +## Usage + +```bash +/specweave-github:sync [options] +``` + +## Arguments + +- `increment-id`: Increment ID (e.g., `0004` or `0004-plugin-architecture`) + +## Options + +### Sync Options +- `--profile `: Use specific sync profile (skip selection prompt) +- `--time-range `: Time range for sync (`1W`, `2W`, `1M`, `3M`, `6M`, `1Y`, `ALL`) +- `--tasks`: Update task checklist in issue body +- `--comment`: Post progress comment (default) +- `--labels`: Update issue labels based on status +- `--force`: Force sync even if up-to-date +- `--direction`: Sync direction (`to-github`, `from-github`, `two-way` - **default: two-way**) +- `--all`: Sync all active increments + +### Safety Options +- `--dry-run`: Preview changes without applying +- `--skip-rate-check`: Skip rate limit validation (not recommended) + +## Sync Direction + +**Default: Two-way** (both directions) + +SpecWeave syncs changes in **both directions** by default: + +| Direction | What It Does | Use When | +|-----------|-------------|----------| +| **`two-way`** (default) | SpecWeave ↔ GitHub
• Pull changes FROM GitHub (status, labels, comments)
• Push changes TO GitHub (tasks, progress, metadata) | **Always** (recommended for keeping both systems in sync) | +| `to-github` | SpecWeave → GitHub only
• Push increment progress to GitHub
• Don't pull GitHub changes back | Read-only GitHub usage, or when GitHub is downstream | +| `from-github` | GitHub → SpecWeave only
• Pull GitHub issue updates
• Don't push SpecWeave changes | Importing GitHub issues, or when SpecWeave is downstream | + +**Why Two-way?** +- ✅ Keep both systems synchronized automatically +- ✅ GitHub status changes update SpecWeave (closed issue → completed increment) +- ✅ SpecWeave task completion updates GitHub (task done → checklist updated) +- ✅ Team members can work in either tool +- ✅ No data loss from changes in either system + +**Override if needed:** +```bash +# Push only (one-way to GitHub) +/specweave-github:sync 0004 --direction to-github + +# Pull only (one-way from GitHub) +/specweave-github:sync 0004 --direction from-github +``` + +## Examples + +```bash +# Interactive two-way sync (default - both directions) +/specweave-github:sync 0004 + +# Use specific profile (still two-way by default) +/specweave-github:sync 0004 --profile specweave-dev + +# Specify time range (two-way) +/specweave-github:sync 0004 --time-range 1M + +# Full two-way sync with all options +/specweave-github:sync 0004 --profile main --time-range 1M --tasks --labels + +# One-way sync examples (override default) +/specweave-github:sync 0004 --direction to-github # Push only +/specweave-github:sync 0004 --direction from-github # Pull only + +# Dry run to preview changes +/specweave-github:sync 0004 --dry-run + +# Force sync all increments (two-way) +/specweave-github:sync --all --force +``` + +## Interactive Workflow + +### Step 1: Profile Selection + +If multiple GitHub profiles exist, you'll be prompted to select one: + +``` +🔗 Select GitHub Profile + +Available profiles: + + 1. specweave-dev + └─ 🐙 GitHub: anton-abyzov/specweave + └─ Main SpecWeave repository + └─ Default time range: 1 month (max: 6 months) + + 2. another-repo + └─ 🐙 GitHub: myorg/another-project + └─ Another project repository + └─ Default time range: 1 month (max: 6 months) + + 3. ✨ Create new profile + +Your choice: [1] +``` + +### Step 2: Time Range Selection + +Choose how far back to fetch GitHub data: + +``` +📅 Select Time Range for Sync + +⚠️ IMPORTANT: Time range affects sync performance and rate limits + +📅 GitHub Rate Limits: + • Limit: 5,000 requests per 1h + • Current: 4,850/5,000 (97% available) + • Resets: 3:00:00 PM (25 min) + +Select time range: + + 1. Last 1 week + └─ ~50 items | 75 API calls | ⚡ 30 sec | Rate: LOW (1.5%) + + 2. Last 2 weeks + └─ ~100 items | 150 API calls | ⚡ 1 min | Rate: LOW (3%) + + 3. Last 1 month ← Recommended + └─ ~200 items | 300 API calls | ⚡ 2 min | Rate: LOW (6%) + + 4. Last 3 months + └─ ~600 items | 900 API calls | ⚠️ 5 min | Rate: MEDIUM (18%) + + 5. Last 6 months + └─ ~1,200 items | 1,800 API calls | ⚠️ 10 min | Rate: HIGH (36%) + + 6. All time + └─ ~5,000 items | 7,500 API calls | ❌ 30+ min | Rate: CRITICAL (150%) + └─ ⚠️ WARNING: Will exceed rate limit! Not recommended. + +Your choice: [3] +``` + +### Step 3: Sync Preview + +Before executing, you'll see a preview: + +``` +📊 Sync Preview: + + Profile: specweave-dev (GitHub) + └─ Repository: anton-abyzov/specweave + └─ Time range: Last 1 month (2025-10-04 to 2025-11-04) + + Estimated sync: + ├─ Work items: ~187 issues/PRs + ├─ API calls: ~280 requests + ├─ Duration: ~2 minutes + └─ Rate limit: Low impact (5.6% of hourly limit) + + GitHub rate limit (BEFORE sync): + ├─ Current: 4,850/5,000 (97% available) + ├─ After sync: ~4,570/5,000 (91% available) + └─ Reset: 3:00:00 PM (25 min) + +✅ This sync is SAFE to proceed + +Continue with sync? [Y/n]: +``` + +### Step 4: Execution + +If confirmed, sync proceeds with progress updates: + +``` +🔄 Two-way sync for increment 0004... + +✓ Profile loaded: specweave-dev +✓ GitHub repository: anton-abyzov/specweave +✓ Rate limit check: PASSED (4,850/5,000 remaining) +✓ Sync direction: Two-way (push & pull) + +Fetching increment state... +✓ Increment loaded: 0004-plugin-architecture +✓ GitHub issue: #130 +✓ Last synced: 30 minutes ago + +Detecting changes (both directions)... + +FROM GitHub: +✓ Issue status changed: open → closed +✓ Label added: ready-for-release +✓ 2 new comments from team + +FROM SpecWeave: +✓ 3 new tasks completed (T-005, T-006, T-007) +✓ Progress: 4/48 → 7/48 (15%) +✓ Current task: T-008 + +Syncing TO GitHub... +✓ Posted progress comment (ID: 1234567) +✓ Updated task checklist (7 tasks marked complete) +✓ Updated labels: +in-progress +✓ Metadata updated + +Syncing FROM GitHub... +✓ Updated increment status: active → completed +✓ Applied label: ready-for-release +✓ Imported 2 team comments to increment notes + +Rate limit after sync: 4,570/5,000 (91% available) + +✅ Two-way Sync Complete! + + SpecWeave ↔ GitHub synchronized + • Pushed: 3 task updates, progress comment + • Pulled: Status change, label, 2 comments + +GitHub Issue: https://github.com/anton-abyzov/specweave/issues/130 +Last synced: just now +Next sync: Automatic (hook-based) or manual when ready +``` + +## Key Features + +- **Multi-Profile Support**: Unlimited GitHub repos (3+, 5+, 10+ profiles) +- **Flexible Syncing**: Different increments can sync to different repos + - Increment 0001 → anton-abyzov/specweave + - Increment 0002 → client-org/mobile-app + - Increment 0003 → internal-org/infrastructure +- **Time Range Filtering**: Fast syncs (2 min vs 25+ min) +- **Rate Limit Protection**: 95%+ success rate with smart estimates +- **Smart Estimates**: Preview impact before every sync + +## Configuration + +### Sync Profiles + +Configure profiles in `.specweave/config.json`: + +```json +{ + "sync": { + "activeProfile": "specweave-dev", + "profiles": { + "specweave-dev": { + "provider": "github", + "displayName": "SpecWeave Development", + "config": { + "owner": "anton-abyzov", + "repo": "specweave" + }, + "timeRange": { + "default": "1M", + "max": "6M" + }, + "rateLimits": { + "maxItemsPerSync": 500, + "warnThreshold": 100 + } + }, + "another-repo": { + "provider": "github", + "displayName": "Another Repository", + "config": { + "owner": "myorg", + "repo": "another-project" + }, + "timeRange": { + "default": "2W", + "max": "3M" + } + } + }, + "settings": { + "autoDetectProject": true, + "defaultTimeRange": "1M", + "rateLimitProtection": true + } + } +} +``` + +### Credentials + +Store credentials in `.env` (never committed): + +```env +# GitHub +GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx +``` + +### Per-Increment Configuration + +Each increment stores its sync metadata in `.specweave/increments/{id}/metadata.json`: + +```json +{ + "id": "0004-plugin-architecture", + "sync": { + "profile": "specweave-dev", + "issueNumber": 130, + "issueUrl": "https://github.com/anton-abyzov/specweave/issues/130", + "timeRange": "1M", + "createdAt": "2025-10-15T10:00:00Z", + "lastSyncAt": "2025-11-04T14:30:00Z", + "status": "active" + } +} +``` + +## Rate Limiting Protection + +### What It Does + +Before every sync: +1. **Estimates API calls** based on time range and project size +2. **Checks current rate limit** via GitHub API +3. **Calculates impact** (low/medium/high/critical) +4. **Validates safety** (will it exceed limit?) +5. **Warns user** if risky operation detected + +### Impact Levels + +| Impact | API Calls | Duration | Safe? | Example Time Range | +|--------|-----------|----------|-------|-------------------| +| **Low** | <250 | <2 min | ✅ Yes | 1 week, 2 weeks, 1 month | +| **Medium** | 250-1000 | 2-5 min | ⚠️ Maybe | 3 months | +| **High** | 1000-2500 | 5-15 min | ⚠️ Risky | 6 months, 1 year | +| **Critical** | 2500+ | 15+ min | ❌ No | All time | + +### Protection Actions + +**Low/Medium Impact** → Proceed with optional warning +**High Impact** → Warn user, require confirmation +**Critical Impact** → Block sync, show recommendations + +### Example: Critical Impact Blocked + +``` +❌ This sync may FAIL due to: + +Blockers: + • CRITICAL rate limit impact: 7,500 API calls exceeds safe threshold for github + • Not enough rate limit remaining. Need 7,500 calls, only 4,850 remaining. + Reset at 2025-11-04 15:00:00 + +Recommendations: + 1. Reduce time range to 1 month (~300 API calls, SAFE) + 2. Wait for rate limit reset (25 minutes) + 3. Split sync across multiple time periods + +Sync cancelled. Please adjust and try again. +``` + +## Error Handling + +### Profile Not Found + +``` +❌ Error: Sync profile 'unknown-profile' not found + +Available profiles: + • specweave-dev (GitHub: anton-abyzov/specweave) + • another-repo (GitHub: myorg/another-project) + +Create profile: /specweave:sync-profile create +List profiles: /specweave:sync-profile list +``` + +### No Profiles Configured + +``` +❌ Error: No GitHub sync profiles configured + +Create your first profile: + /specweave:sync-profile create + +Or migrate from old configuration: + specweave migrate-to-profiles +``` + +### Rate Limit Exceeded During Sync + +``` +⚠️ GitHub API rate limit exceeded during sync + +Synced: 127/187 items (68%) +Remaining: 60 items +Rate limit resets: 2025-11-04 15:00:00 (12 minutes) + +What would you like to do? + + 1. Wait and resume (auto-resume in 12 min) + 2. Resume manually later (/specweave-github:sync 0004 --resume) + 3. Cancel sync (partial data saved) + +Your choice: [1] +``` + +### Network Error with Retry + +``` +❌ Error: Network error while syncing to GitHub + +Failed to connect to GitHub API. +Synced: 45/187 items before error + +Retry options: + 1. Retry immediately + 2. Retry with exponential backoff (recommended) + 3. Cancel and retry manually later + +Your choice: [2] + +Retrying in 5 seconds... +Retrying in 10 seconds... +✓ Connection restored! Resuming sync... +``` + +## First-Time Setup + +### Automatic Profile Creation + +Run migration script: + +```bash +specweave migrate-to-profiles +``` + +Output: +``` +🔍 Detected old configuration: + GitHub: Yes + +✅ Backed up old configuration to .specweave/config.json.backup + +✅ Created GitHub profile: default-github + Repository: anton-abyzov/specweave + +✅ Created default project context + Name: specweave + Default profile: default-github + +📊 Migration Summary: + Profiles created: 1 + Projects created: 1 + Warnings: 0 + Errors: 0 + +✅ Migration completed successfully! + +Next steps: + 1. Review profiles: /specweave:sync-profile list + 2. Test sync: /specweave-github:sync 0004 + 3. Keep backup: .specweave/config.json.backup (until confirmed working) +``` + +### Manual Setup + +If automatic profile creation fails: + +1. Create profile manually: + ```bash + /specweave:sync-profile create + ``` + +2. Update increment metadata: + ```json + { + "sync": { + "profile": "default-github", + "issueNumber": 130 + } + } + ``` + +3. Test sync: + ```bash + /specweave-github:sync 0004 + ``` + +## Related Commands + +- `/specweave-github:create-issue `: Create issue with profile selection +- `/specweave-github:close-issue `: Close issue +- `/specweave-github:status `: Check sync status +- `/specweave:sync-profile create`: Create new sync profile +- `/specweave:sync-profile list`: List all profiles + +## Tips & Best Practices + +### 1. Choose the Right Time Range + +**For Active Projects**: +- Use `1M` (1 month) - Balances completeness and performance +- Daily syncs: `1W` (fast, <1 min) + +**For Historical Analysis**: +- Use `3M` or `6M` with caution (check rate limits first) +- Never use `ALL` unless absolutely necessary + +### 2. Monitor Rate Limits + +Check before large operations: +```bash +gh api rate_limit +``` + +Output: +```json +{ + "resources": { + "core": { + "limit": 5000, + "remaining": 4850, + "reset": 1699027200 + } + } +} +``` + +### 3. Use Profiles Strategically + +**Organize by project**: +- `project-a-dev` → Development repo +- `project-a-prod` → Production repo +- `project-b` → Different project + +**Organize by team**: +- `frontend-team` → Frontend repo +- `backend-team` → Backend repo +- `infra-team` → Infrastructure repo + +### 4. Enable Auto-Sync + +For active development: +```json +{ + "sync": { + "settings": { + "autoSync": true, + "syncFrequency": "every-task", + "rateLimitProtection": true + } + } +} +``` + +### 5. Use Dry Run for Testing + +Before large syncs: +```bash +/specweave-github:sync 0004 --dry-run --time-range 6M +``` + +This shows what would happen without actually executing. + +## Advanced + +### Batch Sync Multiple Increments + +```bash +# Sync all active increments (respects rate limits) +/specweave-github:sync --all --time-range 1M + +# Sync specific increments +/specweave-github:sync 0001,0002,0003 --time-range 2W +``` + +### Custom Rate Limit Thresholds + +Override default thresholds: +```json +{ + "sync": { + "profiles": { + "my-profile": { + "rateLimits": { + "maxItemsPerSync": 1000, + "warnThreshold": 200 + } + } + } + } +} +``` + +### Resume Failed Syncs + +If sync fails mid-operation: +```bash +/specweave-github:sync 0004 --resume +``` + +System will: +1. Load sync state from metadata +2. Skip already-synced items +3. Continue from last checkpoint + +--- + +**Command**: `/specweave-github:sync` +**Plugin**: specweave-github +**Version**: 1.0.0 (Multi-Project) +**Last Updated**: 2025-11-05 +**Requires**: SpecWeave Core v0.8.0+ diff --git a/commands/specweave-github-update-user-story.md b/commands/specweave-github-update-user-story.md new file mode 100644 index 0000000..2abfbb9 --- /dev/null +++ b/commands/specweave-github-update-user-story.md @@ -0,0 +1,156 @@ +--- +name: specweave-github-update-user-story +description: Update GitHub issue for user story with proper ACs and tasks +--- + +# Update User Story GitHub Issue + +**Purpose**: Update an existing GitHub issue for a user story to include: +- ✅ Checkable acceptance criteria (GitHub task checkboxes) +- ✅ Task connections (links to increment tasks) +- ✅ Proper formatting and status + +**Usage**: +```bash +/specweave-github:update-user-story FS-031 US-004 +``` + +**What It Does**: + +1. **Finds user story file**: `.specweave/docs/internal/specs/{project}/FS-031/us-004-*.md` +2. **Parses content**: + - User story description (As a... I want... So that...) + - Acceptance criteria with completion status + - Tasks from increment tasks.md +3. **Finds existing GitHub issue**: Searches for `[FS-031][US-004]` or `[FS-031 US-004]` +4. **Updates issue body**: Replaces with properly formatted content including: + - Checkable ACs + - Task connections + - Status and progress + +**Arguments**: +- `featureId` - Feature ID (e.g., `FS-031`) +- `userStoryId` - User Story ID (e.g., `US-004`) + +**Example**: +```bash +# Update US-004 in FS-031 +/specweave-github:update-user-story FS-031 US-004 + +# Output: +# 🔍 Finding user story: FS-031/US-004 +# 📄 Found: .specweave/docs/internal/specs/default/FS-031/us-004-bidirectional-status-sync.md +# 🔍 Searching for existing GitHub issue... +# 🔗 Found issue #501: [FS-031][US-004] Bidirectional Status Sync +# 📝 Building updated issue body... +# ✅ 6 acceptance criteria (4 completed) +# ✅ 6 tasks (3 completed) +# 🚀 Updating GitHub issue #501... +# ✅ Updated successfully! +# 🔗 https://github.com/owner/repo/issues/501 +``` + +**What Gets Updated**: + +```markdown +**Feature**: [FS-031](../../_features/_archive/FS-031/FEATURE.md) +**Status**: complete +**Priority**: P1 +**Project**: default + +--- + +## User Story + +**As a** PM +**I want** status changes in external tools to sync back to SpecWeave +**So that** both systems stay in sync without manual updates + +📄 View full story: [`us-004-bidirectional-status-sync.md`](...) + +--- + +## Acceptance Criteria + +Progress: 4/6 criteria met (67%) + +- [x] **AC-US4-01**: SpecWeave status change triggers external update (P1, testable) +- [x] **AC-US4-02**: External issue close triggers SpecWeave prompt (P1, testable) +- [x] **AC-US4-03**: External issue reopen triggers SpecWeave prompt (P2, testable) +- [x] **AC-US4-04**: Sync logs include timestamp and reason (P2, testable) +- [ ] **AC-US4-05**: Failed syncs retry with exponential backoff (P2, testable) +- [ ] **AC-US4-06**: Sync works for GitHub, JIRA, and ADO (P1, testable) + +--- + +## Implementation Tasks + +Progress: 3/6 tasks complete (50%) + +**Increment**: [0031-external-tool-status-sync](../../increments/0031-external-tool-status-sync/) + +- [x] [T-008: Create Status Sync Engine (Core)](../../increments/0031/tasks.md#t-008-create-status-sync-engine-core) +- [x] [T-009: Implement GitHub Status Sync](../../increments/0031/tasks.md#t-009-implement-github-status-sync) +- [x] [T-010: Implement JIRA Status Sync](../../increments/0031/tasks.md#t-010-implement-jira-status-sync) +- [ ] [T-011: Implement ADO Status Sync](../../increments/0031/tasks.md#t-011-implement-ado-status-sync) +- [ ] [T-018: Add Sync Event Logging](../../increments/0031/tasks.md#t-018-add-sync-event-logging) +- [ ] [T-021: Error Handling & Retry Logic](../../increments/0031/tasks.md#t-021-error-handling-retry-logic) + +--- + +🤖 Auto-synced by SpecWeave User Story Sync +``` + +**When to Use**: + +- ✅ After completing increment implementation (update task statuses) +- ✅ After modifying acceptance criteria +- ✅ When GitHub issue is missing proper formatting +- ✅ When you want to refresh issue content from living docs + +**Related Commands**: +- `/specweave-github:sync-epic FS-031` - Sync entire epic (all user stories) +- `/specweave-github:create-issue 0031` - Create issue for increment +- `/specweave-github:sync 0031` - Two-way sync for increment + +--- + +## Implementation + +**File**: `plugins/specweave-github/lib/user-story-content-builder.ts` + +**Workflow**: +1. Parse user story file with `UserStoryContentBuilder` +2. Search GitHub for existing issue (title pattern matching) +3. Build rich issue body with checkable ACs and task links +4. Update issue via `gh issue edit` with new body + +**Error Handling**: +- ✅ Graceful fallback if user story file not found +- ✅ Clear error if GitHub issue doesn't exist +- ✅ Validation of required fields (epic, status, etc.) + +--- + +## Execution + +When user runs this command, the Claude Code assistant should: + +1. Extract `featureId` and `userStoryId` from command arguments +2. Find user story file in living docs (search all projects) +3. Use `UserStoryContentBuilder` to parse and build issue body +4. Search for existing GitHub issue using `gh issue list --search` +5. Update issue using `gh issue edit --body` +6. Report success with issue URL + +**Tech Stack**: +- TypeScript (UserStoryContentBuilder class) +- GitHub CLI (`gh issue list`, `gh issue edit`) +- YAML frontmatter parsing +- Markdown formatting + +**Testing**: +- Test with FS-031/US-004 (bidirectional status sync) +- Verify ACs are checkable +- Verify tasks link to correct increment tasks.md +- Verify progress percentages are correct diff --git a/hooks/README.md b/hooks/README.md new file mode 100644 index 0000000..1f77f2f --- /dev/null +++ b/hooks/README.md @@ -0,0 +1,289 @@ +# SpecWeave GitHub Plugin Hooks + +**Plugin**: `specweave-github` +**Location**: `plugins/specweave-github/hooks/` + +--- + +## Purpose + +This hook provides GitHub Issues sync functionality for SpecWeave increments. + +**Key Features**: +- ✅ Updates GitHub issue checkboxes based on `tasks.md` completion status +- ✅ Posts progress comments with percentage completion +- ✅ Bidirectional sync (local → GitHub) +- ✅ Non-blocking (failures don't stop core workflow) +- ✅ Self-contained (no dependencies on core plugin) + +**IMPORTANT CHANGE (v0.26.0)**: This hook is NO LONGER automatically triggered on task completion. GitHub sync should be done manually or on increment completion to avoid excessive API calls and performance overhead. + +--- + +## Available Hooks + +### 1. `post-task-completion.sh` + +**Triggers**: Manual invocation or increment completion (NOT on task completion) + +**Preconditions**: +- ✅ Active increment exists (`.specweave/increments/####/`) +- ✅ `metadata.json` has `.github.issue` field +- ✅ GitHub CLI (`gh`) installed and authenticated +- ✅ `tasks.md` file exists in increment + +**Actions**: +1. Reads completed tasks from `tasks.md` +2. Fetches GitHub issue body +3. Updates checkboxes for completed tasks +4. Posts progress comment with percentage +5. Logs all actions to `.specweave/logs/hooks-debug.log` + +**Example Flow**: +``` +Task T-003 completed in tasks.md +↓ +Hook fires (PostToolUse + TodoWrite matcher) +↓ +GitHub issue #42 checkboxes updated: [ ] T-003 → [x] T-003 +↓ +Progress comment posted: "Progress Update: 3/5 tasks (60%)" +↓ +Log: "[GitHub] ✅ GitHub sync complete" +``` + +**Dependencies**: +- `gh` CLI (GitHub CLI) +- `jq` for JSON parsing +- Bash 4.0+ + +--- + +## Configuration + +### Hook Registration + +**DEPRECATED (v0.26.0)**: This hook is NO LONGER automatically registered on TodoWrite events. + +**Previous behavior (v0.24.0 and earlier)**: +- Hook automatically fired on EVERY task completion +- Caused excessive GitHub API calls +- Created performance overhead and duplicate executions + +**New behavior (v0.26.0+)**: +- Hook must be invoked manually via `/specweave-github:sync` +- OR triggered on increment completion (not task completion) +- Reduces API calls by 90%+ +- Eliminates duplicate hook executions + +### Usage + +**Manual Sync** (recommended workflow): +```bash +# After completing several tasks, sync progress to GitHub +/specweave-github:sync + +# Or sync specific feature +/specweave-github:sync FS-048 +``` + +**Automatic Sync Options**: +1. **On Increment Completion**: Add hook to specweave plugin's post-increment-completion +2. **Periodic Sync**: Set up cron job or CI/CD trigger +3. **On Demand**: Call `/specweave-github:sync` when needed + +### Metadata Format + +Increments must have `metadata.json` with GitHub issue link: + +```json +{ + "github": { + "issue": 42, + "url": "https://github.com/owner/repo/issues/42", + "repo": "owner/repo" + } +} +``` + +--- + +## Installation + +### Automatic (Recommended) + +When `specweave init` runs, all plugin hooks are automatically installed: + +```bash +npx specweave init my-project +# Installs all plugins including specweave-github +# Hooks auto-register via hooks.json +``` + +### Manual (Development) + +For testing or development: + +```bash +# Install plugin +/plugin install specweave-github + +# Verify hook registration +cat ~/.claude/settings.json +# Should show specweave-github hooks registered +``` + +--- + +## Testing + +### Test Hook Independently + +```bash +# Test syntax +bash -n plugins/specweave-github/hooks/post-task-completion.sh + +# Test execution (requires active increment + GitHub issue) +./plugins/specweave-github/hooks/post-task-completion.sh +``` + +### Test with GitHub Issue + +1. Create increment: `/specweave:increment "test feature"` +2. Create GitHub issue: `/specweave-github:create-issue 0001` +3. Complete several tasks via TodoWrite +4. **Manually trigger sync**: `/specweave-github:sync` +5. Check GitHub issue for updates + +--- + +## Logging + +All GitHub sync actions are logged to: + +``` +.specweave/logs/hooks-debug.log +``` + +**Example Log Output**: +``` +[2025-11-10] [GitHub] 🔗 GitHub sync hook fired +[2025-11-10] [GitHub] 🔄 Syncing to GitHub issue #42 +[2025-11-10] [GitHub] 📊 Syncing task checkboxes to GitHub issue #42 +[2025-11-10] [GitHub] Completed tasks found: T-001 T-002 T-003 +[2025-11-10] [GitHub] Updated checkbox for task: T-001 +[2025-11-10] [GitHub] Updated checkbox for task: T-002 +[2025-11-10] [GitHub] Updated checkbox for task: T-003 +[2025-11-10] [GitHub] ✅ Issue description checkboxes updated +[2025-11-10] [GitHub] ✅ Progress comment posted (60%) +[2025-11-10] [GitHub] ✅ GitHub sync complete +``` + +**Log Prefixes**: +- `[GitHub]` - All messages from this hook +- `🔗` - Hook fired +- `🔄` - Syncing started +- `📊` - Syncing task data +- `✅` - Success +- `⚠️` - Warning (non-blocking failure) +- `ℹ️` - Info (skipped due to precondition) + +--- + +## Architecture + +### How It Works with Core Plugin + +**Before (v0.12.x)**: +``` +Core hook (500+ lines) +├── Sound notifications +├── Living docs sync +├── Translation +├── GitHub sync ← Embedded in core! +├── JIRA sync ← Embedded in core! +└── ADO sync ← Embedded in core! +``` + +**After (v0.13.0+)**: +``` +Core hook (330 lines) GitHub plugin hook (241 lines) +├── Sound notifications ├── Check for GitHub issue +├── Living docs sync ├── Update checkboxes +├── Translation ├── Post progress comment +└── Self-reflection └── Log actions +``` + +**Key Benefits**: +- ✅ **Separation of concerns**: Core plugin has NO external tool dependencies +- ✅ **Optional plugin**: GitHub sync only runs if `specweave-github` installed +- ✅ **Independent testing**: Test GitHub sync in isolation +- ✅ **Cleaner code**: Each hook <250 lines, single responsibility +- ✅ **Parallel execution**: Claude Code runs all hooks concurrently + +--- + +## Troubleshooting + +### Hook Not Firing + +**Check**: +1. Plugin installed: `/plugin list --installed | grep specweave-github` +2. Hook registered: `cat ~/.claude/settings.json | grep specweave-github` +3. Active increment: `cat .specweave/logs/current-increment` +4. GitHub issue linked: `cat .specweave/increments/####/metadata.json | jq .github` + +### GitHub CLI Not Found + +**Fix**: +```bash +# macOS +brew install gh + +# Linux +curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg +echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null +sudo apt update +sudo apt install gh + +# Authenticate +gh auth login +``` + +### Sync Failures + +**Check logs**: +```bash +tail -f .specweave/logs/hooks-debug.log | grep '\[GitHub\]' +``` + +**Common issues**: +- ❌ No `metadata.json`: Create GitHub issue via `/specweave-github:create-issue` +- ❌ Not authenticated: Run `gh auth login` +- ❌ Invalid issue number: Check `metadata.json` has correct issue ID +- ❌ Network error: Check internet connection + +--- + +## Migration from v0.12.x + +If upgrading from SpecWeave v0.12.x or earlier: + +1. **Automatic**: Run `specweave init` (re-installs all hooks) +2. **Manual**: Copy `plugins/specweave-github/hooks/` to `.claude/hooks/` (not recommended) + +**No action needed**: Existing increments with GitHub issues will continue to sync automatically. + +--- + +## Related Documentation + +- **Core Plugin Hooks**: `plugins/specweave/hooks/README.md` +- **Architecture Analysis**: `.specweave/increments/0018-strict-increment-discipline-enforcement/reports/HOOKS-ARCHITECTURE-ANALYSIS.md` +- **Claude Code Hooks Guide**: https://code.claude.com/docs/en/hooks-guide +- **GitHub Sync Command**: `plugins/specweave-github/commands/specweave-github-sync.md` + +--- + +**Version**: v0.13.0+ +**Last Updated**: 2025-11-10 diff --git a/hooks/post-task-completion.sh b/hooks/post-task-completion.sh new file mode 100755 index 0000000..7fc947a --- /dev/null +++ b/hooks/post-task-completion.sh @@ -0,0 +1,319 @@ +#!/bin/bash + +# SpecWeave GitHub Sync Hook +# Runs after task completion to sync progress to GitHub Projects +# +# ARCHITECTURE (v0.19.0+): IMMUTABLE DESCRIPTIONS + PROGRESS COMMENTS +# - User Story files (.specweave/docs/internal/specs/) ↔ GitHub Issues +# - Issue descriptions created once (IMMUTABLE snapshot) +# - All updates via progress comments (audit trail) +# +# This hook is part of the specweave-github plugin and handles: +# - Finding which spec user stories the current work belongs to +# - Syncing progress via GitHub comments (NOT editing issue body) +# - Creating audit trail of all changes over time +# - Notifying stakeholders via GitHub notifications +# +# Dependencies: +# - Node.js and TypeScript CLI (dist/cli/commands/sync-spec-content.js) +# - GitHub CLI (gh) must be installed and authenticated +# - ProgressCommentBuilder (lib/progress-comment-builder.ts) + +set +e # EMERGENCY FIX: Prevents Claude Code crashes + +# EMERGENCY KILL SWITCH +if [[ "${SPECWEAVE_DISABLE_HOOKS:-0}" == "1" ]]; then + exit 0 +fi + +# ============================================================================ +# CIRCUIT BREAKER & FILE LOCKING +# ============================================================================ + +# CIRCUIT BREAKER: Auto-disable after consecutive failures +CIRCUIT_BREAKER_FILE=".specweave/state/.hook-circuit-breaker-github" +CIRCUIT_BREAKER_THRESHOLD=3 + +mkdir -p ".specweave/state" 2>/dev/null || true + +if [[ -f "$CIRCUIT_BREAKER_FILE" ]]; then + FAILURE_COUNT=$(cat "$CIRCUIT_BREAKER_FILE" 2>/dev/null || echo 0) + if (( FAILURE_COUNT >= CIRCUIT_BREAKER_THRESHOLD )); then + # Circuit breaker is OPEN - hooks are disabled + exit 0 + fi +fi + +# FILE LOCK: Only allow 1 GitHub sync hook at a time +LOCK_FILE=".specweave/state/.hook-github-sync.lock" +LOCK_TIMEOUT=15 # seconds (GitHub sync can take longer) + +LOCK_ACQUIRED=false +for i in {1..15}; do + if mkdir "$LOCK_FILE" 2>/dev/null; then + LOCK_ACQUIRED=true + trap 'rmdir "$LOCK_FILE" 2>/dev/null || true' EXIT + break + fi + + # Check for stale lock + if [[ -d "$LOCK_FILE" ]]; then + LOCK_AGE=$(($(date +%s) - $(stat -f "%m" "$LOCK_FILE" 2>/dev/null || echo 0))) + if (( LOCK_AGE > LOCK_TIMEOUT )); then + rmdir "$LOCK_FILE" 2>/dev/null || true + continue + fi + fi + + sleep 0.2 +done + +if [[ "$LOCK_ACQUIRED" == "false" ]]; then + # Another instance is running, skip + exit 0 +fi + +# ============================================================================ +# PROJECT ROOT DETECTION +# ============================================================================ + +# Find project root by searching upward for .specweave/ directory +find_project_root() { + local dir="$1" + while [ "$dir" != "/" ]; do + if [ -d "$dir/.specweave" ]; then + echo "$dir" + return 0 + fi + dir="$(dirname "$dir")" + done + # Fallback: try current directory + if [ -d "$(pwd)/.specweave" ]; then + pwd + else + echo "$(pwd)" + fi +} + +PROJECT_ROOT="$(find_project_root "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")" +cd "$PROJECT_ROOT" 2>/dev/null || true + +# ============================================================================ +# CONFIGURATION +# ============================================================================ + +LOGS_DIR=".specweave/logs" +DEBUG_LOG="$LOGS_DIR/hooks-debug.log" + +mkdir -p "$LOGS_DIR" 2>/dev/null || true + +# ============================================================================ +# PRECONDITIONS CHECK +# ============================================================================ + +echo "[$(date)] [GitHub] 🔗 GitHub sync hook fired" >> "$DEBUG_LOG" 2>/dev/null || true + +# Check if Node.js is available +if ! command -v node &> /dev/null; then + echo "[$(date)] [GitHub] ⚠️ Node.js not found, skipping GitHub sync" >> "$DEBUG_LOG" 2>/dev/null || true + cat <> "$DEBUG_LOG" 2>/dev/null || true + cat < /dev/null; then + echo "[$(date)] [GitHub] ⚠️ GitHub CLI (gh) not found, skipping sync" >> "$DEBUG_LOG" 2>/dev/null || true + cat </dev/null | xargs -n1 basename | grep -v "_backlog" | grep -v "_archive" | grep -v "_working" | head -1) + +if [ -z "$CURRENT_INCREMENT" ]; then + echo "[$(date)] [GitHub] ℹ️ No active increment, checking for spec changes..." >> "$DEBUG_LOG" 2>/dev/null || true + # Fall through to sync all changed specs +fi + +# 2. Use TypeScript CLI to detect all specs +DETECT_CLI="$PROJECT_ROOT/dist/src/cli/commands/detect-specs.js" + +if [ -f "$DETECT_CLI" ]; then + echo "[$(date)] [GitHub] 🔍 Detecting all specs in increment $CURRENT_INCREMENT..." >> "$DEBUG_LOG" 2>/dev/null || true + + # Call detect-specs CLI and capture JSON output + DETECTION_RESULT=$(node "$DETECT_CLI" 2>> "$DEBUG_LOG" || echo "{}") + + # Extract spec count + SPEC_COUNT=$(echo "$DETECTION_RESULT" | node -e "const fs=require('fs'); const data=JSON.parse(fs.readFileSync(0,'utf-8')); console.log(data.specs?.length || 0)") + + echo "[$(date)] [GitHub] 📋 Detected $SPEC_COUNT spec(s)" >> "$DEBUG_LOG" 2>/dev/null || true + + # Store detection result for later use + echo "$DETECTION_RESULT" > /tmp/specweave-detected-specs.json +else + echo "[$(date)] [GitHub] ⚠️ detect-specs CLI not found at $DETECT_CLI, falling back to git diff" >> "$DEBUG_LOG" 2>/dev/null || true + SPEC_COUNT=0 +fi + +# ============================================================================ +# SYNC ALL DETECTED SPECS TO GITHUB (Multi-Spec Support) +# ============================================================================ + +if [ -f /tmp/specweave-detected-specs.json ] && [ "$SPEC_COUNT" -gt 0 ]; then + # Multi-spec sync: Loop through all detected specs + echo "[$(date)] [GitHub] 🔄 Syncing $SPEC_COUNT spec(s) to GitHub..." >> "$DEBUG_LOG" 2>/dev/null || true + + # Extract spec paths using Node.js + SPEC_PATHS=$(node -e " + const fs = require('fs'); + const data = JSON.parse(fs.readFileSync('/tmp/specweave-detected-specs.json', 'utf-8')); + const syncable = data.specs.filter(s => s.syncEnabled && s.project !== '_parent'); + syncable.forEach(s => console.log(s.path)); + " 2>> "$DEBUG_LOG") + + # Count syncable specs + SYNCABLE_COUNT=$(echo "$SPEC_PATHS" | grep -v '^$' | wc -l | tr -d ' ') + + if [ "$SYNCABLE_COUNT" -gt 0 ]; then + echo "[$(date)] [GitHub] 📋 Syncing $SYNCABLE_COUNT syncable spec(s) (excluding _parent)" >> "$DEBUG_LOG" 2>/dev/null || true + + # Sync each spec + echo "$SPEC_PATHS" | while read -r SPEC_FILE; do + if [ -n "$SPEC_FILE" ] && [ -f "$SPEC_FILE" ]; then + # Extract project and spec ID from path + SPEC_NAME=$(basename "$SPEC_FILE" .md) + PROJECT=$(basename "$(dirname "$SPEC_FILE")") + + echo "[$(date)] [GitHub] 🔄 Syncing $PROJECT/$SPEC_NAME..." >> "$DEBUG_LOG" 2>/dev/null || true + + (cd "$PROJECT_ROOT" && node "$SYNC_CLI" --spec "$SPEC_FILE" --provider github) 2>&1 | tee -a "$DEBUG_LOG" >/dev/null || { + echo "[$(date)] [GitHub] ⚠️ Spec sync failed for $PROJECT/$SPEC_NAME (non-blocking)" >> "$DEBUG_LOG" 2>/dev/null || true + } + + echo "[$(date)] [GitHub] ✅ Synced $PROJECT/$SPEC_NAME" >> "$DEBUG_LOG" 2>/dev/null || true + fi + done + + echo "[$(date)] [GitHub] ✅ Multi-spec sync complete ($SYNCABLE_COUNT synced)" >> "$DEBUG_LOG" 2>/dev/null || true + else + echo "[$(date)] [GitHub] ℹ️ No syncable specs (all specs are _parent or syncEnabled=false)" >> "$DEBUG_LOG" 2>/dev/null || true + fi + + # Cleanup temp file + rm -f /tmp/specweave-detected-specs.json 2>/dev/null || true +else + # Fallback: Sync all modified specs (check git diff) + echo "[$(date)] [GitHub] 🔄 Checking for modified specs..." >> "$DEBUG_LOG" 2>/dev/null || true + + MODIFIED_SPECS=$(git diff --name-only HEAD .specweave/docs/internal/specs/**/*.md 2>/dev/null || echo "") + + if [ -n "$MODIFIED_SPECS" ]; then + echo "[$(date)] [GitHub] 📝 Found modified specs:" >> "$DEBUG_LOG" 2>/dev/null || true + echo "$MODIFIED_SPECS" >> "$DEBUG_LOG" 2>/dev/null || true + + # Sync each modified spec + echo "$MODIFIED_SPECS" | while read -r SPEC_FILE; do + if [ -n "$SPEC_FILE" ] && [ -f "$SPEC_FILE" ]; then + echo "[$(date)] [GitHub] 🔄 Syncing $SPEC_FILE..." >> "$DEBUG_LOG" 2>/dev/null || true + (cd "$PROJECT_ROOT" && node "$SYNC_CLI" --spec "$SPEC_FILE" --provider github) 2>&1 | tee -a "$DEBUG_LOG" >/dev/null || true + fi + done + + echo "[$(date)] [GitHub] ✅ Batch spec sync complete" >> "$DEBUG_LOG" 2>/dev/null || true + else + echo "[$(date)] [GitHub] ℹ️ No modified specs found, skipping sync" >> "$DEBUG_LOG" 2>/dev/null || true + fi +fi + +# ============================================================================ +# EPIC GITHUB ISSUE SYNC (DEPRECATED v0.24.0+) +# ============================================================================ +# +# ⚠️ DEPRECATED: SpecWeave now syncs ONLY at User Story level. +# +# Feature/Epic-level issues are no longer updated. +# Use /specweave-github:sync instead to sync User Story issues. +# +# To re-enable (NOT recommended): +# export SPECWEAVE_ENABLE_EPIC_SYNC=true +# +# @see .specweave/increments/0047-us-task-linkage/reports/GITHUB-TITLE-FORMAT-FIX-PLAN.md +# ============================================================================ + +if [ "$SPECWEAVE_ENABLE_EPIC_SYNC" = "true" ]; then + echo "[$(date)] [GitHub] 🔄 Checking for Epic GitHub issue update (DEPRECATED)..." >> "$DEBUG_LOG" 2>/dev/null || true + + # Find active increment ID + ACTIVE_INCREMENT=$(ls -t .specweave/increments/ | grep -v '^\.' | while read inc; do + if [ -f ".specweave/increments/$inc/metadata.json" ]; then + STATUS=$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' ".specweave/increments/$inc/metadata.json" 2>/dev/null | sed 's/.*"\([^"]*\)".*/\1/' || true) + if [ "$STATUS" = "active" ]; then + echo "$inc" + break + fi + fi + done | head -1) + + if [ -n "$ACTIVE_INCREMENT" ]; then + echo "[$(date)] [GitHub] 🎯 Active increment: $ACTIVE_INCREMENT" >> "$DEBUG_LOG" 2>/dev/null || true + + # Run Epic sync script (silently, errors logged to debug log) + if [ -f "$PROJECT_ROOT/scripts/update-epic-github-issue.sh" ]; then + echo "[$(date)] [GitHub] 🚀 Updating Epic GitHub issue (DEPRECATED)..." >> "$DEBUG_LOG" 2>/dev/null || true + "$PROJECT_ROOT/scripts/update-epic-github-issue.sh" "$ACTIVE_INCREMENT" >> "$DEBUG_LOG" 2>&1 || true + echo "[$(date)] [GitHub] ⚠️ Epic sync is deprecated. Use /specweave-github:sync instead." >> "$DEBUG_LOG" 2>/dev/null || true + else + echo "[$(date)] [GitHub] ⚠️ Epic sync script not found, skipping" >> "$DEBUG_LOG" 2>/dev/null || true + fi + else + echo "[$(date)] [GitHub] ℹ️ No active increment found, skipping Epic sync" >> "$DEBUG_LOG" 2>/dev/null || true + fi +else + echo "[$(date)] [GitHub] ℹ️ Epic sync disabled (sync at User Story level only)" >> "$DEBUG_LOG" 2>/dev/null || true +fi + +# ============================================================================ +# CIRCUIT BREAKER UPDATE +# ============================================================================ +# Reset circuit breaker on successful completion (all errors are caught above) +echo "0" > "$CIRCUIT_BREAKER_FILE" 2>/dev/null || true + +# ============================================================================ +# OUTPUT TO CLAUDE +# ============================================================================ + +cat < P2 > P3) + - Show ONLY if priority exists (don't show "undefined") + - Example: `**Priority**: P1` + +5. **NO Project Field** + - Don't include `**Project**: ...` - not needed for GitHub issues + - Project is determined by repository context + +### ❌ Never Use + +- ❌ Relative paths (`../../_features/FS-031`) +- ❌ Undefined values (`**Priority**: undefined`) +- ❌ Project field in metadata +- ❌ Plain bullet points for ACs (must be checkboxes) +- ❌ Plain bullet points for tasks (must be checkboxes with links) + +## Implementation + +### UserStoryContentBuilder (✅ REFERENCE IMPLEMENTATION) + +**File**: `plugins/specweave-github/lib/user-story-content-builder.ts` + +This is the **gold standard** implementation. All other builders must follow this pattern. + +**Key features**: +```typescript +// 1. Accept GitHub repo parameter +async buildIssueBody(githubRepo?: string): Promise + +// 2. Auto-detect repo from git remote +private async detectGitHubRepo(): Promise + +// 3. Extract priority from ACs +private extractPriorityFromACs(criteria: AcceptanceCriterion[]): string | null + +// 4. Generate GitHub URLs (not relative) +const featureUrl = `https://github.com/${repo}/tree/develop/.specweave/docs/internal/specs/_features/${featureId}`; + +// 5. Convert task links to GitHub URLs +if (repo && taskLink.startsWith('../../')) { + const relativePath = taskLink.replace(/^\.\.\/\.\.\//, '.specweave/'); + taskLink = `https://github.com/${repo}/tree/develop/${relativePath}`; +} +``` + +### Template + +```markdown +**Feature**: [FS-031](https://github.com/owner/repo/tree/develop/.specweave/docs/internal/specs/_features/FS-031) +**Status**: complete +**Priority**: P1 + +--- + +## User Story + +**As a** user +**I want** feature +**So that** benefit + +📄 View full story: [`us-004-name.md`](https://github.com/owner/repo/tree/develop/.specweave/docs/internal/specs/default/_archive/FS-031/us-004-name.md) + +--- + +## Acceptance Criteria + +Progress: 4/6 criteria met (67%) + +- [x] **AC-US4-01**: Description (P1, testable) +- [x] **AC-US4-02**: Description (P1, testable) +- [ ] **AC-US4-03**: Description (P2, testable) +- [ ] **AC-US4-04**: Description (P2, testable) + +--- + +## Implementation Tasks + +Progress: 3/6 tasks complete (50%) + +**Increment**: [0031-name](https://github.com/owner/repo/tree/develop/.specweave/increments/0031-name) + +- [x] [T-008: Title](https://github.com/owner/repo/tree/develop/.specweave/increments/0031/tasks.md#t-008-title) +- [x] [T-009: Title](https://github.com/owner/repo/tree/develop/.specweave/increments/0031/tasks.md#t-009-title) +- [ ] [T-010: Title](https://github.com/owner/repo/tree/develop/.specweave/increments/0031/tasks.md#t-010-title) + +--- + +🤖 Auto-synced by SpecWeave +``` + +## Implementation + +### Content Builders + +All GitHub issue content is generated by these builders: + +1. **UserStoryIssueBuilder** (`plugins/specweave-github/lib/user-story-issue-builder.ts`) + - Creates issues from `us-*.md` files + - Generates `[FS-XXX][US-YYY] Title` format + - Extracts ACs and tasks as checkboxes + - Uses GitHub URLs (not relative paths) + +2. **GitHubFeatureSync** (`plugins/specweave-github/lib/github-feature-sync.ts`) + - Syncs Features as GitHub Milestones + - Syncs User Stories as GitHub Issues via UserStoryIssueBuilder + - Universal Hierarchy: Feature → Milestone, User Story → Issue + +### Commands + +All GitHub sync commands use the Universal Hierarchy: + +- `/specweave-github:sync` - Sync increments via Feature/UserStory hierarchy +- `/specweave-github:create-issue` - Create issue using standard format +- `/specweave-github:update-user-story` - Update user story issue + +## Validation Checklist + +When creating/updating a GitHub issue, verify: + +- [ ] Feature link is clickable GitHub URL (not `../../`) +- [ ] User story link is clickable GitHub URL +- [ ] All task links are clickable GitHub URLs +- [ ] ACs are checkable (GitHub checkboxes work in UI) +- [ ] Tasks are checkable (GitHub checkboxes work in UI) +- [ ] Priority shows actual value (P1/P2/P3) or is omitted +- [ ] No "Project: undefined" field +- [ ] Progress percentages are correct +- [ ] Increment link is clickable GitHub URL + +## Benefits + +- ✅ **Links work**: No more broken relative paths +- ✅ **Checkable**: ACs and tasks can be checked/unchecked in GitHub UI +- ✅ **Clean metadata**: No undefined values cluttering the issue +- ✅ **Consistent**: Same format across all issue types +- ✅ **Traceable**: Direct links to source files in repository + +## When to Use + +**Always!** This is the ONLY acceptable format for GitHub issues created by SpecWeave. + +No exceptions. No shortcuts. Every issue follows this standard. + +## Related Files + +- **User Story Builder**: `plugins/specweave-github/lib/user-story-issue-builder.ts` +- **Feature Sync**: `plugins/specweave-github/lib/github-feature-sync.ts` +- **Example Issue**: https://github.com/anton-abyzov/specweave/issues/501 diff --git a/skills/github-issue-tracker/SKILL.md b/skills/github-issue-tracker/SKILL.md new file mode 100644 index 0000000..371c3ec --- /dev/null +++ b/skills/github-issue-tracker/SKILL.md @@ -0,0 +1,497 @@ +--- +name: github-issue-tracker +description: Task-level GitHub issue tracking for SpecWeave increments. Provides fine-grained progress tracking via issue comments, task checklists, and labels. Enables team collaboration on individual tasks. Activates for task tracking, GitHub comments, issue updates, task progress, team collaboration, granular tracking. +--- + +# GitHub Issue Tracker - Task-Level Progress Tracking + +**Purpose**: Provide fine-grained task-level visibility in GitHub issues for detailed progress tracking and team collaboration. + +**When to Use**: +- Detailed progress tracking (per-task updates) +- Team collaboration on specific tasks +- Task assignments via GitHub +- Blocking issue tracking +- Task-level comments and discussions + +**Integration**: Works with `github-sync` skill and `/specweave:github:*` commands + +--- + +## How Task Tracking Works + +### 1. Task Checklist in GitHub Issue + +When creating an increment issue, automatically add task checklist: + +```markdown +## Tasks + +### Week 1: Foundation (12 tasks) + +- [ ] T-001: Create plugin type definitions (6h) @developer1 +- [ ] T-002: Create plugin manifest schema (4h) @developer1 +- [ ] T-003: Implement PluginLoader (6h) @developer2 +- [ ] T-004: Implement PluginManager (8h) @developer2 +... + +### Week 2: GitHub Plugin (10 tasks) + +- [ ] T-013: Create GitHub plugin structure (2h) +- [ ] T-014: Implement github-sync skill (8h) +... +``` + +**Features**: +- Clickable checkboxes (GitHub native) +- Time estimates in parentheses +- Assignees via @mentions +- Organized by phase/week + +### 2. Per-Task Comments + +After each task completion, post detailed comment: + +```markdown +### ✅ Task Completed: T-007 + +**Title**: Implement Claude plugin installer +**Estimated**: 8h +**Actual**: 7h +**Assignee**: @developer2 + +**What Changed**: +- Added `compilePlugin()` method to ClaudeAdapter +- Implemented plugin file copying to `.claude/` +- Added unload and status methods +- Updated adapter interface + +**Files Modified**: +- `src/adapters/claude/adapter.ts` (+150 lines) +- `src/adapters/adapter-interface.ts` (+35 lines) + +**Tests**: +- ✅ Unit tests passing (12 new tests) +- ✅ Integration test: plugin install/uninstall + +**Next Task**: T-008 - Implement Cursor plugin compiler + +--- + +**Progress**: 7/48 tasks (15%) | Week 1: 7/12 complete + +🤖 Posted by SpecWeave at 2025-10-30 14:30:00 +``` + +**Benefits**: +- Detailed change log per task +- Time tracking (estimated vs actual) +- File change summary +- Test status +- Context for code reviewers + +### 3. Task Assignments + +Assign tasks to team members via GitHub: + +**Method 1: Task checklist with @mentions** +```markdown +- [ ] T-015: Create test suite (8h) @qa-engineer +``` + +**Method 2: Issue comments** +``` +@developer1 Can you take T-003 and T-004 this week? +``` + +**Method 3: GitHub Projects** +- Drag tasks to columns (To Do, In Progress, Done) +- Auto-sync with increment status + +### 4. Blocking Issues + +Track dependencies and blockers: + +```markdown +### 🚨 Blocked: T-020 + +**Task**: Implement Kubernetes plugin +**Blocked By**: #127 (Infrastructure setup incomplete) +**Blocking**: T-021, T-022 +**Reason**: Need staging cluster before testing K8s plugin + +**Resolution**: Wait for #127 to close, then proceed with T-020 + +--- + +**ETA**: Blocked since 2025-10-28, expected resolution by 2025-11-01 +``` + +--- + +## Configuration + +Enable task-level tracking in `.specweave/config.yaml`: + +```yaml +plugins: + settings: + specweave-github: + # Task-level tracking + task_tracking: + enabled: true + + # Post comment after each task + post_task_comments: true + + # Update checklist after each task + update_checklist: true + + # Include file changes in comments + include_file_changes: true + + # Include time tracking + include_time_tracking: true + + # Auto-assign tasks based on git author + auto_assign: true + + # Blocking issue detection + blocking_issues: + enabled: true + + # Check for blocking keywords in task descriptions + keywords: ["blocked by", "depends on", "requires"] +``` + +--- + +## Commands + +### Check Task Status + +```bash +/specweave:github:status 0004 +``` + +Output: +``` +GitHub Issue: #130 +Status: Open (In Progress) + +Tasks: 7/48 completed (15%) + +Week 1: Foundation +✅ T-001: Create plugin types (Done) +✅ T-002: Create manifest schema (Done) +✅ T-003: Implement PluginLoader (Done) +✅ T-004: Implement PluginManager (Done) +✅ T-005: Implement PluginDetector (Done) +✅ T-006: Update adapter interface (Done) +✅ T-007: Implement Claude installer (Done) +⏳ T-008: Implement Cursor compiler (In Progress) +⏸️ T-009: Implement Copilot compiler (Pending) +``` + +### Sync Task Checklist + +```bash +/specweave:github:sync 0004 --tasks +``` + +Updates GitHub issue checklist to match current increment progress. + +### Comment on Task + +```bash +/specweave:github:comment 0004 T-008 "Cursor adapter completed, moving to testing phase" +``` + +Posts custom comment to GitHub issue for specific task. + +--- + +## GitHub Labels for Tasks + +Automatically apply labels based on task status: + +| Label | When Applied | Purpose | +|-------|--------------|---------| +| `in-progress` | First task starts | Increment is actively being worked on | +| `testing` | Implementation tasks done | Ready for QA | +| `blocked` | Task marked as blocked | Needs attention | +| `review-requested` | PR created | Code review needed | +| `ready-for-merge` | Review approved | Can be merged | + +--- + +## Team Collaboration Patterns + +### Pattern 1: Daily Standups via GitHub + +Team members comment on tasks with daily updates: + +```markdown +**@developer1** on T-008: +Yesterday: Implemented Cursor adapter skeleton +Today: Adding plugin compilation logic +Blockers: None + +**@developer2** on T-014: +Yesterday: Created github-sync skill +Today: Testing sync workflow +Blockers: Waiting for #130 review +``` + +### Pattern 2: Code Review Integration + +Link PRs to tasks: + +```markdown +### T-007: Claude plugin installer + +**PR**: #45 +**Status**: Ready for review +**Reviewers**: @tech-lead, @architect + +**Changes**: +- Implemented plugin support in Claude adapter +- Added comprehensive tests +- Updated documentation + +**Review Checklist**: +- [ ] Code quality (clean, readable) +- [ ] Test coverage (80%+) +- [ ] Documentation updated +- [ ] No security issues +``` + +### Pattern 3: Task Handoff + +Transfer task ownership: + +```markdown +@developer1 → @developer2 (T-015) + +**Context**: +- Tests framework configured +- Need to write E2E tests for plugin system +- Reference: T-007 implementation + +**Handoff Notes**: +- Use Playwright for E2E tests +- Cover happy path + error scenarios +- See `.specweave/increments/0004/tests.md` for test cases +``` + +--- + +## Time Tracking + +### Automatic Time Tracking + +Track time spent on tasks: + +```yaml +# .specweave/increments/0004-plugin-architecture/.metadata.yaml +tasks: + T-007: + estimated_hours: 8 + actual_hours: 7 + started_at: 2025-10-30T10:00:00Z + completed_at: 2025-10-30T17:00:00Z + assignee: developer2 +``` + +### Time Reports + +Generate time reports: + +```bash +/specweave:github:time-report 0004 +``` + +Output: +``` +Time Report: Increment 0004 + +Estimated: 240 hours (6 weeks) +Actual: 56 hours (1.4 weeks) +Remaining: 184 hours (4.6 weeks) + +By Developer: +- developer1: 24h (5 tasks) +- developer2: 32h (2 tasks) + +By Phase: +- Week 1 Foundation: 56h / 96h (58%) +- Week 2 GitHub Plugin: 0h / 80h (0%) +- Week 3 Plugins: 0h / 120h (0%) +- Week 4 Docs: 0h / 88h (0%) + +Pace: On track (4% ahead of schedule) +``` + +--- + +## GitHub Projects Integration + +### Automated Kanban Board + +Sync increment tasks with GitHub Projects: + +**Board Columns**: +1. **Backlog**: Pending tasks +2. **Ready**: Tasks ready to start +3. **In Progress**: Currently being worked on +4. **Review**: PRs open, needs review +5. **Done**: Completed tasks + +**Auto-Move Rules**: +- Task starts → Move to "In Progress" +- PR created → Move to "Review" +- PR merged → Move to "Done" + +### Milestone Tracking + +Link increments to GitHub Milestones: + +```yaml +# .specweave/config.yaml +plugins: + settings: + specweave-github: + milestones: + "v0.4.0": + increments: + - 0004-plugin-architecture + - 0005-user-authentication + due_date: 2025-11-30 +``` + +GitHub Milestone view shows progress across multiple increments. + +--- + +## Advanced Features + +### Task Dependencies + +Define task dependencies in `tasks.md`: + +```markdown +### T-008: Implement Cursor compiler + +**Dependencies**: T-006, T-007 +**Blocks**: T-011, T-012 + +**Description**: ... +``` + +SpecWeave enforces dependency order and warns if attempting blocked task. + +### Subtasks + +Break complex tasks into subtasks: + +```markdown +### T-014: Implement github-sync skill (8h) + +**Subtasks**: +- [ ] T-014.1: Create SKILL.md (1h) +- [ ] T-014.2: Implement export (increment → issue) (3h) +- [ ] T-014.3: Implement import (issue → increment) (2h) +- [ ] T-014.4: Add progress updates (1h) +- [ ] T-014.5: Write tests (1h) +``` + +Subtasks appear as nested checkboxes in GitHub issue. + +### External Issue Links + +Reference external blocking issues: + +```markdown +### T-020: Kubernetes plugin + +**Blocked By**: +- #127 (this repo): Infrastructure setup +- https://github.com/kubernetes/kubernetes/issues/12345: K8s API bug + +**Resolution Plan**: +1. Wait for #127 (ETA: 2025-11-01) +2. Work around K8s bug using alternative API +``` + +--- + +## Notifications + +### Task Assignment Notifications + +GitHub automatically notifies assignees: + +``` +@developer1 you were assigned T-015 in #130 +``` + +### Blocking Notifications + +Notify blocked task assignees when blocker resolves: + +``` +@developer2 Task T-020 is unblocked (#127 was closed) +``` + +### Deadline Reminders + +Warn when tasks are behind schedule: + +``` +⚠️ T-008 is 2 days overdue (estimated: 2 days, actual: 4 days) +``` + +--- + +## Troubleshooting + +**Checklist not updating?** +- Verify `update_checklist: true` in config +- Check GitHub API permissions (repo write access) +- Manually sync: `/specweave:github:sync 0004 --tasks` + +**Comments not posting?** +- Check `post_task_comments: true` +- Verify GitHub CLI authenticated: `gh auth status` +- Check rate limits: `gh api rate_limit` + +**Time tracking inaccurate?** +- Verify task timestamps in `.metadata.yaml` +- Check for manual edits to metadata +- Re-sync: `/specweave:github:sync 0004 --force` + +--- + +## Best Practices + +1. **Keep Tasks Atomic**: Each task should be completable in one work session (2-8 hours) +2. **Update Checklists Daily**: Sync progress at least once per day +3. **Use Assignees**: Assign tasks to specific developers for accountability +4. **Track Blockers**: Immediately flag blocking issues for visibility +5. **Link PRs**: Always reference task ID in PR title (`T-007: Add plugin support`) +6. **Comment Context**: Add context comments when handing off tasks +7. **Review Time Estimates**: Adjust estimates based on actual time tracked + +--- + +## Related + +- **github-sync**: High-level increment ↔ issue synchronization +- **github-manager agent**: AI agent for GitHub operations +- **Commands**: All `/specweave:github:*` commands + +--- + +**Version**: 1.0.0 +**Plugin**: specweave-github +**Last Updated**: 2025-10-30 diff --git a/skills/github-multi-project/SKILL.md b/skills/github-multi-project/SKILL.md new file mode 100644 index 0000000..a0a7492 --- /dev/null +++ b/skills/github-multi-project/SKILL.md @@ -0,0 +1,249 @@ +--- +name: github-multi-project +description: Expert at organizing specs and splitting tasks across multiple GitHub repositories. Handles monorepo, polyrepo, and parent repo architectures. Activates for multi-project GitHub setups, task splitting, spec organization, team allocation, cross-repo coordination. +--- + +# GitHub Multi-Project Management Skill + +Expert skill for managing SpecWeave projects across multiple GitHub repositories. + +## Core Capabilities + +### 1. Spec Organization +- Organizes specs in `.specweave/docs/internal/projects/{project-id}/` structure +- Maps increments to specific projects/repos +- Maintains traceability across repositories +- Handles cross-project dependencies + +### 2. Task Splitting +When a SpecWeave increment spans multiple repositories: +- Analyzes tasks in `tasks.md` +- Identifies which tasks belong to which repo +- Creates repo-specific task lists +- Maintains cross-repo coordination + +### 3. Repository Architectures + +#### Single Repository +``` +my-app/ +├── .specweave/ +│ └── docs/internal/projects/default/ +└── src/ +``` + +#### Multi-Repository (Polyrepo) +``` +my-app-frontend/ +├── .git +└── src/ + +my-app-backend/ +├── .git +└── src/ + +my-app-shared/ +├── .git +└── src/ +``` + +#### Parent Repository Approach (Recommended for Multi-Repo) +``` +my-app-parent/ # Parent repo with .specweave +├── .specweave/ +│ └── docs/internal/projects/ +│ ├── frontend/ +│ ├── backend/ +│ └── shared/ +└── services/ # Implementation repos + ├── frontend/ + ├── backend/ + └── shared/ +``` + +#### Monorepo +``` +my-app/ +├── .specweave/ +│ └── docs/internal/projects/ +│ ├── frontend/ +│ ├── backend/ +│ └── shared/ +└── packages/ + ├── frontend/ + ├── backend/ + └── shared/ +``` + +## Task Splitting Examples + +### Example 1: E-commerce Platform +**Increment**: Add shopping cart functionality + +**Tasks split by repository**: + +**Frontend (my-app-frontend)**: +- T-001: Create CartItem component +- T-002: Implement cart state management +- T-003: Add cart UI with add/remove buttons + +**Backend (my-app-backend)**: +- T-004: Create cart database schema +- T-005: Implement cart API endpoints +- T-006: Add cart validation logic + +**Shared (my-app-shared)**: +- T-007: Define cart TypeScript types +- T-008: Create cart utility functions + +### Example 2: Microservices Architecture +**Increment**: Implement user notifications + +**Tasks split by service**: + +**User Service**: +- T-001: Add notification preferences to user profile +- T-002: Create preference API endpoints + +**Notification Service**: +- T-003: Implement notification queue +- T-004: Create email sender +- T-005: Create push notification sender + +**Gateway Service**: +- T-006: Add notification routes +- T-007: Implement rate limiting + +## Commands + +### Analyze Task Distribution +```typescript +// Analyze which tasks belong to which repository +function analyzeTaskDistribution(tasks: Task[]): Map { + const distribution = new Map(); + + for (const task of tasks) { + const repo = detectRepository(task); + if (!distribution.has(repo)) { + distribution.set(repo, []); + } + distribution.get(repo).push(task); + } + + return distribution; +} +``` + +### Create Repository-Specific Issues +```typescript +// Create GitHub issues in each repository +async function createRepoSpecificIssues( + increment: Increment, + distribution: Map +) { + for (const [repo, tasks] of distribution) { + const issue = await createGitHubIssue({ + repo, + title: `[${increment.id}] ${increment.name} - ${repo}`, + body: formatTasksAsChecklist(tasks), + labels: ['specweave', 'increment', repo] + }); + + console.log(`Created issue #${issue.number} in ${repo}`); + } +} +``` + +## Best Practices + +### 1. Parent Repository Approach +**Recommended for multi-repo projects**: +- Central .specweave/ folder in parent repo +- Living docs sync to parent (single source of truth) +- Implementation repos stay clean +- Better for enterprise/multi-team projects + +### 2. Task Naming Convention +``` +T-{repo}-{number}: {description} +T-FE-001: Create user profile component +T-BE-001: Implement user API +T-SHARED-001: Define user types +``` + +### 3. Cross-Repository Dependencies +Mark dependencies clearly: +``` +T-FE-002: Consume user API + Dependencies: T-BE-001 (must complete first) +``` + +### 4. Spec Organization +``` +.specweave/docs/internal/projects/ +├── frontend/ +│ └── specs/ +│ ├── spec-001-user-interface.md +│ └── spec-002-cart-ui.md +├── backend/ +│ └── specs/ +│ ├── spec-001-api-design.md +│ └── spec-002-database.md +└── shared/ + └── specs/ + └── spec-001-types.md +``` + +## Integration with GitHub Projects + +### Multi-Repo GitHub Project +Create a GitHub Project that spans multiple repositories: +1. Create project at organization level +2. Add issues from all repos +3. Use project boards for cross-repo coordination +4. Track overall increment progress + +### Repository-Specific Projects +Each repository can have its own project: +- Frontend Project: UI tasks +- Backend Project: API tasks +- Shared Project: Common tasks + +## Automation + +### GitHub Actions Integration +```yaml +# .github/workflows/specweave-sync.yml +name: SpecWeave Multi-Repo Sync + +on: + workflow_dispatch: + schedule: + - cron: '0 */6 * * *' # Every 6 hours + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Sync to repositories + run: | + # Sync tasks to frontend repo + gh issue create --repo myorg/frontend ... + + # Sync tasks to backend repo + gh issue create --repo myorg/backend ... +``` + +## Error Handling + +### Common Issues +1. **Repository not found**: Ensure repos exist and token has access +2. **Task ambiguity**: Use clear naming to indicate target repo +3. **Cross-repo conflicts**: Use parent repo as single source of truth +4. **Permission errors**: Token needs repo scope for all repositories + +## Related Skills +- github-sync: Basic GitHub synchronization +- github-issue-tracker: Task-level tracking +- specweave:multi-project-spec-mapper: Intelligent spec splitting \ No newline at end of file diff --git a/skills/github-sync/SKILL.md b/skills/github-sync/SKILL.md new file mode 100644 index 0000000..0731431 --- /dev/null +++ b/skills/github-sync/SKILL.md @@ -0,0 +1,471 @@ +--- +name: github-sync +description: Two-way synchronization between SpecWeave specs and GitHub Projects (push & pull by default). Activates ONLY when user asks questions about GitHub integration or needs help configuring GitHub sync. Does NOT activate for slash commands. For syncing, use /specweave-github:sync-spec command instead. +--- + +# GitHub Sync - Two-way Spec ↔ Project Synchronization + +**Purpose**: Seamlessly synchronize SpecWeave specs with GitHub Projects for team visibility and project management. + +**Default Behavior**: **Two-way sync** (push & pull) - Changes in either system are automatically synchronized + +**⚠️ IMPORTANT**: This skill provides HELP and GUIDANCE about GitHub sync. For actual syncing, users should use the `/specweave-github:sync-spec` command directly. This skill should NOT auto-activate when the command is being invoked. + +## When to Activate + +✅ **Do activate when**: +- User asks: "How do I set up GitHub sync?" +- User asks: "What GitHub credentials do I need?" +- User asks: "How does the GitHub integration work?" +- User needs help configuring GitHub integration + +❌ **Do NOT activate when**: +- User invokes `/specweave-github:sync-spec` command (command handles it) +- Command is already running (avoid duplicate invocation) +- Task completion hook is syncing (automatic process) + +**Integration**: Works with `/specweave-github:sync-spec` command + +--- + +## CORRECT Architecture (v0.17.0+) + +**CRITICAL**: SpecWeave syncs **SPECS** to GitHub, NOT increments! + +``` +✅ CORRECT: +.specweave/docs/internal/specs/spec-001.md ↔ GitHub Project +├─ User Story US-001 ↔ GitHub Issue #1 +├─ User Story US-002 ↔ GitHub Issue #2 +└─ User Story US-003 ↔ GitHub Issue #3 + +❌ WRONG (OLD, REMOVED!): +.specweave/increments/0001-feature ↔ GitHub Issue (DEPRECATED!) +``` + +**Why Specs, Not Increments?** +- ✅ **Specs = Permanent** (living docs, feature-level knowledge base) +- ❌ **Increments = Temporary** (implementation snapshots, can be deleted after done) +- ✅ **GitHub should mirror PERMANENT work**, not temporary iterations + +--- + +## How GitHub Sync Works + +### 1. Spec → GitHub Project (Export) + +**Trigger**: When spec is created or updated + +**Actions**: +1. Create GitHub Project with: + - Title: `[SPEC-001] Core Framework & Architecture` + - Description: Spec overview + progress + - Columns: Backlog, In Progress, Done + - Linked to repository + +2. Store project ID in spec metadata: + ```yaml + # .specweave/docs/internal/specs/spec-001.md (frontmatter) + --- + externalLinks: + github: + projectId: 123 + projectUrl: https://github.com/users/anton-abyzov/projects/123 + syncedAt: 2025-11-11T10:00:00Z + --- + ``` + +3. Create GitHub Issues for each user story: + - Title: `[US-001] As a developer, I want to install SpecWeave via NPM` + - Body: Acceptance criteria as checkboxes + - Labels: `user-story`, `spec:spec-001`, `priority:P1` + - Linked to project + +**Example GitHub Project**: +```markdown +# [SPEC-001] Core Framework & Architecture + +**Status**: In Progress (75% complete) +**Priority**: P0 (Critical) +**Feature Area**: Foundation & Plugin System + +## Overview + +The core framework and architecture spec covers SpecWeave's foundational capabilities: +- TypeScript-based CLI framework +- Plugin system architecture +- Cross-platform compatibility + +## Progress + +- ✅ US-001: NPM installation (Complete) +- ✅ US-002: Plugin system (Complete) +- ⏳ US-003: Context optimization (In Progress) +- ⏳ US-004: Intelligent agents (In Progress) + +**Overall**: 2/4 user stories complete (50%) + +--- + +🤖 Auto-synced by SpecWeave GitHub Plugin +``` + +### 2. User Story Progress Updates (Spec → GitHub) + +**Trigger**: After each task completion (via post-task-completion hook) + +**Actions**: +1. **Update GitHub Issue** (for user story): + - Updates acceptance criteria checkboxes + - Marks completed ACs with `[x]` + - Updates issue description + - Updates labels (`in-progress`, `testing`, `ready-for-review`) + +2. **Update GitHub Project**: + - Moves cards between columns (Backlog → In Progress → Done) + - Updates project progress percentage + - Posts progress comment + +**Example Issue Update**: +```markdown +**User Story**: US-001 + +As a developer, I want to install SpecWeave via NPM so that I can use it in my projects + +## Acceptance Criteria + +- [x] AC-001-01: `npm install -g specweave` works +- [x] AC-001-02: `specweave init` creates `.specweave/` structure +- [ ] AC-001-03: Version command shows current version (In Progress) + +--- + +**Progress**: 2/3 ACs complete (67%) + +🤖 Auto-updated by SpecWeave (2025-11-11) +``` + +### 3. Spec Completion (Close Project) + +**Trigger**: All user stories in spec are complete + +**Actions**: +1. Close all GitHub Issues (user stories) +2. Archive GitHub Project +3. Post final comment: + ```markdown + ✅ **Spec Completed** + + **Final Stats**: + - 35 user stories completed (100%) + - 4 increments implemented (0001, 0002, 0004, 0005) + - Duration: 6 weeks + + **Deliverables**: + - Core framework architecture + - Plugin system + - Cross-platform CLI + + Spec complete. Project archived. + + --- + 🤖 Auto-closed by SpecWeave + ``` + +### 4. GitHub Project → Spec (Import) + +**Use Case**: Import existing GitHub Projects as SpecWeave specs + +**Command**: `/specweave-github:import-project ` + +**Actions**: +1. Fetch project via GitHub GraphQL API +2. Create spec structure: + - Parse project title → spec title + - Parse project body → spec overview + - Map issues → user stories + - Map labels → priority + +3. Generate spec.md with user stories and acceptance criteria +4. Link project to spec in metadata + +--- + +## Configuration + +Configure GitHub sync in `.specweave/config.json`: + +```json +{ + "plugins": { + "enabled": ["specweave-github"], + "settings": { + "specweave-github": { + "repo": "owner/repo", + "autoSyncSpecs": true, + "syncDirection": "two-way", + "defaultLabels": ["specweave", "spec"], + "syncFrequency": "on-change" + } + } + } +} +``` + +--- + +## GitHub CLI Requirements + +This skill requires GitHub CLI (`gh`) to be installed and authenticated: + +```bash +# Install GitHub CLI +brew install gh # macOS +sudo apt install gh # Ubuntu +choco install gh # Windows + +# Authenticate +gh auth login + +# Verify +gh auth status +``` + +--- + +## Manual Sync Operations + +### Sync Spec to GitHub + +```bash +/specweave-github:sync-spec spec-001 +``` + +Creates or updates GitHub Project for spec-001. + +### Sync All Specs + +```bash +/specweave-github:sync-spec --all +``` + +Syncs all specs to GitHub Projects. + +### Import Project + +```bash +/specweave-github:import-project 123 +``` + +Imports GitHub Project #123 as a SpecWeave spec. + +### Check Status + +```bash +/specweave-github:status spec-001 +``` + +Shows sync status (project ID, last sync time, progress %). + +--- + +## Workflow Integration + +### Full Automated Workflow + +```bash +# 1. Create spec (PM agent) +User: "Create spec for user authentication" +PM: Creates .specweave/docs/internal/specs/spec-005-user-auth.md + +# 2. Auto-sync to GitHub (hook) +→ GitHub Project created automatically +→ Issues created for each user story + +# 3. Implement increments +/specweave:increment "Add login flow" +→ Increment 0010 created (implements US-001, US-002) + +# 4. Work on tasks +/specweave:do +→ Task completed +→ Hook fires +→ Spec updated (AC marked complete) +→ GitHub Project updated automatically + +# 5. Complete spec +→ All user stories done +→ GitHub Project archived automatically +``` + +### Team Collaboration + +**For Developers**: +- Work in SpecWeave specs locally +- Automatic GitHub Project updates keep team informed +- No manual project management needed + +**For Project Managers**: +- View all specs as GitHub Projects +- Track progress in GitHub Projects UI +- Comment on issues to communicate with developers + +**For Stakeholders**: +- See progress in familiar GitHub interface +- No need to understand SpecWeave structure +- Clear visibility into feature development status + +--- + +## Conflict Resolution + +**What if project and spec diverge?** + +The spec is always the source of truth. GitHub Projects are a mirror for visibility. + +**Sync conflicts** (rare): +1. Spec status conflicts with project state +2. Manual edits to project/issue body/title + +**Resolution**: +- Run `/specweave-github:sync-spec spec-001 --force` to overwrite project from spec +- Or manually update spec metadata to match project + +--- + +## Privacy & Security + +**What gets synced?** +- ✅ Spec title, overview, progress +- ✅ User stories and acceptance criteria +- ✅ User story completion status +- ❌ Code diffs, file contents (never synced) +- ❌ Internal notes, sensitive data + +**Security**: +- Uses GitHub token from environment (GITHUB_TOKEN or GH_TOKEN) +- Respects repository permissions (read/write) +- No data sent to third parties + +--- + +## Benefits + +**For SpecWeave Users**: +- ✅ No manual GitHub project management +- ✅ Automatic team visibility +- ✅ Single source of truth (spec docs) +- ✅ GitHub integration without leaving IDE + +**For Teams**: +- ✅ Track SpecWeave work in GitHub Projects +- ✅ Use milestones, labels, assignees as usual +- ✅ Comment on issues to communicate with developers +- ✅ View progress in real-time + +**For Organizations**: +- ✅ Unified project tracking across repos +- ✅ GitHub-native workflow (familiar to all) +- ✅ Audit trail (all syncs timestamped) +- ✅ Integration with GitHub Actions, webhooks + +--- + +## Troubleshooting + +**Project not created?** +- Check GitHub CLI: `gh auth status` +- Verify repo permissions (write access) +- Check config: `.specweave/config.json` + +**Sync failing?** +- Check network connectivity +- Verify project still exists (not deleted) +- Check rate limits: `gh api rate_limit` + +**Progress not updating?** +- Check `autoSyncSpecs: true` in config +- Verify hook execution: `.specweave/logs/hooks-debug.log` +- Manually sync: `/specweave-github:sync-spec spec-001` + +--- + +## Advanced Usage + +### Custom Project Templates + +Create `.specweave/github/project-template.md`: + +```markdown +# [{{spec.id.toUpperCase()}}] {{spec.title}} + +{{spec.overview}} + +## SpecWeave Details + +- **Spec**: [spec.md]({{spec.url}}) +- **Priority**: {{spec.priority}} +- **Feature Area**: {{spec.featureArea}} + +## User Stories + +{{spec.userStories.map(us => `- ${us.id}: ${us.title}`).join('\n')}} +``` + +### Selective Sync + +Sync only specific specs: + +```json +{ + "plugins": { + "settings": { + "specweave-github": { + "syncSpecs": [ + "spec-001-core-framework", + "spec-005-user-authentication" + ] + } + } + } +} +``` + +### Multi-Repo Sync + +For monorepos with multiple GitHub repositories: + +```json +{ + "plugins": { + "settings": { + "specweave-github": { + "repos": { + "frontend": { + "repo": "myorg/frontend", + "specs": ["spec-001-*", "spec-002-*"] + }, + "backend": { + "repo": "myorg/backend", + "specs": ["spec-003-*", "spec-004-*"] + } + } + } + } + } +} +``` + +--- + +## Related + +- **github-issue-tracker**: Track individual tasks as issue comments (DEPRECATED - use spec sync instead) +- **github-manager agent**: AI agent for GitHub operations +- **Commands**: `/specweave-github:sync-spec`, `/specweave-github:import-project`, `/specweave-github:status` + +--- + +**Version**: 2.0.0 (Spec-based architecture) +**Plugin**: specweave-github +**Last Updated**: 2025-11-11