# Router-gate v4.0+v4.1+v4.2 Implementation — Master Coordination Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` to implement sub-plans task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
>
> **This is the MASTER coordination plan.** It does not contain code tasks itself — it orchestrates 7 parallel sub-plans. Each sub-plan is generated via `superpowers:writing-plans` skill in a separate parallel session.

**Goal:** Реализовать router-gate v4.0+v4.1+v4.2 — поведенческий разворот + max-closure (3-judge LLM + per-tool judge + response scan) + VM-sandbox изоляция — за 30-40 часов wall-clock через параллельные сессии (vs 49-65h sequential).

**Architecture:** 9 независимых streams, разбитые на 7 sub-plans + 2 coordination touchpoints. Каждый stream работает над непересекающимися файлами в `tools/` или `docs/`. Sequential зависимости минимальны и явно отмечены.

**Tech Stack:** Node.js (ES modules), vitest (testing), proper-lockfile (atomic state), shell-quote (Bash tokenizer), keytar (OS keychain), VirtualBox (sandbox), Anthropic Claude API через ProxyAPI (LLM-judge).

**Specs (canonical):**
- v4.0 base: [`docs/superpowers/specs/2026-05-29-router-gate-v4-design.md`](../specs/2026-05-29-router-gate-v4-design.md) — 2249 строк
- v4.1 max-closure: [`docs/superpowers/specs/2026-05-29-router-gate-v4-1-max-closure.md`](../specs/2026-05-29-router-gate-v4-1-max-closure.md) — 1051 строк
- v4.2 VM-sandbox: [`docs/superpowers/specs/2026-05-29-router-gate-v4-2-vm-sandbox.md`](../specs/2026-05-29-router-gate-v4-2-vm-sandbox.md) — 411 строк

---

## §1. Parallel Session Strategy

### Принцип параллелизма

**Каждый Stream — отдельная Claude session.** Координация через эту master-plan + `docs/sessions/CURRENT.md` (Pravila §15.1).

**Распределение Streams по сессиям:**

```
                  ┌─ Session 1: Stream A (Pure modules)        [Independent]
                  ├─ Session 2: Stream B (Shell parsing)       [Independent]
                  ├─ Session 3: Stream C (Static + MCP)        [Independent]
Master            ├─ Session 4: Stream D (LLM-judge Layer 4)   [Independent]
session ──────────┤
(вы координируете)├─ Session 5: Stream E (AskUser + subagent)  [Independent]
                  ├─ Session 6: Stream F (VM-sandbox setup)    [Independent, user-driven]
                  │
                  ├─ Sequential CHECKPOINT 1 ────────────────── после A+B+C+D+E
                  │
                  ├─ Session 7: Stream G (Cleanup + register)  [Sequential — depends on A-E]
                  │
                  ├─ Sequential CHECKPOINT 2 ────────────────── после G
                  │
                  ├─ Session 8: User-run Smokes 1-9            [Sequential — depends on G]
                  │
                  └─ Session 9: Stream H (Brain-retro + docs)  [Sequential — depends on smokes]
```

**Wall-clock estimate:**
- Parallel phase (Sessions 1-6 одновременно): 8-12 часов wall-clock (5-6h per stream через subagent-driven-development)
- Checkpoint 1 (review): 1-2 часа
- Session 7 (cleanup + register): 2-3 часа
- Checkpoint 2 + Smokes (user-run): 2-3 часа
- Session 9 (docs): 2-3 часа
- **Итого: ~16-23 часов wall-clock vs 49-65h sequential** — экономия ~30-40h.

### Coordination protocol

**Перед началом каждой parallel session:**

1. Создать worktree per session чтобы не мешать друг другу:
   ```powershell
   git worktree add ../v4-stream-A feat/v4-stream-A
   ```
