| name | implement |
| description | Use when shipping a new feature, endpoint, page, or significant change against a spec.md / plan.md (from /geniro:plan) OR a raw inline task description. 3-phase autonomous loop: Analyze → Implement → Self-review-and-Ship. Optional --deep deepens two phases — a multi-angle self-review with verification escalated only where the call is contested, and a 3× fact-check of the spec's cited claims before editing (higher quality, higher cost). |
| context | main |
| model | inherit |
| allowed-tools | ["Read","Write","Edit","Bash","Glob","Grep","Agent","AskUserQuestion","TodoWrite","EnterWorktree","ExitWorktree","Workflow"] |
| argument-hint | [task description | spec.md path | empty to resume | 'continue'] [--deep] |
Implement Skill — 3-Phase Autonomous Loop
You are an autonomous executor. You consume an externally-provided spec (or inline task description), make all required code edits, run the test suite, then run a parallel self-review pass before shipping. Strategic concerns belong upstream in /geniro:plan. A single orchestrator owns Phase 2 code-edits; an independent, self-contained slice may be delegated to a code-editing subagent per Phase 2 Step 3's delegation rule — coupled slices never are.
Runtime portability. ${CLAUDE_PLUGIN_ROOT} is set by Claude Code. When it is unset (another Agent-Skills runtime, e.g. Cursor), resolve it before following any reference: the plugin root is the ancestor directory of this file containing .claude-plugin/plugin.json — substitute it for every ${CLAUDE_PLUGIN_ROOT} occurrence and export it as CLAUDE_PLUGIN_ROOT in every Bash call. Tool and hook substitutions for non-Claude-Code runtimes: ${CLAUDE_PLUGIN_ROOT}/skills/_shared/runtime-portability.md.
Phases:
- Analyze (Phase 1) — Step 0 workspace setup AUQ (with auto-continue for in-worktree fix-up runs); semantic-parse
$ARGUMENTS; resolve spec source (spec.md / plan.md / DESIGN_DOC frontmatter OR inline-task fallback); refresh custom instructions + project snapshot; spawn knowledge-retrieval and codebase-explorer agents in parallel; query past learnings; persist review / debug / resolve handoffs to state.md; fact-check the spec against the current code before any edit (spec-driven mode only).
- Implement (Phase 2) — TodoWrite sequential decomposition (3-15 todos, one in_progress at a time); per-todo Edit/Write batch, with optional delegation of a genuinely independent slice to a code-editing subagent (Step 3 delegation rule); end-of-phase test-suite run via
test-runner-agent; bounded 3-retry fix loop on test failure → escalate-AUQ on exhaust.
- Self-review + Ship (Phase 3) — reviewer-agents in parallel (bugs / security / architecture / tests / code-quality) + 1 adversarial-tester-agent (skipped when codebase-explorer reports
change_scope: trivial OR when --no-adversarial modifier is present in $ARGUMENTS) + any custom dimensions discovered via ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-reviewers.md (.geniro/instructions/review-extra/<slug>.md, ≤10 cap, path-filtered); bounded 3-round fix loop, round N+1 = dims with actionable findings only (minor findings collect into a pre-ship disposition gate instead of forcing rounds); on clean exit, the minor-findings and test-quality gates, then ship sub-step (Pre-Ship Visual Verification if applicable, commit, ship-mode AUQ, learnings + snapshot writes, cleanup).
Reference material (templates, $ARGUMENTS-parse table, subagent spawn templates, fix-loop, ship sub-step): Read ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md AT each phase — load only the section that phase needs, so the reference's other phases don't crowd the working context.
State machine
State.md frontmatter phase: transitions (from-phase → to-phase | trigger):
| From | To | Trigger |
|---|
| (entry) | analyze | Phase 1 start |
| analyze | implement | spec parsed, handoffs resolved |
| analyze | (analyze) | surface failures inline; no separate escalation state |
| implement | self-review | Phase 2 todos done, tests green |
| implement | phase-2-escalated | test fix-loop exhausted / not converging |
| phase-2-escalated | debug-handoff | user picked "escalate to debug" (terminal) |
| phase-2-escalated | self-review | user picked "accept failures" |
| phase-2-escalated | aborted | user picked "abort" (terminal) |
| self-review | ship | happy path — review clean |
| self-review | self-review-only | "stop after review" modifier — exit before commit (terminal) |
| self-review | phase-3-escalated | review fix-loop exhausted / not converging |
| phase-3-escalated | debug-handoff | user picked "escalate to debug" (terminal) |
| phase-3-escalated | ship | user picked "accept findings" → ## Accepted Findings body block |
| phase-3-escalated | aborted | user picked "abort" (terminal) |
| ship | done | committed + pushed + PR (terminal) |
| ship | ship-committed-only | "don't push" / "no push" / "commit only" modifier (terminal) |
Each git push / gh pr create / posted comment appends to non-resumable-actions[] as it fires.
Terminal states: done, ship-committed-only, self-review-only, debug-handoff, aborted. Every transition into a terminal state runs the transient cleanup in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Cleanup" before the terminal phase: write — leftover transient files in a finished task-dir resurface as recurring migration warnings on every plugin update.
Non-terminal states: analyze, implement, self-review, ship.
Escalation (paused) states: phase-2-escalated, phase-3-escalated — a fix-loop exhausted and an AUQ is open. On resume the recovery re-surfaces "task was paused — last AUQ options" so the user re-picks without losing context (mirrors /geniro:debug's escalation states).
Termination reason convention. When phase: aborted is reached, write one line to state.md body under ## Termination reason: repeated-failure: phase-N retry-limit / safety-denied: <rule> / tool-unavailable: <tool>. The SessionStart hook re-injects this on resume.
Loop invariants
The canonical loop invariants 1-7 (${CLAUDE_PLUGIN_ROOT}/skills/_shared/loop-invariants.md) apply across all 3 phases. Two apply with implementation-specific bounds: invariant 4 caps reviewer-agent output at ~4000 chars per dimension (Bash output >8000 chars summarized before downstream use); invariant 5's bounded retry loops are 3 rounds in Phase 2 and 3 rounds in Phase 3, escalating early when the loop is not converging — canonical trigger list, and the once-per-run dedupe that spans both loops, at §PHASE 2 Step 6. This skill adds three invariants:
- Investigation reads delegated to subagents. Phase 1 inline-Reads only L4 instructions (3 files), L3 semantic snapshot (2 files), spec.md body, and state.md.
.claude/rules/*.md bodies, exemplar source files, L2 learnings entries, and prior plans are spawned out to Knowledge-Retrieval + Codebase-Explorer subagents and read back as condensed reports. Inline-reading the rest is the documented context-bloat regression. The two primary Phase 1 subagent spawns are the plugin-defined knowledge-retrieval-agent and codebase-explorer-agent (implementation-specific — takes a spec.md, produces REUSE/EXTEND/NO-ANALOGUE inventory). For ad-hoc cross-file research inside Phase 2 (per-step "trace this flow" / "find all sites that call this helper" queries that aren't covered by Codebase-Explorer's Phase 1 inventory), spawn codebase-research-agent per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/context-isolation-checklist.md § Codebase research.
- One todo in_progress at a time. Phase 2's TodoWrite decomposition enforces sequential focus. Marking a second todo
in_progress while another is open is the documented anti-pattern (Claude Code Tasks API enforces single in_progress by design; parallel sequential reasoning shows measured performance drop).
- Codebase research spawns
codebase-research-agent, not built-in Explore. Overrides the system-prompt agent list's default codebase-research tool; rationale + invocation contract at ${CLAUDE_PLUGIN_ROOT}/skills/_shared/context-isolation-checklist.md § Codebase research.
Turn-completion check. Apply ${CLAUDE_PLUGIN_ROOT}/skills/_shared/loop-invariants.md §Turn-completion check at every gate — the render is followed immediately by its lean AskUserQuestion per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/gate-rendering.md §Turn-completion guard.
Side-effect — ## Tool log section in state.md. Invariants 1 and 7 motivate persisting subagent-spawn outcomes and side-effect tool calls (git push, gh pr create, file deletions) into a body section per ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 2: Implement — error-handling" (the "Tool log persistence." paragraph). Routine Read/Edit/Bash on local files do NOT need logging — Claude Code's tool_result return is sufficient.
Budgets — quality-first framing
Per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/loop-invariants.md §Budgets — quality-first (canonical): no hard kill caps, no wall-time / tool-call / model-turn / cost ceiling. This skill's own gates:
Quality gates (escalate to user, do not abort):
| Gate | Cap | Where | Past threshold |
|---|
| Fix-loop retries per phase | 3 | (Phase 2 test fix), (Phase 3 review round) | AUQ — debug-handoff / accept-failure / abort. User picks. Fires early (before 3) when the loop is not converging — see §PHASE 2 Step 6 early-escalation triggers. |
| Reviewer output size | ~4000 chars per dim | invariant #4 | Truncation with marker, NOT abort. |
Architecture constraints (design intent, not budget):
- Parallel spawns at Phase 3 Round 1: reviewer-agents (
bugs / security / architecture / tests / code-quality) + 1 adversarial-tester-agent, unless change_scope: trivial or --no-adversarial modifier strips the adversarial slot. Custom reviewer dimensions from .geniro/instructions/review-extra/ append to the same batch (≤10 cap, path-filtered).
- Parallel spawns at Phase 1 Step 7: 2 subagents (
knowledge-retrieval-agent + codebase-explorer-agent).
State persistence
Task directory:
.geniro/planning/<task-slug>/
Where <task-slug> is derived from $ARGUMENTS / spec.md filename / git branch per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-naming.md. Created at start of Phase 1.
State.md frontmatter:
---
tier: T1.5
producer: implement
schema-version: 1
branch: <git-branch>
worktree: <git-rev-parse-show-toplevel>
timestamp: <ISO-8601 UTC>
phase: <state-machine-enum>
status: in-progress
non-resumable-actions: []
approvals: []
deep-mode: <true|false>
---
When deep-mode: true, Phase 1 (spec fact-check) and Phase 3 (self-review) run their deeper paths per ${CLAUDE_PLUGIN_ROOT}/skills/implement/deep-mode-reference.md. Activation follows ${CLAUDE_PLUGIN_ROOT}/skills/_shared/deep-mode.md §2 — the --deep flag pre-resolves it, else the Step 0 depth question asks, else (auto-continue / resume paths, where that question never fires) depth is flag-only. The resolved depth is persisted once, at Phase 1 Step 4.
Write contract. Route every state.md mutation through atomic_state_write — a direct Edit or Write on a canonical state path bypasses the helper and corrupts the file mid-crash; the State-helper enforcement hook hard-blocks such a direct write (exit 2). Invocation snippet: ${CLAUDE_PLUGIN_ROOT}/skills/_shared/atomic-state-write.md.
Validation before resume. When Phase 1 detects a pre-existing state.md (resume path), pre-flight via validate_state_file per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/validate-state-file.md; on failure, open the recovery AskUserQuestion (delete-and-restart / open-in-editor / update-worktree-path / skip-emergency).
Memory I/O
Phase 1 entry inventory
Phase 1 entry runs Step 0 first (workspace setup — see §PHASE 1 Step 0 below), then six helper calls — two L4/L3 reads, two subagent spawns (Knowledge-Retrieval + Codebase-Explorer), one L2 query, one cross-layer protocol:
- Step 0 workspace setup — passive context detection followed by 1-2 question AUQ (skipped on auto-continue path). Fires BEFORE any L4/L3/L2 helper call; workspace decision determines the worktree the rest of Phase 1 inspects.
- Load custom instructions —
load-custom-instructions with MODE: refresh; see §L4 below.
- Load the project snapshot —
load-semantic with MODE: refresh; see §L3 below.
- Knowledge-Retrieval subagent spawn — parallel with Codebase-Explorer; reads back from
<task-dir>/.kr-out.md. See §Phase 1 subagent spawn.
- Codebase-Explorer subagent spawn — parallel with Knowledge-Retrieval; reads back from
<task-dir>/.ce-out.md. See §Phase 1 subagent spawn.
- Query past learnings —
query-learnings; see "past learnings" sub-section below. Tags may be primed by the knowledge-retrieval agent's output.
- Cross-layer conflict resolution —
resolve-conflicts; see §Cross-layer conflict surfacing. Fires only if disagreement detected after the reads.
Phase 2 makes no new helper calls at entry; per-Edit .claude/rules/*.md JIT loads fire only when an Edit target matches a rule path returned by Codebase-Explorer (cache scope: Phase 2). Phase 3 entry re-fires load-custom-instructions(MODE: refresh) AND fires load-custom-reviewers once (round 1 only) per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-reviewers.md — spawn-specs are appended to the parallel reviewer batch alongside the 5 built-ins and the adversarial-tester. Phase 3 fix-loop iterations may re-fire query-learnings. Phase 3 ship sub-step adds writes: emit-learning (L2), update-semantic (L3 bounded append), and atomic_state_write (state.md frontmatter non-resumable-actions[]).
L4 — Custom instructions (procedural)
Apply ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-instructions.md with SKILL_SLUG: implement, LOAD_TIER: pipeline, MODE: refresh. The helper's §Procedure prescribes imperative Read directives on global.md, implement.md, and code-style.md (3 files); its §Echo contract requires one observable line per file. Both are mandatory.
Phase boundaries:
- Phase 1 entry —
MODE: refresh — scope = implement + global + code-style (3 files). refresh re-Reads every file and re-emits the Echo lines; the procedure is identical to initial-load. The mode name signals compaction-survival intent.
- Phase 3 entry —
MODE: refresh on every run, because the re-read survives any Phase 2 compaction. Cost: 1 extra helper read.
The Echo contract survives compaction via the SessionStart hook re-injection.
L3 — Semantic snapshot
source "${CLAUDE_PLUGIN_ROOT}/lib/load-semantic.sh"
load_semantic
load_semantic --extras "_FEATURES.md"
Phase 1 entry only. load_semantic has no MODE flag — every Read fires unconditionally, fingerprint drift check fires unconditionally. Drift notification surfaces to user if .fingerprint.json mismatched. Phase 3 does NOT re-load L3 (Phase 2 doesn't materially mutate L3 — update-semantic writes are bounded to single-line append on _CODEBASE_MAP.md).
L2 — Episodic event log
Route every L2 read below per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/query-learnings.md §"Memory backend override": when memory.md declares a ## Memory Backend block for learnings, query the declared read tool instead of the file helper — under mode: replace the local learnings.jsonl is never written, so the file query returns nothing and only the backend read recalls anything. Absent block → the file query is correct, unchanged.
Read (Phase 1 entry):
source "${CLAUDE_PLUGIN_ROOT}/lib/query-learnings.sh"
query_learnings --tag <inferred-tag> --scope <inferred-scope> --limit 5
Tags inferred from task description (e.g., react, auth, bug); skipped if task description is too generic. query-learnings has no MODE parameter — calls are idempotent.
Read (Phase 3 fix-loop):
query_learnings --tag <inferred-tag> --scope <changed-file-path> --limit 5
Used to prime reviewer-agent prompts with known conventions/pitfalls (same backend routing as the Phase 1 entry read above).
Write (Phase 3 ship sub-step, auto-emit):
source "${CLAUDE_PLUGIN_ROOT}/lib/emit-learning.sh"
echo '{"type":"convention","scope":"...","summary":"...","tags":[...],"trust":"verified"}' | emit_learning
Triggers:
type=convention → when Phase 3 architecture or code-quality reviewer reports ≥3 instances of same pattern.
type=decision → when spec.md records a non-trivial approach choice with ## Considered Alternatives (inline-task path; /geniro:plan emits decisions directly when it owns the upstream step).
Default trust = verified (Phase 3 findings are test-validated on entry).
Promotion suggestion fires ONLY for convention emits — see reference.md §"Extract Learnings". Echo Recorded learning: <summary> after a successful emit and fire it before the Ship-mode AUQ, per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/emit-learning.md §"Caller contract".
L3 — Bounded write (Phase 3 ship sub-step)
source "${CLAUDE_PLUGIN_ROOT}/lib/update-semantic.sh"
update_semantic --file codebase-map --append "- <path> — <short description>, used by <consumer>"
Fires when Phase 2 added a new module. Lock-guarded; rc=11 (lock held) is a recoverable skip-and-defer.
Cross-layer conflict surfacing
When L4/L3/L2 reads disagree, follow the protocol in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/resolve-conflicts.md:
- Soft conflict: print
emit_conflict_notice text, continue using precedence-winning value.
- Hard conflict (L4 rule contradicts L3 reality): halt, call
hard_conflict_block + AskUserQuestion to surface to user.
ACI per-phase tool surface
| Phase | Allowed | Blocked |
|---|
| Phase 1 (Analyze) — orchestrator | Read / Grep / Glob / Bash (git status, gh pr view, git worktree add, git checkout -b, and the Step 0 freshness commands git fetch / git merge / git rebase / git stash / git pull --ff-only per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-freshness.md); Agent spawns for knowledge-retrieval-agent + codebase-explorer-agent, plus the read-only spec-claim verifier spawns fired by the Step 12.5 spec-challenge gate per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/spec-challenge.md, plus one top-level general-purpose web-research spawn (WebSearch + WebFetch) for the library-candidate research in the Step 8.5 library-reuse audit (OMIT model=); Workflow (deep-mode: true only — the internal deep fan-out for the Phase 1 spec-check and Phase 3 self-review, OMIT model=) | Edit / Write on source code; gh pr create; commit; Phase 3 agent types |
| Phase 1 subagents | Per agent frontmatter tools: whitelist — see agents/knowledge-retrieval-agent.md and agents/codebase-explorer-agent.md | Edit / Write (except their own OUTPUT_PATH); Agent (leaf agents, no nesting) |
| Phase 2 (Implement) inner loop | Read / Grep / Glob / Edit / Write / Bash (incl. test runs); test-runner-agent spawn at end-of-phase; bounded code-delegate spawns (general-purpose, disjoint file sets) per §PHASE 2 Step 3 "Delegating a todo" | git push, gh pr create, gh pr comment, Phase 3 agent types |
| Phase 2 test-runner-agent | Bash (one test-suite invocation), Read, Grep — enforced by agents/test-runner-agent.md frontmatter | Edit / Write on source code; git mutation; destructive Bash; Agent (leaf agent) |
| Phase 3 reviewer-agent spawns | Per dim: Read / Grep / Glob / Bash (read-only) — enforced by agents/reviewer-agent.md frontmatter tools: whitelist | Edit / Write / Agent / mutating Bash / external network |
| Phase 3 adversarial-tester-agent spawn | Read / Write / Edit (restricted to test-file paths) / Bash (read-only) / Glob / Grep — enforced by agents/adversarial-tester-agent.md frontmatter tools: + Critical Constraints | Production-source edits; git mutation; destructive Bash; Agent (leaf agent) |
| Phase 3 Ship sub-step | git commit, git push, gh pr create — each gated by the push-grade doctrine at §Ship sub-step step 4; gh api thread reply + resolveReviewThread (resolve-handoff only — action-gated, after the push, per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/pr-threads.md write side) | External commits before AUQ resolution |
Existing safety layer: file-protection hook, git-guardrail hook, and .geniro/ deletion guard apply across ALL phases regardless of this matrix.
PHASE 1: ANALYZE
State.md phase: analyze on entry.
Resolve PRIMARY_ROOT once at Phase 1 entry. Run the Mode A snippet from ${CLAUDE_PLUGIN_ROOT}/skills/_shared/primary-worktree.md via Bash. Phase 1 reads handoffs at <PRIMARY_ROOT>/.geniro/state/handoff/from-*-<branch>.md, targeted-reads global.md for the branch-format rule at Step 0a from the resolved instructions base dir (the external override $GENIRO_INSTRUCTIONS_DIR / $CLAUDE_PLUGIN_OPTION_INSTRUCTIONS_DIR when set and a valid directory, else <PRIMARY_ROOT>/.geniro/instructions), and spawns knowledge-retrieval + codebase-explorer agents whose spawn-prompt slots (KNOWLEDGE_ROOT, PLANNING_ROOT, HANDOFF_DIR) require this value substituted to absolute paths per Mode B. Without it, the handoff probes / global.md read / subagent spawns silently fall back to cwd-relative paths and miss content in the primary worktree when /geniro:implement runs from a linked worktree.
Step 0 — Workspace setup
Step 0 fires BEFORE any L4 / L3 / L2 helper call and BEFORE the Knowledge-Retrieval / Codebase-Explorer spawn. Workspace decision determines the worktree the rest of Phase 1 inspects; running L3 fingerprint drift checks against the wrong worktree is wasted work.
Two sub-steps: passive detection (0a, no AUQ) → decide action (0b, auto-continue or AUQ).
0a — Detect current context (passive)
Collect these signals before deciding:
| Signal | How detected |
|---|
CURRENT_BRANCH | git branch --show-current |
CURRENT_TOPLEVEL | git rev-parse --show-toplevel |
IN_WORKTREE | CURRENT_TOPLEVEL is registered in git worktree list --porcelain AND is NOT the porcelain bare row or the main worktree row. Porcelain registry is the source of truth; the .claude/worktrees/<slug>/ path convention is a sanity check, NOT the primary signal. |
PROTECTED_BRANCH | CURRENT_BRANCH ∈ {main, master, develop, trunk} (per-project override via .geniro/safety.json) |
EXISTING_TASK_STATE | Glob .geniro/planning/*/state.md; any state.md whose frontmatter branch: equals CURRENT_BRANCH AND phase: is terminal ⇒ "prior task on this branch" |
REVIEW_HANDOFF | Path <PRIMARY_ROOT>/.geniro/state/handoff/from-review-<CURRENT_BRANCH>.md exists ⇒ "review just produced findings for this branch" |
DEBUG_HANDOFF | Path <PRIMARY_ROOT>/.geniro/state/handoff/from-debug-<CURRENT_BRANCH>.md exists ⇒ "debug just authored repro tests for this branch" |
RESOLVE_HANDOFF | Path <PRIMARY_ROOT>/.geniro/state/handoff/from-resolve-<CURRENT_BRANCH>.md exists ⇒ "PR-feedback triage just produced a fix plan for this branch". EXISTING_TASK_STATE does not cover it — that glob scans .geniro/planning/*/state.md, while /geniro:resolve keeps its state under .geniro/state/resolve/<slug>/. Without this signal the run falls through to the workspace question and can be steered onto a new branch, off the PR branch the fixes must land on. |
BRANCH_MATCHES_TASK_SLUG | Derived-from-spec slug (per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-naming.md) substring-matches CURRENT_BRANCH |
SPEC_WORKFLOW_REFS | If spec.md present at resolved task slug: parse workflow_refs: frontmatter list (per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/workflow-refs-schema.md). Empty list when field absent. |
SPEC_LAUNCH_CONFIG | If spec.md present at resolved task slug: parse the optional launch_config: frontmatter block (per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/launch-config-schema.md) — workspace / deep_mode / branch_freshness / ship_mode, plus the optional tracker_status (present only when the spec had a linked tracker ticket). Empty when the block is absent, on an inline-task run with no spec, or on a pre-m5-v4 spec that omits it. When present, it pre-answers the matching Step 0 setup questions per Step 0g below. |
BRANCH_FORMAT_RULE | Read global.md directly here at Step 0a from the resolved instructions base dir: when $GENIRO_INSTRUCTIONS_DIR (or $CLAUDE_PLUGIN_OPTION_INSTRUCTIONS_DIR) is set and is a directory, read <that-dir>/global.md (expand a leading ~ to $HOME); otherwise read <PRIMARY_ROOT>/.geniro/instructions/global.md. Extract any branch-format directive present (regex pattern, required components such as <type>/<ticket>-<desc>, ticket-prefix requirement). Empty when file absent or no branch rule documented. The custom-instructions loader at Step 5 will re-Read the same file with full echo contract; this Step 0a read is a targeted extraction so Step 0c knows the format constraint before authorizing branch creation. Without this signal, Step 0c authorizes branch names that violate project rules and the agent has to rename after the fact. |
TICKET_ID_IN_SCOPE | Set to the detected ticket ID when $ARGUMENTS contains a Linear URL / <TEAM>-<N> ID, OR spec.md frontmatter workflow_refs[] carries one, OR CURRENT_BRANCH already encodes one. Empty when none in scope. Cross-checked against BRANCH_FORMAT_RULE at Step 0c to decide whether the no-ticket-ID sub-flow fires. |
CONCURRENT_ACTIVITY | Set when another agent/session may be mutating this working tree: git worktree list --porcelain shows a peer worktree already on CURRENT_BRANCH, OR git status --porcelain at Step 0 entry shows changes this run did not author. Signals a contested shared working tree where in-place work risks an external reset/rename orphaning a commit. |
0b — Decide action
Decision tree (first match wins; evaluate top-down):
1. Resumable state.md exists for resolved task slug
AND state.md frontmatter phase: ∈ {analyze, implement, self-review, ship, phase-2-escalated, phase-3-escalated}
⇒ SKIP Step 0 entirely. Resume per state.md — a non-terminal phase rolls back to phase entry; an escalation (paused) phase re-surfaces its last AUQ options.
2. IN_WORKTREE == true
AND CURRENT_BRANCH ∈ continuing-work set:
• BRANCH_MATCHES_TASK_SLUG == true, OR
• REVIEW_HANDOFF == true, OR
• DEBUG_HANDOFF == true, OR
• RESOLVE_HANDOFF == true, OR
• EXISTING_TASK_STATE == true
⇒ AUTO-CONTINUE in current worktree. NO workspace AUQ. Echo the continue in plain English — translate the matched signal to its meaning, never surface the raw token (REVIEW_HANDOFF → "a review just produced findings for this branch"; DEBUG_HANDOFF → "a debug run just authored reproduction tests for this branch"; RESOLVE_HANDOFF → "a PR-feedback triage just produced a fix plan for this branch"; EXISTING_TASK_STATE → "a prior task on this branch"; slug match → "the branch name matches this task"):
"Continuing in worktree '<dir>' on '<branch>' — <plain-English reason>.
<when a review or resolve handoff matched:> Any open questions from it will be resolved before code changes."
Workflow Question 2 still asked if applicable (see 0c).
3. IN_WORKTREE == false
AND PROTECTED_BRANCH == false
AND any of {REVIEW_HANDOFF, DEBUG_HANDOFF, RESOLVE_HANDOFF, EXISTING_TASK_STATE} == true
⇒ When CONCURRENT_ACTIVITY is set, do NOT auto-continue in place — fire the full
workspace AUQ (0c) with the recommendation flipped to "Git worktree (Recommended)"
(an isolated worktree prevents a concurrent process from orphaning this run's commit
via an external reset/rename on the shared working tree). Otherwise AUTO-CONTINUE on
current branch, NO workspace AUQ. Echo (translate <signal> to the plain-English reason per rule 2's mapping — never the raw token):
"Continuing on '<branch>' — <plain-English reason>.
Reverse with: re-run with 'new-branch' modifier in arguments."
Workflow Question 2 still asked if applicable.
4. IN_WORKTREE == true
AND CURRENT_BRANCH ∉ continuing-work set
⇒ Fire 3-option AUQ (header: "Worktree mismatch"):
A) "Continue here in '<dir>'" — recommended if user explicitly cd'd here
B) "Exit to repo root and create new worktree '<new-slug>'" — call ExitWorktree, then standard new-worktree flow
C) "Abort — I'm in the wrong place" — terminal, no-op
Workflow Question 2 omitted (mismatch hint suggests confusion; don't pile on).
5. IN_WORKTREE == false, PROTECTED_BRANCH == true, no continuing signals
⇒ Fire the full workspace AUQ (0c). "New feature branch (Recommended)" stays default.
6. IN_WORKTREE == false, PROTECTED_BRANCH == false, no continuing signals
⇒ Fire the full workspace AUQ (0c). Recommendation flips: "Current branch (Recommended)" since the user is on a feature branch already — unless CONCURRENT_ACTIVITY is set, in which case the recommendation is "Git worktree (Recommended)" so a concurrent process mutating the shared working tree cannot orphan this run's work.
On any AUTO-CONTINUE path (rule 2, and rule 3 when it auto-continues — both skip the AUQ), apply Mode FRESH-CONTINUE in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-freshness.md right after the continue echo — offer to update a branch that is behind the default branch before Phase 1 begins. It skips silently when the branch is already current, and is skipped entirely on a compaction-resume (the branch was synced when the run first started).
Inline modifier overrides (parsed from $ARGUMENTS per the Phase 1 semantic-parse table; an explicit modifier wins over auto-detection, because the user's stated intent overrides an inferred signal):
| Modifier in $ARGUMENTS | Effect |
|---|
new-branch / new branch | Force rule 5 path even if a "continuing" signal is detected. |
current-branch / current branch | Force auto-continue regardless of signals. |
worktree / new-worktree | Force worktree creation path. |
no-worktree / here | Force in-place execution; skips worktree even if IN_WORKTREE == false. |
--no-adversarial | Disables Phase 3 adversarial-tester spawn for this run (skips the 6th slot in Round 1). |
--deep / deep | Sets deep-mode: true — the deeper Phase 1 + Phase 3 paths per ${CLAUDE_PLUGIN_ROOT}/skills/implement/deep-mode-reference.md. |
Conflicting modifiers (e.g., new-branch AND current-branch both present): last-occurrence wins (right-to-left scan). Emit soft notice: "Both 'new-branch' and 'current-branch' modifiers detected; using <last>."
The full cross-skill catalog of modifiers and the spec launch_config block (workspace / ship / depth / freshness / tracker_status) lives in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/flags-reference.md.
0c — AUQ structure
Read ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: Step 0 setup detail" before firing this AUQ — it carries the approvals[] entry shapes, the edge-case behaviors (0f), and the spec launch_config field map (0g); the literal question templates live in §"Phase 1: Step 0c AUQ templates".
Single AskUserQuestion call carrying up to 3 questions (always-WAIT, never auto-resolve). When a spec launch_config pre-answered a question (Step 0g), drop that question from the batch — the pre-set is its answer; if launch_config pre-answers every question that would otherwise fire, the AUQ does not fire at all.
Question 1 — always asked when rules 5 or 6 fire (header: "Git workspace") — offers "New feature branch (Recommended)" / "Current branch" / "Git worktree"; literal template in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: Step 0c AUQ templates".
No-ticket-ID sub-flow. When BRANCH_FORMAT_RULE requires a ticket prefix AND TICKET_ID_IN_SCOPE is empty, the agent cannot derive a conformant slug. Chain a sub-AUQ BEFORE Question 1 fires (or BEFORE the worktree command runs if Question 1 has already resolved to "New feature branch" / "Git worktree") — options: provide the ticket ID inline / use a placeholder slug (<type>/no-ticket-<desc>, renameable later) / cancel (terminal, no git mutation); literal template in the same reference section. This AUQ does NOT include a "create the ticket for me" option — /geniro:implement never creates tracker artifacts (see the anti-rationalization row covering tracker-mutation authority).
Question 2 — conditional on workflow_refs OR .geniro/workflow/*.md having an ### On task start section:
Merge sources for the workflow-refs-to-process list:
workflow_refs_to_process = []
if $ARGUMENTS contains tracker URL/ID → append to workflow_refs_to_process
for each ref in spec.md frontmatter workflow_refs[] → append to workflow_refs_to_process
deduplicate by (kind, issue_id) — $ARGUMENTS reference wins on conflict
For each entry, find the workflow file with primary-worktree fallback per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/primary-worktree.md Mode A — try ./.geniro/workflow/<ref.kind>.md (cwd-local; uncommitted local edits win) first; on file-not-found retry against <PRIMARY_ROOT>/.geniro/workflow/<ref.kind>.md. If both missing → log warning + skip (graceful degrade). Staleness check: if fetched_at is > 1 hour old OR absent → re-fetch via MCP (timeout 3s, fail-open) — the refresh ALSO updates the cached status field. Resolve the current status (re-fetched value, or cached when fresh) BEFORE applying the workflow block — the workflow file's ### On task start section gates its question shape on that field (e.g., the Linear template skips the "Move to In Progress?" prompt when status is already "In Progress", rephrases to "Move back?" when in non-terminal non-In-Progress states, and reframes as "Reopen?" when terminal). Apply the workflow file's ### On task start block — it may append 0-2 questions to the AUQ batch depending on resolved status and assignee fields. Echo any "skipped — already in target state" cases to the user inline (not as an AUQ).
The workflow file IS the source of truth for question text, options, AND status-conditional branching — do NOT hardcode "Linear" / "Jira" labels, and do NOT bypass the status check by firing the prompt unconditionally.
When the spec's launch_config.tracker_status is set (applied at Step 0g), it pre-answers this workflow-status question — /geniro:implement auto-applies the answer the workflow file's ### On task start block would have asked for, still subject to that block's status-conditional gate (a pre-set move-to-in-progress is skipped when the task is already In Progress and reframed/omitted in other states), so the question does not fire interactively. The pre-set is a no-op when no tracker ref is in scope, and fail-open when the workflow MCP is unavailable (logs a warning and proceeds without the transition — same as an interactive "Yes").
If the batch exceeds 4 questions — 1 (workspace, when rules 5/6 fire) + N (workflow) + 1 (depth, when --deep is absent) > 4 — chain into a second AUQ.
Question 3 — implement depth (fired when $ARGUMENTS lacks --deep) (header: "Implement depth") — "Standard" (one fact-check pass, one self-review pass) vs "Deep — 3× fact-check + multi-angle self-review"; literal template in §"Phase 1: Step 0c AUQ templates". Question 3 joins the Step 0c AUQ batch whenever that AUQ fires and --deep is absent, and counts toward the batch-exceeds-4 chain rule above. Neither option carries (Recommended) — Deep is costlier, not safer; an empty answer defaults to Standard (deep-mode: false). Activation and the flag-only fallback where this AUQ never fires: §State persistence above.
0d — Approvals-persistence
Persist the workspace and workflow-status answers to state.md approvals[] (entry shapes: reference §"Phase 1: Step 0 setup detail"). The depth pick (Question 3) is NOT written here — it is materialized once at Step 4, so the depth choice lives in exactly one place.
On compaction-resume, Step 0 reads approvals[] and re-applies prior answers without re-prompting.
0e — Execution after AUQ
- Workspace action — execute branch creation / worktree create / no-op per
implement_workspace_setup pick (which a spec launch_config.workspace may have pre-answered at Step 0g). Slug source: ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-naming.md. Branch and worktree creation cut from the latest default branch — apply Mode FRESH-BASE in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/branch-freshness.md so the new working tree starts from the freshest default-branch tip rather than the current HEAD. For the "Current branch" (no-op) pick, apply Mode FRESH-CONTINUE from the same helper — offer to bring the branch up to date before Phase 1 proceeds. When launch_config.branch_freshness is set, pass it as the pre-chosen strategy so a clean fast-forward applies it without asking; a real conflict still surfaces interactively.
- Workflow status action — for each persisted
implement_workflow_status approval, follow the workflow file's ### On task start instructions. Skill does NOT hardcode MCP call shape — workflow file owns that.
- State.md frontmatter update —
branch: and worktree: reflect the new working tree before Phase 1 continues.
0f — Edge cases
Resolved by the table in reference §"Phase 1: Step 0 setup detail" (workflow MCP down · missing ### On task start · an "Other" pick on Question 1 · several handoffs on one branch · a stale handoff · a worktree on a protected branch).
0g — Apply spec launch_config (pre-answer setup)
When SPEC_LAUNCH_CONFIG is non-empty (a spec carried a launch_config: block), apply its fields per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/launch-config-schema.md — each field pre-answers one Step 0 setup question, so the matching question does not fire; the enum values and per-field semantics are owned by that schema file. Absent block (no spec, inline-task run, or a pre-m5-v4 spec without the block) ⇒ behavior is unchanged: every setup question fires interactively exactly as it does today.
Field → decision it pre-answers: the map in reference §"Phase 1: Step 0 setup detail". Two caller-side deltas the schema file does not own:
workspace does NOT override an active auto-continue / resume signal — when a continuing signal already skips the workspace question (decision-tree rules 1-3), that path wins; the plan-time pre-set is not a directive to abandon an in-flight workspace.
- Record the applied choices in
approvals[] the same way the interactive answers would — implement_workspace_setup, deep_mode_choice, ship_mode, and — when tracker_status was set — implement_workflow_status — each carrying source: launch_config so a compaction-resume re-applies them without re-asking.
Doctrine — setup only, never safety. launch_config pre-answers SETUP questions only; it does NOT pre-authorize the genuine safety gates, which stay Always-WAIT and fire only when actually triggered — the gate list + rationale: ${CLAUDE_PLUGIN_ROOT}/skills/_shared/launch-config-schema.md §"Doctrine boundary — setup only, never safety".
Steps (after Step 0 settles)
- Semantic-parse
$ARGUMENTS. Apply the table in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: $ARGUMENTS semantic-parse table".
- Resolve spec source. Walk the spec discovery list (
${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: Spec discovery walk-list"). If no spec.md / plan.md / DESIGN_DOC frontmatter found AND $ARGUMENTS is non-empty → inline-task mode (write ## Inline Plan to state.md body).
- Disambiguate if needed. If $ARGUMENTS is ambiguous, fire AUQ per Phase 1 table. Persist outcome to state.md frontmatter
approvals[] with category: disambiguate_arguments.
- Resolve task slug. Used for state.md path. If task-dir exists, validate state.md (recovery AUQ on validation fail). If task-dir is fresh,
mkdir -p. Write the resolved depth into the state.md frontmatter at creation: deep-mode: true when EITHER Step 1 parsed --deep OR the Step 0 Question-3 depth pick was Deep; deep-mode: false for a Standard / empty pick. Append the matching {category: deep_mode_choice, picked: <deep|standard>, at: <ISO-8601 UTC>} to approvals[] via atomic_state_write — the resolved depth must be persisted, not just held in working memory, so a compaction-resume re-applies it.
- Load custom instructions. Apply
${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-instructions.md with SKILL_SLUG: implement, LOAD_TIER: pipeline, MODE: refresh. The helper's §Procedure prescribes imperative Read directives on global.md, implement.md, and code-style.md (3 files); the §Echo contract requires one observable line per file. Both are mandatory.
- Load project snapshot.
load_semantic with default top-2 (_project.md + _CODEBASE_MAP.md). Optional --extras _FEATURES.md if spec mentions feature backlog. Fingerprint drift check fires automatically; surface drift notification to user.
- Spawn knowledge-retrieval + codebase-explorer agents in parallel. ONE assistant response, TWO
Agent(...) tool calls. Apply the spawn template in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: Subagent spawn template" — first prime both spawns with the related-task chain context (parent epic + sibling tasks + neighboring milestones) per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/task-chain-context.md. Apply the registration-degradation ladder in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/spawn-agent.md at each spawn site. OMIT model= argument — the frontmatter governs (codebase-explorer-agent declares model: inherit; knowledge-retrieval-agent declares model: sonnet, a mechanical-gather carve-out). Backgrounding when a handoff gate is pending: when Step 0a flagged a review, debug, or resolve handoff for this branch (REVIEW_HANDOFF / DEBUG_HANDOFF / RESOLVE_HANDOFF) that carries unresolved open-questions, spawn both agents run_in_background: true and run the Step 12 open-questions gate (sub-steps 1-7) during their compute — procedure in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Backgrounding when a handoff gate is pending". Otherwise — the common case, no such handoff — spawn both BLOCKING exactly as before.
- Read subagent outputs — drain point. Confirm both agents returned before reading:
Read <task-dir>/.kr-out.md and <task-dir>/.ce-out.md, or resume by ID when the output file has not yet landed. When Step 7 backgrounded the agents, this drain is the first step that consumes their output — it must not proceed until both have returned (reference §"Backgrounding when a handoff gate is pending"). The codebase-explorer's change_scope field gates the Phase 3 adversarial-tester spawn (trivial → skip). Failure handling for either agent: on missing/empty output OR Agent tool error, one silent retry; second failure → inline-Read fallback (load top-3 exemplar files + _CODEBASE_MAP.md rows by Grep) with change_scope: medium as safe default. Emit a diagnosis learning with trust: retrieved. Echo notice to user.
8.5. Library reuse audit (build-vs-buy). For each codebase-explorer NO-ANALOGUE component, when change_scope is small / medium / big (skip trivial), apply ${CLAUDE_PLUGIN_ROOT}/skills/_shared/library-reuse-audit.md with MODE: implement — a web-research agent finds candidate libraries in the project's detected ecosystem, filters them (existence-verified against the real registry), and a message-first confirmation gate requires explicit approval before any library is adopted (persists approvals[] category library_adoption). Skip silently when there is no package manifest or no NO-ANALOGUE component; fail-open on a research/registry error.
- Query past learnings.
query_learnings --tag <inferred> --scope <task-path> --limit 5 — route per the Memory I/O §"Read" backend rule above (a declared backend redirects this to its read tool; the file is empty under replace). Tags may be primed by the knowledge-retrieval output. Skip if task description is too generic.
- Resolve cross-layer conflicts. Apply
${CLAUDE_PLUGIN_ROOT}/skills/_shared/resolve-conflicts.md protocol if instructions / snapshot / learnings disagree.
- Detect frontend files in scope. Use the codebase-explorer "Likely-Touched Files" report against the UI-file detection rule (
${CLAUDE_PLUGIN_ROOT}/skills/_shared/ui-preview-gate.md §UI-file detection rule). Gates Pre-Ship Visual Verification.
- Persist review / debug / resolve handoffs AND gate on unresolved open questions. When Step 7 backgrounded the agents, sub-steps 1-7 already ran during the knowledge-retrieval / codebase-explorer wait (per the reference §"Backgrounding when a handoff gate is pending", including its persist-in-the-pick-turn rule) — do NOT re-run them; run sub-steps 8-11 here. Otherwise run all sub-steps in order here. Either way the Edit/Write boundary is unchanged: every unresolved entry must be resolved before transitioning to
phase: implement, regardless of when it was asked. For every <PRIMARY_ROOT>/.geniro/state/handoff/from-<producer>-<branch>.md that exists:
- Read the handoff file with the
Read tool (or Bash cat).
- Persist the body under state.md
## Inputs from <producer> body section.
- Parse frontmatter
open_questions[] per the schema in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/state-tier-spec.md §T2. Also read report_status (review handoffs): an explicit report_status: draft (missing reads as final per the state-tier-spec back-compat rule) means /geniro:review did not finish its decision gates — the handoff is not yet finalized. Surface a one-line warning ("the review handoff is still a draft — its decisions weren't finalized; resolving the open questions below completes it") and require the unresolved-open-questions gate (sub-steps 4-5) to clear before transitioning to phase: implement. The draft marker is a signal, not a separate block — the open_questions[] gate is the actionable resolution.
- Filter to entries with
status: unresolved.
- If the filtered list is non-empty, fire an AUQ batch BEFORE transitioning to
phase: implement. Chain one AUQ per unresolved entry (cap-extension when >4). Apply the 3-tier rendering procedure in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/review-handoff.md §2.5 — it renders each question as a self-contained chat message first, then a lean question, per the shared finding-gate contract (${CLAUDE_PLUGIN_ROOT}/skills/_shared/per-finding-question.md §Message-first rendering); which tier fires depends on the producer fields the entry carries (single-sourced in §2.5 — don't restate them here). Set resolution.asked_in_phase: phase-1-step-12 and resolution.resolved_by: implement when persisting answers (vs §2.5's phase-6-pre-gate / review).
- After each user pick, round-trip the update into the PRODUCER's handoff file via
atomic_state_write: set status: resolved plus resolution.picked / .at / .asked_in_phase: phase-1-step-12 / .resolved_by: implement on that entry, and re-emit the file's ENTIRE original content around it — the helper overwrites rather than merges, so every other frontmatter key and body section the producer wrote must survive byte-for-byte or the write silently truncates state a downstream consumer (including sub-step 9's authored_tests[] read) depends on. Per-producer key inventory: ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 1: Handoff round-trip write".
- Persist a parallel approval to state.md
approvals[] with category: review_handoff_resolution, picked: <chosen option>, at: <ISO-8601 UTC>, source_handoff: <producer>, question_id: <id> for compaction-resume idempotency.
- After all entries are
resolved or wontfix, proceed to sub-step 9.
- Extract authored F→P tests when the handoff is from
/geniro:debug. Skip when <producer> is anything other than debug (e.g., review); fire only for from-debug-<branch>.md and from-debug-adversarial-<branch>.md. Apply the canonical Scan/Extract/Verify/Decide protocol in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/debug-handoff.md:
- Extract — prefer frontmatter
authored_tests[] (m7-v2+); fall back to body **Reproduction test:** / **Test file:** parse for legacy m7-v1 handoffs.
- Verify — resolve each path against this skill's current
git rev-parse --show-toplevel and bucket as PRESENT / MISSING.
- Decide and surface — Case A (all PRESENT, debug-source-branch matches) → one-line acknowledgment in the Phase 1 context summary. Case B1 (any MISSING) → surface the suggest-only relocation block from
_shared/debug-handoff.md §Step 4; the user runs git checkout <debug-source-branch> -- <paths> or cp themselves — never auto-execute cross-branch git operations. Case B2 (all PRESENT but branches differ) → one-line "tests carried over" note. Case C (legacy fields missing) → degraded suggestion without explicit checkout command.
- Persist to state.md as
Authored-tests: (comma-separated relative paths on a single line) plus, when sourced from m7-v2+ frontmatter, Authored-tests-intent: (parallel comma-separated intents) and Debug-source-branch: / Debug-source-worktree:. Phase 2 reads these to prime TodoWrite decomposition — each authored test becomes a pre-existing acceptance gate, surfacing in the relevant todo's description so the production-fix work cannot ship without those tests going GREEN.
- Authored-tests extraction is informational, NOT a gate — do NOT block transition to
phase: implement on missing files. The user retains agency to either run the suggested commands, re-author tests in the current branch, or accept the divergence.
- Stash
/geniro:resolve comment-resolutions. When <producer> is resolve, also parse the handoff's comment_resolutions[] (per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/state-tier-spec.md §/geniro:resolve producer fields) and persist it to state.md under ## Inputs from resolve for the Phase 3 Ship "Resolve PR review threads" sub-step (step 6.5). It is informational, NOT an Edit/Write gate — only open_questions[] blocks editing; a fix whose thread is closed later still flows through the normal fix loop.
- After authored-tests and comment-resolutions handling, proceed to step 12.5.
/geniro:implement is the consumer; the contract per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/state-tier-spec.md §T2 forbids proceeding with Edit/Write while any unresolved entry remains. A consumer that ships anyway violates the contract — the producer surfaced the ambiguity precisely so it gets resolved BEFORE code changes.
12.5. Spec challenge — fact-check the spec against the current code before editing. The last gate before code edits begin.
- Spec-driven mode only. Run this step only when Step 2 resolved a real spec.md / plan.md / DESIGN_DOC. SKIP it in inline-task fallback mode — there is no written spec to fact-check, so emit a one-line note ("No spec file — skipping the spec fact-check") and proceed to step 13.
- Invoke the helper. Apply
${CLAUDE_PLUGIN_ROOT}/skills/_shared/spec-challenge.md with MODE: implement, SPEC_PATH: <resolved spec path>, TASK_DIR: <task-dir>, EFFORT_TIER: <the codebase-explorer change_scope>, DEEP: <true when state.md deep-mode: true, else false>. Verdict handling — the skip-when-clean advisory and, on defects-found, the message-first render (per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/per-finding-question.md §Message-first rendering) followed by the lean AskUserQuestion with options "Proceed anyway" / "Fix the spec, then proceed" / "Abort — re-plan via /geniro:plan" — is owned by that file's §8.
- Persist the pick. Record the user's choice in state.md frontmatter
approvals[] with category: spec_challenge, picked: <chosen option>, at: <ISO-8601 UTC> for compaction-resume idempotency.
- Fail-open. If the helper or any verifier spawn fails, write a line to state.md
## Errors, emit a one-line notice to the user, and proceed to step 13 — a fact-check failure does not hard-block the run.
- State.md write.
atomic_state_write with phase: analyze body sections populated → upon completion, transition phase: implement.
Workflow plumbing. Workflow integrations (.geniro/workflow/*.md) apply their argument-detection patterns BEFORE the semantic-parse table. Non-blocking — log warning if integration backend unavailable.
Big-task notice
When Codebase-Explorer reports change_scope: big AND no milestone-*.md files exist alongside spec.md, emit one informational notice (NOT AUQ — just observation):
This is a large change. Consider running /geniro:plan in milestone mode to
split it into separate milestone files before implementing. This run will
proceed as a single pass with a step-by-step task list; splitting is cleaner.
Milestone-mode is the canonical answer for truly Big tasks (separate worktrees, separate /geniro:implement runs). User may cancel and re-run /geniro:plan on this task — /geniro:plan emits milestone files automatically when it classifies the task as Big; otherwise the run proceeds.
PHASE 2: IMPLEMENT
State.md phase: implement on entry.
No custom-instructions or project-snapshot refresh at Phase 2 entry — both remain in context from Phase 1.
Steps
-
Read spec source — Phase 1 resolved either a spec.md path OR wrote ## Inline Plan to state.md body. Inline-Read the spec.md (full body) and the Codebase-Explorer "Likely-Touched Files" + "Reuse Inventory" sections.
-
Decompose into todos via TodoWrite (Phase 2 entry — before any Edit). Author N concrete edit-tasks via TodoWrite. Each todo = one logical unit of change, sliced vertically — one behavior paired with the test that pins it (e.g., "Add migration X + test the new column round-trips", "Add expiry check to Y controller + test expired tokens get 401") — never horizontally (all production edits first, then a trailing "add tests" todo). Tests authored in bulk after the code pass on first run and discriminate nothing; pairing each behavior with its test keeps every test anchored to a change it actually observed. N typically:
- 1-3 todos for Small scope
- 3-10 todos for Medium scope
- up to 15 todos for Big scope (unless already split into milestones)
All todos initially status: pending. Mark the FIRST todo in_progress before any Edit.
A library adopted at the Phase 1 build-vs-buy library-reuse audit (approvals[] category library_adoption) also becomes a todo here: add it through the package manager (not by editing a lockfile — lockfile writes stay hook-protected) and integrate it in place of the hand-written component.
-
Work through todos sequentially — one in_progress at a time (Loop invariant #9):
for each todo in pending order:
a. Mark todo in_progress via TodoWrite
b. Make the Edit/Write changes for THAT slice ONLY
c. JIT-load any .claude/rules/*.md whose paths: glob matches an Edit target
(use the rule list returned by Codebase-Explorer §"Relevant Rules";
cache rule bodies for the rest of Phase 2)
d. Mark todo completed via TodoWrite
e. Move to next todo
Delegating a todo (bounded). Default is inline — the orchestrator edits directly. Delegate a todo to a general-purpose subagent (same worktree, OMIT model=) only when the slice is genuinely independent: its file set overlaps no other todo's, it shares no in-flux type/contract/import with concurrently-edited code, and the prompt can carry everything the delegate needs (the todo's spec excerpt, exemplar file paths, the paired test, and the relevant code-style/conventions content inlined — a subagent inherits no orchestrator context). Good candidates: a mechanical wide edit (a rename across many call sites), an isolated leaf module, boilerplate generation. Coupled slices stay inline — splitting them across agents produces the style drift and duplicated implementations that lint/compile cannot catch. Rules: the delegate edits ONLY its named file set; on return, read its diff before marking the todo completed — the orchestrator owns every line it ships; the end-of-phase suite still runs once for the whole phase. Multiple delegates may run in parallel ONLY when their file sets are pairwise disjoint; integrate their results one at a time (invariant #9 governs the todo states, not the spawns).
Scope discipline. Build what the todo's slice requires and nothing beyond it — no speculative abstractions, configuration options, or generalized helpers for needs the spec doesn't name. Generality added "while we're here" is scope the user never approved, and the code-quality reviewer flags it as speculative generality in Phase 3.
Comment discipline. Match the surrounding file's comment density and idiom. Write a comment only where the code cannot show the constraint itself — a non-obvious WHY, an invariant the types don't express, a legal header, a TODO with an issue reference. Never restate what a line does, narrate the change being made ("added X", "now handles Y"), or address the reviewer — those comments are noise the moment the diff merges, and the reviewer reads the diff, not annotations. A per-project code-style.md rule overrides this default where they conflict.
Halt on unbidden working-tree mutation. Between Edits, if the working tree changes in ways this run did not make — an Edit/Write repeatedly fails with "file changed since read", or files/tests this run never authored appear on disk — treat it as a concurrent external process, NOT a benign harness restore. Stop and fire an AskUserQuestion (header: "Workspace changed", options: "Pause — let me resolve the other process" / "Move my work into a fresh worktree and continue there" / "Abort"). Committing from a working tree another process is mutating risks the commit being orphaned by an external reset.
-
End-of-phase test run via test-runner-agent. After all todos completed, spawn test-runner-agent once with the project's pre-resolved TEST_COMMAND (from CLAUDE.md "Essential Commands"), the CHANGED_FILES list, OUTPUT_PATH <task-dir>/.tr-out.md, and MAX_FAILURES_REPORTED (default per the test-runner-agent spawn template in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md). Apply the registration-degradation ladder in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/spawn-agent.md. OMIT model= — test-runner-agent declares model: sonnet (mechanical run-and-parse carve-out). Read back the OUTPUT_PATH report. Attach the report's Command / Exit code / Summary / Verdict block as Evidence per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/evidence-standard.md.
-
In-phase fix loop on test failure. Up to 3 retries (full pseudo-code + token-cost analysis: ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 2: Implement — error-handling"). On each retry: read .tr-out.md, escalate-AUQ immediately on INFRA_ERROR, edit top-priority failures on HAS_FAILURES, re-spawn test-runner-agent. On ALL_GREEN — by EITHER path (the first-shot end-of-phase run OR a later fix-loop iteration) — run the spec's per-criterion verify: commands (step 5.5) BEFORE exiting to Phase 3. Retry exhaust OR an early-escalation trigger (see below) → escalate-AUQ before the 3-retry budget is spent — a loop that is not converging burns the user's tokens on the same wall.
5.5. Run the spec's per-criterion verify: commands once the suite is ALL_GREEN (spec-driven runs only). This fires on the suite's green exit from step 5 — whichever path reached green — so a red→green run never ships without the spec's acceptance checks. For each section 9 (Validation) criterion that carries a verify: line, the orchestrator runs that one command via its own Bash (NOT test-runner-agent — its single-command leaf contract forbids it orchestrating several commands) and classifies the result on the same {ALL_GREEN, HAS_FAILURES, INFRA_ERROR} taxonomy. Bounded single-shot — run once and attach as evidence; not an iterate-to-green loop. Side-effect screen first: before executing each command, refuse to auto-run any that carries a ship / deploy / external-state-mutation verb (git push, gh pr create, gh pr merge, git commit, deploy / release / publish, etc.) — this command runs before the ship gate, and the safety hooks block force-push but NOT a plain git push / gh pr create, so auto-running it would ship past the gate (Loop-Invariant #3). A refused command routes into the same Step 6 escalation with a plain-English reason — never executed, never silently skipped. Any HAS_FAILURES / INFRA_ERROR (or a refused command) feeds the same Step 6 escalation digest so the user stays the ship decider. Inline-task runs (no spec) have no verify: lines and skip this step. Mechanics: ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 2: Implement — error-handling", "Per-criterion verify: commands".
-
Escalation on retry exhaust, INFRA_ERROR, or a not-converging signal. Render the failure digest to chat first per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/per-finding-question.md §Message-first rendering — what failed in plain English, the failing items as a ☐ checklist, why it blocks the phase (worked digest shape: ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 2: Implement — error-handling", "Phase 2 check-failure escalation digest") — then fire the lean AUQ with the header keyed to what failed ("Test failure" for a failing test suite, "Acceptance check failed" for a failing spec verify: command, "Checks failed" when both — per the reference's failure-source table) and these options:
- A) Hand off to /geniro:debug — state.md
phase: debug-handoff (terminal)
- B) Accept the failing check as a documented limitation — state.md
phase: self-review, append ## Accepted Failures block (label is source-neutral: the failure may be a test OR a spec verify: acceptance check)
- C) Abort — state.md
phase: aborted (terminal)
Empty answer = upstream bug, fall back to plain text and re-ask. Do not auto-default.
Early-escalation triggers (derived from state.md ## Errors + ## Tool log history — no new state surface). Fire the same AUQ before retries exhaust when any of these holds, because each is a signal the loop has stalled rather than progressed:
- No forward progress between two checkpoints. Two consecutive retry checkpoints produce no new passing tests AND no forward diff progress (the changed-files set and failing-test set are unchanged across the pair). The fix edits are not moving the suite.
- Retry storm — the same failure recurring. An identical failing test name OR an identical error message / stack-trace recurs across retry attempts (compare the current test-runner output against the prior retry's failing-test list still in context). Re-hitting the same wall means the current approach cannot clear it.
- Cost / scope drift. The run has exceeded its expected size by either of two sub-signals: (a) the codebase-explorer
change_scope tier from Phase 1 (e.g. a trivial/small task now spanning many files and edit batches), OR (b) for a spec-driven run, the size the user wrote into the spec — the budget.max_files_to_edit / budget.max_lines_changed numbers — crossed by the live diff (count files and lines from the CHANGED_FILES set / git diff --stat, no new state surface per invariant #5). Each budget value is disarmed when null (= unbounded); the inline-task fallback has no budget block, so sub-signal (b) never arms there. Whichever sub-signal trips first fires this AUQ once — dedupe with the other so one scope-drift escalation fires per run, and the dedupe spans Phase 2 AND the Phase 3 fix loop (this trigger set is reused there) so it never double-fires across phases. The AUQ question names which bound was crossed.
When an early trigger fires, state the plain-English reason in the AUQ question text (e.g. "the same test keeps failing across retries" / "this is turning out larger than the size you set in the spec") so the user knows why the gate opened early — never surface the raw signal name (e.g. max_files_to_edit / change_scope / budget).
State.md update on phase exit. phase: self-review (happy path) or phase: phase-2-escalated (if escalation fires). On aborted, write ## Termination reason: repeated-failure: phase-2 retry-limit (<N> failing Phase 2 checks) — source-neutral, since the escalation covers both a failing test suite AND a failing/refused spec verify: acceptance check.
L2 emit on retry exit. When Phase 2 exits AND retry_count ≥ 2 (i.e., at least one fix-iteration happened), call emit-learning with type: retry_failure_sequence, trust: verified, required ext.{phase: "phase-2-fix-loop", attempts: [...], resolution}. Each attempts[] entry = {round: N, failure: "<one-line summary>"}. resolution ∈ {passed, escalated, aborted} matches the actual exit state. Sliding-window cap = 3 latest per (producer, scope, phase); on overflow, flip the oldest entry's deprecated: true BEFORE appending — this mutates .geniro/knowledge/learnings.jsonl, so rewrite the file through the atomic-write path (atomic_state_write), not a direct Edit/Write the state-helper hook guards (mirrors debug §1.5). Single-retry exits (retry_count == 1) do NOT emit. Future Phase 1 query-learnings calls surface this as priming context.
Loop visualization
PHASE 2 (sequential, single-context):
spec.md + Codebase-Explorer report
↓
[Phase 2 entry] TodoWrite: decompose into N todos
↓
┌─→ todo[i].in_progress ──→ Edit/Write batch ──→ todo[i].completed ─┐
│ │
│ [i++; loop until all completed] │
│ │
└────────────────────────────────────────────────────────────────────┘
↓
[End-of-Phase] test-runner-agent spawn (one shot)
↓
[3-retry fix-loop on failures]
↓ (suite ALL_GREEN — by either path)
[run spec verify: commands] (spec-driven runs only)
↓ (all pass) ↘ (any fail/refused)
Phase 3 [Step 6 escalation AUQ]
PHASE 3: SELF-REVIEW + SHIP
State.md phase: self-review on entry.
Refresh L4 instructions (always, regardless of compaction-marker presence). Apply ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-instructions.md with MODE: refresh, scope = same as Phase 1.
Green-light verification on entry. The suite should be green from Phase 2. Skip the confirming re-run only when ALL of: Phase 2's final test-runner result this run was ALL_GREEN (not accepted-failures), no compaction marker has appeared since that green run, and no Edit/Write touched project files after it. If any condition fails or is uncertain, re-run the test suite once — fail toward running. If the suite is NOT green, the orchestrator may NOT unilaterally reclassify the failures as pre-existing/flaky and proceed — it routes through the documented gate: roll back to the Phase 2 retry loop, or (on retry-exhaust) the escalation AUQ (debug-handoff / accept-failures / abort), which records a ## Accepted Failures block that is then disclosed at the ship-mode AUQ. If the orchestrator suspects the failures are pre-existing, it may baseline-prove them (re-run the failing tests on the unchanged base, e.g. via git stash) — but that evidence routes INTO the accept-failures AUQ for the user to acknowledge; it does not authorize shipping past a RED required suite on the orchestrator's own authority.
Resolve PRIMARY_ROOT before the parallel reviewer batch fires. Run the Mode A snippet from ${CLAUDE_PLUGIN_ROOT}/skills/_shared/primary-worktree.md via Bash. The custom-reviewer discovery in Step 1 calls ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-reviewers.md, which dual-globs .geniro/instructions/review-extra/*.md against cwd AND <PRIMARY_ROOT>/.geniro/instructions/review-extra/*.md — without the slot in scope, a linked-worktree session sees an empty .geniro/instructions/ even when user-authored review-extra files exist on the main worktree.
Steps
-
Round 1 parallel spawn IS the Phase 3 review mechanism — reviewer-agents + 1 adversarial-tester-agent in the SAME assistant response. Multiple Agent(...) tool uses in one message. An inline "self-review summary" the orchestrator writes from its own context does NOT satisfy Phase 3: it shares every assumption the implementer just made, so it cannot deliver the independent, anchoring-bias-free read the spawned reviewer-agents (fresh isolated contexts) exist to provide. The fresh parallel spawn fires regardless of how well the orchestrator believes it understands the change. Apply the registration-degradation ladder in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/spawn-agent.md at every spawn site. OMIT model= at every spawn site (every agent declares model: inherit).
Deep-mode branch (deep-mode: true). Run Round 1 via the deep self-review Workflow(...) instead of the single parallel batch below — each reviewer dimension under 3 angles (union + dedup per dim), then a signal-gated verification of each deduped finding, per ${CLAUDE_PLUGIN_ROOT}/skills/implement/deep-mode-reference.md §3-4. Only verified findings enter the fix loop; the adversarial-tester-agent stays a single spawn. Fail-safe to the standard single-pass batch below if the workflow errors (deep-mode-reference §7). Fix-loop rounds 2-3 run single-pass regardless. Everything below describes the standard single-pass Round 1.
-
reviewer-agents — one per dimension. Apply ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 3: Self-review reviewer-agent template". Dimensions: bugs / security / architecture / tests / code-quality. The architecture dim covers docs-staleness AND spec-compliance. See reference.md §"The reviewer dimensions" for full criteria-file mapping.
-
1 adversarial-tester-agent — apply ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 3: Adversarial-tester spawn template". The agent authors F→P-verified failing tests against the diff and writes them to the project's test directory. SKIPPED on either of two conditions:
- Codebase-Explorer
change_scope: trivial, OR
--no-adversarial modifier present in $ARGUMENTS.
-
Custom reviewer dimensions — discovered once at Round 1 entry via ${CLAUDE_PLUGIN_ROOT}/skills/_shared/load-custom-reviewers.md (.geniro/instructions/review-extra/<slug>.md, ≤10 cap, path-filtered). Append one Agent(subagent_type="reviewer-agent",...) call per spec to the same parallel batch.
-
Collect findings. Reviewer-agent output schema per agents/reviewer-agent.md §Output Format. Adversarial-tester output schema per agents/adversarial-tester-agent.md §Output Schema AND authored test files on disk under the project's test directory. Cap per-dim output at ~4000 chars (invariant #4); truncate with marker on overflow.
-
Bounded fix loop. Up to 3 rounds. Full pseudo-code + scope/severity partition + drop-rules for round N+1 + adversarial-as-6th-dim mechanics: ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 3: Bounded fix loop". Summary: on each round, collect findings from the parallel spawns and partition per the reference — mechanical LOW nits in code this run authored (comment noise, naming slips, dead imports) are fixed within the round; findings tagged pre-existing are NEVER auto-fixed at any severity, because fixing code this change didn't introduce silently expands the diff past what the spec authorized — they and the remaining minor findings persist to state.md ## Deferred Findings via atomic_state_write for the step-5 disposition gate, where the user decides. If no actionable findings remain AND no authored adversarial tests still fail, exit to Ship; otherwise apply the smallest fixes that resolve the findings inline (no further agent spawns, no abstractions the finding doesn't require), re-spawn test-runner-agent (rollback to Phase 2 if not green), increment round, then re-spawn ONLY the reviewer dims with actionable findings (and the adversarial-tester conditionally). Round 4 entry is forbidden — escalate-AUQ instead.
-
Escalation on round-3 exhaust or a not-converging signal. Render the unresolved findings to chat first per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/per-finding-question.md §Message-first rendering, then fire the lean AUQ (header: "Resolve findings") — worked render procedure in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 3: Bounded fix loop", "Escalation at exhaust"; options:
- A) Hand off to /geniro:debug — state.md
phase: debug-handoff (terminal)
- B) Accept findings, ship anyway — state.md
phase: ship, append ## Accepted Findings block
- C) Abort — state.md
phase: aborted (terminal)
Empty answer = upstream bug, fall back to plain text and re-ask. Do not auto-default.
The Phase 2 early-escalation triggers (§PHASE 2 Step 6) apply to this fix loop too — same trigger set, same once-per-run dedupe, so a scope-drift escalation that already fired in Phase 2 never re-fires here. Read them from the same state.md ## Errors + ## Tool log history, with review rounds and surviving findings substituting for retries and failing tests, and fire this AUQ before round 3 exhausts when one holds. State the plain-English reason in the AUQ question text — never the raw signal name.
-
Post-convergence gates — minor findings, then test quality. First the minor-findings gate: when state.md ## Deferred Findings is non-empty (the fix loop's persisted minor findings), render the list message-first and ask whether to fix them now or leave them listed in the ship report — canonical contract (AUQ shape, fix / leave branches, minor_findings_disposition persistence, boundary rules) in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Phase 3: Minor-findings gate"; skip silently when the section is empty or absent; ship modifiers and launch_config.ship_mode never pre-answer it. Then the test-quality gate: when this run authored or changed test files, surface the test audit as a visible decision before Ship per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/test-quality-gate.md — the fresh tests reviewer already audited the new tests against the spec (claimed-vs-asserted scope, spec-coverage, redundancy among new tests, weak assertions, and scenery tests flagged for removal per ${CLAUDE_PLUGIN_ROOT}/skills/_shared/review-criteria/tests-criteria.md), so this step makes that audit visible rather than re-running it; skip-when-clean (a clean audit records a one-line confirmation in the ship report and asks nothing), open findings render message-first then a lean AUQ (tighten all / pick / ship as-is). Both gates are advisory and fail-open — they never block Ship on their own, never override the Ship-mode AUQ, and spawn no new agent (each consumes output already collected).
Ship sub-step
State.md phase: ship on entry.
- Pre-Ship Visual Verification — fires only when frontend files in scope AND Playwright MCP available. Apply
${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Pre-Ship Visual Verification".
- Commit. Verify the live
git branch --show-current matches the intended branch before staging — do not trust the session-start branch snapshot (stale across compaction); on mismatch, fire the branch-check AskUserQuestion (full procedure in ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Step 2 — Commit") rather than committing. Then stage only this run's CHANGED_FILES set by name (git add <paths>, never -A/.). If git status shows production files modified outside that set — edits this run did not author — do NOT auto-fold them; fire an AskUserQuestion to confirm whether they belong in this commit before staging. Then git commit with conventional message (e.g., feat(auth): add OAuth login [ENG-123]). Task ID inferred from spec.md / state.md metadata.
- Emit learnings. Fire this before the Ship-mode AUQ — the learning describes the change just committed and doesn't depend on the push outcome, so emitting here makes it part of finalizing the work rather than a postscript that gets dropped once the PR is open (the documented sparse-L2 cause). Emit
convention when a ≥3-instance pattern was detected; emit decision if spec.md recorded a non-trivial approach choice; a clean single-pass change with neither emits nothing. Default trust = verified. After a successful emit, echo Recorded learning: <summary> to the user, and surface the promotion suggestion only for convention type. Apply ${CLAUDE_PLUGIN_ROOT}/skills/implement/implement-reference.md §"Extract Learnings" plus the visibility + ordering rules in ${CLAUDE_PLUGIN_ROOT}/skills/_shared/emit-learning.md §"Caller contract".