GitHub Project Management workflow for product development: PRD creation, epic/task breakdown, TDD execution, and QA planning
- version
- 0.3.0
- GitHub stars
- 12
Install
/plugin install ghpm@jebs-dev-toolsRun it inside Claude Code after adding the marketplace with /plugin marketplace add el-feo/ai-context.
Contents
Discovered from sourceCommands 11
Default behavior:
- If no
fromprovided, uses the most recent tag - If no tags exist, uses the first commit
<usage_examples> Generate changelog since last tag:
/ghpm:changelog
Generate changelog between versions:
/ghpm:changelog from=v1.0.0 to=v1.1.0
Generate changelog to specific file:
/ghpm:changelog output=docs/CHANGELOG.md
Generate changelog from date:
/ghpm:changelog from=2024-01-01
</usage_examples>
<operating_rules>
- Parse PR titles and commit messages for conventional commit format
- Group changes by type (feat, fix, refactor, etc.)
- Include PR numbers and links
- Include contributor attribution
- Handle breaking changes specially (highlight at top)
- Preserve existing changelog content when appending </operating_rules>
<changelog_format>
Output Format
# Changelog
## [Unreleased] OR [vX.Y.Z] - YYYY-MM-DD
### Breaking Changes
- **scope:** description (#PR) @contributor
### Features
- **scope:** description (#PR) @contributor
### Bug Fixes
- **scope:** description (#PR) @contributor
### Performance
- **scope:** description (#PR) @contributor
### Code Refactoring
- **scope:** description (#PR) @contributor
### Documentation
- **scope:** description (#PR) @contributor
### Testing
- **scope:** description (#PR) @contributor
### Maintenance
- **scope:** description (#PR) @contributor
Section Mapping
| Commit Type | Changelog Section |
|---|---|
feat | Features |
fix | Bug Fixes |
perf | Performance |
refactor | Code Refactoring |
docs | Documentation |
test | Testing |
chore | Maintenance |
build | Maintenance |
ci | Maintenance |
style | (excluded) |
revert | Reverts |
</changelog_format>
Step 1: Determine Range
# Get most recent tag if from not specified
FROM_REF="${FROM:-$(git describe --tags --abbrev=0 2>/dev/null || git rev-list --max-parents=0 HEAD)}"
TO_REF="${TO:-HEAD}"
echo "Generating changelog from $FROM_REF to $TO_REF"
Step 2: Fetch Merged PRs
# Get merged PRs in range
gh pr list \
--state merged \
--base main \
--json number,title,author,mergedAt,labels \
--jq '.[] | select(.mergedAt >= "'$FROM_DATE'")' \
> /tmp/prs.json
Alternatively, parse git log:
git log "$FROM_REF".."$TO_REF" --oneline --format="%s|%h|%an" > /tmp/commits.txt
Step 3: Parse Conventional Commits
For each PR title or commit message, extract:
- Type:
feat,fix,refactor, etc. - Scope: Optional scope in parentheses
- Breaking:
!after type orBREAKING CHANGE:in body - Description: The commit description
- PR number:
(#123)reference
Regex pattern:
^(feat|fix|refactor|perf|test|docs|chore|build|ci|style|revert)(\(.+\))?(!)?:\s*(.+?)(?:\s*\(#(\d+)\))?$
Step 4: Group by Type
Organize parsed commits into sections:
breaking_changes = []
features = []
fixes = []
performance = []
refactoring = []
documentation = []
testing = []
maintenance = []
reverts = []
Step 5: Generate Changelog Content
Build markdown content with:
- Version header (from
toref or "Unreleased") - Date (today or tag date)
- Sections in order (Breaking Changes first, then Features, etc.)
- Only include sections that have entries
- Each entry:
- **scope:** description (#PR) @author
Step 6: Write Output
OUTPUT_FILE="${OUTPUT:-CHANGELOG.md}"
# If file exists, insert new content after header
# Otherwise create new file
# Write content
cat > "$OUTPUT_FILE" << 'EOF'
# Changelog
<generated content>
EOF
If prepending to existing changelog:
# Read existing content (skip header)
EXISTING=$(tail -n +3 "$OUTPUT_FILE")
# Write new content + existing
cat > "$OUTPUT_FILE" << EOF
# Changelog
<new version content>
$EXISTING
EOF
<error_handling> If no conventional commits found:
- Warn user that commits don't follow conventional format
- Offer to list all commits without categorization
If no PRs in range:
- Check if range is valid
- Suggest alternative range
- Fall back to commit-based changelog
If output file not writable:
- Check permissions
- Suggest alternative path
- Output to stdout as fallback </error_handling>
<success_criteria> Command completes successfully when:
- Changelog content is generated
- Changes are properly grouped by type
- PR numbers and authors are included
- Breaking changes are highlighted
- Output file is written (or content displayed)
Output summary:
Changelog generated:
- Range: v1.0.0..HEAD
- PRs processed: 15
- Features: 5
- Bug Fixes: 3
- Refactoring: 4
- Other: 3
- Output: CHANGELOG.md
</success_criteria>
Proceed now.
Resolution order if omitted:
- Most recent open issue labeled
PRD
Optional environment variables:
GHPM_PROJECT- GitHub Project name to associate Epics with (e.g., "OrgName/ProjectName" or "ProjectName")
<usage_examples> With PRD number:
/ghpm:create-epics prd=#42
Auto-resolve most recent PRD:
/ghpm:create-epics
With project association:
export GHPM_PROJECT="MyOrg/Q1 Roadmap"
/ghpm:create-epics prd=#42
</usage_examples>
<operating_rules>
- Do not ask clarifying questions. If the PRD has ambiguity, encode it as assumptions within each Epic and/or add open questions.
- Do not create local markdown files. All output goes into GitHub issues/comments.
- Each Epic issue must be self-contained for its scope and must reference the PRD by number/link.
- Epics should collectively cover the entire PRD scope without gaps or overlaps.
Epic Count Guidelines
Default to 1 Epic. Only create multiple Epics when the PRD contains truly independent work streams that could be implemented by different people without coordination.
| PRD Type | Epic Count | Justification Required |
|---|---|---|
| Minimal (docs, config, single-file) | 1 | N/A |
| Small (single feature) | 1 | N/A |
| Medium (2-3 independent features) | 2-3 | Each Epic must deliver independent value |
| Large (platform/system) | 3-5 | Each Epic must be separable work stream |
Decision questions before creating multiple Epics:
- Would each Epic deliver independent, usable value if the others were never implemented?
- Could different developers implement each Epic without needing to coordinate on shared code?
- Is there a natural break point where work could pause between Epics?
If the answer to any question is "no", consolidate into fewer Epics.
Anti-patterns (DO NOT create separate Epics for these)
- "Infrastructure" vs "Integration": If the infrastructure is just code embedded in the integration, it's one Epic
- "Implementation" vs "Documentation": Docs are part of completing a feature, not a separate Epic
- "Backend" vs "Frontend": If the feature requires both to be useful, it's one Epic
- "Core" vs "Extensions": If extensions depend entirely on core, it's one Epic
- Per-file Epics: Creating Epics for each file touched rather than for outcomes
Example: Single-Feature PRD → 1 Epic
PRD: "Add issue claiming workflow to execute, tdd-task, and qa-execute commands"
❌ Wrong (3 Epics):
- Epic: Core Claiming Infrastructure
- Epic: Command Integration
- Epic: Documentation
❌ Why it's wrong: The "infrastructure" is just a bash function embedded in commands. Documentation is part of completing the feature. All three are tightly coupled.
✅ Correct (1 Epic):
- Epic: Issue Claiming Workflow
</operating_rules>
<epic_issue_format>
Required Epic Structure (Issue Body)
Use this streamlined template. Omit optional sections if empty.
# Epic: <Name>
**PRD:** #<PRD_NUMBER>
## Objective
<1-3 sentences: what this Epic accomplishes and delivers>
## Scope
<Bulleted list of specific deliverables - merge any "Key Requirements" here>
## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] ...
## Dependencies
<Only include if external dependencies exist; omit section entirely if none>
Template Guidance
- PRD link: Single line at top, not a separate "Links" section
- Objective: Concise statement of what this Epic delivers (not duplicating PRD content)
- Scope: Specific deliverables; merge "Key Requirements" here rather than separate section
- Acceptance Criteria: Checkboxes for Epic-level verification
- Dependencies: Only include if there are actual dependencies; omit if none
Omit these sections (redundant with PRD or rarely populated):
- Out of Scope (inherit from PRD)
- Risks / Edge Cases (inherit from PRD)
- Notes / Open Questions (use issue comments instead)
- Key Requirements (merge into Scope)
</epic_issue_format>
<input_validation>
Validation Checks
Before proceeding, verify:
# 1. Verify gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Verify in git repository
git rev-parse --git-dir > /dev/null 2>&1 || { echo "ERROR: Not in a git repository"; exit 1; }
# 3. Verify GitHub remote exists and get repo info
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner) || { echo "ERROR: No GitHub remote found"; exit 1; }
# 4. Get owner and repo for API calls
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO_NAME=$(gh repo view --json name -q '.name')
</input_validation>
Step 1: Validate Environment
Run input validation checks from previous section.
Step 2: Resolve PRD Number
# If prd=#N provided, extract N
if [[ "$ARGUMENTS" =~ prd=#([0-9]+) ]]; then
PRD="${BASH_REMATCH[1]}"
else
# Find most recent open PRD
PRD=$(gh issue list -l PRD -s open --limit 1 --json number -q '.[0].number')
if [ -z "$PRD" ]; then
echo "ERROR: No open PRD issues found. Create one with /ghpm:create-prd"
exit 1
fi
fi
echo "Using PRD #$PRD"
Step 3: Fetch PRD Content
# Verify PRD exists and get content
PRD_DATA=$(gh issue view "$PRD" --json title,body,url,number)
if [ -z "$PRD_DATA" ]; then
echo "ERROR: PRD #$PRD not found"
exit 1
fi
PRD_TITLE=$(echo "$PRD_DATA" | jq -r '.title')
PRD_BODY=$(echo "$PRD_DATA" | jq -r '.body')
PRD_URL=$(echo "$PRD_DATA" | jq -r '.url')
echo "PRD: $PRD_TITLE"
echo "URL: $PRD_URL"
Step 4: Generate Epics
Analyze the PRD scope and generate the minimum number of Epics needed. For narrow-scope PRDs (documentation updates, configuration changes, single-file modifications), a single Epic is often sufficient. Each Epic should:
- Cover a distinct, cohesive area of functionality
- Be independently implementable (with dependencies noted)
- Reference the PRD by number
- Represent meaningful, separable work (not artificial subdivisions)
Step 5: Create Epic Issues
# For each Epic, create an issue
gh issue create \
--repo "$REPO" \
--title "Epic: <Name>" \
--label "Epic" \
--body "$(cat <<'EOF'
<Generated Epic Content>
EOF
)"
# Capture issue number from output
EPIC_NUM=<captured from gh issue create output>
EPIC_URL=<captured from gh issue create output>
# Track created Epics
CREATED_EPICS+=("$EPIC_NUM|Epic: <Name>|$EPIC_URL")
Step 6: Add to GitHub Project (Optional)
if [ -n "$GHPM_PROJECT" ]; then
gh issue edit "$EPIC_NUM" --add-project "$GHPM_PROJECT" 2>/dev/null || {
echo "WARNING: Failed to add Epic #$EPIC_NUM to project '$GHPM_PROJECT'"
}
fi
Step 7: Link Epics as Sub-Issues of PRD
# Get the PRD's internal issue ID
PRD_ID=$(gh api "repos/$OWNER/$REPO_NAME/issues/$PRD" --jq .id)
for epic_info in "${CREATED_EPICS[@]}"; do
EPIC_NUM=$(echo "$epic_info" | cut -d'|' -f1)
# Get the Epic's internal issue ID
EPIC_ID=$(gh api "repos/$OWNER/$REPO_NAME/issues/$EPIC_NUM" --jq .id)
# Add Epic as sub-issue of PRD
gh api "repos/$OWNER/$REPO_NAME/issues/$PRD/sub_issues" \
-X POST \
-F sub_issue_id="$EPIC_ID" \
--silent && echo "✓ Linked Epic #$EPIC_NUM as sub-issue of PRD #$PRD" \
|| echo "WARNING: Could not link Epic #$EPIC_NUM as sub-issue"
done
Step 8: Post PRD Comment with Summary
COMMENT_BODY="## Epics Created
The following Epics have been created from this PRD:
$(for epic_info in "${CREATED_EPICS[@]}"; do
EPIC_NUM=$(echo "$epic_info" | cut -d'|' -f1)
EPIC_TITLE=$(echo "$epic_info" | cut -d'|' -f2)
echo "- #$EPIC_NUM $EPIC_TITLE"
done)
View sub-issues in the PRD's \"Sub-issues\" section.
---
*Generated by GHPM*"
gh issue comment "$PRD" --body "$COMMENT_BODY"
<error_handling> If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If not in git repository:
- Navigate to repository directory
- Verify with:
git status
If no GitHub remote:
- Check remote:
git remote -v - Add remote if needed:
git remote add origin <url>
If PRD not found:
- Verify PRD number:
gh issue view <number> - Check PRD label exists:
gh issue list -l PRD - Create PRD first:
/ghpm:create-prd <description>
If label "Epic" doesn't exist:
- Create it:
gh label create Epic --description "Epic issue" --color 1D76DB - Or omit
--label "Epic"from issue creation and continue
If issue creation fails:
- Check rate limits:
gh api rate_limit - Verify write permissions:
gh repo view --json viewerPermission -q .viewerPermission - Check repository exists and is accessible
If sub-issue linking fails:
- Sub-issues API may not be available for all repositories
- Command continues with warning
- Epics are still created and reference PRD in their body
If project association fails:
- Verify
GHPM_PROJECTformat is correct - Check project exists:
gh project list - Command continues with warning </error_handling>
<success_criteria> Command completes successfully when:
- All Epic issues are created with "Epic" label
- Each Epic body contains required sections: PRD link, Objective, Scope, Acceptance Criteria
- Each Epic references the PRD at the top of the body
- All Epics are linked as sub-issues of the PRD (or warnings issued)
- Summary comment is posted to PRD
- If
GHPM_PROJECTset, Epics are added to project (or warnings issued) - Optional sections (Dependencies) only included when populated with meaningful content
Verification:
# View created Epics
gh issue list -l Epic --json number,title,url
# Verify sub-issues are linked to PRD
gh api "repos/$OWNER/$REPO_NAME/issues/$PRD/sub_issues" --jq '.[] | "#\(.number) \(.title)"'
# View PRD comments
gh issue view "$PRD" --comments
</success_criteria>
After completion, report:- PRD: # -
- Epics Created:
- # Epic: -
- # Epic: -
- ...
- Sub-Issue Linking:
- Success count / Total count
- Any warnings
- Project Association:
- Success: "Added to project '<GHPM_PROJECT>'"
- Failure: "WARNING: Could not add to project"
- N/A: "No project specified"
- Next Step: "Run
/ghpm:create-tasks epic=#<number>to break an Epic into Tasks"
Example Output (Minimal PRD - single epic):
Epics Created Successfully
PRD: #42 - https://github.com/owner/repo/issues/42
Epics Created:
- #43 Epic: Update README Documentation - https://github.com/owner/repo/issues/43
Sub-Issue Linking: 1/1 successful
Project Association: No project specified
Next Step: Run `/ghpm:create-tasks epic=#43` to break an Epic into Tasks
Example Output (Large PRD - multiple epics):
Epics Created Successfully
PRD: #42 - https://github.com/owner/repo/issues/42
Epics Created:
- #43 Epic: User Authentication - https://github.com/owner/repo/issues/43
- #44 Epic: Database Schema - https://github.com/owner/repo/issues/44
- #45 Epic: API Endpoints - https://github.com/owner/repo/issues/45
- #46 Epic: Frontend Integration - https://github.com/owner/repo/issues/46
- #47 Epic: Testing & QA - https://github.com/owner/repo/issues/47
Sub-Issue Linking: 5/5 successful
Project Association: Added to project 'Q1 Roadmap'
Next Step: Run `/ghpm:create-tasks epic=#43` to break an Epic into Tasks
<related_commands> GHPM Workflow:
- Previous:
/ghpm:create-prd- Create PRD from user input - Current:
/ghpm:create-epics- Break PRD into Epics - Next:
/ghpm:create-tasks epic=#N- Break Epics into Tasks - Finally:
/ghpm:tdd-task [task=#N]- Implement Tasks with TDD
Related:
/ghpm:execute epic=#N- Execute all tasks in an Epic/ghpm:qa-create- Create QA issue for testing </related_commands>
Now proceed:
- Resolve PRD number from $ARGUMENTS or find most recent.
- Fetch PRD content and analyze scope.
- Determine appropriate Epic count based on scope complexity (1 Epic for narrow PRDs, more for larger scope).
- Generate Epics covering the entire PRD without artificial subdivision.
- Create each Epic issue via
gh issue create. - Link Epics as sub-issues of the PRD.
- Post summary comment to PRD.
Optional environment variables:
GHPM_PROJECT- GitHub Project name to associate issue with. If not set, the command will query available projects for the repository owner and prompt for selection.
<usage_examples>
Detailed input (skips clarification):
/ghpm:create-prd Build a user authentication system with email/password and OAuth support for enterprise customers who need SSO to reduce IT friction during onboarding
→ Detailed input (30+ words, has who/what/why) → Proceeds directly to PRD generation
Vague input (triggers clarification):
/ghpm:create-prd Add a dashboard
→ Vague input (4 words, missing who/why/scope) → Presents clarifying questions:
- Who is the primary user? (Internal team, Customers, Admins, Developers)
- What problem does this solve? (Efficiency, Missing capability, UX, Compliance)
- What's the scope? (MVP, Feature complete, Production-ready, Enterprise-grade)
After user responds → Generates PRD with enriched context
Complex feature (typically detailed enough):
/ghpm:create-prd Add real-time collaboration features to the document editor, similar to Google Docs, so remote teams can co-edit documents without version conflicts
→ Detailed input → Proceeds directly to PRD generation
With project association (auto-prompt):
/ghpm:create-prd Implement dark mode across the application for users with visual sensitivities to reduce eye strain
→ If GHPM_PROJECT not set, prompts: "Which GitHub Project should this PRD be added to?" with available projects
With project pre-set (skip prompt):
export GHPM_PROJECT="MyOrg/Q1 Roadmap"
/ghpm:create-prd Implement dark mode across the application for users with visual sensitivities to reduce eye strain
→ Skips project selection prompt and uses pre-set project
</usage_examples>
<operating_rules>
- For vague input: Use
AskUserQuestiontool to gather context before generating the PRD. See<vagueness_detection>for criteria. - For detailed input: Proceed directly to PRD generation. Make reasonable assumptions and explicitly record them under Assumptions and Open Questions.
- Do not create or persist local markdown artifacts (no local PRD files). All artifacts must live in GitHub issue bodies/comments.
- Use Markdown in the issue body. Make the PRD self-contained.
- Keep scope crisp; if the request is broad, define a "V1" and park the rest in Out of Scope / Future Ideas.
- Clarification should be quick (max 4 questions) - do not interrogate the user. </operating_rules>
<prd_structure>
Required PRD Structure (Issue Body)
Use this exact outline:
# PRD: <Concise Name>
## Summary
## Problem / Opportunity
## Goals (Success Metrics)
## Non-Goals / Out of Scope
## Users & Use Cases
## Requirements
- Functional Requirements
- Non-Functional Requirements
## UX / UI Notes (if relevant)
## Data / Integrations (if relevant)
## Risks / Edge Cases
## Assumptions
## Open Questions
## Acceptance Criteria (high level)
## Rollout / Release Notes (brief)
## Implementation Notes (non-binding)
(Keep this section minimal; do not over-prescribe.)
</prd_structure>
<input_validation>
Validation Checks
Before proceeding, verify:
# 1. Verify gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Verify in git repository
git rev-parse --git-dir > /dev/null 2>&1 || { echo "ERROR: Not in a git repository"; exit 1; }
# 3. Verify GitHub remote exists
gh repo view --json nameWithOwner -q .nameWithOwner || { echo "ERROR: No GitHub remote found"; exit 1; }
If $ARGUMENTS is empty or missing, report an error:
ERROR: Product idea or feature description required
Usage: /ghpm:create-prd <description>
</input_validation>
<vagueness_detection>
Detecting Vague Input
Before generating the PRD, evaluate whether user input is sufficiently detailed. Input is considered vague if ANY of the following criteria are met:
Vagueness Criteria
| Criterion | Threshold | Example (Vague) | Example (Detailed) |
|---|---|---|---|
| Too short | < 20 words | "I want a dashboard" | "Build an analytics dashboard for sales managers to track quarterly revenue, pipeline metrics, and team performance with drill-down by region" |
| Missing 'who' | No target user/audience mentioned | "Add authentication" | "Add OAuth2 authentication for enterprise customers who need SSO" |
| Missing 'what' | No specific functionality described | "Improve performance" | "Optimize database queries in the user search endpoint to reduce p95 latency below 200ms" |
| Missing 'why' | No problem/goal articulated | "Add export feature" | "Add CSV export for compliance reports so auditors can analyze data offline" |
| Ambiguous scope | Could mean vastly different things | "Make it mobile-friendly" | "Create responsive layouts for the checkout flow that work on screens 320px to 768px wide" |
Evaluation Process
- Count words in input (excluding common stop words for accuracy assessment)
- Scan for user/audience indicators: "users", "customers", "admins", "managers", "developers", etc.
- Scan for problem/goal indicators: "so that", "in order to", "because", "to enable", "to reduce", etc.
- Assess specificity: Does the input contain concrete details (numbers, specific features, constraints)?
If 2+ criteria are triggered: Proceed to clarification step If 0-1 criteria triggered: Skip clarification, proceed directly to PRD generation
</vagueness_detection>
<clarification_questions>
Clarifying Questions
When vague input is detected, use the AskUserQuestion tool to gather context. Select 2-4 questions based on what's missing from the input.
Question Templates
Q1: Target Users (use when 'who' is missing)
{
"question": "Who is the primary user of this feature?",
"header": "Users",
"multiSelect": false,
"options": [
{"label": "End users/customers", "description": "People using the product directly"},
{"label": "Internal team members", "description": "Employees within the organization"},
{"label": "Administrators", "description": "Users who configure or manage the system"},
{"label": "Developers/API consumers", "description": "Technical users integrating with the system"}
]
}
Q2: Problem Being Solved (use when 'why' is missing)
{
"question": "What problem does this solve for users?",
"header": "Problem",
"multiSelect": false,
"options": [
{"label": "Efficiency/speed", "description": "Reduce time or effort to complete tasks"},
{"label": "Missing capability", "description": "Enable something users currently cannot do"},
{"label": "User experience", "description": "Improve usability, accessibility, or satisfaction"},
{"label": "Compliance/security", "description": "Meet regulatory or security requirements"}
]
}
Q3: Core Capabilities (use when 'what' is vague)
{
"question": "Which capabilities are most important?",
"header": "Features",
"multiSelect": true,
"options": [
{"label": "View/display data", "description": "Read-only access to information"},
{"label": "Create/edit content", "description": "CRUD operations on data"},
{"label": "Automation/workflows", "description": "Automated processes or triggers"},
{"label": "Reporting/analytics", "description": "Insights, charts, or exports"}
]
}
Q4: Technical Constraints (use when scope is ambiguous)
{
"question": "Are there specific technical constraints?",
"header": "Constraints",
"multiSelect": true,
"options": [
{"label": "Must integrate with existing system", "description": "Needs to work with current infrastructure"},
{"label": "Performance-critical", "description": "High throughput or low latency required"},
{"label": "Mobile support required", "description": "Must work on mobile devices"},
{"label": "No constraints", "description": "Greenfield implementation"}
]
}
Q5: Scope/Priority (use when input could mean many things)
{
"question": "What's the scope for the initial version?",
"header": "Scope",
"multiSelect": false,
"options": [
{"label": "MVP/proof of concept", "description": "Minimal viable version to validate the idea"},
{"label": "Feature complete for core use case", "description": "Fully functional for primary scenario"},
{"label": "Production-ready with edge cases", "description": "Robust handling of all scenarios"},
{"label": "Enterprise-grade", "description": "Scalability, security, and compliance built-in"}
]
}
Selecting Questions
Based on vagueness detection results, select appropriate questions:
| Missing Element | Questions to Ask |
|---|---|
| Who (users) | Q1 (Target Users) |
| Why (problem) | Q2 (Problem Being Solved) |
| What (features) | Q3 (Core Capabilities) |
| Scope unclear | Q4 (Technical Constraints), Q5 (Scope/Priority) |
| Multiple missing | Combine up to 4 questions maximum |
Incorporating Responses
After receiving user responses, append them to the original input before generating the PRD:
Original input: "I want a dashboard"
Enriched context from clarification:
- Target users: Internal team members
- Problem: Efficiency/speed - reduce time to complete tasks
- Capabilities: Reporting/analytics, View/display data
- Scope: Feature complete for core use case
Generate PRD using both original input AND enriched context.
</clarification_questions>
## Step 1: Validate EnvironmentRun input validation checks from previous section.
Step 2: Determine Repository and Owner
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
OWNER=$(gh repo view --json owner -q .owner.login)
Step 3: Select GitHub Project (if not pre-set)
If GHPM_PROJECT environment variable is already set, skip to Step 4.
Otherwise, query available projects for the repository owner and prompt the user to select one:
# Get list of projects for the repo owner
PROJECTS=$(gh project list --owner "$OWNER" --format json --limit 20)
If projects exist: Use AskUserQuestion to let the user select a project.
Build the question dynamically based on available projects:
{
"question": "Which GitHub Project should this PRD be added to?",
"header": "Project",
"multiSelect": false,
"options": [
{"label": "<Project Title 1>", "description": "Project #<number>"},
{"label": "<Project Title 2>", "description": "Project #<number>"},
...
{"label": "None", "description": "Do not add to any project"}
]
}
- Include up to 4 projects (the most recently updated, or first 4 returned)
- Always include "None" as the last option
- If user selects a project, set
GHPM_PROJECTto the selected project title - If user selects "None", leave
GHPM_PROJECTunset
If no projects exist: Skip project selection and inform the user:
No GitHub Projects found for owner '$OWNER'. Skipping project association.
To create a project, visit: https://github.com/<owner>?tab=projects
Step 4: Evaluate Input & Clarify (if needed)
Evaluate user input against the vagueness criteria in <vagueness_detection>.
If input is sufficiently detailed (0-1 criteria triggered):
- Skip to Step 5 (Draft PRD Content)
If input is vague (2+ criteria triggered):
- Identify which elements are missing (who, what, why, scope)
- Select appropriate questions from
<clarification_questions>(max 4) - Use
AskUserQuestiontool to present questions:
Use the AskUserQuestion tool with the selected question templates.
Wait for user responses before proceeding.
- Combine original input with user responses to form enriched context
- Proceed to Step 5 with enriched context
Example clarification flow:
Input: "I want a dashboard"
Vagueness analysis:
- ✗ Too short (4 words < 20)
- ✗ Missing 'who' (no user mentioned)
- ✗ Missing 'why' (no problem stated)
- ✓ Has 'what' (dashboard is a feature)
- ✗ Ambiguous scope (dashboard could mean many things)
→ 4 criteria triggered → Ask Q1 (Users), Q2 (Problem), Q5 (Scope)
Step 5: Draft PRD Content
Based on user input ($ARGUMENTS) and any enriched context from clarification, generate comprehensive PRD following the structure template.
Step 6: Create GitHub Issue
# Use heredoc to safely handle multiline content
gh issue create \
--repo "$REPO" \
--title "PRD: <Concise Name>" \
--label "PRD" \
--body "$(cat <<'EOF'
<Generated PRD Content>
EOF
)"
Step 7: Add to GitHub Project
Use the new GitHub Projects API (gh project item-add) instead of the deprecated --add-project flag.
if [ -n "$GHPM_PROJECT" ]; then
# Get the issue URL (needed for gh project item-add)
ISSUE_URL=$(gh issue list --repo "$REPO" -l PRD --limit 1 --json url -q '.[0].url')
# Get project number from the project list
# GHPM_PROJECT can be either the project title or number
if [[ "$GHPM_PROJECT" =~ ^[0-9]+$ ]]; then
PROJECT_NUMBER="$GHPM_PROJECT"
else
# Look up project number by title
PROJECT_NUMBER=$(gh project list --owner "$OWNER" --format json | \
jq -r --arg title "$GHPM_PROJECT" '.projects[] | select(.title == $title) | .number')
fi
if [ -n "$PROJECT_NUMBER" ]; then
gh project item-add "$PROJECT_NUMBER" --owner "$OWNER" --url "$ISSUE_URL" 2>/dev/null || {
echo "WARNING: Failed to add issue to project '$GHPM_PROJECT'"
ISSUE_NUMBER=$(echo "$ISSUE_URL" | grep -oE '[0-9]+$')
gh issue comment "$ISSUE_NUMBER" --body "Note: Could not automatically add to project '$GHPM_PROJECT'. Please add manually if needed."
}
else
echo "WARNING: Could not find project '$GHPM_PROJECT'"
fi
fi
Note: The gh project item-add command requires:
- Project number (not title) - we look this up from the project list
- Owner (user or organization)
- Issue URL (not issue number)
<error_handling> If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If not in git repository:
- Navigate to repository directory
- Verify with:
git status
If no GitHub remote:
- Check remote:
git remote -v - Add remote if needed:
git remote add origin <url>
If label "PRD" doesn't exist:
- Create it:
gh label create PRD --description "Product Requirements Document" --color 0E8A16 - Or omit
--label "PRD"from issue creation and continue
If issue creation fails:
- Check rate limits:
gh api rate_limit - Verify write permissions:
gh repo view --json viewerPermission -q .viewerPermission - Check repository exists and is accessible
If project association fails:
- Verify
GHPM_PROJECTis either the project number or exact title - Check project exists:
gh project list --owner <OWNER> - Ensure the new Projects API is used (
gh project item-add), not the deprecated--add-projectflag - Common error: "Projects (classic) is being deprecated" means you're using the old API
- Command will continue and add warning comment to issue </error_handling>
<success_criteria> Command completes successfully when:
- PRD issue is created with "PRD" label
- Issue body contains all required sections from PRD structure
- Issue number and URL are captured
- If
GHPM_PROJECTset, issue is added to project (or warning issued)
Verification:
# View the created PRD
gh issue view <issue_number>
# List all PRD issues
gh issue list -l PRD --json number,title,url
</success_criteria>
After completion, report:- PRD Issue: # -
- Repository: /
- Project Association:
- Success: "Added to project '<GHPM_PROJECT>'"
- Failure: "WARNING: Could not add to project (see issue comment)"
- N/A: "No project specified"
- Next Step: "Run
/ghpm:create-epics prd=#<number>to break this PRD into Epics"
Example Output:
PRD Created Successfully
PRD Issue: #42 - https://github.com/owner/repo/issues/42
Repository: owner/repo
Project Association: Added to project 'Q1 Roadmap'
Next Step: Run `/ghpm:create-epics prd=#42` to break this PRD into Epics
<related_commands> GHPM Workflow:
- Current:
/ghpm:create-prd- Create PRD from user input - Next:
/ghpm:create-epics [prd=#N]- Break PRD into Epics - Then:
/ghpm:create-tasks epic=#N- Break Epics into Tasks - Finally:
/ghpm:tdd-task [task=#N]- Implement Tasks with TDD
Related:
/gh-create-epic- Create standalone Epic (not part of GHPM workflow) </related_commands>
Now proceed:
- Validate environment prerequisites.
- Determine repository and owner.
- If
GHPM_PROJECTnot set: Query projects for owner and prompt user to select one. - Evaluate input against vagueness criteria.
- If vague (2+ criteria triggered): Use AskUserQuestion to gather context.
- Draft the PRD from $ARGUMENTS (and enriched context if clarified).
- Create the issue via
gh issue create. - Add it to the GitHub project if
GHPM_PROJECTis set.
Optional environment variables:
GHPM_TEMPLATE_PROJECT- Project number to use as template (e.g., "7")GHPM_TEMPLATE_OWNER- Owner of the template project (defaults to current repo owner)
<usage_examples>
With title argument:
/ghpm:create-project Q1 Roadmap
→ Creates project titled "Q1 Roadmap", links to current repo
Without title (prompts):
/ghpm:create-project
→ Prompts: "What should the project be called?" → Creates and links project
With template pre-configured:
export GHPM_TEMPLATE_PROJECT="7"
/ghpm:create-project Feature Development
→ Copies from template project #7, links to current repo
</usage_examples>
<operating_rules>
- Always prompt for project title if not provided via $ARGUMENTS
- Check for template projects before creating blank project
- Link the project to the current repository after creation
- Set
GHPM_PROJECTto the new project title for use in subsequent commands - Report the project URL so user can configure views manually if needed
</operating_rules>
<input_validation>
Validation Checks
Before proceeding, verify:
# 1. Verify gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Verify project scope
gh auth status 2>&1 | grep -q "project" || echo "WARNING: Token may not have 'project' scope. Run 'gh auth refresh -s project' if project creation fails."
# 3. Verify in git repository
git rev-parse --git-dir > /dev/null 2>&1 || { echo "ERROR: Not in a git repository"; exit 1; }
# 4. Verify GitHub remote exists
gh repo view --json nameWithOwner -q .nameWithOwner || { echo "ERROR: No GitHub remote found"; exit 1; }
</input_validation>
Step 1: Validate Environment
Run input validation checks from previous section.
Step 2: Determine Repository and Owner
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
OWNER=$(gh repo view --json owner -q .owner.login)
Step 3: Get Project Title
If $ARGUMENTS contains a title: Use it directly.
TITLE="$ARGUMENTS"
If $ARGUMENTS is empty: Use AskUserQuestion to prompt for the title.
{
"question": "What should the new GitHub Project be called?",
"header": "Title",
"multiSelect": false,
"options": [
{"label": "Roadmap", "description": "General product roadmap"},
{"label": "Sprint Board", "description": "Agile sprint tracking"},
{"label": "Feature Development", "description": "Feature work tracking"}
]
}
- If user selects an option, use that as
TITLE - If user selects "Other" and provides custom text, use that as
TITLE
Step 4: Check for Template Project
If GHPM_TEMPLATE_PROJECT is set:
TEMPLATE_OWNER="${GHPM_TEMPLATE_OWNER:-$OWNER}"
TEMPLATE_NUMBER="$GHPM_TEMPLATE_PROJECT"
# Verify template exists
gh project view "$TEMPLATE_NUMBER" --owner "$TEMPLATE_OWNER" --format json > /dev/null 2>&1
If not set: Check if owner has any template projects available:
# Query for template projects
TEMPLATES=$(gh api graphql -f query="
{
user(login: \"$OWNER\") {
projectsV2(first: 10) {
nodes {
number
title
template
}
}
}
}" --jq '.data.user.projectsV2.nodes | map(select(.template == true))')
# For organizations, use:
# gh api graphql -f query="{ organization(login: \"$OWNER\") { ... } }"
If templates found: Use AskUserQuestion to let user choose:
{
"question": "Would you like to create from a template project?",
"header": "Template",
"multiSelect": false,
"options": [
{"label": "<Template Name 1>", "description": "Project #<number> - includes pre-configured views"},
{"label": "<Template Name 2>", "description": "Project #<number> - includes pre-configured views"},
{"label": "Blank project", "description": "Start fresh with default Table view only"}
]
}
Step 5: Create the Project
Option A: Copy from template
PROJECT_DATA=$(gh project copy "$TEMPLATE_NUMBER" \
--source-owner "$TEMPLATE_OWNER" \
--target-owner "$OWNER" \
--title "$TITLE" \
--format json)
PROJECT_NUMBER=$(echo "$PROJECT_DATA" | jq -r '.number')
PROJECT_URL=$(echo "$PROJECT_DATA" | jq -r '.url')
Option B: Create blank project
PROJECT_DATA=$(gh project create \
--owner "$OWNER" \
--title "$TITLE" \
--format json)
PROJECT_NUMBER=$(echo "$PROJECT_DATA" | jq -r '.number')
PROJECT_URL=$(echo "$PROJECT_DATA" | jq -r '.url')
Step 6: Link Project to Repository
gh project link "$PROJECT_NUMBER" --owner "$OWNER" --repo "$REPO"
Step 7: Set GHPM_PROJECT Variable
Report the command to set the environment variable:
export GHPM_PROJECT="$TITLE"
<error_handling>
If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If missing project scope:
- Check:
gh auth status(look for "project" in scopes) - Fix:
gh auth refresh -s project
If template project not found:
- Verify template number:
gh project view <number> --owner <owner> - Fall back to creating blank project
If project creation fails:
- Check rate limits:
gh api rate_limit - Verify owner permissions
- Check if project with same name already exists
If linking fails:
- Verify repository exists:
gh repo view - Project may already be linked (not an error)
</error_handling>
<success_criteria>
Command completes successfully when:
- Project is created (from template or blank)
- Project is linked to current repository
- Project number and URL are captured
- User is informed how to set
GHPM_PROJECT
Verification:
# View the created project
gh project view <project_number> --owner <owner>
# Verify link to repository
gh api graphql -f query='
{
repository(owner: "<owner>", name: "<repo>") {
projectsV2(first: 5) {
nodes { title number }
}
}
}'
</success_criteria>
After completion, report:
- Project Created: "" (#<number>)
- URL: <project_url>
- Repository: /
- Created From: "Template: <template_name>" or "Blank project"
- Linked: Yes/No
Example Output:
Project Created Successfully
Project: "Q1 Roadmap" (#8)
URL: https://github.com/users/el-feo/projects/8
Repository: el-feo/ai-context
Created From: Template "GHPM Template" (#7)
Linked: Yes
To use this project with GHPM commands, run:
export GHPM_PROJECT="Q1 Roadmap"
Or add to your shell profile for persistence.
Next Steps:
- Configure views in the project UI if needed: <project_url>
- Run `/ghpm:create-prd <description>` to create your first PRD
If created from blank project, add:
Note: This project was created without a template.
Visit the project URL to add custom views (Board, Roadmap, etc.)
<template_setup>
Creating a Template Project (One-Time Setup)
To enable the "copy from template" feature, create a template project:
-
Create a project manually with your desired configuration:
- Add views (Board, Table, Roadmap)
- Configure fields (Status, Priority, Sprint, etc.)
- Set up filters and groupings
-
Mark it as a template:
gh project mark-template <project_number> --owner <owner> -
Optionally set as default template:
export GHPM_TEMPLATE_PROJECT="<project_number>" export GHPM_TEMPLATE_OWNER="<owner>"
Recommended Template Configuration:
-
Views:
- Table (default) - All items
- Board - Grouped by Status
- Roadmap - Timeline view
-
Fields:
- Status: Todo, In Progress, In Review, Done
- Priority: High, Medium, Low
- Type: PRD, Epic, Task
- Sprint/Iteration (optional)
</template_setup>
<related_commands>
GHPM Workflow:
- Current:
/ghpm:create-project- Create and link a GitHub Project - Next:
/ghpm:create-prd <description>- Create PRD in the project - Then:
/ghpm:create-epics prd=#N- Break PRD into Epics - Then:
/ghpm:create-tasks epic=#N- Break Epics into Tasks - Finally:
/ghpm:tdd-task task=#N- Implement Tasks with TDD
</related_commands>
Now proceed:
- Validate environment prerequisites.
- Determine repository and owner.
- Get project title from $ARGUMENTS or prompt user.
- Check for available template projects.
- If templates available, ask user to choose template or blank.
- Create the project (copy from template or create blank).
- Link the project to the current repository.
- Report success and next steps.
Resolution order if omitted:
- Most recent open Epic issue:
gh issue list -l Epic -s open --limit 1 --json number -q '.[0].number'
<usage_examples> With epic number:
/ghpm:create-tasks epic=#42
With PRD number (creates tasks for all linked Epics):
/ghpm:create-tasks prd=#10
Auto-resolve most recent Epic:
/ghpm:create-tasks
</usage_examples>
<operating_rules>
- Do not ask clarifying questions. Make assumptions and record them.
- Do not create local markdown files. All output goes into GitHub issues/comments.
- Tasks must be atomic and independently executable by a human or agent.
- Each Task must include all context needed for its scope (plus links to Epic/PRD).
- Each Task MUST include a Commit Type (
feat,fix,refactor, etc.) and Scope for conventional commits. - Task count must be proportional to Epic scope - see guidance below.
- Each Task MUST have a Fibonacci estimate (1, 2, 3, 5, or 8) - see estimation guidance below. </operating_rules>
<estimation_guidance>
Fibonacci Estimation Scale
Assign a Fibonacci estimate to each Task based on relative complexity. Estimates reflect effort/complexity, not hours.
| Estimate | Complexity | Examples |
|---|---|---|
| 1 | Trivial | Update README, fix typo, change config value |
| 2 | Simple | Add a single test, update documentation section, simple refactor |
| 3 | Moderate | Add simple feature, refactor small module, add validation |
| 5 | Complex | Multi-file feature, significant refactor, new API endpoint |
| 8 | Very Complex | Cross-cutting feature, complex integration, architectural change |
Decomposition Rule
Tasks estimated >8 MUST be decomposed. If a task would be estimated higher than 8:
- Do NOT create the task as-is
- Break it into smaller, independent tasks
- Each sub-task should be estimable at 8 or below
- Re-analyze scope to find natural boundaries
Estimation Heuristics
- File count: 1 file = 1-2, 2-3 files = 3, 4+ files = 5-8
- Test requirements: No tests = lower, comprehensive tests = higher
- Dependencies: Self-contained = lower, cross-cutting = higher
- Unknowns: Clear requirements = lower, exploration needed = higher
</estimation_guidance>
<task_count_guidance>
Determining Appropriate Task Count
Match task count to Epic complexity, not a fixed range. Over-decomposition creates overhead without value.
Heuristics
| Epic Scope | Task Count | Example |
|---|---|---|
| Single file, simple change | 1 task | Update README, fix typo, change config |
| Single file, multiple changes | 1-2 tasks | Refactor a module, update docs with verification |
| Multiple related files | 2-4 tasks | Add feature touching model + controller + view |
| Cross-cutting feature | 4-8 tasks | New API endpoint with auth, tests, docs |
| Large architectural change | 8-15 tasks | Database migration, new service layer |
Signs of Over-Decomposition
- Tasks that would result in the same commit
- Tasks that can't be meaningfully verified independently
- "Verify X" as a separate task from "Update X"
- Multiple tasks touching the same file for related changes
Signs of Under-Decomposition
- Task requires multiple unrelated commits
- Task touches many files across different concerns
- Task has acceptance criteria spanning multiple features
Rule of Thumb
If an Epic affects 1-2 files with a clear scope, 1-2 tasks is usually sufficient.
</task_count_guidance>
<input_validation>
Validation Checks
Before proceeding, validate:
# 1. Check gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Validate issue number format (if provided)
# Epic and PRD numbers must be positive integers
# 3. Verify issue exists and is accessible
gh issue view "$EPIC" > /dev/null 2>&1 || { echo "ERROR: Cannot access issue #$EPIC"; exit 1; }
</input_validation>
<task_issue_format>
Task Issue Body Template
Use this streamlined template. Tasks link to Epic only (PRD reachable via Epic).
# Task: <Name>
**Epic:** #<EPIC_NUMBER> | **Type:** `<type>` | **Scope:** `<scope>`
## Objective
<1-2 sentences: what to implement>
## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] ...
## Test Plan
<How to verify completion - manual steps, test commands, or verification approach>
Template Guidance
- Context line: Single line with Epic link, commit type, and scope (no PRD link - navigate via Epic)
- Objective: Concise statement merging previous "Objective" and "Scope (In)" sections
- Acceptance Criteria: Task-level, testable criteria
- Test Plan: How to verify the task is complete
Omit these sections (redundant or rarely populated):
- PRD link (reachable via Epic)
- Scope (In) (merge into Objective)
- Out of Scope (inherit from Epic)
- Implementation Notes (use comments if needed)
- Risks / Edge Cases (inherit from Epic/PRD)
- Notes / Open Questions (use issue comments instead)
Commit Type Guidelines
The Commit Type field determines the conventional commit prefix used during implementation:
| Type | Use When |
|---|---|
feat | Adding new functionality, features, or capabilities |
fix | Fixing bugs, errors, or incorrect behavior |
refactor | Restructuring code without changing behavior |
test | Adding or improving tests only |
docs | Documentation changes only |
chore | Build, CI, dependencies, or tooling changes |
How to determine:
- Task creates new user-facing behavior →
feat - Task fixes reported issue/bug →
fix - Task improves code quality without behavior change →
refactor - Task adds/updates tests without implementation →
test - Task updates documentation →
docs - Task updates build/CI/tooling →
chore
</task_issue_format>
Step 1: Resolve Target Epic(s)
# If epic=#N provided, use N
EPIC={provided_epic_number}
# Else if prd=#N provided, find Epics as sub-issues of the PRD
# NOTE: Use heredoc to avoid shell escaping issues with '!' characters
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO=$(gh repo view --json name -q '.name')
cat > /tmp/ghpm-subissues.graphql << 'GRAPHQL'
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $number) {
subIssues(first: 50) {
nodes {
number
title
state
labels(first: 10) {
nodes { name }
}
}
}
}
}
}
GRAPHQL
gh api graphql -F owner="$OWNER" -F repo="$REPO" -F number=$PRD \
-f query="$(cat /tmp/ghpm-subissues.graphql)" \
--jq '.data.repository.issue.subIssues.nodes[] | select(.state == "OPEN") | select(.labels.nodes[].name == "Epic") | [.number, .title] | @tsv'
# Else pick most recent open Epic
gh issue list -l Epic -s open --limit 1 --json number -q '.[0].number'
Step 2: Fetch Epic Context
For each Epic:
# Fetch Epic body and metadata
gh issue view "$EPIC" --json title,body,url,labels -q '.'
Extract from Epic:
- Objective and scope
- PRD reference (look for
PRD: #123or similar pattern) - Acceptance criteria to decompose
Step 3: Generate Task Issues
For each Epic, generate the appropriate number of atomic tasks based on the task count guidance above.
Create each task:
# Create the task issue
TASK_URL=$(gh issue create \
--title "Task: <Name>" \
--label "Task" \
--body "<Task markdown from template>")
# Extract task number from URL
TASK_NUM=$(echo "$TASK_URL" | grep -oE '[0-9]+$')
# Set the estimate value determined during task planning (1, 2, 3, 5, or 8)
ESTIMATE=<fibonacci_number> # Replace with actual estimate, e.g., ESTIMATE=3
If $GHPM_PROJECT is set (project number), add the task to the project and set the Estimate field:
# Add task to project and set estimate (if GHPM_PROJECT is set)
if [ -n "$GHPM_PROJECT" ]; then
# Add to project (GHPM_PROJECT should be the project number, e.g., "7")
ITEM_ID=$(gh project item-add "$GHPM_PROJECT" --owner "$OWNER" --url "$TASK_URL" --format json 2>/dev/null | jq -r '.id')
if [ -n "$ITEM_ID" ] && [ "$ITEM_ID" != "null" ]; then
# Get project ID and Estimate field ID
PROJECT_DATA=$(gh project view "$GHPM_PROJECT" --owner "$OWNER" --format json 2>/dev/null)
PROJECT_ID=$(echo "$PROJECT_DATA" | jq -r '.id')
ESTIMATE_FIELD_ID=$(gh project field-list "$GHPM_PROJECT" --owner "$OWNER" --format json 2>/dev/null | jq -r '.fields[] | select(.name == "Estimate") | .id')
if [ -n "$ESTIMATE_FIELD_ID" ] && [ "$ESTIMATE_FIELD_ID" != "null" ]; then
# Set estimate value (ESTIMATE is the Fibonacci number assigned to this task)
gh project item-edit --project-id "$PROJECT_ID" --id "$ITEM_ID" --field-id "$ESTIMATE_FIELD_ID" --number "$ESTIMATE" 2>/dev/null \
&& echo "✓ Set estimate $ESTIMATE for Task #$TASK_NUM" \
|| echo "WARNING: Could not set estimate for Task #$TASK_NUM"
else
echo "WARNING: Estimate field not found in project. Add a Number field named 'Estimate'."
fi
else
echo "WARNING: Could not add Task #$TASK_NUM to project '$GHPM_PROJECT'"
fi
fi
Step 4: Link Tasks as Sub-Issues of Epic
IMPORTANT: Tasks MUST be linked as sub-issues of the Epic, not just listed in a comment.
For each created task, link it as a sub-issue:
# Get the Epic's internal issue ID
EPIC_ID=$(gh api repos/{owner}/{repo}/issues/$EPIC --jq .id)
# Get the Task's internal issue ID
TASK_ID=$(gh api repos/{owner}/{repo}/issues/$TASK_NUM --jq .id)
# Add task as sub-issue of Epic
gh api repos/{owner}/{repo}/issues/$EPIC/sub_issues \
-X POST \
-F sub_issue_id=$TASK_ID \
--silent || echo "Warning: Could not link Task #$TASK_NUM as sub-issue"
After all tasks are created and linked, optionally comment on the Epic with a summary:
gh issue comment "$EPIC" --body "$(cat <<'EOF'
## Tasks Created
Created and linked as sub-issues:
- #<TASK_1> Task: <Name>
- #<TASK_2> Task: <Name>
...
View sub-issues in the Epic's "Sub-issues" section.
EOF
)"
Step 5: Update PRD (if known)
If PRD is known, comment on the PRD (one comment per Epic, avoid spam):
gh issue comment "$PRD" --body "Tasks created for Epic #$EPIC - see checklist on the Epic."
<error_handling> If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If Epic/PRD not found:
- Verify issue number is correct
- Check repository access permissions
- Confirm issue is not closed/deleted
If issue creation fails:
- Check rate limits:
gh api rate_limit - Verify label "Task" exists or omit label
- Check repository write permissions
If sub-issue linking fails:
- Continue with next task (don't block on linking failures)
- Log warning in output summary with specific task number
- Common causes: task already has a parent, duplicate sub-issue, API error
- Verify with:
gh api repos/{owner}/{repo}/issues/$EPIC/sub_issues
If project association fails:
- Continue without project association
- Log warning in output summary
- Verify
$GHPM_PROJECTvalue is correct
If Estimate field is missing from project:
- Log warning: "Estimate field not found in project. Add a Number field named 'Estimate'."
- Continue without setting estimate
- Tasks are still created and linked correctly
- Provide setup instructions in warning
If task would exceed estimate of 8:
- Do NOT create the task
- Log: "Task scope too large (would be >8). Decomposing into smaller tasks."
- Break task into smaller units (each ≤8)
- Create the smaller tasks instead </error_handling>
<success_criteria> Command completes successfully when:
- All target Epics have been processed
- Each Epic has an appropriate number of Task issues (per task count guidance)
- Each Task issue contains required sections: Context line (Epic, Type, Scope), Objective, Acceptance Criteria, Test Plan
- Each Task has a Fibonacci estimate (1, 2, 3, 5, or 8) - no task exceeds 8
- Each Task is linked as a sub-issue of its Epic
- If
GHPM_PROJECTset, Estimate field is populated (or warning issued if field missing) - PRD is notified (if applicable)
- Optional sections omitted when not populated with meaningful content
Verification:
# List created tasks
gh issue list -l Task -s open --limit 50 --json number,title
# Verify sub-issues are linked to Epic
gh api repos/{owner}/{repo}/issues/$EPIC/sub_issues --jq '.[] | [.number, .title] | @tsv'
# View Epic to confirm (sub-issues appear in issue view)
gh issue view "$EPIC"
</success_criteria>
After completion, report:-
Epic(s) processed: # and URL for each
-
Tasks created: Issue numbers, URLs, and estimates
Task Title Estimate #N Task: Name 3 -
Sub-issue linking: Success/failure for each task linked to Epic
-
Total tasks: Count per Epic, total estimate points
-
Project association: Success/failure status (if
$GHPM_PROJECTset) -
Estimate field: Success/failure for setting estimates (if
$GHPM_PROJECTset) -
Warnings: Any issues encountered (e.g., sub-issue linking failed, project add failed, Estimate field missing)
Proceed now.
- TDD workflow (
/ghpm:tdd-task): Forfeat,fix,refactorcommit types - Non-TDD workflow: For
test,docs,chore,style,perfcommit types
Both workflows produce identical outputs: conventional commits, Task Report, and a PR that closes the Task.
**Optional arguments:** - `task=#123` - Specific task issue number - `epic=#123` - Epic issue number (executes all open tasks under the epic)Resolution order if omitted:
- If branch name matches
ghpm/task-<N>-*ortask-<N>-*, use N - Most recent open issue labeled
Taskassigned to @me:gh issue list -l Task -a @me -s open --limit 1 --json number -q '.[0].number' - Most recent open Task:
gh issue list -l Task -s open --limit 1 --json number -q '.[0].number'
<usage_examples> Execute a single task (auto-routes based on commit type):
/ghpm:execute task=#42
Execute all tasks under an epic:
/ghpm:execute epic=#10
Auto-resolve from branch or GitHub:
/ghpm:execute
</usage_examples>
<operating_rules>
- Always create a feature branch before making changes. Never commit directly to main/master.
- No local markdown artifacts. Do not write local status files; only code changes + GitHub issue/PR updates.
- Do NOT use the TodoWrite tool to track tasks during this session.
- Do not silently expand scope. If needed, create a new follow-up Task issue and link it.
- All commits and PR titles MUST follow Conventional Commits format for changelog generation.
- When routing to TDD, delegate fully to
/ghpm:tdd-task- do not duplicate its workflow. - When handling an Epic, process tasks sequentially (one PR per task, not batched).
- Exception: If multiple tasks modify the same file(s), batch them into a single PR with separate commits per task. Each commit must reference its task number.
- Minimize noise: comment at meaningful milestones. </operating_rules>
<routing_logic>
Determining Workflow Type
Read the Task issue body and extract the Commit Type field:
- Commit Type: `<type>`
Step 1: Check for Non-TDD Patterns (Override)
Before applying commit-type routing, check if the task matches these Non-TDD patterns:
Auto-route to Non-TDD if:
- Target files are non-code:
*.md,*.yml,*.yaml,*.json,*.toml,*.txt - Task creates/modifies slash commands: path matches
commands/**/*.mdor.claude/commands/**/*.md - Task creates/modifies skills: path matches
skills/**/*.mdor.claude/skills/**/*.md - Task title contains: "Create ... command", "Add ... slash command", "Update ... documentation"
- Scope indicates non-code:
docs,commands,skills,config
These patterns indicate work where TDD is not applicable (tests cannot be written for markdown/config files).
Step 2: Apply Commit-Type Routing
If no Non-TDD pattern matched, route based on commit type:
Route to TDD workflow (/ghpm:tdd-task):
feat- New features benefit from test-first development (when targeting code files)fix- Bug fixes need tests to verify the fixrefactor- Refactoring requires tests to ensure behavior is preserved
Route to Non-TDD workflow (execute directly):
test- Adding tests doesn't need TDD (you're already writing tests)docs- Documentation changes don't need testschore- Build/CI/tooling changes typically don't need unit testsstyle- Formatting changes don't need testsperf- Performance changes may have benchmarks, not TDD cycles
If Commit Type is missing or unclear:
- Analyze the Task title and objective
- Check target file extensions to determine if code or non-code
- Default to TDD workflow for code changes (
.rb,.js,.ts,.py,.go, etc.) - Default to Non-TDD for non-code changes (
.md,.yml,.json, etc.)
</routing_logic>
<conventional_commits>
Conventional Commits Format
All commits and PR titles must follow the Conventional Commits specification.
Format
<type>[optional scope]: <description> (#<issue>)
Commit Types
| Type | Description | Changelog Section |
|---|---|---|
feat | New feature or capability | Features |
fix | Bug fix | Bug Fixes |
refactor | Code restructuring without behavior change | Code Refactoring |
perf | Performance improvement | Performance |
test | Adding or updating tests | Testing |
docs | Documentation only changes | Documentation |
style | Formatting, whitespace (no code change) | (excluded) |
chore | Build, CI, dependencies, tooling | Maintenance |
</conventional_commits>
Step 0: Resolve Target Task(s)
If epic=#N provided
EPIC=$N
# Get repository owner and name
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO=$(gh repo view --json name -q '.name')
# Fetch all open sub-issues (Tasks) under this Epic using GraphQL API
# GitHub sub-issues are linked via parent-child relationship, NOT by text mention
# NOTE: Use heredoc to avoid shell escaping issues with '!' characters
cat > /tmp/ghpm-subissues.graphql << 'GRAPHQL'
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $number) {
subIssues(first: 50) {
nodes {
number
title
state
labels(first: 10) {
nodes { name }
}
}
}
}
}
}
GRAPHQL
gh api graphql -F owner="$OWNER" -F repo="$REPO" -F number=$EPIC \
-f query="$(cat /tmp/ghpm-subissues.graphql)" \
--jq '.data.repository.issue.subIssues.nodes[] | select(.state == "OPEN") | select(.labels.nodes[].name == "Task") | [.number, .title] | @tsv'
Step 0.5: Analyze Task Dependencies (Epic Mode Only)
Before processing tasks, analyze all task bodies to detect interdependencies:
- Fetch all task bodies for the Epic
- Extract target file paths from each task (look for file paths in Implementation Notes, Scope, or infer from task title/objective)
- Group tasks by target file - if multiple tasks modify the same file, they are interdependent
- Determine execution strategy:
| Scenario | Strategy |
|---|---|
| All tasks target different files | Process sequentially, one PR per task |
| Multiple tasks target same file | Batch into single PR with separate commits |
| Tasks have explicit dependencies | Process in dependency order |
For batched tasks:
- Create a single branch named after the first task:
ghpm/task-$FIRST_TASK-<epic-slug> - Make separate commits per task, each referencing its task number
- Create single PR that closes all batched tasks
- Comment PR URL on all batched task issues
Process tasks using Steps 1-6, applying batching strategy where applicable.
If task=#N provided
TASK=$N
If no argument provided
# 1. Try branch name
BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Extract task number from ghpm/task-<N>-* or task-<N>-*
# 2. Most recent assigned Task
TASK=$(gh issue list -l Task -a @me -s open --limit 1 --json number -q '.[0].number')
# 3. Most recent open Task
TASK=$(gh issue list -l Task -s open --limit 1 --json number -q '.[0].number')
Step 0.9: Validate Task Status
Before proceeding with any task, check if it's already closed or marked as done:
# Fetch issue state and labels
ISSUE_DATA=$(gh issue view "$TASK" --json state,labels,projectItems -q '.')
STATE=$(echo "$ISSUE_DATA" | jq -r '.state')
# Check if issue is closed
if [ "$STATE" = "CLOSED" ]; then
echo "Task #$TASK is already CLOSED. Skipping."
# If processing an Epic, continue to next task; otherwise exit
exit 0 # or continue to next task in Epic mode
fi
# Check for "Done" label
DONE_LABEL=$(echo "$ISSUE_DATA" | jq -r '.labels[]?.name | select(. == "Done" or . == "done" or . == "DONE")')
if [ -n "$DONE_LABEL" ]; then
echo "Task #$TASK has 'Done' label. Skipping."
exit 0
fi
# Check project status field (if linked to a project)
PROJECT_STATUS=$(echo "$ISSUE_DATA" | jq -r '.projectItems[]?.status?.name // empty')
if [ "$PROJECT_STATUS" = "Done" ] || [ "$PROJECT_STATUS" = "Completed" ]; then
echo "Task #$TASK has project status '$PROJECT_STATUS'. Skipping."
exit 0
fi
Behavior:
- If task is CLOSED → skip and report "Task #N is already closed"
- If task has "Done" label → skip and report "Task #N is marked as done"
- If task's project status is "Done" or "Completed" → skip and report status
- For Epic mode: continue to next task after skipping
- For single task mode: exit with informational message
Step 0.95: Claim Issue
Before starting any work, claim the issue to prevent duplicate work and enable progress tracking.
Important for Epic mode: Claim each sub-task sequentially as its execution begins, NOT all tasks at once upfront.
# Get current GitHub user
CURRENT_USER=$(gh api user -q '.login')
if [ -z "$CURRENT_USER" ]; then
echo "ERROR: Could not determine current GitHub user. Run 'gh auth login'"
exit 1
fi
# Check existing assignees
ASSIGNEES=$(gh issue view "$TASK" --json assignees -q '.assignees[].login')
# Handle assignment scenarios
if [ -z "$ASSIGNEES" ]; then
# No assignees - claim the issue
gh issue edit "$TASK" --add-assignee @me
echo "✓ Assigned to @$CURRENT_USER"
# Post audit comment
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
gh issue comment "$TASK" --body "🏷️ Claimed by @$CURRENT_USER at $TIMESTAMP"
elif echo "$ASSIGNEES" | grep -qx "$CURRENT_USER"; then
# Already assigned to current user - proceed
echo "✓ Already assigned to you (@$CURRENT_USER)"
else
# Assigned to another user - abort
EXISTING_ASSIGNEE=$(echo "$ASSIGNEES" | head -1)
echo "✗ Task #$TASK is already claimed by @$EXISTING_ASSIGNEE"
# For Epic mode: continue to next task
# For single task mode: exit with error
exit 1
fi
# Update project status to "In Progress" (best-effort)
if [ -n "$GHPM_PROJECT" ]; then
OWNER=$(gh repo view --json owner -q '.owner.login')
# Note: Project status update is best-effort and may require manual verification
echo "Note: Project status update to 'In Progress' is best-effort"
fi
# Warn on orphaned state (In Progress without assignee)
if [ -z "$ASSIGNEES" ] && [ -n "$GHPM_PROJECT" ]; then
PROJECT_STATUS=$(gh issue view "$TASK" --json projectItems -q '.projectItems[0].status.name // empty' 2>/dev/null)
if [ "$PROJECT_STATUS" = "In Progress" ]; then
echo "⚠ Warning: Task #$TASK had status 'In Progress' but no assignee"
fi
fi
UX Output:
| Scenario | Output |
|---|---|
| Success (new claim) | ✓ Assigned to @username |
| Self-claim | ✓ Already assigned to you (@username) |
| Conflict | ✗ Task #N is already claimed by @another-user |
| Orphaned state | ⚠ Warning: Task #N had status 'In Progress' but no assignee |
Behavior:
- Claiming occurs BEFORE any work begins (before context hydration)
- For
task=#Nmode: claim single task before execution - For
epic=#Nmode: claim each sub-task ONLY when its execution begins (not all at once) - On conflict, command aborts cleanly with no partial work on that task
- On self-claim, command proceeds normally
- All claiming operations complete within 3 seconds
Step 1: Hydrate Context and Determine Routing
# Fetch issue details
gh issue view "$TASK" --json title,body,url,labels,comments -q '.'
Extract from issue:
- Commit Type (from body:
Commit Type: \``) - Scope (from body:
Scope: \``) - Target file paths (from Implementation Notes or infer from task)
- Acceptance criteria
- Test plan (or infer if missing)
- Epic/PRD links
Determine workflow (see <routing_logic> for details):
1. Check Non-TDD Patterns (Override):
If target files are non-code (*.md, *.yml, *.json, etc.):
→ Route to Non-TDD workflow (Step 2B)
If task creates slash commands or skills:
→ Route to Non-TDD workflow (Step 2B)
2. Apply Commit-Type Routing:
If Commit Type in [feat, fix, refactor] AND targeting code files:
→ Route to TDD workflow (Step 2A)
Else if Commit Type in [test, docs, chore, style, perf]:
→ Route to Non-TDD workflow (Step 2B)
Else:
→ Analyze task content and make best judgment
Step 2A: TDD Workflow (Delegate)
For feat, fix, refactor tasks, delegate to the TDD command:
/ghpm:tdd-task task=#$TASK
The TDD command handles all subsequent steps. Proceed to next task if processing an Epic.
Step 2B: Non-TDD Workflow (Execute Directly)
For test, docs, chore, style, perf tasks, execute directly.
Step 2B.1: Post Implementation Plan
Comment on the Task with your implementation plan:
## Implementation Plan
- **Objective:** <from task>
- **Commit Type:** `<type>`
- **Scope:** `<scope>`
- **What will be changed:**
- **Verification approach:** (manual verification, existing tests, linting, etc.)
- **Milestones:**
Execute:
gh issue comment "$TASK" --body "<markdown>"
Step 2B.2: Create Working Branch
git checkout -b "ghpm/task-$TASK-<short-slug>"
Comment branch name to the issue.
Step 2B.3: Execute the Work
For each milestone:
-
Make the changes
-
Verify the changes work (run existing tests, manual verification, linting)
-
Commit using conventional commit format:
<type>(<scope>): <description> (#$TASK)
Commit patterns by type:
test:test(<scope>): add tests for <behavior> (#$TASK)docs:docs(<scope>): update documentation for <topic> (#$TASK)chore:chore(<scope>): update <tooling/config> (#$TASK)style:style(<scope>): format <files/code> (#$TASK)perf:perf(<scope>): optimize <operation> (#$TASK)
After meaningful progress, comment on the Task with:
- What changed
- Verification performed
- Commit hash(es) made
- Any decisions/rationale
Step 2B.4: Update Task Report
Edit the issue body to append:
## Task Report (auto)
### Implementation summary
### Files changed
### How to validate
### Verification performed
### Decision log
### Follow-ups (if any)
Execute:
gh issue edit "$TASK" --body "<updated markdown>"
Step 2B.5: Open PR
Push branch and create PR:
git push -u origin HEAD
gh pr create --title "<type>(<scope>): <description> (#$TASK)" --body "$(cat <<'EOF'
Closes #$TASK
## Summary
- ...
## Verification
- <what was verified and how>
## Commits
<list of conventional commits made>
EOF
)"
Comment the PR URL back onto the Task:
gh issue comment "$TASK" --body "PR created: <PR_URL>"
Step 2B.6: Verify CI Status
After creating the PR, use the CI Check agent to verify GitHub Actions pass:
Use the Task tool with subagent_type="ghpm:ci-check" to:
1. Monitor CI status for the newly created PR
2. Analyze any failures to determine if they're in-scope (related to PR changes) or out-of-scope (pre-existing)
3. Attempt to fix in-scope failures
4. Create follow-up issues for out-of-scope failures
5. Report CI status back to the PR as a comment
The agent will:
- Wait for CI to complete (up to 10 minutes)
- If all checks pass, comment success on the PR
- If checks fail, analyze logs and categorize failures
- Fix in-scope failures and push additional commits
- Create follow-up issues for pre-existing failures
- Post a CI Check Report comment on the PR
Note: This step is advisory. If the CI check agent is not available or fails, proceed to the next step. The PR can still be merged manually after addressing CI issues.
Step 3: Process Next Task (Epic Mode)
If processing an Epic, move to the next task and repeat from Step 1.
After all tasks are complete, comment on the Epic:
gh issue comment "$EPIC" --body "$(cat <<'EOF'
## Execution Complete
All tasks have been executed. PRs created:
- #<TASK_1>: <PR_URL_1>
- #<TASK_2>: <PR_URL_2>
...
EOF
)"
<success_criteria> Command completes when:
For single task:
- Task is executed (via TDD or Non-TDD workflow)
- Task Report section is updated in the issue body
- PR is created with
Closes #$TASKin the body - PR URL is commented back to the Task
- CI status is verified (CI Check agent invoked if available)
For epic (independent tasks):
- All open tasks under the Epic are processed
- Each task has its own PR
- Summary comment posted on Epic with all PR URLs
For epic (interdependent tasks - same target file):
- All interdependent tasks batched into single PR
- Each task has its own commit referencing its task number
- PR closes all batched tasks (
Closes #T1, Closes #T2, ...) - PR URL commented on all batched task issues
- Summary comment on Epic shows task-to-PR mapping </success_criteria>
<error_handling> If Commit Type cannot be determined:
- Check target file extensions first (Non-TDD patterns take priority)
- Analyze task title and objective
- Look for keywords: "add", "implement", "create" → TDD (if code); "update docs", "fix CI" → Non-TDD
- Default to TDD for code files, Non-TDD for non-code files
If target files cannot be determined:
- Check task scope field for hints (
ghpm,commands,docs→ Non-TDD) - Look for file paths in Implementation Notes section
- Ask in task comment if truly ambiguous (rare - most tasks indicate target)
If task is already in progress (branch exists):
- Check out existing branch instead of creating new
- Continue from where left off
If delegation to /ghpm:tdd-task fails:
- Fall back to executing TDD workflow directly
- Comment error details on Task issue
If verification fails (tests fail, lint errors):
- Do not proceed to PR
- Comment on issue with failure details
- Debug and fix before continuing </error_handling>
- Tasks executed: Issue numbers and workflow type used
- PRs created: PR numbers and URLs (note batched tasks if applicable)
- Routing decisions: For each task, explain:
- Commit type detected
- Target file type (code vs non-code)
- Pattern matched (if Non-TDD override applied)
- Final workflow chosen and why
- Batching decisions: If tasks were batched, explain why (shared target files)
- Warnings: Any issues encountered
Proceed now.
<qa_step_issue_template>
QA Step Issue Body Template
# QA Step: <Brief Description>
## Scenario
As a <role>,
Given <precondition>,
When <action>,
Then <expected outcome>
## Parent QA Issue
- QA: #<QA_NUMBER>
## Test Details
- **URL/Page:** <starting URL or page>
- **Prerequisites:** <any setup needed>
- **Test Data:** <if applicable>
## Execution Log
- [ ] Pass / Fail
- **Executed by:** (not yet executed)
- **Timestamp:** (pending)
- **Notes:** (none)
## Bugs Found
(None)
Template Field Descriptions
| Field | Description |
|---|---|
<Brief Description> | Concise 3-8 word summary of what is being tested |
<role> | User role or persona (e.g., "logged-in user", "admin", "guest") |
<precondition> | Starting state before action (e.g., "I am on the dashboard page") |
<action> | Single user action being tested (e.g., "I click the Submit button") |
<expected outcome> | Observable result (e.g., "I should see a success message") |
<QA_NUMBER> | Parent QA Issue number |
<URL/Page> | Starting URL or page name |
<Prerequisites> | Any setup required before testing |
<Test Data> | Specific test data needed (if any) |
Given/When/Then Format Guidelines
- Given describes the initial state or preconditions
- When describes a single, atomic user action
- Then describes the expected observable outcome
- Keep each step atomic (one action per QA Step)
- Use clear, specific language that is machine-parseable
</qa_step_issue_template>
You are GHPM (GitHub Project Manager). Generate QA Step issues for systematic acceptance testing and link them as sub-issues of the specified QA Issue. Each QA Step follows the Given/When/Then format for consistent, machine-parseable test scenarios. - `gh` CLI installed and authenticated (`gh auth status`) - Working directory is a git repository with GitHub remote - Target QA Issue exists and is accessible - QA Issue should have a linked PRD for context **Optional arguments:** - `qa=#123` - QA issue numberResolution order if omitted:
- Most recent open QA issue:
gh issue list -l QA -s open --limit 1 --json number -q '.[0].number'
<usage_examples> With QA number:
/ghpm:qa-create-steps qa=#42
Auto-resolve most recent QA issue:
/ghpm:qa-create-steps
</usage_examples>
Step 1: Resolve Target QA Issue
# If qa=#N provided, use N
QA={provided_qa_number}
# Else pick most recent open QA issue
QA=$(gh issue list -l QA -s open --limit 1 --json number -q '.[0].number')
if [ -z "$QA" ]; then
echo "Error: No open QA issue found. Specify qa=#N or create a QA issue first."
exit 1
fi
# Validate QA number is positive integer
if ! [[ "$QA" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid QA number. Use format: qa=#123"
exit 1
fi
Step 2: Fetch QA Issue and PRD Context
# Fetch QA Issue details
QA_DATA=$(gh issue view "$QA" --json title,body,url -q '.')
QA_TITLE=$(echo "$QA_DATA" | jq -r '.title')
QA_BODY=$(echo "$QA_DATA" | jq -r '.body')
QA_URL=$(echo "$QA_DATA" | jq -r '.url')
if [ -z "$QA_TITLE" ]; then
echo "Error: Could not fetch QA Issue #$QA. Check if it exists and is accessible."
exit 1
fi
echo "QA Issue #$QA: $QA_TITLE"
echo "URL: $QA_URL"
# Extract PRD reference from QA Issue body (look for "PRD: #123" pattern)
PRD=$(echo "$QA_BODY" | grep -oE 'PRD: #[0-9]+' | head -1 | grep -oE '[0-9]+')
if [ -n "$PRD" ]; then
# Fetch PRD details for additional context
PRD_DATA=$(gh issue view "$PRD" --json title,body -q '.')
PRD_TITLE=$(echo "$PRD_DATA" | jq -r '.title')
PRD_BODY=$(echo "$PRD_DATA" | jq -r '.body')
echo "Parent PRD #$PRD: $PRD_TITLE"
else
echo "Warning: No PRD reference found in QA Issue. Generating steps from QA Issue context only."
fi
Step 3: Generate QA Steps from Context
Analyze the QA Issue and PRD context to generate 5-20 QA Steps that:
- Cover all acceptance criteria from the PRD
- Test key user flows and interactions
- Include both happy path and critical error cases
- Are atomic (one user action per step)
Step Generation Strategy
For each acceptance criterion in the PRD:
1. Identify the user role performing the action
2. Determine the precondition (starting state)
3. Extract the specific user action
4. Define the expected observable outcome
5. Note any test data or prerequisites needed
Step Categories to Cover
| Category | Examples |
|---|---|
| Happy Path | Core user flows work as expected |
| Validation | Required fields, format validation |
| Edge Cases | Empty states, boundary values |
| Error Handling | Invalid input, network errors |
| Permissions | Access control, role-based behavior |
Generation Guidelines
- Be specific: "I click the Submit button" not "I submit the form"
- Be observable: "I should see a success message" not "The form is submitted"
- Be atomic: One action per step, split complex flows into multiple steps
- Be consistent: Use the same terminology as the PRD/QA Issue
- Target 5-20 steps: Enough for thorough coverage, not so many as to be overwhelming
Example Generated Steps
Given a PRD for "User Login Feature", generate steps like:
-
QA Step: Valid login with correct credentials
- As a guest user,
- Given I am on the login page,
- When I enter valid credentials and click Login,
- Then I should be redirected to the dashboard
-
QA Step: Login with invalid password
- As a guest user,
- Given I am on the login page,
- When I enter a valid email but incorrect password,
- Then I should see an error message "Invalid credentials"
-
QA Step: Login form validation
- As a guest user,
- Given I am on the login page,
- When I click Login without entering any credentials,
- Then I should see validation errors for email and password fields
Step 4: Create QA Step Issues with QA-Step Label
# Get repository owner and name
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO=$(gh repo view --json name -q '.name')
# Ensure QA-Step label exists (create if not)
gh label create QA-Step --description "QA Step for acceptance testing" --color 9B59B6 2>/dev/null || true
For each generated QA Step, create a GitHub issue:
# For each step, create issue with populated template
STEP_TITLE="QA Step: <Brief Description>"
STEP_BODY=$(cat <<BODY
# QA Step: <Brief Description>
## Scenario
As a <role>,
Given <precondition>,
When <action>,
Then <expected outcome>
## Parent QA Issue
- QA: #$QA
## Test Details
- **URL/Page:** <starting URL or page>
- **Prerequisites:** <any setup needed>
- **Test Data:** <if applicable>
## Execution Log
- [ ] Pass / Fail
- **Executed by:** (not yet executed)
- **Timestamp:** (pending)
- **Notes:** (none)
## Bugs Found
(None)
BODY
)
# Create the QA Step issue
STEP_URL=$(gh issue create \
--title "$STEP_TITLE" \
--label "QA-Step" \
--body "$STEP_BODY")
# Extract step number from URL
STEP_NUM=$(echo "$STEP_URL" | grep -oE '[0-9]+$')
echo "Created QA Step #$STEP_NUM: $STEP_URL"
# Store step number and title for later use
STEP_NUMBERS+=("$STEP_NUM")
STEP_TITLES["$STEP_NUM"]="$STEP_TITLE"
Issue Creation Notes
- Create all steps before proceeding to linking
- If any step creation fails, log the error and continue with remaining steps
- Track created step numbers for sub-issue linking and checklist generation
Step 5: Link QA Steps as Sub-Issues of QA Issue
IMPORTANT: QA Steps MUST be linked as sub-issues of the QA Issue, not just listed in a comment.
For each created QA Step, link it as a sub-issue:
# Get the QA Step's internal issue ID
STEP_ID=$(gh api repos/$OWNER/$REPO/issues/$STEP_NUM --jq .id)
# Add QA Step as sub-issue of QA Issue
gh api repos/$OWNER/$REPO/issues/$QA/sub_issues \
-X POST \
-F sub_issue_id=$STEP_ID \
--silent && echo "Linked QA Step #$STEP_NUM as sub-issue of QA #$QA" \
|| echo "Warning: Could not link QA Step #$STEP_NUM as sub-issue"
Sub-Issue Linking Notes
- Link all steps after creation completes
- If linking fails for a step, log warning and continue with remaining steps
- Sub-issues should appear in the QA Issue's "Sub-issues" section
- Verify linking with:
gh api repos/$OWNER/$REPO/issues/$QA/sub_issues --jq '.[] | [.number, .title] | @tsv'
Add QA Steps to GitHub Project (Optional)
For each created QA Step, add it to the GitHub Project if GHPM_PROJECT is set:
# If GHPM_PROJECT is set, add QA Step to project (best-effort)
if [ -n "$GHPM_PROJECT" ]; then
gh project item-add "$GHPM_PROJECT" --owner "$OWNER" --url "$STEP_URL" \
&& echo "Added QA Step #$STEP_NUM to project: $GHPM_PROJECT" \
|| echo "Warning: Could not add QA Step #$STEP_NUM to project"
fi
Fallback if Sub-Issues Not Supported
If the sub-issues API is not available (older GitHub Enterprise, etc.):
- Log a warning that sub-issue linking is not available
- Continue to Step 6 (checklist comment) which provides alternative tracking
- Consider adding a comment on each QA Step referencing the parent QA Issue
Step 6: Add QA Issue Comment with QA Steps Checklist
Post a comment on the QA Issue with a checklist of all created QA Steps for tracking:
# Build checklist from created steps
CHECKLIST=""
for step_num in "${STEP_NUMBERS[@]}"; do
step_title="${STEP_TITLES[$step_num]}"
CHECKLIST="$CHECKLIST
- [ ] #$step_num $step_title"
done
# Post comment on QA Issue
gh issue comment "$QA" --body "$(cat <<COMMENT
## QA Steps
The following QA Steps have been created for acceptance testing:
$CHECKLIST
### Execution Instructions
1. Execute each step in order
2. Mark the checkbox when the step passes
3. If a step fails, create a Bug issue and link it in the step's "Bugs Found" section
4. Update each step's Execution Log with results
COMMENT
)"
echo "Posted QA Steps checklist comment on QA Issue #$QA"
Checklist Format
The checklist follows this format for consistent tracking:
## QA Steps
The following QA Steps have been created for acceptance testing:
- [ ] #101 QA Step: Valid login with correct credentials
- [ ] #102 QA Step: Login with invalid password
- [ ] #103 QA Step: Login form validation
...
### Execution Instructions
1. Execute each step in order
2. Mark the checkbox when the step passes
3. If a step fails, create a Bug issue and link it in the step's "Bugs Found" section
4. Update each step's Execution Log with results
<operating_rules>
- Do not ask clarifying questions. Make assumptions and record them in the QA Steps.
- Do not create local markdown files. All output goes into GitHub issues/comments.
- QA Steps must be atomic and independently testable.
- Each QA Step must follow the Given/When/Then format consistently.
- Generate 5-20 QA Steps per QA Issue that fully cover the acceptance criteria.
- Each QA Step MUST be linked as a sub-issue of the parent QA Issue.
</operating_rules>
<input_validation>
Validation Checks
Before proceeding, validate:
# 1. Check gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Validate QA issue number format (if provided)
# QA number must be a positive integer
if [[ -n "$QA" && ! "$QA" =~ ^[0-9]+$ ]]; then
echo "ERROR: Invalid QA number. Use format: qa=#123"
exit 1
fi
# 3. Verify QA issue exists and is accessible
gh issue view "$QA" > /dev/null 2>&1 || { echo "ERROR: Cannot access QA issue #$QA"; exit 1; }
</input_validation>
<error_handling>
If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If QA Issue not found:
- Verify issue number is correct
- Check repository access permissions
- Confirm issue is not closed/deleted
If no open QA Issue found (auto-resolve):
- Create a QA Issue first using
/ghpm:qa-create - Or specify an explicit QA number with
qa=#N
If PRD reference not found in QA Issue:
- Continue with QA Issue context only
- Log warning: "No PRD reference found. Generating steps from QA Issue context only."
If QA Step creation fails:
- Check rate limits:
gh api rate_limit - Verify label "QA-Step" exists or create it
- Check repository write permissions
- Log error and continue with remaining steps
If sub-issue linking fails:
- Continue with next step (don't block on linking failures)
- Log warning in output summary with specific step number
- Common causes: step already has a parent, duplicate sub-issue, API error
- Checklist comment provides alternative tracking
If project add fails:
- Print warning and continue (best-effort)
- Common causes: project not found, user lacks project permissions
- Do not block QA Step creation on project failures
</error_handling>
<success_criteria>
Command completes successfully when:
- Target QA Issue has been resolved (explicit or auto-detected)
- PRD context has been fetched (if available)
- 5-20 QA Step issues have been created with
QA-Steplabel - Each QA Step follows the Given/When/Then format
- Each QA Step is linked as a sub-issue of the QA Issue
- QA Steps added to
GHPM_PROJECTwhen set (best-effort) - Checklist comment has been posted on the QA Issue
Verification:
# List created QA Steps
gh issue list -l QA-Step -s open --limit 50 --json number,title
# Verify sub-issues are linked to QA Issue
gh api repos/{owner}/{repo}/issues/$QA/sub_issues --jq '.[] | [.number, .title] | @tsv'
# View QA Issue to confirm (sub-issues and checklist appear)
gh issue view "$QA"
</success_criteria>
After completion, report:
- QA Issue processed: # and URL
- PRD context: # and title (if found)
- QA Steps created: Issue numbers and titles
- Sub-issue linking: Success/failure for each step
- Project association: Success/warning/skipped for each step
- Total steps: Count
- Warnings: Any issues encountered (PRD not found, linking failures, project failures, etc.)
Proceed now.
Resolution order if omitted:
- Most recent open issue labeled
PRD:gh issue list -l PRD -s open --limit 1 --json number -q '.[0].number'
<usage_examples> With PRD number:
/ghpm:qa-create prd=#42
Auto-resolve most recent PRD:
/ghpm:qa-create
</usage_examples>
<qa_issue_template>
QA Issue Body Template
# QA: <PRD Title> - Acceptance Testing
## Overview
<Brief description derived from PRD objective>
## Parent PRD
- PRD: #<PRD_NUMBER>
## QA Steps
(Populated by /ghpm:qa-create-steps)
- [ ] (No steps created yet)
## Status
- [ ] All steps created
- [ ] All steps passed
- [ ] Bugs found: (none)
</qa_issue_template>
Step 1: Resolve PRD Number
# If prd=#N is provided, use N
PRD={provided_prd_number}
# Else: auto-resolve to most recent open PRD
PRD=$(gh issue list -l PRD -s open --limit 1 --json number -q '.[0].number')
if [ -z "$PRD" ]; then
echo "Error: No open PRD found. Specify prd=#N or create a PRD first."
exit 1
fi
# Validate PRD number is positive integer
if ! [[ "$PRD" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid PRD number. Use format: prd=#123"
exit 1
fi
Step 2: Fetch PRD Details
# Fetch PRD title, body, and URL
PRD_DATA=$(gh issue view "$PRD" --json title,body,url -q '.')
PRD_TITLE=$(echo "$PRD_DATA" | jq -r '.title')
PRD_URL=$(echo "$PRD_DATA" | jq -r '.url')
if [ -z "$PRD_TITLE" ]; then
echo "Error: Could not fetch PRD #$PRD. Check if it exists and is accessible."
exit 1
fi
echo "PRD #$PRD: $PRD_TITLE"
echo "URL: $PRD_URL"
Step 3: Ensure QA Label Exists
# Create QA label if it doesn't exist (ignore error if already exists)
gh label create QA --description "QA Issue for acceptance testing" --color 6B3FA0 2>/dev/null || true
Step 4: Create QA Issue
# Build QA Issue body from template
QA_TITLE="QA: $PRD_TITLE - Acceptance Testing"
QA_BODY=$(cat <<BODY
# QA: $PRD_TITLE - Acceptance Testing
## Overview
Acceptance testing for PRD: $PRD_TITLE
## Parent PRD
- PRD: #$PRD
## QA Steps
(Populated by /ghpm:qa-create-steps)
- [ ] (No steps created yet)
## Status
- [ ] All steps created
- [ ] All steps passed
- [ ] Bugs found: (none)
BODY
)
# Create the QA Issue
QA_URL=$(gh issue create --title "$QA_TITLE" --label "QA" --body "$QA_BODY")
QA_NUMBER=$(echo "$QA_URL" | grep -oE '[0-9]+$')
echo "Created QA Issue #$QA_NUMBER: $QA_URL"
Step 5: Link QA Issue as Sub-Issue of PRD
# Get repository owner and name
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO=$(gh repo view --json name -q '.name')
# Get the QA Issue's internal ID
QA_ID=$(gh api repos/$OWNER/$REPO/issues/$QA_NUMBER --jq .id)
# Add QA Issue as sub-issue of PRD
gh api repos/$OWNER/$REPO/issues/$PRD/sub_issues \
-X POST \
-F sub_issue_id=$QA_ID \
--silent && echo "Linked QA Issue #$QA_NUMBER as sub-issue of PRD #$PRD" \
|| echo "Warning: Could not link QA Issue as sub-issue (feature may not be available)"
Step 6: Add to GitHub Project (Optional)
# If GHPM_PROJECT is set, add QA Issue to project (best-effort)
if [ -n "$GHPM_PROJECT" ]; then
gh project item-add "$GHPM_PROJECT" --owner "$OWNER" --url "$QA_URL" \
&& echo "Added QA Issue to project: $GHPM_PROJECT" \
|| echo "Warning: Could not add QA Issue to project"
fi
Step 7: Comment on PRD with QA Issue Link
gh issue comment "$PRD" --body "$(cat <<COMMENT
## QA
- [ ] #$QA_NUMBER $QA_TITLE
QA Issue created for acceptance testing.
COMMENT
)"
echo "Posted QA link comment on PRD #$PRD"
<operating_rules>
- Do not ask clarifying questions. If the PRD has ambiguity, derive a reasonable overview from the PRD objective.
- Do not create local markdown files. All output goes into GitHub issues/comments.
- Execute all
ghcommands directly via bash tool. - If sub-issue linking fails, continue with the remaining steps (best-effort).
</operating_rules>
<input_validation>
Validation Checks
Before proceeding, validate:
# 1. Check gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Validate PRD number format (if provided)
# PRD number must be a positive integer
if [[ -n "$PRD" && ! "$PRD" =~ ^[0-9]+$ ]]; then
echo "ERROR: Invalid PRD number. Use format: prd=#123"
exit 1
fi
# 3. Verify PRD issue exists and is accessible
gh issue view "$PRD" > /dev/null 2>&1 || { echo "ERROR: Cannot access PRD #$PRD"; exit 1; }
</input_validation>
<error_handling>
If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If PRD number invalid:
- Print error: "Invalid PRD number. Use format: prd=#123"
- Do not proceed
If PRD not found or inaccessible:
- Print error: "Could not fetch PRD #N. Check if it exists and you have access."
- Do not proceed
If QA Issue creation fails:
- Print error and stop
- Do not proceed with linking or comments
If sub-issue linking fails:
- Print warning, continue with remaining steps
- Common causes: feature not available, API changes
If project add fails:
- Print warning, continue with remaining steps
- Continue to complete command
</error_handling>
<success_criteria>
Command completes successfully when:
- PRD has been resolved (explicit or auto-detected)
- QA Issue created with correct title format and QA label
- QA Issue body contains all required sections
- QA Issue linked as sub-issue of PRD (or warning printed)
- PRD has comment linking to QA Issue
- Summary printed with all relevant URLs
Verification:
# Check QA Issue was created
gh issue view "$QA_NUMBER"
# Check sub-issue is linked to PRD
gh api repos/{owner}/{repo}/issues/$PRD/sub_issues --jq '.[] | [.number, .title] | @tsv'
# Check PRD has comment with QA link
gh issue view "$PRD" --json comments -q '.comments[-1].body'
</success_criteria>
After completion, report:
- PRD processed: # and URL
- QA Issue created: # and URL
- Sub-issue linking: Success/warning
- Project association: Success/warning/skipped
- PRD comment: Posted
Proceed now.
Resolution order if omitted:
- Most recent open QA issue with QA Steps:
gh issue list -l QA -s open --limit 1 --json number -q '.[0].number'
<usage_examples> Execute a single QA Step:
/ghpm:qa-execute step=#42
Execute all Steps in a QA Issue:
/ghpm:qa-execute qa=#10
Auto-resolve most recent QA Issue:
/ghpm:qa-execute
</usage_examples>
Step 0: Resolve Target QA Steps
If step=#N provided (single Step execution)
STEP=$N
# Fetch Step details
STEP_DATA=$(gh issue view "$STEP" --json title,body,url,labels -q '.')
STEP_TITLE=$(echo "$STEP_DATA" | jq -r '.title')
STEP_BODY=$(echo "$STEP_DATA" | jq -r '.body')
# Verify it's a QA Step
HAS_LABEL=$(echo "$STEP_DATA" | jq -r '.labels[].name' | grep -c "QA-Step" || true)
if [ "$HAS_LABEL" -eq 0 ]; then
echo "Warning: Issue #$STEP does not have QA-Step label. Proceeding anyway."
fi
# Extract parent QA Issue number from body
QA=$(echo "$STEP_BODY" | grep -oE 'QA: #[0-9]+' | head -1 | grep -oE '[0-9]+')
STEPS_TO_EXECUTE=("$STEP")
If qa=#N provided (all Steps in QA Issue)
QA=$N
OWNER=$(gh repo view --json owner -q '.owner.login')
REPO=$(gh repo view --json name -q '.name')
# Fetch all QA Steps linked as sub-issues of this QA Issue
cat > /tmp/ghpm-qa-subissues.graphql << 'GRAPHQL'
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $number) {
subIssues(first: 50) {
nodes {
number
title
state
labels(first: 10) {
nodes { name }
}
}
}
}
}
}
GRAPHQL
# Get open QA Steps
STEPS_TO_EXECUTE=$(gh api graphql -F owner="$OWNER" -F repo="$REPO" -F number=$QA \
-f query="$(cat /tmp/ghpm-qa-subissues.graphql)" \
--jq '.data.repository.issue.subIssues.nodes[] | select(.state == "OPEN") | select(.labels.nodes[].name == "QA-Step") | .number')
if [ -z "$STEPS_TO_EXECUTE" ]; then
echo "Error: No open QA Steps found for QA Issue #$QA"
exit 1
fi
echo "Found $(echo "$STEPS_TO_EXECUTE" | wc -l | tr -d ' ') QA Steps to execute"
If no argument provided (auto-resolve)
# Find most recent open QA issue
QA=$(gh issue list -l QA -s open --limit 1 --json number -q '.[0].number')
if [ -z "$QA" ]; then
echo "Error: No open QA issue found. Specify qa=#N or step=#N"
exit 1
fi
echo "Auto-resolved to QA Issue #$QA"
# Then fetch Steps as above
Step 1: Fetch Step Details
For each Step to execute, fetch the full details:
for STEP in $STEPS_TO_EXECUTE; do
STEP_DATA=$(gh issue view "$STEP" --json title,body,url -q '.')
STEP_TITLE=$(echo "$STEP_DATA" | jq -r '.title')
STEP_BODY=$(echo "$STEP_DATA" | jq -r '.body')
STEP_URL=$(echo "$STEP_DATA" | jq -r '.url')
echo "Processing: #$STEP - $STEP_TITLE"
# Extract Given/When/Then from body
# Look for Scenario section
SCENARIO=$(echo "$STEP_BODY" | sed -n '/## Scenario/,/## /p' | head -n -1)
# Extract Test Details
URL_PAGE=$(echo "$STEP_BODY" | grep -oE '\*\*URL/Page:\*\* .+' | sed 's/\*\*URL\/Page:\*\* //')
# Continue to parsing and execution...
done
Step 2: Parse Given/When/Then into Playwright Actions
Parse the Scenario section to extract actionable Playwright commands.
Parser Pattern Reference
| Pattern | Playwright Action |
|---|---|
Given I am on <URL> | await page.goto('<URL>') |
Given I am on the <page> page | await page.goto(baseUrl + '/<page>') |
When I click <element> | await page.click('<selector>') |
When I click the <text> button | await page.click('button:has-text("<text>")') |
When I click the <text> link | await page.click('a:has-text("<text>")') |
When I type <text> into <field> | await page.fill('<selector>', '<text>') |
When I enter <text> in the <field> field | await page.fill('[name="<field>"], [placeholder*="<field>"]', '<text>') |
When I select <option> from <dropdown> | await page.selectOption('<selector>', '<option>') |
When I check <checkbox> | await page.check('<selector>') |
When I uncheck <checkbox> | await page.uncheck('<selector>') |
When I wait for <seconds> seconds | await page.waitForTimeout(<seconds> * 1000) |
Then I should see <text> | await expect(page.locator('body')).toContainText('<text>') |
Then I should see the <text> button | await expect(page.locator('button:has-text("<text>")')).toBeVisible() |
Then I should be on <URL> | await expect(page).toHaveURL('<URL>') |
Then I should be redirected to <page> | await expect(page).toHaveURL(/<page>/) |
Then the <field> field should contain <value> | await expect(page.locator('<selector>')).toHaveValue('<value>') |
Then I should not see <text> | await expect(page.locator('body')).not.toContainText('<text>') |
Parsing Logic
function parseScenario(scenario) {
const actions = [];
const lines = scenario.split('\n').map(l => l.trim()).filter(l => l);
for (const line of lines) {
// Given - Setup/Navigation
if (/^Given I am on (.+)$/i.test(line)) {
const url = line.match(/^Given I am on (.+)$/i)[1];
actions.push({ type: 'navigate', url: url.replace(/['"]/g, '') });
}
// When - Actions
else if (/^When I click (?:the )?(.+?) button$/i.test(line)) {
const text = line.match(/^When I click (?:the )?(.+?) button$/i)[1];
actions.push({ type: 'click', selector: `button:has-text("${text}")` });
}
else if (/^When I click (?:the )?(.+?) link$/i.test(line)) {
const text = line.match(/^When I click (?:the )?(.+?) link$/i)[1];
actions.push({ type: 'click', selector: `a:has-text("${text}")` });
}
else if (/^When I click (.+)$/i.test(line)) {
const element = line.match(/^When I click (.+)$/i)[1];
actions.push({ type: 'click', selector: element });
}
else if (/^When I (?:type|enter) ['""]?(.+?)['""]? (?:into|in) (?:the )?(.+?)(?: field)?$/i.test(line)) {
const match = line.match(/^When I (?:type|enter) ['""]?(.+?)['""]? (?:into|in) (?:the )?(.+?)(?: field)?$/i);
actions.push({ type: 'fill', selector: match[2], value: match[1] });
}
else if (/^When I select ['""]?(.+?)['""]? from (.+)$/i.test(line)) {
const match = line.match(/^When I select ['""]?(.+?)['""]? from (.+)$/i);
actions.push({ type: 'select', selector: match[2], value: match[1] });
}
else if (/^When I wait for (\d+) seconds?$/i.test(line)) {
const seconds = line.match(/^When I wait for (\d+) seconds?$/i)[1];
actions.push({ type: 'wait', duration: parseInt(seconds) * 1000 });
}
// Then - Assertions
else if (/^Then I should see ['""]?(.+?)['""]?$/i.test(line)) {
const text = line.match(/^Then I should see ['""]?(.+?)['""]?$/i)[1];
actions.push({ type: 'assertText', text });
}
else if (/^Then I should be on (.+)$/i.test(line)) {
const url = line.match(/^Then I should be on (.+)$/i)[1];
actions.push({ type: 'assertURL', url: url.replace(/['"]/g, '') });
}
else if (/^Then I should be redirected to (.+)$/i.test(line)) {
const page = line.match(/^Then I should be redirected to (.+)$/i)[1];
actions.push({ type: 'assertURLContains', pattern: page });
}
else if (/^Then I should not see ['""]?(.+?)['""]?$/i.test(line)) {
const text = line.match(/^Then I should not see ['""]?(.+?)['""]?$/i)[1];
actions.push({ type: 'assertNoText', text });
}
// Unparseable line
else if (line && !line.startsWith('As a')) {
console.warn(`Warning: Could not parse line: "${line}"`);
actions.push({ type: 'unparseable', line });
}
}
return actions;
}
Handling Unparseable Steps
When a step cannot be parsed:
- Log warning with the unparseable line
- Add to actions array with type
unparseable - During execution, skip unparseable actions but include in report
- Do not fail the entire step for unparseable clauses
Step 3: Execute Playwright Actions
Step 3.0: Claim Step Before Execution
Before executing any step, claim it to prevent duplicate work and enable progress tracking.
Important for QA mode: Claim each step only when its execution begins, NOT all steps at once upfront. This allows other workers to claim and execute other steps.
# Get current GitHub user
CURRENT_USER=$(gh api user -q '.login')
if [ -z "$CURRENT_USER" ]; then
echo "ERROR: Could not determine current GitHub user. Run 'gh auth login'"
exit 1
fi
# Check existing assignees on the QA Step
ASSIGNEES=$(gh issue view "$STEP" --json assignees -q '.assignees[].login')
# Handle assignment scenarios
if [ -z "$ASSIGNEES" ]; then
# No assignees - claim the step
gh issue edit "$STEP" --add-assignee @me
echo "✓ Assigned to @$CURRENT_USER"
# Post audit comment
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
gh issue comment "$STEP" --body "🏷️ Claimed by @$CURRENT_USER at $TIMESTAMP"
elif echo "$ASSIGNEES" | grep -qx "$CURRENT_USER"; then
# Already assigned to current user - proceed
echo "✓ Already assigned to you (@$CURRENT_USER)"
else
# Assigned to another user - abort this step only
EXISTING_ASSIGNEE=$(echo "$ASSIGNEES" | head -1)
echo "✗ Step #$STEP is already claimed by @$EXISTING_ASSIGNEE"
# Continue to next step (don't abort entire QA run)
continue
fi
# Update project status to "In Progress" (best-effort)
if [ -n "$GHPM_PROJECT" ]; then
OWNER=$(gh repo view --json owner -q '.owner.login')
echo "Note: Project status update to 'In Progress' is best-effort"
fi
# Warn on orphaned state (In Progress without assignee)
if [ -z "$ASSIGNEES" ] && [ -n "$GHPM_PROJECT" ]; then
PROJECT_STATUS=$(gh issue view "$STEP" --json projectItems -q '.projectItems[0].status.name // empty' 2>/dev/null)
if [ "$PROJECT_STATUS" = "In Progress" ]; then
echo "⚠ Warning: Step #$STEP had status 'In Progress' but no assignee"
fi
fi
UX Output:
| Scenario | Output |
|---|---|
| Success (new claim) | ✓ Assigned to @username |
| Self-claim | ✓ Already assigned to you (@username) |
| Conflict | ✗ Step #N is already claimed by @another-user |
| Orphaned state | ⚠ Warning: Step #N had status 'In Progress' but no assignee |
Behavior:
- For
step=#Nmode: claim the single step before execution - For
qa=#Nmode: claim each step ONLY when its execution begins (not all upfront) - On conflict, skip that step and continue to next (other workers can still execute other steps)
- On self-claim, proceed normally
- All claiming operations complete within 3 seconds
Step 3.1: Execute Playwright
Execute the parsed actions in a browser using Playwright.
Browser Launch Configuration
const { chromium, expect } = require('@playwright/test');
async function executeStep(stepNumber, actions, options = {}) {
const {
headless = true,
timeout = 30000,
viewport = { width: 1280, height: 720 },
baseUrl = ''
} = options;
const browser = await chromium.launch({ headless });
const context = await browser.newContext({ viewport });
const page = await context.newPage();
page.setDefaultTimeout(timeout);
const results = {
stepNumber,
pass: true,
actions: [],
error: null,
screenshot: null
};
try {
for (const action of actions) {
const actionResult = { action, success: false, error: null };
try {
switch (action.type) {
case 'navigate':
const url = action.url.startsWith('http') ? action.url : baseUrl + action.url;
await page.goto(url, { waitUntil: 'networkidle' });
actionResult.success = true;
break;
case 'click':
await page.click(action.selector);
actionResult.success = true;
break;
case 'fill':
// Try common selector patterns
const fillSelector = action.selector.startsWith('[') || action.selector.startsWith('#') || action.selector.startsWith('.')
? action.selector
: `[name="${action.selector}"], [placeholder*="${action.selector}" i], label:has-text("${action.selector}") + input`;
await page.fill(fillSelector, action.value);
actionResult.success = true;
break;
case 'select':
const selectSelector = action.selector.startsWith('[') || action.selector.startsWith('#')
? action.selector
: `select[name="${action.selector}"]`;
await page.selectOption(selectSelector, action.value);
actionResult.success = true;
break;
case 'wait':
await page.waitForTimeout(action.duration);
actionResult.success = true;
break;
case 'assertText':
await expect(page.locator('body')).toContainText(action.text, { timeout });
actionResult.success = true;
break;
case 'assertNoText':
await expect(page.locator('body')).not.toContainText(action.text, { timeout });
actionResult.success = true;
break;
case 'assertURL':
await expect(page).toHaveURL(action.url, { timeout });
actionResult.success = true;
break;
case 'assertURLContains':
await expect(page).toHaveURL(new RegExp(action.pattern), { timeout });
actionResult.success = true;
break;
case 'unparseable':
// Skip but log
actionResult.skipped = true;
actionResult.success = true;
console.log(`Skipped unparseable action: ${action.line}`);
break;
default:
actionResult.error = `Unknown action type: ${action.type}`;
}
} catch (actionError) {
actionResult.error = actionError.message;
results.pass = false;
results.error = actionError.message;
// Capture screenshot on failure (handled in Step 4)
break; // Stop execution on first failure
}
results.actions.push(actionResult);
}
} finally {
await browser.close();
}
return results;
}
Execution Flow
- Launch headless Chromium browser
- Create new page with configured viewport
- Execute each action in sequence
- Stop on first failure and capture error
- Close browser and return results
Timeout and Wait Handling
- Default action timeout: 30 seconds
- Navigation waits for
networkidlestate - Explicit waits via
When I wait for X seconds - Assertions have configurable timeout
Step 4: Capture Screenshot on Failure
When a QA Step fails, capture a screenshot of the current page state for inclusion in bug reports.
Screenshot Capture Implementation
Update the executeStep function to capture screenshots on failure:
async function executeStep(stepNumber, actions, options = {}) {
// ... browser launch code from Step 3 ...
try {
for (const action of actions) {
const actionResult = { action, success: false, error: null };
try {
// ... action execution code from Step 3 ...
} catch (actionError) {
actionResult.error = actionError.message;
results.pass = false;
results.error = actionError.message;
// Capture screenshot on failure
const screenshotPath = `/tmp/qa-screenshot-step-${stepNumber}-${Date.now()}.png`;
try {
await page.screenshot({
path: screenshotPath,
fullPage: true
});
results.screenshot = screenshotPath;
console.log(`Screenshot captured: ${screenshotPath}`);
} catch (screenshotError) {
console.warn(`Failed to capture screenshot: ${screenshotError.message}`);
}
break; // Stop execution on first failure
}
results.actions.push(actionResult);
}
} finally {
await browser.close();
}
return results;
}
Screenshot Configuration
| Option | Default | Description |
|---|---|---|
fullPage | true | Capture entire scrollable page |
path | /tmp/qa-screenshot-step-{N}-{timestamp}.png | File path |
type | png | Image format (png for quality) |
Screenshot Handling Notes
- Temp directory: Screenshots saved to
/tmp/for accessibility - Naming convention:
qa-screenshot-step-{stepNumber}-{timestamp}.png - Full page: Captures entire page, not just viewport
- Error resilience: Screenshot failure doesn't fail the test (warns only)
- No screenshot on pass: Only captured when test fails
Accessing Screenshots
The screenshot path is returned in the results object:
const results = await executeStep(42, actions);
if (!results.pass && results.screenshot) {
console.log(`Failure screenshot: ${results.screenshot}`);
// Pass to bug creation workflow
}
Step 5: Handle Pass Result with GitHub Comment
When a QA Step passes, post a success comment on the Step issue.
Pass Comment Template
gh issue comment "$STEP" --body "$(cat <<'COMMENT'
## ✅ Passed
- **Executed by:** AI (Claude Code)
- **Timestamp:** $(date -u +"%Y-%m-%d %H:%M:%S UTC")
- **Result:** All assertions passed
### Actions Executed
- Navigate to <URL>
- Click <element>
- Fill <field> with <value>
- Assert text "<text>" visible
COMMENT
)"
Pass Handler Implementation
async function handlePassResult(stepNumber, results) {
const timestamp = new Date().toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
// Build action summary
const actionSummary = results.actions
.filter(a => a.success && !a.skipped)
.map(a => {
switch (a.action.type) {
case 'navigate': return `- Navigate to ${a.action.url}`;
case 'click': return `- Click \`${a.action.selector}\``;
case 'fill': return `- Fill \`${a.action.selector}\` with "${a.action.value}"`;
case 'select': return `- Select "${a.action.value}" from \`${a.action.selector}\``;
case 'wait': return `- Wait ${a.action.duration / 1000} seconds`;
case 'assertText': return `- Assert text "${a.action.text}" visible`;
case 'assertNoText': return `- Assert text "${a.action.text}" not visible`;
case 'assertURL': return `- Assert URL is ${a.action.url}`;
case 'assertURLContains': return `- Assert URL contains "${a.action.pattern}"`;
default: return `- ${a.action.type}`;
}
})
.join('\n');
const comment = `## ✅ Passed
- **Executed by:** AI (Claude Code)
- **Timestamp:** ${timestamp}
- **Result:** All assertions passed
### Actions Executed
${actionSummary}`;
// Post comment using gh CLI
const { execSync } = require('child_process');
execSync(`gh issue comment ${stepNumber} --body "${comment.replace(/"/g, '\\"')}"`, {
stdio: 'inherit'
});
console.log(`Posted pass comment on QA Step #${stepNumber}`);
}
Pass Comment Format
| Field | Value |
|---|---|
| Emoji | ✅ |
| Executed by | AI (Claude Code) |
| Timestamp | UTC timestamp |
| Result | All assertions passed |
| Actions | Bulleted list of executed actions |
Step 6: Handle Fail Result and Trigger Bug Creation
When a QA Step fails, post a failure comment and trigger the bug creation workflow.
Fail Comment Template
gh issue comment "$STEP" --body "$(cat <<'COMMENT'
## ❌ Failed
- **Executed by:** AI (Claude Code)
- **Timestamp:** $(date -u +"%Y-%m-%d %H:%M:%S UTC")
- **Error:** <error message>
### Failed Action
- **Action:** <action that failed>
- **Expected:** <what was expected>
- **Actual:** <what happened>
### Screenshot
📸 Screenshot captured for bug report
### Bug Report
🐛 Creating bug issue...
COMMENT
)"
Fail Handler Implementation
// Bug creation must complete within 30 seconds per NFR2 (Task #43)
const BUG_CREATION_TIMEOUT_MS = 30000;
async function handleFailResult(stepNumber, stepTitle, stepBody, results, qaNumber) {
const startTime = Date.now();
const timestamp = new Date().toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
// Helper to check if we're approaching timeout
const checkTimeout = (operation) => {
const elapsed = Date.now() - startTime;
if (elapsed > BUG_CREATION_TIMEOUT_MS * 0.9) {
console.warn(`Warning: Bug creation approaching 30s timeout at ${operation} (${elapsed}ms elapsed)`);
}
return elapsed;
};
// Find the failed action
const failedAction = results.actions.find(a => a.error);
const failedActionDesc = failedAction
? describeAction(failedAction.action)
: 'Unknown action';
// Extract scenario from step body
const scenarioMatch = stepBody.match(/## Scenario\s+([\s\S]*?)(?=##|$)/);
const scenario = scenarioMatch ? scenarioMatch[1].trim() : 'Scenario not found';
// Build failure comment
const comment = `## ❌ Failed
- **Executed by:** AI (Claude Code)
- **Timestamp:** ${timestamp}
- **Error:** ${results.error}
### Failed Action
\`\`\`
${failedActionDesc}
\`\`\`
### Scenario
\`\`\`
${scenario}
\`\`\`
### Screenshot
${results.screenshot ? '📸 Screenshot captured: `' + results.screenshot + '`' : '⚠️ No screenshot available'}
### Bug Report
🐛 Creating bug issue...`;
// Post failure comment (Task #43 timing: ~2s)
checkTimeout('post failure comment');
const { execSync } = require('child_process');
execSync(`gh issue comment ${stepNumber} --body "${comment.replace(/"/g, '\\"').replace(/`/g, '\\`')}"`, {
stdio: 'inherit'
});
// Bug creation timing breakdown (Task #43 - NFR2):
// - Post failure comment: ~2s
// - Fetch QA Issue for PRD: ~1s
// - Process screenshot: ~2-5s
// - Build bug body: ~0.1s
// - Create bug issue: ~2s
// - Link as sub-issue: ~2s
// - Update Bugs Found: ~2s
// - Post bug link comment: ~1s
// Total estimated: 12-17s (well under 30s target)
// Trigger bug creation workflow (Epic #9)
// Pass context: step number, error, screenshot path, scenario
const bugContext = {
qaStep: stepNumber,
qaIssue: qaNumber,
title: `Bug: ${stepTitle.replace('QA Step: ', '')} - Failed`,
error: results.error,
scenario: scenario,
screenshot: results.screenshot,
timestamp: timestamp
};
// Create bug issue with full template (Epic #9 implementation)
// Build traceability chain: Bug → QA Step → QA Issue → PRD (Task #42)
// Chain traversal:
// 1. Bug knows QA Step number (passed in as stepNumber)
// 2. QA Step body contains QA Issue reference (passed in as qaNumber)
// 3. QA Issue body contains PRD reference (extracted below)
const qaIssueData = JSON.parse(
execSync(`gh issue view ${qaNumber} --json body,title`, { encoding: 'utf-8' })
);
// Look for PRD reference in various formats: "PRD: #123", "PRD #123", "PRD: 123"
const prdPatterns = [
/PRD:\s*#(\d+)/i,
/PRD\s*#(\d+)/i,
/PRD:\s*(\d+)/i,
/-\s*PRD:\s*#(\d+)/i,
/\*\*PRD:\*\*\s*#(\d+)/i
];
let prdNumber = null;
for (const pattern of prdPatterns) {
const match = qaIssueData.body.match(pattern);
if (match) {
prdNumber = match[1];
break;
}
}
// If still not found, it might be in the title or not linked
if (!prdNumber) {
console.warn('Warning: Could not find PRD reference in QA Issue body');
prdNumber = 'Not linked';
}
// Extract Then clause for expected behavior
const thenMatch = scenario.match(/Then\s+(.+?)(?:\n|$)/i);
const expectedBehavior = thenMatch ? thenMatch[1].trim() : 'As specified in the QA Step assertions';
// Process screenshot for attachment (Task #38)
let screenshotSection;
if (results.screenshot) {
const screenshotInfo = await uploadScreenshotToGitHub(results.screenshot);
if (screenshotInfo) {
screenshotSection = screenshotInfo.note;
} else {
screenshotSection = `📸 Screenshot captured but upload failed.\n\nLocal path: \`${results.screenshot}\``;
}
} else {
screenshotSection = '⚠️ No screenshot available';
}
// Build bug body with full template structure (FR6 from PRD #5)
// All references use #<NUMBER> format for clickable GitHub links
const prdReference = /^\d+$/.test(prdNumber) ? `#${prdNumber}` : prdNumber;
const bugBody = `# Bug: ${stepTitle.replace('QA Step: ', '')}
## Source
- **QA Step:** #${stepNumber}
- **QA Issue:** #${qaNumber}
- **PRD:** ${prdReference}
## Reproduction Steps
${generateReproductionSteps(scenario, results.error)}
## Expected Behavior
${expectedBehavior}
## Actual Behavior
${results.error}
## Screenshot
${screenshotSection}
## Environment
- **Browser:** Chromium (Playwright)
- **Viewport:** 1280x720
- **Timestamp:** ${timestamp}
- **Executor:** AI (Claude Code)
`;
// Ensure required labels exist (create if missing)
try {
execSync('gh label create bug --color D73A4A --description "Something isn\'t working" 2>/dev/null || true', { stdio: 'pipe' });
execSync('gh label create QA-Bug --color B60205 --description "Bug found via QA automation" 2>/dev/null || true', { stdio: 'pipe' });
} catch (e) {
// Labels may already exist, continue
}
// Generate error summary for title (truncate if too long)
const errorSummary = results.error.length > 50
? results.error.substring(0, 47) + '...'
: results.error;
// Clean step title for bug title
const cleanStepTitle = stepTitle
.replace(/^QA Step:\s*/i, '')
.replace(/^Step:\s*/i, '');
const bugTitle = `Bug: ${cleanStepTitle} - ${errorSummary}`;
// Write body to temp file to avoid shell escaping issues
const fs = require('fs');
const tempBodyFile = `/tmp/bug-body-${stepNumber}-${Date.now()}.md`;
fs.writeFileSync(tempBodyFile, bugBody);
// Create bug issue with both labels
const bugUrl = execSync(
`gh issue create --title "${bugTitle.replace(/"/g, '\\"')}" --label "bug,QA-Bug" --body-file "${tempBodyFile}"`,
{ encoding: 'utf-8' }
).trim();
// Clean up temp file
fs.unlinkSync(tempBodyFile);
const bugNumber = bugUrl.match(/\/(\d+)$/)?.[1];
// Link Bug as sub-issue of QA Step (Task #39)
// This creates third-level nesting: PRD → QA → Step → Bug
let subIssueLinkSuccess = false;
try {
// Get repo info
const repoInfo = JSON.parse(
execSync('gh repo view --json owner,name', { encoding: 'utf-8' })
);
const owner = repoInfo.owner.login;
const repo = repoInfo.name;
// Get the Bug's internal issue ID (different from issue number)
const bugId = JSON.parse(
execSync(`gh api repos/${owner}/${repo}/issues/${bugNumber} --jq '.id'`, { encoding: 'utf-8' }).trim()
);
// Add Bug as sub-issue of QA Step
execSync(
`gh api repos/${owner}/${repo}/issues/${stepNumber}/sub_issues -X POST -F sub_issue_id=${bugId} --silent`,
{ stdio: 'pipe' }
);
subIssueLinkSuccess = true;
console.log(`Linked Bug #${bugNumber} as sub-issue of QA Step #${stepNumber}`);
} catch (linkError) {
// Sub-issue linking may fail if:
// - Feature not available in this GitHub instance
// - Third-level nesting not supported
// - Bug already has a parent
console.warn(`Warning: Could not link Bug #${bugNumber} as sub-issue of Step #${stepNumber}: ${linkError.message}`);
// Continue without sub-issue link - the body reference is sufficient
}
// Update the failure comment with bug link
const linkNote = subIssueLinkSuccess
? '(linked as sub-issue)'
: '(sub-issue link failed, see bug body for traceability)';
execSync(`gh issue comment ${stepNumber} --body "🐛 Bug created: ${bugUrl} ${linkNote}"`, {
stdio: 'inherit'
});
// Update QA Step's Bugs Found section with bug link (Task #41)
// Skip if we're running low on time (Task #43)
const elapsedBeforeBugsUpdate = checkTimeout('before bugs found update');
if (elapsedBeforeBugsUpdate < BUG_CREATION_TIMEOUT_MS * 0.8) {
try {
await updateBugsFoundSection(stepNumber, bugNumber, stepTitle);
console.log(`Updated Bugs Found section in QA Step #${stepNumber}`);
} catch (updateError) {
console.warn(`Warning: Could not update Bugs Found section: ${updateError.message}`);
// Non-critical - the comment already links to the bug
}
} else {
console.log('Skipping Bugs Found update to meet 30s target');
}
// Add Bug to GitHub Project if GHPM_PROJECT is set (Task #48)
// Skip if we're running low on time (Task #43)
const elapsedBeforeProjectAdd = checkTimeout('before project add');
if (elapsedBeforeProjectAdd < BUG_CREATION_TIMEOUT_MS * 0.85) {
if (process.env.GHPM_PROJECT) {
try {
const repoInfo = JSON.parse(
execSync('gh repo view --json owner,name', { encoding: 'utf-8' })
);
const owner = repoInfo.owner.login;
execSync(
`gh project item-add "${process.env.GHPM_PROJECT}" --owner "${owner}" --url "${bugUrl}"`,
{ stdio: 'pipe' }
);
console.log(`Added Bug #${bugNumber} to project: ${process.env.GHPM_PROJECT}`);
} catch (projectError) {
console.warn(`Warning: Could not add Bug #${bugNumber} to project: ${projectError.message}`);
// Non-critical - continue without project association
}
}
} else {
console.log('Skipping project add to meet 30s target');
}
// Log total bug creation time (Task #43 - NFR2 compliance)
const totalTime = Date.now() - startTime;
const timeStatus = totalTime <= BUG_CREATION_TIMEOUT_MS ? '✅' : '⚠️';
console.log(`${timeStatus} Bug creation completed in ${totalTime}ms (target: ${BUG_CREATION_TIMEOUT_MS}ms)`);
if (totalTime > BUG_CREATION_TIMEOUT_MS) {
console.warn(`Warning: Bug creation exceeded 30s target. Consider optimizing screenshot upload or parallel execution.`);
}
console.log(`Posted fail comment and created bug #${bugNumber} for QA Step #${stepNumber}`);
return bugNumber;
}
// Update QA Step's Bugs Found section with bug link (Task #41)
async function updateBugsFoundSection(stepNumber, bugNumber, bugTitle) {
const fs = require('fs');
// Fetch current step body
const stepData = JSON.parse(
execSync(`gh issue view ${stepNumber} --json body`, { encoding: 'utf-8' })
);
let body = stepData.body;
// Format: - #<BUG_NUMBER> Bug: <Title>
const cleanBugTitle = bugTitle
.replace(/^QA Step:\s*/i, '')
.replace(/^Step:\s*/i, '');
const bugLink = `- #${bugNumber} Bug: ${cleanBugTitle}`;
// Find Bugs Found section and update it
// Pattern: ## Bugs Found\n\n(None) or ## Bugs Found\n\n- #123 ...
const bugsFoundRegex = /## Bugs Found\s*\n\n(\(None\)|[-*][\s\S]*?)(?=\n##|\n*$)/;
if (bugsFoundRegex.test(body)) {
body = body.replace(bugsFoundRegex, (match, existingContent) => {
if (existingContent.trim() === '(None)') {
// Replace "(None)" with bug link
return `## Bugs Found\n\n${bugLink}`;
} else {
// Append to existing bug list
return `## Bugs Found\n\n${existingContent.trim()}\n${bugLink}`;
}
});
} else {
// If no Bugs Found section exists, append it
body = body.trimEnd() + `\n\n## Bugs Found\n\n${bugLink}`;
}
// Write updated body to temp file and update issue
const tempFile = `/tmp/qa-step-body-${stepNumber}-${Date.now()}.md`;
fs.writeFileSync(tempFile, body);
execSync(`gh issue edit ${stepNumber} --body-file "${tempFile}"`, {
stdio: 'pipe'
});
// Clean up temp file
fs.unlinkSync(tempFile);
}
// Upload screenshot to GitHub and return markdown image embed (Task #38)
async function uploadScreenshotToGitHub(screenshotPath) {
if (!screenshotPath) return null;
const fs = require('fs');
const path = require('path');
// Check if file exists
if (!fs.existsSync(screenshotPath)) {
console.warn(`Screenshot file not found: ${screenshotPath}`);
return null;
}
try {
// Get file stats for size check
const stats = fs.statSync(screenshotPath);
const fileSizeMB = stats.size / (1024 * 1024);
// Compress if over 5MB (GitHub has 10MB limit)
if (fileSizeMB > 5) {
console.log(`Screenshot is ${fileSizeMB.toFixed(2)}MB, may need compression`);
// Note: Compression would require additional tools like sharp
// For now, proceed and let GitHub reject if too large
}
// Get repo info
const repoInfo = JSON.parse(
execSync('gh repo view --json owner,name', { encoding: 'utf-8' })
);
const owner = repoInfo.owner.login;
const repo = repoInfo.name;
// GitHub's file upload for issues uses the uploads endpoint
// We can use gh api with file upload to create an asset
// However, direct issue image upload requires special handling
// Alternative approach: Upload via issue comment which auto-uploads images
// Create a temp issue comment with the image, extract the URL, then delete
// This is the most reliable way to get a GitHub-hosted image URL
// For now, we'll embed the local path and note that manual upload may be needed
// A production implementation would use GitHub's upload API or a separate image host
// Read file as base64 for inline embedding (works in some contexts)
const imageData = fs.readFileSync(screenshotPath);
const base64 = imageData.toString('base64');
const filename = path.basename(screenshotPath);
const mimeType = 'image/png';
// Return markdown with note about screenshot location
return {
markdown: ``,
localPath: screenshotPath,
base64: base64,
filename: filename,
note: `📸 Screenshot saved locally: \`${screenshotPath}\`\n\n_To attach: drag and drop the screenshot file into this issue on GitHub._`
};
} catch (error) {
console.warn(`Failed to process screenshot: ${error.message}`);
return null;
}
}
function describeAction(action) {
switch (action.type) {
case 'navigate': return `Navigate to ${action.url}`;
case 'click': return `Click ${action.selector}`;
case 'fill': return `Fill ${action.selector} with "${action.value}"`;
case 'select': return `Select "${action.value}" from ${action.selector}`;
case 'assertText': return `Assert text "${action.text}" is visible`;
case 'assertNoText': return `Assert text "${action.text}" is not visible`;
case 'assertURL': return `Assert URL is ${action.url}`;
case 'assertURLContains': return `Assert URL contains "${action.pattern}"`;
default: return JSON.stringify(action);
}
}
// Generate numbered reproduction steps from Given/When/Then scenario (Task #40)
// Converts Given/When clauses to numbered action steps and adds failure observation
function generateReproductionSteps(scenario, error) {
const steps = [];
const lines = scenario.split('\n').map(l => l.trim()).filter(l => l);
let expectedBehavior = null;
let stepNum = 1;
for (const line of lines) {
if (/^Given\s+/i.test(line)) {
// Convert Given to setup step
let action = line.replace(/^Given\s+/i, '');
// Transform common patterns to clearer language
action = action.replace(/^I am on the /, 'Navigate to the ');
action = action.replace(/^I am on /, 'Navigate to ');
action = action.replace(/^I have /, 'Ensure ');
action = action.replace(/^the /, 'Ensure the ');
steps.push(`${stepNum}. ${action.charAt(0).toUpperCase() + action.slice(1)}`);
stepNum++;
} else if (/^When\s+/i.test(line)) {
// Convert When to action step
let action = line.replace(/^When\s+/i, '');
// Transform first-person to imperative
action = action.replace(/^I click /, 'Click ');
action = action.replace(/^I type /, 'Type ');
action = action.replace(/^I enter /, 'Enter ');
action = action.replace(/^I select /, 'Select ');
action = action.replace(/^I submit /, 'Submit ');
action = action.replace(/^I scroll /, 'Scroll ');
action = action.replace(/^I wait /, 'Wait ');
steps.push(`${stepNum}. ${action.charAt(0).toUpperCase() + action.slice(1)}`);
stepNum++;
} else if (/^And\s+/i.test(line)) {
// And clauses continue previous context
let action = line.replace(/^And\s+/i, '');
// Apply same transformations
action = action.replace(/^I click /, 'Click ');
action = action.replace(/^I type /, 'Type ');
action = action.replace(/^I enter /, 'Enter ');
action = action.replace(/^I select /, 'Select ');
action = action.replace(/^I should see /, 'Should see ');
steps.push(`${stepNum}. ${action.charAt(0).toUpperCase() + action.slice(1)}`);
stepNum++;
} else if (/^Then\s+/i.test(line)) {
// Capture expected behavior from Then clause (used in step observation)
expectedBehavior = line.replace(/^Then\s+/i, '').replace(/^I should /, 'Should ');
}
// Skip other lines (comments, blank, etc.)
}
// Handle empty scenario
if (steps.length === 0) {
steps.push('1. (Scenario steps could not be parsed)');
stepNum = 2;
}
// Add failure observation as final step, including what was expected
const expectedNote = expectedBehavior ? ` (expected: ${expectedBehavior})` : '';
steps.push(`${stepNum}. **Observe:** ${error}${expectedNote}`);
return steps.join('\n');
}
Fail Comment Format
| Field | Value |
|---|---|
| Emoji | ❌ |
| Executed by | AI (Claude Code) |
| Timestamp | UTC timestamp |
| Error | Error message from Playwright |
| Failed Action | Description of the action that failed |
| Scenario | The Given/When/Then from the step |
| Screenshot | Path to captured screenshot |
| Bug Report | Link to created bug issue |
Bug Issue Template Structure (FR6 from PRD #5)
The created bug issue follows this template:
# Bug: <Brief Description>
## Source
- QA Step: #<step_number>
- QA Issue: #<qa_number>
- PRD: #<prd_number>
## Reproduction Steps
1. Navigate to <URL>
2. <action from When clause>
3. <additional actions>
4. **Observe:** <error message>
## Expected Behavior
<from the QA Step's Then clause>
## Actual Behavior
<what actually happened / error message>
## Screenshot
📸 Screenshot attached below (or warning if unavailable)
## Environment
- Browser: Chromium (Playwright)
- Viewport: 1280x720
- Timestamp: <execution time>
- Executor: AI (Claude Code)
The bug issue includes:
- Source: Full traceability chain (QA Step → QA Issue → PRD)
- Reproduction Steps: Numbered list generated from Given/When/Then + failure observation
- Expected Behavior: Extracted from Then clause
- Actual Behavior: Error message from Playwright
- Screenshot: Attached screenshot (when available)
- Environment: Browser, viewport, timestamp details
Step 7: Update QA Step Execution Log Section
Update the Execution Log section in the QA Step issue body with execution results.
Execution Log Section Format
The QA Step issue body contains an Execution Log section:
## Execution Log
- [ ] Pass / Fail
- **Executed by:** (not yet executed)
- **Timestamp:** (pending)
- **Notes:** (none)
After execution, update to:
On Pass:
## Execution Log
- [x] Pass / ~~Fail~~
- **Executed by:** AI (Claude Code)
- **Timestamp:** 2025-01-15 14:30:00 UTC
- **Notes:** All 5 actions completed successfully
On Fail:
## Execution Log
- [ ] ~~Pass~~ / Fail
- **Executed by:** AI (Claude Code)
- **Timestamp:** 2025-01-15 14:30:00 UTC
- **Notes:** Failed at action 3: Assert text "Welcome" visible - Bug #123 created
Update Implementation
async function updateExecutionLog(stepNumber, results, bugNumber = null) {
const timestamp = new Date().toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
// Fetch current issue body
const { execSync } = require('child_process');
const issueData = JSON.parse(
execSync(`gh issue view ${stepNumber} --json body`, { encoding: 'utf-8' })
);
let body = issueData.body;
// Build new Execution Log content
let newExecutionLog;
if (results.pass) {
const actionCount = results.actions.filter(a => a.success).length;
newExecutionLog = `## Execution Log
- [x] Pass / ~~Fail~~
- **Executed by:** AI (Claude Code)
- **Timestamp:** ${timestamp}
- **Notes:** All ${actionCount} actions completed successfully`;
} else {
const failedIndex = results.actions.findIndex(a => a.error);
const notes = bugNumber
? `Failed at action ${failedIndex + 1}: ${results.error} - Bug #${bugNumber} created`
: `Failed at action ${failedIndex + 1}: ${results.error}`;
newExecutionLog = `## Execution Log
- [ ] ~~Pass~~ / Fail
- **Executed by:** AI (Claude Code)
- **Timestamp:** ${timestamp}
- **Notes:** ${notes}`;
}
// Replace Execution Log section in body
// Match from "## Execution Log" to next "##" or end of string
const executionLogRegex = /## Execution Log[\s\S]*?(?=##[^#]|$)/;
if (executionLogRegex.test(body)) {
body = body.replace(executionLogRegex, newExecutionLog + '\n\n');
} else {
// If no Execution Log section exists, append it
body = body + '\n\n' + newExecutionLog;
}
// Update issue body
// Write body to temp file to avoid shell escaping issues
const fs = require('fs');
const tempFile = `/tmp/qa-step-body-${stepNumber}.md`;
fs.writeFileSync(tempFile, body);
execSync(`gh issue edit ${stepNumber} --body-file "${tempFile}"`, {
stdio: 'inherit'
});
// Clean up temp file
fs.unlinkSync(tempFile);
console.log(`Updated Execution Log for QA Step #${stepNumber}`);
}
Update Notes
- Preserve other sections: Only replace the Execution Log section
- Shell escaping: Use temp file to avoid issues with special characters
- Pass/Fail checkbox: Use strikethrough to indicate the opposite result
- Bug reference: Include bug number in notes when applicable
<operating_rules>
- Do not ask clarifying questions. Make reasonable assumptions and proceed.
- Do not create local markdown files. All output goes into GitHub issues/comments.
- Execute steps sequentially, posting results after each step completes.
- If a step fails, continue to the next step (don't abort entire QA run).
- Minimize noise: only comment at meaningful milestones (pass/fail results).
- Never retry failed steps automatically (manual retry or bug triage expected).
</operating_rules>
Before execution, verify:
# 1. Check gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Check Playwright installation
npx playwright --version || { echo "ERROR: Playwright not installed. Run 'npm install -D @playwright/test'"; exit 1; }
# 3. Check browser availability
npx playwright install chromium --dry-run 2>/dev/null || {
echo "WARNING: Chromium may not be installed. Run 'npx playwright install chromium'"
}
<input_validation>
Validation Checks
# Validate step number format (if provided)
if [[ -n "$STEP" && ! "$STEP" =~ ^[0-9]+$ ]]; then
echo "ERROR: Invalid step number. Use format: step=#123"
exit 1
fi
# Validate QA number format (if provided)
if [[ -n "$QA" && ! "$QA" =~ ^[0-9]+$ ]]; then
echo "ERROR: Invalid QA number. Use format: qa=#123"
exit 1
fi
# Verify issue exists and is accessible
if [[ -n "$STEP" ]]; then
gh issue view "$STEP" > /dev/null 2>&1 || { echo "ERROR: Cannot access QA Step #$STEP"; exit 1; }
fi
if [[ -n "$QA" ]]; then
gh issue view "$QA" > /dev/null 2>&1 || { echo "ERROR: Cannot access QA Issue #$QA"; exit 1; }
fi
</input_validation>
<error_handling>
Common Errors and Recovery
If gh CLI not authenticated:
- Check:
gh auth status - Fix:
gh auth login
If Playwright not installed:
- Check:
npx playwright --version - Fix:
npm install -D @playwright/test && npx playwright install chromium
If browser not installed:
- Check:
npx playwright install chromium --dry-run - Fix:
npx playwright install chromium
If QA Step/Issue not found:
- Verify issue number is correct
- Check repository access permissions
- Confirm issue is not closed/deleted
If no QA Steps found for QA Issue:
- Verify QA Steps are linked as sub-issues
- Check that QA Steps have the
QA-Steplabel - Confirm QA Steps are in OPEN state
If Given/When/Then parsing fails:
- Log warning with unparseable line
- Skip unparseable actions during execution
- Include unparseable lines in execution report
If Playwright action fails:
- Capture screenshot before closing browser
- Post failure comment with error details
- Create bug issue with context
- Continue to next QA Step (don't abort run)
If screenshot capture fails:
- Log warning but don't fail the step
- Note "No screenshot available" in bug report
If GitHub API rate limited:
- Check:
gh api rate_limit - Wait and retry, or authenticate with higher-privilege token
</error_handling>
<success_criteria>
Command completes successfully when:
- Target QA Steps have been resolved (from argument or auto-resolved)
- Each QA Step has been executed through Playwright
- Pass results: ✅ comment posted, Execution Log updated
- Fail results: ❌ comment posted, bug created, Execution Log updated
- Bug issues added to
GHPM_PROJECTwhen set (best-effort) - All steps processed (failures don't abort the run)
Verification:
# Check execution comments on QA Steps
gh issue view "$STEP" --json comments -q '.comments[-1].body'
# Check Execution Log was updated
gh issue view "$STEP" --json body -q '.body' | grep -A5 "## Execution Log"
# Check bugs created for failures
gh issue list -l Bug --json number,title
</success_criteria>
After completion, report:
- QA Steps executed: Count and issue numbers
- Results:
- Passed: Count and step numbers
- Failed: Count, step numbers, and bug numbers created
- Project association: Success/warning/skipped for bugs
- Unparseable steps: Count and warnings
- Execution time: Total duration
- Errors: Any issues encountered
Example output:
## QA Execution Complete
- **QA Issue:** #42
- **Steps executed:** 5
### Results
| Step | Title | Result | Bug |
|------|-------|--------|-----|
| #101 | Valid login | ✅ Pass | - |
| #102 | Invalid password | ✅ Pass | - |
| #103 | Form validation | ❌ Fail | #150 |
| #104 | Password reset | ✅ Pass | - |
| #105 | Logout | ✅ Pass | - |
### Summary
- **Passed:** 4
- **Failed:** 1
- **Bugs created:** 1 (#150)
- **Execution time:** 2m 34s
Proceed now.
Optional flags (in $ARGUMENTS):
--label <name>- Add a label (can be used multiple times)--no-branch- Create issue only, skip branch creation--type <fix|feat|chore>- Set work type (default:fix)fix→ addsbuglabel, createsfix/branchfeat→ addsenhancementlabel, createsfeat/branchchore→ no automatic label, createschore/branch
Optional environment variables:
GHPM_PROJECT- GitHub Project number to add issue to (e.g.,export GHPM_PROJECT=7)
<usage_examples> Bug fix (default):
/ghpm:quick-issue Fix the login redirect loop when session expires
Output:
✓ Issue #42 created: "Fix the login redirect loop when session expires"
https://github.com/owner/repo/issues/42
Labels: bug
✓ Branch created: fix/issue-42-login-redirect-loop
✓ Switched to branch fix/issue-42-login-redirect-loop
Ready to work on issue #42. What would you like me to do first?
New feature:
/ghpm:quick-issue Add dark mode toggle --type feat
→ Labels: enhancement
→ Branch: feat/issue-43-dark-mode-toggle
Maintenance/chore:
/ghpm:quick-issue Update dependencies to latest versions --type chore
→ Labels: (none by default)
→ Branch: chore/issue-44-update-dependencies
With additional labels:
/ghpm:quick-issue Fix slow dashboard loading --label performance --label high-priority
→ Labels: bug, performance, high-priority
Issue only (no branch):
/ghpm:quick-issue Update README with new API docs --type chore --no-branch
With project association:
export GHPM_PROJECT=7
/ghpm:quick-issue Fix broken date formatting in reports
→ Issue added to project #7
</usage_examples>
<operating_rules>
- Do not ask clarifying questions. Create the issue immediately with the provided description.
- The issue description becomes both the issue title and the summary in the body.
- Labels are determined by the
--typeflag using standard GitHub labels:fix(default) →buglabelfeat→enhancementlabelchore→ no automatic label
- Additional labels can be added with
--labelflag. - Branch names are sanitized: lowercase, special characters removed, truncated to 50 chars.
- Default type is
fix(assumes most quick issues are bug fixes). - If
--no-branchis specified, skip branch creation entirely. - On any error, provide actionable guidance for resolution. </operating_rules>
Step 1: Validate Environment
# 1. Verify gh CLI authentication
gh auth status || { echo "ERROR: Not authenticated. Run 'gh auth login'"; exit 1; }
# 2. Verify in git repository
git rev-parse --git-dir > /dev/null 2>&1 || { echo "ERROR: Not in a git repository"; exit 1; }
# 3. Verify GitHub remote exists
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner) || { echo "ERROR: No GitHub remote found"; exit 1; }
OWNER=$(gh repo view --json owner -q '.owner.login')
Step 2: Parse Arguments
Extract from $ARGUMENTS:
- Issue description (everything that's not a flag)
--label <name>if present (can appear multiple times)--no-branchflag--type <fix|feat|chore>if present (default:fix)
# Example parsing
DESCRIPTION="<extracted description>"
EXTRA_LABELS=() # array of additional labels from --label flags
NO_BRANCH=false # or true if --no-branch present
WORK_TYPE="fix" # or feat/chore if --type specified
Validate:
- Description must not be empty
- If
--typeprovided, must be one of: fix, feat, chore
Step 3: Determine Labels Based on Type
# Map work type to standard GitHub label
case "$WORK_TYPE" in
fix)
TYPE_LABEL="bug"
BRANCH_PREFIX="fix"
;;
feat)
TYPE_LABEL="enhancement"
BRANCH_PREFIX="feat"
;;
chore)
TYPE_LABEL="" # No automatic label for chores
BRANCH_PREFIX="chore"
;;
esac
# Build label list
LABELS=""
if [ -n "$TYPE_LABEL" ]; then
LABELS="$TYPE_LABEL"
fi
# Add any extra labels from --label flags
for label in "${EXTRA_LABELS[@]}"; do
if [ -n "$LABELS" ]; then
LABELS="$LABELS,$label"
else
LABELS="$label"
fi
done
Step 4: Create GitHub Issue
# Build gh issue create command
if [ -n "$LABELS" ]; then
ISSUE_URL=$(gh issue create \
--repo "$REPO" \
--title "$DESCRIPTION" \
--label "$LABELS" \
--body "$(cat <<EOF
$DESCRIPTION
---
*Created via \`/ghpm:quick-issue\`*
EOF
)")
else
# No labels
ISSUE_URL=$(gh issue create \
--repo "$REPO" \
--title "$DESCRIPTION" \
--body "$(cat <<EOF
$DESCRIPTION
---
*Created via \`/ghpm:quick-issue\`*
EOF
)")
fi
# Extract issue number from URL
ISSUE_NUM=$(echo "$ISSUE_URL" | grep -oE '[0-9]+$')
Step 5: Add to GitHub Project (if configured)
if [ -n "$GHPM_PROJECT" ]; then
gh project item-add "$GHPM_PROJECT" --owner "$OWNER" --url "$ISSUE_URL" 2>/dev/null && \
echo "✓ Added to project #$GHPM_PROJECT" || \
echo "WARNING: Could not add to project #$GHPM_PROJECT"
fi
Step 6: Create and Checkout Branch (unless --no-branch)
if [ "$NO_BRANCH" = false ]; then
# Generate branch name slug from description
# 1. Convert to lowercase
# 2. Replace spaces and special chars with hyphens
# 3. Remove consecutive hyphens
# 4. Truncate to 50 chars
# 5. Remove trailing hyphens
SLUG=$(echo "$DESCRIPTION" | \
tr '[:upper:]' '[:lower:]' | \
sed 's/[^a-z0-9]/-/g' | \
sed 's/-\+/-/g' | \
cut -c1-50 | \
sed 's/-$//')
BRANCH_NAME="$BRANCH_PREFIX/issue-$ISSUE_NUM-$SLUG"
# Check for uncommitted changes
if ! git diff-index --quiet HEAD -- 2>/dev/null; then
echo "WARNING: Uncommitted changes detected. Branch created but not checked out."
echo "Run: git stash && git checkout $BRANCH_NAME"
else
# Create and checkout branch
git checkout -b "$BRANCH_NAME" || {
echo "ERROR: Failed to create branch. You may need to create it manually:"
echo " git checkout -b $BRANCH_NAME"
}
fi
# Update issue body with branch link
gh issue edit "$ISSUE_NUM" --repo "$REPO" --body "$(cat <<EOF
$DESCRIPTION
**Branch:** \`$BRANCH_NAME\`
---
*Created via \`/ghpm:quick-issue\`*
EOF
)"
fi
Step 7: Output Success Message
echo ""
echo "✓ Issue #$ISSUE_NUM created: \"$DESCRIPTION\""
echo " $ISSUE_URL"
if [ -n "$LABELS" ]; then
echo " Labels: $LABELS"
fi
if [ "$NO_BRANCH" = false ]; then
echo "✓ Branch created: $BRANCH_NAME"
echo "✓ Switched to branch $BRANCH_NAME"
fi
if [ -n "$GHPM_PROJECT" ]; then
echo "✓ Added to project #$GHPM_PROJECT"
fi
echo ""
echo "Ready to work on issue #$ISSUE_NUM. What would you like me to do first?"
<error_handling> If gh CLI not authenticated:
ERROR: Not authenticated. Run 'gh auth login'
If not in git repository:
ERROR: Not in a git repository. Navigate to your project directory.
If no GitHub remote:
ERROR: No GitHub remote found. Add one with: git remote add origin <url>
If description is empty:
ERROR: Issue description required.
Usage: /ghpm:quick-issue <description> [--type <fix|feat|chore>] [--label <name>] [--no-branch]
If issue creation fails:
ERROR: Failed to create issue. Check:
- gh auth status (authentication)
- Repository permissions (write access to issues)
- Rate limits: gh api rate_limit
If branch creation fails:
WARNING: Issue #N created, but branch creation failed.
Create branch manually: git checkout -b <branch-name>
If uncommitted changes exist:
WARNING: Uncommitted changes detected. Branch created but not checked out.
Run: git stash && git checkout <branch-name>
</error_handling>
<success_criteria> Command completes successfully when:
- GitHub issue is created with appropriate label(s) based on type
- Issue body contains description and branch link (if branch created)
- Branch is created with correct naming convention (unless
--no-branch) - Branch is checked out (unless uncommitted changes or
--no-branch) - Issue is added to project (if
GHPM_PROJECTset) - Success message displays issue URL, labels, and branch name
Verification:
# View the created issue
gh issue view <issue_number>
# Check current branch
git branch --show-current
# Verify issue labels
gh issue view <issue_number> --json labels -q '.labels[].name'
</success_criteria>
After completion, display:✓ Issue #<number> created: "<description>"
<issue_url>
Labels: <label1>, <label2>
✓ Branch created: <branch_prefix>/issue-<number>-<slug>
✓ Switched to branch <branch_prefix>/issue-<number>-<slug>
[✓ Added to project #<project_number>] (if GHPM_PROJECT set)
Ready to work on issue #<number>. What would you like me to do first?
If --no-branch was specified:
✓ Issue #<number> created: "<description>"
<issue_url>
Labels: <label1>, <label2>
[✓ Added to project #<project_number>] (if GHPM_PROJECT set)
Issue created. Run `/ghpm:tdd-task task=#<number>` to start implementation.
<related_commands> After creating a quick issue:
/ghpm:tdd-task task=#N- Implement the issue using TDD/ghpm:execute task=#N- Execute the issue (auto-routes to TDD or non-TDD)
Full GHPM workflow (for larger features):
/ghpm:create-prd- Create PRD from user input/ghpm:create-epics- Break PRD into Epics/ghpm:create-tasks- Break Epics into Tasks/ghpm:tdd-task- Implement Tasks with TDD </related_commands>
Proceed now: parse $ARGUMENTS, validate environment, create issue and branch.
Resolution order if omitted:
- If branch name matches
ghpm/task-<N>-*ortask-<N>-*, use N - Most recent open issue labeled
Taskassigned to @me:gh issue list -l Task -a @me -s open --limit 1 --json number -q '.[0].number' - Most recent open Task:
gh issue list -l Task -s open --limit 1 --json number -q '.[0].number'
<usage_examples> With task number:
/ghpm:tdd-task task=#42
With focus hint:
/ghpm:tdd-task task=#42 focus=unit
Auto-resolve from branch:
# On branch: ghpm/task-42-add-auth
/ghpm:tdd-task
Auto-resolve from GitHub:
# No arguments - uses most recent assigned Task
/ghpm:tdd-task
</usage_examples>
<operating_rules>
- Always create a feature branch before making changes. Never commit directly to main/master.
- No local markdown artifacts. Do not write local status files; only code changes + GitHub issue/PR updates.
- Do NOT use the TodoWrite tool to track tasks during this session.
- Do not silently expand scope. If you must, create a new follow-up Task issue and link it.
- Always provide a runnable test command in the final notes.
- Minimize noise: comment at meaningful milestones.
- All commits and PR titles MUST follow Conventional Commits format for changelog generation. </operating_rules>
<conventional_commits>
Conventional Commits Format
All commits and PR titles must follow the Conventional Commits specification to enable automated changelog generation.
Format
<type>[optional scope]: <description> (#<issue>)
[optional body]
[optional footer(s)]
Commit Types
| Type | Description | Changelog Section |
|---|---|---|
feat | New feature or capability | Features |
fix | Bug fix | Bug Fixes |
refactor | Code restructuring without behavior change | Code Refactoring |
perf | Performance improvement | Performance |
test | Adding or updating tests | Testing |
docs | Documentation only changes | Documentation |
style | Formatting, whitespace (no code change) | (excluded) |
chore | Build, CI, dependencies, tooling | Maintenance |
revert | Revert a previous commit | Reverts |
Determining Commit Type
Infer the type from the Task context:
- Task labels:
enhancement→feat,bug→fix - Task title keywords: "add", "implement", "create" →
feat; "fix", "resolve", "correct" →fix - Epic context: Feature epic →
feat, Bug epic →fix, Tech debt epic →refactor - Scope of change: If primarily tests →
test, if primarily docs →docs
Breaking Changes
For breaking changes, add `!` after the type or include `BREAKING CHANGE:` in the footer:
feat!: remove deprecated API endpoint (#123)
BREAKING CHANGE: The /v1/users endpoint has been removed. Use /v2/users instead.
Examples
Feature commit:
feat(auth): add OAuth2 login flow (#42)
Bug fix commit:
fix(payments): resolve null pointer in checkout (#103)
Refactor commit:
refactor(users): extract email service into separate module (#87)
Test commit:
test(api): add integration tests for user endpoints (#156)
Commit Message During TDD Cycles
During Red-Green-Refactor cycles, commit at each meaningful milestone:
- RED phase:
test(<scope>): add failing test for <behavior> (#<task>) - GREEN phase:
feat(<scope>): implement <behavior> (#<task>)orfix(<scope>): ... - REFACTOR phase:
refactor(<scope>): <improvement description> (#<task>)
</conventional_commits>
Step 0: Hydrate context
Resolve the task number and fetch context:
# Resolve task number from arguments, branch, or auto-select
TASK={resolved_task_number}
# Fetch issue details
gh issue view "$TASK" --json title,body,url,labels,comments -q '.'
Extract from issue:
- Acceptance criteria
- Test plan (or infer if missing)
- Epic/PRD links
Step 0.5: Validate Task Status
Before proceeding, check if the task is already closed or marked as done:
# Fetch issue state and labels
ISSUE_DATA=$(gh issue view "$TASK" --json state,labels,projectItems -q '.')
STATE=$(echo "$ISSUE_DATA" | jq -r '.state')
# Check if issue is closed
if [ "$STATE" = "CLOSED" ]; then
echo "Task #$TASK is already CLOSED. Cannot proceed with TDD."
exit 0
fi
# Check for "Done" label
DONE_LABEL=$(echo "$ISSUE_DATA" | jq -r '.labels[]?.name | select(. == "Done" or . == "done" or . == "DONE")')
if [ -n "$DONE_LABEL" ]; then
echo "Task #$TASK has 'Done' label. Cannot proceed with TDD."
exit 0
fi
# Check project status field (if linked to a project)
PROJECT_STATUS=$(echo "$ISSUE_DATA" | jq -r '.projectItems[]?.status?.name // empty')
if [ "$PROJECT_STATUS" = "Done" ] || [ "$PROJECT_STATUS" = "Completed" ]; then
echo "Task #$TASK has project status '$PROJECT_STATUS'. Cannot proceed with TDD."
exit 0
fi
Behavior:
- If task is CLOSED → exit with message "Task #N is already closed. Cannot proceed with TDD."
- If task has "Done" label → exit with message "Task #N is marked as done. Cannot proceed with TDD."
- If task's project status is "Done" or "Completed" → exit with status message
Step 0.8: Claim Issue
Before starting any work, claim the issue to prevent duplicate work and enable progress tracking.
# Get current GitHub user
CURRENT_USER=$(gh api user -q '.login')
if [ -z "$CURRENT_USER" ]; then
echo "ERROR: Could not determine current GitHub user. Run 'gh auth login'"
exit 1
fi
# Check existing assignees
ASSIGNEES=$(gh issue view "$TASK" --json assignees -q '.assignees[].login')
# Handle assignment scenarios
if [ -z "$ASSIGNEES" ]; then
# No assignees - claim the issue
gh issue edit "$TASK" --add-assignee @me
echo "✓ Assigned to @$CURRENT_USER"
# Post audit comment
TIMESTAMP=$(date -u +"%Y-%m-%d %H:%M:%S UTC")
gh issue comment "$TASK" --body "🏷️ Claimed by @$CURRENT_USER at $TIMESTAMP"
elif echo "$ASSIGNEES" | grep -qx "$CURRENT_USER"; then
# Already assigned to current user - proceed
echo "✓ Already assigned to you (@$CURRENT_USER)"
else
# Assigned to another user - abort
EXISTING_ASSIGNEE=$(echo "$ASSIGNEES" | head -1)
echo "✗ Task #$TASK is already claimed by @$EXISTING_ASSIGNEE"
exit 1
fi
# Update project status to "In Progress" (best-effort)
if [ -n "$GHPM_PROJECT" ]; then
OWNER=$(gh repo view --json owner -q '.owner.login')
# Note: Project status update is best-effort and may require manual verification
echo "Note: Project status update to 'In Progress' is best-effort"
fi
# Warn on orphaned state (In Progress without assignee)
if [ -z "$ASSIGNEES" ] && [ -n "$GHPM_PROJECT" ]; then
PROJECT_STATUS=$(gh issue view "$TASK" --json projectItems -q '.projectItems[0].status.name // empty' 2>/dev/null)
if [ "$PROJECT_STATUS" = "In Progress" ]; then
echo "⚠ Warning: Task #$TASK had status 'In Progress' but no assignee"
fi
fi
UX Output:
| Scenario | Output |
|---|---|
| Success (new claim) | ✓ Assigned to @username |
| Self-claim | ✓ Already assigned to you (@username) |
| Conflict | ✗ Task #N is already claimed by @another-user |
| Orphaned state | ⚠ Warning: Task #N had status 'In Progress' but no assignee |
Behavior:
- Claiming occurs BEFORE any work begins (before TDD plan posting)
- On conflict, command aborts cleanly with no partial work
- On self-claim, command proceeds normally
- All claiming operations complete within 3 seconds
Step 1: Post a TDD Plan comment
Comment on the Task with your implementation plan:
## TDD Plan
- **Objective:**
- **Target behavior / acceptance criteria:**
- **Test strategy (focus level + what to cover):**
- **Proposed minimal design (non-binding):**
- **Commands (build/test/lint) you will run:**
- **Milestones (Red/Green/Refactor slices):**
Execute:
gh issue comment "$TASK" --body "<markdown>"
Step 2: Create a working branch
git checkout -b "ghpm/task-$TASK-<short-slug>"
Comment branch name to the issue (same comment or a follow-up).
Step 3: TDD execution loop
For each slice:
- RED: Add failing test(s)
- Commit:
test(<scope>): add failing test for <behavior> (#$TASK)
- Commit:
- GREEN: Implement minimum change to pass
- Commit:
<type>(<scope>): <description> (#$TASK)(typicallyfeatorfix)
- Commit:
- REFACTOR: Clean up while tests stay green
- Commit:
refactor(<scope>): <description> (#$TASK)
- Commit:
- Run tests and capture command + result
Commit after each phase using conventional commit format. Determine the type from Task context (see <conventional_commits> section).
After each slice, comment on the Task with:
- What changed
- Tests added/updated
- Test command executed + result
- Commit hash(es) made
- Any decision/rationale
Step 4: Update the Task body with a "Task Report" section
Edit the issue body to append:
## Task Report (auto)
### Implementation summary
### Files changed
### How to validate locally
### Test command(s) and results
### Decision log
### Follow-ups (if any)
Execute:
gh issue edit "$TASK" --body "<updated markdown>"
Step 5: Open a PR that closes the Task
Push branch and create PR using Conventional Commits format for the title:
git push -u origin HEAD
# Determine type from Task context (see <conventional_commits> section)
# Format: <type>(<scope>): <description> (#$TASK)
gh pr create --title "<type>(<scope>): <description> (#$TASK)" --body "$(cat <<'EOF'
Closes #$TASK
## Summary
- ...
## Test Plan
- `<test command>`
## Commits
<list of conventional commits made during TDD>
EOF
)"
PR Title Examples:
feat(auth): add OAuth2 login flow (#42)fix(payments): resolve checkout null pointer (#103)refactor(users): extract email service (#87)
Comment the PR URL back onto the Task:
gh issue comment "$TASK" --body "PR created: <PR_URL>"
Step 6: Final checkpoint
- Ensure all tests pass
- Ensure Task Report is updated in issue body
- Ensure PR references and closes the Task
<success_criteria> Command completes when:
- All tests pass
- Task Report section is updated in the issue body
- PR is created with
Closes #$TASKin the body - PR URL is commented back to the Task </success_criteria>
<error_handling> If tests fail during a cycle:
- Do not proceed to refactor
- Comment on issue with failure details
- Debug and fix before continuing
If PR creation fails:
- Ensure branch is pushed
- Check repository permissions
- Verify issue number exists
- Comment failure details on Task issue </error_handling>
Proceed now.
Agents 1
You are a CI Check agent that monitors GitHub Actions status after PR creation and handles failures intelligently.
Purpose
After a PR is created, verify that CI checks pass. If they fail:
- Analyze the failure to determine root cause
- Categorize as "in-scope" (related to PR changes) or "out-of-scope" (pre-existing issues)
- Attempt to fix in-scope failures
- Create follow-up issues for out-of-scope failures
- Report findings back to the PR
Workflow
Step 1: Get PR Information
# Get the current PR number (from branch or argument)
PR_NUMBER=$(gh pr view --json number -q '.number' 2>/dev/null)
if [ -z "$PR_NUMBER" ]; then
echo "ERROR: No PR found for current branch"
exit 1
fi
# Get PR details
gh pr view "$PR_NUMBER" --json title,headRefName,body,files
Step 2: Wait for CI to Complete
# Check CI status - wait up to 10 minutes for completion
MAX_WAIT=600
INTERVAL=30
WAITED=0
while [ $WAITED -lt $MAX_WAIT ]; do
STATUS=$(gh pr checks "$PR_NUMBER" --json state -q '.[].state' | sort -u)
# Check if all checks are complete
if ! echo "$STATUS" | grep -qE "PENDING|IN_PROGRESS|QUEUED"; then
break
fi
echo "CI still running... waiting ${INTERVAL}s (${WAITED}s elapsed)"
sleep $INTERVAL
WAITED=$((WAITED + INTERVAL))
done
# Get final status
gh pr checks "$PR_NUMBER"
Step 3: Analyze Failures
If any checks failed:
# Get failed checks
FAILED_CHECKS=$(gh pr checks "$PR_NUMBER" --json name,state,conclusion -q '.[] | select(.conclusion == "FAILURE") | .name')
if [ -z "$FAILED_CHECKS" ]; then
echo "All CI checks passed!"
gh pr comment "$PR_NUMBER" --body "CI Status: All checks passed"
exit 0
fi
echo "Failed checks: $FAILED_CHECKS"
For each failed check:
-
Fetch the failure logs:
# Get the run ID for the failed check RUN_ID=$(gh run list --branch "$(gh pr view $PR_NUMBER --json headRefName -q '.headRefName')" --limit 1 --json databaseId -q '.[0].databaseId') # View the failed job logs gh run view "$RUN_ID" --log-failed -
Categorize the failure:
In-Scope Failures (attempt to fix):
- Test failures in files changed by the PR
- Lint/style errors in files changed by the PR
- Type errors in files changed by the PR
- Build errors caused by PR changes
Out-of-Scope Failures (create follow-up issue):
- Test failures in files NOT changed by the PR
- Pre-existing lint violations in unchanged files
- Infrastructure/CI configuration issues
- Flaky tests that pass on retry
Step 4: Fix In-Scope Failures
For in-scope failures:
- Analyze the error message to understand what needs to be fixed
- Read the relevant file(s) to understand the context
- Make the fix using Edit tool
- Run the check locally if possible to verify:
# For Ruby/RuboCop bundle exec rubocop <file> # For tests bundle exec rspec <spec_file> # For TypeScript/ESLint npm run lint -- <file> - Commit the fix:
git add -A git commit -m "fix(ci): resolve <issue> (#<PR_NUMBER>)" git push
Step 5: Handle Out-of-Scope Failures
For out-of-scope failures, create a follow-up issue:
gh issue create --title "Fix pre-existing CI failure: <description>" --body "$(cat <<'EOF'
## Context
Discovered during PR #<PR_NUMBER>: <PR_TITLE>
This CI failure is **pre-existing** and not related to the PR changes.
## Failure Details
- **Check:** <check_name>
- **Error:** <error_message>
- **File(s):** <affected_files>
## Suggested Fix
<analysis_and_fix_suggestion>
---
*Auto-created by CI Check Agent*
EOF
)"
Step 6: Report Status
Comment on the PR with findings:
gh pr comment "$PR_NUMBER" --body "$(cat <<'EOF'
## CI Check Report
### Status: <PASSED|FAILED|PARTIALLY_FIXED>
### In-Scope Issues
<list of issues found and fixed, or "None">
### Out-of-Scope Issues
<list of pre-existing issues with links to follow-up issues, or "None">
### Actions Taken
- <list of commits made to fix issues>
- <list of follow-up issues created>
---
*Generated by CI Check Agent*
EOF
)"
Error Handling
- If CI doesn't complete within timeout, report status and exit
- If unable to determine failure cause, report as "needs manual investigation"
- If fix attempt fails, revert changes and report the issue
- Never force-push or modify git history
Success Criteria
- CI status is checked and reported
- In-scope failures are fixed (or attempted with clear explanation if not possible)
- Out-of-scope failures have follow-up issues created
- PR has a comment summarizing CI status and any actions taken
Sponsors
Details
- Marketplace
- el-feo/ai-context
- Source
- plugins/ghpm
- Author
- Jeb Coleman
- Category
- Community