2. Записать заявку в `docs/sessions/CURRENT.md` (Pravila §15.2):
   ```markdown
   ## Session [N] — Stream [X]
   - **Дата старт:** YYYY-MM-DD HH:MM
   - **Worktree:** ../v4-stream-X
   - **Ветка:** feat/v4-stream-X
   - **Файлы scope:** tools/<list>
   - **Статус:** in_progress | review | merged
   ```
3. Открыть VSCode в worktree, запустить Claude CLI.

**При merge stream'а:**

1. Merge ветки в main: `git checkout main && git merge feat/v4-stream-X --no-ff`
2. Push: `git push origin main`
3. Удалить worktree: `git worktree remove ../v4-stream-X`
4. Обновить `docs/sessions/CURRENT.md` → статус: merged.

**Конфликты между streams:**

Файлы каждого stream'а distinct (см. §2 ниже). **Конфликтов быть не должно**. Если возникает — координация через master session.

---

## §2. Stream definitions

### Stream A — Pure decision modules (Session 1)

**Scope:** Чистые decision-функции и core verifiers без I/O. Сердце gate'а — все определения «allow / block / unlock» живут здесь.

**Files to create (8 modules + tests):**
- `tools/router-gate-decide.mjs` — core decide() function, 4 поведения
- `tools/router-gate-decide.test.mjs`
- `tools/safe-baseline-metering.mjs` — Direction 1 (§3.1.2)
- `tools/safe-baseline-metering.test.mjs`
- `tools/skill-scope-verifier.mjs` — Direction 2 (§3.7) + v4.1 content-level
- `tools/skill-scope-verifier.test.mjs`
- `tools/decomposition-detector.mjs` — Direction 3 (§3.8) + v4.1 hard-block
- `tools/decomposition-detector.test.mjs`
- `tools/todowrite-skill-verifier.mjs` — Direction 4 (§3.9) + v4.1 hard sync
- `tools/todowrite-skill-verifier.test.mjs`
- `tools/self-debrief-detector.mjs` — §3.12 v4.1 (NEW)
- `tools/self-debrief-detector.test.mjs`
- `tools/tdd-real-test-verifier.mjs` — §3.11
- `tools/tdd-real-test-verifier.test.mjs`
- `tools/path-normalization.mjs` — simplified per §3.1.1
- `tools/path-normalization.test.mjs`

**~250 unit tests общим итогом.**

**Dependencies:** Nothing (это pure modules). Может стартовать сразу.

**Estimate:** 8-10 hours through subagent-driven-development (3 parallel subagents per Stream).

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-A-pure-modules.md` — generates next.

---

### Stream B — Shell content parsing (Session 2)

**Scope:** Bash + PowerShell tokenization, content rules, whitelist/blacklist matching.

**Files to create/modify:**
- `tools/shell-content-rules.mjs` — shared logic
- `tools/shell-content-rules.test.mjs`
- `tools/bash-tokenizer.mjs` — already exists в v3.7, расширить под v4.0+v4.1 patterns
- `tools/bash-tokenizer.test.mjs`
- `tools/enforce-router-gate.mjs` — Bash content section (§5.1) + v4.1 additions (C16, #4, #21, #22, #34)
- `tools/enforce-powershell-gate.mjs` — PowerShell content (§5.1.2) + v4.1 additions (G10)

**v4.1 additions:**
- C16 stderr redirects (`2>`, `&>`, `|&`)
- #4 node -e fs.X heuristic
- #21 env modifiers (`env -i`)
- #22 watch flag
- #34 echo user-prompt-injection
- G5 git --no-verify
- G6 -c gpgsign=false
- G7 plain wget
- G8 nc/socat
- G10 PowerShell $env: direct set

**Dependencies:** Stream A `tools/path-normalization.mjs` (для path-deny overlay). Можно запустить сразу — заглушку path-normalization сделать temporarily.

**Estimate:** 5-7 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-B-shell-content.md`.

---

### Stream C — Static content scan + MCP path-deny (Session 3)

