---
name: plan
description: "Analyze the repository and write routed PLAN/CODE_REVIEW pairs for initial work or archived WARN/FAIL findings. The plan model only plans, runtime gates dependencies, and a separate implementation model consumes only ready pairs. Plan, implementation, and review must use different model identities."
---

# Plan

## Purpose

Create the planning artifacts for the implementation loop:

```text
plan model -> routed pair -> runtime dependency gate -> implementation model -> review-ready -> review model
    ^                                                                                |
    +-------------------------------- plan-ready -------------------------------------+
```

After writing the pair, report `implementation-ready` only for a task whose encoded predecessors are satisfied; report `dependency-waiting` for an unsatisfied dependent task. Then stop.

Role completion means leaving the routed PLAN/CODE_REVIEW pair and its readiness result; it does not include implementation or worker scheduling.

`code-review` writes `USER_REVIEW.md` only when a selected Milestone `구현 잠금 > 결정 필요` item blocks implementation. Other blockers become `plan-ready` findings.

Plan, implementation, and review use different model identities; separate agents using the same model do not satisfy this rule.

## Workflow Contract

This skill intentionally uses routed active files under an active task directory as the state protocol. Do not change this directory or filename contract unless the paired code-review skill is updated together.

Role boundary:

- The plan model may inspect source/tests but must not edit them or run implementation verification.
- Write only PLAN/CODE_REVIEW files and required planning metadata.
- Do not implement, review, invoke `code-review`, or start another agent.
- Record the runtime-provided Plan model identity in both files. It is immutable for that pair; do not infer it from lane/G or agent name.
- Runtime, not the implementation worker, resolves encoded predecessor `complete.log` evidence and starts only `implementation-ready` tasks. The worker never searches task archives, interprets dependency state, or schedules siblings.

Task path terms:

- `{task_group}` is the top-level work category under `agent-task/`. Normal task groups use a short snake_case name such as `refactoring`.
- Milestone-linked work uses the reserved task group form `m-<milestone-slug>`, where `<milestone-slug>` is the active Milestone filename without `.md`.
- `{subtask_dir}` is an indexed executable sibling inside grouped work and follows the naming rules below, such as `01_core` or `02+01_db`.
- `{subtask_name}` is the short snake_case name after the index or dependency prefix inside `{subtask_dir}`.
- `{task_name}` in headers and templates means the active task path relative to `agent-task/`: either `{task_group}` for a one-off task or `{task_group}/{subtask_dir}` for a grouped task.
- A single-plan task stores active files directly under `agent-task/{task_group}/`.
- Grouped work stores one active pair under each `agent-task/{task_group}/{subtask_dir}/`; the parent `agent-task/{task_group}/` must not contain active plan/review files.
- Initial planning may create immediate sibling pairs. A `plan-ready` follow-up keeps the exact existing task path and writes one replacement pair.

Filename rules:

- Plan file: `PLAN-{build_lane}-GNN.md`
- Review stub: `CODE_REVIEW-{review_lane}-GNN.md`
- `{lane}` is only `local` or `cloud`; never put model names in filenames.
- `GNN` is a two-digit capability grade from `G01` to `G10`; the runtime maps lane+grade to current models externally.
- Lane, grade, and both canonical basenames come only from `agent-ops/skills/common/finalize-task-routing/SKILL.md`.

Generated pair boundary:

- Runtime records the Implementation identity and verifies every encoded predecessor before dispatch. An unsatisfied dependent pair remains `dependency-waiting`.
- The implementation model receives only a ready pair, edits source/tests, fills implementation-owned review sections, then reports `review-ready` and stops. It does not inspect task/archive state.
- The review model judges and archives the pair. On WARN/FAIL, orchestration dispatches a different plan model; no model performs another role itself.

Planning-time verification boundary:

- This skill designs verification; build executes it and records actual output, and review validates the evidence and reruns commands required by its review scope.
- During planning, use repository files, manifests, scripts, workflows, rules, and already-recorded evidence only. Do not refresh existing evidence.
- Do not run compile, build, test, lint, source formatter, smoke/E2E, live/remote checks, package installation, dependency download, or cache warming while planning.
- Missing implementation-time output is not a planning evidence gap. Record the command, expected result, assumptions, and responsible build/review stage instead.

Shallow sibling extraction policy:

- Treat a Milestone Epic or other broad request as a selection boundary. Select exactly one next executable Milestone Task or non-roadmap candidate; do not batch every Task in the Epic.
- Before loading implementation files in depth, use the selected Task, roadmap/SDD, repository structure, and targeted symbol/test inventory to make one shallow splitability check.
- If the selected Task has at least two clearly separable implementation or verification chunks and keeping them together would make local context unnecessarily broad, materialize the minimum complete set of immediate sibling tasks. Otherwise keep one task.
- Create one routed PLAN/CODE_REVIEW pair for every materialized sibling. Do not create empty directories, placeholder files, index-only reservations, decomposition caches, or manifests.
- Split only one level. Do not recursively subdivide siblings or expand into other Milestone Tasks. Reuse the shallow inventory and load only each sibling's required source/test regions.
- Account for the selected Task's required scope across the sibling set. Do not hide a known required chunk as deferred prose. Irreducible scope that has no coherent boundary remains one task and is handled by final cloud routing.
- Declare each sibling's intended write set and shared mutable state. Siblings may run in parallel only when their write sets are disjoint and they have no state, ordering, or contract-handoff dependency; read-only overlap is allowed.
- If write sets overlap or one sibling consumes another's state or contract, merge them or encode the producer as a `+` predecessor. Unknown overlap is not parallel-safe.
- Record the full immediate sibling set and real dependencies in every sibling plan. Approximate but bounded fan-out is preferred over exhaustive decomposition.

