# Execute

> Primary pipeline execution step after /prd-to-issues or for clearly scoped implementation work. Use to build, verify, and commit a concrete slice, delegating to /tdd for backend work and behavior-heavy frontend logic when red-green-refactor will reduce risk. Not for shaping or pre-merge review.

- Skill: `chrislacey89/execute` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add chrislacey89/execute`
- Raw SKILL.md: https://api.skillmd.com/api/skills/chrislacey89/execute/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Product & Planning
- Author: chrislacey89 (https://skillmd.com/u/chrislacey89)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/chrislacey89/execute

---


# Execute

Execute a complete unit of work: plan it, build it, verify the actual outcomes, commit it.

## Invocation Position

This is a primary pipeline skill used after `/prd-to-issues` has produced a concrete slice, or when the user already has a clearly scoped implementation task.

Use `/execute` when the work is ready to build, verify, and commit.

Use HITL `/execute` when the slice still needs active user judgment, supervision, or acceptance decisions during implementation. Use AFK `/execute` only when the next slice is already durable in GitHub, unblocked, and legible from its issue, boundary map, and any linked research artifact (archive file or spike issue) or `docs/solutions/` context.

Legible to a reader holding none of it — which is what an AFK iteration is. `/prd-to-issues` §4's context completeness check is the gate behind that condition: it requires every AFK slice to carry a `### Context` block, or explicit empty declarations, before the issue is filed. A slice marked AFK with no such block was never checked against this condition, only assumed to meet it. Treat that as a reason to run the slice HITL, or to send it back through `/prd-to-issues`, rather than as a formality to wave through.

See **Step 0: Prerequisites** below for the mandatory Ralph auto-detection and TDD marker gates.

Do not use it to replace `/shape`, `/research`, or `/write-a-prd` when the problem or shape is still unresolved. Do not use it as a substitute for `/pre-merge` once implementation is complete and ready for review.

## Workflow

### 0. Prerequisites

**Branch isolation gate.** Before any implementation work, ensure you are working on a clean branch created for this specific task — not a leftover feature branch from previous work.

**Isolation already provided — stand down (check this first, before the numbered rules).** Some environments hand the session a dedicated, isolated worktree+branch *before* `/execute` runs — Conductor workspaces, GitHub Codespaces, devcontainers, and similar hosts each provision "one workspace = one branch, auto-forked from the base," with setup scripts already run. When that is the case the pipeline does not own provisioning: creating a worktree here would nest one *inside* the host's, and the host's branch (named for the *workspace*, not the task) is not "stale." Read the environment's signal and cede the worktree to whoever already owns it (Norman — read the world's signifier instead of carrying an in-head assumption that the pipeline always provisions; Meadows — one actor per stock, so the pipeline *defers* rather than adding a competing manager).

Resolve the provisioning mode from `.claude/settings.json` `worktree.provisioning` — `"host" | "pipeline" | "auto"`, default `"auto"` when the key is absent (mirroring the existing `research.storage` precedent):

- **`host`** — isolation is host-owned. Stand down unconditionally.
- **`pipeline`** — the pipeline provisions. Skip this stand-down and run the numbered gate below.
- **`auto`** (default) — stand down if *either* signal fires:
  - a host environment variable is present — `[ -n "$CONDUCTOR_WORKSPACE_PATH" ]`, `[ -n "$CODESPACES" ]`, or `[ -n "$REMOTE_CONTAINERS" ]`. This is the cheapest, primary discriminator: the pipeline's only detection mechanism is Bash, and these vars are visible in the agent's shell. (Do **not** detect via a `.conductor` directory in the cwd — Conductor keeps it under `$CONDUCTOR_ROOT_PATH`, not the workspace.)
  - the current working tree is not the repo's primary working tree — `git rev-parse --show-toplevel` differs from the first path in `git worktree list --porcelain`.

When standing down: **skip worktree creation and `EnterWorktree`, and work in place on the current branch.** The numbered rules below are already satisfied — in particular **rule 3 does not apply** (a host-provisioned branch is neither base nor task-named, but it is not stale; do not nest a worktree and do not stop). The host has already seeded git-ignored config and dependencies, so most of the "Worktree setup checklist" is informational only — spot-check `.env.local`/deps if a command fails, but do not re-provision. **Its git-hooks item is the exception and still applies.** Hosts provision *tracked* files plus dependencies; git hooks live in `.git/hooks`, which is per-worktree and untracked, so a host-provisioned workspace characteristically has none. Check that item even when standing down. Continue to the issue-shape gate.