**Scope:** Multi-language static scan (PHP/Ruby/Go/Java/Rust/.NET) + framework-boot scan + Glob F8 + MCP path-deny overlay.

**Files to create:**
- `tools/static-content-scanner.mjs` — multi-language patterns
- `tools/static-content-scanner.test.mjs`
- `tools/framework-boot-scanner.mjs` — F7 v4.0 closure
- `tools/framework-boot-scanner.test.mjs`
- `tools/glob-restricted-filter.mjs` — F8 post-execution Glob filter
- `tools/glob-restricted-filter.test.mjs`
- `tools/mcp-tool-classifier.mjs` — §5.3 classification + path_args + query_full_statement_scan
- `tools/mcp-tool-classifier.test.mjs`
- `tools/commit-message-scanner.mjs` — G11 v4.1 commit message content scan
- `tools/commit-message-scanner.test.mjs`

**v4.1 additions:**
- G1 WebSearch / WebFetch classification + URL whitelist + content scan
- G11 commit message scan
- G12 MCP database-query full-statement (vs prefix only)

**Dependencies:** Stream A `tools/path-normalization.mjs`. Same workaround как B.

**Estimate:** 5-7 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-C-static-mcp.md`.

---

### Stream D — LLM-judge Layer 4 (Session 4)

**Scope:** Multi-judge consensus (Sonnet+Haiku+Opus) + per-tool LLM-judge + response text LLM-judge + normative-content gate.

**Files to create:**
- `tools/llm-judge.mjs` — основной helper, multi-judge consensus
- `tools/llm-judge.test.mjs`
- `tools/llm-judge-per-tool.mjs` — per-tool judge (v4.1 new)
- `tools/llm-judge-per-tool.test.mjs`
- `tools/llm-judge-response-scan.mjs` — response text scan (v4.1 new)
- `tools/llm-judge-response-scan.test.mjs`
- `tools/enforce-normative-content-rules.mjs` — §3.6.2 + v4.1 multi-judge restored
- `tools/enforce-normative-content-rules.test.mjs`

**External dependency:**
- ProxyAPI key (через env var ROUTER_LLM_KEY — v4.0 simpler vs v3.8 keytar).
- Anthropic API endpoints for Sonnet 4.6, Haiku 4.5, Opus 4.7.

**Dependencies:** Nothing внутри code. External: ProxyAPI ключ должен быть валиден.

**Estimate:** 6-8 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-D-llm-judge.md`.

---

### Stream E — AskUser + subagent integration (Session 5)

**Scope:** AskUser answer parser, cosmetic detector, subagent inheritance, subagent return scanner с narrative validation.

**Files to create/modify:**
- `tools/askuser-answer-parser.mjs` — §4.5 + S27 stop-keywords + E33 invisible Unicode + E34 whitespace
- `tools/askuser-answer-parser.test.mjs`
- `tools/askuser-cosmetic-detector.mjs` — v4.1 cosmetic hard-block
- `tools/askuser-cosmetic-detector.test.mjs`
- `tools/enforce-subagent-return-scanner.mjs` — §3.4 + G2 v4.1 narrative validation
- `tools/enforce-subagent-return-scanner.test.mjs`
- `tools/subagent-output-schema.json` — schema enforcement
- `tools/subagent-prompt-prefix.mjs` — extension (Pravila §15.1)

**Dependencies:** Stream D `tools/llm-judge.mjs` для recovery-pattern detection. Можно подменить заглушкой.

