---
name: local-implementation
description: >-
  Internal routed strategy behind `dev-loop` for local phase-bounded
  implementation. Use it when authoritative startup/resume routing selects the
  `local_implementation` strategy so the child agent can own phase planning,
  artifact discipline, test-first implementation, and local validation in fresh
  context.
compatibility: Skill for git-based repositories with Node.js/npm and optional subagent support.
allowed-tools: read bash edit write subagent review_loop
user-invocable: false
---

# Local Implementation

Canonical owner for the internal `local_implementation` route behind the public `dev-loop` façade.

Use it only after the public dispatcher has already resolved `selectedStrategy: local_implementation`. This skill owns the local phase procedure and artifact discipline for that route; it does not redefine the shipped runtime semantics of helper CLIs, shared loop logic, or extension commands.

Read the authoritative public routing contract at [Public Dev Loop Contract](../docs/public-dev-loop-contract.md) and keep any repository-specific decisions grounded in [Project Plan](../../PLAN.md), durable phase docs, source, tests, config, and actual validation commands.
For UI validation under `dev-loop`, see [UI Validation Contract](../docs/ui-validation-contract.md), [UI Smoke Harness](../docs/ui-smoke-harness.md), [UI Artifact Contract](../docs/ui-artifact-contract.md), and [UI Designer Review Loop](../docs/ui-designer-review-loop.md) (designer + `uiReviewMode: vision`).

## Minimal required project inputs

For a new project, the only required inputs are:

1. [Project Plan](../../PLAN.md)
2. [this skill file](./SKILL.md)

Everything else is optional and may be bootstrapped by this skill.

## Required startup reads