This stand-down is deliberately *asymmetric* with `/closeout`'s teardown check. Inflow only needs to answer *"am I already isolated?"* — generic detection (toplevel ≠ primary) and the env-var hint each settle that. The outflow question — *"who owns teardown?"* — is stricter and cannot rely on the generic heuristic alone, because a pipeline-made worktree also satisfies toplevel ≠ primary; `/closeout` keys off the explicit setting or host env var only.

1. Check the current branch: `git branch --show-current`
2. If the current branch is the base branch (e.g., `main`, `prod`, `master`), create a new feature branch for this task.
3. If the current branch is a **different feature branch** (not the base branch and not a branch named for this task), you are on a stale branch from previous work. Do not commit new work here. **Exception:** if the current branch is a sibling slice branch named in this task's `Consumes from #N` declaration, you are intentionally about to fork from it for a stacked-PR slice — proceed. **Exception (host-provisioned):** if the stand-down check above fired, this branch is the host's isolated workspace branch — it is not stale; work in place.

**To create an isolated branch**, use one of these approaches (in order of preference):

- **Worktrunk** (if `wt` is available): `wt switch --create <branch-name>` — creates a new worktree + branch from the appropriate base and switches to it, giving full filesystem isolation. Use the `/worktrunk` skill for guidance.
- **Plain git**: `git checkout <base> && git checkout -b <branch-name>` — creates a new branch from the appropriate base in the current working directory.

The **appropriate base** is the repo's own base branch by default — whatever the repo declares (`git symbolic-ref refs/remotes/origin/HEAD --short | sed 's@^origin/@@'`). Do not assume `main`. For a slice with an unmerged `Consumes from #N` dependency that produces symbols this slice imports, branch from that sibling slice's branch instead so the stacked PR can target the sibling's PR (Hammant *Trunk-Based Development* Ch. 13: multiple PRs per story; the sibling's PR must still merge to the repo's base branch within 2 days).

Derive the branch name from the task: e.g., `issue-5-landing-page`, `landing-page`, or the issue slug. Do not reuse branch names from previous work.

**Enter the worktree as a session (when you created a worktree).** Creating the worktree is not the same as the session *running inside* it — `wt switch --create` resets the shell cwd back to the project root after each command, so without a further step the session stays anchored at the original checkout and the reported cwd lies about where work is happening. After creating the worktree, enter it with the harness `EnterWorktree` tool so the session's working directory genuinely *is* the worktree:

- Call `EnterWorktree { path: <absolute-worktree-path> }`. The path must already appear in `git worktree list` for this repo (it will, because you just created it). This persistently switches the session into the worktree.
- Keep the creation step exactly as above — `wt switch --create` / `git worktree add` runs the worktrunk `pre-start` hooks that seed `.env.local` and dependencies. `EnterWorktree` only switches the cwd; it does not run those hooks. Create first (to seed env/deps), then enter.
- This puts the knowledge in the world, not the head: the cwd tells the truth about where edits and commits land (a watching operator can see it), and there is no per-command `cd` prefix to forget — eliminating the slip class where one un-prefixed command writes to the wrong tree.
- The **Plain git** option (`git checkout -b`, no worktree) creates the branch in the current checkout — there is no worktree to enter, so skip `EnterWorktree` and work in place.

**AFK / headless fallback.** If `EnterWorktree` is unavailable (headless runs, AFK Ralph, cron), fall back to cwd-prefix discipline: the shell cwd resets to the project root after every Bash command, so prefix every Bash call in this session with `cd <absolute-worktree-path> &&`. Use this only when the harness tool is genuinely unavailable — it is the old workaround, retained for environments without the native mechanism.

This worktree's teardown is owned by `/closeout` at the pipeline tail — after the PR merges, `/closeout` re-anchors the shell to the base checkout, removes the worktree, and prunes the merged branch. `/execute` is the inflow side of the worktree lifecycle; `/closeout` is the outflow. Step 6 cleanup below removes only the `.tdd-*` markers — it deliberately does not remove the worktree.

**After creating the worktree, set it up.** A new worktree inherits tracked files but not git-ignored ones (`.env.local`, per-worktree deps, build caches). Two paths:

**Preferred — configure once via worktrunk hooks** (`.config/wt.toml` in the project):

```toml
[pre-start]
copy = "wt step copy-ignored"
install = "pnpm install"
```