**Estimate:** 4-6 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-E-askuser-subagent.md`.

---

### Stream F — VM-sandbox setup (Session 6, USER-DRIVEN)

**Scope:** VirtualBox install + VM creation + Windows install inside + dev tools + shared folders + Claude CLI migration + snapshot.

**Это НЕ code stream.** Это hands-on infrastructure setup на хосте.

**Tasks:**
1. Install VirtualBox 7+ (download from oracle.com).
2. Download Windows Server 2022 Evaluation ISO.
3. Create VM `claude-sandbox` (8-16GB RAM, 100GB disk, NAT network, 4-6 CPU).
4. Install Windows внутри VM.
5. Install Node.js, Git, VS Code, Claude Code CLI, PHP+Composer, Pest, PostgreSQL client.
6. Configure VirtualBox Shared Folder: host `C:\моя\проекты\портал crm\Документация` → VM `C:\project` (read-write).
7. Migrate `C:\Users\Administrator\.claude\` → VM `C:\Users\Administrator\.claude\`.
8. Test Claude CLI работает внутри VM.
9. Take VirtualBox Snapshot: `clean-state-2026-05-29`.

**Dependencies:** None — параллельно с code work. Можно запустить **сегодня вечером** пока остальные сессии работают.

**Estimate:** 10-12 hours (user time, не subagent).

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-F-vm-sandbox.md` — содержит пошаговую инструкцию + screenshots/команды.

---

### CHECKPOINT 1 — Review всех parallel streams

**После завершения Sessions 1-5 (A, B, C, D, E) + Session 6 (F можно параллельно):**

**Master session проверяет:**

1. Все ветки `feat/v4-stream-X` запушены на origin.
2. Все тесты GREEN: `npx vitest run tools/ --exclude='**/worktrees/**'`.
3. Cross-stream interfaces работают (например, `decide()` корректно зовёт `safeBaselineMetering()`).
4. Code review: `/code-review high` или ultra на каждую ветку.

**Если всё GREEN — merge streams в main:**
```bash
git checkout main
git merge feat/v4-stream-A --no-ff
git merge feat/v4-stream-B --no-ff
git merge feat/v4-stream-C --no-ff
git merge feat/v4-stream-D --no-ff
git merge feat/v4-stream-E --no-ff
git push origin main
```

**Если есть конфликты или fail tests — backlog в новую parallel session для починки.**

**Estimate:** 1-2 часа master review.

---

### Stream G — Cleanup + settings.json registration (Session 7, SEQUENTIAL)

**Scope:** Удалить старые v3.9 hooks, vocab.json, зарегистрировать новые v4 hooks в `.claude/settings.json`.

**Files to delete:**
- `tools/enforce-chain-recommendation.mjs` + test
- `tools/enforce-classifier-match.mjs` + test
- `tools/enforce-graph-first.mjs` + test
- `tools/enforce-semgrep-security.mjs` + test
- `tools/enforce-override-limit.mjs` + test
- `tools/enforce-override-vocab.json`

**Files to modify:**
- `tools/enforce-hook-helpers.mjs` — `findOverride`/`findOverrideAttempt`/`loadOverrideVocab` → permanent stubs (return null/null/empty).
- `.claude/settings.json` — снять registrations 5 удалённых хуков, добавить новые v4 hooks:
  - `enforce-router-gate.mjs` (PreToolUse universal)
  - `enforce-powershell-gate.mjs` (PreToolUse PowerShell)
  - `enforce-normative-content-rules.mjs` (PreToolUse Edit/Write на normative paths)
  - `enforce-subagent-return-scanner.mjs` (PostToolUse Task)
  - `enforce-tdd-real-test-verifier.mjs` (extension к existing TDD gate)
  - `enforce-self-debrief-detector.mjs` (PreToolUse mutating)
  - `enforce-todowrite-skill-verifier.mjs` (Stop hook)
  - `enforce-askuser-cosmetic-detector.mjs` (PreToolUse AskUserQuestion)
  - `enforce-llm-judge-per-tool.mjs` (PreToolUse mutating)
  - `enforce-llm-judge-response-scan.mjs` (Stop hook)
  - `enforce-parallel-session-lock.mjs` (SessionStart hook, §6.4 v4.0)
  - `enforce-mcp-classification.mjs` (PreToolUse MCP tools)