Task directory naming rules:

- A normal single-plan task uses `agent-task/{task_group}/` with a short snake_case category name, e.g. `agent-task/refactoring/`.
- If the plan is based on a selected active Milestone, use `agent-task/m-<milestone-slug>/` as the task group. Do not include the Phase slug, Epic id, Task id, or a separate task slug in the task group.
- `m-<milestone-slug>` is a reserved top-level task group namespace for Milestone-linked work. Non-roadmap tasks must not use `m-`.
- Runtime completion-event routing for `m-*` reads only the top-level `{task_group}` name. It resolves `<milestone-slug>` by matching exactly one active file at `agent-roadmap/phase/*/milestones/<milestone-slug>.md`; archive paths are not target candidates.
- New Milestone/Epic task extraction creates either one indexed `{subtask_dir}` or the immediate sibling set selected by the shallow split.
- Choose the next two-digit index after all active sibling indices and archived sibling directory basenames for the same task group. Read archive basenames only; do not read archived file contents. Allocate consecutive indices only to siblings that will receive routed pairs in this invocation.
- Each indexed directory owns exactly one normal active plan file and one normal active review stub. The index increases for sorting but is not a serial execution dependency.
- Use `NN_{subtask_name}` for a task with no runtime dependencies, e.g. `01_core`, `04_docs`, `05_ui`.
- Use `NN+PP[,QQ...]_{subtask_name}` for a task that depends on earlier task indices, e.g. `02+01_db`, `03+01,02_api`, `06+05_integration`.
- Valid independent pattern: `^[0-9]{2}_[a-z0-9_]+$`.
- Valid dependent pattern: `^[0-9]{2}\+[0-9]{2}(,[0-9]{2})*_[a-z0-9_]+$`.
- `NN`, `PP`, and `QQ` are two-digit indices. Every predecessor index after `+` must be lower than `NN` and must refer to a sibling indexed task directory under the same `{task_group}`.
- The first `_` after the index or dependency list starts `{subtask_name}`. `{subtask_name}` stays short snake_case and may contain additional underscores.
- Scheduling contract: a runtime that consumes task directories reads only `{subtask_dir}`; `_` means `depends_on=[]`, and `+` means `depends_on` is the comma-separated index list between `+` and the first `_`. Before worker dispatch, runtime requires one unambiguous matching predecessor `complete.log` for every encoded index. This skill records dependencies and readiness but does not start or schedule workers.
- An independent `NN_...` name asserts that its write set and shared mutable state do not conflict with concurrently runnable siblings. Any write/state/ordering/contract conflict must appear as `NN+PP[,QQ...]_...` or be merged into one sibling.
- Subtask directory names are the source of truth for runtime dependencies. Do not hide extra dependencies only in the plan body, and do not create a bare `NN+{subtask_name}` without predecessor indices.
- A predecessor index is satisfied by a `complete.log` for the matching predecessor subtask under the same `{task_group}`. Check active siblings first, then matching archived subtasks across all archive month folders. This is a narrow exception to the normal archive skip rule: read only candidate predecessor `complete.log` files needed to prove split dependency completion.
- For predecessor index `PP`, the only valid active lookup candidates are `agent-task/{task_group}/PP_*/complete.log` and `agent-task/{task_group}/PP+*/complete.log`.
- For predecessor index `PP`, the only valid archive lookup candidates are `agent-task/archive/*/*/{task_group}/PP_*/complete.log` and `agent-task/archive/*/*/{task_group}/PP+*/complete.log`.
- Archive lookup matches the predecessor index at the start of the archived subtask directory name, such as `01_...` or `01+...`, under the same `{task_group}`. If multiple candidates match one predecessor index, do not choose by guess; record the ambiguity and require a concrete task path or runtime selection.
- Do not treat an archived predecessor as the active task to edit. Archive lookup is only for dependency satisfaction before writing or implementing a dependent split plan.
- `01_core`, `02+01_edge_integration`, and `03+01_node_integration` express two integrations that may run in parallel after `01_core` completes. A shallow split may create all three routed sibling pairs in one invocation.
- Preserve task group and subtask directory names verbatim; do not normalize, reinterpret, or choose execution order by agent judgment.

Final routing boundary:

- Do not estimate, inherit, or write lane/G while analyzing. Keep the task `unrouted` until plan scope, split, verification design, ownership, decision facts, and available existing evidence are complete.
- Execute `agent-ops/skills/common/finalize-task-routing/SKILL.md` for both `build` and `review` after analysis. Its routed outputs are the only source for active PLAN/CODE_REVIEW filenames.
- Apply this boundary independently to every first-pass sibling and to each review WARN/FAIL or USER_REVIEW replan.
- A previous loop's lane, grade, score, rationale, and filename are quarantined. Prior code paths, recorded command output, and review findings may be carried as raw evidence after confirming their path and revision relevance without rerunning commands.
- `needs_evidence` requires missing static planning facts and a fresh full routing run. It must not trigger implementation verification. A first-pass `blocked` may prevent loop entry; once a selected review loop is active, a valid Milestone-lock decision routes to `USER_REVIEW.md`, while every other limitation becomes a routed follow-up with its blocker evidence and deterministic release condition.
- If plan facts change after routing, invalidate both target results and run final routing again before writing files.
- Treat non-behavioral review artifact drift and obvious non-behavioral source nits as current-scope evidence; they do not bypass final routing.

Directory states:

| State | Meaning |
|-------|---------|
| `PLAN-*-G??.md` only | Invalid; plan skill always writes both active files |
| `STAGED_BATCH.md` | Multi-sibling write transaction; finish every listed sibling before reporting |
| `STAGED_PLAN.md` only | Pair write interrupted; render the matching staged review from this fixed plan without rerouting |
| `STAGED_PLAN.md` + `STAGED_CODE_REVIEW.md` | Pair is fully staged; verify and promote both without rerouting |
| unstarted active pair + staged replacement | Explicit replan transaction; archive only the old pair, then promote the staged pair |
| one old active member + its archived counterpart + staged replacement | Interrupted replan archive; finish the old archive, then promote the staged pair |
| routed PLAN plus matching `STAGED_CODE_REVIEW.md` | Partial promotion; promote the staged review and do not rewrite the PLAN |
| `PLAN-*-G??.md` + `CODE_REVIEW-*-G??.md` stub, dependencies satisfied | `implementation-ready`; a different implementation model consumes the pair |
| `PLAN-*-G??.md` + `CODE_REVIEW-*-G??.md` stub, dependencies unsatisfied | `dependency-waiting`; runtime does not dispatch the implementation model |
| `PLAN-*-G??.md` + filled `CODE_REVIEW-*-G??.md`, dependencies satisfied | `review-ready`; a different review model consumes the pair |
| `PLAN-*-G??.md` + filled `CODE_REVIEW-*-G??.md`, dependencies unsatisfied | `dependency-waiting`; runtime does not dispatch the review model |
| `PLAN-*-G??.md` + `CODE_REVIEW-*-G??.md` with appended verdict | Review finalization pending; the plan model must not modify it |
| `complete.log` + `*.log` files | Task complete (PASS or user-review-resolved PASS), with exact final archive/event metadata fixed before the final task-directory archive move |
| `USER_REVIEW.md` + `*.log` files | Linked Milestone decision is required before planning |
| Highest numeric-suffix matching `user_review_*.log` has `## 상태` value `RESOLVED` and `해소 결과 > 결과` value `REPLAN`, with no active pair | Resolved user-review `plan-ready`; create one follow-up pair from that log and its referenced archived pair |
| `agent-task/archive/YYYY/MM/{task_name}/complete.log` + `*.log` files | Archived completed task path (PASS or user-review-resolved PASS); not active |
| Matching archived plan/review logs with WARN/FAIL | `plan-ready`; create one follow-up pair from those exact logs |

## Step 1 - Determine Task

If the user names an exact existing task path for continuation or replan, use it. Do not treat a Milestone/Epic id or title as an exact task path.

Any plan-creation request scoped to a Milestone, Epic, or other broad roadmap item enters new-task extraction mode unless it selects an existing indexed task. Select one Milestone Task inside the requested Epic before applying sibling extraction.

Otherwise, find active plan files with both globs, excluding `agent-task/archive/**`:

- `agent-task/*/PLAN-*-G??.md`
- `agent-task/*/*/PLAN-*-G??.md`

Find `agent-task/*/STAGED_BATCH.md`, then `STAGED_PLAN.md` and `STAGED_CODE_REVIEW.md` with the task-depth globs before classifying active plans or selecting a new task. A staged state wins selection and resumes every listed sibling at Steps 5-6 with the recorded Plan model identity, without rerouting or a new task path. Do not apply active-pair stop rules until that transaction finishes.

Also note active user-review stops, excluding `agent-task/archive/**`:

- `agent-task/*/USER_REVIEW.md`
- `agent-task/*/*/USER_REVIEW.md`

| Result | Action |
|--------|--------|
| Exactly one | Select it, then apply the active-state guards below |
| None | Create a new task only for a feature/refactor/fix/follow-up that belongs in this workflow |
| Multiple | If the user/runtime named a task group, task path, or subtask directory that identifies exactly one active plan, use it. Otherwise list paths and stop with an ambiguity report; do not choose by agent judgment and do not create a user-review request for routing ambiguity. |

For an exact task path with no active pair, inspect durable evidence in this order:

1. If the highest numeric-suffix matching `user_review_*.log` has `## 상태` value `RESOLVED` and `해소 결과 > 결과` value `REPLAN`, require its referenced archived plan/review pair, treat all three files as `plan-ready` evidence, use the next monotonic plan number, and refuse the handoff if the current Plan model identity matches either forbidden identity recorded in the resolution log.
2. Otherwise accept follow-up planning only when the highest numeric-suffix matching archived review log is WARN/FAIL, its plan log is identifiable, and the archived review does not contain a valid unresolved Milestone-lock user-review gate. Treat that pair as `plan-ready` evidence, use the next monotonic plan number, and refuse the handoff if the current Plan model identity matches the archived Implementation or Review identity.
3. If the archived review contains a valid unresolved user-review gate and no matching resolved log exists, return the task to code-review recovery so it writes or restores `USER_REVIEW.md`; do not plan.

If `USER_REVIEW.md` exists, do not plan until a review model resolves and archives it.

If a selected task directory contains both `USER_REVIEW.md` and an active `PLAN-*-G??.md` or `CODE_REVIEW-*-G??.md`, do not overwrite either state or ask the user to choose between files. Treat a valid unresolved `USER_REVIEW.md` as the terminal state; otherwise return the exact paths and provenance to code-review finalization/recovery so it can continue from evidence rather than waiting for another instruction.

If an active review already has a verdict, leave it unchanged and report that review finalization is required.

Before reporting readiness for an indexed active pair, validate its basename against `NN_{subtask_name}` or `NN+PP[,QQ...]_{subtask_name}` and require every predecessor to be lower than `NN`. Return a malformed pair for Plan path migration; never dispatch it or report it as ready.

If the selected active pair is an unfilled stub, resolve its encoded predecessor evidence. Report `implementation-ready` only when all predecessors are satisfied; otherwise report `dependency-waiting`. Replan it only when the user explicitly requests replan before implementation starts. If its implementation-owned sections are filled and it has no verdict, report `review-ready` and stop.

로드맵 확인:

- `agent-roadmap/current.md`는 브랜치별 로컬 포인터다. 있으면 구현 계획 파일을 만들기 전에 읽고, 사용자 요청, 브랜치, 변경 경로를 기준으로 관련 Phase와 Milestone을 선택한다.
- `agent-roadmap/priority-queue.md`가 있으면 명시 target이 없는 구현 계획에서 Phase를 가로지르는 후보 순서를 확인하기 위해 읽는다. 큐 순서는 우선순위 참고이며, 상태/잠금/기능 원본은 각 Milestone 문서다.
- 사용자가 target Milestone을 명시하지 않았고 요청이 "다음 작업" 또는 일반 구현 계획이면 `priority-queue.md`의 위에서 아래 순서 중 요청과 맞고 활성 경로에 존재하는 첫 Milestone을 우선 후보로 둔다.
- `priority-queue.md` 링크가 깨졌으면 Milestone을 추측해 계획하지 말고 `update-roadmap`으로 큐 재정렬/재생성이 필요하다고 보고한다.
- `agent-roadmap/`이 있는데 `current.md`가 없으면 `agent-ops/skills/common/_templates/roadmap-current-template.md` 형식으로 로컬 파일을 만들거나, `ROADMAP.md`의 Phase 흐름과 관련 `PHASE.md`에서 후보를 고른 뒤 로컬 current를 채운다. current 없음만으로 일반 task routing으로 빠지지 않는다.
- `current.md`가 `agent-roadmap/archive/**`를 가리키면 해당 문서는 읽지 말고 활성 Phase/Milestone이 아니라고 보고한다.
- 선택한 Phase를 한 번 읽어 Phase 목표, Milestone 흐름, Phase 경계를 확인한다.
- 선택한 Milestone을 한 번 읽어 목표, 상태, 승격 조건, 범위, 기능 Task, 완료 리뷰, 범위 제외, 구현 잠금을 확인한다. `승격 조건`은 `[스케치]`에서만 필수이며, `[계획]` 이상에서 섹션이 없으면 `없음`으로 본다. `구현 잠금` 섹션이 없거나, 상태가 `잠금`이거나, 미완료 `결정 필요` 항목이 하나라도 있으면 실구현 계획을 만들지 않는다.
- 구현 잠금에 걸린 Milestone에서는 `PLAN-*-G??.md`, `CODE_REVIEW-*-G??.md`, task directory, file/API/package 수준 구현 단계를 확정하지 말고 `구현 잠금 차단`으로 보고한다. 보고에는 Milestone 경로, 잠금 상태, 남은 `결정 필요` 항목, 다음에 필요한 `update-roadmap` 조치를 적는다.
- 남은 `결정 필요` 항목이 현재 실구현 범위가 아니라고 판단되더라도 같은 plan 요청 안에서 구현 계획을 계속 쓰지 않는다. 먼저 roadmap-only 갱신으로 해당 항목을 `범위 제외`, 후속 Milestone, 또는 `작업 컨텍스트`로 옮기고 `구현 잠금`을 `해제`한 뒤 새 plan 요청에서 진행한다.
- 선택한 Milestone에 `SDD: 필요`가 있으면 승인된 SDD를 구현 계획 작성의 입력으로 읽는다. SDD 문서가 없거나, 상태가 `[승인됨]`이 아니거나, `SDD 잠금`이 `잠금`이거나, 같은 디렉터리에 `USER_REVIEW.md`가 있으면 plan 파일을 만들지 말고 `roadmap-sdd` 또는 `update-roadmap` 조치가 필요하다고 보고한다.
- `SDD: 필요` Milestone의 구현 계획은 Milestone 기능 Task만 보고 작성하지 않는다. 요청 대상 Task id에 연결된 SDD Acceptance Scenario와 Evidence Map을 먼저 매핑하고, 그 결과에서 구현 범위, checklist, 검증 명령, 완료 evidence를 역산한다. 매핑이 없거나 SDD와 Milestone Task가 어긋나면 plan 생성을 멈추고 SDD와 Milestone의 정합성 갱신이 필요하다고 보고한다.
- 선택한 Milestone에 legacy `필수 기능`/`완료 기준`이 분리되어 있으면 plan 파일을 만들지 말고 `update-roadmap` 정규화가 필요하다고 보고한다.
- 선택한 Phase 또는 Milestone 상태가 `[스케치]`이면 구현 계획 파일을 만들지 않는다. `[스케치]`는 컨셉 상태이므로 `update-roadmap`의 concretize 흐름으로 승격 조건, 결정 필요, 범위, 기능 Task를 정리해 `[계획]`으로 전환해야 한다고 보고한다.
- Phase 또는 Milestone 후보가 여럿이면 요청 문장, 변경 경로 직접성, Milestone 상태, 구현 잠금, 선후 의존성, Phase/Milestone 흐름상 위치를 기준으로 1순위와 2순위를 추천하고 필요한 후보 문서만 읽어 범위를 좁힌다.
- 로드맵 current가 있고 활성 Phase/Milestone 밖 작업이면 `ROADMAP.md`의 Phase 흐름을 확인하고 전환, 신규 Phase/Milestone, 또는 기존 활성 범위 내 배치 필요성을 보고한다.
- 사용자가 선택한 Milestone의 작업, 구현, 계획 작성을 명시했더라도 `구현 잠금`이 완전히 해제되어 있지 않으면 계획 작성을 이어가지 않는다. Milestone 전체에서 에이전트가 확정할 수 없는 결정 항목이 더 이상 없을 때만 roadmap update 흐름으로 `구현 잠금` 상태를 `해제`로 갱신할 수 있다.
- 제품 선택, 우선순위 결정처럼 에이전트가 확정할 수 없는 항목은 구현 계획의 실행 checklist로 쓰지 않는다. 그런 항목이 남아 있으면 plan 생성을 멈추고 `구현 잠금 > 결정 필요`로 분리한다.
- 기능 Task에 `검증:`이 있으면 구현 계획의 같은 plan item 안에 해당 검증을 포함한다. 검증이 명시되지 않은 기능 Task에는 억지 검증 항목을 만들지 말고, 필요한 일반 빌드/회귀 확인만 최종 검증에 둔다.
- 선택한 활성 Milestone 범위에 속하는 구현 계획이면 `{task_group}`을 `m-<milestone-slug>`로 정한다. `<milestone-slug>`는 선택한 Milestone 경로의 파일명에서 `.md`를 제거한 값이다.
- Milestone 또는 Epic 범위의 plan 생성은 먼저 Milestone Task 하나를 선택하고, 그 Task가 크면 immediate sibling pair들을 `agent-task/m-<milestone-slug>/<subtask_dir>/` 아래에 함께 만든다. Epic은 선택 범위일 뿐 완료 대상으로 쓰지 않는다.
- Milestone 기능 Task 완료를 목표로 하는 계획이면 `Roadmap Targets` 섹션에 활성 Milestone 경로와 완료 대상 Task id를 고정한다. Sibling split에서는 모든 필수 sibling을 선행 조건으로 가진 closure sibling 하나에만 이 섹션을 둔다. 자연스러운 마지막 sibling이 없으면 작은 integration/verification closure sibling을 만든다. 이 섹션은 `complete.log`의 `Roadmap Completion` 근거로 복사되어 `update-roadmap`이 해당 Task만 체크하는 anchor가 된다. `{task_group}`이 해당 Milestone slug의 `m-<milestone-slug>`일 때만 쓴다.
- Milestone 작업이 아니거나, Milestone 안의 조사/부분 구현처럼 이번 작업만으로 특정 기능 Task 완료를 주장할 수 없으면 `Roadmap Targets` 섹션을 쓰지 않는다. 해당 기능 Task의 남은 acceptance를 실제로 닫는 마지막 작업에만 넣는다. 섹션이 없으면 PASS 후에도 roadmap Task 체크를 하지 않는다.
- `agent-roadmap/` 디렉터리가 없으면 기존 task routing 규칙대로 진행한다.

Use short snake_case task group names for non-roadmap work, e.g. `api_refactor`.

Before choosing plan files or task directory names, apply the shallow sibling extraction policy once. Choose one task directory or a complete immediate sibling set. Do not put multiple active plan files in one task directory or mix indexed task directories with active plan/review files directly in the parent task group.

## Step 2 - Analyze Before Writing