`pre-start` hooks are blocking — the worktree is not reported ready until they finish. Use `pre-start` (not `post-start`) for both, because `post-start` runs in the background and subsequent commands that need `.env.local` or `node_modules` will race the hook. See `/worktrunk` for the full recipe. One-time per project.

**Fallback — manual setup for plain `git worktree add`** (no worktrunk):

- `cp <source-repo>/.env.local <worktree>/.env.local` (and any other git-ignored config the project uses).
- Run the project's install command (`pnpm install`, `npm ci`, `pip install -r requirements.txt`, etc.) from the worktree.

**Worktree setup checklist (DO-CONFIRM — perform each step, then verify before proceeding).** Applies regardless of how the worktree was created:

- [ ] Git-ignored config copied — `.env.local` (and any other `.env.*`, `*.local`, or project-specific ignored config) exists in the worktree
- [ ] Dependencies installed — install command (`pnpm install`, `npm ci`, etc.) ran without error in the worktree
- [ ] Session is inside the worktree — `pwd` reports the worktree path because you entered it via `EnterWorktree { path }` (not the project root). In the AFK/headless fallback only, this item instead means the `cd <absolute-worktree-path> &&` prefix is being applied to every Bash call
- [ ] `$CLAUDE_PROJECT_DIR` scoping correct — if the project references this env var in scripts, verify it resolves to the worktree path, not the primary repo
- [ ] **Local git hooks are installed and their manager is on `PATH`** — `ls "$(git rev-parse --git-dir)/hooks/" | grep -v '\.sample$'` lists something, and the manager the repo declares (`lefthook`, `husky`, `pre-commit`, …) resolves. Hooks live in `.git/hooks`, which is **per-worktree and untracked**, so a fresh worktree inherits none of them — and the failure is silent in the worst direction: every commit succeeds, and every guarantee the repo documents at commit time simply did not run. If the manager is absent, either install it (`lefthook install`) or record in the Step 6 review notes that local gates were inactive for this branch, so nobody reads a green local run as the merge gate
- [ ] TDD marker absent — `.claude/.tdd-active` and `.claude/.tdd-skipped` do not exist in the worktree (fresh slate; Step 3 creates them)
- [ ] **Post-review lock flags absent** — `.claude/.review-stamped` and `.claude/.fix-findings-active` do not exist. Both belong to the *previous* branch's review: `/pre-merge` Phase 4 writes the first, `/fix-findings` writes the second, and `/closeout` and `/fix-findings` respectively remove them at the end of that branch. A leaked `.review-stamped` refuses every implementation write on this slice before it starts; a leaked `.fix-findings-active` holds the lock open for the whole slice, which is the silent direction. Delete either one you find — you are at the start of a branch that has had no review, so neither can be describing this one

**Issue-shape detection gate.** If the task is a GitHub issue, verify it is a slice (implementation-ready), not an undecomposed PRD. Run `gh issue view <n> --comments` and check for a comment matching `^Decomposed into: #\d+`.

- If such a comment exists: proceed. The PRD has been decomposed; the operator is presumably working on one of its child slices (and should have supplied that slice's number, not the PRD's).
- If no such comment exists AND the issue body contains shaped-pitch markers (sections named `Appetite`, `Rabbit Holes`, `No-gos`, `User Stories`, or `Implementation Decisions`): halt. This is an undecomposed PRD. Invoke `/prd-to-issues <this-issue-number>` to produce implementation-ready slices, then restart `/execute` against one of the child slice issues.
- If multiple `Decomposed into:` comments exist, read the most recent; `/prd-to-issues` is responsible for ensuring only one is authoritative.

Skip this gate for one-off tasks not tied to a GitHub issue.

**Blocked-slice gate.** Still on the issue, confirm the slice is actually takeable before implementing it. Read the edges themselves rather than a summary count, which can be served stale right after a mutation:

```bash
gh issue view <n> --json blockedBy \
  --jq '{open_blockers: [.blockedBy.nodes[] | select(.state == "OPEN") | {number, title}],
         ever_wired: .blockedBy.totalCount}'
```

`open_blockers` empty means takeable — proceed. Any open blocker means **stop**: name the blocking issues to the user and let them decide whether to work the blocker first, or to override because the dependency is stale or irrelevant to this slice. Do not start implementing and discover the gap halfway in.