**Dependencies:** ВСЕ streams A-E завершены и merged в main.

**Estimate:** 2-3 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-G-cleanup-register.md`.

---

### CHECKPOINT 2 — User-run smoke tests

**После Stream G merge:**

**User-run smokes (требуют отдельной чистой Claude session):**

- **Smoke 1** — env propagation в субагент.
- **Smoke 2** — PostToolUse fires на failing skill.
- **Smoke 3** — subagent block-file write.
- **Smoke 4** — tool_use_id entropy (defense-in-depth).
- **Smoke 5** — transcript JSONL hard-deny.
- **Smoke 7** — subagent gate-process startup.
- **Smoke 8** — Workflow agent() inheritance (v4.0 C20 — БЛОКИРУЕТ Workflow до PASS).
- **Smoke 9** — PostToolUse Task scanner modify capability (v4.1 F9).

**Каждый smoke документирован в спеке §3.2.0.** User читает спек, выполняет каждый smoke в чистой сессии, фиксирует PASS/FAIL.

**Если все PASS** → Stream H можно стартовать.

**Если хоть один FAIL** → degraded mode fallback (см. спек §3.2.0).

**Estimate:** 2-3 часа user time.

---

### Stream H — Brain-retro adaptation + Documentation (Session 9, SEQUENTIAL)

**Scope:** Update brain-retro analyzer + написать recovery-procedures.md + sync CLAUDE.md/Pravila/PSR/Tooling.

**Files to modify:**
- `tools/brain-retro-analyzer.mjs` — Table 16-new (15 controller bypass categories) + Table 17-new (LLM-judge per-tool stats).
- `.claude/skills/brain-retro/SKILL.md` — mandatory tables 11→13 (added Table 16, 17).

**Files to create:**
- `docs/recovery-procedures.md` — plain-Russian cheatsheet (§6.1).

**Files to sync:**
- `CLAUDE.md` — version bump v2.40→v2.41, mention v4 deployment.
- `docs/Pravila_raboty_Claude_v1_1.md` — bump v1.43→v1.44, §17 universal skill-coverage updated.
- `docs/Plugin_stack_rules_v1.md` — bump v3.23→v3.24.
- `docs/Tooling_v8_3.md` Прил. Н — bump v2.24→v2.25.

**Dependencies:** Streams A-G merged + Smokes PASS.

**Estimate:** 2-3 hours.

**Sub-plan:** `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-H-docs.md`.

---

## §3. File scope summary (no overlap between streams)

| Файл | Stream | Тип |
|---|---|---|
| `tools/router-gate-decide.mjs` | A | Create |
| `tools/safe-baseline-metering.mjs` | A | Create |
| `tools/skill-scope-verifier.mjs` | A | Create |
| `tools/decomposition-detector.mjs` | A | Create |
| `tools/todowrite-skill-verifier.mjs` | A | Create |
| `tools/self-debrief-detector.mjs` | A | Create (NEW v4.1) |
| `tools/tdd-real-test-verifier.mjs` | A | Create |
| `tools/path-normalization.mjs` | A | Create (simplified §3.1.1) |
| `tools/shell-content-rules.mjs` | B | Create |
| `tools/bash-tokenizer.mjs` | B | Modify (extend) |
| `tools/enforce-router-gate.mjs` | B | Create main + integrate A |
| `tools/enforce-powershell-gate.mjs` | B | Create |
| `tools/static-content-scanner.mjs` | C | Create |
| `tools/framework-boot-scanner.mjs` | C | Create |
| `tools/glob-restricted-filter.mjs` | C | Create |
| `tools/mcp-tool-classifier.mjs` | C | Create |
| `tools/commit-message-scanner.mjs` | C | Create |
| `tools/llm-judge.mjs` | D | Create |
| `tools/llm-judge-per-tool.mjs` | D | Create (NEW v4.1) |
| `tools/llm-judge-response-scan.mjs` | D | Create (NEW v4.1) |
| `tools/enforce-normative-content-rules.mjs` | D | Create |
| `tools/askuser-answer-parser.mjs` | E | Create |
| `tools/askuser-cosmetic-detector.mjs` | E | Create (NEW v4.1) |
| `tools/enforce-subagent-return-scanner.mjs` | E | Create |
| `tools/subagent-output-schema.json` | E | Create |
| `tools/subagent-prompt-prefix.mjs` | E | Modify |
| `tools/enforce-chain-recommendation.mjs` | G | **DELETE** |
| `tools/enforce-classifier-match.mjs` | G | **DELETE** |
| `tools/enforce-graph-first.mjs` | G | **DELETE** |
| `tools/enforce-semgrep-security.mjs` | G | **DELETE** |
| `tools/enforce-override-limit.mjs` | G | **DELETE** |
| `tools/enforce-override-vocab.json` | G | **DELETE** |
| `tools/enforce-hook-helpers.mjs` | G | Modify (stub helpers) |
| `.claude/settings.json` | G | Modify (registrations) |
| `tools/brain-retro-analyzer.mjs` | H | Modify (Table 16, 17) |
| `.claude/skills/brain-retro/SKILL.md` | H | Modify (mandatory tables count) |
| `docs/recovery-procedures.md` | H | Create |
| `CLAUDE.md` | H | Modify (version bump + entry) |
| `docs/Pravila_*.md` | H | Modify |
| `docs/Plugin_stack_rules_*.md` | H | Modify |
| `docs/Tooling_*.md` | H | Modify |

**0 conflicts между streams.** Streams работают над disjoint set файлов.

---

## §4. Coordination touchpoints

### Cross-stream interface contracts

Streams используют друг друга через **обещанные интерфейсы**. Каждый stream **стабит** зависимости пока другие streams не готовы.

**Example — Stream A `decide()` использует Stream B `bashContentClassify()`:**

В Stream A code:
```js
// stream A — temporary stub:
import { bashContentClassify } from './shell-content-rules.mjs';
// если файла ещё нет — заглушка:
const bashContentClassify = (cmd) => ({result: 'allow', reason: 'stub'});
```

Когда Stream B мержится в main — stub удаляется в Stream A:
```js
import { bashContentClassify } from './shell-content-rules.mjs';
```

**Master session ведёт interface contract checklist:**

| Interface | Provider stream | Consumer streams | Status |
|---|---|---|---|
| `pathNormalize(target)` | A | B, C, D, E | TBD |
| `bashContentClassify(cmd)` | B | A | TBD |
| `staticScanFile(path, lang)` | C | A | TBD |
| `llmJudgeCall(opts)` | D | A, C, E | TBD |
| `askUserAnswerParse(toolResult)` | E | A | TBD |

---

## §5. Risk mitigation

### Stream parallelism risks

| Risk | Mitigation |
|---|---|
| Один stream сильно отстаёт | Master session мониторит through `docs/sessions/CURRENT.md`; если >2 days behind — reassign tasks |
| Interface contract changes | Master session approves любые non-trivial interface changes; all streams notified |
| Merge conflicts | Disjoint file scope обеспечивает 0 conflicts; если возникает — bug в scope assignment, master fixes |
| External dependency (ProxyAPI) fail | Stream D работает с mock LLM responses; integration verified в Checkpoint 1 |
| User stress параллельных сессий | Limit max 3 concurrent sessions (Pravila §15.1 + spec §3.4 max_parallel_subagents=3) |

### Sequential phase risks

| Risk | Mitigation |
|---|---|
| Stream G ломает critical hook | Feature-branch + push до finalize, rollback план в спеке §10.5 |
| Smoke test FAIL | Degraded mode fallback (§3.2.0); если FAIL persists — отдельный fix-stream перед Stream H |
| Documentation drift | Stream H последний, синкает по факту реализации |

### General

- **Backup branch** перед Stream G: `git branch backup-pre-v4-cleanup main`.
- **Snapshot VM** (если Stream F готов) перед Stream G: VirtualBox snapshot.
- **Test full lefthook** в Checkpoint 1 и 2: `lefthook run pre-push`.

---

## §6. Acceptance criteria (для финального merge)

После всех streams + smokes:

- **~250+ unit tests GREEN** (vitest tools-only).
- **All 8 user-run smokes PASS** (или degraded mode acknowledged для FAIL).
- **Lefthook full GREEN** (gitleaks + markdownlint + cspell + adr-judge + lychee).
- **No file overlap conflicts**.
- **`.claude/settings.json` корректно reg'нут** все v4 hooks, удалены v3.9 5 hooks.
- **`docs/recovery-procedures.md` написан** plain-Russian.
- **CLAUDE.md / Pravila / PSR / Tooling sync'нуты** до новой версии.
- **Brain-retro Table 16-new работает** — surface 15 controller bypass categories.

---

## §7. Per-stream sub-plan creation

Каждый Stream нуждается в детальном sub-plan'е (через writing-plans skill в отдельной сессии). Sub-plan содержит:

- Header (Stream name, goal, files, dependencies).
- File-by-file task breakdown (TDD micro-steps: failing test → minimal code → green → commit).
- Each task: exact file paths, exact code, exact commands, expected outputs.
- ~50-100 tasks per Stream (5-7h work).
- Self-review check.

**Команды для генерации sub-plan'а:**

В каждой parallel session:
```bash
cd ../v4-stream-X  # worktree
# Запустить Claude CLI
# В Claude:
/superpowers:writing-plans
# Skill prompts: «Read master plan + spec, generate sub-plan for Stream X»
```

---

## §8. Implementation order (для master session)

- [ ] **Step 0: User создаёт worktrees для 5 parallel streams**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git worktree add ../v4-stream-A feat/v4-stream-A
git worktree add ../v4-stream-B feat/v4-stream-B
git worktree add ../v4-stream-C feat/v4-stream-C
git worktree add ../v4-stream-D feat/v4-stream-D
git worktree add ../v4-stream-E feat/v4-stream-E
```