Complete these four items before creating active plan/review files. The only allowed pre-plan edits are local `agent-roadmap/current.md` creation or `.gitignore` repair needed for routing. Report test-rule gaps separately; do not create or update test rules while planning.

- [ ] **Fix scope and split once** — select one executable candidate from the request and required roadmap/SDD context. Keep it whole or freeze one immediate sibling set; do not recurse.
- [ ] **Fix directories and dependencies** — allocate indices, encode real predecessors, and confirm concurrent siblings have disjoint writes and no shared state or ordering conflict. Resolve only the predecessor `complete.log` paths required by dependent siblings.
- [ ] **Inspect the implementation surface** — read targeted source/test regions, affected contracts, renamed or removed symbol references, and relevant manifests. Identify obvious dependency, import, type, or implementation risks statically; do not load unrelated files or compile.
- [ ] **Write the verification contract** — use the user-selected `test_env` or `local` by default. Read applicable rules/profiles or a static fallback, then record test additions or gaps, exact commands, workdir, expected results, cache policy when stale results could hide failure, and any non-local preflight assumptions. Do not execute commands, probe environments, or mutate test rules.

## Step 3 - Finalize Task Routing

This step is mandatory and must be the last semantic decision before routed filenames are fixed. Complete Step 2 and prepare the full plan structure in memory before starting it.

- [ ] **Build neutral input** — for each sibling, prepare its scope, affected paths, invariants, context size, sibling-set position, verification plan, available existing evidence, ownership, unresolved decisions, and existing failure evidence for `build` and `review`. Exclude every previous lane, grade, routing score, rationale, filename, and archive basename that exposes them.
- [ ] **Select evaluation mode** — use `first-pass` for new work and `isolated-reassessment` for `plan-ready` findings. Exclude the previous lane, grade, score, rationale, and preferred route.
- [ ] **Run the routing skill** — read and fully execute `agent-ops/skills/common/finalize-task-routing/SKILL.md` with both targets independently for each sibling. Do not reproduce or replace its decision logic inside this skill. Do not return `blocked` merely because a separate evaluation context or explicit follow-up instruction is unavailable.
- [ ] **Resolve non-final states** — for `needs_evidence`, collect only static planning facts and rerun. Never execute implementation verification.
- [ ] **Accept only a fully routed set** — require independent `build` and `review` closure records, lane, grade scores, GNN, and canonical filename for every sibling. If any new sibling is not routed, write none of the new sibling batch.
- [ ] **Freeze the result** — use each sibling's exact basenames in Steps 4-6. If any routing input or sibling boundary changes before files are written, discard the affected set and repeat this step.

## Step 4 - Prepare Task Files

Apply this step independently to every routed sibling directory. Do not archive or overwrite unrelated active siblings.

- Validate that the task directory contains at most one active routed pair, at most one staged pair, and at most one `USER_REVIEW.md`. Reject ambiguous, malformed, or identity-mismatched files.
- For multi-sibling work, require at most one `STAGED_BATCH.md` in the task-group parent.
- Ensure `.gitignore` exposes task Markdown and log files.
- Do not archive review artifacts. A `plan-ready` pair is already archived by the review model.
- For an explicit replan with an unstarted active pair, calculate its archive destinations but defer renames until the replacement pair is fully staged.
- Use monotonic suffixes for the new pair's future archive names.

Set each `next_log_suffix` to `0` when no matching log exists, otherwise `max(existing numeric suffix) + 1`. A normal new pair uses those suffixes. An explicit replacement archives the old pair at those suffixes and uses suffix plus one for the staged pair. Set `plan_number=plan_log_number`.

## Step 5 - Render Plan File

Render each complete plan in memory. Do not write the routed PLAN basename yet.

Header line must be exactly:

```markdown
<!-- task={task_name} plan={plan_number} tag={TAG} -->
```

Write the immutable Plan identity in a second metadata comment:

```markdown
<!-- plan-model={plan_model_identity} -->
```

Required sections:

- Title.
- `구현 에이전트 규칙`: keep this to four short bullets:
  - runtime has already verified encoded predecessor dependencies before dispatch; do not search `agent-task/**` or `agent-task/archive/**`;
  - change only the listed implementation files and follow the checklist/verification contract;
  - fill only implementation-owned fields in the review stub;
  - report `review-ready` and stop without reviewing, archiving, writing terminal files, or starting another agent.
- `배경`: 1-3 sentences explaining why the work is needed.
- `Archive Evidence Snapshot`: include this section only when the plan resumes from a resolved `user_review_*.log`, a prior archived review, or any archive evidence. Omit it for first-pass plans with no archive evidence. For resolved user review, include the resolution log path, decision, evidence, and its referenced archived pair. The section must otherwise contain only the archive facts needed to implement without rereading archive by default: prior task/archive paths, verdict, Required/Suggested/Nit summary, affected files, verification evidence, and any roadmap carryover. If exact prior context is still required, cite the specific archive file paths allowed to read; do not ask the implementer to search `agent-task/archive/**` broadly.
- `Roadmap Targets`: include this section only when the plan is intended to complete one or more existing Milestone 기능 Task ids. In a sibling set, include it only in the closure sibling whose directory dependencies cover every required predecessor. Omit the section entirely for non-roadmap work or partial siblings that should not check a Task on PASS. Format exactly:

```markdown
## Roadmap Targets

- Milestone: `agent-roadmap/phase/<phase-slug>/milestones/<milestone-slug>.md`
- Milestone link: [Milestone 문서](agent-roadmap/phase/<phase-slug>/milestones/<milestone-slug>.md)
- Task ids:
  - `<task-id>`: <Task text or concise label>
- Completion mode: check-on-pass
```
- `Agent UI Completion`: include this section only when the plan implements agent-ui definition/frame/component changes in code and code-review PASS should move specific agent-ui documents to `status: 구현됨`. Omit it for non-agent-ui work, `direct-sync` work handled entirely by `sync-agent-ui`, and `milestone-required` work whose status update is intentionally deferred to Milestone 종료 검토. Format exactly:

```markdown
## Agent UI Completion

- Mode: review-pass-status-update
- Agent UI docs:
  - `agent-ui/definition/views/<view-id>/index.md`
- Required code evidence:
  - `<code path>`: <what proves the UI definition is implemented>
- Required implementation verification:
  - `<test or analysis command>`: PASS expected before review
- Review finalization validation:
  - `validate-agent-ui scope=<scope>`: PASS expected after status/evidence update
- Status updates on PASS:
  - `agent-ui/definition/views/<view-id>/index.md`: `계획` -> `구현됨`
```
- `구현 범위`: give the worker only execution-relevant facts:
  - exact write set;
  - required behavior, invariants, and public/inner contract constraints;
  - only the source/spec/test-rule paths needed while implementing;
  - tests to add or update;
  - explicit exclusions.
  Keep routing scores, lane rationale, full read inventories, split deliberation, and dependency-resolution history out of the generated plan. The routed filenames and task directory already preserve those decisions. For SDD work, include only the applicable SDD path, Acceptance Scenario ids, Milestone Task ids, and required evidence behavior.
- `구현 체크리스트`: a top-level checklist the implementing agent must follow while coding. Include one item per implementation/verification unit; if the roadmap feature Task has `검증:`, keep that verification in the same checklist item. Make the final item exactly: `- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 채우고 review-ready를 보고한 뒤 현재 실행을 종료한다. code-review를 실행하거나 다음 에이전트를 시작하지 않는다.` Copy it into the review stub unchanged.
- One item per change: `### [TAG-1] Title`, `TAG-2`, etc.
- `수정 파일 요약`: table mapping files to item ids.
- `최종 검증`: runnable commands and expected outcome. Prefer commands from the matched agent-test env/profile rules. The final line must read exactly — **"검증 결과를 review stub에 기록하고 review-ready를 보고한 뒤 현재 실행을 종료한다. code-review를 실행하거나 다음 에이전트를 시작하지 않는다."**

Each plan item must include the applicable fields below:

- `문제`: concrete problem with file:line references.
- `해결 방법`: exact approach and before/after code block for non-trivial changes.
- `수정 파일 및 체크리스트`: exhaustive file-level checklist.
- `테스트 작성`: explicit write/skip decision. If writing tests, include path, test name, assertion goal, and fixtures. If skipping, justify.
- `중간 검증` (optional): include it only when a later plan item depends on that result; otherwise rely on final verification.

Describe within-task implementation order only when one plan item depends on another. Do not copy sibling dependency status into the generated plan or instruct the implementation worker to inspect `complete.log`; `{subtask_dir}` and runtime remain the dependency source of truth.

Quality rules:

- Exact line numbers in every Before snippet.
- Use the language's required override annotation/keyword wherever an abstract method is implemented.
- Include full import statements for new packages.
- List all call sites for renamed/removed symbols.
- Never write "add tests as needed"; decide up front.
- Do not cite files you did not read.
- Be concise. Write the minimum words needed to convey the decision or fact. No preamble, no restatement of context already in the plan, no closing summaries.

Test policy:

| Change | Test requirement |
|--------|------------------|
| Bug fix | Regression test required |
| New public API | Normal + boundary tests required |
| API rename | Existing test call-site updates usually enough |
| Internal refactor | Existing tests may be enough |
| Concurrency logic | Race/ordering test recommended |

Verification fidelity rules:

These are execution rules for build and review, not commands for the plan author to run.

- Plan verification commands are a contract. The implementing agent must run them exactly as written.
- If a command must be changed, the implementing agent must record the replacement command and reason in `계획 대비 변경 사항`, then paste the replacement command's actual stdout/stderr.
- Before claiming a tool is unavailable, run and record `command -v <tool>` or the project-equivalent check.
- Before a remote/field/external verification command assumes a checkout, binary, config, runtime identity, or listening port, the plan must include a preflight command that proves those assumptions or a setup command that makes them true.
- Do not download, generate, or leave verification tools inside the repository. Temporary tools belong outside the repo, such as under `/tmp`, and must not become task artifacts.
- For search commands whose output order may vary, specify deterministic options in the plan, for example `rg --sort path`.
- `검증 결과` must contain actual stdout/stderr, not summarized or reconstructed output. If output is too long, record the saved output file path and the exact command used to create it.
- If mobile/UI verification has no progress for 2 minutes or times out, stop blind retries; collect focused stdout plus screenshot/window/UI-tree evidence when available, or record why capture is impossible.
- If the plan's pass condition says all leftovers must be intentional exceptions, any `변경 필요` item forces FAIL until resolved or explicitly reclassified with evidence.
- Decide in the plan whether Go test cache output is acceptable. If fresh execution matters, use `go test -count=1 ...`.