**Read `ever_wired` before trusting an empty list.** Empty has two causes: the slice genuinely has no open blockers, or the repo predates the edge wiring in `/prd-to-issues` §7 and has no edges at all. `totalCount` counts blockers in every state, so it separates them — `ever_wired > 0` means this slice *was* wired and its blockers have since closed, so the empty list is real. `ever_wired == 0` means no edge was ever written and the empty list proves nothing; if the issue body carries a prose `Blocked by #N` line, trust the prose and check those blockers' state by hand.

Note `state` here is the GraphQL enum — uppercase `OPEN`, not the REST endpoint's lowercase `open`.

Skip this gate for one-off tasks not tied to a GitHub issue.

**Ralph auto-detection gate.** Evaluate all three conditions:

- [ ] The task comes from a GitHub issue (not a one-off verbal request)
- [ ] The issue has multi-slice scope (PRD, big-batch appetite, or multiple user stories)
- [ ] No `ralph-once.sh` or `ralph.sh` exists in the repo root

If all three are true, invoke `/setup-ralph-loop` now. Do not proceed to Step 1 until Ralph setup is complete or the conditions are not met.

**Pipeline hooks gate.** The hook file existing is not the same as the hook carrying the post-review edit lock, and this gate tests both. A project that ran `/init-pipeline` before the post-review edit lock shipped carries a hook that never reads `.claude/.review-stamped`: the lock is inert there, and a `/fix-findings` fixer holding `.claude/.fix-findings-active` is refused anyway — by the classification clause, under a message that names `/tdd` and never names the route the fixer is standing on. Both halves fail silently, which is why an existence-only check is not enough: an inert lock looks from the outside exactly like a branch nobody edited after review.

```bash
HOOK="${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel)}/.claude/hooks/enforce-classification.sh"
if [ ! -f "$HOOK" ]; then
  echo "hooks-absent"
elif ! grep -q '\.claude/\.review-stamped' "$HOOK"; then
  echo "hooks-stale"
else
  echo "hooks-lock-present"
fi
```

`hooks-absent` and `hooks-stale` both mean **invoke `/init-pipeline` now**, and do not proceed to Step 1 until it reports. The first scaffolds enforcement hooks into a project that has none. The second re-scaffolds § 2's hook body over an existing install and re-runs § 6's `.gitignore` append, which that install never ran for the lock's two flags — without it both land as untracked files that can be committed, holding the lock shut or open across every future branch in that repo. `/init-pipeline` § 2 carries an existing `IMPL_PATTERNS` line through a re-scaffold rather than re-asking, so an upgrade does not reset a trigger surface the project customized. `hooks-lock-present` proceeds.

**What this gate cannot see, since its third verdict would otherwise read as a claim it does not make.** The term it greps for is the lock's own flag path, so it recognizes exactly one version boundary and reports which side of it an install is on. That is sound in one direction only. A hook with no `.claude/.review-stamped` term is provably pre-lock, so `hooks-stale` is right whenever it fires; but once a project has been upgraded the term is there forever, so every *later* change to `/init-pipeline` § 2's hook body also reports `hooks-lock-present` and is never distributed by this gate — including another one of exactly the kind the lock's own ordering fix was. The third verdict is therefore named for the term it found rather than for currency, which the check cannot establish. A later hook change owns its own distribution: give the boundary it introduces its own `elif` term above, in the commit that introduces it. This narrowness is declared here and not self-tested.

**TDD classification gate.** Step 3 requires classifying the work before writing any code. `/tdd` automatically creates `.claude/.tdd-active` via harness preprocessing when loaded (not LLM-dependent); visual frontend creates `.claude/.tdd-skipped`. A PreToolUse hook blocks all `.ts` file writes unless one of these markers exists. Step 6 removes both markers after commit.

**Trivial-task exception.** For single-commit cleanups unrelated to active feature work — typo fixes, dead code removal, comment-only changes, formatting-only changes, dependency version bumps without API surface changes — you may skip classification by creating `.claude/.tdd-skipped` directly. This exception applies only when **all** of the following are true:

- The task is not tied to an open GitHub issue, PRD, slice issue, or QA bug
- The task is not part of an active feature branch created for multi-slice work
- The change is expected to be a single commit (not a sequence of logical units)
- The change does not touch behavior — no new conditionals, no new state, no new exported symbols, no schema or migration changes

If any of these is false, go through the normal classification gate. When in doubt, use the gate — the cost of one extra `/tdd` invocation is lower than the cost of an unverified behavior change slipping through as "trivial."