**Stream F (VM)** — без worktree, hands-on setup.

- [ ] **Step 1: Запустить parallel sessions 1-5**

В каждом из 5 worktree:
1. Открыть VS Code в worktree.
2. Запустить Claude CLI.
3. В Claude:
   ```
   /superpowers:writing-plans

   Read master plan: docs/superpowers/plans/2026-05-29-router-gate-v4-master.md
   Generate sub-plan for Stream [A|B|C|D|E].
   Save to docs/superpowers/plans/2026-05-29-router-gate-v4-stream-[X]-<name>.md.
   ```
4. После approval sub-plan'а: `/superpowers:subagent-driven-development` для реализации.

- [ ] **Step 2: Параллельно — Stream F (VM setup)**

User-driven hands-on по `docs/superpowers/plans/2026-05-29-router-gate-v4-stream-F-vm-sandbox.md` (когда будет написан).

- [ ] **Step 3: Master session мониторит progress**

- Раз в 1-2 часа: проверить `docs/sessions/CURRENT.md`.
- Если stream завис >2 часа без commits — открыть session, проверить blocker.
- Если interface contract conflict — master решает.

- [ ] **Step 4: Checkpoint 1 — merge streams A-E**

После всех 5 streams готовы:
```bash
git checkout main
git pull origin main

# Merge каждый stream
git merge feat/v4-stream-A --no-ff -m "feat(router-gate): v4 stream A — pure modules"
git merge feat/v4-stream-B --no-ff -m "feat(router-gate): v4 stream B — shell content"
git merge feat/v4-stream-C --no-ff -m "feat(router-gate): v4 stream C — static + MCP"
git merge feat/v4-stream-D --no-ff -m "feat(router-gate): v4 stream D — LLM-judge Layer 4"
git merge feat/v4-stream-E --no-ff -m "feat(router-gate): v4 stream E — AskUser + subagent"

# Регрессия
npx vitest run tools/ --exclude='**/worktrees/**'
# Expected: ~250+ tests GREEN

git push origin main
```

