---
name: plan
description: Analyze the current repository and write a detailed PLAN-{build_lane}-GNN.md plus CODE_REVIEW-{review_lane}-GNN.md stub for implementation work. Use for every feature, refactor, bug fix, and code-review WARN/FAIL follow-up that enters the plan-code-review loop. Every initial or follow-up pair must run finalize-task-routing after analysis and before routed filenames are chosen. Milestone-linked work uses an m-prefixed task group and first-line milestone-task ids so PASS logs can be aggregated by sync-milestone-workstate.
---

# Plan

## Purpose

Create the planning artifacts for the implementation loop:

```text
plan skill -> analysis -> finalize-task-routing -> PLAN-{build_lane}-GNN.md + CODE_REVIEW-{review_lane}-GNN.md stub
implementation -> code changes + filled implementation evidence in CODE_REVIEW-{review_lane}-GNN.md
code-review skill -> verdict + archive, complete.log and task-directory archive move, USER_REVIEW.md, or mandatory plan-skill follow-up
runtime -> for m-prefixed PASS completion events, aggregate complete.log evidence with sync-milestone-workstate
```

`code-review` may stop the automatic loop with `USER_REVIEW.md` for either a selected Milestone `구현 잠금 > 결정 필요` item (`milestone-lock`) or required external verification that cannot proceed without a user-controlled runner, device, credential, interactive session, evidence handoff, or explicit authorization (`external-execution`). A current-host mismatch or missing command is not enough when a repository-declared runner or authorized executor can perform the step automatically. Repeated non-PASS reviews and missing evidence are not user-review reasons by themselves. Plan creation after `USER_REVIEW.md` requires its recorded user action or decision to be resolved. If that resolution closes the task as complete/PASS, code-review writes `complete.log` and archives the task instead of creating a new plan.

The plan file and review stub must be self-sufficient for implementation agents that do not read this skill. Implementing agents fill the active review's implementation evidence. They never decide whether user review is needed, write a user-review request, ask the user for a decision, create `USER_REVIEW.md`, or modify runtime-owned artifacts; those control-plane responsibilities belong to the official code-review skill and runtime.

## 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.

Invocation modes:

- `write` is the default for initial plans and explicit replans. After routing, this skill archives any prior active pair and writes the new pair.
- `prepare-follow-up` is used only when code-review has appended WARN/FAIL but has not archived the active pair. This skill completes analysis, final routing, and exact PLAN/review-stub rendering in memory without mutating repository files. It returns `prepared_plan`, `prepared_review`, their routed basenames, the current pair's predicted archive names/numbers, and the post-archive log counts used by the new pair.
- Both modes execute the same mandatory Step 3. `prepare-follow-up` is not a route-only shortcut.

Optional context:

- `verification_context` is a neutral handoff containing environment, source paths, commands, expected results, preconditions, read-only preflight results, constraints, gaps, and confidence. Consume it when supplied, but verify that its paths and commands still match the current checkout. The plan remains responsible for repository-native fallback analysis when it is absent or incomplete.

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 used only for split work and follows the existing indexed directory 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 single-plan task or `{task_group}/{subtask_dir}` for a split subtask.
- A single-plan task stores active files directly under `agent-task/{task_group}/`.
- Split work stores active files under `agent-task/{task_group}/{subtask_dir}/`; the parent `agent-task/{task_group}/` contains no active plan/review files.

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`.

Role boundary rules:

- Keep root cause, scope, ownership, and next-state decisions under plan/review, and validate their artifacts directly; dispatcher use is optional. Let implementing agents execute the packet without reinterpreting findings or changing its owner/write boundary.
- Implementing agents fill implementation-owned `CODE_REVIEW-*-G??.md` sections, keep active files in place, and report ready for review.
- If implementation cannot continue, implementing agents record the exact blocker, attempted commands/output, and resume condition only in `Verification Results` or `Deviations from Plan` (legacy: `검증 결과` or `계획 대비 변경 사항`), then leave the active files in place for official review.
- During implementation, do not ask the user directly, present choices, call user-input tools, or create control-plane stop files. The official reviewer owns all next-state classification.
- Required evidence capture that needs a user-owned runner, device, emulator, permission, secret, interactive access, evidence handoff, or explicit external authorization unavailable to the agent is a verification blocker for the implementing agent. Record the declared execution target, attempted routing/preflight commands, actual output, authorization state, and resume condition in `Verification Results` or `Deviations from Plan` (legacy: `검증 결과` or `계획 대비 변경 사항`) so the official reviewer can evaluate the `external-execution` gate.
- Finalization (`Code Review Result` [legacy: `코드리뷰 결과`], plan/review log rename, `complete.log`, task artifact archive moves, review-only checklist) is code-review-skill only.

Split decision policy:

- Split only by behavior/contract boundaries whose children each have a stable intermediate contract and deterministic PASS verification.
- Keep every production change with its required tests; use a test-only child only for additional integration evidence.
- Keep one plan when the work is compact or split would sever one correctness/transaction invariant. Never split to lower lane, grade, context, or signature count.
- If the existing analysis cannot prove that children independently PASS, keep the atomic work together and route it as one packet.
- Record either each child's contract/dependency or the invariant that makes one plan indivisible.

Split gates:

- Separate foundation from rollout only when the foundation preserves compatibility and independently passes.
- Split domains, verification profiles, or risk slices only when each independently passes.
- Split work that can produce a useful earlier `complete.log` without invalid intermediate state.
- Isolate mobile/UI/external verification that can block otherwise completed implementation.

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 the top-level `{task_group}` name and the first-line `milestone-task` ids preserved in `complete.log`. It resolves `<milestone-slug>` by matching exactly one active file at `agent-roadmap/phase/*/milestones/<milestone-slug>.md`; archive paths are not target candidates.
- When split gates require decomposition, create one shared category folder and multiple subtask directories under it. Each subtask directory owns exactly one normal active plan file and one normal active review stub.
- Multi-plan output is a set of independent `PLAN-{build_lane}-GNN.md` + `CODE_REVIEW-{review_lane}-GNN.md` pairs across `agent-task/{task_group}/{subtask_dir}/` folders, not multiple plan files inside one folder.
- Multi-plan subtask directory names must start with a stable two-digit task index. The index must increase across sibling subtask directories for sorting, but it is not a serial execution dependency.
- Assign new sibling indices in topological dependency order so every producer precedes its consumers. For ties, keep the planned sibling order; assign each task the lowest collision-free two-digit index greater than all of its predecessors.
- Before writing the pairs, verify that the sibling dependency graph has no cycle and every predecessor index is lower than its consumer index. Skip an index only when it is not greater than an unchanged existing predecessor or is already occupied by an active/archived sibling.
- 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 multi-plan subtask 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.
- Runtime scheduling reads only the `{subtask_dir}` name: `_` means `depends_on=[]`; `+` means `depends_on` is the comma-separated index list between `+` and the first `_`.
- 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.
- Example: split a refactoring common core plus two app integrations under `agent-task/refactoring/` as `01_core`, `02+01_app_a_integration`, `03+01_app_b_integration`. Both integrations depend only on `01_core` and may run in parallel after `01_core` has `complete.log`.
- Example: split three sequential tasks under one task group as `01_schema`, `02+01_migration`, `03+02_api`.
- Example: split independent docs/UI plus an integration under one task group as `01_core`, `02+01_db`, `03+02_api`, `04_docs`, `05_ui`, `06+05_integration`; `01_core`, `04_docs`, and `05_ui` can start together, and `06+05_integration` waits only for `05_ui`.
- After a pair is written, preserve its task group and subtask directory name verbatim. Only an explicit `refine-plans` run may rename eligible unstarted siblings by its dependency-order rules.

Final routing boundary:

- Keep the task `unrouted` until split, PLAN body, verification, evidence, ownership, and decisions are complete.
- Treat each final in-memory PLAN as its build packet. Derive `large_indivisible_context` and positive loop-risk signatures once from analysis already required to write that PLAN; do not create a separate packet summary or search for negative risk evidence.
- Execute `finalize-task-routing` once for build/review and use only its lane/G/filenames. Apply it to first-pass, follow-up, USER_REVIEW replan, and each split subtask independently.
- Quarantine previous lane/G/score/rationale. Carry only revalidated code, findings, command output, `review_rework_count`, and `evidence_integrity_failure`.
- `needs_evidence` names genuinely missing closure evidence; `blocked` stops file creation. Changed plan facts invalidate the route.
- Only `refine-plans` may replace an unstarted pair with strict-subset children. It must run `finalize-task-routing` in `isolated-reassessment` mode for every completed child packet and must not retain the parent route.

Directory states:

| State | Meaning |
|-------|---------|
| `PLAN-*-G??.md` only | Invalid; plan skill always writes both active files |
| `PLAN-*-G??.md` + `CODE_REVIEW-*-G??.md` stub | Implementation is pending/in progress |
| `PLAN-*-G??.md` + filled `CODE_REVIEW-*-G??.md` without verdict | Ready for code-review skill |
| `PLAN-*-G??.md` + `CODE_REVIEW-*-G??.md` with appended verdict | Review finalization is pending. Continue only when code-review invokes `prepare-follow-up`; `write` mode must not overwrite this state. |
| `complete.log` + `*.log` files | Task complete (PASS or user-review-resolved PASS), before final task-directory archive move |
| `USER_REVIEW.md` + `*.log` files | Automatic loop stopped; its recorded Milestone decision or external-execution user action must be resolved before creating another plan |
| `agent-task/archive/YYYY/MM/{task_name}/complete.log` + `*.log` files | Archived completed task path (PASS or user-review-resolved PASS); not active |
| Only `*.log` files (no `complete.log`) | Inspect the newest review log. A verdict with no required next state is post-archive finalization pending; otherwise the task is terminated mid-loop or abandoned. |

## Step 1 - Determine Task

If the user names the task explicitly, use that task group or task path.

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

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

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

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

| Result | Action |
|--------|--------|
| Exactly one | Continue that task |
| 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. |

The routed plan file is the loop entry point. A missing active plan normally means only that no plan has been started for a new task; do not create task files for casual analysis, status, or review requests unless the user explicitly asks for a plan.

If no active plan exists but one or more `USER_REVIEW.md` files exist, report the recorded user action or decision and list the paths unless one path is explicitly selected for resolution or replanning. If a selected active task directory contains `USER_REVIEW.md`, read it before planning. Do not write a new follow-up plan unless the recorded action or decision has been resolved or the new plan explicitly replans around that resolution. When planning resumes from `USER_REVIEW.md`, archive it to `user_review_N.log` in the same task directory before writing the new active plan/review pair, and record the resolved action or decision in the new plan `Background` or `Analysis` (legacy: `배경` or `분석 결과`).

If a selected task directory contains both `USER_REVIEW.md` and active `PLAN-*-G??.md` or `CODE_REVIEW-*-G??.md`, report an inconsistent loop state and do not overwrite either state until a later explicit command selects either user-review resolution or the active plan/review path.

If the selected review already has an appended verdict, accept it only in `prepare-follow-up` mode invoked by code-review. In every other mode, leave the pair unchanged and report that code-review finalization must resume.

로드맵 확인:

- `agent-roadmap/current.md`는 브랜치별 로컬 포인터다. 있으면 구현 계획 파일을 만들기 전에 읽고, 사용자 요청, 브랜치, 변경 경로를 기준으로 관련 Phase와 Milestone을 선택한다.
- `agent-roadmap/priority-queue.md`가 있으면 명시 target이 없는 구현 계획에서 prefix별 후보와 차단 예외를 확인하기 위해 읽는다. 상태/잠금/기능 원본은 각 Milestone 문서다.
- 각 prefix에서 가장 작은 active index 하나만 lane head 후보로 둔다. `선행 차단`이 남은 후보는 제외하고, `동시 차단` target이 현재 실행 중이면 제외한다. 다른 prefix의 열린 head들은 병렬 후보이며 문서상 위쪽 group은 target 없는 "다음 작업"의 tie-breaker로만 쓴다.
- 사용자가 Milestone을 명시해도 같은 prefix의 더 작은 active index, `선행 차단`, 현재 진행 중인 `동시 차단` target이 있으면 plan을 만들지 않고 실행 순서 차단을 보고한다.
- queue의 설명은 후보 이해에 유지하되 scheduling 판단에는 tag, link target, exact `선행 차단`/`동시 차단` label만 사용한다.
- `priority-queue.md` 링크, 실행 태그, group-prefix, blocker 참조가 깨졌으면 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에서 split work가 필요하면 기존 split 규칙 그대로 `agent-task/m-<milestone-slug>/<subtask_dir>/` 아래에 계획 파일을 만든다.
- Milestone 작업 계획은 첫 줄에 `milestone-task=<task-id>[,<task-id>...]`를 넣어 이 작업이 기여하는 기존 기능 Task id를 고정한다. id는 선택한 활성 Milestone `기능` 섹션에 실제로 존재해야 하고, `rules-roadmap.md`의 item-id 문법을 따르며, 중복 없이 쉼표로 구분하고 공백을 넣지 않는다.
- `milestone-task`는 PASS 즉시 체크할 완료 주장이나 plan 하나당 Task 하나라는 뜻이 아니다. 여러 plan이 같은 id에 기여할 수 있고 한 plan이 여러 id에 기여할 수 있다. 이후 `sync-milestone-workstate`가 같은 Milestone task group의 모든 `complete.log`를 id별로 모아 Task 설명·검증·SDD evidence 충족 여부를 평가한다.
- Milestone 범위의 하위 구현이나 조사도 관련 기능 Task id가 명확하면 같은 id를 기록한다. 관련 id를 정할 수 없다면 `m-*` task group으로 계획하지 말고, 먼저 Milestone 기능 Task를 보강하거나 비마일스톤 task group으로 분리한다.
- WARN/FAIL follow-up은 범위가 그대로면 이전 `milestone-task` id 목록을 정확히 유지한다. 범위를 바꾸는 경우에만 현재 Milestone과 SDD mapping을 다시 확인해 id를 명시적으로 교정하며, id가 조용히 누락되거나 다른 id로 바뀌면 안 된다.
- `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 split decision policy above. When the policy allows a single plan, write active files directly under `agent-task/{task_group}/` and record the exception rationale. When the policy requires multiple plans, choose one shared `{task_group}` and `{subtask_dir}` names using the task directory naming rules above. Do not put multiple active plan files in one active task directory, and do not mix split subtask directories with active plan/review files directly in the parent task group.

## Step 2 - Analyze Before Writing

Complete all items below before creating active plan/review files. Work through them in order; do not proceed to the next step until every checkbox is done. Keep the user request as the scope anchor and reconcile derived acceptance conditions before the split decision; do not create a separate routing summary. The only allowed file edits before writing plan/review files are local `agent-roadmap/current.md` creation or `.gitignore` block repair needed for roadmap routing.

- [ ] **Resolve verification context** — because implementation plans include verification, consume supplied `verification_context` when present and confirm its source paths, commands, expected results, preconditions, constraints, gaps, and confidence still apply. When it is absent or incomplete, derive the missing facts from repository manifests, scripts, workflows, domain rules, related tests, user-provided environment facts, and safe read-only probes. Record which facts came from the handoff and which came from repository-native fallback evidence. A missing optional handoff is not a user-review blocker.
- [ ] **Read all source files in full** — read every source file the change will touch, whole file. No partial reads.
- [ ] **Preflight external verification** — when any required verification leaves the current checkout, including remote runner, field/bootstrap, external provider, Docker/code-server, emulator/device, or shared long-running runtime, confirm or derive a read-only preflight before writing final verification commands. Record runner, repo root/workdir, branch/HEAD/dirty state, source sync status, binary/artifact paths, command help/version output needed by the verification, config path, runtime identity, ports/process state, external hosts, and OS/arch assumptions. If the preflight shows stale artifacts, dirty/divergent checkout, wrong identity, missing command, closed ports, host OS mismatch, or unsynced source, add an explicit setup/sync/rebuild step or report the blocker.
- [ ] **Read all test files in full** — read every test file that exercises the changed behavior, including files identified by the verification context and repository test layout.
- [ ] **Assess test coverage** — for each behavior change, explicitly record whether existing tests cover it.
- [ ] **Assess split boundaries once** — reconcile request acceptance with source/tests, then split only where every child has a stable contract and independent PASS verification. Otherwise keep the invariant together; do not gather extra evidence solely to lower routing risk.
- [ ] **Capture recovery signals once** — first-pass uses `review_rework_count=0` and `evidence_integrity_failure=false`. In `prepare-follow-up`, reuse the values already validated and appended by code-review; do not recount verdict history. For another isolated replan, derive them once from the same-task state already loaded for planning, without a routing-only log pass.
- [ ] **Resolve follow-up findings once** — in `prepare-follow-up`, map every inherited Required/Suggested id. Default repository-fixable work to `direct-fix` with exact root-cause files, overriding stale verification-only exclusions. Allow `verified-dependency` only when an exact active PLAN claims those files and task-protocol ordering applies, or when `complete.log` plus fresh evidence proves the failed precondition is satisfied; vague owners or `complete.log` alone are invalid. Set `ownership_closed=true` only after all mappings are proven. Reject unchanged-precondition verification loops. Reuse the existing analysis; add no model, sub-agent, or routing-only pass.
- [ ] **Resolve split predecessor completion** — if the selected or proposed subtask directory has `NN+PP[,QQ...]_...`, resolve each predecessor index under the same task group. Check only the active and archive candidate patterns defined in the task directory naming rules. Record found active/archive paths, missing predecessors, or ambiguous matches in `Analysis > Split Judgment` (legacy: `분석 결과 > 분할 판단`) and, when order matters, `Dependencies and Execution Order` (legacy: `의존 관계 및 구현 순서`).
- [ ] **Grep all symbol references** — for any renamed or removed symbol, find every call site and import chain.
- [ ] **Check dependency manifests** — before adding any dependency, inspect the repository's relevant dependency manifest and lockfile, confirm whether it already exists, and follow the repository-native version and update policy.
- [ ] **Pre-check compile issues** — identify missing interface implementations, type mismatches, and broken imports.
- [ ] **Verify verification commands** — confirm that the final verification commands actually run in this repository layout.
- [ ] **Stabilize fragile verification** — for search or generated-output checks, choose deterministic commands up front, such as `rg --sort path`, and decide whether cached test output is acceptable or the repository's test runner must use its fresh-run or cache-bypass option.
- [ ] **Derive routing signals once** — treat each completed in-memory PLAN as the worker packet. From facts already collected, record `large_indivisible_context`, positive matched loop-risk names/count, and recovery signals. Do not reread files, prove unmatched signatures false, or aggregate parent/sibling risk for routing.

## 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.

- [ ] **Freeze routing input and mode** — use the completed in-memory PLAN and existing analysis facts. Include closure, grade, `large_indivisible_context`, positive risk names/count, and recovery signals; exclude previous route fields. Use `first-pass` with no prior route, otherwise `isolated-reassessment`. Remove prior route fields in memory; do not create a sub-agent, packet document, or routing-only evidence pass.
- [ ] **Run routing once** — fully execute `agent-ops/skills/common/finalize-task-routing/SKILL.md` for build/review. Do not duplicate its decision rules in this skill.
- [ ] **Stop or accept** — `needs_evidence` may rerun only after collecting all named new evidence; `blocked` stops without task-file mutation. Accept `routed` only when finalizer identity, closure, base/final basis, signals, grade, lane, and filenames satisfy the routing skill.
- [ ] **Freeze routed names** — use the returned basenames unchanged in Steps 4-6. If an input fact changes before write, invalidate both routes and perform this step once again on the changed input.

## Step 4 - Archive Existing Active Files

In `write` mode, complete this step before writing new active files. In `prepare-follow-up` mode, calculate the same counts and archive names but do not modify any repository file; code-review owns the later archive.

- Validate that the task directory contains at most one active `PLAN-(local|cloud)-G(0[1-9]|10).md`, at most one active `CODE_REVIEW-(local|cloud)-G(0[1-9]|10).md`, and at most one `USER_REVIEW.md`. Reject ambiguous or malformed active names.
- In `write` mode, ensure `.gitignore` has the Agent-Ops managed gitignore block before renaming any active file to `*.log` or creating local `agent-roadmap/current.md`. Prefer `source agent-ops/bin/ai-ignore.sh && agent_ops_ensure_gitignore_task_artifact_block .gitignore`; if the helper is unavailable, add or update a block containing `!agent-task/`, `!agent-task/**/`, `!agent-task/**/*.md`, `!agent-task/**/*.log`, and `agent-roadmap/current.md`. In `prepare-follow-up` mode, only inspect the block and return `gitignore_repair_needed: true|false`; code-review performs any repair after preparation.
- Count existing `plan_*.log` as `current_plan_archive_number`. If an active plan exists, parse `current_build_lane` and `current_build_grade` from that active filename and set `current_plan_archive_name=plan_{current_build_lane}_{current_build_grade}_{current_plan_archive_number}.log`. Require that destination not to exist. In `write` mode rename that exact active file to the calculated name; in `prepare-follow-up` only return the name and number. Never use the newly routed build lane/grade to archive the old active plan.
- Count existing `code_review_*.log` as `current_review_archive_number`. If an active review exists, parse `current_review_lane` and `current_review_grade` from that active filename and set `current_review_archive_name=code_review_{current_review_lane}_{current_review_grade}_{current_review_archive_number}.log`. Require that destination not to exist. In `write` mode rename that exact active file to the calculated name; in `prepare-follow-up` only return the name and number. Never use the newly routed review lane/grade to archive the old active review.
- Count existing `user_review_*.log` as `current_user_review_archive_number`. If `USER_REVIEW.md` exists and its recorded user action or decision is resolved for replanning, set `current_user_review_archive_name=user_review_{current_user_review_archive_number}.log`; require that destination not to exist and rename it only in `write` mode.
- Compute `post_archive_plan_log_count`, `post_archive_review_log_count`, and `post_archive_user_review_log_count` from the filesystem after actual archive in `write` mode, or from the predicted addition of each current active file in `prepare-follow-up` mode.

Set `plan_number=post_archive_plan_log_count`. The new pair's future archive suffixes are `plan_log_number=post_archive_plan_log_count` and `review_log_number=post_archive_review_log_count`. These are intentionally different concepts from `current_plan_archive_number` and `current_review_archive_number`.

## Step 5 - Write Plan File

Render the complete plan in memory first. In `write` mode, write it to the routed plan basename. In `prepare-follow-up` mode, return the exact rendered body as `prepared_plan` and do not write it.

Header line must be exactly one of these forms:

```markdown
<!-- task={task_name} plan={plan_number} tag={TAG} -->
<!-- task=m-<milestone-slug>[/<subtask_dir>] plan={plan_number} tag={TAG} milestone-task=<task-id>[,<task-id>...] -->
```

Use the second form for every `m-*` task and the first form for every non-milestone task. The PLAN and review stub first lines must be identical.

Example:

```markdown
<!-- task=m-sample-capability/03+01,02_storage plan=0 tag=API milestone-task=sample-item -->
```

Required sections:

- Title.
- `For the Implementing Agent`: warn that filling implementation-owned `CODE_REVIEW-*-G??.md` sections is mandatory. Tell the implementer to run verification, fill actual notes/output, keep active files in place, and report ready for review; finalization is code-review-skill only. If blocked, the implementer records only exact blocker evidence, attempted commands/output, and resume conditions in implementation-owned evidence fields. It must not ask the user, call user-input tools, create control-plane stop files, classify the next state, archive logs, or write `complete.log`.
- `Background`: 2-4 sentences explaining why the work is needed.
- `Archive Evidence Snapshot`: include this section only when the plan resumes from `USER_REVIEW.md`, a prior archived review, or any archive evidence. Omit it for first-pass plans with no archive evidence. The section must 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.
- `Finding Resolution Map`: for WARN/FAIL follow-ups only, use one row per Required/Suggested id: mode, exact fix/dependency evidence, and changed/satisfied precondition. Put every `direct-fix` file in `Modified Files Summary`. For an unordered dependency, emit no worker packet; return `status=blocked`, `blocked_reason=dependency-wait`, `next-task`, and resume condition.
- `Analysis`: record the findings from Step 2 and the final routed output from Step 3. This section is the written output of the analysis — not a summary, but the actual findings that justify the plan's scope and decisions. Must include all of the following subsections:
  - `Files Read`: list every source and test file read during analysis, with path. List verification-context source files only when they were actually present and read.
  - `SDD Criteria`: for `SDD: 필요` Milestones, list the SDD path, status, first-line `milestone-task` ids, targeted Acceptance Scenario ids, and the Evidence Map rows that drive the plan. State explicitly how those rows shaped the implementation checklist and final verification. If the selected Milestone has `SDD: 불필요`, state the recorded reason. If the work is not Milestone-linked, state "not applicable".
  - `Verification Context`: state whether a handoff was supplied, every source path actually read, concrete commands/criteria applied, preconditions, constraints, gaps, confidence, and repository-native fallback evidence. If required verification leaves the current checkout, include an `External Verification Preflight` record with runner, repo root/workdir, branch/HEAD/dirty state, source sync status, binary/artifact paths, required command help/version output, config path, runtime identity, ports/process state, external hosts, OS/arch assumptions, and the exact setup/sync/rebuild step or blocker derived from mismatches.
  - `Test Coverage Gaps`: list each behavior change and whether existing tests cover it; explicitly note gaps.
  - `Symbol References`: list renamed/removed symbols and every call site found, or state "none" if no symbols were changed.
  - `Split Judgment`: for one plan, name the indivisible invariant or compact boundary; for split plans, list each child's stable contract, PASS evidence, and dependency. For dependent subtask plans, include each predecessor index and whether it is satisfied by an active or archived `complete.log`, missing, or ambiguous.
  - `Scope Rationale`: state which files or areas were explicitly excluded from this change and why. This is the boundary justification — the implementing agent must not silently expand scope beyond what is recorded here.
  - `Final Routing`: record `evaluation_mode`, finalizer, both targets' closure/grade/route, `large_indivisible_context`, positive loop-risk names/count, recovery signals, capability-gap evidence, and canonical filenames. Do not include or compare a previous loop's lane/G.
- `Implementation Checklist`: 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 instead of making a separate completion-criteria item. Include one item for whole-plan intermediate/final verification only when it is not already covered by the feature items. Make the last item exactly `- [ ] Fill implementation-owned sections in CODE_REVIEW-*-G??.md with actual implementation notes and verification output.` Copy this checklist into the review stub's `Implementation Checklist` section with the same item text and order.
- One item per change: `### [TAG-1] Title`, `TAG-2`, etc.
- `Modified Files Summary`: table mapping files to item ids. This is the skill-owned implementation write boundary.
  - Include exactly one `## Modified Files Summary` section and at least one exact workspace file path.
  - Wrap every claimed file path in backticks. A bare path cell is invalid.
  - Use repository-relative or canonical absolute file paths. Never use a glob (`*`, `?`, `[]`), directory path, workspace root, URL, path outside the workspace, malformed path, or prose placeholder as a claim.
  - Enumerate only implementer- or reviewer-owned workspace files, including the active review evidence file and deterministic workspace evidence artifacts.
  - For generated verification artifacts, choose deterministic exact workspace filenames or write them under a task-specific temporary directory outside the repository. Never substitute a directory or glob claim for dynamic filenames.
  - Before writing or returning a prepared pair, inspect the rendered PLAN itself and confirm this section occurs exactly once, is non-empty, and satisfies every path rule above. For a follow-up, also confirm every `direct-fix` target in `Finding Resolution Map` is present here.