**Assumptions validation gate.** If the task is a GitHub issue with an "Assumptions from Parent PRD" section, spend 60 seconds checking each listed assumption against current reality before proceeding. For each:

- Is the external service still available at the expected API and pricing tier?
- Does the parent PRD's approach still hold given what you now know?
- Are the packages this slice depends on still at compatible versions *and entrypoints*? A subpath swap (e.g. `pkg` → `pkg/http`, or any `pkg/<sub>` → `pkg/<other-sub>`) for a multi-runtime package is a runtime-affecting change disguised as a type-only diff — treat it as an assumption shift, not a free-pass type-equivalent edit.

If all assumptions still hold, proceed to Step 1. If any assumption has changed, stop and flag it to the user — this slice needs a targeted `/research` + mini-PRD cycle before execution, not a patch during implementation. Do not proceed with stale assumptions and attempt to work around them mid-execution.

Skip this gate entirely for one-off tasks without an "Assumptions from Parent PRD" section.

**Un-discharged feasibility check (advisory).** If the task's research artifact (archive file or spike issue) still carries `Uncertain` or `Speculative` assumptions whose verdicts are cheaply settled by 10 lines of throwaway code — does the library actually expose this, does the streaming path emit partial tags, does this format render where we need it — surface them now and suggest `/prototype` FEASIBILITY before main implementation. This is advisory, not blocking (per XP's *slack* principle); the user may have a reason to proceed and discover the answer mid-implementation. But the cost asymmetry is real (XP's *Defect Cost Increase*): a spike at this moment costs minutes, while the same assumption discovered mid-implementation costs hours of pivot. State the un-discharged assumptions explicitly and let the user decide. Skip this check for one-off tasks without a research artifact or when every assumption is already tagged `Verified` / `Refuted`.

**Consumes verification gate.** Only for issue-based slice work. If the task comes from a GitHub issue created by `/prd-to-issues`, and its `## Boundary Map` / `### Consumes` section references an already-closed upstream slice, spend 60 seconds verifying each listed symbol exists at the declared path in the current tree. This catches upstream boundary-map drift before implementation starts.

For each Consumes entry:

1. If it names a file path — check the file exists.
2. If it names a function, type, or exported symbol — grep for the export.
3. If it names a shape (e.g. "Effect Layer", "Zod schema", "React component", "Context provider") — confirm the *shape* matches, not just the name. A pure helper function does not satisfy a claim of "Effect Layer." A plain object does not satisfy a claim of "Zod schema."
4. If the Consumes entry names a typed symbol from a sibling slice (per `/prd-to-issues` Boundary Map guidance), confirm the consumer code derives its input type from the producer via `import type` (or the language's equivalent) rather than re-declaring the shape. A local re-declaration that happens to match the producer is a DRY violation that will silently drift when the producer evolves; the typed import is the structural fix that makes that drift class impossible.

If any Consumes symbol is missing or wrong-shaped, **stop**. The upstream boundary map is stale. Choose one of:

1. **Expand scope in this slice** to fill the gap. Note the expansion in the first commit's message, in the PR description, and file a post-hoc correction comment on the upstream closed issue so future slices don't trust the stale claim.
2. **Backtrack via `/correct-course`** to update the upstream boundary map and reshape the affected slices.
3. **File a new slice** for the missing work and block this one on it.

Do not silently absorb the gap — leave a breadcrumb for the next slice.

Skip this gate for one-off tasks, sibling slices still being planned, or issues without upstream `Consumes` entries.

This gate is scoped to intra-repo symbols (paths, exports, shapes). The mirror check for *externally-resolvable* declarations — package names, public API symbols, and pinned versions against the research snapshot — runs at `/pre-merge`'s Boundary Map Contracts dimension under "Spec-reality check." Step 0 sees the registry at slice-start; `/pre-merge` sees it at merge time. Both windows are intentional; do not widen this gate to duplicate the review-time check.

### 1. Understand the Task

Read any referenced plan, PRD, or GitHub issue. Explore the codebase to understand the relevant files, patterns, and conventions. If the task is ambiguous, ask the user to clarify scope before proceeding.

**Read the issue comment thread (issue-based work only).** When the task is a GitHub issue, read its comment thread before implementing — do not stop at the body. Step 0's issue-shape detection gate already ran `gh issue view <n> --comments`, so the thread is in context; reuse it rather than re-fetching. The comments are where the pipeline's continuation state lives: prior-iteration handoff notes (what was done, what remains, the exact error output a previous context window hit), plateau-stop notes naming what did *not* advance, post-hoc correction comments filed against this issue when an upstream boundary map drifted, and explicit human scope changes added after the issue was authored. In AFK Ralph loops this is load-bearing — iteration N+1 is designed to continue from what iteration N wrote into the thread, so skipping it re-derives or repeats work the previous iteration already explained.

**Precedence rule.** The issue body remains the durable contract. Comments augment it; they do not silently override it. A comment is an authoritative addition only when it is (a) a pipeline-authored continuation or correction comment, or (b) an explicit human scope change. Freeform discussion is context, never an override. If a comment appears to contradict the body on scope, and it is not a clear pipeline-authored correction or human scope change, flag the conflict to the user rather than acting on the comment.

**Disposal rule.** Classifying a comment is not the whole job — decide what happens to the part of the thread the body does *not* cover. This applies when this slice's PR will close the issue (`Closes #N`). The body is this pipeline's baseline: acceptance criteria live there, `/prd-to-issues` decomposes bodies, `Closes #N` closes on a body's terms. A capability that stays in a comment is outside every one of those mechanisms, so the close silently discards it — and the loss emits no signal, because the issue closes green and the PR merges clean.

The discriminator is a single test, and it is **not** "is the idea good": **can you name the consumer?** If you can point at the issue, slice, PRD, or shipped code that would use the capability, it qualifies. If you cannot — a design musing, a "we might want," an approach the author was thinking aloud about with no identified caller — it does **not** qualify and must not be promoted; promoting it manufactures scope and invents dependencies. When in doubt, it does not qualify.

For a comment that does qualify, surface it to the user before finishing the slice and offer the two disposals:

1. **Promote it into the body** — add it to this issue's acceptance criteria and build it in this slice, when it is genuinely the same seam and the appetite absorbs it.
2. **File its own issue** with a `Blocks #N` link naming the consumer you identified — when it is real work that belongs elsewhere.

Either one gives the capability an owner that survives the close. Do not silently absorb it, do not widen scope unilaterally, and do not implement it just because you noticed it — the choice is the user's. On AFK runs there is no user to ask, so default to filing the follow-up issue with the `Blocks #N` link; promotion into the body widens the slice without approval.

Skip this read — and the disposal rule with it — for one-off tasks not tied to a GitHub issue (the same scope guard Step 0 uses).

**Read the research artifact for this feature.** The PRD's "Research Reference" section names where it lives — one of two locations depending on the project's `research.storage` mode:

1. **Spike-issue mode** — the PRD references a closed `research`-labeled GitHub issue (`Refs #<spike-issue-number>`). Read it with:
   ```bash
   gh issue view <spike-issue-number>
   ```
   This works on any machine — fresh clones, CI sandboxes, recovered laptops, or contributor environments.

2. **Archive mode** (default) — the PRD references `~/.claude/research/<repo-slug>/<feature-slug>-<YYYY-MM-DD>.md`. Read the file directly. If you are running on a machine other than the one that produced the research, the file will not exist; flag this to the user and either re-run `/research` or proceed with explicit acknowledgment of the missing context.

Some legacy PRDs may still reference `research.md` in the repo root or `plans/` — read it if present. Whatever the location, the research artifact contains cached technical research that should inform your approach. Do not re-research what has already been decided.

**Read the slice's `### Context` block before the grep below (issue-based work only).** When the slice issue's `## Boundary Map` carries a `### Context` subsection, read its anchors, gotchas, and research pointer *first*. `/prd-to-issues` wrote that block so this session would not have to re-derive it: the anchors name the existing files to read or imitate, and the research pointer goes straight to the artifact instead of walking the parent PRD to find it. Reading it is not optional — a block that is written and never preferentially read is not neutral overhead, it is a section readers learn to skip, which taxes the Boundary Map around it.

Treat it as pointers, not truth. The anchors were written at decomposition time and siblings may have merged since; the code and the research artifact still win on any conflict, per the precedence rule below. A stale anchor is a correction to file on the issue, not a reason to skip the block.

Consult `docs/solutions/` for relevant past solutions before starting implementation:

```bash
grep -rl "relevant-keyword" docs/solutions/ 2>/dev/null
```

If past solutions exist for this problem domain, incorporate their lessons and avoid their documented pitfalls.

**Artifact precedence:** When the research artifact and `docs/solutions/` give conflicting guidance, follow the research artifact — it was verified against the current installed versions. Storage location does not affect trust: a spike issue and an archive entry carry equivalent authority. If the conflict is significant enough that you are uncertain, flag it to the user before proceeding. Load `docs/solutions/` selectively: grep for relevant keywords first, then read only matching files.

### 2. Plan the Implementation (optional)

If the task has not already been planned, create a plan for it. If the GitHub issue includes boundary maps (Produces/Consumes sections), use them to understand the interfaces you need to implement or code against.

### Stack-Specific References

Before implementing, check the project's stack and load relevant best practices.

- **Next.js / React projects**: If `package.json` includes `next` or `react`, load these skills before writing code:
  - `/vercel-react-best-practices` — performance optimization and React Server Component guidance
  - `/vercel-composition-patterns` — component composition patterns that scale without prop sprawl
  - `/next-best-practices` — file conventions, data patterns, metadata, and error handling
  - `/next-cache-components` — cache components, `use cache`, `cacheLife`, and `cacheTag`

### 3. Implement

**STOP — classify before writing any code:**

- [ ] **Backend code** → invoke `/tdd` now (creates `.claude/.tdd-active`)
- [ ] **Behavior-heavy frontend** (reducers, state machines, validation, accessibility, interaction regressions) → invoke `/tdd` now (creates `.claude/.tdd-active`)
- [ ] **Visual/layout/styling/copy frontend** → run: `mkdir -p .claude && touch .claude/.tdd-skipped`

A PreToolUse hook blocks all `.ts` file writes unless one of these markers exists. Do not write implementation code until you have classified the work.

If `/tdd` is not available, follow this minimum discipline:

1. Write a single failing test for the smallest vertical slice of behavior
2. Run the test — confirm it fails (red)
3. Write the minimum code to make it pass (green)
4. Repeat from step 1 for the next slice of behavior
5. Refactor if needed while keeping tests green

Do not write all tests upfront — write one, make it pass, then move to the next.

**[TypeScript projects] Library callback returns.** When a logical unit implements a callback the library asks the application to provide (agent hooks, middleware, proxy, tool handlers, render props, lifecycle methods), anchor the returned value to the library's declared return type with `satisfies LibraryReturnType`, a fresh object literal, or a derived type (`ReturnType<typeof …>`). Never return a typed local variable — TypeScript's excess-property check does not run on returns of typed values, so fields the library's signature does not declare are silently dropped at runtime. See `/tdd` Refactor step for the full rationale; if the research artifact (archive file or spike issue) carries a Library Callback Contracts snapshot (`/research` Phase 1.25), use its accepted-fields list as the pinned source.

**Comment the code, not the incident.** A comment you write here carries the *current* why — what this code does, and why it is shaped this way. The incident that led you here goes to the commit message and the PR body instead: what the prior behavior was, which earlier attempt this supersedes, what you rejected on the way. Before committing a unit, reread the comments you added to it and move any sentence that explains history rather than code.

#### Commit after each logical unit

Do not accumulate all changes into one commit. Commit after each self-contained unit of progress. A logical unit is the smallest change that leaves the codebase in a working state — typecheck passes, tests pass, nothing is half-wired. Examples:

- One red-green-refactor TDD cycle (test + implementation for one behavior)
- A new module, type, or schema with its tests
- A wiring change (route registration, dependency injection, config)
- A refactor that improves structure without changing behavior
- A migration or seed file
- A cross-file type or interface refactor whose intermediate per-file steps would leave typecheck broken — the whole ripple is one logical unit

After completing each logical unit:

1. Run `pnpm run typecheck` and `pnpm run test` (or the project's equivalent). Fix any failures before committing.
2. Stage only the files for that unit — do not stage unrelated changes.
3. Commit with a message that says what this unit accomplished, not "WIP" or "progress". When the unit corrects earlier behavior, write the incident history the paragraph above routes here — and put it in the PR body as well, not the commit message alone. A squash merge collapses these per-unit messages into one, and `/closeout` treats squash as the common convention, so the commit message alone is not a durable destination. The PR body is the copy that survives intact for a reader running `git blame` months later.

If a unit touches both a test and its implementation, they belong in the same commit. If a refactor was triggered by the unit but is conceptually separate, commit the refactor separately.

### 4. Verify

**"All steps done" is NOT verification. Check the actual outcomes.**

By this point, each logical unit has already been committed with passing typecheck and tests. Step 4 is the full-slice verification pass — confirming the whole feature works end-to-end, not just that individual units pass.

Run the full feedback loops one final time:

```
pnpm run typecheck
pnpm run test
```

Fix any issues. If fixes are needed, commit them as a separate commit (e.g., "fix integration between X and Y").

Then apply the verification ladder — use the strongest tier you can reach:

#### Tier 1: Static Verification
- Files that should exist actually exist
- Exports are present (not just declared but actually exported)
- Imports between modules are wired correctly (not importing from a path that doesn't resolve)
- Implementation is substantive (not stubs, not console.log placeholders, not TODO comments where real code should be)

**Deletion Completeness (when this slice's diff deletes or renames a module).** Read the trigger off the diff, which you already have, rather than off a section header nothing in the pipeline writes:

```bash
BASE_BRANCH=$(git symbolic-ref refs/remotes/origin/HEAD --short 2>/dev/null | sed 's@^origin/@@')
if [ -z "$BASE_BRANCH" ]; then
  for candidate in main master prod develop trunk; do
    if git rev-parse --verify "$candidate" >/dev/null 2>&1; then BASE_BRANCH=$candidate; break; fi
  done
fi
# A name is not a ref. $BASE_BRANCH names the branch (for `--base`, `git switch`);
# $BASE_REF points at it, and is the only thing safe as a range endpoint.
if git rev-parse --verify "origin/$BASE_BRANCH" >/dev/null 2>&1; then
  BASE_REF="origin/$BASE_BRANCH"
else
  BASE_REF="$BASE_BRANCH"
  echo "note: origin/$BASE_BRANCH does not resolve — measuring against the local branch, which may be stale" >&2
fi
git diff --diff-filter=DR --name-status "$BASE_REF...HEAD"
```

**Residual:** `$BASE_REF` is only as fresh as the last `git fetch`, and on a triangular fork (or a remote not named `origin`) `origin/$BASE_BRANCH` may be absent or track your fork rather than upstream — the `else` branch then falls back to the local branch, which is the stale-ref behavior this guard exists to avoid. It says so on stderr rather than falling back silently, because a plausible wrong answer with no signal is what let this defect live for five months. If the counts look wrong, `git fetch` and re-run, or set `BASE_REF` by hand.

Deleted paths print as `D<TAB><path>`, renames as `R<score><TAB><old><TAB><new>`. Any output at all fires the rung; empty output skips it. Gate on the output, not the exit status — the command exits 0 either way. A `### Deletes` section in the slice body is an optional hint that names which surfaces to sweep; it is not the trigger.

For each deleted or renamed module, enumerate its external consumer surfaces — the symbolic names callers were taught to emit for it to consume, beyond its exports. Typical surfaces:

- DOM data-attributes the module read (`data-*`)
- CSS class names and selectors the module applied or queried
- Global or custom event names (`addEventListener('foo-bar')`, `dispatchEvent(new CustomEvent('foo-bar'))`)
- `window`, `localStorage`, or `sessionStorage` keys
- Route names, config keys, or feature-flag names the module owned

Infer surfaces from the module body as it existed before deletion (`git show <base>:<path>`, or the `Deletes` hint notes when the slice body happens to carry them). Grep the merged tree for each surface across every source-text file type the project uses — templates, source code, styles, config, docs. Do not restrict to a fixed extension list; the relevant surfaces depend on the stack (`.py`/`.rb`/`.go`/`.rs` for imports, `.vue`/`.svelte`/`.astro`/`.tsx` for templates, `.css`/`.scss`/`.sass`/`.less`/`.styl` for styles, `.yml`/`.toml`/`.json` for config, `.md`/`.mdx` for docs that ship). Zero matches required to pass. Non-zero matches: restore the module, migrate the consumers, or declare them as intentionally inert and track the cleanup as a follow-up slice. Imports alone are the narrowest possible definition of "consumer"; the surface may be wider.

**Upstream shape sweep.** After the consumer-surface sweep above, list each export touched on a shared module in this slice (context fields, builder return-type fields, interface or type members, schema fields, exported map or record entries). For each such export, grep the post-delete tree for non-self-reference reads. Zero matches required to pass. Non-zero matches: confirm the readers are live and intentional. Zero matches: drop the export in the same PR — the migration window closes the moment the legacy consumer is deleted, and a retained-but-unread export widens the import contract so a future cleanup becomes a breaking change rather than a silent removal. Dead-export linters (`knip`, `ts-prune`, TypeScript `noUnusedLocals`) cover many shapes of this but not exported context, interface, or schema fields — those are read by the type itself and look live to

…(truncated)
