# Claude Code Automation Completion Plan

> **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:** Завершить post-implementation activation, verification, и integration внедрённых 8 automations из feat/claude-automation (10 commits, branch pushed to origin), плюс sync нормативной документации и merge в main.

**Architecture:** 9 tasks разделены на 3 фазы:

- **Phase A — Immediate post-push activation** (Tasks 1–2): PR creation + Claude Code session reload.
- **Phase B — Active verification** (Tasks 3–7): hook smoke tests, MCP prereq checks, skill/subagent invocations, Sentry credentials.
- **Phase C — Closure** (Tasks 8–9): Pest/Vitest regression baseline + sync нормативки + merge + worktree cleanup.

**Tech Stack:** Bash (curl-free, sequential), PowerShell (env vars persistent), Edit/Write для file mods (sync нормативки), Agent/Skill tools для invocations, git для merge/cleanup.

**Precedent:** Spec за automations — [docs/superpowers/specs/2026-05-13-claude-automation-recommendations-design.md](../specs/2026-05-13-claude-automation-recommendations-design.md) (committed d0460f6). Sync нормативки precedent — v1.83 audit gap closure pattern (CLAUDE.md v1.86 history entry; формализация 21st.dev Magic MCP + UI UX Pro Max в Tooling §3.3 #32/#31 retrospectively).

**Pre-execution state (2026-05-13 ~07:55 UTC):**

- Branch `feat/claude-automation` HEAD `4822610` pushed to `origin/feat/claude-automation`
- Worktree active at `.claude/worktrees/claude-automation/` (locked to branch)
- Main HEAD `f454e95 docs(audit): Phase 0 pre-flight skeletons + findings (audit #2)` от concurrent session
- 10 commits ahead of merge-base `1efd25d`
- 8 automations implemented + verified per-commit; 6 sorted post-actions + 3 deferred items pending

---

## File Structure

| Файл / артефакт | Действие | Задача |
|---|---|---|
| GitHub PR | Create через web UI (gh CLI failed PAT scope) | Task 1 |
| VSCode workspace | Close/reopen для Claude Code session reload | Task 2 |
| Root [`CLAUDE.md`](../../../CLAUDE.md) (whitespace test) | Edit + revert (hook smoke) | Task 3 |
| Root [`db/schema.sql`](../../../db/schema.sql) (whitespace test) | Edit + revert (hook smoke) | Task 3 |
| Memurai service / redis-cli | Verify connection (read-only) | Task 4 |
| `/q-item-add` skill | Live invocation test | Task 5 |
| `/rls-check` skill | Live invocation test | Task 5 |
| `rls-reviewer` subagent | Live dispatch test | Task 6 |
| `pest-parallel-debugger` subagent | Live dispatch test | Task 6 |
| PowerShell user env | Set SENTRY_URL + SENTRY_AUTH_TOKEN | Task 7 |
| Sentry MCP tools | Verify enumerable post-restart | Task 7 |
| Pest + Vitest | Baseline regression на main checkout | Task 8 |
| [`docs/Tooling_v8_3.md`](../../../docs/Tooling_v8_3.md) | §3.3 +#34 sentry + #35 redis rows; Прил. Н v1.16 → v1.17 | Task 9.1 |
| [`docs/Plugin_stack_rules_v1.md`](../../../docs/Plugin_stack_rules_v1.md) | R10.1 +sentry+redis entries; v2.0 → v2.1 | Task 9.2 |
| Root [`CLAUDE.md`](../../../CLAUDE.md) (через plugin) | §3.3 +#34/#35; §0 cross-refs; шапка v1.91 → v1.92 | Task 9.3 |
| [`docs/Pravila_raboty_Claude_v1_1.md`](../../../docs/Pravila_raboty_Claude_v1_1.md) | §13.2 counter bump infrastructure subsection; v1.12 → v1.13 | Task 9.4 |
| Memory `MEMORY.md` + `reference_archive.md` | Version refs sync v1.91→v1.92 / v1.12→v1.13 etc. | Task 9.5 |
| git | Merge feat → main + worktree remove | Task 9.6 |

---

## Pre-execution baseline (capture before Task 1)

Run from worktree cwd (`.claude/worktrees/claude-automation/`):

```bash
git log --oneline -12
git status --short
git remote -v
```

Expected: HEAD `4822610`, working tree clean, origin = `https://github.com/CoralMinister/lidpotok.git`.

```bash
"C:/моя/проекты/портал crm/Документация/bin/gitleaks.exe" detect --source . --no-banner --config "C:/моя/проекты/портал crm/Документация/.gitleaks.toml" --redact 2>&1 | tail -3
```

Expected baseline: `388 commits scanned ~11.97 MB / no leaks found`.

Capture in transcript для compare в Tasks 7+9.

---

## Task 1: Create PR через web UI

**Files (artefacts):**

- Create: GitHub PR на repository `CoralMinister/lidpotok`, base `main`, head `feat/claude-automation`.

**Why это первое:** unlocks merge path. Все остальные verification tasks могут проходить параллельно с PR review, но без PR работа не консолидируется в main.

- [ ] **Step 1.1: Open PR URL в браузере**

```text
https://github.com/CoralMinister/lidpotok/pull/new/feat/claude-automation
```

- [ ] **Step 1.2: Fill title**

```text
feat: Claude Code automation recommendations — 8 automations
```

- [ ] **Step 1.3: Fill body (paste from previous transcript or this draft)**

````markdown
## Summary

10 commits adding 8 automations to project Claude Code configuration:

- 2 MCP servers in `.mcp.json`: `sentry` (`@sentry/mcp-server@0.33.0+`), `redis` (`@modelcontextprotocol/server-redis@2025.4.25` — deprecated, migration plan in entry comment)
- 2 project-local skills in `.claude/skills/`: `/q-item-add`, `/rls-check`
- 2 hooks in `.claude/settings.json`: PreToolUse warning on direct CLAUDE.md edits (Option A — warning-only), PostToolUse reminder on `db/schema.sql` edits
- 2 subagents in `.claude/agents/`: `rls-reviewer` (5-role RLS), `pest-parallel-debugger` (verified quirks 72-73)

Plus spec + plan in `docs/superpowers/{specs,plans}/`.

**Out of scope per customer decision:**

- Sync нормативки (PSR_v1 R10.1 + Tooling §3.3 #34/#35 + CLAUDE.md §3.3 + Pravila §13.2) — отдельным планом
- Plugin `commit-commands` install — excluded

## Verification done in worktree

- `.mcp.json` JSON valid, 6 entries; `.claude/settings.json` JSON valid, PreToolUse + 2 PostToolUse
- 4 skill/agent YAML frontmatter valid; markdownlint 0 errors
- Gitleaks full history 388 commits / 11.97 MB / 0 leaks
- Lychee 402 total / 291 OK / 2 errors (pre-existing, не от этой branch)

## Test Plan

- [ ] Reload Claude Code session — verify skills/agents auto-discover
- [ ] PreToolUse hook smoke (Edit root CLAUDE.md → revert)
- [ ] PostToolUse hook smoke (Edit db/schema.sql → revert)
- [ ] Negative case (Edit app/CLAUDE.md or README.md → no hook fire)
- [ ] Invoke /q-item-add + /rls-check после restart
- [ ] Dispatch rls-reviewer + pest-parallel-debugger после restart
- [ ] Sentry MCP — credentials inject (SENTRY_URL + SENTRY_AUTH_TOKEN)
- [ ] Redis MCP — Memurai running localhost:6379

Spec: docs/superpowers/specs/2026-05-13-claude-automation-recommendations-design.md
Plan: docs/superpowers/plans/2026-05-13-claude-automation-recommendations-plan.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)
````

- [ ] **Step 1.4: Submit PR**

Click "Create pull request" button. Capture PR number (e.g., `#42`).

- [ ] **Step 1.5: Verify PR visible**

```bash
gh pr list --repo CoralMinister/lidpotok --head feat/claude-automation 2>&1 | head -5
```

Если `gh pr list` fails — verify manually через browser что PR appears на `https://github.com/CoralMinister/lidpotok/pulls`.

- [ ] **Step 1.6: No commit (PR creation is external action)**

---

## Task 2: Reload Claude Code session

**Files (artefacts):**

- Action: close + reopen VSCode workspace (или Claude Code restart equivalent).

**Why это второе:** unlocks 4 automations (2 skills + 2 subagents) которые auto-discover требует session restart per Q6 pre-flight (conservative; не verified direct test).

**Important:** перед reload — verify worktree state НЕ потеряется. Worktree path `.claude/worktrees/claude-automation/` survives session restart (git native, не Claude-specific).

- [ ] **Step 2.1: Optional — note current session state**

```bash
git status --short
git log --oneline -3
pwd
```

Capture в memory или scratch note. После reload — return to worktree если нужно через `EnterWorktree path=.claude/worktrees/claude-automation`.

- [ ] **Step 2.2: Close VSCode workspace**

File → Close Folder (Windows: Ctrl+K, F) — или close VSCode window entirely.

- [ ] **Step 2.3: Reopen VSCode workspace**

Open Folder → `c:\моя\проекты\портал crm\Документация`.

- [ ] **Step 2.4: Verify Claude Code session restart**

В new Claude Code session — check `available skills` system reminder. Должны появиться:

- `q-item-add` (project-local)
- `rls-check` (project-local)

И `available subagents`:

- `rls-reviewer`
- `pest-parallel-debugger`

Если **НЕ** появились — auto-discovery не работает without explicit registration. Escalate как NEEDS_CONTEXT.

- [ ] **Step 2.5: Re-enter worktree (если требуется для дальнейших tasks)**

```bash
# В новой session
git worktree list  # verify .claude/worktrees/claude-automation present
```

Use `EnterWorktree` tool with `path=.claude/worktrees/claude-automation` если нужно switch session cwd обратно в worktree для Tasks 3+.

Альтернатива: работать в main checkout (root project), но HEAD там — main `f454e95`, мои changes только на feature branch. Для Tasks 3-7 — main checkout с pulled feat/claude-automation lokal branch достаточен.

- [ ] **Step 2.6: No commit**

---

## Task 3: Hook smoke tests (PreToolUse CLAUDE.md + PostToolUse db/schema.sql)

**Files:**

- Test edit: `CLAUDE.md` (root) — whitespace-only change + revert
- Test edit: `db/schema.sql` (root) — whitespace-only change + revert
- Test edit: `app/CLAUDE.md` OR `README.md` (negative case) — whitespace + revert

**Pre-requisite:** Task 2 (reload). Hooks из `.claude/settings.json` могут потребовать session reload чтобы Claude Code picked them up на feat/claude-automation. Если работаем на main checkout — нужно сначала merge или checkout feat/claude-automation там.

**Important: tests run на feat/claude-automation branch (или после merge в main).** На main HEAD `f454e95` hooks отсутствуют.

- [ ] **Step 3.1: Verify hooks installed (на feat/claude-automation)**

```bash
node -e "const s=JSON.parse(require('fs').readFileSync('.claude/settings.json','utf8')); console.log('PreToolUse:', s.hooks.PreToolUse?.length, 'PostToolUse:', s.hooks.PostToolUse?.length);"
```

Expected: `PreToolUse: 1 PostToolUse: 2`.

- [ ] **Step 3.2: Smoke positive — Edit root CLAUDE.md (whitespace)**

Через Claude Code Edit tool — добавить trailing space в любой пустой строке `CLAUDE.md`:

```text
File: CLAUDE.md
Edit: line N → line N + " " (single trailing space)
```

**Expected hook output** (stderr in transcript):

```text
[hook] WARNING: Direct edit of root CLAUDE.md detected. Per CLAUDE.md §5 п.10,
prefer /claude-md-management:revise-claude-md or /claude-md-management:claude-md-improver.
If invoked via that skill, this warning is informational.
```

- [ ] **Step 3.3: Revert CLAUDE.md change**

```bash
git checkout -- CLAUDE.md
git status --short
```

Expected: working tree clean.

- [ ] **Step 3.4: Smoke positive — Edit db/schema.sql (whitespace)**

Через Claude Code Edit tool — trailing space в пустой строке `db/schema.sql`.

**Expected hook output** (stdout in transcript):

```text
[hook] REMINDER: You modified db/schema.sql. Per CLAUDE.md §5 п.8,
add a corresponding entry to db/CHANGELOG_schema.md before committing.
```

- [ ] **Step 3.5: Revert db/schema.sql change**

```bash
git checkout -- db/schema.sql
git status --short
```

Expected: clean.

- [ ] **Step 3.6: Smoke negative — Edit `app/CLAUDE.md` OR README.md (whitespace)**

Если `app/CLAUDE.md` существует (на момент pre-flight отсутствовал, но Boost manages):

```text
File: app/CLAUDE.md OR README.md
Edit: line N → line N + " "
```

**Expected:** NO hook output (markdownlint hook может trigger на README.md, но **не** PreToolUse warning — это для CLAUDE.md root only).

- [ ] **Step 3.7: Revert negative-case change**

```bash
git checkout -- app/CLAUDE.md  # or README.md
```

- [ ] **Step 3.8: No commit (smoke tests, no permanent changes)**

```bash
git status --short
```

Expected: clean.

---

## Task 4: Redis MCP — Memurai verification

**Files:**

- Read only: Memurai service status (Windows service control).
- No commits.

**Why:** Redis MCP entry в `.mcp.json` подключается к `redis://localhost:6379`. Если Memurai not running — MCP startup fails, tools не enumerable. Verify раньше — faster debug.

- [ ] **Step 4.1: PowerShell service check**

```powershell
Get-Service Memurai 2>&1
```

**Expected output (если установлен):**

```text
Status   Name               DisplayName
------   ----               -----------
Running  Memurai            Memurai
```

Если Status = `Stopped`:

```powershell
Start-Service Memurai
```

Если service не найден — Memurai не установлен; document в результате.

- [ ] **Step 4.2: redis-cli ping (если redis-cli или Memurai-cli в PATH)**

```bash
redis-cli -h localhost -p 6379 ping 2>&1
```

OR (PowerShell):

```powershell
& "C:\Program Files\Memurai\memurai-cli.exe" -h localhost -p 6379 ping 2>&1
```

**Expected:** `PONG`

Если timeout / connection refused → Memurai service не listening. Проверить firewall + port 6379.

- [ ] **Step 4.3: Smoke Redis MCP startup (если возможно)**

После Task 2 reload + Tasks 3 smoke complete:

```bash
npx -y @modelcontextprotocol/server-redis redis://localhost:6379 --help 2>&1 | head -5
```

Expected: package downloads (deprecated warning OK) и shows help OR прерывается. Цель — verify package downloadable и executable.

Note: package deprecated — npm может show warning `npm WARN deprecated @modelcontextprotocol/server-redis: ...`. Это expected.

- [ ] **Step 4.4: No commit**

Document результат в session transcript как notes для PR review.

---

## Task 5: Live skill invocations (/q-item-add + /rls-check)

**Pre-requisite:** Task 2 reload — skills auto-discovered.

**Files:**

- Skill tool calls (no file changes).
- Optional: scratch note для skill response verification.

**Why:** Tasks 4 + 5 (skill creation) не были live-tested. Frontmatter validated, content valid markdown, но runtime invocation pending. Без live test — possible silent fail из-за format issues unknown.

- [ ] **Step 5.1: Verify /q-item-add appears в available skills**

В Claude transcript — observe `available skills` system reminder list. Look for `q-item-add`.

Если **отсутствует** — auto-discovery failed. STOP, escalate как BLOCKED. Возможные причины: SKILL.md path не stand, plugin-namespace required, restart не captured changes.

- [ ] **Step 5.2: Invoke /q-item-add (dry-run mode)**

В Claude transcript:

```text
/q-item-add
```

(без args)

**Expected:** skill responds с описанием workflow OR prompts for `<prefix>` + `<question text>`. Конкретный response зависит от Claude Code interpretation skill content.

If skill responds с "/q-item-add invalid" — frontmatter format problem.

- [ ] **Step 5.3: Verify /rls-check appears в available skills**

Look for `rls-check` в `available skills` system reminder.

- [ ] **Step 5.4: Invoke /rls-check (dry-run)**

```text
/rls-check supplier_csv_reconcile_log
```

**Expected:** skill loads SKILL.md content, walks 7-item checklist OR prompts for confirmation before running grep/squawk commands. Note: skill cannot run без access к `db/schema.sql` (which exists on feat/claude-automation после Task 2 reload).

- [ ] **Step 5.5: No commit (read-only verification)**

Document outcomes для PR Test Plan checkmark.

---

## Task 6: Live subagent invocations (rls-reviewer + pest-parallel-debugger)

**Pre-requisite:** Task 2 reload — agents auto-discovered.

**Files:**

- Agent tool dispatches (no file changes).

**Why:** Tasks 8 + 9 (subagent creation) не были live-tested. Frontmatter validated, content valid, но runtime dispatch pending.

- [ ] **Step 6.1: Verify rls-reviewer в available subagents**

```text
Try Agent tool dispatch with subagent_type='rls-reviewer'
```

Если `subagent_type` enum показывает `rls-reviewer` → discovered. Если нет → BLOCKED.

- [ ] **Step 6.2: Dispatch rls-reviewer smoke**

```text
Agent({
  description: "RLS reviewer smoke test",
  subagent_type: "rls-reviewer",
  prompt: "Review db/schema.sql line range 100-200 for RLS compliance on whatever table is defined there. This is a smoke test — just verify the agent loads and can read files."
})
```

**Expected outcome:** agent returns structured report per format в `.claude/agents/rls-reviewer.md` line 47-58 (`RLS Review — <table_name>` template). Without crash на frontmatter parse.

- [ ] **Step 6.3: Verify pest-parallel-debugger в available subagents**

- [ ] **Step 6.4: Dispatch pest-parallel-debugger smoke**

```text
Agent({
  description: "Pest debugger smoke test",
  subagent_type: "pest-parallel-debugger",
  prompt: "Smoke test — paste raw output: 'Test failed: tests/Feature/Supplier/SyncSupplierProjectsJobTest.php line 42 expected 1 got 0'. Walk through diagnostic pipeline and recommend next step."
})
```

**Expected outcome:** agent returns Pest --parallel debugger report template per `.claude/agents/pest-parallel-debugger.md` line 56-72. Should classify as `Hypothesis 2 (quirk 72 Redis supplier:session race)` (test в `tests/Feature/Supplier/*`) и recommend rerun `--parallel=0`.

- [ ] **Step 6.5: No commit**

---

## Task 7: Sentry MCP credentials inject + verification

**Pre-requisite:** Sentry self-hosted instance running в Yandex Cloud (per CLAUDE.md §2). Если Sentry not yet deployed (зависит от Б-1 ООО registration P0) — Task 7 **BLOCKED** до deployment.

**Files:**

- PowerShell user environment (persistent).
- No commits.

**Why:** Sentry MCP entry в `.mcp.json` использует `${SENTRY_URL}` + `${SENTRY_AUTH_TOKEN}` env vars. Без credentials — MCP fails gracefully на startup, `mcp__sentry__*` tools не enumerable. С credentials Claude может прямо запрашивать Sentry issues во время debug сессии.

- [ ] **Step 7.1: Verify Sentry instance reachable**

```powershell
Invoke-RestMethod -Uri "https://sentry.<your-domain>.ru/api/0/" -Method Head -ErrorAction Stop 2>&1 | Select-Object StatusCode
```

(replace `<your-domain>` с actual hostname)

**Expected:** HTTP 200 OR 401 (auth required, что норм без token).

Если connection refused / DNS error → Sentry not deployed; Task 7 BLOCKED.

- [ ] **Step 7.2: Generate Sentry auth token**

В Sentry web UI (`https://sentry.<your-domain>.ru/settings/account/api/auth-tokens/`):

1. Create new auth token
2. Scope: `org:read`, `project:read`, `event:read` (read-only)
3. Copy token value (one-time visible).

- [ ] **Step 7.3: Set persistent env vars (PowerShell, User scope)**

```powershell
[Environment]::SetEnvironmentVariable("SENTRY_URL", "https://sentry.<your-domain>.ru", "User")
[Environment]::SetEnvironmentVariable("SENTRY_AUTH_TOKEN", "<token-from-step-7.2>", "User")
```

**Verify:**

```powershell
[Environment]::GetEnvironmentVariable("SENTRY_URL", "User")
[Environment]::GetEnvironmentVariable("SENTRY_AUTH_TOKEN", "User") | Measure-Object -Character | Select-Object Characters
```

Expected: URL printed, token characters count > 30.

**Important:** token НЕ должен попадать в git. `.env.local` или PowerShell User scope — safe.

- [ ] **Step 7.4: Reload Claude Code session (повторный reload — env vars подхватываются на startup)**

Close + reopen VSCode workspace (как Task 2).

- [ ] **Step 7.5: Verify Sentry MCP tools enumerable**

```text
ToolSearch("select:mcp__sentry__*", max_results=10)
```

Or look at available MCP tools в system reminder. Expected:

```text
mcp__sentry__get_issue
mcp__sentry__list_events
mcp__sentry__search_errors
mcp__sentry__... (other tools per @sentry/mcp-server@0.33.0 spec)
```

Если tools НЕ enumerable — MCP startup failed; capture stderr через `claude mcp logs sentry` (если поддерживается).

- [ ] **Step 7.6: Smoke MCP call**

```text
mcp__sentry__get_issue({ issue_id: "1" })
```

Или другой read-only tool. Expected: HTTP 200 with issue data OR 404 если issue id не существует. Goal: verify auth + connectivity works.

- [ ] **Step 7.7: No commit (env vars не commit'ятся; .env.local gitignored)**

---

## Task 8: Pest/Vitest regression baseline на main checkout

**Pre-requisite:** main checkout доступен в `c:\моя\проекты\портал crm\Документация` (root, не worktree).

**Files:**

- Read only: tests run, output capture.
- No commits.

**Why:** Config-only changes на feat/claude-automation теоретически не должны влиять на Pest/Vitest. Sanity check — verify baseline preserved (memory project_state.md 13.05.2026 day +1: Pest 742/739/0/3, Vitest 88/683+3). После merge feat→main — повторный run для confirmation.

- [ ] **Step 8.1: Switch session cwd to main checkout**

ExitWorktree (если в worktree) OR cd main:

```bash
# Через native tool
ExitWorktree action="keep"  # keep worktree alive для Task 9
```

Or manually:

```bash
cd "/c/моя/проекты/портал crm/Документация"
git branch --show-current
```

Expected current branch: `main` HEAD = `f454e95` (concurrent session work).

- [ ] **Step 8.2: Pest --parallel baseline**

```bash
cd app
./vendor/bin/pest --parallel --recreate-databases 2>&1 | tail -10
```

**Expected** (per memory baseline):

```text
{"tool":"pest","result":"passed","tests":742,"passed":739,"assertions":2243,"duration_ms":~55000,"skipped":3}
```

If failures > 0 → investigate per quirks 72/73 (use `pest-parallel-debugger` subagent если activated). NB: concurrent session's audit-2 commits (`f454e95`) на main shouldn't affect Pest — но verify.

- [ ] **Step 8.3: Vitest baseline**

```bash
cd app
npm run test:vue 2>&1 | tail -10
```

**Expected:**

```text
Test Files  88 passed (88)
Tests  683 passed | 3 skipped (686)
```

If failures → investigate.

- [ ] **Step 8.4: Document baseline in session transcript**

Capture numbers для compare после merge.

- [ ] **Step 8.5: Re-enter worktree (если планируется Task 9 в worktree)**

```bash
EnterWorktree path=".claude/worktrees/claude-automation"
```

OR if Task 9 sync нормативки делается на main — оставить cwd на main.

**Decision point:** Task 9 sync нормативки делается на **main** или **feat/claude-automation**?

Recommendation: **separate branch `feat/claude-automation-norm-sync`** off main **after** merge feat/claude-automation. Это аtomic logical change separate от automation impl. Plan ниже assumes this approach.

- [ ] **Step 8.6: No commit**

---

## Task 9: Sync нормативки + merge feat → main + worktree cleanup

**Pre-requisite:** PR (Task 1) reviewed и approved (manual user action). Tasks 3-8 verifications done.

**Files:**

- Read+Modify: `docs/Tooling_v8_3.md` (§3.3 #34/#35 rows + Прил. Н version bump)
- Read+Modify: `docs/Plugin_stack_rules_v1.md` (R10.1 sentry+redis entries + version bump)
- Read+Modify (через plugin): `CLAUDE.md` (§3.3 + cross-refs + version bump v1.91 → v1.92)
- Read+Modify: `docs/Pravila_raboty_Claude_v1_1.md` (§13.2 counter bump infrastructure subsection + version bump v1.12 → v1.13)
- Read+Modify: Memory `MEMORY.md`, `reference_archive.md` (version refs sync)
- Git: merge feat/claude-automation → main; remove worktree

**Architecture decision (3 sub-paths):**

- **Option A — Merge first, sync нормативки after on separate branch.** Recommended. Clean PR audit trail, sync — отдельный PR.
- **Option B — Sync нормативки на feat/claude-automation перед merge.** Adds 5 commits, larger PR, mixing concerns.
- **Option C — Sync нормативки на main directly (no PR).** Simpler но bypass review.

Plan ниже uses **Option A**.

### Task 9.1: Merge feat/claude-automation → main

- [ ] **Step 9.1.1: Switch to main**

```bash
cd "/c/моя/проекты/портал crm/Документация"
git checkout main
git pull origin main  # capture любые concurrent changes
```

Capture HEAD на main pre-merge.

- [ ] **Step 9.1.2: Fast-forward или merge?**

```bash
git log --oneline main..feat/claude-automation
git log --oneline feat/claude-automation..main
```

Если `main..feat/claude-automation` показывает 10 commits AND `feat/claude-automation..main` показывает 0 commits → fast-forward possible.
Если оба нон-empty → merge commit needed (concurrent main work).

- [ ] **Step 9.1.3: Merge**

```bash
git merge feat/claude-automation --no-ff -m "$(cat <<'EOF'
Merge feat/claude-automation: Claude Code automation recommendations

10 commits adding 8 automations (2 MCP + 2 skills + 2 hooks + 2 subagents)
+ spec/plan documentation.

PR: #<NN> (replace with actual PR number from Task 1.4)

Sync нормативки (PSR_v1 R10.1 + Tooling §3.3 #34/#35 + CLAUDE.md §3.3 +
Pravila §13.2) — отдельным планом feat/claude-automation-norm-sync.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)"
```

- [ ] **Step 9.1.4: Verify merge result**

```bash
git log --oneline -15
git status --short
```

Expected: all 10 commits present + merge commit. Working tree clean.

- [ ] **Step 9.1.5: Run Pest/Vitest post-merge для regression check**

```bash
cd app
./vendor/bin/pest --parallel --recreate-databases 2>&1 | tail -3
npm run test:vue 2>&1 | tail -5
cd ..
```

Expected: same baseline as Task 8 (742/739/0/3 + 88/683+3).

- [ ] **Step 9.1.6: Push merged main**

```bash
git push origin main
```

Expected: `* feat/claude-automation -> main` (fast-forward) OR `<sha1>..<sha2> main -> main`.

- [ ] **Step 9.1.7: Cleanup worktree**

```bash
git worktree list  # verify .claude/worktrees/claude-automation listed
ExitWorktree action="remove"
# Or manual:
# git worktree remove ".claude/worktrees/claude-automation"
# git worktree prune
```

Verify:

```bash
git worktree list
ls .claude/worktrees/ 2>&1
```

Expected: claude-automation worktree absent.

- [ ] **Step 9.1.8: Delete merged feature branch**

```bash
git branch -d feat/claude-automation
git push origin --delete feat/claude-automation
```

Expected: branch deleted local + remote.

### Task 9.2: Create sync нормативки branch

- [ ] **Step 9.2.1: New branch**

```bash
git checkout -b feat/claude-automation-norm-sync
```

### Task 9.3: Sync `docs/Tooling_v8_3.md` (§3.3 + #34 sentry + #35 redis)

- [ ] **Step 9.3.1: Read current Tooling §3.3**

```bash
grep -n "^### 3.3" docs/Tooling_v8_3.md
```

Capture line range section 3.3.

- [ ] **Step 9.3.2: Edit §3.3 — add #34 sentry row**

В table в §3.3 (после #33 claude-md-management):

```markdown
| 34 | Off-phase MCP — отладка production runtime errors через self-hosted Sentry в Yandex Cloud | **Sentry MCP** (`@sentry/mcp-server`, server `sentry` в `.mcp.json`, tools `mcp__sentry__*`) | автоматически через `.mcp.json`. Env vars `SENTRY_URL` + `SENTRY_AUTH_TOKEN` через shell. Установлен 13.05.2026 (CLAUDE.md v1.91 implementation; формализован retrospectively v1.92). Pending: Sentry instance deployment (зависит от Б-1 ООО registration). |
```

- [ ] **Step 9.3.3: Edit §3.3 — add #35 redis row**

```markdown
| 35 | Off-phase MCP — отладка Redis/Memurai очередей, кэша, Pest --parallel races | **Redis MCP** (`@modelcontextprotocol/server-redis@2025.4.25` — DEPRECATED Anthropic source; migration plan на `@easy-mcps/redis-mcp-server@1.0.8` post-MVP, server `redis` в `.mcp.json`, tools `mcp__redis__*`) | автоматически через `.mcp.json`. URL `redis://localhost:6379` (Memurai Windows service). READ-ONLY для debug. Установлен 13.05.2026. |
```

- [ ] **Step 9.3.4: Edit §3.4 footer — bump count**

Найти текст «**Total формализованных позиций: 33**» — bump на 35.

Найти текст «29 phase-active + 3 off-phase + 1 historic» — bump на «29 + 5 off-phase + 1 historic» (3 → 5: +sentry +redis).

- [ ] **Step 9.3.5: Edit Прил. Н version bump**

Поiskать секцию "Прил. Н v1.16" — bump до v1.17 от 13.05.2026 day +1 с changelog entry.

- [ ] **Step 9.3.6: Verify lychee on Tooling**

```bash
"C:/моя/проекты/портал crm/Документация/bin/lychee.exe" --config .lychee.toml docs/Tooling_v8_3.md 2>&1 | tail -5
```

Expected: 0 broken links.

- [ ] **Step 9.3.7: Commit**

```bash
git add docs/Tooling_v8_3.md
git commit -m "$(cat <<'EOF'
docs(tooling): §3.3 +#34 sentry-mcp + #35 redis-mcp formalization

Total формализованных позиций 33 → 35.
Off-phase tools: 3 → 5 (sentry + redis added).

Прил. Н v1.16 → v1.17.

Закрывает gap c v1.83 audit precedent: «5 инструментов активно
без формализации». После 13.05.2026 implementation (CLAUDE.md v1.91)
sentry+redis MCP были active 1 day без registry sync.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)"
```

### Task 9.4: Sync `docs/Plugin_stack_rules_v1.md` (R10.1 sentry+redis)

- [ ] **Step 9.4.1: Read current PSR_v1 R10.1**

```bash
grep -n "^### R10.1\|^## R10\b" docs/Plugin_stack_rules_v1.md
```

- [ ] **Step 9.4.2: Edit R10.1 reestr — add sentry + redis rows**

В таблице R10.1 (плагины — реестр) добавить:

```markdown
| `@sentry/mcp-server` | Off-phase MCP | Tooling #34. Установлен 13.05.2026. Pending Sentry instance deployment (Б-1). | — |
| `@modelcontextprotocol/server-redis` | Off-phase MCP | Tooling #35. Установлен 13.05.2026. Deprecated package (Anthropic source). | — |
```

- [ ] **Step 9.4.3: Edit PSR_v1 version bump**

Шапка v2.0 → v2.1 от 13.05.2026 day +1 с changelog entry.

- [ ] **Step 9.4.4: Commit**

```bash
git add docs/Plugin_stack_rules_v1.md
git commit -m "$(cat <<'EOF'
docs(psr): R10.1 +sentry-mcp + redis-mcp реестр entries

PSR_v1 v2.0 → v2.1. R10.1 расширен 2 off-phase MCP записями.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)"
```

### Task 9.5: Sync `CLAUDE.md` через `/claude-md-management:claude-md-improver`

**Important:** CLAUDE.md правится **только** через plugin (§5 п.10). Не Edit/Write напрямую.

- [ ] **Step 9.5.1: Invoke `/claude-md-management:claude-md-improver`**

В Claude transcript:

```text
/claude-md-management:claude-md-improver
```

Skill самостоятельно делает targeted updates. Дать ей инструкцию:

```text
Add #34 sentry + #35 redis to CLAUDE.md §3.3 (table). Update §3.4 footer count
33 → 35. Update §0 cross-references row "Tooling" v1.16 → v1.17 and row "PSR_v1"
v2.0 → v2.1. Bump CLAUDE.md шапка v1.91 → v1.92 with changelog entry.
```

- [ ] **Step 9.5.2: Verify plugin output**

Plugin should report changes. Verify через `git diff CLAUDE.md`.

- [ ] **Step 9.5.3: Commit (plugin или manual)**

```bash
git add CLAUDE.md
git commit -m "$(cat <<'EOF'
docs(meta): CLAUDE.md v1.91 → v1.92 — §3.3 +#34/#35 sentry+redis MCP

§3.3 table расширен 2 строками (Tooling #34 sentry, #35 redis).
§3.4 footer count 33 → 35.
§0 cross-refs: Tooling v1.16 → v1.17, PSR_v1 v2.0 → v2.1.

Через /claude-md-management:claude-md-improver per §5 п.10.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)"
```

### Task 9.6: Sync `docs/Pravila_raboty_Claude_v1_1.md` (§13.2 counter)

- [ ] **Step 9.6.1: Read current Pravila §13.2**

```bash
grep -n "^### 13.2\|infrastructure subsection" docs/Pravila_raboty_Claude_v1_1.md | head -5
```

- [ ] **Step 9.6.2: Edit §13.2 — bump infrastructure subsection counter**

В §13.2 — counter инфраструктурных плагинов / off-phase tools — bump соответствующее число для отражения 2 новых off-phase tools (sentry + redis).

Точная локация — search «инфраструктур» в §13.2.

- [ ] **Step 9.6.3: Edit Pravila version bump**

Шапка v1.12 → v1.13 от 13.05.2026 day +1.

- [ ] **Step 9.6.4: Commit**

```bash
git add docs/Pravila_raboty_Claude_v1_1.md
git commit -m "$(cat <<'EOF'
docs(rules): Pravila v1.12 → v1.13 — §13.2 counter bump (infrastructure)

§13.2 infrastructure subsection counter — отражение Tooling §3.3 #34/#35
sentry+redis MCP off-phase tools added 13.05.2026.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EOF
)"
```

### Task 9.7: Sync Memory (MEMORY.md + reference_archive.md)

- [ ] **Step 9.7.1: Read Memory MEMORY.md**

```bash
cat "C:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/MEMORY.md"
```

- [ ] **Step 9.7.2: Edit MEMORY.md reference_archive line**

Update version refs:

- CLAUDE.md v1.91 → v1.92
- Pravila v1.12 → v1.13
- Tooling v1.16 → v1.17
- PSR_v1 v2.0 → v2.1

- [ ] **Step 9.7.3: Edit reference_archive.md содержимое**

Update же version refs + entry «sentry+redis MCP formalization 13.05.2026 day +1 (Tooling #34/#35)».

- [ ] **Step 9.7.4: NO commit (memory лежит вне repo, persistent locally)**

### Task 9.8: Final lychee + gitleaks regression на main

- [ ] **Step 9.8.1: Lychee на full docs**

```bash
"C:/моя/проекты/портал crm/Документация/bin/lychee.exe" --config .lychee.toml "docs/**/*.md" "db/**/*.md" "*.md" 2>&1 | tail -5
```

Expected baseline per memory project_state.md: 252 OK / 0 broken. После sync — должно быть тот же baseline или +N если добавились внутренние cross-refs.

- [ ] **Step 9.8.2: Gitleaks full history**

```bash
"C:/моя/проекты/портал crm/Документация/bin/gitleaks.exe" detect --source . --no-banner --config .gitleaks.toml --redact 2>&1 | tail -5
```

Expected: 0 leaks. Sentry credentials НЕ должны попадать (User scope env vars).

- [ ] **Step 9.8.3: Push sync branch**

```bash
git push -u origin feat/claude-automation-norm-sync
```

- [ ] **Step 9.8.4: Create sync PR через web UI**

URL: `https://github.com/CoralMinister/lidpotok/pull/new/feat/claude-automation-norm-sync`

Title: `docs(meta): sync нормативки (#34 sentry + #35 redis MCP) — v1.91→v1.92 / v1.12→v1.13 / v2.0→v2.1 / v1.16→v1.17`

Body: краткое описание 4 file updates + Memory sync + reference to feat/claude-automation merge.

- [ ] **Step 9.8.5: Merge sync PR + cleanup**

После approval — merge через web UI (или local fast-forward + push). Delete sync branch.

---

## Self-review (после написания plan)

### 1. Spec coverage

Coverage 9 пунктов из user choice "9 пунктов":

| User scope | Plan Task |
|---|---|
| Reload session | Task 2 |
| PR via web UI | Task 1 |
| Hook smoke (CLAUDE.md + db/schema.sql) | Task 3 (combined, 2 sub-cases + negative) |
| Redis Memurai check | Task 4 |
| Live skill invocations | Task 5 |
| Live subagent invocations | Task 6 |
| Sentry MCP credentials | Task 7 |
| Pest/Vitest regression | Task 8 |
| Sync нормативки + merge + cleanup | Task 9 (sub-tasks 9.1-9.8) |

✅ 9 пунктов covered.

### 2. Placeholder scan

- `<your-domain>` в Sentry URL — placeholder требующий user input (Sentry hostname). **Acceptable**: actual value depends на Sentry deployment Б-1. Task 7.1/7.2 instructs user replace.
- `<token-from-step-7.2>` — generated token. Acceptable placeholder.
- `<NN>` для PR number в merge commit — actual value captured в Step 1.4. Acceptable.
- `<sha1>..<sha2>` в push output — runtime value. Acceptable.

No "TBD" / "implement later" / "fill in details" placeholders.

### 3. Type consistency

- `feat/claude-automation` — consistent branch name через все tasks.
- `feat/claude-automation-norm-sync` — consistent в Task 9.2-9.8.
- `SENTRY_URL` + `SENTRY_AUTH_TOKEN` — consistent env var names (matches `.mcp.json` placeholders).
- `mcp__sentry__*` + `mcp__redis__*` — consistent MCP tool prefixes.
- `q-item-add`, `rls-check`, `rls-reviewer`, `pest-parallel-debugger` — consistent slugs matching `.claude/skills/` + `.claude/agents/` filenames.
- Quirks 72-73 — consistent с memory + previous spec/plan.

✅ Type consistency holds.

### 4. NB ограничения (явно)

- **Не верифицировал**, что Sentry instance actually deployed в Yandex Cloud — Task 7 BLOCKED если Б-1 не closed.
- **Не верифицировал**, что Memurai service installed на dev machine — Task 4 может revealить gap (need install).
- **Не верифицировал** точные line numbers для §13.2 Pravila counter — Task 9.6.1 grep локирует на момент execution.
- **Не верифицировал** что `/claude-md-management:claude-md-improver` skill can perform targeted updates as instructed — depends on plugin behavior. Если plugin не auto-applies — fallback на manual Edit (нарушение §5 п.10) с явным consent от user.
- **Auto-discovery behavior** для skills/agents post-reload — Task 5.1/6.1 verify; если fail → BLOCKED escalation.

---

## Execution handoff

Plan complete и saved to `docs/superpowers/plans/2026-05-13-claude-automation-completion-plan.md`.

Две execution options:

1. **Subagent-Driven (recommended для Tasks 8-9)** — fresh subagent per sub-task, two-stage review между. Использует `superpowers:subagent-driven-development`. NB: Tasks 1, 2, 3, 4, 5, 6, 7 — heavy на manual user actions (browser, VSCode restart, PowerShell env, etc.), subagent не может выполнить. Subagent useful для Task 9 sync нормативки + merge.

2. **Inline Execution** — execute tasks в текущей session, batch с checkpoints через `superpowers:executing-plans`. Pros: я могу coordinate UI actions + automated tasks; user делает Task 1 (PR) и Task 2 (reload) manually.

**Какой подход?** (или — только plan saved, execution отложить?)