- `Final Verification`: runnable commands and expected outcome. Prefer commands from verified handoff facts when supplied; fill missing coverage from repository manifests, scripts, workflows, domain rules, and related tests, and record the source in `Analysis > Verification Context`. Commands must be exact and deterministic enough for the reviewer to rerun; use stable ordering for searches and state whether cached test output is acceptable. End this section with **"After completing all code changes, fill implementation-owned sections in `CODE_REVIEW-*-G??.md`."**

Each plan item must include:

- `Problem`: concrete problem with file:line references.
- `Solution`: exact approach and before/after code block for non-trivial changes.
- `Modified Files and Checklist`: exhaustive file-level checklist.
- `Test Strategy`: explicit write/skip decision. If writing tests, include path, test name, assertion goal, and fixtures. If skipping, justify.
- `Verification`: runnable commands and expected result.

Include `Dependencies and Execution Order` only when order matters.

For split multi-plan work, the `{subtask_dir}` directory name is the runtime source of truth. If a plan has a `NN+PP[,QQ...]_...` subtask directory name, `Dependencies and Execution Order` (legacy: `의존 관계 및 구현 순서`) must echo the decoded predecessor subtask directories under the same task group that must produce `complete.log` before implementation starts, and it must not add dependencies that are absent from the directory name. If a predecessor already completed, cite the active or archived `complete.log` path that satisfies it.

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:

- 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 `Deviations from Plan` (legacy: `계획 대비 변경 사항`), 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`.
- `Verification Results` (legacy: `검증 결과`) 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 cached test output is acceptable. If fresh execution matters, use the repository's test runner option that forces a fresh run or bypasses cached results, and record the exact command.

## 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`.
Replace every occurrence of each token below:

- Scalar tokens: `{date}`, `{task_group}`, `{task_name}`, `{plan_number}`, `{TAG}`, `{milestone_task_metadata_or_omit}`, `{build_lane}`, `{build_grade}`, `{review_lane}`, `{review_grade}`, `{plan_log_number}`, `{review_log_number}`. Set `{milestone_task_metadata_or_omit}` to ` milestone-task=<ids>` for `m-*` and to an empty string otherwise.
- Plan-copy tokens: `{archive_evidence_snapshot_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.

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.
In `write` mode, write the rendered stub to the routed review basename. In `prepare-follow-up` mode, return it as `prepared_review` without writing.
Do not write or return a prepared pair when either routing target is not `routed`. After rendering, scan 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.

## Naming

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

## Final Checklist

- In `write` mode, the routed `PLAN-{build_lane}-GNN.md` and `CODE_REVIEW-{review_lane}-GNN.md` both exist under `agent-task/{task_name}/`. In `prepare-follow-up` mode, neither routed file was written; both exact bodies and basenames were returned while the verdict-appended current pair remained active.
- The plan skill directly checked the rendered PLAN before the pair was written or returned. Its single non-empty `Modified Files Summary` contains only exact workspace file claims and no glob or directory claim.
- In `write` mode, `.gitignore` has the Agent-Ops managed block that unignores `agent-task/**/*.md` and `agent-task/**/*.log` and ignores local `agent-roadmap/current.md`. In `prepare-follow-up` mode, the block was only inspected and any needed repair was returned as `gitignore_repair_needed`.
- Single-plan work stores active files directly under `agent-task/{task_group}/`.
- Split work, if any, uses one shared `agent-task/{task_group}/` parent and one subtask directory per plan/review pair with names like `01_core`, `02+01_app_a_integration`, `03+01_app_b_integration`; dependency details live in the subtask directory name as `NN+PP[,QQ...]_subtask_name`.
- Split sibling indices follow topological dependency order: every predecessor is lower than its consumer, and every gap is explained by an unchanged existing predecessor or an occupied active/archive index.
- Milestone-linked work uses `agent-task/m-<milestone-slug>/` as the task group; non-roadmap task groups do not start with `m-`.
- Both first lines are identical. Non-milestone pairs match `<!-- task={task_name} plan={plan_number} tag={TAG} -->`; `m-*` pairs append exactly ` milestone-task=<task-id>[,<task-id>...]` before ` -->`.
- The review stub was rendered from `agent-ops/skills/common/plan/templates/review-stub-template.md` after routing and has no unresolved known template token.
- In `write` mode, previous active files, if any, were archived with lane/grade parsed from their own basenames and the correct current archive suffixes. In `prepare-follow-up` mode, those archive names were only predicted.
- In `write` mode when resuming from `USER_REVIEW.md`, it was archived to the calculated `current_user_review_archive_name` and the resolved user action or decision was recorded in the new plan.
- Every `m-*` pair has a non-empty, duplicate-free `milestone-task` list whose ids exist in the selected active Milestone; non-milestone pairs omit the field.
- `milestone-task` ids describe evidence contribution scope, not check-on-PASS completion. Split/follow-up pairs preserve their declared scope under the refinement and follow-up rules.
- If the selected Milestone has `SDD: 필요`, the plan's `Analysis > SDD Criteria` (legacy: `분석 결과 > SDD 기준`) proves that the implementation checklist and final verification were derived from the approved SDD Acceptance Scenarios and Evidence Map. Missing SDD mapping blocks plan creation.
- If the plan is a follow-up or resumes from prior archive evidence, it has `Archive Evidence Snapshot` and the review stub contains the identical section.
- `Analysis > Verification Context` records supplied handoff facts, source paths actually read, external preflight, gaps, confidence, and repository-native fallback evidence.
- Dependent split plans record predecessor completion using active sibling `complete.log` or matching archived `complete.log`; ambiguous archive matches are not guessed.
- Every plan item has problem, solution, checklist, test decision, and intermediate verification.
- The plan and review stub have matching `Implementation Checklist` (legacy: `구현 체크리스트`) item text/order; their final checkbox is the mandatory `CODE_REVIEW-*-G??.md` evidence item.
- `finalize-task-routing` ran once after the PLAN body was complete, used no routing-only evidence pass, counted only positive packet-local risk, kept capability/grade basis from being relabeled by escalation signals, and produced matching filenames.
- Review WARN/FAIL follow-ups entered through this plan skill and did not inherit or compare the archived lane/G.
- Every WARN/FAIL finding has one proven direct fix or ordered/satisfied dependency; only then is ownership closed, and verification does not repeat against an unchanged precondition.
- The plan's implementer instructions and review stub limit local implementation agents to implementation/test/evidence work and keep user-review classification plus control-plane stop files out of their input and ownership.
- The review stub has a clearly marked `Review-Only Checklist` (legacy: `코드리뷰 전용 체크리스트`) owned only by the review agent.
- Routed review file completion table lists every plan item.
- In `prepare-follow-up`, no repository file was mutated and the returned prepared basenames/bodies, `plan_number`, current archive names/numbers, post-archive log counts, and `gitignore_repair_needed` are complete; in `write`, prior active state was archived with its own parsed route and both new active files were written.