- [ ] **Step 5: Stream G — cleanup + register**

В новой Claude session (можно в main worktree):
```
/superpowers:writing-plans
Generate sub-plan for Stream G (cleanup + register).
```
Затем `/superpowers:subagent-driven-development`.

- [ ] **Step 6: User-run Smokes 1-9**

Открыть **чистую** Claude session (без активных хуков ещё лучше). Выполнить каждый smoke по спеку §3.2.0. Фиксировать PASS/FAIL в `docs/observer/smoke-results.md`.

- [ ] **Step 7: Stream H — brain-retro + docs**

В новой Claude session:
```
/superpowers:writing-plans
Generate sub-plan for Stream H (brain-retro + docs).
```

- [ ] **Step 8: Final verification**

- [ ] All tests GREEN (vitest tools-only + integration + smokes).
- [ ] Lefthook full GREEN.
- [ ] Brain-retro Table 16-new выдаёт хотя бы header (нет данных yet, OK).
- [ ] `docs/recovery-procedures.md` exists.
- [ ] CLAUDE.md / Pravila / PSR / Tooling bumped.

- [ ] **Step 9: Закрытие proj — push final commit**

```bash
git add .
git commit -m "feat(router-gate): v4.0+v4.1+v4.2 deployment complete

Aggregate bypass: ~0.5-0.8% (vs v3.9 ~25%).
Implementation: 9 streams через subagent-driven-development.
Smokes: 8/9 PASS, Smoke 9 documented residual.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
git push origin main
```

