Implement Skill
Quick Ref: Execute single issue end-to-end. Output: code changes + commit + closed issue.
YOU MUST EXECUTE THIS WORKFLOW. Do not just describe it.
Execute a single issue from start to finish.
CLI dependencies: bd (issue tracking), ao (ratchet gates). Both optional β see skills/shared/SKILL.md for fallback table. If bd is unavailable, use the issue description directly and track progress via TaskList instead of beads.
Execution Steps
Given /implement <issue-id-or-description>:
Step 0: Pre-Flight Checks (Resume + Gates)
For resume protocol details, read skills/implement/references/resume-protocol.md.
For ratchet gate checks and pre-mortem gate details, read skills/implement/references/gate-checks.md.
Step 0.5: Pull Relevant Knowledge
ao lookup --bead <issue-id> --limit 3 2>/dev/null || true
Apply retrieved knowledge (mandatory when results returned):
If learnings or patterns are returned, do NOT just load them as passive context. For each returned item:
- Check: does this learning apply to the current issue? (answer yes/no)
- If yes: treat it as an implementation constraint β does it warn about an approach? suggest a pattern? flag a known pitfall?
- Reference applicable learnings in your implementation decisions (e.g., "per learning X, avoiding approach Y")
- Cite applicable learnings by filename in commit messages or PR descriptions
After reviewing, record each citation with the correct type:
ao metrics cite "<learning-path>" --type applied 2>/dev/null || true
ao metrics cite "<learning-path>" --type retrieved 2>/dev/null || true
Section evidence: When lookup results include section_heading, matched_snippet, or match_confidence fields, prefer the matched section over the whole file β it pinpoints the relevant portion. Higher match_confidence (>0.7) means the section is a strong match; lower values (<0.4) are weaker signals. Use the matched_snippet as the primary context rather than reading the full file.
Skip silently if ao is unavailable or returns no results.
Step 1: Get Issue Details
If beads issue ID provided (e.g., gt-123):
bd show <issue-id> 2>/dev/null
If plain description provided: Use that as the task description.
If no argument: Check for ready work:
bd ready 2>/dev/null | head -3
Step 2: Claim the Issue
bd update <issue-id> --status in_progress 2>/dev/null
Step 2a: Build Context Briefing
if command -v ao &>/dev/null; then
ao context assemble --task='<issue title and description>'
fi
This produces a 5-section briefing (GOALS, HISTORY, INTEL, TASK, PROTOCOL) at .agents/rpi/briefing-current.md with secrets redacted. Read it before gathering additional context.
Step 3: Gather Context
USE THE TASK TOOL to explore relevant code:
Tool: Task
Parameters:
subagent_type: "Explore"
description: "Gather context for: <issue title>"
prompt: |
Find code relevant to: <issue description>
1. Search for related files (Glob)
2. Search for relevant keywords (Grep)
3. Read key files to understand current implementation
4. Identify where changes need to be made
Return:
- Files to modify (paths)
- Current implementation summary
- Suggested approach
- Any risks or concerns
Step 3.5: Grep for Existing Utilities
Before implementing any new function or utility, grep the codebase for existing implementations:
grep -rn "<function-name-pattern>" --include="*.go" --include="*.py" --include="*.ts" .
Why: In context-orchestration-leverage, a worker created a duplicate estimateTokens function that already existed in context.go. A 5-second grep would have prevented the duplication and the rework needed to consolidate it.
If you find an existing implementation, reuse it. If it needs modification, modify it in place rather than creating a parallel version.
Step 3.6: Write Failing Tests First (TDD-First Default)
Before implementing, write tests that define the expected behavior:
- Write tests covering: happy path, one error path, one edge case
- Run tests to confirm they FAIL (RED confirmation)
- If tests pass β feature already exists or tests are wrong. Investigate before proceeding.
- Proceed to Step 4 with failing tests as the implementation target
Test level selection: Classify each test by pyramid level (see the test pyramid standard (test-pyramid.md in the standards skill)):
- L0 (Contract): Write if the issue touches spec boundaries, file existence, or registration
- L1 (Unit): Write always for feature/bug issues β happy path, one error path, one edge case
- L2 (Integration): Write if the change crosses module boundaries or involves multiple components
- L3 (Component): Write if the change affects a full subsystem workflow (with mocked external deps)
If the issue includes test_levels metadata from /plan, use those levels. Otherwise, default to L1 + any applicable higher levels from the decision tree above.
When delegating to /test, carry those selected levels and any BF expectations into the request context. --quick is not permission to collapse to L1-only coverage.
Bug-Finding Level Selection (alongside L0βL3):
If the implementation touches external boundaries (APIs, databases, file I/O):
- Add BF4 chaos test: mock the boundary to fail, verify graceful error handling
- This catches the bugs that L1 unit tests mock away
If the implementation includes data transformations (parse, render, serialize):
- Add BF1 property test: randomize inputs with hypothesis/gopter/fast-check
- This catches edge cases no human would write
If the implementation generates output files (configs, reports, manifests):
- Add BF2 golden test: generate canonical output, save as golden file, assert match
Reference: the test pyramid standard in /standards for full tooling matrix.
RED Verification Gate (mechanical):
After writing tests, run the test suite and verify ALL new tests FAIL:
- If exit code == 0 (all tests PASS before implementation): BLOCK with "Tests pass before implementation -- either feature already exists or tests don't test new behavior. Investigate."
- If exit code != 0 (tests fail as expected): proceed to Step 4
- Skip if:
--no-tdd flag is set, GREEN mode is active, or issue type is chore, docs, or ci
Skip conditions (any of these bypasses Step 3.5):
- GREEN mode is active (invoked by
/crank --test-first β tests already exist)
- Issue type is
chore, docs, or ci
--no-tdd flag is set
- No test framework detected in the project
Note: Tests written here are MUTABLE β unlike GREEN mode's immutable tests, you may adjust these tests during implementation if you discover the initial test design was wrong. The goal is to think about behavior before code, not to be rigid.
Step 3.6a: Auto-Generate Tests via /test (lifecycle integration)
If skip conditions above are NOT met AND --no-lifecycle is NOT set:
Skill(skill="test", args="generate <feature-scope> --quick")
The generated test request must preserve the selected test_levels and BF expectations from Step 3.6. Review the generated tests. Adjust as needed (tests are MUTABLE in this context). If /test fails to produce useful output or is unavailable, fall back to manual test writing in Step 3.6 above.
Skip if: --no-lifecycle flag, GREEN mode active, issue type is chore/docs/ci, or /test is unavailable.
CI-safe tests: If the function under test shells out to an external CLI (bd, ao, gh), do NOT test the wrapper. Instead, test the underlying function that performs the testable work (event emission, state mutation, file I/O). See the Go standards (Testing section) for examples.
Step 4: Implement the Change
GREEN Mode check: If test files were provided (invoked by /crank --test-first):
- Read all provided test files FIRST
- Read the contract for invariants
- Implement to make tests pass (do NOT modify test files)
- Skip to Step 5 verification
Based on the context gathered:
- Edit existing files using the Edit tool (preferred)
- Write new files only if necessary using the Write tool
- Follow existing patterns in the codebase
- Keep changes minimal - don't over-engineer
Step 4a: Build Verification (CLI repos only)
If the project has a Go cmd/ directory or a Makefile with a build target, run build verification before proceeding to tests:
if [ -f go.mod ] && ls cmd/*/main.go &>/dev/null; then
echo "CLI repo detected β running build verification..."
go build ./cmd/... 2>&1
if [ $? -ne 0 ]; then
echo "BUILD FAILED β fix compilation errors before proceeding"
fi
go vet ./cmd/... 2>&1
BINARY=$(ls -t cmd/*/main.go | head -1 | xargs dirname | xargs basename)
if [ -f "bin/$BINARY" ]; then
./bin/$BINARY --help > /dev/null 2>&1
echo "Smoke test: $BINARY --help passed"
fi
fi
If build fails: Fix compilation errors and re-run before proceeding. Do NOT skip to verification with a broken build.
If not a CLI repo: This step is a no-op β proceed directly to Step 5.
Step 4.5: Security Verification
Before proceeding to functional verification, check for common security issues in modified code:
| Check |
What to Look For |
Action |
| Input validation |
User/external input used without validation |
Add validation at entry points |
| Output escaping |
Raw data in HTML/templates (innerHTML, document.write, dangerouslySetInnerHTML) |
Use framework auto-escaping or explicit sanitization |
| Path safety |
Path traversal via .. sequences; file paths from user input without sanitization |
Reject .., absolute paths; use filepath.Clean() or equivalent; verify path stays within allowed directory |
| Auth gates |
Endpoints/handlers missing authentication or authorization checks |
Add middleware or guard clauses |
| Content-Type |
HTTP responses without explicit Content-Type headers |
Set Content-Type to prevent MIME-sniffing attacks |
| CORS |
Overly permissive CORS configuration (* origin, credentials: true) |
Restrict to known origins; never combine wildcard with credentials |
| CSRF tokens |
State-changing endpoints (POST/PUT/DELETE) without anti-CSRF tokens |
Add anti-CSRF token validation; do not rely solely on cookies for auth |
| Rate limiting |
Authentication, API, and upload endpoints without rate limits |
Add rate-limit middleware; return 429 with Retry-After header |
Skip when: The change does not involve HTTP handlers, user-facing input, file system operations, or template rendering. Pure internal refactors, test-only changes, and documentation edits skip this step.
If issues found: Fix before proceeding to Step 5. Log fixes in the commit message.
Step 5: Verify the Change
Success Criteria (all must pass):
Check for test files and run them:
ls *test* tests/ test/ __tests__/ 2>/dev/null | head -5
If tests exist: All tests must pass. Any failure = verification failed.
If no tests exist: Manual verification required:
If verification fails: Do NOT proceed to Step 5a. Fix the issue first.
Step 5a: Verification Gate (MANDATORY)
THE IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
Before reporting success,