
Implement
- 1.3k installs
- 416 repo stars
- Updated August 5, 2026
- boshu2/agentops
implement provides documented workflows for Implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill".
About
The implement skill implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill". # 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.** ## Loop position Move **4 (TDD per slice)** of the [operating loop](../../docs/architecture/operating-loop.md). Consumes one vertical slice from the [slice validation plan](../../docs/templates/slice-validation.md); produces failing test → passing implementation → refactor-under-green. Discipline: (1) first failing test must fail for the right reason (missing behavior, not syntax); (2) smallest change to flip green; (3) refactor as its own commit. Slices that mix refactor + feature are two slices, not one. Code without a failing test has no contract; the slice is not done. 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.
- Use `/implement <issue-id>` to implement a specific tracked issue.
- Use `/implement` (no argument) to pick up next ready work via `bd ready`.
- Use `/implement <description>` to implement an ad-hoc task without a tracked issue.
- **`pr-implement` → OSS contribution mode.** Use when you need to implement a scoped OSS PR -
- Agent reads issue from beads: "Add JWT token validation middleware"
Implement by the numbers
- 1,300 all-time installs (skills.sh)
- +26 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #345 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
implement capabilities & compatibility
- Capabilities
- use `/implement <issue id>` to implement a speci · use `/implement` (no argument) to pick up next r · use `/implement <description>` to implement an a · **`pr implement` → oss contribution mode.** use · agent reads issue from beads: "add jwt token val
- Use cases
- documentation
What implement says it does
# Implement Skill > **Quick Ref:** Execute single issue end-to-end.
Output: code changes + commit + closed issue.
npx skills add https://github.com/boshu2/agentops --skill implementAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.3k |
|---|---|
| repo stars | ★ 416 |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 5, 2026 |
| Repository | boshu2/agentops ↗ |
How do I use implement for the task described in its SKILL.md triggers?
Implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill".
Who is it for?
Teams invoking implement when the user request matches documented triggers and prerequisites.
Skip if: Skip when cached docs are missing, the request is a negative trigger, or another sibling skill owns the workflow.
When should I use this skill?
Implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill".
What you get
Step-by-step guidance grounded in implement documentation and reference files.
- .agents/specs/<issue-id>.json behavioral specification
By the numbers
- Produces behavioral specs at schema version 1 in .agents/specs/
- Connects to Stage 4 behavioral validation STEP 1.8 in /validation
Files
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.
Loop position
Move 4 (TDD per slice) of the operating loop. Consumes one vertical slice from the slice validation plan; produces failing test → passing implementation → refactor-under-green. Discipline: (1) first failing test must fail for the right reason (missing behavior, not syntax); (2) smallest change to flip green; (3) refactor as its own commit. Slices that mix refactor + feature are two slices, not one. Code without a failing test has no contract; the slice is not done.
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.
When to use
- Use
/implement <issue-id>to implement a specific tracked issue. - Use
/implement(no argument) to pick up next ready work viabd ready. - Use
/implement <description>to implement an ad-hoc task without a tracked issue.
Folded triggers (ag-s43tg wave 1): pr-implement routes here
- `pr-implement` → OSS contribution mode. Use when you need to implement a scoped OSS PR —
fork-based implementation of an open source contribution with mandatory isolation checks. Same single-issue TDD discipline as internal work, plus the fork lane: ensure the fork exists and is current, create an isolated worktree, run an isolation pre-check (BLOCK on mixed concerns) and post-check (BLOCK on scope creep), check for competing PRs before starting, and hand off to /pr-prep for commit/PR shaping. Input is the plan artifact from /pr-prep + /plan (run those first if no plan exists).
Examples
Implement Specific Issue
User says: /implement ag-5k2
What happens: 1. Agent reads issue from beads: "Add JWT token validation middleware" 2. Explore agent finds relevant auth code and middleware patterns 3. Agent edits middleware/auth.go to add token validation 4. Runs go test ./middleware/... — all tests pass 5. Commits with message "Add JWT token validation middleware\n\nImplements: ag-5k2" 6. Closes issue via bd close ag-5k2 --reason "commit:<sha> files:[middleware/auth.go]"
Result: Issue implemented, verified, committed, and closed. Ratchet recorded.
Pick Up Next Available Work
User says: /implement
What happens: 1. Agent runs bd ready — finds ag-3b7 (first unblocked issue) 2. Claims issue via bd update ag-3b7 --status in_progress 3. Implements and verifies 4. Closes issue
Result: Autonomous work pickup and completion from ready queue.
GREEN Mode (Test-First)
User says: /implement ag-8h3 (invoked by /crank --test-first)
What happens: 1. Agent receives failing tests (immutable) and contract 2. Reads tests to understand expected behavior 3. Implements ONLY enough to make tests pass 4. Does NOT modify test files 5. Verification: all tests pass with fresh output
Result: Minimal implementation driven by tests, no over-engineering.
Lifecycle Integration Flags
| Flag | Default | Description |
|---|---|---|
--no-lifecycle | off | Skip ALL lifecycle skill auto-invocations (test gen, review, refactor) |
--lifecycle=<tier> | matches complexity | Controls which lifecycle skills fire: minimal (test only), standard (+review), full (+refactor dry-run) |
Lifecycle tier defaults to matching the current complexity level. Explicit --lifecycle=<tier> overrides.
Execution
Read references/workflow.md when you need the full step-by-step procedure (Steps 0 through 8, including pre-flight gates, TDD discipline, build/security verification, the binary-deployment gate, the verification iron law, commit, close, and ratchet record).
GREEN mode rules live in references/green-mode.md. The pre-commit autonomous quality loop lives in references/quality-loop.md. The behavioral spec format lives in references/behavioral-spec.md.
Key Rules
- TDD by default - write failing tests before implementing (skip with
--no-tdd) - Lifecycle skills fire automatically - /test, /review, /refactor run at appropriate steps (disable with
--no-lifecycle) - Explore first - understand before changing
- Edit, don't rewrite - prefer Edit tool over Write tool
- Follow patterns - match existing code style
- Verify changes - run tests or sanity checks
- Commit with context - reference the issue ID
- Close the issue - update status when done
Without Beads
If bd CLI not available: 1. Skip the claim/close status updates 2. Use the description as the task 3. Still commit with descriptive message 4. Report completion to user
Output Specification
Per the output_contract in frontmatter: code changes, test results, bead status update, and behavioral spec (optional).
Completion Markers
<promise>DONE</promise>If blocked or incomplete:
<promise>BLOCKED</promise>
Reason: <why blocked><promise>PARTIAL</promise>
Remaining: <what's left>Troubleshooting
| Problem | Cause | Solution |
|---|---|---|
| Issue not found | Issue ID doesn't exist or local state looks stale | Run bd show <id> to verify; use bd vc status only if you need Dolt state |
| GREEN mode violation | Edited a file not related to the issue scope | Revert unrelated changes. GREEN mode restricts edits to files relevant to the issue |
| Verification gate fails | Tests fail or build breaks after implementation | Read the verification output, fix the specific failures, re-run verification |
| "BLOCKED" status | Contract contradicts tests or is incomplete in GREEN mode | Write BLOCKED with specific reason, do NOT modify tests |
| Fresh verification missing | Agent claims success without running verification command | MUST run verification command fresh with full output before claiming completion |
| Ratchet record failed | ao CLI unavailable or chain.jsonl corrupted | Implementation still closes via bd, but ratchet chain needs manual repair |
Reference Documents
- references/behavioral-spec.md — Behavioral spec format for Stage 4 validation
- references/binary-deployment-gate.md — CLI/hook binary-deployment gate spec
- references/gate-checks.md — Ratchet and pre-mortem gate checks
- references/green-mode.md — GREEN mode test-first implementation rules
- references/implement.feature — Executable spec: the /implement done-state (first-failing-test → green → refactor → verified close) (soc-qk4b.2)
- references/quality-loop.md — Pre-commit autonomous quality loop
- references/resume-protocol.md — Resume protocol for interrupted sessions
- references/workflow.md — Full execution workflow (Steps 0 through 8)
See also
- test — Test generation, coverage analysis, and TDD workflow
Generate Behavioral Spec (Optional)
Skip if: --no-spec flag, or issue type is docs/chore/ci.
After verification passes, produce a behavioral spec documenting what the implementation does. This feeds Stage 4 behavioral validation (STEP 1.8 in /validate).
mkdir -p .agents/specs
cat > .agents/specs/<issue-id>.json <<'SPEC'
{
"id": "auto-<issue-id>",
"version": 1,
"date": "<YYYY-MM-DD>",
"goal": "<one-line: what user outcome this implementation serves>",
"narrative": "<2-3 sentences: what the implementation does and how a user interacts with it>",
"expected_outcome": "<what a satisfied user observes when this works correctly>",
"acceptance_vectors": [
{
"dimension": "<name: correctness|performance|usability|security|...>",
"threshold": <0.0-1.0>,
"check": "<optional: mechanical check command>"
}
],
"satisfaction_threshold": 0.7,
"scope": {
"files": ["<list of modified files>"],
"functions": ["<key functions added/modified>"],
"behaviors": ["<behavioral descriptions>"]
},
"source": "agent",
"status": "active"
}
SPECGuidelines:
acceptance_vectorsshould capture the BEHAVIORAL contract, not test assertions.
Example: {"dimension": "isolation", "threshold": 1.0, "check": "echo ... | bash hook; test $? -eq 2"}
- Include at least 2 acceptance vectors (correctness + one other dimension).
scope.filesmust match the files you actually modified (not planned files).- The spec is validated by the evaluator council during STEP 1.8 — it is NOT
visible to YOU during implementation (holdout isolation applies to agent-built specs the same way it applies to human-written scenarios).
If skipped: Log "Behavioral spec skipped (reason: <flag|issue-type>)" and proceed.
Binary-Deployment Gate (CLI/Hook Bug Fixes)
Purpose: Block declaring "done" on any CLI or runtime-hook bug fix until the deployed runtime matches the source fix. The user invokes the deployed binary and the cached hook — those are the actual surfaces under test, not the source tree.
Why this gate exists: A fix shipped to source while the deployed runtime is pre-fix keeps reproducing the bug during its own post-mortem. The post-mortem of the close-loop dedup fix on 2026-05-01 hit exactly this: source-level tests passed, the issue was closed, but ~/go/bin/ao was still the pre-fix binary, so duplicates kept generating during the post-mortem itself.
Sources:
- Council finding:
.agents/council/2026-05-01-evolution-cycle-council.md, finding 1, action item A (6/6 judges concurred this is the highest-priority follow-up). - Captured failure mode:
.agents/learnings/2026-05-01-fix-shipped-binary-stale.md.
Trigger
The gate fires when the diff touches CLI binaries or runtime hooks:
CHANGED=$(
git diff --name-only HEAD~1 2>/dev/null
git diff --name-only --cached 2>/dev/null
git diff --name-only 2>/dev/null
)
TRIGGERS=$(printf '%s\n' "$CHANGED" | grep -E '^(cli/cmd/|hooks/|cli/embedded/hooks/)' | sort -u)
if [ -z "$TRIGGERS" ]; then
echo "Binary-deployment gate: no CLI/hook surfaces touched — skip"
exit 0
fi
echo "Binary-deployment gate FIRES on:"
printf ' %s\n' $TRIGGERSIf $TRIGGERS is empty, skip the gate. Otherwise, both checks below MUST pass before Step 5a.
Check A: Deployed binary mtime ≥ source-fix commit timestamp
For each binary under cli/cmd/<bin>/ touched by the diff (typically just ao):
BIN=ao # substitute the binary you fixed
DEPLOYED=$(command -v "$BIN" 2>/dev/null)
if [ -z "$DEPLOYED" ]; then
echo "BLOCK: $BIN not on PATH — fix is unreachable from a fresh shell"
echo " REMEDIATION: install the binary (cd cli && make install) or add to PATH"
exit 1
fi
# Deployed mtime — Linux first, macOS fallback
DEPLOYED_MTIME=$(stat -c %Y "$DEPLOYED" 2>/dev/null || stat -f %m "$DEPLOYED")
# Source-fix commit timestamp — last commit touching the cmd dir
SOURCE_MTIME=$(git log -1 --format=%ct -- "cli/cmd/$BIN/")
if [ "$DEPLOYED_MTIME" -lt "$SOURCE_MTIME" ]; then
echo "BLOCK: deployed $BIN at $DEPLOYED is older than the fix commit"
echo " deployed: $(date -d @$DEPLOYED_MTIME 2>/dev/null || date -r $DEPLOYED_MTIME)"
echo " source: $(date -d @$SOURCE_MTIME 2>/dev/null || date -r $SOURCE_MTIME)"
echo " REMEDIATION: cd cli && make build && make install (or your repo's deploy step)"
exit 1
fi
echo "Check A PASS: deployed $BIN ($DEPLOYED_MTIME) >= source ($SOURCE_MTIME)"Why mtime, not hash: the deployed binary is built by the user's local toolchain at install time, so a hash comparison against any source artifact is meaningless. Mtime ≥ source-commit-timestamp is the cheapest sufficient condition: it proves the deploy ran after the fix landed.
Caveat: git log --format=%ct reports the commit timestamp of the most recent commit touching the directory. If you re-built the binary before committing the fix, deployed mtime will be older than the commit. Ship the fix as a commit FIRST, then rebuild and redeploy, then run this check.
Check B: Plugin-cache hook copies reflect the fix
For any change under hooks/ or cli/embedded/hooks/, the user's runtime reads from a plugin cache (~/.claude/plugins/cache/... for Claude Code, ~/.codex/plugins/cache/... for Codex). If a stale copy is in the cache, the source fix never reaches the user.
Substitute the marker string introduced by your fix — a unique constant, env var, or substring that appears ONLY in the post-fix file. For the close-loop fix, the marker was AGENTOPS_STARTUP_CLOSE_LOOP.
MARKER="AGENTOPS_STARTUP_CLOSE_LOOP" # substitute your unique marker
HOOK_FILENAME="session-start.sh" # substitute the hook you edited
STALE=$(
find ~/.claude/plugins/cache ~/.codex/plugins/cache \
-name "$HOOK_FILENAME" \
-path '*agentops*' \
-exec grep -L "$MARKER" {} \; 2>/dev/null
)
if [ -n "$STALE" ]; then
echo "BLOCK: plugin-cache hook copies are pre-fix:"
printf ' %s\n' $STALE
echo " REMEDIATION 1 (preferred): reinstall the agentops plugin —"
echo " bash <(curl -fsSL https://raw.githubusercontent.com/boshu2/agentops/main/scripts/install.sh)"
echo " REMEDIATION 2: delete the stale cache files and let the harness re-fetch."
exit 1
fi
echo "Check B PASS: no stale plugin-cache copies of $HOOK_FILENAME"Picking a marker: prefer something that already exists in the diff. The closer the marker is to the actual fix (an env var name, a new function, a unique string literal), the more meaningful the check. Avoid markers that only appear in comments — comments are easy to copy across stale and fresh files.
No-op case: if the find command produces no results because the user has no plugin cache (e.g., a CI runner), the check passes vacuously. That's fine — the gate is most useful on developer machines where stale caches accumulate.
Pass criteria
The gate passes when EITHER:
- Trigger is empty (the diff touched no CLI/hook surfaces), OR
- Both Check A and Check B pass.
Only then may you proceed to Step 5a (Verification Gate).
Failure recovery
If Check A fails: rebuild & redeploy. Typical commands:
cd cli && make build && make install # repo-canonical build/deploy
# OR for go users:
go install ./cli/cmd/aoRe-run Check A. Repeat until pass.
If Check B fails: reinstall the plugin or delete stale cache copies. Re-run Check B. Repeat until pass.
Do NOT close the issue or declare "done" until both checks pass. The whole point of the gate is that source-level test pass is necessary but not sufficient for a deployed-runtime bug.
Why this is a block, not a warning
A passing source-level test suite proves the source is correct. It does NOT prove the deployed runtime — the actual surface the user invokes — got the fix. The 2026-05-01 close-loop incident demonstrated the failure mode in vivo: the post-mortem itself reproduced the bug because the binary it ran was pre-fix. A warning would not have stopped that. A block does.
Gate Checks
Extracted from implement SKILL.md Steps 0a-0b. Ratchet gate checks and pre-mortem validation prerequisites.
Ratchet Status Check (RPI Workflow)
Before implementation, verify prior workflow gates passed:
# Check if ao CLI is available
if command -v ao &>/dev/null; then
# Check if research and plan phases completed
RATCHET_STATUS=$(ao ratchet status --json 2>/dev/null || echo '{}')
RESEARCH_DONE=$(echo "$RATCHET_STATUS" | jq -r '.research.completed // false')
PLAN_DONE=$(echo "$RATCHET_STATUS" | jq -r '.plan.completed // false')
if [ "$RESEARCH_DONE" = "true" ] && [ "$PLAN_DONE" = "true" ]; then
echo "Ratchet: Prior gates passed (research + plan complete)"
elif [ "$RESEARCH_DONE" = "false" ] || [ "$PLAN_DONE" = "false" ]; then
echo "WARNING: Prior gates not complete. Run /research and /plan first."
echo " Research: $RESEARCH_DONE"
echo " Plan: $PLAN_DONE"
echo ""
echo "Override with: ao ratchet skip <gate> --reason 'manual override'"
fi
# Get current spec path for reference
SPEC_PATH=$(ao ratchet spec 2>/dev/null || echo "")
if [ -n "$SPEC_PATH" ]; then
echo "Ratchet: Current spec at $SPEC_PATH"
fi
else
echo "Ratchet: ao CLI not available - skipping gate check"
fiFallback: If ao is not available, proceed without ratchet checks. The skill continues normally.
Pre-Flight Pre-Mortem Gate
Before starting implementation, check if pre-mortem validation was run on the plan:
if command -v ao &>/dev/null; then
RATCHET_JSON=$(ao ratchet status --json 2>/dev/null || echo '{}')
PRE_MORTEM_STATUS=$(echo "$RATCHET_JSON" | jq -r '.steps[]? | select(.name == "pre-mortem") | .status // "none"')
PLAN_EXISTS=$(ls .agents/plans/*.md 2>/dev/null | head -1)
if [ "$PRE_MORTEM_STATUS" = "pending" ] && [ -n "$PLAN_EXISTS" ]; then
echo "Pre-mortem hasn't been run on your plan."
echo "Options:"
echo " 1. Run /pre-mortem first"
echo " 2. Skip: ao ratchet skip pre-mortem --reason 'user chose to skip'"
echo " 3. Proceed anyway"
# Ask user: "Pre-mortem hasn't been run on your plan. Run /pre-mortem first, skip, or proceed?"
# If skip: ao ratchet skip pre-mortem --reason "user chose to skip"
fi
# If ao unavailable or no chain: proceed silently
fiFallback: If ao is not available or no ratchet chain exists, proceed silently.
Behavioral Spec Completeness (Advisory — Pre-Commit)
When: After Step 5b quality loop passes, before Step 6 commit. Severity: WARN (advisory, not blocking). Blocking in --quality mode.
Check if the implementing agent generated a behavioral spec in Step 5c:
ISSUE_ID="${ISSUE_ID:-unknown}"
SPEC_FILE=".agents/specs/${ISSUE_ID}.json"
if [ -f "$SPEC_FILE" ]; then
# Validate spec structure
python3 -c "
import json, sys
with open('$SPEC_FILE') as f:
spec = json.load(f)
assert 'id' in spec, 'Missing id'
assert spec['id'].startswith('auto-'), 'Agent spec id must start with auto-'
assert 'acceptance_vectors' in spec, 'Missing acceptance_vectors'
assert len(spec['acceptance_vectors']) >= 2, 'Need at least 2 acceptance vectors'
for v in spec['acceptance_vectors']:
assert 'dimension' in v and 'threshold' in v, 'Vector missing dimension or threshold'
print('Spec gate: PASS')
" 2>&1 || echo "WARN: Spec validation failed — review .agents/specs/${ISSUE_ID}.json"
else
echo "WARN: No behavioral spec generated at ${SPEC_FILE}"
echo " Step 5c was skipped or spec not written."
echo " This is advisory — commit proceeds without spec."
fiSkip conditions: --no-spec flag, issue type is docs/chore/ci.
GREEN Mode (Test-First Implementation)
When invoked by /crank with --test-first, the worker receives:
- Failing tests (immutable — DO NOT modify)
- Contract (contract-{issue-id}.md)
- Issue description
GREEN Mode Rules:
1. Read failing tests FIRST — understand what must pass 2. Read contract — understand invariants and failure modes 3. Implement ONLY enough to make all tests pass 4. Do NOT modify test files — tests are immutable in GREEN mode 5. Do NOT add features beyond what tests require 6. Diff check (mechanical): After implementation, verify no test files were modified:
MODIFIED_TESTS=$(git diff --name-only -- '*_test.go' '*_test.py' '*.test.ts' '*.test.js' '*.spec.ts' '*.spec.js')
if [ -n "$MODIFIED_TESTS" ]; then
echo "BLOCK: GREEN mode violation: test file modified: $MODIFIED_TESTS"
# Revert test changes and re-implement without modifying tests
fiOpt-out: --allow-test-modification flag (for cases where test fixtures need updating) 7. BLOCKED if spec error — if contract contradicts tests or is incomplete, write BLOCKED with reason
Verification (GREEN Mode): 1. Run test suite → ALL tests must PASS 2. Standard Iron Law (Step 5a) still applies — fresh verification evidence required 3. No untested code — every line must be reachable by a test
Test Immutability Enforcement:
- Workers may ADD new test files but MUST NOT modify existing test files provided by the TEST WAVE
- If a test appears wrong, write BLOCKED with the specific test and reason — do NOT fix it
# Executable spec for the /implement skill — the loop's slice executor (BC3 Loop).
# /implement takes ONE tracked issue (a bounded slice carrying domain intent) and
# produces verified git-changes via TDD: a first failing test, then the minimal
# change to green, then refactor — never claiming done without a passing build.
# Hexagon: driving-adapter; consumes: domain; produces: git-changes. (soc-qk4b.2)
Feature: Implement one tracked issue via TDD
As the loop's slice executor
I want each issue implemented test-first with a verified build before close
So that every slice ships as evidence-backed git-changes, never status text
Background:
Given a single tracked issue with a bounded scope and stated acceptance
And a clean worktree at the slice's base SHA
Scenario: First failing test precedes implementation
When /implement starts the slice
Then it writes or identifies a failing test for the acceptance first
And no implementation code is written before that test fails
Scenario: Minimal change to green, then refactor
Given a first failing test
When /implement makes the change
Then the test passes with the smallest sufficient change
And any refactor happens only after green, with the test still passing
Scenario: Verification iron law gates close
When /implement believes the slice is done
Then build, tests, and lint pass (go build/vet/test or the per-language equivalent)
And the issue closes only after verification passes — never from status text alone
Scenario: Output is verified git-changes with closure evidence
Then /implement produces committed git-changes (produces: git-changes)
And it records ratchet / closure evidence against the issue
Autonomous Quality Loop (Pre-Commit)
Before committing, run a fix-verify loop on all files modified in this session (max 3 iterations):
Iteration N:
1. List modified files: git diff --name-only HEAD 2. Read each modified file completely — do not skim 3. Check for defects:
- Wrong variable references (copy-paste errors, stale names)
- Silent error swallowing (
_ = error empty catch blocks) - Hardcoded values that should be configurable or constants
- Missing edge cases identified during implementation
- Inconsistencies with existing patterns in the codebase
- Unused imports or variables
- Complexity budget violations (function cyclomatic complexity >15)
4. Lifecycle review (once per loop, first iteration only): If --no-lifecycle is NOT set AND lifecycle tier is standard or full AND staged changes exist:
Skill(skill="review", args="--diff --staged --quick")Merge review findings into the defect list. CRITICAL → HIGH, WARNING → MEDIUM, NIT → LOW. This runs EXACTLY ONCE (first iteration only) — do NOT re-run review after fixes. Skip if: --no-lifecycle flag, lifecycle tier is minimal or fast, no staged changes.
4a. Complexity-triggered refactor check (once per loop, first iteration only): If --no-lifecycle is NOT set AND lifecycle tier is full AND any modified function has cyclomatic complexity > 15:
Skill(skill="refactor", args="<high-cc-function> --dry-run")Treat refactor suggestions as MEDIUM findings. Do NOT auto-apply — report only. Skip if: --no-lifecycle flag, lifecycle tier is not full, no function exceeds CC > 15.
5. Report findings as a numbered list with severity (HIGH/MEDIUM/LOW) 6. HIGH findings: Fix immediately, re-run tests, re-sweep (next iteration)
- If a fix causes test regression: revert the fix, report as unresolvable, proceed
7. MEDIUM/LOW findings: Report in commit message, proceed
Loop termination:
- 0 HIGH findings → exit loop, proceed to Step 6
- 3 iterations exhausted with HIGH findings remaining → BLOCK commit. Report remaining HIGHs and stop. Do NOT proceed to Step 6.
- Override:
--force-commitallows proceeding with documented HIGHs (explicit opt-in only)
Output: Record iteration count, findings per iteration, and remaining items.
If no modified files or sweep finds zero issues on first pass, proceed directly to Step 5c.
Resume Protocol
Extracted from implement SKILL.md Step 0. Handles session continuation and checkpoint detection.
Check Issue State (Resume Logic)
Before starting implementation, check if resuming:
1. Check if issue is in_progress:
bd show <issue-id> --json 2>/dev/null | jq -r '.status'2. If status = in_progress AND assigned to you:
- Look for checkpoint in issue notes:
bd show <id> --json | jq -r '.notes' - Resume from last checkpoint step
- Announce: "Resuming issue from Step N"
3. If status = in_progress AND assigned to another agent:
- Report: "Issue claimed by <agent> - use
bd update <id> --assignee self --forceto override" - Do NOT proceed without explicit override
4. Store checkpoints after each major step:
bd update <issue-id> --append-notes "CHECKPOINT: Step N completed at $(date -Iseconds)" 2>/dev/nullImplement Workflow — Full 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
# Pull knowledge scoped to this issue (if ao available)
ao lookup --bead <issue-id> --limit 3 2>/dev/null || trueApply retrieved knowledge (mandatory when results returned):
If learnings or patterns are returned, do NOT just load them as passive context. For each returned item: 1. Check: does this learning apply to the current issue? (answer yes/no) 2. If yes: treat it as an implementation constraint — does it warn about an approach? suggest a pattern? flag a known pitfall? 3. Reference applicable learnings in your implementation decisions (e.g., "per learning X, avoiding approach Y") 4. Cite applicable learnings by filename in commit messages or PR descriptions
After reviewing, record each citation with the correct type:
# Only use "applied" when the learning actually influenced your output.
# Use "retrieved" for items that were loaded but not referenced in your work.
ao metrics cite "<learning-path>" --type applied 2>/dev/null || true # influenced a decision
ao metrics cite "<learning-path>" --type retrieved 2>/dev/null || true # loaded but not usedSection 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/nullIf plain description provided: Use that as the task description.
If no argument: Check for ready work:
bd ready 2>/dev/null | head -3Step 2: Claim the Issue
bd update <issue-id> --status in_progress 2>/dev/nullStep 2a: Build Context Briefing
if command -v ao &>/dev/null; then
ao context assemble --task='<issue title and description>'
fiThis 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 2b: Apply Behavioral Discipline
Before exploring or editing, load the behavioral discipline standard from /standards and write a short execution frame for yourself:
Assumptions:what is known, what is ambiguous, and which unknowns would change the solutionSmallest change:the minimum patch that could satisfy the requestBlast radius:which files or surfaces are in scope, plus what is explicitly out of scopeVerification:the tests, commands, or gates that will prove the work is done
Rules:
- If ambiguity would materially change the implementation, ask before editing instead of silently choosing.
- If a simpler approach exists than the heavier path implied by the prompt, say so and prefer it.
- If you notice unrelated cleanup, create a bead or note it separately; do not fold it into the patch.
- Every changed line should trace back to the request or to cleanup that your change made necessary.
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 concernsStep 3.5: Grep for Existing Utilities
Before implementing any new function or utility, grep the codebase for existing implementations:
# Search for the function name pattern you're about to create
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:
1. Write tests covering: happy path, one error path, one edge case 2. Run tests to confirm they FAIL (RED confirmation)
- If tests pass → feature already exists or tests are wrong. Investigate before proceeding.
3. Proceed to Step 4 with failing tests as the implementation target
# Run tests - ALL new tests must FAIL
# Python: pytest tests/test_<feature>.py -v
# Go: go test ./path/to/... -run TestNew
# Node: npm test -- --grep "new feature"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-tddflag is set, GREEN mode is active, or issue type ischore,docs, orci
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, orci --no-tddflag 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): 1. Read all provided test files FIRST 2. Read the contract for invariants 3. Implement to make tests pass (do NOT modify test files) 4. Skip to Step 5 verification
Based on the context gathered:
1. Edit existing files using the Edit tool (preferred) 2. Write new files only if necessary using the Write tool 3. Follow existing patterns in the codebase 4. 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:
# Detect CLI repo
if [ -f go.mod ] && ls cmd/*/main.go &>/dev/null; then
echo "CLI repo detected — running build verification..."
# Build
go build ./cmd/... 2>&1
if [ $? -ne 0 ]; then
echo "BUILD FAILED — fix compilation errors before proceeding"
# Do NOT proceed to Step 5
fi
# Vet
go vet ./cmd/... 2>&1
# Smoke test: run the binary with --help
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
fiIf 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):
- [ ] All existing tests pass (no new failures introduced)
- [ ] New code compiles/parses without errors
- [ ] No new linter warnings (if linter available)
- [ ] Change achieves the stated goal
Check for test files and run them:
# Find tests
ls *test* tests/ test/ __tests__/ 2>/dev/null | head -5
# Run tests (adapt to project type)
# Python: pytest
# Go: go test ./...
# Node: npm test
# Rust: cargo testIf tests exist: All tests must pass. Any failure = verification failed.
If no tests exist: Manual verification required:
- [ ] Syntax check passes (file compiles/parses)
- [ ] Imports resolve correctly
- [ ] Can reproduce expected behavior manually
- [ ] Edge cases identified during implementation are handled
If verification fails: Do NOT proceed to Step 5a. Fix the issue first.
Step 5.5: Binary-Deployment Gate (CLI/Hook Bug Fixes) — MANDATORY
For the full gate spec (rationale, mtime check, plugin-cache check, remediation), read `skills/implement/references/binary-deployment-gate.md`.
This gate BLOCKS declaring "done" when the diff touches CLI/hook surfaces. It is not a warning. Council finding (.agents/council/2026-05-01-evolution-cycle-council.md, finding 1, action item A; 6/6 judges): a fix shipped to source while the deployed runtime is pre-fix keeps reproducing the bug during its own post-mortem. Captured failure mode: .agents/learnings/2026-05-01-fix-shipped-binary-stale.md.
Trigger — gate fires if the diff touches cli/cmd/**, hooks/**, or cli/embedded/hooks/**:
CHANGED=$(git diff --name-only HEAD~1 2>/dev/null; git diff --name-only --cached; git diff --name-only)
TRIGGERS=$(printf '%s\n' "$CHANGED" | grep -E '^(cli/cmd/|hooks/|cli/embedded/hooks/)' | sort -u)
[ -z "$TRIGGERS" ] && echo "Binary-deployment gate: no CLI/hook surfaces touched, skipping" || echo "Binary-deployment gate FIRES on: $TRIGGERS"When fired, both checks below MUST pass before Step 5a.
Check A — deployed binary mtime ≥ source-fix commit timestamp (per binary under cli/cmd/<bin>/):
BIN=<binary-name> # e.g., ao
DEPLOYED=$(command -v "$BIN") || { echo "BLOCK: $BIN not on PATH"; exit 1; }
DEPLOYED_MTIME=$(stat -c %Y "$DEPLOYED" 2>/dev/null || stat -f %m "$DEPLOYED") # Linux | macOS
SOURCE_MTIME=$(git log -1 --format=%ct -- "cli/cmd/$BIN/")
[ "$DEPLOYED_MTIME" -lt "$SOURCE_MTIME" ] && { echo "BLOCK: deployed $BIN is pre-fix — rebuild & redeploy"; exit 1; }Check B — plugin-cache hook copies reflect the fix (for any hooks/ or cli/embedded/hooks/ change, substitute the marker string introduced by the fix, e.g., AGENTOPS_STARTUP_CLOSE_LOOP):
STALE=$(find ~/.claude/plugins/cache ~/.codex/plugins/cache \
-name '<hook-name>.sh' -path '*agentops*' \
-exec grep -L "<MARKER>" {} \; 2>/dev/null)
[ -n "$STALE" ] && { echo "BLOCK: stale plugin-cache hook copies: $STALE"; exit 1; }Pass criteria: both checks clean (or trigger is empty). Only then proceed to Step 5a. Failure modes, fallbacks, and remediation steps are in the references doc.
Step 5a: Verification Gate (MANDATORY)
THE IRON LAW: NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
Before reporting success, you MUST:
1. IDENTIFY - What command proves this claim works? 2. RUN - Execute the FULL command (fresh, not cached output) 3. READ - Check full output AND exit code 4. VERIFY - Does output actually confirm the claim? 5. ONLY THEN - Make the completion claim
Forbidden phrases without fresh verification evidence:
- "should work", "probably fixed", "seems to be working"
- "Great!", "Perfect!", "Done!" (without output proof)
- "I just ran it" (must run it AGAIN, fresh)
Rationalization Table
| Excuse | Reality |
|---|---|
| "Too simple to verify" | Simple code breaks. Verification takes 10 seconds. |
| "I just ran it" | Run it AGAIN. Fresh output only. |
| "Tests passed earlier" | Run them NOW. State changes. |
| "It's obvious it works" | Nothing is obvious. Evidence or silence. |
| "The edit looks correct" | Looking != working. Run the code. |
Store checkpoint:
bd update <issue-id> --append-notes "CHECKPOINT: Step 5a verification passed at $(date -Iseconds)" 2>/dev/nullGREEN Mode (Test-First Implementation)
For GREEN mode rules and verification details, read `skills/implement/references/green-mode.md`.
Step 5b: Autonomous Quality Loop (Pre-Commit)
For the full pre-commit fix-verify loop spec, read `skills/implement/references/quality-loop.md`.
Step 5c: Generate Behavioral Spec (Optional)
For the behavioral spec format and guidelines, read `skills/implement/references/behavioral-spec.md`.
Step 6: Commit the Change
If the change is complete and verified:
git add <modified-files>
git commit -m "<descriptive message>
Implements: <issue-id>"Step 7: Close the Issue with Evidence
Close with scoped evidence so the closure-integrity audit can resolve without parser_miss/timing_miss. The close reason must cite the commit and changed files from Step 6.
COMMIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
CHANGED_FILES=$(git diff --name-only HEAD~1 2>/dev/null | head -10 | tr '\n' ' ' | sed 's/ $//')
bd close <issue-id> --reason "commit:${COMMIT_SHA} files:[${CHANGED_FILES}]" 2>/dev/nullIf bd close is unavailable, fall back to bd update <issue-id> --status closed.
Step 7a: Record Implementation in Ratchet Chain
After successful issue closure, record in ratchet:
# Check if ao CLI is available
if command -v ao &>/dev/null; then
# Reuse commit evidence from Step 7
COMMIT_HASH=$(git rev-parse HEAD 2>/dev/null || echo "")
CHANGED_FILES=$(git diff --name-only HEAD~1 2>/dev/null | tr '\n' ',' | sed 's/,$//')
if [ -n "$COMMIT_HASH" ]; then
# Record successful implementation
# Determine TDD mode for ratchet tracking
# Values: red (wrote failing tests), green (GREEN mode from crank),
# skipped (skip conditions met), no-tdd (explicitly disabled)
TDD_MODE="red" # default when TDD was followed
# Override based on context:
# GREEN mode → "green", skip conditions → "skipped", --no-tdd → "no-tdd"
ao ratchet record implement \
--tdd-mode "$TDD_MODE" \
--output "$COMMIT_HASH" \
--files "$CHANGED_FILES" \
--issue "<issue-id>" \
2>&1 | tee -a .agents/flywheel.log
if [ $? -eq 0 ]; then
echo "Ratchet: Implementation recorded (commit: ${COMMIT_HASH:0:8})"
else
echo "Ratchet: Failed to record - chain.jsonl may need repair"
fi
else
echo "Ratchet: No commit found - skipping record"
fi
else
echo "Ratchet: ao CLI not available - implementation NOT recorded"
echo " Run manually: ao ratchet record implement --output <commit>"
fiOn failure/blocker: Record the blocker in ratchet:
if command -v ao &>/dev/null; then
ao ratchet record implement \
--status blocked \
--reason "<blocker description>" \
2>/dev/null
fiFallback: If ao is not available, the issue is still closed via bd but won't be tracked in the ratchet chain. The skill continues normally.
Step 7b: Post-Implementation Ratchet Record
After implementation is complete:
if command -v ao &>/dev/null; then
ao ratchet record implement --output "<issue-id>" 2>/dev/null || true
fiTell user: "Implementation complete. Run /validate to validate before pushing."
Step 8: Report to User
Tell the user: 1. What was changed (files modified) 2. How it was verified (with actual command output) 3. Issue status (closed) 4. Any follow-up needed 5. Ratchet status (implementation recorded or skipped)
Output completion marker:
<promise>DONE</promise>If blocked or incomplete:
<promise>BLOCKED</promise>
Reason: <why blocked><promise>PARTIAL</promise>
Remaining: <what's left>#!/usr/bin/env bash
set -euo pipefail
SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"
PASS=0; FAIL=0
check() { if bash -c "$2"; then echo "PASS: $1"; PASS=$((PASS + 1)); else echo "FAIL: $1"; FAIL=$((FAIL + 1)); fi; }
check "SKILL.md exists" "[ -f '$SKILL_DIR/SKILL.md' ]"
check "SKILL.md has YAML frontmatter" "head -1 '$SKILL_DIR/SKILL.md' | grep -q '^---$'"
check "SKILL.md has name: implement" "grep -q '^name: implement' '$SKILL_DIR/SKILL.md'"
check "references/ directory exists" "[ -d '$SKILL_DIR/references' ]"
check "references/ has at least 2 files" "[ \$(ls '$SKILL_DIR/references/' | wc -l) -ge 2 ]"
check "SKILL.md mentions bd for issue tracking" "grep -q 'bd ' '$SKILL_DIR/SKILL.md'"
check "SKILL.md mentions beads" "grep -qi 'beads' '$SKILL_DIR/SKILL.md'"
check "skill mentions /validate for closeout" "grep -rqs '/validate' '$SKILL_DIR/SKILL.md' '$SKILL_DIR/references/'"
check "SKILL.md mentions Explore agent" "grep -qi 'explore' '$SKILL_DIR/SKILL.md'"
check "SKILL.md mentions verification gate" "grep -qi 'verification\|verify' '$SKILL_DIR/SKILL.md'"
check "SKILL.md mentions ratchet record" "grep -q 'ratchet record' '$SKILL_DIR/SKILL.md'"
check "SKILL.md mentions GREEN mode" "grep -q 'GREEN' '$SKILL_DIR/SKILL.md'"
check "SKILL.md mentions DONE/BLOCKED/PARTIAL markers" "grep -q 'DONE\|BLOCKED\|PARTIAL' '$SKILL_DIR/SKILL.md'"
echo ""; echo "Results: $PASS passed, $FAIL failed"
[ $FAIL -eq 0 ] && exit 0 || exit 1
Related skills
FAQ
What does implement do?
Implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill".
When should I use implement?
Implement one tracked issue. Triggers: "implement", "implement one tracked issue.", "implement skill".
What are common prerequisites?
--- name: implement description: 'Implement one tracked issue.
Is Implement safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.