- [ ] **Step 10: Cleanup worktrees**

```powershell
git worktree remove ../v4-stream-A
git worktree remove ../v4-stream-B
git worktree remove ../v4-stream-C
git worktree remove ../v4-stream-D
git worktree remove ../v4-stream-E
```

---

## §9. Что НЕ покрыто этим master plan'ом

- **Детальные TDD-задачи** per stream — пишутся в sub-plan'ах в parallel sessions.
- **Stream F VM-setup пошаговая инструкция** — отдельный sub-plan, hands-on UI работа.
- **Workflow tool** — DEFERRED до Smoke 8 PASS (см. v4.1 §3.4 C20). После Smoke 8 — отдельная задача активации.

---

## §10. Cross-refs

- Specs: v4.0 + v4.1 + v4.2 (см. шапку).
- Predecessor: v3.9 ([design](../specs/2026-05-28-router-gate-hard-wall-design.md)).
- Brain-retro #10: [`docs/observer/notes/2026-05-28-brain-retro-10.md`](../../observer/notes/2026-05-28-brain-retro-10.md).
- Pravila §15 — параллельные сессии coordination.
- CLAUDE.md §3.6 — brain governance.

---

## Execution Handoff

**Master plan complete и saved в `docs/superpowers/plans/2026-05-29-router-gate-v4-master.md`.**

**Следующие шаги:**

1. **Вы создаёте 5 worktrees** (Step 0).
2. **Запускаете 5 параллельных Claude sessions** (Step 1). Каждая sub-session инвокирует `superpowers:writing-plans` для генерации своего sub-plan'а, затем `superpowers:subagent-driven-development` для реализации.
3. **Параллельно** — Stream F (VM setup) hands-on у вас (когда я напишу Stream F sub-plan в отдельной session).
4. **Master session (эта)** мониторит progress, делает Checkpoint 1, Stream G, координирует smokes, делает Stream H.

**Hint:** sub-plan'ы для streams F+G+H короче чем A-E (меньше pure code), их можно генерировать как готовятся.

**Total wall-clock estimate:** 16-23 часа от начала до final merge.