Read the canonical entrypoint briefing first: [Entrypoint Strategies](../docs/entrypoint-strategies.md#local-implementation). Then read only what the current step needs:

- [Agent Instructions](../../AGENTS.md) (repo constitution)
- [Public Dev Loop Contract](../docs/public-dev-loop-contract.md)
- [Retrospective Checkpoint Contract](../docs/retrospective-checkpoint-contract.md) (when async state applies)
- [Project Plan](../../PLAN.md) and phase/tracker docs when relevant
- Relevant issue/PR, validation surface, and task files

Treat missing optional files as normal bootstrap conditions, not errors.

### Tracker-backed local implementation

Local implementation supports these spec-of-record inputs. The first two are durable/committed artifacts; the third is a spec-of-record that is NOT a durable committed artifact:

Durable/committed spec artifacts:

- phase-doc-backed local sessions ([Phase Plan](../../docs/phases/phase-x.md) is canonical)
- tracker-backed local sessions (the tracker issue is canonical)

Non-durable spec-of-record (no committed plan artifact):

- lightweight PR-body-as-spec sessions (`--lightweight`): the resolver output carries `canonicalSpecSource: pr_body` and the derived handoff envelope carries `specSource: pr_body`. The PR description is the spec-of-record; no phase/plan doc is minted or committed. The gate sequence matches the phase-doc path. See [Artifact Authority Contract](../docs/artifact-authority-contract.md) "Lightweight (PR-body-as-spec)".

Tracker-backed local implementation stays inside the existing `local_implementation` path and adds no routing mode. For sub-issue tree decomposition, see [Sub-Issue Tree Contract](../docs/sub-issue-tree-contract.md).

When the local spec already lives in a tracker issue:

- resolve the tracker reference deterministically from a GitHub issue URL or explicit `<owner/name>` + issue number
- use the bounded GitHub helper `scripts/github/resolve-tracker-local-spec.mjs` when you need a machine-readable spec bundle
- treat the tracker issue title/body/url/state as the durable local spec bundle
- the no-duplicate-phase-doc rule is owned by `ARTIFACT-TRACKER-FIRST-NO-DUP` in [Artifact Authority Contract](../docs/artifact-authority-contract.md); do not read [Phase Plan](../../docs/phases/phase-x.md) for that same tracker-backed session either
- sync durable scope / acceptance / status changes back to the tracker issue rather than maintaining a duplicate local phase doc
- keep `tmp/` as temporary local execution state only; it does not become a second durable spec surface
- for tracker-backed sessions, the handoff path is always: push the working branch → open a PR → merge via GitHub
- <!-- rule: LOCAL-PR-CREATE-CANONICAL --> for tracker-backed sessions, you MUST open PRs through the canonical `node <dev-loops-package-root>/cli/index.mjs pr create` path — always draft and always assigned — self-assigned by default (`--assignee @me` when none is given; honors an explicit `--assignee <login>` / `-a <login>`) — and MUST NOT open them via raw `gh pr create`. Author the PR body from the canonical conformant skeleton at [PR Body Skeleton](../dev-loop/templates/pr-body.md): a tracker-backed body MUST carry Objective, In scope, Acceptance criteria + Definition of done checklists, an explicit Non-goals section, and a `Closes #N` (or `Fixes #N`) reference for the linked issue so GitHub auto-closes it on merge. The `validate-pr-body-spec` contract runs at both ends: `node <dev-loops-package-root>/cli/index.mjs pr create` fails closed at create time on a non-conformant body, like the ready-for-review boundary. When `.devloops` sets `workflow.requireDraftFirst` to true, use `node <dev-loops-package-root>/cli/index.mjs pr create --assignee @me ...`. The always-draft creation mechanism is owned by [`OPS-DRAFT-FIRST-PR`](../docs/copilot-loop-operations.md): `create-pr.mjs` is draft-only regardless of the toggle, and the toggle governs whether the draft-gate boundary is enforced before ready.
- <!-- rule: LOCAL-TRACKER-NO-DIRECT-MERGE --> `LOCAL-TRACKER-NO-DIRECT-MERGE`: for tracker-backed sessions, agents MUST NOT suggest a direct local-main merge and MUST NOT merge the working branch into local `main` at phase completion

## Primary execution rules

### Step 0: Pre-flight gate (mandatory for local_implementation)

<!-- rule: LOCAL-PREFLIGHT-GATE-MANDATORY -->
For the `local_implementation` strategy, before any planning or implementation mutation, you MUST run the pre-flight gate:

```sh
node <dev-loops-package-root>/cli/index.mjs loop pre-flight-gate --expected-branch <working-branch> --check-subagents
```

(source-repo fallback: `node scripts/loop/pre-flight-gate.mjs --expected-branch <working-branch> --check-subagents`)

Before creating or reusing a worktree for local implementation, use the canonical lifecycle entrypoint (`WORKTREE-CREATE-PROVISION`, see [Worktree usage guidance](../docs/worktree-guidance.md#create-or-reuse--provision-ensure-worktreemjs)):

```sh
node <dev-loops-package-root>/cli/index.mjs loop ensure-worktree --repo-root <main> --issue <n>
```

(source-repo fallback: `node scripts/loop/ensure-worktree.mjs --repo-root <main> --issue <n>`)

This validates worktree isolation (the checkout's `node_modules/@dev-loops/core` resolves to its own `packages/core`; `tmp/worktrees/` is the recommended default, not the enforced condition) and branch identity (current branch matches the working branch). `--check-subagents` is advisory: it reports subagent availability and fails open. If the gate fails, **stop and fix the violation** before proceeding; do not bypass it in normal workflow execution.

This preflight gate applies only to `local_implementation`. Other routed strategies retain their own execution rules and the isolation requirements in [Worktree Guidance](../docs/worktree-guidance.md); absence of this preflight never authorizes editing an arbitrary checkout. The development-only bypass (`DEVLOOPS_PREFLIGHT_BYPASS=1`) exists for testing the gate itself and MUST NOT be used in production workflow runs.

## Narrow failure-triage fast path

<!-- rule: LOCAL-FAILURE-TRIAGE-ORDER -->
When resuming local implementation with dirty work or an observed failing command, you MUST follow this ordered path before broad discovery:

1. run startup once from the relevant worktree/context
2. inspect current state with `git status` and the changed files
3. reproduce or identify the failing command
4. run an exact-pattern search in changed files for the suspect call site
5. patch the minimum call sites
6. run focused smoke checks for that failure
7. run default verification

Follow [Anti-patterns](../docs/anti-patterns.md) for the general tooling-internals and duplicate-broad-search prohibition; this local fast path owns only the ordered failure-triage procedure above.

### Step 1

- <!-- rule: LOCAL-PHASE-ONE-AT-A-TIME --> You MUST implement **one phase at a time** and MUST NOT refine later phases in detail before the current phase is complete.
- Use the `refiner` agent for phase-refinement work when subagents are available; escalate RFC-worthy technical decisions to the parent session / human operator.
- <!-- rule: LOCAL-TEST-FIRST-COVERAGE --> You MUST work **test-first** for all non-trivial logic; coverage thresholds are owned by [VALIDATE-COVERAGE-THRESHOLD](../docs/validation-policy.md).
- Log detailed iteration artifacts under `tmp/` using the required structure below.
- Spec-of-record split (phase-doc-backed vs. tracker-backed vs. lightweight): see [Tracker-backed local implementation](#tracker-backed-local-implementation) above.
- When a phase changes durable product truth in ways `PLAN.md` should express (for example command surface, accepted product decisions, resolved open questions, or scope changes), update [Project Plan](../../PLAN.md) before closing the phase.
- Branch, commit, pre-approval-gate, and finalization mechanics: see [Branch / review / merge policy](#branch--review--merge-policy), [Commit policy](#commit-policy), and [Implementation loop for the phase](#implementation-loop-for-the-phase) below.
- When subagents are used, log what each subagent was asked to do and what it concluded.
- If [Project Plan](../../PLAN.md) is too rough or ambiguous to safely start the current phase, do not guess: run a clarification/interview step with the user first.

## Structural quality

Apply [Structural Quality](../docs/structural-quality.md) from the `deep` review angle.

<!-- rule: LOCAL-COMMENT-DISCIPLINE -->
`LOCAL-COMMENT-DISCIPLINE`: Comments describe current invariants, constraints, fail-closed/security rationale, calibration knobs, or external contracts. They MUST NOT narrate agent moves, restate acceptance criteria, or carry issue/PR numbers (including historical or authoritative-reason references). Cite a load-bearing contract by name, path or rule ID instead. `scripts/loop/check-comment-discipline.mjs` fails closed on added runtime-source comment lines containing `#NNN`; it excludes the existing backlog. A genuinely load-bearing exception requires inline `comment-discipline:allow`.

## Light mode (small changes)

<!-- rule: LOCAL-LIGHT-MODE-CONFIG-SURFACE -->
`localImplementation.lightMode` (`.devloops` field; this repo sets `maxLines: 40`, `maxFiles: 2`) is this skill's config surface for light-mode gate dispatch. Gate-collapse mechanics, escalation, and dispatch resolution (`resolveGateDispatchMode`, `scripts/loop/resolve-gate-dispatch.mjs`) are owned by [Light-mode inline acceptance](../docs/gate-review-sub-loop-contract.md#light-mode-inline-acceptance-under-threshold-micro-prs); this skill MUST NOT redefine them.

Use `scripts/loop/detect-change-scope.mjs` to determine scope:
```sh
node scripts/loop/detect-change-scope.mjs
```

## Deterministic logging structure

Treat the workflow as three layers:
- [Project Plan](../../PLAN.md) = strategic product and architecture truth
- [Phase Plan](../../docs/phases/phase-x.md) or the canonical tracker issue = durable per-phase plan and acceptance criteria for the active local session
- `tmp/` = temporary local execution audit trail and machine-friendly continuation state

Maintain the core paths below while the phase is active locally, and create optional artifacts only when they are actually used:

Core paths:
- for phase-doc-backed local sessions: [Phase Plan](../../docs/phases/phase-x.md)
- `tmp/phases/index.json`
- `tmp/phases/phase-x/manifest.json`
- `Variant A` (`tmp/phases/phase-x/variant-a.md`)
- `Variant B` (`tmp/phases/phase-x/variant-b.md`)
- `Merged Plan` (`tmp/phases/phase-x/merged-plan.md`)
- `Phase Review` (`tmp/phases/phase-x/review.md`)
- `Phase Summary` (`tmp/phases/phase-x/summary.md`)
- `Retrospective` (`tmp/phases/phase-x/retrospective.md`)

Optional when used:
- `Variant C` (`tmp/phases/phase-x/variant-c.md`)
- `tmp/phases/phase-x/subagents/`
- `tmp/phases/phase-x/subagents/raw/`
- `tmp/phases/phase-x/bash-exit-1.jsonl`
- `Clarification Log` (`tmp/phases/phase-x/clarification.md`)
- in dev mode: `tmp/phases/phase-x/dev-mode-context.json`
- in dev mode: `Dev Mode Review` (`tmp/phases/phase-x/dev-mode-review.md`) as optional analytical notes when they help shape the retrospective
- in dev mode: `Dev Mode Retrospective` (`tmp/phases/phase-x/dev-mode-retrospective.md`)
- in dev mode: `Dev Mode Skill Changes` (`tmp/phases/phase-x/dev-mode-skill-changes.md`)

Use the templates in `../dev-loop/templates/` (the sibling `skills/dev-loop/templates/` directory in this repo).

Use deterministic helper scripts from `../dev-loop/scripts/` (the sibling `skills/dev-loop/scripts/` directory in this repo; in installed-skill layouts these live at `../dev-loop/scripts/` relative to this skill file, not inside this skill's own directory) for repeatable support tasks such as phase initialization, phase-file updates, template materialization, bash-exit logging, and dev-mode context collection.

## Bootstrap missing support files

If these files are missing, create them from the `../dev-loop/templates/` directory before continuing:

- missing [Agent Instructions](../../AGENTS.md) -> create from [Bootstrap Agents Template](../dev-loop/templates/bootstrap-agents.md)
- missing [Implementation State](../../docs/IMPLEMENTATION_STATE.md) -> create from [Bootstrap Implementation State Template](../dev-loop/templates/bootstrap-implementation-state.md)
- missing [Implementation Workflow](../../docs/IMPLEMENTATION_WORKFLOW.md) -> create from [Bootstrap Implementation Workflow Template](../dev-loop/templates/bootstrap-implementation-workflow.md)
- missing [Phase Plan](../../docs/phases/phase-x.md) for the active phase -> create from [Phase Doc Template](../dev-loop/templates/phase-doc.md)
- missing `tmp/phases/index.json` -> create or reinitialize it

The bootstrap files are support infrastructure; the layers in [Deterministic logging structure](#deterministic-logging-structure) stay authoritative. For tracker-backed sessions, do not bootstrap a duplicate local phase doc.

For bootstrap/setup phases, do not mark the phase `completed` or `awaiting-finalization` until the expected durable support files for the chosen workflow contract actually exist in the repository. Temporary `tmp/` execution artifacts do not need to be committed.
## Plan sufficiency check

Before phase planning, check whether [Project Plan](../../PLAN.md) contains enough information to proceed safely.

At minimum, the current phase needs enough information to infer:
- the goal of the phase
- the main constraints
- the intended scope or boundaries
- at least rough acceptance criteria or success shape

If that information is missing or too ambiguous, pause implementation and run a clarification/interview step.

## Clarification / interview step

When the plan is insufficient, use one of these modes:

### Mode A — interactive clarification
- ask only the missing high-value questions needed to safely refine the current phase
- prefer a short interview or wizard-style sequence over one giant question dump
- record the answers in `Clarification Log` (`tmp/phases/phase-x/clarification.md`)
- update [Phase Plan](../../docs/phases/phase-x.md) with clarified durable phase intent, scope, or acceptance criteria
- update [Project Plan](../../PLAN.md) only if the clarified information is durable product/project truth beyond the current phase
- update [Implementation State](../../docs/IMPLEMENTATION_STATE.md) if the clarification changes the next phase boundary

### Mode B — auto clarification
Use this when the user explicitly asks for an auto option, says to just proceed, or is clearly optimizing for speed over discussion.

In auto mode:
- infer the smallest safe defaults for the current phase only
- prefer conservative assumptions over ambitious ones
- never auto-resolve product, security, or architecture decisions that could materially change scope
- write all assumptions to `Clarification Log` (`tmp/phases/phase-x/clarification.md`)
- mark them clearly as `auto-assumptions`
- surface the assumptions in the phase plan audit so they can be challenged later
- if an assumption is too risky to make safely, stop and ask the user anyway

Do not begin fan-out planning until the current phase is sufficiently specified, either by user clarification or safe auto-assumptions.

## Determine where to resume

Read [Implementation State](../../docs/IMPLEMENTATION_STATE.md) and identify the next unfinished phase.
Read [Phase Plan](../../docs/phases/phase-x.md) for that phase if it exists.

If `tmp/phases/index.json` exists locally, use it as a fast index for prior artifacts.
If the durable phase doc, the state file, and the tmp index disagree, trust docs first and note the mismatch in the phase plan audit log.

If the state file is ambiguous, resolve ambiguity conservatively:
- prefer the earliest clearly unfinished phase
- do not skip ahead
- note the ambiguity in the phase plan audit log under `tmp/`
- if this is a first-run bootstrap, start from the earliest phase implied by [Project Plan](../../PLAN.md)

## Phase planning loop

For the **current phase only**, run this loop before implementation.

### 1. Create or update the durable phase doc and tmp scaffold

**Lightweight (PR-body-as-spec) exception:** for a lightweight session ([Tracker-backed local implementation](#tracker-backed-local-implementation); started via `resolve-dev-loop-startup.mjs --issue <n> --lightweight`), SKIP the durable phase-doc mint entirely. Do NOT create or commit any `docs/phases/*.md` for this session. The ephemeral `tmp/phases/` scaffold may still hold local execution state. All other steps proceed unchanged.

For tracker-backed sessions, update the canonical issue instead; `ARTIFACT-TRACKER-FIRST-NO-DUP` forbids minting a duplicate phase doc. Create or update the durable phase doc only for phase-doc-backed sessions.

Use paths like:
- `docs/phases/phase-0.md`
- `tmp/phases/phase-0/`
- `docs/phases/phase-1.md`
- `tmp/phases/phase-1/`

Create or update:
- [Phase Plan](../../docs/phases/phase-x.md)
- `tmp/phases/phase-x/manifest.json`
- `tmp/phases/index.json`

Prefer the deterministic helper:
- `../dev-loop/scripts/init-phase.mjs`

Use `../dev-loop/scripts/phase-files.mjs` only when you need a narrower manifest/index update without regenerating the standard phase-planning scaffold.

### 2. Read the previous phase's learning before planning the next one

If a previous phase exists, read:
- its `summary.md`
- its `retrospective.md`
- any relevant subagent summaries

Use those lessons to improve the current phase plan.

### 2b. Optional bounded refinement audit

Before variant fan-out, optionally run one bounded audit when the active phase would benefit from slop-risk discovery, structural drift discovery, or adjacent cleanup discovery.

When used:
- run one bounded audit before variant fan-out
- write the audit artifact to `tmp/phases/phase-x/audit/refinement-audit-summary.json`
- use `node scripts/loop/run-refinement-audit.mjs --paths ... --output tmp/phases/phase-x/audit/refinement-audit-summary.json`
- pass a concise audit summary into every refiner briefing
- keep the audit opt-in; do not turn it into a mandatory precondition
- preserve prioritized findings, the highest-value follow-up candidates, and an explicit statement of what this phase will not rewrite or broaden in the merged plan and review artifacts

### 3. Fan out short plan variants

Write 2-3 short variants:
- `Variant A` (`tmp/phases/phase-x/variant-a.md`) = smallest safe implementation
- `Variant B` (`tmp/phases/phase-x/variant-b.md`) = best practical UX/developer-experience option within phase scope
- `Variant C` (`tmp/phases/phase-x/variant-c.md`) = safest boundary/risk-reduction option when useful

When subagents are available, the default refinement path should use the `refiner` role and **parallel fresh-context subagents**, one per variant.

Each refiner variant should make room for:
- explicit non-goals
- complete acceptance criteria
- a complete definition of done
- risks and unresolved questions
- when a bounded audit artifact exists: prioritized findings, highest-value follow-up candidates, and what the phase will not rewrite or broaden
- RFC escalation notes when technical decisions should go to the parent session / human operator
- for watcher/predicate-heavy phases: explicit negative-case tests and timeout semantics, including any zero-timeout or single-check contract; verify the recommended watcher CLI, supported timeout flags, and mutation-capable preflight against source before drafting a reduced-read procedure

Use the template in [Phase Variant Template](../dev-loop/templates/phase-variant.md).

Also include the phase's scope, touched files/modules, tests to write first, and implementation order.

When a phase includes a bounded audit, inventory, or scan:
- treat the scan as a first-class deliverable rather than an implicit side note
- require prioritized findings, not an unbounded dump
- state explicitly what the scan does **not** authorize or rewrite in the current phase

If subagents generate the variants:
- give each variant generator a concise briefing summary that includes phase objective, in-scope work, constraints, known risks, and required outputs
- keep each `variant-a` / `variant-b` pair anchored to one persona or refinement angle so the alternatives are directly comparable
- when you want broader hardening, add another fan-out pass with a different persona or angle and its own `variant-a` / `variant-b` pair instead of blending multiple personas into one pair; merge across the resulting passes
- do not fork the parent session just to share planning context; summarize it instead
- save raw subagent outputs under `tmp/phases/phase-x/subagents/raw/` only when keeping the raw capture is actually useful
- then write the human-oriented `Variant A` (`tmp/phases/phase-x/variant-a.md`) / `Variant B` (`tmp/phases/phase-x/variant-b.md`) / `Variant C` (`tmp/phases/phase-x/variant-c.md`) files from those raw outputs when applicable

Update `manifest.json` with the planned artifact list and current status.

### 4. Fan in to a merged phase plan

Write:
- `Merged Plan` (`tmp/phases/phase-x/merged-plan.md`)
- update [Phase Plan](../../docs/phases/phase-x.md) with the selected durable phase plan

Use the templates in [Merged Phase Plan Template](../dev-loop/templates/merged-phase-plan.md) and [Phase Doc Template](../dev-loop/templates/phase-doc.md).

The merged plan must include:
- exact scope for this phase
- explicit non-goals
- tests to write first
- implementation order
- validation steps
- acceptance criteria
- definition of done
- when a bounded audit artifact exists: prioritized findings, highest-value follow-up candidates, and an explicit statement of what this phase will not rewrite or broaden
- RFC escalation notes for any RFC-worthy technical decisions that must go to the parent session / human operator instead of being silently resolved during refinement; accepted decisions are persisted as ADRs per the [Decision record contract](../docs/decision-record-contract.md)
- for any new CLI surface: explicit success-output and malformed-argument/error-contract expectations
- for any watcher/predicate-driven behavior: explicit timeout semantics plus negative-case detection rules for non-target identities or events
- for package-first phases in a source-loaded workspace: explicit expectations about whether callers consume shared logic through workspace/source adapters or published package import paths during local development

The durable phase doc should capture the subset that a fresh human or agent should read first: objective, why now, scope, non-goals, acceptance criteria, definition of done, validation approach, durable decisions, and open questions.

### 5. Review the merged phase plan adversarially

Produce one local planning artifact in this session, not a multi-reviewer fan-out or lifecycle-gate evidence. Do not dispatch reviewer subagents here. The review template's PR gate structure belongs to the later `draft_gate` / `pre_approval_gate`, not this step.

Write:
- `Phase Review` (`tmp/phases/phase-x/review.md`)

Use the template in [Review Template](../dev-loop/templates/review.md).
Ensure the durable phase doc still matches the reviewed plan; update [Phase Plan](../../docs/phases/phase-x.md) if the review changes accepted scope or criteria.

The review must check for:
- overreach beyond phase scope
- KISS/SRP/YAGNI violations
- missing tests
- weak validation
- unclear module boundaries
- hidden coupling to Pi runtime internals
- ambiguous acceptance criteria
- unclear or incomplete definition-of-done output
- missing review-surface completeness
- weak RFC-escalation sanity when the plan surfaces an unresolved technical decision
- for bounded audits/scans: missing prioritization or quiet expansion into a broad rewrite
- for new CLI surfaces: weak malformed-argument or error-contract coverage
- for watcher/predicate-heavy behavior: weak timeout semantics or missing negative-case tests for non-target activity
- for package-first phases: ambiguous source-loaded workspace integration boundaries that leave local scripts/tests guessing how shared helpers are consumed

If the review finds real issues, revise the merged plan and briefly update the review.

### 6. Only then start implementation

<!-- rule: LOCAL-PLAN-REVIEW-GATE -->
You MUST NOT begin coding before the merged phase plan has passed review.
Update `manifest.json` to show that phase implementation has started.

## Task breakdown & delegation

After the merged phase plan passes review and before implementation starts, break the phase
into parallel executable tasks and dispatch them to the right specialist subagents.

### Task decomposition

1. Read the merged phase plan and identify independent work slices.
2. Break each slice into a discrete task with explicit acceptance criteria, required files,
   and expected verification.
3. Prefer parallel dispatch of non-overlapping tasks.
4. Treat task ordering as: parallel-independent work first, then dependent work that requires
   a prior task's output.

### Delegation contract

<!-- rule: LOCAL-DELEGATION-TABLE -->
Implementation tasks MUST be dispatched to dedicated specialist agents per this table:

| Task type | Delegate to |
|---|---|
| Code changes, refactors, tests, bug fixes, feature work | `developer` |
| Build systems, CI, test runners, type-checking, linting | `quality` |
| README, plan docs, agent docs, migration notes | `docs` |
| Review-comment follow-up, PR fix commits | `fixer` |

For each delegated task:
- a `fixer` dispatch is never a prose brief: emit its work order with `scripts/loop/emit-fixer-work-order.mjs --repo <owner/name> --pr <n> --head-sha <headRefOid> --phase commit_only (--threads-file <list-review-threads.mjs --unresolved-only output> | --act-list-file <judge-pass --out> --gate <gate>) [--delta-result <path>] --harness <claude|pi|codex>` and dispatch the printed `dispatchPayload` unchanged (ADR 0106, 0107); on Claude Code join the fixer with `node <dev-loops-package-root>/cli/index.mjs gate wait-for-units --artifact <hand-back path> --after <emitted planPath> [--timeout <seconds>]` on the work order's `joinRef` (the single-child join in [gate sub-loop contract](../docs/gate-review-sub-loop-contract.md)); the later `--phase full` emission follows [delta mode](../docs/pre-pr-review-contract.md#delta-mode); the rules below apply to the other roles
- give the subagent one focused task with exact success criteria
- include only the minimum relevant files, plans, and repo context
- tell the subagent whether it should implement, verify, or review
- require the subagent to report blockers, verification results, and changed files
- avoid circular delegation and overlapping scopes
- <!-- rule: LOCAL-DELEGATE-SELF-COMMIT --> `developer`/`quality`/`docs`/`fixer` dispatches COMMIT THEIR OWN WORK before exit per [LOCAL-COMMIT-BEFORE-EXIT](#implementation-loop-for-the-phase) (step 11); for a session that pushes and opens a PR (the scope step 11b defines: tracker-backed or issue-less `--lightweight`) the first push is deferred to the pre-PR review step (11b) so the branch reaches origin once, already cleaned. There is no "edit here, commit there" split: an editing sub-delegate is never told not to commit, and an orchestrator that wants a single consolidated commit performs the edits itself rather than delegating the edit and keeping the commit. The removed `DEVLOOPS_ORCHESTRATOR_OWNS_COMMIT` exemption must not be used; `subagent-stop-uncommitted-guard` remains enforced for every editing role.
<!-- pi-only -->
- resolve the subagent's model via `resolveRoleModel(config, { role, harness: "pi" })` (`role` = the delegate name, e.g. `developer`/`quality`/`docs`/`fixer`/`refiner`) and pass it at dispatch **only when non-null**; this is a routine **role** dispatch, so leave `kind` unset (a gate inspection-angle fan-out passes `kind: "angle"` instead — see the pull-request gate reviewer dispatch in [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md)). Built-in Pi tiers are `null`, so this is a no-op until an operator sets `models.tiers.<alias>.pi`. See [Main-agent delegation contract](../docs/main-agent-contract.md). (Under Claude the tier is baked into the agent's `model:` frontmatter, so no dispatch-time model param is needed.)
<!-- /pi-only -->

### Status monitoring

On Codex, ordinary worker dispatch follows [Generic Codex dispatch](../docs/main-agent-contract.md#generic-codex-dispatch):
run `gate resolve-role --role <name> --harness codex` from the target repo,
forward `nativeOverrides` unchanged with `fork_turns: "none"`, and stop on
config or native rejection without fallback. This includes artifact-only
refiners; fixer work orders keep their immutable emitted payloads.

Track each dispatched task:
- at minimum record agent name, task summary, status (`queued`, `running`, `done`, `failed`),
  and output artifacts
- when tasks are dispatched asynchronously, check status periodically
- if a subagent exits while the task is still non-terminal, resume or re-dispatch

### Consolidation

After all dispatched tasks complete:
1. Collect results and verification output from each task.
2. Review that each task's acceptance criteria are genuinely satisfied.
3. Resolve any coordination gaps or overlapping changes.
4. Proceed to the implementation loop for the phase once all tasks are green.

## Subagent summary logging

If subagents are used for planning, review, research, or implementation support:

Create one summary file per subagent run under:
- `tmp/phases/phase-x/subagents/`

Recommended naming:
- `001-planner.md`
- `002-reviewer-correctness.md`
- `003-reviewer-maintainability.md`
- `004-worker-followup.md`

Each summary must include a machine-readable header block using bullet-key format so
`conductor-monitor.mjs` can detect and parse local phase subagent state:

```
- agent name: <developer|quality|docs|review|refiner|fixer>
- status: <queued|running|completed|failed|paused>
- run id: <subagent-run-id>
- task: <one-line task summary>
- cwd: <working directory>
```

Only `agent name` and `status` are required for conductor-monitor detection; the
other fields improve resume-plan quality. The header block must start at the
beginning of a line (no leading whitespace before the bullet).

Below the header, include human-readable context:
- whether it was sync or async
- why it was used
- main findings or output
- files or artifacts it influenced
- whether its advice was accepted, partially accepted, or rejected
- raw output path if output was saved separately

If the subagent ran asynchronously, update its summary when results arrive so fresh sessions can understand what happened without replaying the whole conversation.

## Workflow-run subagent hand-off contract

When handing off a full workflow run to a subagent (draft PR, gates, Copilot, merge), or
delegating GitHub-first routed follow-up (`copilot_pr_followup`, `issue_intake`), use the
canonical [Workflow Handoff Contract](../docs/workflow-handoff-contract.md) by path. Do not rely
on abbreviated task summaries or operator memory. Read the resolver-derived envelope first
(`requiredReads`, `nextAction`, gate evidence, acceptance and stop rules) and load its required
contracts before acting. The [PR Lifecycle Contract](../docs/pr-lifecycle-contract.md) owns the
gate/Copilot/approval sequence; the envelope is not a fixed checklist.

## Implementation loop for the phase

After the phase plan passes review:

1. Write or update tests first.
2. Implement only enough code for the current phase.
3. Run local validation:
   - run the narrowest deterministic targeted check for the touched slice (repository-pinned Bun 1.4.1 for contributor/CI installs, scripts, and unit tests). If the changed surface requires local full-repository validation, record that requirement for the PR gate; `node <dev-loops-package-root>/cli/index.mjs gate resolve-validation` needs a clean, committed HEAD and cannot run in this pre-commit step. A phase-doc-backed local session with this requirement must follow [plan-file promotion](../docs/local-planning.md#4-promote-to-a-single-draft-pr) into the PR gate path after its local human-review checkpoint; it cannot finalize by local merge
   - when you edit docs/prose (or generated-asset sources) that a contract test guards, run `bun run test:doc-guard` **before** push. It runs the doc-guard and reproducibility contract tests (`test/contracts/*.test.mjs`, including `claude-assets-reproducible.test.mjs`, plus `test/workflow-handoff-contract.test.mjs`)
   - for a *rendered* HTML artifact (a deck `docs/presentations/*.html`, an article `docs/articles/*.html`, or the inspect-run viewer source) UI e2e coverage is **required and auto-scoped** — not opt-in. Touching one obliges you to register it in the shared harness and have a passing UI e2e suite, or the gate fails closed (see [UI e2e scoping step](../docs/ui-e2e-scoping-step.md)); run the matching shared suite locally, e.g. `bun run test:playwright:intro-deck` / `:intro-article` / `:viewer`. These package scripts deliberately launch Playwright with Node. For a bespoke local UI surface that is not a registered rendered artifact, the WebKit smoke seam (fixture-backed Playwright WebKit plus screenshot capture) remains available without being mandatory
   - **Commit immediately after targeted validation passes.** Once the narrowest justified validation is green, stage and commit the current slice with an atomic commit message. For a session that pushes and opens a PR (the scope step 11b defines), commit here and do not push; the push waits for step 11b. Commit authorization follows [Commit policy](#commit-policy). Do not defer commits.
4. <!-- rule: LOCAL-DEV-SELF-CHECK-NO-FANOUT --> Perform exactly one developer self-check of the implementation against the merged phase plan. This is a single self-review by this working session. It MUST NOT dispatch review subagents, resolve or run gate angles (for example `resolveGateAngles(config, "preApproval")`), consolidate a fan-in disposition ledger, or produce anything treated as lifecycle-gate evidence. Multi-reviewer angle fan-out and fan-in are pull-request lifecycle activities only: they run on an existing pull request, bound to its head SHA, at the two gate boundaries — the `draft_gate` and the `pre_approval_gate`, which are the only two lifecycle-gate fan-out sites — and they are conductor-owned, defined by [PR Lifecycle Contract](../docs/pr-lifecycle-contract.md) and [Gate Review Sub-Loop Contract](../docs/gate-review-sub-loop-contract.md). Do not run a pre-pull-request gate fan-out here.
   - The developer self-check artifact and any local review notes are NOT lifecycle-gate evidence. Gate evidence is only the visible gate comment and disposition ledger on the current pull request head, defined by [Gate Review Comment Contract](../docs/gate-review-comment-contract.md).
   - Fail closed on completeness: any review — this developer self-check or a later pull-request gate pass — with a reviewer that did not complete MUST NOT be summarized as clean; an unfinished reviewer yields a non-clean result.
5. Update [Phase Plan](../../docs/phases/phase-x.md) so it reflects the phase as actually implemented, including any accepted scope or validation changes.
6. Update [Project Plan](../../PLAN.md) when the phase changed durable product truth, resolved an open question, or made the shipped command/behavior surface more concrete.
7. Write `Phase Summary` (`tmp/phases/phase-x/summary.md`) using [Phase Summary Template](../dev-loop/templates/phase-summary.md).
8. <!-- rule: LOCAL-RETRO-FRESH-CONTEXT-DISPATCH --> Write `Retrospective` (`tmp/phases/phase-x/retrospective.md`) — but the retrospective MUST be produced by a **fresh-context, independent subagent dispatch** (like a gate reviewer), never written inline by this working session: dispatch a fresh-context pass seeded with the cycle's full agent/subagent tool-call/action/result record (the existing session transcript/journal artifacts — reuse them, do not build a new transcript store) plus the phase docs and the issue's acceptance criteria / definition of done / non-goals, and have it evaluate neutrally against those contracts. Save the record path used and record the checkpoint with provenance via `checkpoint-contract.mjs --state complete ... --retro-context fresh --record-source <record-path>` (see [Retrospective Checkpoint Contract](../docs/retrospective-checkpoint-contract.md)); an inline self-authored retro fails the checkpoint (fail-closed, test-pinned). Use [Retrospective Template](../dev-loop/templates/retrospective.md).
9. Update `tmp/phases/phase-x/manifest.json` and `tmp/phases/index.json`.
10. Update [Implementation State](../../docs/IMPLEMENTATION_STATE.md).
11. <!-- rule: LOCAL-COMMIT-BEFORE-EXIT --> **Exit validation gate — no uncommitted changes.** Run `git status --porcelain` before exiting. Revert unintended/speculative deltas; validate intended changes with the narrowest justified check, then commit. For a session that pushes and opens a PR (the scope step 11b defines) the first push is deferred to the pre-PR review step (11b); phase-doc-backed sessions eligible for local merge do not push. Recheck that status is empty before declaring phase completion. Dirty exit is a workflow defect, never clean completion. The `SubagentStop` hook (`.claude/hooks/subagent-stop-uncommitted-guard.mjs`) refuses dirty exits under `tmp/worktrees/`, naming the rule and paths. The read-only roles listed in `READONLY_SUBAGENT_ROLES` (`packages/core/src/claude/hook-decisions.mjs`) are exempt: their foreign tracked edits produce an advisory naming the orchestrator as responsible. Enforcement remains for the orchestrator and every editing role (`developer`, `fixer`, `docs`, `quality`).
11b. <!-- rule: LOCAL-PRE-PR-REVIEW-BEFORE-PUSH --> **Pre-PR review pass (before the first push).** For any session that pushes and opens a PR — tracker-backed, issue-less `--lightweight` (PR-body-as-spec), or a phase-doc-backed session requiring full validation; only a phase-doc-backed session eligible for local merge is exempt — after the step-11 commit and before the branch's first push and PR creation, run the pre-PR review phase per [Pre-push review contract](../docs/pre-pr-review-contract.md): hand a mandatory developer-authored review brief to ONE fresh-context general-purpose reviewer, paired with the adversarial-enumeration checklist and the stale-surface scan per `PRE-PR-STALE-SURFACE-SWEEP`. Resolve the reviewer model via `resolveRoleModel(config, { role: "pre-push-reviewer", harness })` and pass it only when non-null; on Claude dispatch the built-in `general-purpose` subagent with the brief as its prompt, on Pi dispatch one fresh subagent with the brief as its task (a general-purpose reviewer; the PR-bound `review` gate procedure does not apply). The reviewer returns findings only and MUST NOT edit the tree; the implementer applies the fixes. Apply findings in-tree, rerun the narrowest justified validation on the fixes (re-check after the final round), then commit them (follow-up commit or amend) so `git status --porcelain` is empty, and only THEN push once. After the final commit, write the review record as `PRE-PR-BEFORE-FIRST-PUSH` specifies; `pr create` (lightweight included) refuses without it. The pass is bounded to one reviewer per round and at most two rounds, is ephemeral (no PR/comment/thread/Copilot), and is NOT lifecycle-gate evidence. The full fan-out `draft_gate`/`pre_approval_gate` still runs afterward as the authority.
12. For tracker-backed sessions, create the PR from the working branch against the resolved base branch — `.devloops` `workflow.baseBranch` when configured, else the repo's auto-detected default branch (`resolveBaseBranch(config, { cwd })` from `@dev-loops/core/config`; bare name, e.g. `main`) — never a hardcoded `--base main`: `node <dev-loops-package-root>/cli/index.mjs pr create --assignee @me --repo <owner/name> --base <resolved-base> --head <branch> --title "..." --body-file <body-file>` (fallback when the CLI helper is unavailable: `node <resolved-skill-scripts>/github/create-pr.mjs --repo <owner/name> --assignee @me --base <resolved-base> --head <branch> --title "..." --body-file <body-file>`); never raw `gh pr create`. Draft/assignment/`Closes #N` policy: [LOCAL-PR-CREATE-CANONICAL](#tracker-backed-local-implementation) above. For a phase-doc-backed session requiring full validation, use [plan-file promotion](../docs/local-planning.md#4-promote-to-a-single-draft-pr) instead so the committed phase doc remains the spec-of-record. At the PR gate, request any required local full-repository validation only through `node <dev-loops-package-root>/cli/index.mjs gate resolve-validation` on the clean, committed current HEAD and record its result.
13. If authorized, merge the fully reviewed, locally validated phase branch back into local `main` only when a phase-doc-backed session needs no full-repository validation; otherwise proceed through the PR gate pipeline.
14. If authorization for PR creation or merge is still pending (commit authorization is already enforced by the exit validation gate in step 11), mark the phase as `awaiting-finalization` rather than `completed`, and record exactly which finalization step is pending.

## Retrospective requirements

The retrospective must capture:
- what worked well in the local dev loop
- what caused friction or waste
- whether the fan-out/fan-in/review loop improved the phase
- what should change in the skill or workflow next time
- what a fresh session should know before the next phase

<!-- rule: LOCAL-RETROSPECTIVE-REQUIRED -->
This is the infrastructure for self-improvement; you MUST NOT skip it.

## Dev mode

Dev mode improves the local implementation loop itself while using it. A repo may declare a default via `.devloops` field `workflow.devModeDefault`; explicit user opt-in/opt-out for the current run still wins over that default. Trigger it when the user explicitly asks for dev mode, self-improvement mode, or says they want the skill to refine itself as it goes.

After the normal phase summary and retrospective, run one extra bounded self-improvement pass:

1. Collect a deterministic context bundle: `../dev-loop/scripts/dev-mode-context.mjs` → `tmp/phases/phase-x/dev-mode-context.json`.
2. Review the phase artifacts/logs for planning quality, review quality, validation friction, bash exit-code-1 patterns, and places where prompts or deterministic tooling should improve.
3. Write `Dev Mode Retrospective` (`tmp/phases/phase-x/dev-mode-retrospective.md`) — required; name the highest-value prompt/workflow follow-ups revealed by the phase.
4. Optionally write `Dev Mode Review` (`tmp/phases/phase-x/dev-mode-review.md`) when separate analytical notes help.
5. Apply at least one bounded follow-up update to a relevant skill and/or agent prompt (supporting tooling/docs/template changes may accompany it but do not replace the prompt update), kept phase-bounded and tied directly to the retrospective findings.
6. Write `Dev Mode Skill Changes` (`tmp/phases/phase-x/dev-mode-skill-changes.md`) recording which prompts and supporting changes landed; if no prompt update can be justified safely, stop and report that dev-mode exit criteria were not met.
7. If skill scripts or deterministic tooling changed, rerun the skill-local tests.
8. Stop after this bounded pass — do not recurse into endless self-editing loops.

Dev mode is still phase-bounded: it improves the loop around the completed phase and does not authorize work on the next product phase.

## tmp/ logging requirements

<!-- rule: LOCAL-TMP-EPHEMERAL-STATE -->
The required durable-doc + `tmp/` artifact set for a phase is defined once in [Deterministic logging structure](#deterministic-logging-structure); this section MUST NOT duplicate that list. Those artifacts are normally temporary and do not need to be checked into git; do not force-add them unless the user explicitly wants checked-in examples or fixtures. Also log validation output summaries and notable decisions if they help evaluate the local dev loop later.

Additionally, append every bash call that exits with code `1` to `tmp/phases/phase-x/bash-exit-1.jsonl` using the deterministic helper `../dev-loop/scripts/log-bash-exit-1.mjs`. Each line is one JSON object with at least `timestamp`, `phase`, `cwd`, `command`, `exitCode`, `purpose`, `summary` (optionally truncated `stdout`/`stderr` or a path to a larger saved artifact). This log improves the local dev loop itself, so do not skip it just because the command was exploratory.

## Stop conditions

See [Stop Conditions](../docs/stop-conditions.md). Local-specific stops: phase completed & finalized, next-phase refinement needed, user/main-agent approval required, validation failure needing direction change.

## Branch / review / merge policy

- Implement on a dedicated local working branch, never directly on `main`, switching to it before the first mutating step; if the repo is unborn (no commits yet), still create the working branch first and make the initial atomic commits there.
- Use atomic local commits to log progress, but only for coherent reviewable slices — [Commit policy](#commit-policy) below governs commit timing/authorization.
- Before finalizing, complete the single developer self-check (implementation loop step 4, `LOCAL-DEV-SELF-CHECK-NO-FANOUT`). Rerun validation after any review-driven fixes on the branch.
- A phase is not operationally closed until its branch state is captured in commit history and the reviewed branch has been finalized according to session type (merged into local `main` for phase-doc-backed sessions that need no full-repository validation; merged via GitHub PR for tracker-backed or promoted plan-file sessions); when authorization for that finalization is still pending, record the phase as `awaiting-finalization` and describe the exact missing step.
- For tracker-backed sessions, follow the handoff path and `LOCAL-TRACKER-NO-DIRECT-MERGE` in [Tracker-backed local implementation](#tracker-backed-local-implementation). A new PR must exist in draft before `gh pr ready` is eligible.
- For phase-doc-backed sessions, merge the fully reviewed, locally validated branch back into local `main` when authorized only if no full-repository validation is required; otherwise promote the persisted plan to a draft PR and complete the gates before finalization.
- Behind-branch integration before merge (for example a sibling PR merged first and both touch shared files): prefer a merge commit (`git merge origin/main`) over rebase + force-push. Dev-loop PRs are squash-merged, so a merge commit lands the same result on `main` without a non-fast-forward push. Force-push (`--force-with-lease` only, never bare `--force`) is acceptable only for a branch the loop solely owns and where no integration alternative exists; document that carve-out. After any integration that changes the head SHA, re-verify gate evidence at the new head ([Merge Preconditions](../docs/merge-preconditions.md#required-before-merge)).

## Commit policy

- Do not commit speculative work or before the relevant validation for that slice passes.
- Immediately before every `git add && git commit` sequence, assert branch identity with `git branch --show-current`; stop on a mismatch. Read and apply `WORKTREE-DEFAULT-USE` in [worktree-guidance.md](../docs/worktree-guidance.md#default-rule-use-a-worktree-for-mutating-local-work), including explicit `git -C <absolute-worktree-path> …` for mutations.
- Commit only when the coordination/main agent has decided the slice or phase is ready. **Exception:** in non-interactive subagent sessions, commit authorization is implicit: the subagent was dispatched to implement and must commit before exiting, enforced by [LOCAL-COMMIT-BEFORE-EXIT](#implementation-loop-for-the-phase) (implementation loop step 11).
- If commit, PR-creation or merge authorization has not yet been given, do not call the phase `completed`; call it `awaiting-finalization` (implementation loop step 14).

## Anti-patterns

See [Anti-patterns](../docs/anti-patterns.md). Local-specific: don't assume optional plan docs exist, don't guess through missing plan details, don't turn the developer self-check into a pre-pull-request angle fan-out, don't skip the pull-request gate fan-out/fan-in (`draft_gate`/`pre_approval_gate`) for tracker-backed sessions, don't skip `tmp/` artifacts, don't use subagents without readable summaries.