## Step 6 - Write Review Stub

Read `agent-ops/skills/common/plan/templates/review-stub-template.md` in full only after Step 3 returns `status: routed` for the complete new sibling set.
Replace every occurrence of each token below:

- Scalar tokens: `{date}`, `{task_name}`, `{plan_number}`, `{TAG}`, `{plan_model_identity}`.
- Plan-copy tokens: `{roadmap_targets_or_omit}`, `{archive_evidence_snapshot_or_omit}`, `{agent_ui_completion_or_omit}`, `{implementation_checklist}`, `{review_checkpoints}`.
- Generated row/section tokens: `{implementation_completion_rows}` contains one row for every plan item, and `{verification_result_sections}` contains the fixed verification instructions plus every intermediate/final command from the plan.
- `{implementation_user_review_request_section}` is replaced by the full contents of `agent-ops/skills/common/_templates/implementation-user-review-request-section.md`; do not prepend another `사용자 리뷰 요청` heading.

`{review_checkpoints}` contains only product behavior, scope, contract, and verification focuses useful while implementing. Do not include model identity, dependency/`complete.log`, archive, terminal-output, or finalization checks; the Review skill owns those controls.

Use the routed build/review grades independently. Remove optional plan-copy content by replacing its token with an empty string, not by leaving template instructions.
Do not write any pair when a sibling's routing target is not `routed`. After rendering, scan every stub for the exact template-token inventory above and reject the output if any known token remains; do not reject unrelated braces in copied commands or code.

For a multi-sibling set, first write `STAGED_BATCH.md` with the task group, Plan identity, complete sibling paths, frozen scopes, routed basenames, and source-evidence fingerprints. Recovery must finish every listed pair without changing scope/routing; reject fingerprint drift. Remove the batch marker only after all listed pairs are verified.

For each sibling, write the complete plan to `STAGED_PLAN.md`, then the complete stub to `STAGED_CODE_REVIEW.md`. An existing staged plan is immutable: use it as the render source, create only a missing staged review, and reject conflicts. Verify both headers, identities, routed basenames, and bodies before promotion.

For an explicit replacement, preflight the old pair's calculated log destinations after both staged files exist, then rename the old review and old plan. On interruption, match the remaining old member, archived counterpart, and staged pair by task/plan headers; finish only the missing old archive and never overwrite a log.

Preflight both routed destinations, then rename `STAGED_PLAN.md` to the routed PLAN basename and `STAGED_CODE_REVIEW.md` to the routed CODE_REVIEW basename. If only the PLAN was promoted, verify it against the staged identity and promote only the remaining review. Never reroute or create a second PLAN during staged recovery.

After every pair is promoted, resolve only its encoded predecessor `complete.log` evidence and report the pair path with exactly one readiness value: `implementation-ready` or `dependency-waiting`. Do not start an implementation agent. Runtime re-evaluates a waiting task before later dispatch.

## Naming

| Tag | Use for |
|-----|---------|
| `API` | Public API changes |
| `REFACTOR` | Internal refactoring |
| `TEST` | Test additions/fixes |
| `REVIEW_<TAG>` | Follow-up fixes after review |

## Final Checklist

- Every planned sibling has one fully routed PLAN/CODE_REVIEW output pair for the correct task path, with matching headers, checklist, conditional sections, and no template tokens.
- No `STAGED_BATCH.md`, `STAGED_PLAN.md`, or `STAGED_CODE_REVIEW.md` remains after every routed pair is verified.
- Directory names encode every real dependency; parallel siblings have no write, state, ordering, or contract conflict. Unsatisfied dependent siblings are reported as `dependency-waiting`, not dispatched.
- `Roadmap Targets`, Agent UI, archive evidence, and user-review sections appear only when their stated conditions apply and match between PLAN and CODE_REVIEW; concise SDD targets remain in the PLAN implementation scope.
- Verification records the selected environment, static sources, test decision, commands, and expected results without plan-time execution output. Intermediate verification appears only when it adds an early failure signal.
- The plan model wrote the routed pair, reported `implementation-ready` or `dependency-waiting` from dependency evidence, and stopped without implementing, reviewing, or starting another agent.
- An explicitly replaced unstarted pair was archived only after its replacement pair was fully staged, with distinct monotonic log suffixes.
- Follow-up routing does not inherit prior lane/G, and implementation/user-review ownership remains unchanged.
- Every generated review ledger states the three-model separation, and the PLAN worker rules state the one-role-per-invocation boundary.
- The PLAN metadata comment and review ledger contain the same runtime-provided Plan model identity; Implementation and Review identities remain pending until runtime starts those roles.
