diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..76b9de6
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,42 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+permissions:
+ contents: read
+
+jobs:
+ opsmith-smoke:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v4
+ - name: Run install smoke test
+ run: bash tests/install-smoke.sh
+
+ ccpilot-tests:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
+ defaults:
+ run:
+ working-directory: modules/ccpilot
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install pytest
+ run: python -m pip install --upgrade pip pytest
+ - name: Run tests
+ run: python -m pytest -q
diff --git a/README.md b/README.md
index d99fb83..a2628dc 100644
--- a/README.md
+++ b/README.md
@@ -12,12 +12,15 @@

-success)

+[](https://github.com/KimHands/opsmith/actions/workflows/ci.yml)
> **무엇이 아닌가** — opsmith은 스킬·플러그인이 **아닙니다**. 특정 도구에 묶이지 않는
> **규칙·스크립트·훅으로 된 운용 계층**을 `~/Ops`에 설치하고, `~/.claude`에는 훅·권한만 얹습니다.
> 기존 설정을 덮어쓰지 않고 병합하며, 언제든 `uninstall.sh`로 되돌립니다.
+>
+> **공개본 상태** — 2026-08 기준 스냅샷이며, 작성자의 실제 운용과 다를 수 있습니다.
---
@@ -85,6 +88,7 @@ opsmith/
├── install.sh 멱등 설치기
├── uninstall.sh 병합분만 되돌림 (사용자 데이터 보존)
├── docs/ 설계 철학·버린 대안·운용 설명서
+├── modules/ccpilot/ 선택 모듈 (기본 설치에 포함되지 않음)
└── tests/ 격리 스모크 테스트
```
@@ -147,10 +151,27 @@ ops # ~/Ops 로 이동
---
+## 🧩 선택 모듈: ccpilot
+
+> 유지보수 중단. 작성자도 현재 사용하지 않으며(2026-08 워크플로우에서 비활성화), 테스트만 CI에서 유지합니다. 프리셋의 플러그인 목록은 작성 당시 환경 기준입니다.
+
+프리셋으로 프로젝트별 플러그인을 구성하고, `/route`로 에이전트 라우팅 계획을 만드는 도구입니다. `/route`는 계획만 만들며 실행은 메인 세션이 합니다.
+
+```bash
+bash modules/ccpilot/install.sh # ~/.claude 에 설치. 같은 이름의 파일은 덮어씁니다
+```
+
+제거 방법과 주의 사항은 [모듈 README](modules/ccpilot/README.md)를 보세요.
+
+`uninstall.sh`는 두 훅이 `settings.json`에서 별도 그룹일 때만 ccpilot 훅을 보존합니다. 한 그룹으로 합쳐 두면 함께 지워집니다.
+
+---
+
## ✅ 검증
```bash
-bash tests/install-smoke.sh # 임시 HOME에서 설치·멱등성 검증 (실제 홈 무해)
+bash tests/install-smoke.sh # 임시 HOME에서 설치·멱등성·ccpilot 공존 검증 (실제 홈 무해)
+(cd modules/ccpilot && python3 -m pytest -q) # ccpilot 테스트 (pytest 필요)
```
---
diff --git a/modules/ccpilot/.gitignore b/modules/ccpilot/.gitignore
new file mode 100644
index 0000000..1fe348e
--- /dev/null
+++ b/modules/ccpilot/.gitignore
@@ -0,0 +1,6 @@
+__pycache__/
+*.pyc
+.pytest_cache/
+data/
+venv/
+.superpowers/
diff --git a/modules/ccpilot/LICENSE b/modules/ccpilot/LICENSE
new file mode 100644
index 0000000..9203276
--- /dev/null
+++ b/modules/ccpilot/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 KimHands
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/modules/ccpilot/README.md b/modules/ccpilot/README.md
new file mode 100644
index 0000000..597982f
--- /dev/null
+++ b/modules/ccpilot/README.md
@@ -0,0 +1,151 @@
+# ccpilot
+
+> 유지보수 중단. 작성자도 현재 사용하지 않으며(2026-08 워크플로우에서 비활성화), 테스트만 CI에서 유지합니다. 프리셋의 플러그인 목록은 작성 당시 환경 기준입니다.
+
+
+
+[](https://github.com/KimHands/opsmith/actions/workflows/ci.yml)
+-success.svg)
+
+
+**프로젝트마다 Claude Code 플러그인·에이전트를 프리셋으로 구성하는 워크플로우 툴킷.**
+
+`ccpilot`은 두 개의 사용자 레벨 확장으로 이루어져 있다:
+
+- **A — 프로젝트 프리셋 워크플로우:** 새 프로젝트에서 프리셋으로 플러그인을 활성화하고, 그 조합에 맞는 **단계별 플레이북**(brainstorm → plan → implement → review → ship)을 자동 생성한다.
+- **B — 에이전트 라우팅 계획 생성:** 구체 작업에 맞는 특화 에이전트로 라우팅하는 **디스패치 계획**을 만든다. 실행과 종합은 메인 세션이 한다. 원본 스킬·에이전트는 수정하지 않는다.
+
+순수 Python 표준 라이브러리 + 마크다운 슬래시 명령/에이전트로 구현했다. 외부 의존성 없음.
+
+---
+
+## 설치
+
+**요구사항:** [Claude Code](https://code.claude.com) · Python 3.10+ · git. (런타임 외부 의존성은 없다 — 표준 라이브러리만 쓴다.)
+
+```bash
+git clone https://github.com/KimHands/opsmith.git
+bash opsmith/modules/ccpilot/install.sh
+```
+
+opsmith 기본 설치(`install.sh`)에는 포함되지 않는다.
+
+`install.sh`가 하는 일:
+
+- `pw/`·`pw_route/` → `~/.claude/`
+- `commands/*.md` → `~/.claude/commands/` (`/project-init` `/phase-next` `/project-status` `/project-activate` `/route`)
+- `agents/security-auditor.md`·`test-engineer.md` → `~/.claude/agents/`
+- `pw/presets.json` → `~/.claude/project-presets.json`, `pw_route/route-rules.json` → `~/.claude/route-rules.json`
+
+설치 후 **Claude Code를 재시작**하면 명령이 로드된다.
+
+**주의**
+
+- 같은 이름의 명령·에이전트 파일은 덮어쓴다.
+- `~/.claude/settings.json`에 SessionStart 훅을 추가하며, 이 파일을 백업하지 않는다.
+- `settings.json`이 깨져 있으면 설치가 중간에 실패한다. 이미 덮어쓴 파일은 복원되지 않고 킥오프 스킬도 설치되지 않는다.
+- `/project-init`은 `~/.claude/plugins/installed_plugins.json`이 필요하다. 플러그인을 한 번도 설치하지 않은 환경에서는 이 파일이 없어 `FileNotFoundError`로 실패한다.
+
+
+제거
+
+```bash
+rm -rf ~/.claude/pw ~/.claude/pw_route
+rm -f ~/.claude/commands/{project-init,phase-next,project-status,project-activate,route}.md
+rm -f ~/.claude/agents/{security-auditor,test-engineer}.md
+rm -f ~/.claude/project-presets.json ~/.claude/route-rules.json
+rm -rf ~/.claude/skills/project-kickoff
+```
+
+`~/.claude/settings.json`의 SessionStart에서 `hook_sessionstart.py` 항목도 삭제한다. 남겨 두면 세션을 시작할 때마다 없는 파일을 호출한다.
+
+
+## 데모
+
+```console
+$ cd my-new-app # (pyproject.toml + .py 파일 존재)
+> /project-init
+ 감지된 언어: python · 추천 프리셋: backend-api
+ ✓ .claude/settings.json (활성 8 · 비활성 12)
+ ✓ .claude/playbook.md · project-state.json · CLAUDE.md
+ → 새 세션에서 로드됨. 다음: /phase-next
+
+> /route 이 코드 보안 감사해줘
+ domain: security → security-auditor (available)
+ plan: kesekit + /semgrep + security-guidance 병렬 → 종합
+ 출력 계약: findings/evidence/inspected/confidence/unresolved/next
+```
+> 실제 스크린샷·GIF는 추후 추가 예정.
+
+---
+
+## 사용법
+
+### A — 프리셋 & 단계 워크플로우
+
+```
+/project-init # 프로젝트 유형 감지 → 프리셋 추천 → 적용
+/project-init web-fullstack # 프리셋 직접 지정
+/project-init minimal --dry-run # 변경 없이 미리보기
+
+/phase-next # 다음 단계로 진행 + 그 단계 도구 가이드
+/project-status # 현재 프리셋·단계·활성 플러그인
+/project-activate # 프리셋 밖 도구 추가
+```
+
+`/project-init`은 프로젝트 `.claude/settings.json`(활성 플러그인 allowlist+denylist), `playbook.md`, `project-state.json`, `CLAUDE.md` 포인터를 생성한다. 플러그인은 세션 시작 시 로드되므로 init 후 **한 번 재시작**한다.
+
+**프리셋:** `web-fullstack` · `backend-api` · `security-audit` · `docs-deck` · `minimal`. 정의는 `pw/presets.json` 하나에 있다 — 자유롭게 편집·추가 가능.
+
+### B — 에이전트 라우팅
+
+```
+/route 이 코드 보안 감사해줘 # → security-auditor로 라우팅 계획
+/route 테스트 작성하고 커버리지 확인 # → test-engineer로 라우팅 계획
+```
+
+`/route`는 **자율 실행자가 아니라 계획 생성기**다. `route-rules.json` + 설치된 에이전트를 live 조회해 규칙에 맞는 전문가를 고르고, 정확한 프롬프트·병렬 여부·출력 계약·종합 체크리스트가 담긴 디스패치 계획을 만든다. 실행·종합은 메인 세션이 한다.
+
+**전문가 에이전트:** `security-auditor`(kesekit·semgrep·security-guidance 종합) · `test-engineer`(test-writer-fixer·LSP·러너). 둘 다 원본 스킬을 그대로 호출하고 구조화 출력(findings/evidence/inspected/confidence/unresolved/next)을 반환한다.
+
+---
+
+## 설계 원칙
+
+- **저하 0:** 스킬·플러그인 에이전트 파일을 수정하지 않는다. 직접 매치되는 원본 에이전트를 우선한다. 종합 시 이견을 보존한다.
+- **충돌 회피:** 워크플로우 도구 하나 · 메모리 하나 · 리뷰는 주력 먼저 → 전문가는 트리거 시.
+- **세션 시작 로드 제약 반영:** 프리셋은 init 때 한 번에 활성화(재시작 1회), 단계는 사용 안내. B는 프로젝트·사용자 에이전트와 플러그인 캐시에서 디스크로 발견한 에이전트 사이에서 라우팅한다. 플러그인 활성화 여부나 현재 세션 로드 여부는 확인하지 않는다.
+
+---
+
+## 저장소 구조
+
+```
+pw/ # A: 프리셋·단계·플레이북 (data·detect·fsutil·playbook·state·cli)
+pw_route/ # B: 에이전트 라우팅 (discover·rules·cli)
+agents/ # B: security-auditor·test-engineer 정의
+commands/ # 슬래시 명령 (project-*·route)
+install.sh # ~/.claude 로 설치
+tests/ # pytest
+docs/superpowers/ # 설계 spec + 구현 plan (A·B)
+```
+
+## 개발
+
+```bash
+cd modules/ccpilot
+python3 -m venv venv && ./venv/bin/pip install pytest
+./venv/bin/python -m pytest -q
+```
+
+Python 3.10+ 표준 라이브러리만 사용한다(런타임 의존성 없음). 슬래시 명령은 `python3 ~/.claude/pw*/cli.py`를 스크립트로 실행하므로 각 `cli.py`는 sys.path 부트스트랩을 포함한다.
+
+## 버전 기록
+
+- **v0.3.0** (2026-07-06) — **의도 기반 킥오프** 스킬. "이 프로젝트 초기화해줘" 류 명시 발화 시 프리셋을 자동 추론하고 `--dry-run` 프리뷰 → **확인** → `/project-init` 실행까지 이어준다. 확률적 트리거라 **파일 쓰기 전 반드시 확인**하며, 확신이 낮으면 명령만 추천한다.
+- **v0.2.0** (2026-07-06) — SessionStart 훅 추가. 세션 시작 시 초기화된 프로젝트는 **현재 단계·도구를 자동 주입**하고, 미설정(소스 있는) 프로젝트는 **`/project-init` 을 제안**한다. 기존 훅 보존·멱등 설치.
+- **v0.1.0** (2026-07-06) — 최초. A(프리셋·단계 플레이북: `/project-init`·`/phase-next`·`/project-status`·`/project-activate`) + B(에이전트 라우팅 `/route` + 전문가 `security-auditor`·`test-engineer`). 순수 stdlib, 48 tests.
+
+## 라이선스
+
+MIT
diff --git a/modules/ccpilot/agents/security-auditor.md b/modules/ccpilot/agents/security-auditor.md
new file mode 100644
index 0000000..96bc943
--- /dev/null
+++ b/modules/ccpilot/agents/security-auditor.md
@@ -0,0 +1,33 @@
+---
+name: security-auditor
+description: >-
+ 이미 설치된 보안 스킬(kesekit KISA 점검, static-analysis의 /semgrep·/codeql,
+ security-guidance)을 한 격리 컨텍스트에서 돌려 결과를 중복제거·우선순위화하고
+ 이견을 보존해 종합한다. "보안 점검/취약점 감사/security review" 요청에 사용.
+tools: Bash, Read, Glob, Grep
+model: sonnet
+---
+
+너는 교차-플러그인 보안 종합가다. 아래 불변식을 지킨다.
+
+## 불변식
+- 어떤 스킬·플러그인 에이전트 파일도 **수정하지 않는다**. 읽고 실행만 한다.
+- 원본 스킬의 결과를 재해석·재구현하지 않는다. 그대로 인용한다.
+- 서로 다른 스킬의 이견을 합치지 말고 **보존**한다.
+
+## 절차
+1. 사용 가능한 것만 실행: kesekit 점검 스킬, `/semgrep`(가능하면 `/codeql`), security-guidance 가이드.
+ - 스킬이 없으면 그 관점을 생략하고 리포트에 폴백으로 명시한다.
+2. 각 도구 원출력을 수집한다(파일·라인·명령 근거 포함).
+3. 중복 지적을 합치되 출처를 잃지 않는다.
+
+## 출력 계약 (반드시 이 구조로 반환)
+- findings: 발견 목록(각 항목에 출처 도구 표기)
+- evidence: 파일/라인/명령 출력
+- inspected: 조사한 파일·명령
+- confidence: high | med | low
+- unresolved: 미해결 질문·이견
+- next: 권장 다음 행동
+
+## 과장 금지
+"도구가 X 보고"를 "X는 확실히 익스플로잇 가능"으로 승격하지 않는다 — 근거가 명확할 때만.
diff --git a/modules/ccpilot/agents/test-engineer.md b/modules/ccpilot/agents/test-engineer.md
new file mode 100644
index 0000000..82b1eed
--- /dev/null
+++ b/modules/ccpilot/agents/test-engineer.md
@@ -0,0 +1,29 @@
+---
+name: test-engineer
+description: >-
+ test-writer-fixer 스킬과 감지 언어 LSP, 테스트 러너를 한 격리 컨텍스트에서
+ 돌려 테스트 작성→실행→실패분석→수정 루프를 수행하고 커버리지 갭을 종합한다.
+ "테스트 작성/수정/커버리지" 요청에 사용.
+tools: Bash, Read, Write, Edit, Glob
+model: sonnet
+---
+
+너는 테스트 종합가다. 아래 불변식을 지킨다.
+
+## 불변식
+- 스킬·플러그인 에이전트 파일을 **수정하지 않는다**(대상 코드의 테스트만 작성/수정).
+- test-writer-fixer 등 원본 스킬의 동작을 재구현하지 않고 호출한다.
+- 통과/실패 결과를 임의로 낙관하지 않는다 — 실제 러너 출력을 근거로 삼는다.
+
+## 절차
+1. 대상 코드의 테스트를 작성/보강한다(test-writer-fixer 스킬 활용, 없으면 폴백 명시).
+2. 실제 러너로 실행한다(pytest/jest 등, 감지 언어에 맞게).
+3. 실패를 분석해 최소 수정하고 재실행한다. 커버리지 갭을 정리한다.
+
+## 출력 계약 (반드시 이 구조로 반환)
+- findings: 추가/수정한 테스트, 남은 갭
+- evidence: 러너 명령과 실제 출력(통과/실패 수)
+- inspected: 조사한 파일·명령
+- confidence: high | med | low
+- unresolved: 미해결 실패·불확실 영역
+- next: 권장 다음 행동
diff --git a/modules/ccpilot/commands/phase-next.md b/modules/ccpilot/commands/phase-next.md
new file mode 100644
index 0000000..fb3e812
--- /dev/null
+++ b/modules/ccpilot/commands/phase-next.md
@@ -0,0 +1,4 @@
+---
+description: 워크플로우를 다음 단계로 진행하고 그 단계의 도구 가이드를 출력한다
+---
+`python3 ~/.claude/pw/cli.py phase-next` 를 실행하고, 반환된 guidance(현재 단계 도구 순서)를 사용자에게 보여준다. atEnd 가 true 면 마지막 단계임을 알린다.
diff --git a/modules/ccpilot/commands/project-activate.md b/modules/ccpilot/commands/project-activate.md
new file mode 100644
index 0000000..c47e1ab
--- /dev/null
+++ b/modules/ccpilot/commands/project-activate.md
@@ -0,0 +1,5 @@
+---
+description: 프리셋 밖 플러그인을 이 프로젝트에 추가 활성화한다
+argument-hint:
+---
+`python3 ~/.claude/pw/cli.py activate $ARGUMENTS` 를 실행하고, "재시작 시 로드됨" 안내를 전달한다.
diff --git a/modules/ccpilot/commands/project-init.md b/modules/ccpilot/commands/project-init.md
new file mode 100644
index 0000000..db7dc33
--- /dev/null
+++ b/modules/ccpilot/commands/project-init.md
@@ -0,0 +1,11 @@
+---
+description: 새 프로젝트에 프리셋을 적용하고 단계별 플레이북을 생성한다
+argument-hint: [preset] [--dry-run|--force]
+---
+현재 폴더에서 프로젝트 프리셋 워크플로우를 초기화한다.
+
+사용자가 프리셋을 인자로 주지 않았으면, 먼저 `python3 ~/.claude/pw/cli.py status` 를 시도해 이미 초기화됐는지 보고, 아니면 폴더의 package.json/pyproject.toml 등을 근거로 프리셋(web-fullstack/backend-api/security-audit/docs-deck/minimal) 중 하나를 추천하고 확인받는다.
+
+확정되면 실행: `python3 ~/.claude/pw/cli.py init ` (미리보기는 `--dry-run`).
+출력 요약을 사용자에게 보여주고, **"새 세션에서 플러그인이 로드된다"** 는 점과 다음 스텝(`/phase-next`)을 안내한다.
+$ARGUMENTS
diff --git a/modules/ccpilot/commands/project-status.md b/modules/ccpilot/commands/project-status.md
new file mode 100644
index 0000000..b5e8d93
--- /dev/null
+++ b/modules/ccpilot/commands/project-status.md
@@ -0,0 +1,4 @@
+---
+description: 현재 프리셋·단계·활성 플러그인을 보여준다
+---
+`python3 ~/.claude/pw/cli.py status` 를 실행하고 결과(preset, phase, enabled/disabled)를 표로 정리해 보여준다.
diff --git a/modules/ccpilot/commands/route.md b/modules/ccpilot/commands/route.md
new file mode 100644
index 0000000..5919226
--- /dev/null
+++ b/modules/ccpilot/commands/route.md
@@ -0,0 +1,14 @@
+---
+description: 작업에 맞는 특화 에이전트 디스패치 "계획"을 만든다 (실행은 메인이 함)
+argument-hint: <작업 설명>
+---
+이 명령은 **자율 실행자가 아니라 디스패치 계획 생성기**다.
+
+1. 라우팅 컨텍스트를 얻는다: `python3 ~/.claude/pw_route/cli.py route "$ARGUMENTS"`
+ - 반환: domain, prefer(가용여부), narrow, fallback, availableAgents, note.
+2. note 에 "restart" 안내가 있으면 → 사용자에게 "이 세션엔 해당 능력이 없음, 프리셋 켜고 재시작(/project-activate)"을 전하고 멈춘다.
+3. 아니면 **디스패치 계획**을 만든다:
+ - 광범위 보안 → security-auditor, 정밀 semgrep 전용 → 원본 semgrep-scanner, 테스트 → test-engineer, 미지 작업 → 원본 플러그인 에이전트 우선(fallback).
+ - 각 선택의 이유 · 병렬 안전 여부 · 각 서브에이전트에 줄 정확한 프롬프트 · 기대 출력 계약(findings/evidence/inspected/confidence/unresolved/next) · 종합 체크리스트.
+4. 계획대로 서브에이전트를 디스패치한다(병렬 가능). **원본 스킬·에이전트는 수정하지 않는다.**
+5. 결과를 종합한다 — 이견을 보존하고, 각 주요 주장에 출처 에이전트를 표기하며, 과장하지 않는다.
diff --git a/modules/ccpilot/docs/superpowers/plans/2026-07-06-agent-orchestration-B.md b/modules/ccpilot/docs/superpowers/plans/2026-07-06-agent-orchestration-B.md
new file mode 100644
index 0000000..23e7e00
--- /dev/null
+++ b/modules/ccpilot/docs/superpowers/plans/2026-07-06-agent-orchestration-B.md
@@ -0,0 +1,670 @@
+# B — 특화 서브에이전트 오케스트레이션 구현 계획
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 구체 작업에 대해 이미 로드된 플러그인 에이전트·스킬 중 최적을 골라 디스패치 "계획"을 만드는 `/route` 명령 + 얇은 종합 전문가 2종(security-auditor·test-engineer)을 만든다.
+
+**Architecture:** 결정적 부분(에이전트 live 조회·규칙 매칭·라우팅 컨텍스트 생성)은 순수 파이썬 패키지 `pw_route/`가, 판단·디스패치는 메인 Claude가 실행하는 얇은 슬래시 명령/에이전트 마크다운이 담당한다. A의 `install.sh`를 확장해 함께 배포한다.
+
+**Tech Stack:** Python 3.10+ 표준 라이브러리만, pytest, 마크다운 에이전트/명령, JSON 규칙.
+
+## Global Constraints
+
+- Python 3.10+ 표준 라이브러리만 — 외부 의존성 금지.
+- 테스트는 `./venv/bin/python -m pytest` 로 실행(시스템 python3엔 pytest 없음).
+- `pw_route/cli.py`는 스크립트로 실행(`python3 ~/.claude/pw_route/cli.py …`)되므로 **맨 위에 sys.path 부트스트랩** 필수(A에서 겪은 교차 임포트 버그 방지).
+- `/route`는 자율 실행자가 아니라 **디스패치 계획 생성기**. 명령 마크다운은 그 점을 명시.
+- B는 스킬·원본 플러그인 에이전트 파일을 **절대 수정하지 않는다**(INV-1). 직접 매치되는 원본 에이전트를 우선(INV-2). 종합은 이견 보존(INV-3).
+- 전문가·명령 마크다운은 **구조화 출력 계약** 키를 포함: `findings, evidence, inspected, confidence, unresolved, next`.
+- 스키마 버전 = 1.
+- 기존 `~/.claude/agents/*.md`(pptx 등)를 덮어쓰지 않는다 — 신규 이름만 사용(security-auditor·test-engineer).
+
+---
+
+### Task 1: pw_route 패키지 + route-rules.json + 규칙 로드
+
+**Files:**
+- Create: `pw_route/__init__.py` (빈 파일)
+- Create: `pw_route/rules.py`
+- Create: `pw_route/route-rules.json`
+- Test: `tests/test_route_rules_load.py`
+
+**Interfaces:**
+- Produces: `pw_route.rules.load_rules(path: str) -> dict` — route-rules.json 로드, `schemaVersion==1` 검증, `rules`(list)·`fallback`(str) 키 필수. 위반 시 `ValueError`.
+
+- [ ] **Step 1: route-rules.json 작성**
+
+Create `pw_route/route-rules.json`:
+
+```json
+{
+ "schemaVersion": 1,
+ "rules": [
+ {
+ "domain": "security",
+ "match": ["보안", "security", "취약", "vuln", "audit", "감사"],
+ "prefer": "security-auditor",
+ "narrow": [{ "when": ["semgrep"], "use": "semgrep-scanner" }, { "when": ["codeql"], "use": "semgrep-scanner" }]
+ },
+ {
+ "domain": "test",
+ "match": ["테스트", "test", "커버리지", "coverage", "단위", "unit"],
+ "prefer": "test-engineer",
+ "narrow": []
+ }
+ ],
+ "fallback": "prefer-original-plugin-agents"
+}
+```
+
+- [ ] **Step 2: 실패 테스트 작성**
+
+Create `tests/test_route_rules_load.py`:
+
+```python
+import json, os, pytest
+from pw_route import rules
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+
+def test_load_rules_ok():
+ d = rules.load_rules(RULES)
+ assert d["schemaVersion"] == 1
+ assert isinstance(d["rules"], list) and len(d["rules"]) >= 2
+ assert d["fallback"] == "prefer-original-plugin-agents"
+ assert any(r["domain"] == "security" for r in d["rules"])
+
+def test_load_rules_bad_schema(tmp_path):
+ p = tmp_path / "bad.json"; p.write_text(json.dumps({"schemaVersion": 2}))
+ with pytest.raises(ValueError):
+ rules.load_rules(str(p))
+```
+
+- [ ] **Step 3: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_rules_load.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw_route`.
+
+- [ ] **Step 4: 최소 구현**
+
+Create `pw_route/__init__.py` (빈 파일). Create `pw_route/rules.py`:
+
+```python
+import json
+
+def load_rules(path):
+ with open(path, encoding="utf-8") as f:
+ d = json.load(f)
+ if d.get("schemaVersion") != 1:
+ raise ValueError(f"unsupported schemaVersion: {d.get('schemaVersion')}")
+ for k in ("rules", "fallback"):
+ if k not in d:
+ raise ValueError(f"missing key: {k}")
+ if not isinstance(d["rules"], list):
+ raise ValueError("rules must be a list")
+ return d
+```
+
+- [ ] **Step 5: 통과 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_rules_load.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 6: 커밋**
+
+```bash
+git add pw_route/__init__.py pw_route/rules.py pw_route/route-rules.json tests/test_route_rules_load.py
+git commit -m "feat(B): route-rules.json + load_rules"
+```
+
+---
+
+### Task 2: 에이전트 live 조회 (frontmatter 파싱)
+
+**Files:**
+- Create: `pw_route/discover.py`
+- Test: `tests/test_route_discover.py`
+
+**Interfaces:**
+- Produces:
+ - `pw_route.discover.parse_frontmatter(text: str) -> dict` — `---`로 감싼 상단 블록에서 `name`/`description`/`tools` 단순 스칼라 추출(폴디드 `>-` 값은 빈 문자열). frontmatter 없으면 `{}`.
+ - `pw_route.discover.discover_agents(dirs: list[str]) -> list[dict]` — 각 dir의 `*.md`를 읽어 `{"name","description","tools","path","source"}` 리스트(name 있는 것만). `source`는 그 dir 경로. 중복 name은 첫 등장 우선.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_route_discover.py`:
+
+```python
+from pw_route import discover
+
+FM = """---
+name: security-auditor
+description: >-
+ Audits security across tools.
+tools: Bash, Read, Glob
+---
+body here
+"""
+
+def test_parse_frontmatter():
+ d = discover.parse_frontmatter(FM)
+ assert d["name"] == "security-auditor"
+ assert d["tools"] == "Bash, Read, Glob"
+
+def test_parse_frontmatter_none():
+ assert discover.parse_frontmatter("no frontmatter here") == {}
+
+def test_discover_agents_reads_dir(tmp_path):
+ (tmp_path / "a.md").write_text("---\nname: alpha\ntools: Read\n---\nx")
+ (tmp_path / "b.md").write_text("---\nname: beta\n---\ny")
+ (tmp_path / "note.txt").write_text("ignored")
+ agents = discover.discover_agents([str(tmp_path)])
+ names = sorted(a["name"] for a in agents)
+ assert names == ["alpha", "beta"]
+ assert all("path" in a and "source" in a for a in agents)
+
+def test_discover_dedup_first_wins(tmp_path):
+ d1 = tmp_path / "d1"; d1.mkdir(); (d1 / "a.md").write_text("---\nname: dup\n---\n1")
+ d2 = tmp_path / "d2"; d2.mkdir(); (d2 / "a.md").write_text("---\nname: dup\n---\n2")
+ agents = discover.discover_agents([str(d1), str(d2)])
+ assert len([a for a in agents if a["name"] == "dup"]) == 1
+ assert agents[0]["source"] == str(d1)
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_discover.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw_route.discover`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw_route/discover.py`:
+
+```python
+import os, glob
+
+def parse_frontmatter(text):
+ if not text.startswith("---"):
+ return {}
+ end = text.find("\n---", 3)
+ if end == -1:
+ return {}
+ block = text[3:end]
+ out = {}
+ for line in block.splitlines():
+ if ":" not in line or line[:1] in (" ", "\t"):
+ continue # skip indented continuation / folded lines
+ key, _, val = line.partition(":")
+ key = key.strip()
+ val = val.strip()
+ if val.startswith((">", "|")):
+ val = "" # folded/literal scalar: value is on following indented lines
+ if key in ("name", "description", "tools"):
+ out[key] = val
+ return out
+
+def discover_agents(dirs):
+ seen, result = set(), []
+ for d in dirs:
+ for path in sorted(glob.glob(os.path.join(d, "*.md"))):
+ try:
+ text = open(path, encoding="utf-8", errors="ignore").read()
+ except OSError:
+ continue
+ fm = parse_frontmatter(text)
+ name = fm.get("name")
+ if not name or name in seen:
+ continue
+ seen.add(name)
+ result.append({"name": name, "description": fm.get("description", ""),
+ "tools": fm.get("tools", ""), "path": path, "source": d})
+ return result
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_discover.py -v`
+Expected: PASS (4 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw_route/discover.py tests/test_route_discover.py
+git commit -m "feat(B): live agent discovery via frontmatter"
+```
+
+---
+
+### Task 3: 규칙 매칭
+
+**Files:**
+- Modify: `pw_route/rules.py`
+- Test: `tests/test_route_match.py`
+
+**Interfaces:**
+- Consumes: `pw_route.rules.load_rules`
+- Produces: `pw_route.rules.match_task(task: str, rules_doc: dict, available_names: set[str]) -> dict` — 반환:
+ `{"domain": str|None, "prefer": {"name": str, "available": bool}|None, "narrow": {"name": str, "available": bool}|None, "fallback": str, "matched": bool}`.
+ 로직: `task` 소문자화; `rules` 순회하며 어떤 `match` 키워드가 task에 부분포함되면 그 규칙 선택(첫 매치). `prefer`의 available은 `name in available_names`. `narrow` 리스트에서 `when` 키워드가 모두 task에 포함되는 첫 항목의 `use`를 narrow로(available 판정 포함). 매치 없으면 domain/prefer/narrow=None, matched=False, fallback은 항상 rules_doc["fallback"].
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_route_match.py`:
+
+```python
+import os
+from pw_route import rules
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+
+def test_match_security_prefer_available():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("이 코드 보안 점검해줘", doc, {"security-auditor"})
+ assert r["matched"] is True
+ assert r["domain"] == "security"
+ assert r["prefer"] == {"name": "security-auditor", "available": True}
+ assert r["narrow"] is None
+
+def test_match_narrow_semgrep_unavailable():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("run a semgrep security scan", doc, {"security-auditor"})
+ assert r["narrow"] == {"name": "semgrep-scanner", "available": False}
+
+def test_no_match_returns_fallback():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("write me a poem", doc, set())
+ assert r["matched"] is False
+ assert r["prefer"] is None
+ assert r["fallback"] == "prefer-original-plugin-agents"
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_match.py -v`
+Expected: FAIL — `AttributeError: match_task`.
+
+- [ ] **Step 3: 최소 구현** — `pw_route/rules.py`에 추가:
+
+```python
+def _avail(name, available_names):
+ return {"name": name, "available": name in available_names}
+
+def match_task(task, rules_doc, available_names):
+ t = (task or "").lower()
+ result = {"domain": None, "prefer": None, "narrow": None,
+ "fallback": rules_doc.get("fallback"), "matched": False}
+ for rule in rules_doc.get("rules", []):
+ if any(kw.lower() in t for kw in rule.get("match", [])):
+ result["matched"] = True
+ result["domain"] = rule.get("domain")
+ if rule.get("prefer"):
+ result["prefer"] = _avail(rule["prefer"], available_names)
+ for n in rule.get("narrow", []):
+ if all(kw.lower() in t for kw in n.get("when", [])):
+ result["narrow"] = _avail(n["use"], available_names)
+ break
+ break
+ return result
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_match.py -v`
+Expected: PASS (3 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw_route/rules.py tests/test_route_match.py
+git commit -m "feat(B): rule matching with availability"
+```
+
+---
+
+### Task 4: CLI — 라우팅 컨텍스트 + sys.path 부트스트랩 + main
+
+**Files:**
+- Create: `pw_route/cli.py`
+- Test: `tests/test_route_cli.py`
+
+**Interfaces:**
+- Consumes: `pw_route.discover`, `pw_route.rules`
+- Produces:
+ - `pw_route.cli.default_agent_dirs(home: str, cwd: str) -> list[str]` — `[cwd/.claude/agents, home/.claude/agents] + glob(home/.claude/plugins/cache/*/*/*/agents)` 중 **존재하는** 디렉토리만.
+ - `pw_route.cli.route(task, rules_path, agent_dirs) -> dict` — discover→match 후 라우팅 컨텍스트 반환: `{"task", "domain", "prefer", "narrow", "fallback", "matched", "availableAgents": [names], "note"}`. prefer/narrow가 unavailable이면 `note`에 "capability unavailable in this session; enable preset and restart" 포함.
+ - `pw_route.cli.main(argv) -> int` — argparse `route ` 서브명령, 결과 JSON 출력. 기본 rules_path=`~/.claude/route-rules.json`.
+ - 파일 맨 위 **sys.path 부트스트랩** 포함.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_route_cli.py`:
+
+```python
+import os, sys, subprocess, json
+from pw_route import cli
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+def test_route_security_available(tmp_path):
+ agents = tmp_path / "agents"; agents.mkdir()
+ (agents / "security-auditor.md").write_text("---\nname: security-auditor\n---\nx")
+ ctx = cli.route("보안 점검해줘", RULES, [str(agents)])
+ assert ctx["domain"] == "security"
+ assert ctx["prefer"] == {"name": "security-auditor", "available": True}
+ assert "security-auditor" in ctx["availableAgents"]
+
+def test_route_unavailable_adds_restart_note(tmp_path):
+ agents = tmp_path / "agents"; agents.mkdir() # empty → security-auditor absent
+ ctx = cli.route("보안 취약점 semgrep 스캔", RULES, [str(agents)])
+ assert ctx["prefer"] == {"name": "security-auditor", "available": False}
+ assert "restart" in ctx["note"].lower()
+
+def test_default_agent_dirs_filters_existing(tmp_path):
+ (tmp_path / ".claude" / "agents").mkdir(parents=True)
+ dirs = cli.default_agent_dirs(str(tmp_path), str(tmp_path))
+ assert any(d.endswith("/.claude/agents") for d in dirs)
+
+def test_cli_runs_as_script_without_import_error(tmp_path):
+ # 설치 경로처럼 스크립트로 직접 실행 → 임포트 크래시 없어야 함
+ r = subprocess.run([sys.executable, os.path.join(REPO, "pw_route", "cli.py")],
+ capture_output=True, text=True, cwd=str(tmp_path))
+ assert "ModuleNotFoundError" not in r.stderr
+ assert r.returncode == 2 # argparse: missing subcommand
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_cli.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw_route.cli` 또는 (script test) ModuleNotFoundError.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw_route/cli.py`:
+
+```python
+import sys, os
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import argparse, glob, json
+from pw_route import discover, rules
+
+RESTART_NOTE = "capability unavailable in this session; enable preset and restart (/project-activate)"
+
+def default_agent_dirs(home, cwd):
+ candidates = [os.path.join(cwd, ".claude", "agents"),
+ os.path.join(home, ".claude", "agents")]
+ candidates += glob.glob(os.path.join(home, ".claude", "plugins", "cache", "*", "*", "*", "agents"))
+ return [d for d in candidates if os.path.isdir(d)]
+
+def route(task, rules_path, agent_dirs):
+ agents = discover.discover_agents(agent_dirs)
+ names = {a["name"] for a in agents}
+ doc = rules.load_rules(rules_path)
+ m = rules.match_task(task, doc, names)
+ note = ""
+ for slot in ("prefer", "narrow"):
+ if m[slot] and not m[slot]["available"]:
+ note = RESTART_NOTE
+ return {"task": task, "domain": m["domain"], "prefer": m["prefer"],
+ "narrow": m["narrow"], "fallback": m["fallback"], "matched": m["matched"],
+ "availableAgents": sorted(names), "note": note}
+
+def main(argv):
+ ap = argparse.ArgumentParser(prog="pw_route")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ pr = sub.add_parser("route"); pr.add_argument("task")
+ pr.add_argument("--rules", default=os.path.join(os.path.expanduser("~"), ".claude", "route-rules.json"))
+ args = ap.parse_args(argv)
+ home, cwd = os.path.expanduser("~"), os.getcwd()
+ if args.cmd == "route":
+ out = route(args.task, args.rules, default_agent_dirs(home, cwd))
+ print(json.dumps(out, ensure_ascii=False, indent=2))
+ return 0
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_cli.py -v`
+Expected: PASS (4 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw_route/cli.py tests/test_route_cli.py
+git commit -m "feat(B): routing-context CLI + sys.path bootstrap"
+```
+
+---
+
+### Task 5: 전문가 에이전트 정의 (불변식 포함)
+
+**Files:**
+- Create: `agents/security-auditor.md`
+- Create: `agents/test-engineer.md`
+- Test: `tests/test_route_agents_md.py`
+
+**Interfaces:**
+- Produces: 두 에이전트 마크다운. 테스트는 필수 문구 포함을 검증(INV-1 미수정 원칙 · 구조화 출력 키 · 폴백 언급).
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_route_agents_md.py`:
+
+```python
+import os
+
+AGENTS = os.path.join(os.path.dirname(__file__), "..", "agents")
+STRUCT_KEYS = ["findings", "evidence", "inspected", "confidence", "unresolved", "next"]
+
+def _read(name):
+ return open(os.path.join(AGENTS, name), encoding="utf-8").read()
+
+def test_security_auditor_has_frontmatter_and_invariants():
+ t = _read("security-auditor.md")
+ assert t.startswith("---")
+ assert "name: security-auditor" in t
+ assert "수정하지 않는다" in t # INV-1 (원본 미수정)
+ for k in STRUCT_KEYS:
+ assert k in t # 구조화 출력 계약
+ assert "폴백" in t or "fallback" in t.lower()
+
+def test_test_engineer_has_frontmatter_and_invariants():
+ t = _read("test-engineer.md")
+ assert t.startswith("---")
+ assert "name: test-engineer" in t
+ assert "수정하지 않는다" in t
+ for k in STRUCT_KEYS:
+ assert k in t
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_agents_md.py -v`
+Expected: FAIL — `FileNotFoundError: agents/security-auditor.md`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `agents/security-auditor.md`:
+
+```markdown
+---
+name: security-auditor
+description: >-
+ 이미 설치된 보안 스킬(kesekit KISA 점검, static-analysis의 /semgrep·/codeql,
+ security-guidance)을 한 격리 컨텍스트에서 돌려 결과를 중복제거·우선순위화하고
+ 이견을 보존해 종합한다. "보안 점검/취약점 감사/security review" 요청에 사용.
+tools: Bash, Read, Glob, Grep
+model: sonnet
+---
+
+너는 교차-플러그인 보안 종합가다. 아래 불변식을 지킨다.
+
+## 불변식
+- 어떤 스킬·플러그인 에이전트 파일도 **수정하지 않는다**. 읽고 실행만 한다.
+- 원본 스킬의 결과를 재해석·재구현하지 않는다. 그대로 인용한다.
+- 서로 다른 스킬의 이견을 합치지 말고 **보존**한다.
+
+## 절차
+1. 사용 가능한 것만 실행: kesekit 점검 스킬, `/semgrep`(가능하면 `/codeql`), security-guidance 가이드.
+ - 스킬이 없으면 그 관점을 생략하고 리포트에 폴백으로 명시한다.
+2. 각 도구 원출력을 수집한다(파일·라인·명령 근거 포함).
+3. 중복 지적을 합치되 출처를 잃지 않는다.
+
+## 출력 계약 (반드시 이 구조로 반환)
+- findings: 발견 목록(각 항목에 출처 도구 표기)
+- evidence: 파일/라인/명령 출력
+- inspected: 조사한 파일·명령
+- confidence: high | med | low
+- unresolved: 미해결 질문·이견
+- next: 권장 다음 행동
+
+## 과장 금지
+"도구가 X 보고"를 "X는 확실히 익스플로잇 가능"으로 승격하지 않는다 — 근거가 명확할 때만.
+```
+
+Create `agents/test-engineer.md`:
+
+```markdown
+---
+name: test-engineer
+description: >-
+ test-writer-fixer 스킬과 감지 언어 LSP, 테스트 러너를 한 격리 컨텍스트에서
+ 돌려 테스트 작성→실행→실패분석→수정 루프를 수행하고 커버리지 갭을 종합한다.
+ "테스트 작성/수정/커버리지" 요청에 사용.
+tools: Bash, Read, Write, Edit, Glob
+model: sonnet
+---
+
+너는 테스트 종합가다. 아래 불변식을 지킨다.
+
+## 불변식
+- 스킬·플러그인 에이전트 파일을 **수정하지 않는다**(대상 코드의 테스트만 작성/수정).
+- test-writer-fixer 등 원본 스킬의 동작을 재구현하지 않고 호출한다.
+- 통과/실패 결과를 임의로 낙관하지 않는다 — 실제 러너 출력을 근거로 삼는다.
+
+## 절차
+1. 대상 코드의 테스트를 작성/보강한다(test-writer-fixer 스킬 활용, 없으면 폴백 명시).
+2. 실제 러너로 실행한다(pytest/jest 등, 감지 언어에 맞게).
+3. 실패를 분석해 최소 수정하고 재실행한다. 커버리지 갭을 정리한다.
+
+## 출력 계약 (반드시 이 구조로 반환)
+- findings: 추가/수정한 테스트, 남은 갭
+- evidence: 러너 명령과 실제 출력(통과/실패 수)
+- inspected: 조사한 파일·명령
+- confidence: high | med | low
+- unresolved: 미해결 실패·불확실 영역
+- next: 권장 다음 행동
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_agents_md.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add agents/security-auditor.md agents/test-engineer.md tests/test_route_agents_md.py
+git commit -m "feat(B): security-auditor + test-engineer specialist agents"
+```
+
+---
+
+### Task 6: /route 명령 + install.sh 확장 + 통합 테스트
+
+**Files:**
+- Create: `commands/route.md`
+- Modify: `install.sh`
+- Test: `tests/test_route_integration.py`
+
+**Interfaces:**
+- Consumes: `pw_route.cli`
+- Produces: `/route` 명령 마크다운 + 확장된 install.sh(pw_route·agents·route.md·route-rules.json 복사). 통합 테스트는 discover→match→route end-to-end + install.sh 안전성.
+
+- [ ] **Step 1: 통합 실패 테스트 작성**
+
+Create `tests/test_route_integration.py`:
+
+```python
+import os, subprocess
+from pw_route import cli
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+def test_end_to_end_route_with_real_specialist_agents(tmp_path):
+ # 실제 저장소의 agents/ 를 조회 대상으로 사용 → security-auditor 존재 → prefer available
+ agents_dir = os.path.join(REPO, "agents")
+ ctx = cli.route("이 저장소 보안 감사", RULES, [agents_dir])
+ assert ctx["domain"] == "security"
+ assert ctx["prefer"] == {"name": "security-auditor", "available": True}
+ assert ctx["note"] == "" # 사용 가능하므로 재시작 안내 없음
+
+def test_install_sh_syntax_ok():
+ r = subprocess.run(["bash", "-n", os.path.join(REPO, "install.sh")],
+ capture_output=True, text=True)
+ assert r.returncode == 0, r.stderr
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `./venv/bin/python -m pytest tests/test_route_integration.py -v`
+Expected: FAIL — `test_end_to_end...`는 Task 5의 agents가 있으면 통과할 수 있으나, install.sh에 pw_route 복사가 없으므로 이 태스크의 목적은 명령·설치 추가. (두 테스트 모두 통과할 때까지 진행.)
+
+- [ ] **Step 3: /route 명령 + install.sh 확장 작성**
+
+Create `commands/route.md`:
+
+```markdown
+---
+description: 작업에 맞는 특화 에이전트 디스패치 "계획"을 만든다 (실행은 메인이 함)
+argument-hint: <작업 설명>
+---
+이 명령은 **자율 실행자가 아니라 디스패치 계획 생성기**다.
+
+1. 라우팅 컨텍스트를 얻는다: `python3 ~/.claude/pw_route/cli.py route "$ARGUMENTS"`
+ - 반환: domain, prefer(가용여부), narrow, fallback, availableAgents, note.
+2. note 에 "restart" 안내가 있으면 → 사용자에게 "이 세션엔 해당 능력이 없음, 프리셋 켜고 재시작(/project-activate)"을 전하고 멈춘다.
+3. 아니면 **디스패치 계획**을 만든다:
+ - 광범위 보안 → security-auditor, 정밀 semgrep 전용 → 원본 semgrep-scanner, 테스트 → test-engineer, 미지 작업 → 원본 플러그인 에이전트 우선(fallback).
+ - 각 선택의 이유 · 병렬 안전 여부 · 각 서브에이전트에 줄 정확한 프롬프트 · 기대 출력 계약(findings/evidence/inspected/confidence/unresolved/next) · 종합 체크리스트.
+4. 계획대로 서브에이전트를 디스패치한다(병렬 가능). **원본 스킬·에이전트는 수정하지 않는다.**
+5. 결과를 종합한다 — 이견을 보존하고, 각 주요 주장에 출처 에이전트를 표기하며, 과장하지 않는다.
+```
+
+Modify `install.sh` — 기존 마지막 `echo` 줄들 앞에 아래 복사 블록을 추가(기존 A 복사 블록은 유지):
+
+```bash
+# --- subsystem B: agent orchestration ---
+mkdir -p "$DEST/pw_route" "$DEST/agents"
+cp -R pw_route/. "$DEST/pw_route/"
+cp pw_route/route-rules.json "$DEST/route-rules.json"
+cp agents/security-auditor.md agents/test-engineer.md "$DEST/agents/"
+cp commands/route.md "$DEST/commands/"
+```
+
+(파일 끝의 안내 `echo` 에 `/route` 를 덧붙인다.)
+
+- [ ] **Step 4: 전체 통과 확인**
+
+Run: `./venv/bin/python -m pytest -q`
+Expected: PASS (모든 테스트 그린)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add commands/route.md install.sh tests/test_route_integration.py
+git commit -m "feat(B): /route command + install.sh + integration test"
+```
+
+---
+
+## Self-Review 결과
+
+- **Spec coverage:** 전문가 2종(T5) · /route 계획 생성기(T4,T6) · route-rules + live 조회(T1,T2,T3,T4) · 저하0 불변식 INV-1/2/3(T5 문구·T3/T6 우선순위) · 구조화 출력(T5,T6) · 동적 플러그인 한계 재시작 안내(T4 note) · A/B 경계(B는 단계상태 없음 — 구조상 미포함) · 설치(T6) · 카탈로그 연기(persistent 없음, live 조회) — 전 항목 매핑됨.
+- **Placeholder scan:** 모든 코드/마크다운 스텝에 실제 내용 포함, TODO 없음.
+- **Type consistency:** `load_rules`(T1)→`match_task`(T3)→`route`(T4) 동일 사용. `discover_agents`(T2)→`route`(T4) 동일. `default_agent_dirs`/`route`(T4)→통합(T6) 동일. sys.path 부트스트랩(T4)은 A에서 검증된 패턴. 일관.
diff --git a/modules/ccpilot/docs/superpowers/plans/2026-07-06-project-preset-workflow.md b/modules/ccpilot/docs/superpowers/plans/2026-07-06-project-preset-workflow.md
new file mode 100644
index 0000000..963628d
--- /dev/null
+++ b/modules/ccpilot/docs/superpowers/plans/2026-07-06-project-preset-workflow.md
@@ -0,0 +1,1197 @@
+# 프로젝트 프리셋 & 단계별 워크플로우 — 구현 계획
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 새 프로젝트 시작 시 프리셋으로 플러그인을 활성화하고, 그 조합에 맞는 단계별 플레이북을 생성하는 사용자 레벨 슬래시 명령 시스템을 만든다.
+
+**Architecture:** 순수 파이썬 패키지 `pw/`가 결정적 로직(프리셋 로드·슬러그 검증·설정 병합·플레이북 생성·상태 관리)을 담당하고, 얇은 슬래시 명령 md가 이를 호출한다. 단일 원천은 `presets.json`. 설치는 `install.sh`가 `~/.claude/`로 복사한다.
+
+**Tech Stack:** Python 3.10+ (표준 라이브러리만), pytest, 마크다운 슬래시 명령, JSON 데이터.
+
+## Global Constraints
+
+- Python 3.10+ 표준 라이브러리만 사용 — 외부 의존성 금지.
+- 슬러그는 반드시 `plugin@marketplace` 정확 형식. 기록 전 `~/.claude/plugins/installed_plugins.json`과 대조.
+- 파일 쓰기는 **비파괴**: 기존 JSON 키·마커 밖 텍스트 보존. 생성 블록은 `` … `` 마커로만 교체.
+- 상시 활성(alwaysOn): `superpowers@superpowers-dev`, `agentmemory@agentmemory`, `andrej-karpathy-skills@karpathy-skills`.
+- 단계 순서: `brainstorm → plan → implement → review → ship`.
+- 모든 명령은 실행 전 설치 목록과 상태를 검증하고, `--dry-run`이면 파일을 바꾸지 않는다.
+- 스키마 버전 = 1 (presets.json, project-state.json 모두).
+
+---
+
+### Task 1: 저장소 스캐폴딩 + presets.json + 로드
+
+**Files:**
+- Create: `pw/__init__.py` (빈 파일)
+- Create: `pw/data.py`
+- Create: `pw/presets.json`
+- Test: `tests/test_data_load.py`
+
+**Interfaces:**
+- Produces: `pw.data.load_presets(path: str) -> dict` — presets.json을 읽어 `schemaVersion==1` 검증 후 dict 반환. 키 누락/버전 불일치 시 `ValueError`.
+
+- [ ] **Step 1: presets.json 작성**
+
+Create `pw/presets.json`:
+
+```json
+{
+ "schemaVersion": 1,
+ "alwaysOn": ["superpowers@superpowers-dev", "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills"],
+ "phaseModel": {
+ "phases": ["brainstorm", "plan", "implement", "review", "ship"],
+ "roles": {
+ "brainstorm": [
+ {"role": "요구사항 취조", "tool": "grill-me", "optional": true},
+ {"role": "설계 확정", "tool": "superpowers:brainstorming"},
+ {"role": "기존코드 이해", "tool": "understand-anything", "whenCapability": "existing-code"}
+ ],
+ "plan": [
+ {"role": "계획 작성", "tool": "superpowers:writing-plans"},
+ {"role": "영향 분석", "tool": "understand-anything", "whenCapability": "existing-code"},
+ {"role": "라이브러리 문서", "tool": "context7"}
+ ],
+ "implement": [
+ {"role": "구현 루프", "tool": "superpowers:test-driven-development"},
+ {"role": "언어 인텔리전스", "tool": "__lsp_by_language__"},
+ {"role": "테스트 작성/수정", "tool": "test-writer-fixer"},
+ {"role": "라이브러리 문서", "tool": "context7"},
+ {"role": "UI 생성", "tool": "frontend-design", "whenCapability": "frontend"},
+ {"role": "문서 산출물", "tool": "document-skills", "whenCapability": "docs-output"}
+ ],
+ "review": [
+ {"role": "주력 리뷰", "tool": "/code-review"},
+ {"role": "단순화", "tool": "code-simplifier"},
+ {"role": "실시간 보안", "tool": "security-guidance"},
+ {"role": "정적 보안", "tool": "static-analysis"},
+ {"role": "한국 규제", "tool": "kesekit", "whenCapability": "kr-compliance"}
+ ],
+ "ship": [
+ {"role": "커밋/PR", "tool": "gh"},
+ {"role": "릴리스 문서", "tool": "document-skills", "whenCapability": "docs-output"},
+ {"role": "학습 영속", "tool": "agentmemory:remember"}
+ ]
+ }
+ },
+ "capabilityTags": {
+ "detect": {
+ "typescript": ["package.json", "tsconfig.json"],
+ "python": ["pyproject.toml", "requirements.txt"],
+ "go": ["go.mod"],
+ "rust": ["Cargo.toml"],
+ "frontend": ["package.json::react", "package.json::next"],
+ "infra": ["Dockerfile", "*.tf"]
+ },
+ "lspFor": {
+ "typescript": "typescript-lsp@claude-plugins-official",
+ "python": "pyright-lsp@claude-plugins-official",
+ "go": "gopls-lsp@claude-plugins-official",
+ "rust": "rust-analyzer-lsp@claude-plugins-official"
+ }
+ },
+ "presets": {
+ "web-fullstack": {"plugins": ["typescript-lsp@claude-plugins-official", "pyright-lsp@claude-plugins-official", "frontend-design@claude-plugins-official", "figma@claude-plugins-official", "vercel@claude-plugins-official", "context7@claude-plugins-official", "test-writer-fixer@awesome-claude-plugins", "code-simplifier@claude-plugins-official", "security-guidance@claude-plugins-official", "understand-anything@understand-anything"]},
+ "backend-api": {"plugins": ["context7@claude-plugins-official", "test-writer-fixer@awesome-claude-plugins", "static-analysis@trailofbits", "security-guidance@claude-plugins-official", "code-simplifier@claude-plugins-official", "understand-anything@understand-anything"], "lspByLanguage": true},
+ "security-audit": {"plugins": ["static-analysis@trailofbits", "kesekit@kesekit", "security-guidance@claude-plugins-official", "understand-anything@understand-anything", "code-simplifier@claude-plugins-official"], "capabilities": ["kr-compliance"]},
+ "docs-deck": {"plugins": ["document-skills@anthropic-agent-skills", "felo-slides@felo-ai", "context7@claude-plugins-official"], "personalSkills": ["academic-pptx", "pptx-from-layouts"], "capabilities": ["docs-output"]},
+ "minimal": {"plugins": ["context7@claude-plugins-official"], "lspByLanguage": true}
+ },
+ "invocationRules": {
+ "orchestrator": {"primary": "superpowers", "rescueOnly": ["codex"]},
+ "memory": {"single": "agentmemory"},
+ "review": {"primary": "/code-review", "specialists": ["code-simplifier", "security-guidance", "static-analysis", "kesekit"], "order": "primary first then specialists on explicit trigger", "stopWhen": "no new findings"},
+ "lsp": "one per detected language",
+ "docs": {"general": "document-skills", "specialized": ["academic-pptx", "pptx-from-layouts", "felo-slides"]}
+ }
+}
+```
+
+- [ ] **Step 2: 실패 테스트 작성**
+
+Create `tests/test_data_load.py`:
+
+```python
+import json, os, pytest
+from pw import data
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_load_presets_returns_dict_with_required_keys():
+ d = data.load_presets(PRESETS)
+ assert d["schemaVersion"] == 1
+ for key in ("alwaysOn", "phaseModel", "capabilityTags", "presets", "invocationRules"):
+ assert key in d
+ assert d["phaseModel"]["phases"] == ["brainstorm", "plan", "implement", "review", "ship"]
+
+def test_load_presets_rejects_wrong_schema(tmp_path):
+ p = tmp_path / "bad.json"
+ p.write_text(json.dumps({"schemaVersion": 99}))
+ with pytest.raises(ValueError):
+ data.load_presets(str(p))
+```
+
+- [ ] **Step 3: 실패 확인**
+
+Run: `python3 -m pytest tests/test_data_load.py -v`
+Expected: FAIL — `ModuleNotFoundError: No module named 'pw'` 또는 `AttributeError: load_presets`.
+
+- [ ] **Step 4: 최소 구현**
+
+Create `pw/__init__.py` (빈 파일). Create `pw/data.py`:
+
+```python
+import json
+
+REQUIRED_KEYS = ("alwaysOn", "phaseModel", "capabilityTags", "presets", "invocationRules")
+
+def load_presets(path):
+ with open(path, encoding="utf-8") as f:
+ d = json.load(f)
+ if d.get("schemaVersion") != 1:
+ raise ValueError(f"unsupported schemaVersion: {d.get('schemaVersion')}")
+ for k in REQUIRED_KEYS:
+ if k not in d:
+ raise ValueError(f"missing key: {k}")
+ return d
+```
+
+- [ ] **Step 5: 통과 확인**
+
+Run: `python3 -m pytest tests/test_data_load.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 6: 커밋**
+
+```bash
+git add pw/__init__.py pw/data.py pw/presets.json tests/test_data_load.py
+git commit -m "feat: presets.json data source + load_presets"
+```
+
+---
+
+### Task 2: 설치 플러그인 읽기 + 슬러그 검증
+
+**Files:**
+- Modify: `pw/data.py`
+- Test: `tests/test_data_validate.py`
+
+**Interfaces:**
+- Consumes: `pw.data.load_presets`
+- Produces:
+ - `pw.data.installed_plugins(installed_json_path: str) -> set[str]` — `installed_plugins.json`의 `plugins` 키 집합 반환.
+ - `pw.data.validate_slugs(slugs: list[str], installed: set[str]) -> tuple[list[str], list[str]]` — `(valid, missing)` 반환, 입력 순서 보존.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_data_validate.py`:
+
+```python
+import json
+from pw import data
+
+def test_installed_plugins_reads_keys(tmp_path):
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {"a@m1": [{}], "b@m2": [{}]}}))
+ assert data.installed_plugins(str(p)) == {"a@m1", "b@m2"}
+
+def test_validate_slugs_splits_valid_and_missing():
+ installed = {"context7@claude-plugins-official", "kesekit@kesekit"}
+ valid, missing = data.validate_slugs(
+ ["context7@claude-plugins-official", "ghost@nowhere", "kesekit@kesekit"], installed)
+ assert valid == ["context7@claude-plugins-official", "kesekit@kesekit"]
+ assert missing == ["ghost@nowhere"]
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_data_validate.py -v`
+Expected: FAIL — `AttributeError: installed_plugins`.
+
+- [ ] **Step 3: 최소 구현** — `pw/data.py`에 추가:
+
+```python
+def installed_plugins(installed_json_path):
+ with open(installed_json_path, encoding="utf-8") as f:
+ d = json.load(f)
+ return set(d.get("plugins", {}).keys())
+
+def validate_slugs(slugs, installed):
+ valid = [s for s in slugs if s in installed]
+ missing = [s for s in slugs if s not in installed]
+ return valid, missing
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_data_validate.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/data.py tests/test_data_validate.py
+git commit -m "feat: installed_plugins + validate_slugs"
+```
+
+---
+
+### Task 3: JSON 읽기/쓰기 + 마커 블록 upsert
+
+**Files:**
+- Create: `pw/fsutil.py`
+- Test: `tests/test_fsutil_marker.py`
+
+**Interfaces:**
+- Produces:
+ - `pw.fsutil.read_json(path: str, default=None) -> dict` — 없으면 default.
+ - `pw.fsutil.write_json(path: str, obj: dict) -> None` — 부모 폴더 생성, 2-space indent, `ensure_ascii=False`.
+ - `pw.fsutil.upsert_marker_block(text: str, block: str, begin: str, end: str) -> str` — `begin`~`end` 사이를 `block`으로 교체. 마커 없으면 끝에 `\n{begin}\n{block}\n{end}\n` append. 마커 밖 텍스트 보존.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_fsutil_marker.py`:
+
+```python
+from pw import fsutil
+
+BEGIN, END = "", ""
+
+def test_upsert_appends_when_no_marker():
+ out = fsutil.upsert_marker_block("existing content\n", "NEW", BEGIN, END)
+ assert "existing content" in out
+ assert f"{BEGIN}\nNEW\n{END}" in out
+
+def test_upsert_replaces_between_markers_preserving_outside():
+ text = f"top\n{BEGIN}\nOLD\n{END}\nbottom\n"
+ out = fsutil.upsert_marker_block(text, "NEW", BEGIN, END)
+ assert "OLD" not in out
+ assert "NEW" in out
+ assert out.startswith("top")
+ assert out.rstrip().endswith("bottom")
+
+def test_read_json_default(tmp_path):
+ assert fsutil.read_json(str(tmp_path / "none.json"), default={"x": 1}) == {"x": 1}
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_fsutil_marker.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw.fsutil`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw/fsutil.py`:
+
+```python
+import json, os, re
+
+def read_json(path, default=None):
+ if not os.path.exists(path):
+ return default
+ with open(path, encoding="utf-8") as f:
+ return json.load(f)
+
+def write_json(path, obj):
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(obj, f, ensure_ascii=False, indent=2)
+ f.write("\n")
+
+def upsert_marker_block(text, block, begin, end):
+ pattern = re.compile(re.escape(begin) + r".*?" + re.escape(end), re.DOTALL)
+ new_block = f"{begin}\n{block}\n{end}"
+ if pattern.search(text):
+ return pattern.sub(new_block, text)
+ sep = "" if text.endswith("\n") or text == "" else "\n"
+ return f"{text}{sep}\n{new_block}\n"
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_fsutil_marker.py -v`
+Expected: PASS (3 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/fsutil.py tests/test_fsutil_marker.py
+git commit -m "feat: json rw + marker block upsert"
+```
+
+---
+
+### Task 4: settings.json 병합 (allowlist/denylist, 보존)
+
+**Files:**
+- Modify: `pw/fsutil.py`
+- Test: `tests/test_fsutil_settings.py`
+
+**Interfaces:**
+- Produces: `pw.fsutil.merge_enabled_plugins(existing: dict, enable: list[str], disable: list[str]) -> dict` — `existing`의 다른 키를 보존하고 `enabledPlugins`만 갱신: `enable`은 `True`, `disable`은 `False`. `enable`이 `disable`보다 우선. 기존 `enabledPlugins`의 다른 키는 유지.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_fsutil_settings.py`:
+
+```python
+from pw import fsutil
+
+def test_merge_preserves_other_keys_and_sets_flags():
+ existing = {"permissions": {"allow": ["x"]},
+ "enabledPlugins": {"keep@m": True, "context7@cpo": True}}
+ out = fsutil.merge_enabled_plugins(
+ existing,
+ enable=["a@m", "b@m"],
+ disable=["context7@cpo", "c@m"])
+ assert out["permissions"] == {"allow": ["x"]} # 보존
+ assert out["enabledPlugins"]["a@m"] is True
+ assert out["enabledPlugins"]["b@m"] is True
+ assert out["enabledPlugins"]["context7@cpo"] is False # denylist가 덮어씀
+ assert out["enabledPlugins"]["c@m"] is False
+ assert out["enabledPlugins"]["keep@m"] is True # 기존 유지
+
+def test_enable_wins_over_disable():
+ out = fsutil.merge_enabled_plugins({}, enable=["a@m"], disable=["a@m"])
+ assert out["enabledPlugins"]["a@m"] is True
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_fsutil_settings.py -v`
+Expected: FAIL — `AttributeError: merge_enabled_plugins`.
+
+- [ ] **Step 3: 최소 구현** — `pw/fsutil.py`에 추가:
+
+```python
+import copy
+
+def merge_enabled_plugins(existing, enable, disable):
+ out = copy.deepcopy(existing) if existing else {}
+ ep = dict(out.get("enabledPlugins", {}))
+ for s in disable:
+ ep[s] = False
+ for s in enable: # enable 이 disable 을 이김
+ ep[s] = True
+ out["enabledPlugins"] = ep
+ return out
+```
+
+(파일 상단 import에 `copy` 추가.)
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_fsutil_settings.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/fsutil.py tests/test_fsutil_settings.py
+git commit -m "feat: merge_enabled_plugins allowlist/denylist"
+```
+
+---
+
+### Task 5: 언어/능력 감지
+
+**Files:**
+- Create: `pw/detect.py`
+- Test: `tests/test_detect.py`
+
+**Interfaces:**
+- Consumes: `capabilityTags` (presets.json)
+- Produces:
+ - `pw.detect.detect_capabilities(project_dir: str, capability_tags: dict) -> set[str]` — 감지된 언어/능력 태그 집합. 마커 형식: `"파일명"`=존재, `"파일명::substr"`=존재+내용포함, `"*.확장자"`=glob 매칭. `existing-code`는 project_dir에 `*.py/*.ts/*.js/*.go/*.rs` 소스가 하나라도 있으면(단 `.claude/`, `docs/`, `node_modules/` 제외) 포함.
+ - `pw.detect.lsp_slugs(capabilities: set[str], lsp_for: dict) -> list[str]` — 감지 언어의 LSP 슬러그 목록(입력 dict 순서).
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_detect.py`:
+
+```python
+from pw import detect
+
+TAGS = {"typescript": ["package.json", "tsconfig.json"],
+ "python": ["pyproject.toml"],
+ "frontend": ["package.json::react"],
+ "infra": ["*.tf"]}
+LSP_FOR = {"typescript": "typescript-lsp@cpo", "python": "pyright-lsp@cpo"}
+
+def test_detects_file_and_content_and_glob(tmp_path):
+ (tmp_path / "package.json").write_text('{"dependencies":{"react":"^18"}}')
+ (tmp_path / "main.tf").write_text("resource {}")
+ (tmp_path / "app.py").write_text("x=1")
+ caps = detect.detect_capabilities(str(tmp_path), TAGS)
+ assert "typescript" in caps # package.json 존재
+ assert "frontend" in caps # react 포함
+ assert "infra" in caps # *.tf
+ assert "existing-code" in caps # app.py
+ assert "python" not in caps # pyproject.toml 없음
+
+def test_lsp_slugs_maps_detected_languages():
+ caps = {"typescript", "frontend"}
+ assert detect.lsp_slugs(caps, LSP_FOR) == ["typescript-lsp@cpo"]
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_detect.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw.detect`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw/detect.py`:
+
+```python
+import os, glob
+
+SOURCE_EXTS = (".py", ".ts", ".js", ".go", ".rs")
+IGNORE_DIRS = {".claude", "docs", "node_modules", ".git"}
+
+def _marker_hit(project_dir, marker):
+ if "::" in marker:
+ fname, substr = marker.split("::", 1)
+ p = os.path.join(project_dir, fname)
+ return os.path.exists(p) and substr in open(p, encoding="utf-8", errors="ignore").read()
+ if "*" in marker:
+ return bool(glob.glob(os.path.join(project_dir, marker)))
+ return os.path.exists(os.path.join(project_dir, marker))
+
+def _has_source(project_dir):
+ for root, dirs, files in os.walk(project_dir):
+ dirs[:] = [d for d in dirs if d not in IGNORE_DIRS]
+ if any(f.endswith(SOURCE_EXTS) for f in files):
+ return True
+ return False
+
+def detect_capabilities(project_dir, capability_tags):
+ caps = set()
+ for cap, markers in capability_tags.get("detect", {}).items():
+ if any(_marker_hit(project_dir, m) for m in markers):
+ caps.add(cap)
+ if _has_source(project_dir):
+ caps.add("existing-code")
+ return caps
+
+def lsp_slugs(capabilities, lsp_for):
+ return [slug for lang, slug in lsp_for.items() if lang in capabilities]
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_detect.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/detect.py tests/test_detect.py
+git commit -m "feat: language/capability detection"
+```
+
+---
+
+### Task 6: 유효 플러그인 집합 계산
+
+**Files:**
+- Modify: `pw/data.py`
+- Test: `tests/test_data_effective.py`
+
+**Interfaces:**
+- Produces:
+ - `pw.data.plugin_name(slug: str) -> str` — `@` 앞부분 반환 (`context7@cpo` → `context7`).
+ - `pw.data.effective_plugins(presets: dict, preset_name: str, always_on: list[str], lsp_slugs: list[str]) -> list[str]` — 프리셋 plugins + alwaysOn + (lspByLanguage 프리셋이면 lsp_slugs) 를 합쳐 **중복 제거·순서 보존**. 존재하지 않는 preset_name은 `KeyError`.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_data_effective.py`:
+
+```python
+import pytest
+from pw import data
+
+PRESETS = {"web": {"plugins": ["a@m", "b@m"]},
+ "min": {"plugins": ["a@m"], "lspByLanguage": True}}
+ALWAYS = ["sp@dev", "am@am"]
+
+def test_plugin_name():
+ assert data.plugin_name("context7@claude-plugins-official") == "context7"
+
+def test_effective_dedup_and_order():
+ eff = data.effective_plugins(PRESETS, "web", ALWAYS, lsp_slugs=["ts@cpo"])
+ assert eff == ["a@m", "b@m", "sp@dev", "am@am"] # web 은 lspByLanguage 아님 → lsp 제외
+
+def test_effective_includes_lsp_when_flagged():
+ eff = data.effective_plugins(PRESETS, "min", ALWAYS, lsp_slugs=["ts@cpo", "py@cpo"])
+ assert eff == ["a@m", "sp@dev", "am@am", "ts@cpo", "py@cpo"]
+
+def test_unknown_preset_raises():
+ with pytest.raises(KeyError):
+ data.effective_plugins(PRESETS, "ghost", ALWAYS, lsp_slugs=[])
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_data_effective.py -v`
+Expected: FAIL — `AttributeError: plugin_name`.
+
+- [ ] **Step 3: 최소 구현** — `pw/data.py`에 추가:
+
+```python
+def plugin_name(slug):
+ return slug.split("@", 1)[0]
+
+def effective_plugins(presets, preset_name, always_on, lsp_slugs):
+ if preset_name not in presets:
+ raise KeyError(preset_name)
+ preset = presets[preset_name]
+ ordered = list(preset.get("plugins", [])) + list(always_on)
+ if preset.get("lspByLanguage"):
+ ordered += list(lsp_slugs)
+ seen, result = set(), []
+ for s in ordered:
+ if s not in seen:
+ seen.add(s)
+ result.append(s)
+ return result
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_data_effective.py -v`
+Expected: PASS (4 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/data.py tests/test_data_effective.py
+git commit -m "feat: effective_plugins + plugin_name"
+```
+
+---
+
+### Task 7: 플레이북 생성
+
+**Files:**
+- Create: `pw/playbook.py`
+- Test: `tests/test_playbook.py`
+
+**Interfaces:**
+- Consumes: `pw.data.plugin_name`
+- Produces: `pw.playbook.generate_playbook(preset_name, phase_model, effective_slugs, capabilities, lsp_slugs, invocation_rules) -> str` — 마커(`` … ``)로 감싼 마크다운.
+ - **도구 포함 규칙** (역할별): tool이 `superpowers:`/`/code-review`/`gh`/`agentmemory:` 로 시작 → 항상 포함(alwaysOn/builtin). `__lsp_by_language__` → `lsp_slugs`의 plugin_name들로 확장(비면 그 줄 생략). 그 외 → `plugin_name(tool)`이 effective_slugs의 plugin_name 집합에 있을 때만. 추가로 role에 `whenCapability`가 있으면 그 capability가 `capabilities`에 있을 때만.
+ - 각 단계 헤더 + 포함된 역할을 번호로 나열. 마지막에 "호출 규칙" 섹션(invocation_rules 요약).
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_playbook.py`:
+
+```python
+from pw import playbook
+
+PHASE_MODEL = {
+ "phases": ["brainstorm", "implement", "review"],
+ "roles": {
+ "brainstorm": [
+ {"role": "설계", "tool": "superpowers:brainstorming"},
+ {"role": "기존코드", "tool": "understand-anything", "whenCapability": "existing-code"},
+ ],
+ "implement": [
+ {"role": "LSP", "tool": "__lsp_by_language__"},
+ {"role": "테스트", "tool": "test-writer-fixer"},
+ {"role": "UI", "tool": "frontend-design", "whenCapability": "frontend"},
+ ],
+ "review": [{"role": "주력", "tool": "/code-review"}],
+ },
+}
+RULES = {"orchestrator": {"primary": "superpowers", "rescueOnly": ["codex"]},
+ "memory": {"single": "agentmemory"}}
+
+def test_playbook_includes_available_excludes_missing():
+ md = playbook.generate_playbook(
+ preset_name="backend-api",
+ phase_model=PHASE_MODEL,
+ effective_slugs=["test-writer-fixer@awesome-claude-plugins", "superpowers@superpowers-dev"],
+ capabilities=set(), # existing-code, frontend 없음
+ lsp_slugs=["pyright-lsp@claude-plugins-official"],
+ invocation_rules=RULES)
+ assert md.startswith("")
+ assert "superpowers:brainstorming" in md # builtin
+ assert "understand-anything" not in md # capability 없음
+ assert "pyright-lsp" in md # LSP 확장
+ assert "test-writer-fixer" in md # effective 에 있음
+ assert "frontend-design" not in md # frontend capability 없음
+ assert "/code-review" in md
+ assert "superpowers" in md and "codex" in md # 호출 규칙 섹션
+
+def test_playbook_omits_lsp_line_when_no_lsp():
+ md = playbook.generate_playbook("minimal", PHASE_MODEL,
+ effective_slugs=[], capabilities=set(), lsp_slugs=[], invocation_rules=RULES)
+ assert "__lsp_by_language__" not in md
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_playbook.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw.playbook`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw/playbook.py`:
+
+```python
+from pw.data import plugin_name
+
+BEGIN_TMPL = ""
+END = ""
+_ALWAYS_PREFIXES = ("superpowers:", "/code-review", "gh", "agentmemory:")
+
+def _resolve(role, effective_names, capabilities, lsp_slugs):
+ """이 역할이 플레이북에 포함되면 표시 문자열, 아니면 None."""
+ if role.get("whenCapability") and role["whenCapability"] not in capabilities:
+ return None
+ tool = role["tool"]
+ if tool == "__lsp_by_language__":
+ names = [plugin_name(s) for s in lsp_slugs]
+ return ", ".join(names) if names else None
+ if tool.startswith(_ALWAYS_PREFIXES):
+ return tool
+ return tool if plugin_name(tool) in effective_names else None
+
+def generate_playbook(preset_name, phase_model, effective_slugs, capabilities, lsp_slugs, invocation_rules):
+ effective_names = {plugin_name(s) for s in effective_slugs}
+ lines = [BEGIN_TMPL.format(preset=preset_name),
+ f"# 프로젝트 플레이북 — {preset_name}",
+ "> 현재 단계는 .claude/project-state.json. /phase-next 로 진행.", ""]
+ for phase in phase_model["phases"]:
+ lines.append(f"## {phase}")
+ n = 1
+ for role in phase_model["roles"].get(phase, []):
+ shown = _resolve(role, effective_names, capabilities, lsp_slugs)
+ if shown is not None:
+ lines.append(f"{n}. {role['role']} — {shown}")
+ n += 1
+ if n == 1:
+ lines.append("_(이 단계에 활성 도구 없음)_")
+ lines.append("")
+ orch = invocation_rules.get("orchestrator", {})
+ mem = invocation_rules.get("memory", {})
+ lines += ["## 호출 규칙 (충돌 가드)",
+ f"- 오케스트레이터: {orch.get('primary')} 하나. {', '.join(orch.get('rescueOnly', []))} 는 rescue 시에만.",
+ f"- 메모리: {mem.get('single')} 하나.",
+ "- 리뷰: /code-review 주력 먼저 → 전문 리뷰어는 트리거 시 → 새 지적 없으면 정지.",
+ END]
+ return "\n".join(lines) + "\n"
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_playbook.py -v`
+Expected: PASS (2 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/playbook.py tests/test_playbook.py
+git commit -m "feat: playbook generation with availability rules"
+```
+
+---
+
+### Task 8: 상태 파일 + 단계 전환
+
+**Files:**
+- Create: `pw/state.py`
+- Test: `tests/test_state.py`
+
+**Interfaces:**
+- Consumes: `pw.fsutil.read_json`, `pw.fsutil.write_json`
+- Produces:
+ - `pw.state.default_state(preset, phases, detected_langs) -> dict` — `{schemaVersion:1, preset, phase:phases[0], phases, detectedLanguages, history:[]}`.
+ - `pw.state.advance(state) -> dict` — 다음 단계로 이동한 새 dict. 마지막 단계면 그대로 두고 `state["_atEnd"]=True`. history에 `{phase, at}` append (`at`은 인자로 받은 `now` 문자열).
+ - 시그니처: `advance(state, now: str) -> dict`.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_state.py`:
+
+```python
+from pw import state
+
+PHASES = ["brainstorm", "plan", "implement"]
+
+def test_default_state():
+ s = state.default_state("web", PHASES, ["python"])
+ assert s["schemaVersion"] == 1
+ assert s["preset"] == "web"
+ assert s["phase"] == "brainstorm"
+ assert s["phases"] == PHASES
+ assert s["detectedLanguages"] == ["python"]
+ assert s["history"] == []
+
+def test_advance_moves_to_next_and_records_history():
+ s = state.default_state("web", PHASES, [])
+ s2 = state.advance(s, now="2026-07-06T00:00:00Z")
+ assert s2["phase"] == "plan"
+ assert s2["history"][-1] == {"phase": "plan", "at": "2026-07-06T00:00:00Z"}
+ assert "_atEnd" not in s2
+
+def test_advance_at_last_phase_flags_end():
+ s = state.default_state("web", PHASES, [])
+ s["phase"] = "implement"
+ s2 = state.advance(s, now="t")
+ assert s2["phase"] == "implement"
+ assert s2["_atEnd"] is True
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_state.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw.state`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw/state.py`:
+
+```python
+import copy
+
+def default_state(preset, phases, detected_langs):
+ return {"schemaVersion": 1, "preset": preset, "phase": phases[0],
+ "phases": list(phases), "detectedLanguages": list(detected_langs), "history": []}
+
+def advance(state, now):
+ s = copy.deepcopy(state)
+ phases = s["phases"]
+ i = phases.index(s["phase"])
+ if i >= len(phases) - 1:
+ s["_atEnd"] = True
+ return s
+ s["phase"] = phases[i + 1]
+ s.setdefault("history", []).append({"phase": s["phase"], "at": now})
+ return s
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_state.py -v`
+Expected: PASS (3 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/state.py tests/test_state.py
+git commit -m "feat: project state + phase advance"
+```
+
+---
+
+### Task 9: CLI — init 서브명령
+
+**Files:**
+- Create: `pw/cli.py`
+- Test: `tests/test_cli_init.py`
+
+**Interfaces:**
+- Consumes: `pw.data`, `pw.detect`, `pw.fsutil`, `pw.playbook`, `pw.state`
+- Produces: `pw.cli.cmd_init(project_dir, preset, presets_path, installed_path, now, dry_run=False, force=False) -> dict` — 결과 요약 dict `{written: [...], enabled: [...], disabled: [...], missing: [...], dryRun: bool}`. `dry_run`이면 파일 안 씀. 이미 `project-state.json` 있고 `force=False`면 `RuntimeError("already initialized; use --repair or --force")`.
+ - denylist = (installed 집합) − (effective 집합).
+ - `.claude/settings.json`, `.claude/playbook.md`, `.claude/project-state.json`, `CLAUDE.md` 포인터를 씀.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_cli_init.py`:
+
+```python
+import json, os
+from pw import cli
+
+def _installed(tmp_path):
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills",
+ "static-analysis@trailofbits", "kesekit@kesekit",
+ "security-guidance@claude-plugins-official", "code-simplifier@claude-plugins-official",
+ "understand-anything@understand-anything"]
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ return str(p)
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_init_writes_files_and_denylists_non_preset(tmp_path):
+ proj = tmp_path / "proj"; proj.mkdir()
+ res = cli.cmd_init(str(proj), "security-audit", PRESETS, _installed(tmp_path),
+ now="2026-07-06T00:00:00Z")
+ settings = json.loads((proj / ".claude" / "settings.json").read_text())
+ ep = settings["enabledPlugins"]
+ assert ep["static-analysis@trailofbits"] is True # 프리셋
+ assert ep["superpowers@superpowers-dev"] is True # alwaysOn
+ assert ep["context7@claude-plugins-official"] is False # 非프리셋 → denylist
+ assert (proj / ".claude" / "playbook.md").exists()
+ state = json.loads((proj / ".claude" / "project-state.json").read_text())
+ assert state["preset"] == "security-audit" and state["phase"] == "brainstorm"
+ assert "playbook" in (proj / "CLAUDE.md").read_text()
+
+def test_init_dry_run_writes_nothing(tmp_path):
+ proj = tmp_path / "proj2"; proj.mkdir()
+ res = cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path),
+ now="t", dry_run=True)
+ assert res["dryRun"] is True
+ assert not (proj / ".claude").exists()
+
+def test_init_refuses_reinit_without_force(tmp_path):
+ proj = tmp_path / "proj3"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ try:
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ assert False, "should have raised"
+ except RuntimeError as e:
+ assert "already initialized" in str(e)
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_cli_init.py -v`
+Expected: FAIL — `ModuleNotFoundError: pw.cli`.
+
+- [ ] **Step 3: 최소 구현**
+
+Create `pw/cli.py`:
+
+```python
+import os
+from pw import data, detect, fsutil, playbook, state
+
+CLAUDE_PTR = ("이 프로젝트는 .claude/playbook.md 의 단계별 워크플로우를 따른다. "
+ "현재 단계는 .claude/project-state.json 참조.")
+PTR_BEGIN, PTR_END = "", ""
+
+def _paths(project_dir):
+ c = os.path.join(project_dir, ".claude")
+ return {"claude": c,
+ "settings": os.path.join(c, "settings.json"),
+ "playbook": os.path.join(c, "playbook.md"),
+ "state": os.path.join(c, "project-state.json"),
+ "claudemd": os.path.join(project_dir, "CLAUDE.md")}
+
+def cmd_init(project_dir, preset, presets_path, installed_path, now, dry_run=False, force=False):
+ p = _paths(project_dir)
+ if os.path.exists(p["state"]) and not force and not dry_run:
+ raise RuntimeError("already initialized; use --repair or --force")
+ presets = data.load_presets(presets_path)
+ installed = data.installed_plugins(installed_path)
+ caps = detect.detect_capabilities(project_dir, presets["capabilityTags"])
+ caps |= set(presets["presets"].get(preset, {}).get("capabilities", []))
+ lsp = detect.lsp_slugs(caps, presets["capabilityTags"]["lspFor"])
+ effective = data.effective_plugins(presets["presets"], preset, presets["alwaysOn"], lsp)
+ enable, missing = data.validate_slugs(effective, installed)
+ disable = [s for s in sorted(installed) if s not in set(enable)]
+ pb = playbook.generate_playbook(preset, presets["phaseModel"], enable, caps, lsp,
+ presets["invocationRules"])
+ st = state.default_state(preset, presets["phaseModel"]["phases"], sorted(caps))
+ result = {"enabled": enable, "disabled": disable, "missing": missing,
+ "dryRun": dry_run, "written": []}
+ if dry_run:
+ return result
+ settings = fsutil.merge_enabled_plugins(fsutil.read_json(p["settings"], {}), enable, disable)
+ fsutil.write_json(p["settings"], settings)
+ os.makedirs(p["claude"], exist_ok=True)
+ with open(p["playbook"], "w", encoding="utf-8") as f:
+ f.write(pb)
+ fsutil.write_json(p["state"], st)
+ existing_md = ""
+ if os.path.exists(p["claudemd"]):
+ existing_md = open(p["claudemd"], encoding="utf-8").read()
+ with open(p["claudemd"], "w", encoding="utf-8") as f:
+ f.write(fsutil.upsert_marker_block(existing_md, CLAUDE_PTR, PTR_BEGIN, PTR_END))
+ result["written"] = [p["settings"], p["playbook"], p["state"], p["claudemd"]]
+ return result
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_cli_init.py -v`
+Expected: PASS (3 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/cli.py tests/test_cli_init.py
+git commit -m "feat: cmd_init with denylist + dry-run + reinit guard"
+```
+
+---
+
+### Task 10: CLI — phase-next / status / activate + argparse main
+
+**Files:**
+- Modify: `pw/cli.py`
+- Test: `tests/test_cli_more.py`
+
+**Interfaces:**
+- Consumes: `pw.state`, `pw.fsutil`
+- Produces:
+ - `pw.cli.cmd_phase_next(project_dir, now) -> dict` — 상태 읽어 advance, 저장, `{phase, atEnd, guidance}` 반환. guidance는 playbook.md의 해당 단계 섹션 텍스트.
+ - `pw.cli.cmd_status(project_dir) -> dict` — `{preset, phase, enabled, disabled}` 반환. 파일 없으면 `RuntimeError("not initialized")`.
+ - `pw.cli.main(argv) -> int` — `argparse`로 `init|phase-next|status|activate` 디스패치.
+
+- [ ] **Step 1: 실패 테스트 작성**
+
+Create `tests/test_cli_more.py`:
+
+```python
+import json, os
+from pw import cli
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def _installed(tmp_path):
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills"]
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ return str(p)
+
+def test_phase_next_advances_and_returns_guidance(tmp_path):
+ proj = tmp_path / "p"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ out = cli.cmd_phase_next(str(proj), now="2026-07-06T01:00:00Z")
+ assert out["phase"] == "plan"
+ assert out["atEnd"] is False
+ assert "plan" in out["guidance"]
+ st = json.loads((proj / ".claude" / "project-state.json").read_text())
+ assert st["phase"] == "plan"
+
+def test_status_returns_current(tmp_path):
+ proj = tmp_path / "p2"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ s = cli.cmd_status(str(proj))
+ assert s["preset"] == "minimal"
+ assert s["phase"] == "brainstorm"
+
+def test_status_uninitialized_raises(tmp_path):
+ proj = tmp_path / "empty"; proj.mkdir()
+ try:
+ cli.cmd_status(str(proj)); assert False
+ except RuntimeError as e:
+ assert "not initialized" in str(e)
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_cli_more.py -v`
+Expected: FAIL — `AttributeError: cmd_phase_next`.
+
+- [ ] **Step 3: 최소 구현** — `pw/cli.py`에 추가:
+
+```python
+import argparse, re
+
+def _phase_section(playbook_text, phase):
+ m = re.search(rf"(^## {re.escape(phase)}\b.*?)(?=^## |\Z)", playbook_text, re.DOTALL | re.MULTILINE)
+ return m.group(1).strip() if m else ""
+
+def cmd_phase_next(project_dir, now):
+ p = _paths(project_dir)
+ st = fsutil.read_json(p["state"])
+ if st is None:
+ raise RuntimeError("not initialized")
+ st2 = state.advance(st, now)
+ fsutil.write_json(p["state"], st2)
+ pb = open(p["playbook"], encoding="utf-8").read() if os.path.exists(p["playbook"]) else ""
+ return {"phase": st2["phase"], "atEnd": st2.get("_atEnd", False),
+ "guidance": _phase_section(pb, st2["phase"])}
+
+def cmd_status(project_dir):
+ p = _paths(project_dir)
+ st = fsutil.read_json(p["state"])
+ if st is None:
+ raise RuntimeError("not initialized")
+ settings = fsutil.read_json(p["settings"], {})
+ ep = settings.get("enabledPlugins", {})
+ return {"preset": st["preset"], "phase": st["phase"],
+ "enabled": [k for k, v in ep.items() if v],
+ "disabled": [k for k, v in ep.items() if not v]}
+
+def cmd_activate(project_dir, slug, installed_path):
+ p = _paths(project_dir)
+ installed = data.installed_plugins(installed_path)
+ if slug not in installed:
+ raise RuntimeError(f"not installed: {slug}")
+ settings = fsutil.merge_enabled_plugins(fsutil.read_json(p["settings"], {}), [slug], [])
+ fsutil.write_json(p["settings"], settings)
+ return {"activated": slug, "note": "restart session to load"}
+
+def main(argv):
+ import datetime
+ ap = argparse.ArgumentParser(prog="pw")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ home = os.path.expanduser("~")
+ dflt_presets = os.path.join(home, ".claude", "project-presets.json")
+ dflt_installed = os.path.join(home, ".claude", "plugins", "installed_plugins.json")
+ pi = sub.add_parser("init"); pi.add_argument("preset"); pi.add_argument("--dry-run", action="store_true")
+ pi.add_argument("--force", action="store_true")
+ sub.add_parser("phase-next"); sub.add_parser("status")
+ pa = sub.add_parser("activate"); pa.add_argument("slug")
+ args = ap.parse_args(argv)
+ now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+ cwd = os.getcwd()
+ if args.cmd == "init":
+ out = cmd_init(cwd, args.preset, dflt_presets, dflt_installed, now,
+ dry_run=args.dry_run, force=args.force)
+ elif args.cmd == "phase-next":
+ out = cmd_phase_next(cwd, now)
+ elif args.cmd == "status":
+ out = cmd_status(cwd)
+ elif args.cmd == "activate":
+ out = cmd_activate(cwd, args.slug, dflt_installed)
+ import json as _json
+ print(_json.dumps(out, ensure_ascii=False, indent=2))
+ return 0
+
+if __name__ == "__main__":
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
+```
+
+- [ ] **Step 4: 통과 확인**
+
+Run: `python3 -m pytest tests/test_cli_more.py -v`
+Expected: PASS (3 passed)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add pw/cli.py tests/test_cli_more.py
+git commit -m "feat: phase-next/status/activate + argparse main"
+```
+
+---
+
+### Task 11: 슬래시 명령 md + install.sh + 통합 테스트
+
+**Files:**
+- Create: `commands/project-init.md`, `commands/phase-next.md`, `commands/project-status.md`, `commands/project-activate.md`
+- Create: `install.sh`
+- Test: `tests/test_integration.py`
+
+**Interfaces:**
+- Consumes: `pw.cli.main`
+- Produces: 설치 스크립트 + 슬래시 명령. `install.sh`는 `pw/`, `commands/*.md`, `pw/presets.json`을 `~/.claude/`로 복사.
+
+- [ ] **Step 1: 통합 실패 테스트 작성**
+
+Create `tests/test_integration.py`:
+
+```python
+import json, os
+from pw import cli
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_end_to_end_init_then_phase_next(tmp_path, monkeypatch):
+ proj = tmp_path / "app"; proj.mkdir()
+ (proj / "pyproject.toml").write_text("[project]\nname='x'")
+ (proj / "svc.py").write_text("x=1")
+ inst = tmp_path / "installed.json"
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills",
+ "pyright-lsp@claude-plugins-official"]
+ inst.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ res = cli.cmd_init(str(proj), "minimal", PRESETS, str(inst), now="t")
+ # 언어 감지로 pyright LSP 가 활성에 포함
+ assert "pyright-lsp@claude-plugins-official" in res["enabled"]
+ pb = (proj / ".claude" / "playbook.md").read_text()
+ assert "pyright-lsp" in pb
+ out = cli.cmd_phase_next(str(proj), now="t2")
+ assert out["phase"] == "plan"
+```
+
+- [ ] **Step 2: 실패 확인**
+
+Run: `python3 -m pytest tests/test_integration.py -v`
+Expected: PASS 또는 FAIL — 이 테스트는 기존 코드로 통과해야 정상(회귀 확인용). 만약 LSP 확장이 minimal 프리셋(`lspByLanguage:true`)에서 안 되면 FAIL → 원인 수정.
+
+- [ ] **Step 3: 슬래시 명령 + install.sh 작성**
+
+Create `commands/project-init.md`:
+
+```markdown
+---
+description: 새 프로젝트에 프리셋을 적용하고 단계별 플레이북을 생성한다
+argument-hint: [preset] [--dry-run|--force]
+---
+현재 폴더에서 프로젝트 프리셋 워크플로우를 초기화한다.
+
+사용자가 프리셋을 인자로 주지 않았으면, 먼저 `python3 ~/.claude/pw/cli.py status` 를 시도해 이미 초기화됐는지 보고, 아니면 폴더의 package.json/pyproject.toml 등을 근거로 프리셋(web-fullstack/backend-api/security-audit/docs-deck/minimal) 중 하나를 추천하고 확인받는다.
+
+확정되면 실행: `python3 ~/.claude/pw/cli.py init ` (미리보기는 `--dry-run`).
+출력 요약을 사용자에게 보여주고, **"새 세션에서 플러그인이 로드된다"** 는 점과 다음 스텝(`/phase-next`)을 안내한다.
+$ARGUMENTS
+```
+
+Create `commands/phase-next.md`:
+
+```markdown
+---
+description: 워크플로우를 다음 단계로 진행하고 그 단계의 도구 가이드를 출력한다
+---
+`python3 ~/.claude/pw/cli.py phase-next` 를 실행하고, 반환된 guidance(현재 단계 도구 순서)를 사용자에게 보여준다. atEnd 가 true 면 마지막 단계임을 알린다.
+```
+
+Create `commands/project-status.md`:
+
+```markdown
+---
+description: 현재 프리셋·단계·활성 플러그인을 보여준다
+---
+`python3 ~/.claude/pw/cli.py status` 를 실행하고 결과(preset, phase, enabled/disabled)를 표로 정리해 보여준다.
+```
+
+Create `commands/project-activate.md`:
+
+```markdown
+---
+description: 프리셋 밖 플러그인을 이 프로젝트에 추가 활성화한다
+argument-hint:
+---
+`python3 ~/.claude/pw/cli.py activate $ARGUMENTS` 를 실행하고, "재시작 시 로드됨" 안내를 전달한다.
+```
+
+Create `install.sh`:
+
+```bash
+#!/usr/bin/env bash
+set -euo pipefail
+DEST="$HOME/.claude"
+mkdir -p "$DEST/commands" "$DEST/pw"
+cp -R pw/. "$DEST/pw/"
+cp pw/presets.json "$DEST/project-presets.json"
+cp commands/*.md "$DEST/commands/"
+echo "설치 완료: $DEST/pw, $DEST/commands, $DEST/project-presets.json"
+echo "명령: /project-init /phase-next /project-status /project-activate"
+```
+
+참고: `cli.py`의 argparse 기본 경로는 `~/.claude/project-presets.json` 과 `~/.claude/plugins/installed_plugins.json` 를 가리키므로, 설치 후 실 사용 시 프리셋 원천은 `~/.claude/project-presets.json`이다.
+
+- [ ] **Step 4: 전체 테스트 통과 확인**
+
+Run: `python3 -m pytest -v`
+Expected: PASS (모든 테스트 그린)
+
+- [ ] **Step 5: 커밋**
+
+```bash
+git add commands/ install.sh tests/test_integration.py
+git commit -m "feat: slash commands + install.sh + e2e integration test"
+```
+
+---
+
+## Self-Review 결과
+
+- **Spec coverage:** 프리셋/단계모델(T1,7) · 슬러그검증(T2) · settings 병합+denylist(T4,9) · 마커 보존(T3) · 언어감지(T5) · 유효집합(T6) · 플레이북(T7) · 상태/전환(T8) · init/phase-next/status/activate(T9,10) · 명령·설치(T11) · CLAUDE.md 포인터(T9) · 멱등/dry-run/force(T9) · MCP는 문서화만(비목표) — 전 항목 태스크 매핑됨.
+- **Placeholder scan:** 모든 코드 스텝에 실제 코드/테스트 포함, TODO 없음.
+- **Type consistency:** `effective_plugins`/`plugin_name`(T6) → playbook(T7)·cli(T9)에서 동일 시그니처 사용. `advance(state, now)`(T8) → cli(T10)에서 동일. `merge_enabled_plugins(existing, enable, disable)`(T4) → cli(T9,10)에서 동일. 일관.
diff --git a/modules/ccpilot/docs/superpowers/specs/2026-07-06-agent-orchestration-B-design.md b/modules/ccpilot/docs/superpowers/specs/2026-07-06-agent-orchestration-B-design.md
new file mode 100644
index 0000000..8db30c5
--- /dev/null
+++ b/modules/ccpilot/docs/superpowers/specs/2026-07-06-agent-orchestration-B-design.md
@@ -0,0 +1,144 @@
+# B — 특화 서브에이전트 오케스트레이션 설계 문서
+
+- 작성일: 2026-07-06
+- 상태: 설계 확정 대기 (코덱스 리뷰 반영, 축소 v1)
+- 선행: A(프로젝트 프리셋 워크플로우) — 완료·설치됨
+- 범위: **B v1 — 이미 로드된 능력 사이의 특화 라우팅 + 종합**
+
+## 1. 목적
+
+구체 작업("이 코드 보안 점검해줘")에 대해, **이미 로드된** 플러그인 에이전트·스킬 중 최적을 골라 **독립 컨텍스트로 디스패치**하고, 여러 결과를 **구조화 종합**해 메인 세션을 가볍게 유지한다. 원본 에이전트·스킬은 **일절 수정하지 않는다**(저하 0의 유일한 보장).
+
+## 2. 비목표 (v1 제외 · 후속)
+
+- **세션 중 플러그인 hot-enable/disable** — Claude Code는 세션 시작 시 로드. 불가. (A/세션 재시작 담당)
+- **intent→preset 자동 선택** — A의 `/project-init` 확장으로 분리.
+- **persistent `agent-catalog.json`** — v1은 live 조회. 반복 라우팅 모호성이 실증되면 캐시로 도입.
+- **범용 무한 라우팅** — v1은 2개 도메인(보안·테스트) + 미지 작업 폴백 규칙.
+- **서브에이전트의 중첩 디스패치** — 미검증. v1 의존 금지.
+
+## 3. 검증된 Claude Code 메커니즘 (전제)
+
+- 에이전트 정의 = `~/.claude/agents/*.md`(user) / `/.claude/agents/*.md`(project). frontmatter: `name`, `description`, `tools`(허용목록), `model`, 본문 시스템 프롬프트. 플러그인은 자체 에이전트를 캐시에 제공.
+- **서브에이전트는 메인 Claude가 Task/Agent 도구로 디스패치.** 관측된 에이전트 정의엔 Task/Agent 도구가 없음 → **서브에이전트는 다른 서브에이전트를 못 띄움**(중첩 불가). 스킬은 서브에이전트도 호출 가능.
+- 플러그인은 세션 시작 시 로드.
+
+## 4. 아키텍처 & 파일
+
+```
+~/.claude/
+├── agents/
+│ ├── security-auditor.md # 얇은 종합 전문가 (스킬 호출 + 구조화 종합)
+│ └── test-engineer.md # 얇은 종합 전문가
+├── commands/
+│ └── route.md # /route <작업> — 디스패치 "계획" 생성 (메인이 실행)
+└── route-rules.json # 작업→선호 에이전트·우선순위 규칙 (소량)
+```
+설치는 A의 `install.sh`를 확장해 함께 배포(§12).
+
+**동작 흐름:** 사용자가 작업을 말함 → 메인 Claude가 `/route <작업>` 실행 → route.md가 `route-rules.json` + **live 에이전트/스킬 디렉토리 조회**로 **디스패치 계획** 생성 → 메인 Claude가 계획대로 Task 디스패치(병렬 가능) → 각 결과(구조화)를 메인이 **종합**.
+
+## 5. 전문가 에이전트 설계 (얇게)
+
+각 전문가는 **서브에이전트**이며, **스킬을 직접 호출**해 작업하고 **구조화 리포트**를 반환한다. 여러 *에이전트* 조합은 전문가 내부가 아니라 `/route` 계획(메인 레벨)이 담당한다.
+
+**공통 규칙(코덱스 #1·#6):**
+- 스킬·원본 플러그인 에이전트 파일을 **수정하지 않는다**.
+- **고유 종합 가치**가 있을 때만 존재. 원본 단일 에이전트로 충분하면 `/route`가 원본을 우선 디스패치.
+- 얇고 선언적: "무엇을 종합하는가 / 어떤 스킬·에이전트를 쓰나 / 무엇을 중복하지 말 것 / 스킬 없을 때 폴백".
+- 이름·설명의 권위는 live 조회. 하드코딩된 절차 복제 금지.
+
+**`security-auditor.md`** — `tools: Bash, Read, Glob, Grep`, `model: sonnet`.
+- 쓰는 스킬: kesekit(KISA 점검), static-analysis(`/semgrep`·`/codeql`), security-guidance 가이드.
+- 고유 가치: 세 관점(규제·규칙기반 정적분석·실시간 패턴)의 결과를 **하나로 중복제거·우선순위화**하고 이견 보존.
+- 폴백: 스킬 미설치 시 해당 관점 생략하고 리포트에 명시.
+
+**`test-engineer.md`** — `tools: Bash, Read, Write, Edit, Glob`, `model: sonnet`.
+- 쓰는 스킬: test-writer-fixer, 감지 언어 LSP, 테스트 러너(pytest/jest 등).
+- 고유 가치: 테스트 작성→실행→실패분석→수정 루프를 한 격리 컨텍스트에서 돌리고 커버리지 갭을 종합.
+- 폴백: 러너/LSP 없으면 명시.
+
+## 6. `/route` — 디스패치 계획 명령 (코덱스 #2)
+
+`/route <작업 설명>` 은 **자율 실행자가 아니라 계획 생성기**다. route.md(프롬프트/제어 텍스트)가 메인 Claude에게:
+
+1. `route-rules.json` 로드 + **live 조회**: `~/.claude/agents/*.md`, `/.claude/agents/*.md`, 플러그인 캐시의 `*/agents/*.md`, 사용 가능 스킬 목록을 읽어 **현재 실제 존재하는** 에이전트/스킬 파악.
+2. 작업을 규칙에 매칭 → **디스패치 계획** 산출:
+ - 선택된 에이전트/스킬 + **각 선택 이유**
+ - 병렬 안전 여부
+ - 각 디스패치의 **정확한 task 프롬프트**
+ - 기대 **출력 계약**(§10)
+ - **종합 체크리스트**
+ - 건너뛸 항목과 이유
+3. 메인 Claude가 계획대로 Task 디스패치 후 §10 규칙으로 종합.
+
+**우선순위 규칙(코덱스 #5):** 광범위 보안 → `security-auditor`; 정밀 Semgrep만 → 원본 `semgrep-scanner`; 테스트 → `test-engineer`; **미지 작업 → 원본 플러그인 에이전트 우선**(큐레이티드 래퍼는 문서화된 통합 이점이 있을 때만).
+
+## 7. `route-rules.json` + live 조회 + 신선도 (코덱스 #4)
+
+v1은 **persistent 카탈로그를 만들지 않는다.** 대신:
+- `route-rules.json`(소량): `{ "rules": [ {"match": ["보안","security","취약"], "prefer": "security-auditor", "narrow": {"semgrep만": "semgrep-scanner@static-analysis"}}, {"match": ["테스트","test","커버리지"], "prefer":"test-engineer"} ], "fallback": "prefer-original-plugin-agents" }`
+- **live 조회로 항상 최신**: `/route` 실행 시 에이전트 디렉토리를 그때 읽으므로 드리프트 없음. 규칙이 가리키는 에이전트가 실제로 없으면 계획에서 제외하고 사유 표기.
+- 규칙 파일은 사용자가 자유 편집(새 도메인 추가).
+
+## 8. 저하 0 원칙 (테스트 가능하게 재정의, 코덱스 #1)
+
+"무조건 향상"은 보장 대상이 아니라 **설계 불변식**으로 표현:
+- **INV-1:** B는 어떤 스킬·플러그인 에이전트 파일도 수정/삭제하지 않는다.
+- **INV-2:** 작업이 원본 플러그인 에이전트와 직접 매치되면 `/route`는 그 원본을 우선 디스패치(재구현 금지).
+- **INV-3:** 종합은 개별 결과를 **버리지 않고** 이견을 보존한다.
+향상은 (a)올바른 선택 (b)병렬 (c)교차-플러그인 종합에서만 나온다. 테스트: INV-1은 파일 해시 불변, INV-2/3은 계획·종합 출력 검증.
+
+## 9. A/B 경계 (코덱스 #8)
+
+- A: 프리셋·단계 상태 소유. B: **단계 상태 소유 안 함.**
+- A 플레이북의 review/implement 단계가 "`/route`로 위임"을 안내할 수 있음(소프트 참조).
+- **B는 A 없이도 동작** — live 카탈로그와 현재 작업만으로.
+
+## 10. 구조화 출력 & 종합 규칙 (코덱스 #7)
+
+디스패치되는 모든 에이전트는 아래를 반환해야 한다:
+```
+- findings: [...]
+- evidence: 파일/라인/명령 출력
+- inspected: 조사한 파일·명령
+- confidence: high|med|low
+- unresolved: 미해결 질문
+- next: 권장 다음 행동
+```
+**종합 규칙:** 이견 보존 + 각 주요 주장에 **출처 에이전트 표기** + 과장 금지(예: "도구가 X 보고" ≠ "X는 확실히 익스플로잇 가능", 전문가가 명시 결론 냈을 때만 승격).
+
+## 11. 동적 플러그인 한계 (코덱스 #3, 명시)
+
+- B v1은 **이미 로드된** 에이전트/스킬 사이에서만 라우팅.
+- hot-enable/disable 안 함.
+- 작업이 현재 프리셋 밖 능력을 요구하면 `/route`는 계획 대신 **"이 세션엔 없음 — 프리셋 켜고 재시작(/project-activate)"** 을 보고.
+
+## 12. 설치 & 배포
+
+- A의 `install.sh`를 확장: `agents/*.md` → `~/.claude/agents/`, `commands/route.md` → `~/.claude/commands/`, `route-rules.json` → `~/.claude/route-rules.json` 복사(기존 pptx 에이전트 등 **덮어쓰지 않음** — 동명 없음 확인).
+- `~/.claude/agents/`의 기존 사용자 에이전트는 보존.
+
+## 13. 엣지 케이스
+
+- **규칙이 가리키는 에이전트 부재** → 계획에서 제외 + 사유.
+- **작업이 여러 도메인** → 계획에 복수 전문가(병렬 안전 표기).
+- **스킬 일부 미설치** → 전문가가 폴백·명시.
+- **원본과 큐레이티드가 둘 다 매치** → §6 우선순위로 하나 선택(광범위=큐레이티드, 정밀=원본).
+- **프리셋 밖 능력 요구** → §11 보고.
+
+## 14. 테스트 전략
+
+- `route-rules.json` 로드·검증(스키마).
+- live 조회: 임시 에이전트 디렉토리에 더미 `*.md`를 두고, 규칙 매칭이 존재하는 것만 계획에 넣는지 / 부재 시 제외하는지.
+- 계획 출력 형식(선택·이유·병렬·프롬프트·출력계약·종합체크) 존재 검증.
+- INV-1: security-auditor/test-engineer 프롬프트에 "원본 스킬·에이전트 파일 수정 금지" 불변식 문구 포함 검증.
+- 프리셋 밖 능력 요구 시 "재시작 안내" 경로.
+- (전문가 에이전트 자체의 종합 품질은 실사용 관측 — 자동 단위테스트 대상 아님.)
+
+## 15. 향후 (v2+)
+
+- persistent `agent-catalog.json`(신선도 해시·타임스탬프) — 반복 라우팅 모호성 실증 시.
+- intent→preset (A 확장): 대화 시작 시 "X 할거야" → 프리셋 추천.
+- 전문가 추가(perf-reviewer, docs-writer 등).
+- A 플레이북에 `/route` 참조 자동 삽입.
diff --git a/modules/ccpilot/docs/superpowers/specs/2026-07-06-intent-kickoff-v3-design.md b/modules/ccpilot/docs/superpowers/specs/2026-07-06-intent-kickoff-v3-design.md
new file mode 100644
index 0000000..a38c51f
--- /dev/null
+++ b/modules/ccpilot/docs/superpowers/specs/2026-07-06-intent-kickoff-v3-design.md
@@ -0,0 +1,76 @@
+# v0.3.0 — 의도 기반 킥오프 (intent-assisted kickoff) 설계 문서
+
+- 작성일: 2026-07-06
+- 상태: 설계 확정 (코덱스 리뷰 "build with changes" 반영)
+- 선행: A(프리셋·단계) · B(에이전트 라우팅) · v2(SessionStart 훅) — 완료·설치됨
+
+## 1. 목적
+
+프로젝트 시작 발화("이 프로젝트 초기화해줘" / "프리셋 정해줘")를 감지하면, **프리셋을 자동 추론 → 프리뷰 → 확인 → `/project-init` 실행**까지 이어준다. 프리셋 선택·타이핑 부담을 없애되, **파일 쓰기 전 반드시 확인**한다.
+
+## 2. 코덱스 반영 원칙 (핵심)
+
+- **확률적 트리거로 파일 자동 작성 금지** → 쓰기 전 확인 게이트 필수(코덱스 #1).
+- **재시작 최소화 최적화 폐기** → init은 denylist로 비프리셋을 끄기까지 하므로 거의 항상 설정이 바뀜 → "init 후 1회 재시작"으로 단순·정확(코덱스 #2).
+- **intent 추론은 모델(스킬 본문)이**, 결정적 코드는 검증·언어감지·프리뷰만(코덱스 #5). 키워드 매칭을 authoritative로 쓰지 않는다.
+- **트리거는 좁게** — 명시적 초기화/셋업 발화만. 일반 "X 만들거야"엔 안 걸린다(코덱스 #4).
+- **낮은 확신 → 자동 실행 X, 명령 추천만**(코덱스 #9).
+- **프리뷰·되돌리기** — 기존 `/project-init X --dry-run` 재사용(코덱스 #6).
+
+## 3. 비목표
+
+- **무확인·무재시작 조용한 완전자동** — 위험·아키텍처상 불가. 확인 게이트 유지.
+- 새 결정적 추론 엔진 — 모델이 추론, 신규 파이썬 최소.
+- 세션 중 플러그인 hot-toggle — 여전히 세션 시작 로드(재시작 필요).
+
+## 4. 아키텍처
+
+기존 자산 재사용이 핵심 — 신규 코드 최소.
+
+```
+~/.claude/skills/project-kickoff/SKILL.md # 신규: 자동 트리거 스킬(모델 주도)
+install.sh # 확장: 스킬 복사
+docs/… # spec + plan
+```
+
+- **project-kickoff 스킬**: 자동 트리거(좁은 description). 본문이 Claude에게 아래 흐름을 지시.
+- **재사용**: 언어 감지·프리뷰는 이미 있는 `python3 ~/.claude/pw/cli.py init --dry-run`(enabled/disabled/missing JSON 반환)로 처리. 신규 파이썬 없음.
+
+## 5. 스킬 흐름 (SKILL.md 본문)
+
+1. **트리거 판별**: "이 폴더/프로젝트를 초기화/셋업", "Claude Code 프리셋 정해줘", "프로젝트 워크플로우 설정" 등 **명시적 킥오프 의도**일 때만. 단순 "X 만들거야"·브레인스토밍·리팩터링 언급엔 발동하지 않는다.
+2. **프리셋 추론(모델)**: 사용자 메시지 + 폴더 파일(package.json/pyproject.toml 등)로 5개 프리셋 중 후보 판단.
+ - 참고 힌트(authoritative 아님): FastAPI·Django·API·백엔드→backend-api · React·Next·UI→web-fullstack · 보안·감사→security-audit · 슬라이드·PPT·문서→docs-deck · 그 외→minimal.
+3. **프리뷰**: `python3 ~/.claude/pw/cli.py init --dry-run` 실행 → 활성/비활성 플러그인·재시작 필요 표시.
+4. **확인 게이트**: "이 폴더를 ``로 초기화할까요? (활성 N · 비활성 M · 재시작 1회)". **승인 전 파일 쓰기 금지.**
+5. **실행**: 승인 시 `python3 ~/.claude/pw/cli.py init ` → "새 세션에서 로드됨(재시작 1회)" 안내.
+6. **낮은 확신/모호**: 자동 실행하지 않고, 후보 프리셋과 정확한 명령(`/project-init `)만 추천. 폴더 초기화 자체가 모호하면 **행동 동의부터** 묻는다("이 폴더를 초기화할까요?").
+7. **기존 프로젝트 보호**: 이미 `.claude/project-state.json`이 있으면 재초기화 대신 현황(`/project-status`)을 안내.
+
+## 6. 안전·되돌리기
+
+- 파일 쓰기는 승인 후에만. init은 비파괴(기존 설정·CLAUDE.md 마커 밖 보존, `--force` 없이는 재초기화 거부).
+- 프리뷰(`--dry-run`)로 변경 대상을 먼저 보여준다.
+
+## 7. 테스트 전략
+
+스킬은 마크다운(모델 행동)이라 필수 요소 존재를 검증:
+- 좁은 트리거 문구 · dry-run 프리뷰 단계 · **확인 게이트 문구** · 낮은 확신 시 추천만 · 재시작 안내 · 기존 프로젝트 보호 언급.
+- 오트리거 방지: "단순 'X 만들거야'엔 발동 안 함" 문구 존재.
+- (추론 정확도는 모델 영역 — 자동 단위테스트 대상 아님.)
+
+## 8. 설치·배포
+
+- `install.sh`에 `mkdir -p ~/.claude/skills/project-kickoff` + 스킬 복사 추가(가산).
+- README `## 버전 기록`에 v0.3.0.
+
+## 9. 정직한 기대치
+
+- ✅ "초기화해줘" → 프리셋 자동 추론 + 프리뷰 + 확인 → init. 선택·타이핑 제거.
+- ❌ 무확인·무재시작 완전자동 아님(확인 게이트 유지).
+- v2 대비 delta: "추천"에서 "확인 후 자동 실행"으로 한 단계.
+
+## 10. 향후
+
+- intent 힌트를 presets.json로 외부화(다국어·도메인 확장).
+- 사용 로그로 트리거 정밀도 튜닝.
diff --git a/modules/ccpilot/docs/superpowers/specs/2026-07-06-project-preset-workflow-design.md b/modules/ccpilot/docs/superpowers/specs/2026-07-06-project-preset-workflow-design.md
new file mode 100644
index 0000000..f6c9444
--- /dev/null
+++ b/modules/ccpilot/docs/superpowers/specs/2026-07-06-project-preset-workflow-design.md
@@ -0,0 +1,262 @@
+# 프로젝트 프리셋 & 단계별 워크플로우 시스템 — 설계 문서
+
+- 작성일: 2026-07-06
+- 상태: 설계 확정 대기 (코덱스 리뷰 반영본)
+- 범위: **A — 프로젝트 도구 프로파일 매니저** (B 특화 서브에이전트 라이브러리는 후속)
+
+## 1. 목적
+
+새 프로젝트를 시작할 때 **프리셋으로 활성 플러그인을 고르고**, 그 조합에 맞는 **단계별 워크플로우(플레이북)** 를 자동 생성한다. 플레이북은 설치된 도구들의 강점을 충돌 없이 단계별로 배치해, "지금 무엇을 어떤 도구로 할지"를 지휘한다.
+
+전제 사용자 환경: 플러그인 20개 + 개인 스킬 2개(academic-pptx, pptx-from-layouts) + MCP 8개(전부 연결).
+
+## 2. 비목표 (이번 범위에서 제외)
+
+- **B. 특화 서브에이전트 라이브러리** (보안/테스트 전용 에이전트) — 별도 spec
+- **claude.ai 전역 커넥터 MCP의 프로젝트별 on/off** — 전역이라 제어 불가, 문서화만
+- **SessionStart 훅 기반 단계 자동주입** — v2로 연기 (v1은 CLAUDE.md 포인터)
+- **플러그인/마켓 패키징 배포** — 잘 돌아가면 v2에서 `kimhands/project-orchestrator`로
+
+## 3. 검증된 Claude Code 메커니즘 (전제)
+
+- `~/.claude/settings.json`의 `enabledPlugins` = `{"plugin@marketplace": true|false}`. 프로젝트 `.claude/settings.json`이 프로젝트 스코프로 override.
+- **플러그인은 세션 시작 시 로드** — 도중 토글은 재시작해야 반영.
+- 설정 우선순위: user → project → project.local (local이 최종 우선일 수 있음, CLI `--setting-sources`도 영향).
+- 프로젝트 `.mcp.json` + `enabledMcpjsonServers`는 프로젝트 스코프 MCP만 제어. claude.ai 커넥터는 전역.
+- SessionStart 훅은 `hookSpecificOutput.additionalContext`로 텍스트 주입 가능(읽기 전용). 대화형 UI 불가.
+- 슬래시 명령 = `~/.claude/commands/*.md`(user) 또는 `/.claude/commands/*.md`(project).
+
+## 4. 아키텍처 & 파일 구조
+
+```
+~/.claude/ # 이 머신 전역 (한 번 설치)
+├── commands/
+│ ├── project-init.md # /project-init [preset] [--dry-run|--repair|--force]
+│ ├── phase-next.md # /phase-next [--activate]
+│ ├── project-status.md # /project-status
+│ └── project-activate.md # /project-activate
+├── project-presets.json # 단일 원천: 프리셋 + 단계모델 + 규칙 + 능력태그
+└── scripts/
+ └── project_workflow.py # 결정적 파일 쓰기/검증 헬퍼 (명령이 호출)
+
+/.claude/ # /project-init 이 생성
+├── settings.json # enabledPlugins (allowlist true + denylist false)
+├── playbook.md # 생성된 단계별 워크플로우 (생성블록 마커 포함)
+└── project-state.json # { preset, phase, phases[], history[], schemaVersion }
+/CLAUDE.md # 플레이북 포인터 한 블록 추가(마커)
+```
+
+**설계 원칙**: `project-presets.json` 하나가 단일 원천. 명령어는 얇게(읽고 검증하고 결정적으로 쓰기). 파일 쓰기·검증 로직은 `project_workflow.py`에 모아 **명령(모델 매개)과 실제 변경(결정적 스크립트)을 분리** — 코덱스 지적(슬래시 명령만으로 대화형 설정은 불안정) 반영.
+
+## 5. 데이터 모델 — `project-presets.json`
+
+```jsonc
+{
+ "schemaVersion": 1,
+ "alwaysOn": ["superpowers@superpowers-dev", "agentmemory@agentmemory",
+ "andrej-karpathy-skills@karpathy-skills"],
+ "phaseModel": {
+ "phases": ["brainstorm", "plan", "implement", "review", "ship"],
+ "roles": {
+ "brainstorm": [
+ { "role": "요구사항 취조", "tool": "grill-me", "optional": true },
+ { "role": "설계 확정", "tool": "superpowers:brainstorming" },
+ { "role": "기존코드 이해", "tool": "understand-anything", "whenCapability": "existing-code" }
+ ],
+ "plan": [
+ { "role": "계획 작성", "tool": "superpowers:writing-plans" },
+ { "role": "영향 분석", "tool": "understand-anything", "whenCapability": "existing-code" },
+ { "role": "라이브러리 문서", "tool": "context7" }
+ ],
+ "implement": [
+ { "role": "구현 루프", "tool": "superpowers:test-driven-development" },
+ { "role": "언어 인텔리전스", "tool": "__lsp_by_language__" },
+ { "role": "테스트 작성/수정", "tool": "test-writer-fixer" },
+ { "role": "라이브러리 문서", "tool": "context7" },
+ { "role": "UI 생성", "tool": "frontend-design", "whenCapability": "frontend" },
+ { "role": "문서 산출물", "tool": "document-skills", "whenCapability": "docs-output" }
+ ],
+ "review": [
+ { "role": "주력 리뷰", "tool": "/code-review" },
+ { "role": "단순화", "tool": "code-simplifier" },
+ { "role": "실시간 보안", "tool": "security-guidance" },
+ { "role": "정적 보안", "tool": "static-analysis" },
+ { "role": "한국 규제", "tool": "kesekit", "whenCapability": "kr-compliance" }
+ ],
+ "ship": [
+ { "role": "커밋/PR", "tool": "gh" },
+ { "role": "릴리스 문서", "tool": "document-skills" },
+ { "role": "학습 영속", "tool": "agentmemory:remember" }
+ ]
+ }
+ },
+ "capabilityTags": {
+ "detect": {
+ "typescript": ["package.json", "tsconfig.json"],
+ "python": ["pyproject.toml", "requirements.txt"],
+ "go": ["go.mod"], "rust": ["Cargo.toml"],
+ "frontend": ["package.json:react", "package.json:next"],
+ "infra": ["Dockerfile", "*.tf"],
+ "existing-code": ["src/**", ">10 source files"]
+ },
+ "toolFor": { "typescript": "typescript-lsp@claude-plugins-official",
+ "python": "pyright-lsp@claude-plugins-official" }
+ },
+ "presets": {
+ "web-fullstack": { "plugins": ["typescript-lsp@...","pyright-lsp@...","frontend-design@...",
+ "figma@...","vercel@...","context7@...","test-writer-fixer@awesome-claude-plugins",
+ "code-simplifier@...","security-guidance@...","understand-anything@understand-anything"] },
+ "backend-api": { "plugins": ["context7@claude-plugins-official",
+ "test-writer-fixer@awesome-claude-plugins","static-analysis@trailofbits",
+ "security-guidance@claude-plugins-official","code-simplifier@claude-plugins-official",
+ "understand-anything@understand-anything"], "lspByLanguage": true },
+ "security-audit": { "plugins": ["static-analysis@trailofbits","kesekit@kesekit",
+ "security-guidance@...","understand-anything@...","code-simplifier@..."] },
+ "docs-deck": { "plugins": ["document-skills@anthropic-agent-skills","felo-slides@felo-ai",
+ "context7@..."], "personalSkills": ["academic-pptx","pptx-from-layouts"] },
+ "minimal": { "plugins": ["context7@..."], "lspByLanguage": true }
+ },
+ "invocationRules": {
+ "orchestrator": { "primary": "superpowers", "rescueOnly": ["codex"] },
+ "memory": { "single": "agentmemory" },
+ "review": { "primary": "/code-review",
+ "specialists": ["code-simplifier","security-guidance","static-analysis","kesekit"],
+ "order": "primary first → specialists on explicit trigger",
+ "stopWhen": "no new findings" },
+ "lsp": "one per detected language",
+ "docs": { "general": "document-skills", "specialized": ["academic-pptx","pptx-from-layouts","felo-slides"] }
+ }
+}
+```
+
+**설계 결정**: 프리셋은 **plugins 목록만** 정의. 단계 배치는 `phaseModel`, 언어별 LSP는 `capabilityTags`로 **런타임 유도** → 다언어 프로젝트 대응(코덱스 #8).
+
+## 6. 단계 모델 (5단계)
+
+| 단계 | 역할 → 도구 (프리셋에 있을 때만 플레이북에 표시) |
+|---|---|
+| brainstorm | grill-me(선택) → superpowers:brainstorming → understand-anything(기존코드 시) |
+| plan | superpowers:writing-plans → understand-anything(영향분석) → context7 |
+| implement | superpowers TDD/subagent → LSP(감지언어) → test-writer-fixer → context7 → frontend-design/pptx(해당 시) |
+| review | /code-review(주력) → code-simplifier → security-guidance → static-analysis(/semgrep) → kesekit(한국규제) |
+| ship | gh CLI → document-skills(릴리스 문서) → agentmemory:remember(학습 영속) |
+
+상시(alwaysOn): agentmemory · andrej-karpathy · superpowers.
+
+## 7. 활성화 모델 (핵심 — 코덱스 반영)
+
+**프리셋 = allowlist + denylist**:
+- `/project-init`이 프로젝트 `.claude/settings.json`에 **프리셋+alwaysOn 플러그인 = `true`**, **현재 켜져 있는 非프리셋 플러그인 = `false`** 를 기록 → 프로젝트가 실제로 lean해짐(코덱스 #6).
+- init 후 **세션 1회 재시작**으로 반영.
+- **단계(phase)는 플러그인을 토글하지 않고 "사용 안내"** 만 함(사용자 확정 사항). `enabled`인 도구 중 그 단계에 쓸 것을 플레이북이 지휘.
+- **`/phase-next --activate`(선택)**: 그 단계 전용 무거운 도구를 뒤늦게 켜고 싶을 때만 `enabledPlugins` 수정 + "재시작 시 로드" 안내.
+
+**슬러그 검증**: 프리셋의 `plugin@marketplace` 키를 `~/.claude/plugins/installed_plugins.json`과 대조. 불일치 시 경고하고 건너뜀(조용한 누락 방지, 코덱스 #5). **로컬 설정 override 경고**: "effective config may be overridden by project.local settings" 안내.
+
+## 8. 명령어 동작
+
+모든 명령은 `project_workflow.py`를 호출해 **결정적**으로 파일을 읽고/검증하고/쓴다. 명령 md는 인자 파싱과 사용자 대화만 담당.
+
+### `/project-init [preset] [--dry-run|--repair|--force]`
+1. 인자로 preset 받음. 없으면 `capabilityTags.detect`로 프로젝트 언어/유형 감지 → 추천 프리셋 제시 후 확인.
+2. **멱등성 검사**: 이미 `project-state.json` 있으면 `--force` 없이는 덮어쓰지 않고 `--repair` 안내.
+3. 프리셋+alwaysOn 슬러그를 설치 목록과 대조·검증.
+4. `.claude/settings.json` 병합 기록(기존 보존, allowlist `true`/denylist `false`).
+5. `playbook.md` 생성(단계모델 ∩ 프리셋 ∩ 감지언어, **생성블록 마커** `…`).
+6. `project-state.json` = `{preset, phase:"brainstorm", phases, history:[], schemaVersion}`.
+7. `CLAUDE.md`에 포인터 블록(마커) append (기존 내용 보존).
+8. 출력: 활성/비활성 요약 · **"새 세션에서 로드됨"** · 다음 스텝. `--dry-run`이면 변경 없이 계획만 출력.
+
+### `/phase-next [--activate]`
+1. `project-state.json` 읽어 현재 단계 → 다음 단계 계산.
+2. **검증**: 다음 단계 도구가 실제 설치·활성인지 확인, 아니면 경고.
+3. state 갱신(history append).
+4. 그 단계의 도구 사용 가이드(플레이북에서) 출력.
+5. `--activate` 시에만 그 단계 추가 플러그인을 `enabledPlugins`에 켜고 재시작 안내.
+
+### `/project-status`
+- 현재 preset·phase·활성/비활성 플러그인 목록 + 이번 단계 가이드 + 드리프트 경고(설치≠설정 시).
+
+### `/project-activate `
+- 프리셋 밖 플러그인 추가: 슬러그 검증 → `enabledPlugins` true → "재시작 시 로드".
+
+## 9. `playbook.md` 형식
+
+```md
+
+# 프로젝트 플레이북 — web-fullstack (langs: typescript, python)
+> 현재 단계는 .claude/project-state.json. /phase-next 로 진행.
+
+## ① brainstorm
+1. grill-me 로 요구사항 취조 (선택)
+2. superpowers:brainstorming 로 설계 확정
+- 상시: agentmemory 캡처 · superpowers 단일 오케스트레이터
+
+## ② plan …
+## ③ implement … (LSP: typescript-lsp, pyright-lsp)
+## ④ review …
+## ⑤ ship …
+
+## 호출 규칙 (충돌 가드)
+- 오케스트레이터: superpowers 하나. codex는 /codex:rescue 시에만.
+- 메모리: agentmemory 하나.
+- 리뷰: /code-review 주력 먼저 → 전문 리뷰어는 트리거 시 → 새 지적 없으면 정지.
+
+```
+
+## 10. `project-state.json` + 드리프트 방어
+
+```json
+{ "schemaVersion": 1, "preset": "web-fullstack",
+ "phase": "brainstorm", "phases": ["brainstorm","plan","implement","review","ship"],
+ "detectedLanguages": ["typescript","python"],
+ "history": [{ "phase": "brainstorm", "at": "2026-07-06T10:00:00Z" }] }
+```
+- 모든 명령은 실행 전 **설치 목록 대조**로 드리프트(플러그인 삭제 등) 감지 → 경고.
+- `--repair`: state·playbook·settings를 현재 설치 상태에 맞춰 재생성(생성블록만 교체, 사용자 편집 보존).
+
+## 11. 소비 방식 (v1)
+
+- **CLAUDE.md 포인터만** (SessionStart 훅 없음, 코덱스 #2). 마커 블록:
+ ```
+ 이 프로젝트는 .claude/playbook.md 의 단계별 워크플로우를 따른다.
+ 현재 단계는 .claude/project-state.json 참조.
+ ```
+- Claude가 단계를 반복적으로 놓치는 게 관측되면 v2에서 SessionStart 훅(작은 텍스트 주입, append-only·멱등) 추가.
+
+## 12. 언어/능력 감지
+
+- init·status 시 `capabilityTags.detect`로 repo 파일 스캔 → `detectedLanguages`/capabilities 산출.
+- 플레이북의 LSP·frontend·infra 항목은 감지 결과로 채움 → 다언어/혼합 프로젝트 정확.
+
+## 13. 충돌 규칙 = 호출 규칙 (코덱스 #10)
+
+"설치 하나"가 아니라 **호출 순서·정지 조건**으로 정의:
+- 리뷰: 주력(/code-review) 먼저 → 전문(simplifier/security/static-analysis/kesekit)은 명시 트리거 → 새 지적 없으면 정지.
+- 오케스트레이터/메모리는 여전히 단일(진짜 충돌).
+
+## 14. MCP 처리 (코덱스 #7)
+
+- `project_mcp`: `.mcp.json` 프로젝트 서버만 자동 관리(있을 때).
+- `global_mcp_assumptions`: claude.ai 커넥터(Figma/Google/Notion/Gmail)·플러그인 MCP(context7/agentmemory/vercel)는 **"사용 가능하나 프리셋 관리 대상 아님"** 으로 플레이북에 사용 안내만.
+
+## 15. 엣지 케이스 / 에러 처리
+
+- **재-init**: `--force` 없이는 비파괴. `--repair`로 생성블록만 갱신.
+- **삭제된 플러그인 참조**: 명령이 설치 목록 대조로 감지·경고·건너뜀.
+- **로컬 설정 override**: init이 "project.local이 최종 우선일 수 있음" 경고.
+- **사용자 수동 편집**: 생성블록 마커 밖 내용은 절대 건드리지 않음.
+- **hooks 병합**: 훅 쓸 일 생기면 append-only·네임스페이스·멱등(v2).
+
+## 16. 테스트 전략
+
+- `project_workflow.py` 단위 테스트: 슬러그 검증, settings 병합(기존 보존/allowlist/denylist), 생성블록 마커 교체, 멱등(--dry-run 무변경), 언어 감지.
+- 통합: 빈 폴더 → `/project-init web-fullstack --dry-run` → 계획 검증 → 실제 실행 → 파일 3종 + CLAUDE.md 확인 → `/phase-next` → state 전이 확인.
+- 회귀: 기존 CLAUDE.md/settings.json 있는 프로젝트에서 사용자 내용 보존 확인.
+
+## 17. 향후 (v2+)
+
+- SessionStart 훅 단계 자동주입(필요 입증 시).
+- **B. 특화 서브에이전트 라이브러리**(보안/테스트 전용 에이전트, 도구 스코핑 + 컨텍스트 격리).
+- 플러그인/마켓 패키징으로 팀·다머신 공유.
+- 프리셋 추가(mobile-rn, data-py 등).
diff --git a/modules/ccpilot/install.sh b/modules/ccpilot/install.sh
new file mode 100755
index 0000000..66fb5b8
--- /dev/null
+++ b/modules/ccpilot/install.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")"
+DEST="$HOME/.claude"
+mkdir -p "$DEST/commands" "$DEST/pw"
+cp -R pw/. "$DEST/pw/"
+cp pw/presets.json "$DEST/project-presets.json"
+cp commands/*.md "$DEST/commands/"
+
+# --- subsystem B: agent orchestration ---
+mkdir -p "$DEST/pw_route" "$DEST/agents"
+cp -R pw_route/. "$DEST/pw_route/"
+cp pw_route/route-rules.json "$DEST/route-rules.json"
+cp agents/security-auditor.md agents/test-engineer.md "$DEST/agents/"
+cp commands/route.md "$DEST/commands/"
+
+# --- v2: SessionStart hook (멱등, 기존 훅 보존) ---
+python3 pw/install_hook.py
+
+# --- v3: intent-based kickoff skill ---
+mkdir -p "$DEST/skills/project-kickoff"
+cp skills/project-kickoff/SKILL.md "$DEST/skills/project-kickoff/"
+
+echo "설치 완료: $DEST/pw, $DEST/commands, $DEST/project-presets.json"
+echo "명령: /project-init /phase-next /project-status /project-activate /route"
+echo "SessionStart 훅: 초기화된 프로젝트면 현재 단계를, 미설정이면 /project-init 을 자동 안내"
+echo "킥오프 스킬: '이 프로젝트 초기화해줘' 발화 시 프리셋 추론→프리뷰→확인→init"
diff --git a/modules/ccpilot/pw/__init__.py b/modules/ccpilot/pw/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/modules/ccpilot/pw/cli.py b/modules/ccpilot/pw/cli.py
new file mode 100644
index 0000000..8543d6a
--- /dev/null
+++ b/modules/ccpilot/pw/cli.py
@@ -0,0 +1,116 @@
+import argparse, os, re
+import sys
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from pw import data, detect, fsutil, playbook, state
+
+CLAUDE_PTR = ("이 프로젝트는 .claude/playbook.md 의 단계별 워크플로우를 따른다. "
+ "현재 단계는 .claude/project-state.json 참조.")
+PTR_BEGIN, PTR_END = "", ""
+
+def _paths(project_dir):
+ c = os.path.join(project_dir, ".claude")
+ return {"claude": c,
+ "settings": os.path.join(c, "settings.json"),
+ "playbook": os.path.join(c, "playbook.md"),
+ "state": os.path.join(c, "project-state.json"),
+ "claudemd": os.path.join(project_dir, "CLAUDE.md")}
+
+def cmd_init(project_dir, preset, presets_path, installed_path, now, dry_run=False, force=False):
+ p = _paths(project_dir)
+ if os.path.exists(p["state"]) and not force and not dry_run:
+ raise RuntimeError("already initialized; use --repair or --force")
+ presets = data.load_presets(presets_path)
+ installed = data.installed_plugins(installed_path)
+ caps = detect.detect_capabilities(project_dir, presets["capabilityTags"]["detect"])
+ caps |= set(presets["presets"].get(preset, {}).get("capabilities", []))
+ lsp = detect.lsp_slugs(caps, presets["capabilityTags"]["lspFor"])
+ effective = data.effective_plugins(presets["presets"], preset, presets["alwaysOn"], lsp)
+ enable, missing = data.validate_slugs(effective, installed)
+ disable = [s for s in sorted(installed) if s not in set(enable)]
+ pb = playbook.generate_playbook(preset, presets["phaseModel"], enable, caps, lsp,
+ presets["invocationRules"])
+ st = state.default_state(preset, presets["phaseModel"]["phases"], sorted(caps))
+ result = {"enabled": enable, "disabled": disable, "missing": missing,
+ "dryRun": dry_run, "written": []}
+ if dry_run:
+ return result
+ settings = fsutil.merge_enabled_plugins(fsutil.read_json(p["settings"], {}), enable, disable)
+ fsutil.write_json(p["settings"], settings)
+ os.makedirs(p["claude"], exist_ok=True)
+ with open(p["playbook"], "w", encoding="utf-8") as f:
+ f.write(pb)
+ fsutil.write_json(p["state"], st)
+ existing_md = ""
+ if os.path.exists(p["claudemd"]):
+ with open(p["claudemd"], encoding="utf-8") as f:
+ existing_md = f.read()
+ with open(p["claudemd"], "w", encoding="utf-8") as f:
+ f.write(fsutil.upsert_marker_block(existing_md, CLAUDE_PTR, PTR_BEGIN, PTR_END))
+ result["written"] = [p["settings"], p["playbook"], p["state"], p["claudemd"]]
+ return result
+
+def _phase_section(playbook_text, phase):
+ m = re.search(rf"(^## {re.escape(phase)}\b.*?)(?=^## |\Z)", playbook_text, re.DOTALL | re.MULTILINE)
+ return m.group(1).strip() if m else ""
+
+def cmd_phase_next(project_dir, now):
+ p = _paths(project_dir)
+ st = fsutil.read_json(p["state"])
+ if st is None:
+ raise RuntimeError("not initialized")
+ st2 = state.advance(st, now)
+ fsutil.write_json(p["state"], st2)
+ pb = open(p["playbook"], encoding="utf-8").read() if os.path.exists(p["playbook"]) else ""
+ return {"phase": st2["phase"], "atEnd": st2.get("_atEnd", False),
+ "guidance": _phase_section(pb, st2["phase"])}
+
+def cmd_status(project_dir):
+ p = _paths(project_dir)
+ st = fsutil.read_json(p["state"])
+ if st is None:
+ raise RuntimeError("not initialized")
+ settings = fsutil.read_json(p["settings"], {})
+ ep = settings.get("enabledPlugins", {})
+ return {"preset": st["preset"], "phase": st["phase"],
+ "enabled": [k for k, v in ep.items() if v],
+ "disabled": [k for k, v in ep.items() if not v]}
+
+def cmd_activate(project_dir, slug, installed_path):
+ p = _paths(project_dir)
+ installed = data.installed_plugins(installed_path)
+ if slug not in installed:
+ raise RuntimeError(f"not installed: {slug}")
+ settings = fsutil.merge_enabled_plugins(fsutil.read_json(p["settings"], {}), [slug], [])
+ fsutil.write_json(p["settings"], settings)
+ return {"activated": slug, "note": "restart session to load"}
+
+def main(argv):
+ import datetime
+ ap = argparse.ArgumentParser(prog="pw")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ home = os.path.expanduser("~")
+ dflt_presets = os.path.join(home, ".claude", "project-presets.json")
+ dflt_installed = os.path.join(home, ".claude", "plugins", "installed_plugins.json")
+ pi = sub.add_parser("init"); pi.add_argument("preset"); pi.add_argument("--dry-run", action="store_true")
+ pi.add_argument("--force", action="store_true")
+ sub.add_parser("phase-next"); sub.add_parser("status")
+ pa = sub.add_parser("activate"); pa.add_argument("slug")
+ args = ap.parse_args(argv)
+ now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ cwd = os.getcwd()
+ if args.cmd == "init":
+ out = cmd_init(cwd, args.preset, dflt_presets, dflt_installed, now,
+ dry_run=args.dry_run, force=args.force)
+ elif args.cmd == "phase-next":
+ out = cmd_phase_next(cwd, now)
+ elif args.cmd == "status":
+ out = cmd_status(cwd)
+ elif args.cmd == "activate":
+ out = cmd_activate(cwd, args.slug, dflt_installed)
+ import json as _json
+ print(_json.dumps(out, ensure_ascii=False, indent=2))
+ return 0
+
+if __name__ == "__main__":
+ import sys
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/modules/ccpilot/pw/data.py b/modules/ccpilot/pw/data.py
new file mode 100644
index 0000000..b6872fd
--- /dev/null
+++ b/modules/ccpilot/pw/data.py
@@ -0,0 +1,40 @@
+import json
+
+REQUIRED_KEYS = ("alwaysOn", "phaseModel", "capabilityTags", "presets", "invocationRules")
+
+def load_presets(path):
+ with open(path, encoding="utf-8") as f:
+ d = json.load(f)
+ if d.get("schemaVersion") != 1:
+ raise ValueError(f"unsupported schemaVersion: {d.get('schemaVersion')}")
+ for k in REQUIRED_KEYS:
+ if k not in d:
+ raise ValueError(f"missing key: {k}")
+ return d
+
+def installed_plugins(installed_json_path):
+ with open(installed_json_path, encoding="utf-8") as f:
+ d = json.load(f)
+ return set(d.get("plugins", {}).keys())
+
+def validate_slugs(slugs, installed):
+ valid = [s for s in slugs if s in installed]
+ missing = [s for s in slugs if s not in installed]
+ return valid, missing
+
+def plugin_name(slug):
+ return slug.split("@", 1)[0]
+
+def effective_plugins(presets, preset_name, always_on, lsp_slugs):
+ if preset_name not in presets:
+ raise KeyError(preset_name)
+ preset = presets[preset_name]
+ ordered = list(preset.get("plugins", [])) + list(always_on)
+ if preset.get("lspByLanguage"):
+ ordered += list(lsp_slugs)
+ seen, result = set(), []
+ for s in ordered:
+ if s not in seen:
+ seen.add(s)
+ result.append(s)
+ return result
diff --git a/modules/ccpilot/pw/detect.py b/modules/ccpilot/pw/detect.py
new file mode 100644
index 0000000..f10812a
--- /dev/null
+++ b/modules/ccpilot/pw/detect.py
@@ -0,0 +1,32 @@
+import os, glob
+
+SOURCE_EXTS = (".py", ".ts", ".js", ".go", ".rs")
+IGNORE_DIRS = {".claude", "docs", "node_modules", ".git"}
+
+def _marker_hit(project_dir, marker):
+ if "::" in marker:
+ fname, substr = marker.split("::", 1)
+ p = os.path.join(project_dir, fname)
+ return os.path.exists(p) and substr in open(p, encoding="utf-8", errors="ignore").read()
+ if "*" in marker:
+ return bool(glob.glob(os.path.join(project_dir, marker)))
+ return os.path.exists(os.path.join(project_dir, marker))
+
+def _has_source(project_dir):
+ for root, dirs, files in os.walk(project_dir):
+ dirs[:] = [d for d in dirs if d not in IGNORE_DIRS]
+ if any(f.endswith(SOURCE_EXTS) for f in files):
+ return True
+ return False
+
+def detect_capabilities(project_dir, capability_tags):
+ caps = set()
+ for cap, markers in capability_tags.items():
+ if any(_marker_hit(project_dir, m) for m in markers):
+ caps.add(cap)
+ if _has_source(project_dir):
+ caps.add("existing-code")
+ return caps
+
+def lsp_slugs(capabilities, lsp_for):
+ return [slug for lang, slug in lsp_for.items() if lang in capabilities]
diff --git a/modules/ccpilot/pw/fsutil.py b/modules/ccpilot/pw/fsutil.py
new file mode 100644
index 0000000..3e23a5f
--- /dev/null
+++ b/modules/ccpilot/pw/fsutil.py
@@ -0,0 +1,32 @@
+import copy
+import json, os, re
+
+def read_json(path, default=None):
+ if not os.path.exists(path):
+ return default
+ with open(path, encoding="utf-8") as f:
+ return json.load(f)
+
+def write_json(path, obj):
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ with open(path, "w", encoding="utf-8") as f:
+ json.dump(obj, f, ensure_ascii=False, indent=2)
+ f.write("\n")
+
+def upsert_marker_block(text, block, begin, end):
+ pattern = re.compile(re.escape(begin) + r".*?" + re.escape(end), re.DOTALL)
+ new_block = f"{begin}\n{block}\n{end}"
+ if pattern.search(text):
+ return pattern.sub(lambda m: new_block, text)
+ base = text if (text == "" or text.endswith("\n")) else text + "\n"
+ return f"{base}\n{new_block}\n"
+
+def merge_enabled_plugins(existing, enable, disable):
+ out = copy.deepcopy(existing) if existing else {}
+ ep = dict(out.get("enabledPlugins", {}))
+ for s in disable:
+ ep[s] = False
+ for s in enable: # enable 이 disable 을 이김
+ ep[s] = True
+ out["enabledPlugins"] = ep
+ return out
diff --git a/modules/ccpilot/pw/hook_sessionstart.py b/modules/ccpilot/pw/hook_sessionstart.py
new file mode 100644
index 0000000..69da927
--- /dev/null
+++ b/modules/ccpilot/pw/hook_sessionstart.py
@@ -0,0 +1,50 @@
+import sys, os
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import json, re
+from pw import fsutil, detect
+
+
+def _phase_section(playbook_text, phase):
+ m = re.search(rf"(^## {re.escape(phase)}\b.*?)(?=^## |\Z)", playbook_text,
+ re.DOTALL | re.MULTILINE)
+ return m.group(1).strip() if m else ""
+
+
+def build_context(cwd):
+ """세션 시작 시 주입할 컨텍스트 문자열. 주입할 게 없으면 ''."""
+ claude = os.path.join(cwd, ".claude")
+ state = fsutil.read_json(os.path.join(claude, "project-state.json"))
+ if state:
+ preset = state.get("preset", "?")
+ phase = state.get("phase", "?")
+ tools = ""
+ pb = os.path.join(claude, "playbook.md")
+ if os.path.exists(pb):
+ with open(pb, encoding="utf-8", errors="ignore") as f:
+ sec = _phase_section(f.read(), phase)
+ tools = " · ".join(re.findall(r"—\s*(.+)", sec))
+ line = f"ccpilot: preset={preset} · 현재 단계={phase}"
+ if tools:
+ line += f" · 이 단계 도구: {tools}"
+ line += " · 다음: /phase-next · 플레이북: .claude/playbook.md"
+ return line
+ if detect._has_source(cwd):
+ return "이 폴더는 ccpilot 미설정입니다 — /project-init 으로 프리셋·플레이북을 설정하세요."
+ return ""
+
+
+def main():
+ try:
+ ctx = build_context(os.getcwd())
+ except Exception:
+ ctx = "" # fail-safe: 세션 시작을 절대 깨뜨리지 않는다
+ if ctx:
+ print(json.dumps({"hookSpecificOutput": {
+ "hookEventName": "SessionStart", "additionalContext": ctx}}, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/modules/ccpilot/pw/install_hook.py b/modules/ccpilot/pw/install_hook.py
new file mode 100644
index 0000000..2b9b25d
--- /dev/null
+++ b/modules/ccpilot/pw/install_hook.py
@@ -0,0 +1,33 @@
+import sys, os
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from pw import fsutil
+
+HOOK_CMD = "python3 ~/.claude/pw/hook_sessionstart.py"
+MARKER = "hook_sessionstart.py"
+
+
+def ensure_hook(settings_path):
+ """~/.claude/settings.json 의 SessionStart 훅에 ccpilot 항목을 멱등 추가.
+ 기존 훅(Stop/Notification 등)은 보존. 이미 있으면 'present', 추가하면 'added'."""
+ settings = fsutil.read_json(settings_path, {}) or {}
+ hooks = settings.setdefault("hooks", {})
+ ss = hooks.setdefault("SessionStart", [])
+ for group in ss:
+ for h in group.get("hooks", []):
+ if MARKER in h.get("command", ""):
+ return "present"
+ ss.append({"hooks": [{"type": "command", "command": HOOK_CMD}]})
+ fsutil.write_json(settings_path, settings)
+ return "added"
+
+
+def main():
+ path = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
+ print(f"SessionStart hook: {ensure_hook(path)}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/modules/ccpilot/pw/playbook.py b/modules/ccpilot/pw/playbook.py
new file mode 100644
index 0000000..94d4bed
--- /dev/null
+++ b/modules/ccpilot/pw/playbook.py
@@ -0,0 +1,42 @@
+from pw.data import plugin_name
+
+BEGIN_TMPL = ""
+END = ""
+_ALWAYS_PREFIXES = ("superpowers:", "/code-review", "gh", "agentmemory:")
+
+def _resolve(role, effective_names, capabilities, lsp_slugs):
+ """이 역할이 플레이북에 포함되면 표시 문자열, 아니면 None."""
+ if role.get("whenCapability") and role["whenCapability"] not in capabilities:
+ return None
+ tool = role["tool"]
+ if tool == "__lsp_by_language__":
+ names = [plugin_name(s) for s in lsp_slugs]
+ return ", ".join(names) if names else None
+ if tool.startswith(_ALWAYS_PREFIXES):
+ return tool
+ return tool if plugin_name(tool) in effective_names else None
+
+def generate_playbook(preset_name, phase_model, effective_slugs, capabilities, lsp_slugs, invocation_rules):
+ effective_names = {plugin_name(s) for s in effective_slugs}
+ lines = [BEGIN_TMPL.format(preset=preset_name),
+ f"# 프로젝트 플레이북 — {preset_name}",
+ "> 현재 단계는 .claude/project-state.json. /phase-next 로 진행.", ""]
+ for phase in phase_model["phases"]:
+ lines.append(f"## {phase}")
+ n = 1
+ for role in phase_model["roles"].get(phase, []):
+ shown = _resolve(role, effective_names, capabilities, lsp_slugs)
+ if shown is not None:
+ lines.append(f"{n}. {role['role']} — {shown}")
+ n += 1
+ if n == 1:
+ lines.append("_(이 단계에 활성 도구 없음)_")
+ lines.append("")
+ orch = invocation_rules.get("orchestrator", {})
+ mem = invocation_rules.get("memory", {})
+ lines += ["## 호출 규칙 (충돌 가드)",
+ f"- 오케스트레이터: {orch.get('primary')} 하나. {', '.join(orch.get('rescueOnly', []))} 는 rescue 시에만.",
+ f"- 메모리: {mem.get('single')} 하나.",
+ "- 리뷰: /code-review 주력 먼저 → 전문 리뷰어는 트리거 시 → 새 지적 없으면 정지.",
+ END]
+ return "\n".join(lines) + "\n"
diff --git a/modules/ccpilot/pw/presets.json b/modules/ccpilot/pw/presets.json
new file mode 100644
index 0000000..4772c39
--- /dev/null
+++ b/modules/ccpilot/pw/presets.json
@@ -0,0 +1,69 @@
+{
+ "schemaVersion": 1,
+ "alwaysOn": ["superpowers@superpowers-dev", "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills"],
+ "phaseModel": {
+ "phases": ["brainstorm", "plan", "implement", "review", "ship"],
+ "roles": {
+ "brainstorm": [
+ {"role": "요구사항 취조", "tool": "grill-me", "optional": true},
+ {"role": "설계 확정", "tool": "superpowers:brainstorming"},
+ {"role": "기존코드 이해", "tool": "understand-anything", "whenCapability": "existing-code"}
+ ],
+ "plan": [
+ {"role": "계획 작성", "tool": "superpowers:writing-plans"},
+ {"role": "영향 분석", "tool": "understand-anything", "whenCapability": "existing-code"},
+ {"role": "라이브러리 문서", "tool": "context7"}
+ ],
+ "implement": [
+ {"role": "구현 루프", "tool": "superpowers:test-driven-development"},
+ {"role": "언어 인텔리전스", "tool": "__lsp_by_language__"},
+ {"role": "테스트 작성/수정", "tool": "test-writer-fixer"},
+ {"role": "라이브러리 문서", "tool": "context7"},
+ {"role": "UI 생성", "tool": "frontend-design", "whenCapability": "frontend"},
+ {"role": "문서 산출물", "tool": "document-skills", "whenCapability": "docs-output"}
+ ],
+ "review": [
+ {"role": "주력 리뷰", "tool": "/code-review"},
+ {"role": "단순화", "tool": "code-simplifier"},
+ {"role": "실시간 보안", "tool": "security-guidance"},
+ {"role": "정적 보안", "tool": "static-analysis"},
+ {"role": "한국 규제", "tool": "kesekit", "whenCapability": "kr-compliance"}
+ ],
+ "ship": [
+ {"role": "커밋/PR", "tool": "gh"},
+ {"role": "릴리스 문서", "tool": "document-skills", "whenCapability": "docs-output"},
+ {"role": "학습 영속", "tool": "agentmemory:remember"}
+ ]
+ }
+ },
+ "capabilityTags": {
+ "detect": {
+ "typescript": ["package.json", "tsconfig.json"],
+ "python": ["pyproject.toml", "requirements.txt"],
+ "go": ["go.mod"],
+ "rust": ["Cargo.toml"],
+ "frontend": ["package.json::react", "package.json::next"],
+ "infra": ["Dockerfile", "*.tf"]
+ },
+ "lspFor": {
+ "typescript": "typescript-lsp@claude-plugins-official",
+ "python": "pyright-lsp@claude-plugins-official",
+ "go": "gopls-lsp@claude-plugins-official",
+ "rust": "rust-analyzer-lsp@claude-plugins-official"
+ }
+ },
+ "presets": {
+ "web-fullstack": {"plugins": ["typescript-lsp@claude-plugins-official", "pyright-lsp@claude-plugins-official", "frontend-design@claude-plugins-official", "figma@claude-plugins-official", "vercel@claude-plugins-official", "context7@claude-plugins-official", "test-writer-fixer@awesome-claude-plugins", "code-simplifier@claude-plugins-official", "security-guidance@claude-plugins-official", "understand-anything@understand-anything"]},
+ "backend-api": {"plugins": ["context7@claude-plugins-official", "test-writer-fixer@awesome-claude-plugins", "static-analysis@trailofbits", "security-guidance@claude-plugins-official", "code-simplifier@claude-plugins-official", "understand-anything@understand-anything"], "lspByLanguage": true},
+ "security-audit": {"plugins": ["static-analysis@trailofbits", "kesekit@kesekit", "security-guidance@claude-plugins-official", "understand-anything@understand-anything", "code-simplifier@claude-plugins-official"], "capabilities": ["kr-compliance"]},
+ "docs-deck": {"plugins": ["document-skills@anthropic-agent-skills", "felo-slides@felo-ai", "context7@claude-plugins-official"], "personalSkills": ["academic-pptx", "pptx-from-layouts"], "capabilities": ["docs-output"]},
+ "minimal": {"plugins": ["context7@claude-plugins-official"], "lspByLanguage": true}
+ },
+ "invocationRules": {
+ "orchestrator": {"primary": "superpowers", "rescueOnly": ["codex"]},
+ "memory": {"single": "agentmemory"},
+ "review": {"primary": "/code-review", "specialists": ["code-simplifier", "security-guidance", "static-analysis", "kesekit"], "order": "primary first then specialists on explicit trigger", "stopWhen": "no new findings"},
+ "lsp": "one per detected language",
+ "docs": {"general": "document-skills", "specialized": ["academic-pptx", "pptx-from-layouts", "felo-slides"]}
+ }
+}
diff --git a/modules/ccpilot/pw/state.py b/modules/ccpilot/pw/state.py
new file mode 100644
index 0000000..3ab8aec
--- /dev/null
+++ b/modules/ccpilot/pw/state.py
@@ -0,0 +1,16 @@
+import copy
+
+def default_state(preset, phases, detected_langs):
+ return {"schemaVersion": 1, "preset": preset, "phase": phases[0],
+ "phases": list(phases), "detectedLanguages": list(detected_langs), "history": []}
+
+def advance(state, now):
+ s = copy.deepcopy(state)
+ phases = s["phases"]
+ i = phases.index(s["phase"])
+ if i >= len(phases) - 1:
+ s["_atEnd"] = True
+ return s
+ s["phase"] = phases[i + 1]
+ s.setdefault("history", []).append({"phase": s["phase"], "at": now})
+ return s
diff --git a/modules/ccpilot/pw_route/__init__.py b/modules/ccpilot/pw_route/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/modules/ccpilot/pw_route/cli.py b/modules/ccpilot/pw_route/cli.py
new file mode 100644
index 0000000..6295e3c
--- /dev/null
+++ b/modules/ccpilot/pw_route/cli.py
@@ -0,0 +1,42 @@
+import sys, os
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import argparse, glob, json
+from pw_route import discover, rules
+
+RESTART_NOTE = "capability unavailable in this session; enable preset and restart (/project-activate)"
+
+def default_agent_dirs(home, cwd):
+ candidates = [os.path.join(cwd, ".claude", "agents"),
+ os.path.join(home, ".claude", "agents")]
+ candidates += glob.glob(os.path.join(home, ".claude", "plugins", "cache", "*", "*", "*", "agents"))
+ return [d for d in candidates if os.path.isdir(d)]
+
+def route(task, rules_path, agent_dirs):
+ agents = discover.discover_agents(agent_dirs)
+ names = {a["name"] for a in agents}
+ doc = rules.load_rules(rules_path)
+ m = rules.match_task(task, doc, names)
+ note = ""
+ prefer_unavail = m["prefer"] and not m["prefer"]["available"]
+ narrow_ok = m["narrow"] and m["narrow"]["available"]
+ if prefer_unavail and not narrow_ok:
+ note = RESTART_NOTE
+ return {"task": task, "domain": m["domain"], "prefer": m["prefer"],
+ "narrow": m["narrow"], "fallback": m["fallback"], "matched": m["matched"],
+ "availableAgents": sorted(names), "note": note}
+
+def main(argv):
+ ap = argparse.ArgumentParser(prog="pw_route")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ pr = sub.add_parser("route"); pr.add_argument("task")
+ pr.add_argument("--rules", default=os.path.join(os.path.expanduser("~"), ".claude", "route-rules.json"))
+ args = ap.parse_args(argv)
+ home, cwd = os.path.expanduser("~"), os.getcwd()
+ if args.cmd == "route":
+ out = route(args.task, args.rules, default_agent_dirs(home, cwd))
+ print(json.dumps(out, ensure_ascii=False, indent=2))
+ return 0
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/modules/ccpilot/pw_route/discover.py b/modules/ccpilot/pw_route/discover.py
new file mode 100644
index 0000000..494553d
--- /dev/null
+++ b/modules/ccpilot/pw_route/discover.py
@@ -0,0 +1,38 @@
+import os, glob
+
+def parse_frontmatter(text):
+ if not text.startswith("---"):
+ return {}
+ end = text.find("\n---", 3)
+ if end == -1:
+ return {}
+ block = text[3:end]
+ out = {}
+ for line in block.splitlines():
+ if ":" not in line or line[:1] in (" ", "\t"):
+ continue # skip indented continuation / folded lines
+ key, _, val = line.partition(":")
+ key = key.strip()
+ val = val.strip()
+ if val.startswith((">", "|")):
+ val = "" # folded/literal scalar: value is on following indented lines
+ if key in ("name", "description", "tools"):
+ out[key] = val
+ return out
+
+def discover_agents(dirs):
+ seen, result = set(), []
+ for d in dirs:
+ for path in sorted(glob.glob(os.path.join(d, "*.md"))):
+ try:
+ text = open(path, encoding="utf-8", errors="ignore").read()
+ except OSError:
+ continue
+ fm = parse_frontmatter(text)
+ name = fm.get("name")
+ if not name or name in seen:
+ continue
+ seen.add(name)
+ result.append({"name": name, "description": fm.get("description", ""),
+ "tools": fm.get("tools", ""), "path": path, "source": d})
+ return result
diff --git a/modules/ccpilot/pw_route/route-rules.json b/modules/ccpilot/pw_route/route-rules.json
new file mode 100644
index 0000000..063983b
--- /dev/null
+++ b/modules/ccpilot/pw_route/route-rules.json
@@ -0,0 +1,18 @@
+{
+ "schemaVersion": 1,
+ "rules": [
+ {
+ "domain": "security",
+ "match": ["보안", "security", "취약", "vuln", "audit", "감사"],
+ "prefer": "security-auditor",
+ "narrow": [{ "when": ["semgrep"], "use": "semgrep-scanner" }, { "when": ["codeql"], "use": "semgrep-scanner" }]
+ },
+ {
+ "domain": "test",
+ "match": ["테스트", "test", "커버리지", "coverage", "단위", "unit"],
+ "prefer": "test-engineer",
+ "narrow": []
+ }
+ ],
+ "fallback": "prefer-original-plugin-agents"
+}
diff --git a/modules/ccpilot/pw_route/rules.py b/modules/ccpilot/pw_route/rules.py
new file mode 100644
index 0000000..541aeb4
--- /dev/null
+++ b/modules/ccpilot/pw_route/rules.py
@@ -0,0 +1,33 @@
+import json
+
+def load_rules(path):
+ with open(path, encoding="utf-8") as f:
+ d = json.load(f)
+ if d.get("schemaVersion") != 1:
+ raise ValueError(f"unsupported schemaVersion: {d.get('schemaVersion')}")
+ for k in ("rules", "fallback"):
+ if k not in d:
+ raise ValueError(f"missing key: {k}")
+ if not isinstance(d["rules"], list):
+ raise ValueError("rules must be a list")
+ return d
+
+def _avail(name, available_names):
+ return {"name": name, "available": name in available_names}
+
+def match_task(task, rules_doc, available_names):
+ t = (task or "").lower()
+ result = {"domain": None, "prefer": None, "narrow": None,
+ "fallback": rules_doc.get("fallback"), "matched": False}
+ for rule in rules_doc.get("rules", []):
+ if any(kw.lower() in t for kw in rule.get("match", [])):
+ result["matched"] = True
+ result["domain"] = rule.get("domain")
+ if rule.get("prefer"):
+ result["prefer"] = _avail(rule["prefer"], available_names)
+ for n in rule.get("narrow", []):
+ if all(kw.lower() in t for kw in n.get("when", [])):
+ result["narrow"] = _avail(n["use"], available_names)
+ break
+ break
+ return result
diff --git a/modules/ccpilot/skills/project-kickoff/SKILL.md b/modules/ccpilot/skills/project-kickoff/SKILL.md
new file mode 100644
index 0000000..b939f22
--- /dev/null
+++ b/modules/ccpilot/skills/project-kickoff/SKILL.md
@@ -0,0 +1,47 @@
+---
+name: project-kickoff
+description: >-
+ Use ONLY when the user explicitly asks to initialize or set up THIS folder as a
+ project, or to choose a Claude Code project preset/workflow — e.g. "이 프로젝트
+ 초기화해줘", "프로젝트 셋업", "프리셋 정해줘", "프로젝트 워크플로우 설정",
+ "initialize/set up this project", "choose a project preset". Do NOT trigger on a
+ generic "X 만들거야 / I'm going to build X", brainstorming, refactoring, issue
+ triage, or hypothetical discussion — those are not explicit initialization intent.
+---
+
+당신은 ccpilot의 킥오프 보조자다. **파일을 쓰기 전에 반드시 사용자 확인을 받는다.**
+
+## 발동 조건 (좁게)
+명시적 "이 폴더/프로젝트 초기화·셋업·프리셋 설정" 의도일 때만 진행한다. 단순 "X 만들거야"·브레인스토밍·리팩터링·가정적 논의엔 발동하지 않는다. 초기화 의도가 모호하면 **행동 동의부터** 묻는다: "이 폴더를 ccpilot 프로젝트로 초기화할까요?"
+
+## 흐름
+
+1. **기존 프로젝트 보호.** `.claude/project-state.json` 이 이미 있으면 재초기화하지 말고 `/project-status` 로 현황을 안내한다(사용자가 명시적으로 재설정을 원하면 `--force` 안내).
+
+2. **프리셋 추론 (모델 판단).** 사용자 메시지 + 폴더 파일(package.json·pyproject.toml·go.mod 등)을 근거로 5개 중 후보를 고른다. 아래는 **참고 힌트**(절대 규칙 아님):
+ - FastAPI·Django·API·서버·백엔드 → `backend-api`
+ - React·Next·UI·프론트엔드 → `web-fullstack`
+ - 보안·감사·취약점 → `security-audit`
+ - 슬라이드·PPT·문서·발표자료 → `docs-deck`
+ - 그 외/불명확 → `minimal`
+
+3. **프리뷰 (결정적, 파일 안 바꿈).** 후보 프리셋으로 dry-run을 실행해 무엇이 바뀔지 보여준다:
+ ```
+ python3 ~/.claude/pw/cli.py init --dry-run
+ ```
+ 반환 JSON의 enabled/disabled/missing 을 요약한다(활성 N · 비활성 M · 재시작 1회 필요).
+
+4. **확인 게이트.** "이 폴더를 `` 로 초기화할까요? (활성 N · 비활성 M · 세션 재시작 1회)" 라고 묻는다. **승인 전에는 어떤 파일도 쓰지 않는다.**
+
+5. **실행.** 승인하면:
+ ```
+ python3 ~/.claude/pw/cli.py init
+ ```
+ 그다음 안내: "적용됨 — 선택된 플러그인은 **세션을 한 번 재시작**해야 로드됩니다. 이후 `/phase-next` 로 단계를 진행하세요."
+
+6. **낮은 확신 / 모호.** 자동으로 실행하지 말고, 후보 프리셋과 **정확한 명령**만 추천한다: "가장 맞아 보이는 건 `` 입니다 — `/project-init ` 로 진행하시겠어요?" 확신이 낮으면 `minimal` 을 조용히 강제하지 말고 사용자에게 고르게 한다.
+
+## 원칙
+- **확인 없이 파일을 쓰지 않는다.** 트리거는 확률적이므로 오발동 대비.
+- 재시작 최소화 같은 optimization은 하지 않는다 — init은 비프리셋 플러그인을 끄기까지 하므로 거의 항상 재시작이 필요하다. 일관되게 "재시작 1회"로 안내한다.
+- 추론은 당신(모델)이, 검증·프리뷰는 위 `cli.py` 가 한다.
diff --git a/modules/ccpilot/tests/test_cli_init.py b/modules/ccpilot/tests/test_cli_init.py
new file mode 100644
index 0000000..db5ebf5
--- /dev/null
+++ b/modules/ccpilot/tests/test_cli_init.py
@@ -0,0 +1,44 @@
+import json, os
+from pw import cli
+
+def _installed(tmp_path):
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills",
+ "static-analysis@trailofbits", "kesekit@kesekit",
+ "security-guidance@claude-plugins-official", "code-simplifier@claude-plugins-official",
+ "understand-anything@understand-anything"]
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ return str(p)
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_init_writes_files_and_denylists_non_preset(tmp_path):
+ proj = tmp_path / "proj"; proj.mkdir()
+ res = cli.cmd_init(str(proj), "security-audit", PRESETS, _installed(tmp_path),
+ now="2026-07-06T00:00:00Z")
+ settings = json.loads((proj / ".claude" / "settings.json").read_text())
+ ep = settings["enabledPlugins"]
+ assert ep["static-analysis@trailofbits"] is True # 프리셋
+ assert ep["superpowers@superpowers-dev"] is True # alwaysOn
+ assert ep["context7@claude-plugins-official"] is False # 非프리셋 → denylist
+ assert (proj / ".claude" / "playbook.md").exists()
+ state = json.loads((proj / ".claude" / "project-state.json").read_text())
+ assert state["preset"] == "security-audit" and state["phase"] == "brainstorm"
+ assert "playbook" in (proj / "CLAUDE.md").read_text()
+
+def test_init_dry_run_writes_nothing(tmp_path):
+ proj = tmp_path / "proj2"; proj.mkdir()
+ res = cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path),
+ now="t", dry_run=True)
+ assert res["dryRun"] is True
+ assert not (proj / ".claude").exists()
+
+def test_init_refuses_reinit_without_force(tmp_path):
+ proj = tmp_path / "proj3"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ try:
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ assert False, "should have raised"
+ except RuntimeError as e:
+ assert "already initialized" in str(e)
diff --git a/modules/ccpilot/tests/test_cli_more.py b/modules/ccpilot/tests/test_cli_more.py
new file mode 100644
index 0000000..fca0050
--- /dev/null
+++ b/modules/ccpilot/tests/test_cli_more.py
@@ -0,0 +1,35 @@
+import json, os
+from pw import cli
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def _installed(tmp_path):
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills"]
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ return str(p)
+
+def test_phase_next_advances_and_returns_guidance(tmp_path):
+ proj = tmp_path / "p"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ out = cli.cmd_phase_next(str(proj), now="2026-07-06T01:00:00Z")
+ assert out["phase"] == "plan"
+ assert out["atEnd"] is False
+ assert "plan" in out["guidance"]
+ st = json.loads((proj / ".claude" / "project-state.json").read_text())
+ assert st["phase"] == "plan"
+
+def test_status_returns_current(tmp_path):
+ proj = tmp_path / "p2"; proj.mkdir()
+ cli.cmd_init(str(proj), "minimal", PRESETS, _installed(tmp_path), now="t")
+ s = cli.cmd_status(str(proj))
+ assert s["preset"] == "minimal"
+ assert s["phase"] == "brainstorm"
+
+def test_status_uninitialized_raises(tmp_path):
+ proj = tmp_path / "empty"; proj.mkdir()
+ try:
+ cli.cmd_status(str(proj)); assert False
+ except RuntimeError as e:
+ assert "not initialized" in str(e)
diff --git a/modules/ccpilot/tests/test_data_effective.py b/modules/ccpilot/tests/test_data_effective.py
new file mode 100644
index 0000000..14731f1
--- /dev/null
+++ b/modules/ccpilot/tests/test_data_effective.py
@@ -0,0 +1,21 @@
+import pytest
+from pw import data
+
+PRESETS = {"web": {"plugins": ["a@m", "b@m"]},
+ "min": {"plugins": ["a@m"], "lspByLanguage": True}}
+ALWAYS = ["sp@dev", "am@am"]
+
+def test_plugin_name():
+ assert data.plugin_name("context7@claude-plugins-official") == "context7"
+
+def test_effective_dedup_and_order():
+ eff = data.effective_plugins(PRESETS, "web", ALWAYS, lsp_slugs=["ts@cpo"])
+ assert eff == ["a@m", "b@m", "sp@dev", "am@am"] # web 은 lspByLanguage 아님 → lsp 제외
+
+def test_effective_includes_lsp_when_flagged():
+ eff = data.effective_plugins(PRESETS, "min", ALWAYS, lsp_slugs=["ts@cpo", "py@cpo"])
+ assert eff == ["a@m", "sp@dev", "am@am", "ts@cpo", "py@cpo"]
+
+def test_unknown_preset_raises():
+ with pytest.raises(KeyError):
+ data.effective_plugins(PRESETS, "ghost", ALWAYS, lsp_slugs=[])
diff --git a/modules/ccpilot/tests/test_data_load.py b/modules/ccpilot/tests/test_data_load.py
new file mode 100644
index 0000000..1c73e05
--- /dev/null
+++ b/modules/ccpilot/tests/test_data_load.py
@@ -0,0 +1,17 @@
+import json, os, pytest
+from pw import data
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_load_presets_returns_dict_with_required_keys():
+ d = data.load_presets(PRESETS)
+ assert d["schemaVersion"] == 1
+ for key in ("alwaysOn", "phaseModel", "capabilityTags", "presets", "invocationRules"):
+ assert key in d
+ assert d["phaseModel"]["phases"] == ["brainstorm", "plan", "implement", "review", "ship"]
+
+def test_load_presets_rejects_wrong_schema(tmp_path):
+ p = tmp_path / "bad.json"
+ p.write_text(json.dumps({"schemaVersion": 99}))
+ with pytest.raises(ValueError):
+ data.load_presets(str(p))
diff --git a/modules/ccpilot/tests/test_data_validate.py b/modules/ccpilot/tests/test_data_validate.py
new file mode 100644
index 0000000..9e31c7f
--- /dev/null
+++ b/modules/ccpilot/tests/test_data_validate.py
@@ -0,0 +1,14 @@
+import json
+from pw import data
+
+def test_installed_plugins_reads_keys(tmp_path):
+ p = tmp_path / "installed.json"
+ p.write_text(json.dumps({"plugins": {"a@m1": [{}], "b@m2": [{}]}}))
+ assert data.installed_plugins(str(p)) == {"a@m1", "b@m2"}
+
+def test_validate_slugs_splits_valid_and_missing():
+ installed = {"context7@claude-plugins-official", "kesekit@kesekit"}
+ valid, missing = data.validate_slugs(
+ ["context7@claude-plugins-official", "ghost@nowhere", "kesekit@kesekit"], installed)
+ assert valid == ["context7@claude-plugins-official", "kesekit@kesekit"]
+ assert missing == ["ghost@nowhere"]
diff --git a/modules/ccpilot/tests/test_detect.py b/modules/ccpilot/tests/test_detect.py
new file mode 100644
index 0000000..43cd309
--- /dev/null
+++ b/modules/ccpilot/tests/test_detect.py
@@ -0,0 +1,22 @@
+from pw import detect
+
+TAGS = {"typescript": ["package.json", "tsconfig.json"],
+ "python": ["pyproject.toml"],
+ "frontend": ["package.json::react"],
+ "infra": ["*.tf"]}
+LSP_FOR = {"typescript": "typescript-lsp@cpo", "python": "pyright-lsp@cpo"}
+
+def test_detects_file_and_content_and_glob(tmp_path):
+ (tmp_path / "package.json").write_text('{"dependencies":{"react":"^18"}}')
+ (tmp_path / "main.tf").write_text("resource {}")
+ (tmp_path / "app.py").write_text("x=1")
+ caps = detect.detect_capabilities(str(tmp_path), TAGS)
+ assert "typescript" in caps # package.json 존재
+ assert "frontend" in caps # react 포함
+ assert "infra" in caps # *.tf
+ assert "existing-code" in caps # app.py
+ assert "python" not in caps # pyproject.toml 없음
+
+def test_lsp_slugs_maps_detected_languages():
+ caps = {"typescript", "frontend"}
+ assert detect.lsp_slugs(caps, LSP_FOR) == ["typescript-lsp@cpo"]
diff --git a/modules/ccpilot/tests/test_fsutil_marker.py b/modules/ccpilot/tests/test_fsutil_marker.py
new file mode 100644
index 0000000..a824264
--- /dev/null
+++ b/modules/ccpilot/tests/test_fsutil_marker.py
@@ -0,0 +1,36 @@
+from pw import fsutil
+
+BEGIN, END = "", ""
+
+def test_upsert_appends_when_no_marker():
+ out = fsutil.upsert_marker_block("existing content\n", "NEW", BEGIN, END)
+ assert "existing content" in out
+ assert f"{BEGIN}\nNEW\n{END}" in out
+
+def test_upsert_replaces_between_markers_preserving_outside():
+ text = f"top\n{BEGIN}\nOLD\n{END}\nbottom\n"
+ out = fsutil.upsert_marker_block(text, "NEW", BEGIN, END)
+ assert "OLD" not in out
+ assert "NEW" in out
+ assert out.startswith("top")
+ assert out.rstrip().endswith("bottom")
+
+def test_read_json_default(tmp_path):
+ assert fsutil.read_json(str(tmp_path / "none.json"), default={"x": 1}) == {"x": 1}
+
+def test_upsert_handles_backslash_content():
+ block = "C:\\Users\\x and \\1"
+
+ # Append case (no existing markers)
+ out_append = fsutil.upsert_marker_block("top\n", block, BEGIN, END)
+ assert block in out_append
+
+ # Replace case (markers already present)
+ text = f"top\n{BEGIN}\nOLD\n{END}\nbottom\n"
+ out_replace = fsutil.upsert_marker_block(text, block, BEGIN, END)
+ assert block in out_replace
+ assert "OLD" not in out_replace
+
+def test_upsert_append_no_trailing_newline():
+ out = fsutil.upsert_marker_block("nonl", "NEW", BEGIN, END)
+ assert "nonl\n\n" in out
diff --git a/modules/ccpilot/tests/test_fsutil_settings.py b/modules/ccpilot/tests/test_fsutil_settings.py
new file mode 100644
index 0000000..3581181
--- /dev/null
+++ b/modules/ccpilot/tests/test_fsutil_settings.py
@@ -0,0 +1,19 @@
+from pw import fsutil
+
+def test_merge_preserves_other_keys_and_sets_flags():
+ existing = {"permissions": {"allow": ["x"]},
+ "enabledPlugins": {"keep@m": True, "context7@cpo": True}}
+ out = fsutil.merge_enabled_plugins(
+ existing,
+ enable=["a@m", "b@m"],
+ disable=["context7@cpo", "c@m"])
+ assert out["permissions"] == {"allow": ["x"]} # 보존
+ assert out["enabledPlugins"]["a@m"] is True
+ assert out["enabledPlugins"]["b@m"] is True
+ assert out["enabledPlugins"]["context7@cpo"] is False # denylist가 덮어씀
+ assert out["enabledPlugins"]["c@m"] is False
+ assert out["enabledPlugins"]["keep@m"] is True # 기존 유지
+
+def test_enable_wins_over_disable():
+ out = fsutil.merge_enabled_plugins({}, enable=["a@m"], disable=["a@m"])
+ assert out["enabledPlugins"]["a@m"] is True
diff --git a/modules/ccpilot/tests/test_hook_sessionstart.py b/modules/ccpilot/tests/test_hook_sessionstart.py
new file mode 100644
index 0000000..09be3d3
--- /dev/null
+++ b/modules/ccpilot/tests/test_hook_sessionstart.py
@@ -0,0 +1,56 @@
+import os, sys, json, subprocess
+from pw import hook_sessionstart as hook
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def _init(tmp_path, phase="implement"):
+ claude = tmp_path / ".claude"
+ claude.mkdir()
+ (claude / "project-state.json").write_text(json.dumps(
+ {"schemaVersion": 1, "preset": "backend-api", "phase": phase,
+ "phases": ["brainstorm", "plan", "implement"], "history": []}))
+ (claude / "playbook.md").write_text(
+ "\n## plan\n1. 계획 — superpowers:writing-plans\n\n"
+ "## implement\n1. 구현 루프 — superpowers:test-driven-development\n"
+ "2. 언어 — pyright-lsp\n\n")
+ return str(tmp_path)
+
+
+def test_context_initialized_has_preset_phase_tools(tmp_path):
+ ctx = hook.build_context(_init(tmp_path))
+ assert "preset=backend-api" in ctx
+ assert "implement" in ctx
+ assert "test-driven-development" in ctx and "pyright-lsp" in ctx
+ assert "/phase-next" in ctx
+
+
+def test_context_suggests_when_uninitialized_with_source(tmp_path):
+ (tmp_path / "main.py").write_text("x = 1")
+ ctx = hook.build_context(str(tmp_path))
+ assert "미설정" in ctx and "/project-init" in ctx
+
+
+def test_context_silent_on_empty_dir(tmp_path):
+ assert hook.build_context(str(tmp_path)) == ""
+
+
+def test_script_failsafe_on_broken_state(tmp_path):
+ claude = tmp_path / ".claude"; claude.mkdir()
+ (claude / "project-state.json").write_text("{ this is not valid json")
+ r = subprocess.run([sys.executable, os.path.join(REPO, "pw", "hook_sessionstart.py")],
+ capture_output=True, text=True, cwd=str(tmp_path))
+ assert r.returncode == 0
+ assert "Traceback" not in r.stderr
+ assert "ModuleNotFoundError" not in r.stderr
+ assert r.stdout.strip() == "" # 깨진 상태 → 조용히 무출력
+
+
+def test_script_emits_valid_json_when_initialized(tmp_path):
+ d = _init(tmp_path)
+ r = subprocess.run([sys.executable, os.path.join(REPO, "pw", "hook_sessionstart.py")],
+ capture_output=True, text=True, cwd=d)
+ assert r.returncode == 0
+ payload = json.loads(r.stdout)
+ assert payload["hookSpecificOutput"]["hookEventName"] == "SessionStart"
+ assert "backend-api" in payload["hookSpecificOutput"]["additionalContext"]
diff --git a/modules/ccpilot/tests/test_install_hook.py b/modules/ccpilot/tests/test_install_hook.py
new file mode 100644
index 0000000..b1361c1
--- /dev/null
+++ b/modules/ccpilot/tests/test_install_hook.py
@@ -0,0 +1,36 @@
+import json
+from pw import install_hook
+
+
+def _settings_with_stop(tmp_path):
+ p = tmp_path / "settings.json"
+ p.write_text(json.dumps({"hooks": {"Stop": [
+ {"hooks": [{"type": "command", "command": "afplay glass.aiff", "async": True}]}]}}))
+ return str(p)
+
+
+def test_ensure_hook_adds_and_preserves_existing(tmp_path):
+ path = _settings_with_stop(tmp_path)
+ assert install_hook.ensure_hook(path) == "added"
+ d = json.loads(open(path).read())
+ # Stop 보존
+ assert d["hooks"]["Stop"][0]["hooks"][0]["command"] == "afplay glass.aiff"
+ # SessionStart 추가됨, 우리 스크립트 참조
+ cmds = [h["command"] for g in d["hooks"]["SessionStart"] for h in g["hooks"]]
+ assert any("hook_sessionstart.py" in c for c in cmds)
+
+
+def test_ensure_hook_idempotent(tmp_path):
+ path = _settings_with_stop(tmp_path)
+ install_hook.ensure_hook(path)
+ assert install_hook.ensure_hook(path) == "present"
+ d = json.loads(open(path).read())
+ cmds = [h["command"] for g in d["hooks"]["SessionStart"] for h in g["hooks"]]
+ assert sum("hook_sessionstart.py" in c for c in cmds) == 1 # 중복 없음
+
+
+def test_ensure_hook_creates_settings_when_missing(tmp_path):
+ path = str(tmp_path / "new.json")
+ assert install_hook.ensure_hook(path) == "added"
+ d = json.loads(open(path).read())
+ assert "SessionStart" in d["hooks"]
diff --git a/modules/ccpilot/tests/test_integration.py b/modules/ccpilot/tests/test_integration.py
new file mode 100644
index 0000000..39b49fd
--- /dev/null
+++ b/modules/ccpilot/tests/test_integration.py
@@ -0,0 +1,28 @@
+import json, os, subprocess, sys
+from pw import cli
+
+PRESETS = os.path.join(os.path.dirname(__file__), "..", "pw", "presets.json")
+
+def test_end_to_end_init_then_phase_next(tmp_path, monkeypatch):
+ proj = tmp_path / "app"; proj.mkdir()
+ (proj / "pyproject.toml").write_text("[project]\nname='x'")
+ (proj / "svc.py").write_text("x=1")
+ inst = tmp_path / "installed.json"
+ slugs = ["context7@claude-plugins-official", "superpowers@superpowers-dev",
+ "agentmemory@agentmemory", "andrej-karpathy-skills@karpathy-skills",
+ "pyright-lsp@claude-plugins-official"]
+ inst.write_text(json.dumps({"plugins": {s: [{}] for s in slugs}}))
+ res = cli.cmd_init(str(proj), "minimal", PRESETS, str(inst), now="t")
+ # 언어 감지로 pyright LSP 가 활성에 포함
+ assert "pyright-lsp@claude-plugins-official" in res["enabled"]
+ pb = (proj / ".claude" / "playbook.md").read_text()
+ assert "pyright-lsp" in pb
+ out = cli.cmd_phase_next(str(proj), now="t2")
+ assert out["phase"] == "plan"
+
+def test_cli_runs_as_script_without_import_error(tmp_path):
+ repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ cli_path = os.path.join(repo_root, "pw", "cli.py")
+ result = subprocess.run([sys.executable, cli_path], capture_output=True, text=True, cwd=str(tmp_path))
+ assert "ModuleNotFoundError" not in result.stderr
+ assert result.returncode == 2
diff --git a/modules/ccpilot/tests/test_kickoff_skill.py b/modules/ccpilot/tests/test_kickoff_skill.py
new file mode 100644
index 0000000..416487e
--- /dev/null
+++ b/modules/ccpilot/tests/test_kickoff_skill.py
@@ -0,0 +1,47 @@
+import os
+
+SKILL = os.path.join(os.path.dirname(__file__), "..", "skills", "project-kickoff", "SKILL.md")
+
+
+def _read():
+ with open(SKILL, encoding="utf-8") as f:
+ return f.read()
+
+
+def test_frontmatter_name():
+ t = _read()
+ assert t.startswith("---")
+ assert "name: project-kickoff" in t
+
+
+def test_narrow_trigger_excludes_generic_build():
+ t = _read()
+ # 명시적 초기화 의도만, 일반 "X 만들거야"엔 발동 금지
+ assert "Do NOT trigger" in t
+ assert "만들거야" in t # 제외 예시로 명시
+
+
+def test_confirm_gate_before_writes():
+ t = _read()
+ assert "초기화할까요" in t
+ assert "승인 전" in t or "승인하면" in t
+ assert "쓰지 않는다" in t # 확인 없이 파일 안 씀
+
+
+def test_uses_dry_run_preview():
+ t = _read()
+ assert "--dry-run" in t
+ assert "cli.py init" in t
+
+
+def test_low_confidence_recommends_only():
+ t = _read()
+ assert "낮은 확신" in t or "낮으면" in t
+ assert "추천" in t
+
+
+def test_restart_notice_and_existing_project_protection():
+ t = _read()
+ assert "재시작" in t
+ assert "project-state.json" in t
+ assert "project-status" in t
diff --git a/modules/ccpilot/tests/test_playbook.py b/modules/ccpilot/tests/test_playbook.py
new file mode 100644
index 0000000..fa66713
--- /dev/null
+++ b/modules/ccpilot/tests/test_playbook.py
@@ -0,0 +1,42 @@
+from pw import playbook
+
+PHASE_MODEL = {
+ "phases": ["brainstorm", "implement", "review"],
+ "roles": {
+ "brainstorm": [
+ {"role": "설계", "tool": "superpowers:brainstorming"},
+ {"role": "기존코드", "tool": "understand-anything", "whenCapability": "existing-code"},
+ ],
+ "implement": [
+ {"role": "LSP", "tool": "__lsp_by_language__"},
+ {"role": "테스트", "tool": "test-writer-fixer"},
+ {"role": "UI", "tool": "frontend-design", "whenCapability": "frontend"},
+ ],
+ "review": [{"role": "주력", "tool": "/code-review"}],
+ },
+}
+RULES = {"orchestrator": {"primary": "superpowers", "rescueOnly": ["codex"]},
+ "memory": {"single": "agentmemory"}}
+
+def test_playbook_includes_available_excludes_missing():
+ md = playbook.generate_playbook(
+ preset_name="backend-api",
+ phase_model=PHASE_MODEL,
+ effective_slugs=["test-writer-fixer@awesome-claude-plugins", "superpowers@superpowers-dev"],
+ capabilities=set(), # existing-code, frontend 없음
+ lsp_slugs=["pyright-lsp@claude-plugins-official"],
+ invocation_rules=RULES)
+ assert md.startswith("")
+ assert "superpowers:brainstorming" in md # builtin
+ assert "understand-anything" not in md # capability 없음
+ assert "pyright-lsp" in md # LSP 확장
+ assert "test-writer-fixer" in md # effective 에 있음
+ assert "frontend-design" not in md # frontend capability 없음
+ assert "/code-review" in md
+ assert "superpowers" in md and "codex" in md # 호출 규칙 섹션
+
+def test_playbook_omits_lsp_line_when_no_lsp():
+ md = playbook.generate_playbook("minimal", PHASE_MODEL,
+ effective_slugs=[], capabilities=set(), lsp_slugs=[], invocation_rules=RULES)
+ assert "__lsp_by_language__" not in md
diff --git a/modules/ccpilot/tests/test_route_agents_md.py b/modules/ccpilot/tests/test_route_agents_md.py
new file mode 100644
index 0000000..6a19648
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_agents_md.py
@@ -0,0 +1,24 @@
+import os
+
+AGENTS = os.path.join(os.path.dirname(__file__), "..", "agents")
+STRUCT_KEYS = ["findings", "evidence", "inspected", "confidence", "unresolved", "next"]
+
+def _read(name):
+ return open(os.path.join(AGENTS, name), encoding="utf-8").read()
+
+def test_security_auditor_has_frontmatter_and_invariants():
+ t = _read("security-auditor.md")
+ assert t.startswith("---")
+ assert "name: security-auditor" in t
+ assert "수정하지 않는다" in t # INV-1 (원본 미수정)
+ for k in STRUCT_KEYS:
+ assert k in t # 구조화 출력 계약
+ assert "폴백" in t or "fallback" in t.lower()
+
+def test_test_engineer_has_frontmatter_and_invariants():
+ t = _read("test-engineer.md")
+ assert t.startswith("---")
+ assert "name: test-engineer" in t
+ assert "수정하지 않는다" in t
+ for k in STRUCT_KEYS:
+ assert k in t
diff --git a/modules/ccpilot/tests/test_route_cli.py b/modules/ccpilot/tests/test_route_cli.py
new file mode 100644
index 0000000..42c4cb3
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_cli.py
@@ -0,0 +1,39 @@
+import os, sys, subprocess, json
+from pw_route import cli
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+def test_route_security_available(tmp_path):
+ agents = tmp_path / "agents"; agents.mkdir()
+ (agents / "security-auditor.md").write_text("---\nname: security-auditor\n---\nx")
+ ctx = cli.route("보안 점검해줘", RULES, [str(agents)])
+ assert ctx["domain"] == "security"
+ assert ctx["prefer"] == {"name": "security-auditor", "available": True}
+ assert "security-auditor" in ctx["availableAgents"]
+
+def test_route_unavailable_adds_restart_note(tmp_path):
+ agents = tmp_path / "agents"; agents.mkdir() # empty → security-auditor absent
+ ctx = cli.route("보안 취약점 semgrep 스캔", RULES, [str(agents)])
+ assert ctx["prefer"] == {"name": "security-auditor", "available": False}
+ assert "restart" in ctx["note"].lower()
+
+def test_route_prefer_available_narrow_missing_no_halt(tmp_path):
+ agents = tmp_path / "agents"; agents.mkdir()
+ (agents / "security-auditor.md").write_text("---\nname: security-auditor\n---\nx")
+ ctx = cli.route("run a semgrep security scan", RULES, [str(agents)])
+ assert ctx["prefer"] == {"name": "security-auditor", "available": True}
+ assert ctx["narrow"] == {"name": "semgrep-scanner", "available": False}
+ assert ctx["note"] == ""
+
+def test_default_agent_dirs_filters_existing(tmp_path):
+ (tmp_path / ".claude" / "agents").mkdir(parents=True)
+ dirs = cli.default_agent_dirs(str(tmp_path), str(tmp_path))
+ assert any(d.endswith("/.claude/agents") for d in dirs)
+
+def test_cli_runs_as_script_without_import_error(tmp_path):
+ # 설치 경로처럼 스크립트로 직접 실행 → 임포트 크래시 없어야 함
+ r = subprocess.run([sys.executable, os.path.join(REPO, "pw_route", "cli.py")],
+ capture_output=True, text=True, cwd=str(tmp_path))
+ assert "ModuleNotFoundError" not in r.stderr
+ assert r.returncode == 2 # argparse: missing subcommand
diff --git a/modules/ccpilot/tests/test_route_discover.py b/modules/ccpilot/tests/test_route_discover.py
new file mode 100644
index 0000000..9bd7880
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_discover.py
@@ -0,0 +1,34 @@
+from pw_route import discover
+
+FM = """---
+name: security-auditor
+description: >-
+ Audits security across tools.
+tools: Bash, Read, Glob
+---
+body here
+"""
+
+def test_parse_frontmatter():
+ d = discover.parse_frontmatter(FM)
+ assert d["name"] == "security-auditor"
+ assert d["tools"] == "Bash, Read, Glob"
+
+def test_parse_frontmatter_none():
+ assert discover.parse_frontmatter("no frontmatter here") == {}
+
+def test_discover_agents_reads_dir(tmp_path):
+ (tmp_path / "a.md").write_text("---\nname: alpha\ntools: Read\n---\nx")
+ (tmp_path / "b.md").write_text("---\nname: beta\n---\ny")
+ (tmp_path / "note.txt").write_text("ignored")
+ agents = discover.discover_agents([str(tmp_path)])
+ names = sorted(a["name"] for a in agents)
+ assert names == ["alpha", "beta"]
+ assert all("path" in a and "source" in a for a in agents)
+
+def test_discover_dedup_first_wins(tmp_path):
+ d1 = tmp_path / "d1"; d1.mkdir(); (d1 / "a.md").write_text("---\nname: dup\n---\n1")
+ d2 = tmp_path / "d2"; d2.mkdir(); (d2 / "a.md").write_text("---\nname: dup\n---\n2")
+ agents = discover.discover_agents([str(d1), str(d2)])
+ assert len([a for a in agents if a["name"] == "dup"]) == 1
+ assert agents[0]["source"] == str(d1)
diff --git a/modules/ccpilot/tests/test_route_integration.py b/modules/ccpilot/tests/test_route_integration.py
new file mode 100644
index 0000000..a51c4b0
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_integration.py
@@ -0,0 +1,18 @@
+import os, subprocess
+from pw_route import cli
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+def test_end_to_end_route_with_real_specialist_agents(tmp_path):
+ # 실제 저장소의 agents/ 를 조회 대상으로 사용 → security-auditor 존재 → prefer available
+ agents_dir = os.path.join(REPO, "agents")
+ ctx = cli.route("이 저장소 보안 감사", RULES, [agents_dir])
+ assert ctx["domain"] == "security"
+ assert ctx["prefer"] == {"name": "security-auditor", "available": True}
+ assert ctx["note"] == "" # 사용 가능하므로 재시작 안내 없음
+
+def test_install_sh_syntax_ok():
+ r = subprocess.run(["bash", "-n", os.path.join(REPO, "install.sh")],
+ capture_output=True, text=True)
+ assert r.returncode == 0, r.stderr
diff --git a/modules/ccpilot/tests/test_route_match.py b/modules/ccpilot/tests/test_route_match.py
new file mode 100644
index 0000000..3e6e71d
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_match.py
@@ -0,0 +1,24 @@
+import os
+from pw_route import rules
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+
+def test_match_security_prefer_available():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("이 코드 보안 점검해줘", doc, {"security-auditor"})
+ assert r["matched"] is True
+ assert r["domain"] == "security"
+ assert r["prefer"] == {"name": "security-auditor", "available": True}
+ assert r["narrow"] is None
+
+def test_match_narrow_semgrep_unavailable():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("run a semgrep security scan", doc, {"security-auditor"})
+ assert r["narrow"] == {"name": "semgrep-scanner", "available": False}
+
+def test_no_match_returns_fallback():
+ doc = rules.load_rules(RULES)
+ r = rules.match_task("write me a poem", doc, set())
+ assert r["matched"] is False
+ assert r["prefer"] is None
+ assert r["fallback"] == "prefer-original-plugin-agents"
diff --git a/modules/ccpilot/tests/test_route_rules_load.py b/modules/ccpilot/tests/test_route_rules_load.py
new file mode 100644
index 0000000..549ab1c
--- /dev/null
+++ b/modules/ccpilot/tests/test_route_rules_load.py
@@ -0,0 +1,16 @@
+import json, os, pytest
+from pw_route import rules
+
+RULES = os.path.join(os.path.dirname(__file__), "..", "pw_route", "route-rules.json")
+
+def test_load_rules_ok():
+ d = rules.load_rules(RULES)
+ assert d["schemaVersion"] == 1
+ assert isinstance(d["rules"], list) and len(d["rules"]) >= 2
+ assert d["fallback"] == "prefer-original-plugin-agents"
+ assert any(r["domain"] == "security" for r in d["rules"])
+
+def test_load_rules_bad_schema(tmp_path):
+ p = tmp_path / "bad.json"; p.write_text(json.dumps({"schemaVersion": 2}))
+ with pytest.raises(ValueError):
+ rules.load_rules(str(p))
diff --git a/modules/ccpilot/tests/test_state.py b/modules/ccpilot/tests/test_state.py
new file mode 100644
index 0000000..eb8bbb3
--- /dev/null
+++ b/modules/ccpilot/tests/test_state.py
@@ -0,0 +1,26 @@
+from pw import state
+
+PHASES = ["brainstorm", "plan", "implement"]
+
+def test_default_state():
+ s = state.default_state("web", PHASES, ["python"])
+ assert s["schemaVersion"] == 1
+ assert s["preset"] == "web"
+ assert s["phase"] == "brainstorm"
+ assert s["phases"] == PHASES
+ assert s["detectedLanguages"] == ["python"]
+ assert s["history"] == []
+
+def test_advance_moves_to_next_and_records_history():
+ s = state.default_state("web", PHASES, [])
+ s2 = state.advance(s, now="2026-07-06T00:00:00Z")
+ assert s2["phase"] == "plan"
+ assert s2["history"][-1] == {"phase": "plan", "at": "2026-07-06T00:00:00Z"}
+ assert "_atEnd" not in s2
+
+def test_advance_at_last_phase_flags_end():
+ s = state.default_state("web", PHASES, [])
+ s["phase"] = "implement"
+ s2 = state.advance(s, now="t")
+ assert s2["phase"] == "implement"
+ assert s2["_atEnd"] is True
diff --git a/tests/install-smoke.sh b/tests/install-smoke.sh
index e7a315b..4469aaa 100755
--- a/tests/install-smoke.sh
+++ b/tests/install-smoke.sh
@@ -20,6 +20,15 @@ EOF
pass() { printf 'PASS %s\n' "$1"; }
fail() { printf 'FAIL %s\n' "$1"; exit 1; }
+count_hook() {
+ EVENT="$1" CMD="$2" python3 -c "import json,os; d=json.load(open(os.environ['HOME']+'/.claude/settings.json')); \
+ print(sum(h['command']==os.environ['CMD'] for b in d['hooks'].get(os.environ['EVENT'],[]) for h in b['hooks']))"
+}
+user_settings_kept() {
+ python3 -c "import json,os; d=json.load(open(os.environ['HOME']+'/.claude/settings.json')); \
+ assert d['model']=='x'; assert 'Bash(ls)' in d['permissions']['allow']; \
+ assert any(h['command']=='mine.sh' for b in d['hooks']['Stop'] for h in b['hooks'])"
+}
bash install.sh >/dev/null
@@ -38,6 +47,9 @@ python3 -c "import json,os; d=json.load(open(os.environ['HOME']+'/.claude/settin
|| fail "sound=off 검증 실패"
grep -q ">>> opsmith >>>" "$HOME/.zshrc" || fail "zshrc 마커 없음"
[ -f "$HOME/Ops/golden/gold-set.md" ] || fail "gold-set.md 미생성"
+for p in pw pw_route commands agents skills project-presets.json route-rules.json; do
+ [ ! -e "$HOME/.claude/$p" ] || fail "opsmith 설치가 ccpilot 경로를 만듦: $p"
+done
pass "1차 설치"
# 멱등성: 다시 돌려도 훅/마커가 중복되지 않아야 한다
@@ -49,4 +61,37 @@ MC=$(grep -c ">>> opsmith >>>" "$HOME/.zshrc")
[ "$MC" = "1" ] || fail "멱등성 위반: zshrc 마커 $MC개"
pass "멱등성"
+# ccpilot 공존: 사용자 설정이 있는 HOME에서, 공백 경로의 클론을 다른 위치에서 설치한다
+export HOME="$TMP/h2"
+mkdir -p "$HOME/.claude"
+cat > "$HOME/.claude/settings.json" <<'EOF'
+{"model":"x","permissions":{"allow":["Bash(ls)"]},"hooks":{"Stop":[{"hooks":[{"type":"command","command":"mine.sh"}]}]}}
+EOF
+CLONE="$TMP/with space"
+cp -R "$WORK" "$CLONE"
+install_ccpilot() { (cd / && bash "$CLONE/modules/ccpilot/install.sh" >/dev/null); }
+CCPILOT_HOOK='python3 ~/.claude/pw/hook_sessionstart.py'
+GUARD_HOOK="python3 $HOME/Ops/bin/session-guard.py"
+
+install_ccpilot
+[ -f "$HOME/.claude/pw/cli.py" ] || fail "ccpilot pw 미설치"
+[ -f "$HOME/.claude/skills/project-kickoff/SKILL.md" ] || fail "ccpilot 스킬 미설치"
+bash install.sh >/dev/null
+install_ccpilot
+bash install.sh >/dev/null
+[ "$(count_hook SessionStart "$CCPILOT_HOOK")" = "1" ] || fail "ccpilot 훅 개수 이상"
+[ "$(count_hook SessionStart "$GUARD_HOOK")" = "1" ] || fail "guard 훅 개수 이상"
+user_settings_kept || fail "사용자 설정 유실"
+mkdir -p "$TMP/proj"
+for hook in "$CCPILOT_HOOK" "$GUARD_HOOK"; do
+ (cd "$TMP/proj" && echo '{}' | bash -c "$hook" >/dev/null) || fail "훅 실행 실패: $hook"
+done
+pass "ccpilot 공존"
+
+bash uninstall.sh >/dev/null
+[ "$(count_hook SessionStart "$CCPILOT_HOOK")" = "1" ] || fail "opsmith 제거가 ccpilot 훅을 지움"
+[ "$(count_hook SessionStart "$GUARD_HOOK")" = "0" ] || fail "guard 훅이 남음"
+user_settings_kept || fail "제거 후 사용자 설정 유실"
+pass "opsmith 제거 후 ccpilot 보존"
+
echo "SMOKE OK"