# Portal Full Audit #2 (2026-05-13) Implementation 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:** Полный 14-phase audit портала Лидерра на main `21262ef` post-merge plan5→main с hybrid fix-policy (P0+P1 → atomic commits, P2/P3 → findings.md only) + новая Phase 14 pre-production readiness.

**Architecture:** 14 последовательных phase'ов (0-14) с parallel subagent dispatch в Phase 1 (×4) + Phase 12/13 (×1 each). Каждая phase производит структурированные findings в `docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md`. P0/P1 fixed atomic commits на main по ходу; P2/P3 — только запись. Verification gates после каждой phase. Final regression gate Phase 9 (≥baseline) + push на `origin/main`.

**Tech Stack:** Pest 4 (PHP tests), Vitest 4.1 (TS tests), Histoire (Vue stories), Vite build, Laravel Boost MCP (DB queries), Playwright MCP (UI smoke + axe-core inject), gitleaks (secrets scan), Pa11y CLI (a11y), rollup-plugin-visualizer (bundle), lefthook (pre-commit/pre-push hooks).

**Spec:** [../specs/2026-05-13-portal-full-audit-2-design.md](../specs/2026-05-13-portal-full-audit-2-design.md) (commit `fc07529`).

**Reference (предыдущий audit):** [../audits/2026-05-12-portal-full-audit-report.md](../audits/2026-05-12-portal-full-audit-report.md).

---

## File Structure

**Audit artefacts (creates):**

- `docs/superpowers/audits/2026-05-13-portal-full-audit.md` — план (этот файл)
- `docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md` — детальные findings per phase
- `docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md` — Q-items
- `docs/superpowers/audits/2026-05-13-portal-full-audit-report.md` — summary verdict
- `audit-screens/2026-05-13/*.png` — 24 screenshots (Phase 5)

**Potentially modified (через Phase 8 fix loop, conditional on findings):**

- `../../../app/resources/js/router/index.ts` — router-guard, missing routes
- `../../../app/routes/web.php` — explicit Route::view list
- `../../../cspell-words.txt` — new project terms
- `../../../app/resources/js/components/**/*.vue` — a11y/eslint fixes
- `CLAUDE.md` — drift bumps (через `claude-md-management:claude-md-improver` skill)
- `docs/Pravila_raboty_Claude_v1_1.md` — если новые quirks из этого audit
- `memory/feedback_environment.md` — новые quirks

---

## Phase 0 — Pre-flight

**Files:**

- Create: `docs/superpowers/audits/2026-05-13-portal-full-audit.md`
- Create: `docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md`
- Create: `docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md`
- Create: `docs/superpowers/audits/2026-05-13-portal-full-audit-report.md`

### Task 0.1: Verify HEAD state

- [ ] **Step 1: Check git status и HEAD**

Run: `git status --short && git log --oneline -3`

Expected output (HEAD должен быть `fc07529` или newer; обязательно на `main`):

```
On branch main
Your branch is ahead of 'origin/main' by N commits.
fc07529 docs(audit): spec for portal full audit #2 (2026-05-13)
...
```

If HEAD не на `main` или есть unrelated uncommitted changes — STOP, escalate.

### Task 0.2: Verify deps installed

- [ ] **Step 1: Composer**

Run: `cd ../../../app && composer install --no-interaction --quiet`

Expected: no output, exit 0.

- [ ] **Step 2: npm (per квирк 74 — Histoire peerDep)**

Run: `cd ../../../app && npm install --legacy-peer-deps`

Expected: «up to date» или incremental install, exit 0.

### Task 0.3: Skeleton 4 audit-документов

- [ ] **Step 1: Create plan.md (этот файл уже создан writing-plans skill'ом, skip)**

- [ ] **Step 2: Create findings.md skeleton**

Write to `docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md`:

```markdown
# Portal Full Audit #2 — Findings (2026-05-13)

> **Связано:** план [2026-05-13-portal-full-audit.md](../plans/2026-05-13-portal-full-audit-2.md), spec [../specs/2026-05-13-portal-full-audit-2-design.md](../specs/2026-05-13-portal-full-audit-2-design.md), blocked `2026-05-13-portal-full-audit-blocked.md`, report `2026-05-13-portal-full-audit-report.md`
> **HEAD:** `main` `fc07529+`
> **Режим:** экономия 0%

## Severity легенда

- P0 — блокирует production / data corruption / security incident
- P1 — нарушение функциональности / failing test / type error / a11y violation
- P2 — warning / style / dead code / stale doc
- P3 — cosmetic / nice-to-have

## Fix-eligibility

- `[FIX-NOW]` — попадает под decision-tree «можно делать», фикс ≤30 мин
- `[FIX-DEFER]` — реально починить, но >1 час / большой refactor
- `[BLOCKED]` — hard-stop из decision-tree, нужно явное «закрываем»

---

## Phase 0 — Pre-flight

### Findings

(заполняется в ходе Phase 0)

---
```

Каждая последующая Phase будет добавлять `## Phase N — <name>` секцию.

- [ ] **Step 3: Create blocked.md skeleton**

Write to `docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md`:

```markdown
# Portal Full Audit #2 — Blocked questions (2026-05-13)

> **Связано:** план [2026-05-13-portal-full-audit.md](../plans/2026-05-13-portal-full-audit-2.md), findings `2026-05-13-portal-full-audit-findings.md`
> **Когда читать:** перед началом следующей сессии Claude

## Категории

- **Q.HARD** — hard-stop из decision-tree (schema, открытые вопросы, ТЗ-правки, новые packages, force-push)
- **Q.PRODUCT** — продуктовое/дизайнерское решение
- **Q.DEFER** — реально починить, но >1 час / большой refactor
- **Q.INFO** — информационный пункт (известный flaky, новый quirk)

## Открытые вопросы

(заполняется в ходе audit'а)

---

## Шаблон вопроса

````text
### Q.{CAT}.NNN — короткий заголовок

**Из:** Phase X / file:line / finding-id
**Severity при отказе:** P0/P1/P2/P3
**Контекст:** что обнаружено, что сделано, почему остановился
**Что нужно от заказчика:** конкретный выбор (A/B/C или «делай Y»)
**Если ответа нет → план Б:** ...
````

```

- [ ] **Step 4: Create report.md skeleton**

Write to `docs/superpowers/audits/2026-05-13-portal-full-audit-report.md`:

```markdown
# Portal Full Audit #2 — Summary Report (2026-05-13)

> **Связано:** план [2026-05-13-portal-full-audit.md](../plans/2026-05-13-portal-full-audit-2.md), findings `2026-05-13-portal-full-audit-findings.md`, blocked `2026-05-13-portal-full-audit-blocked.md`
> **HEAD start:** `main` `fc07529`
> **Режим:** экономия 0%

---

## TL;DR

(заполняется в Phase 9 после final verification)

---

## По phase'ам

(детали — в findings.md)

---

## Метрики до/после

| Метрика | Phase 0 baseline | Phase 9 final | Delta |
|---|---|---|---|
| Pest --parallel | … | … | |
| Vitest | … | … | |
| Histoire | … | … | |
| Vite build | … | … | |
| ESLint | … | … | |
| vue-tsc | … | … | |
| markdownlint | … | … | |
| cspell | … | … | |
| lychee | … | … | |
| gitleaks (full) | … | … | |
| RLS policies | … | … | |

---

## Blocked questions (см. blocked.md)

(перечисляются IDs)

---

## Что НЕ зафиксировано в коде

(P2/P3 findings + BLOCKED + FIX-DEFER)

---

## Verdict

🟢/🟡/🔴

---

## Commits made в этой сессии

(заполняется в Phase 9)

---

## Lessons captured

(новые quirks для memory + Pravila)
```

### Task 0.4: Inventory untracked workdir

- [ ] **Step 1: List untracked**

Run: `git ls-files --others --exclude-standard`

Expected: 0-N untracked files. Запиши список в findings.md Phase 0 section как Reference (informational).

- [ ] **Step 2: Commit Phase 0 artefacts**

Run:

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git add docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md
git add docs/superpowers/audits/2026-05-13-portal-full-audit-report.md
git add docs/superpowers/plans/2026-05-13-portal-full-audit-2.md
git commit -m "$(cat <<'EOF'
docs(audit): skeletons for portal full audit #2 (2026-05-13)

Plan + findings + blocked + report skeletons. Audit start.

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

Expected: lefthook clean (gitleaks 0, markdownlint 0, cspell 0), commit created.

---

## Phase 1 — Static analysis (parallel ×4 subagents)

**Files:** только findings.md updates (если P0/P1 findings — fix commits в Phase 8).

### Task 1.1: Dispatch 4 parallel subagents

- [ ] **Step 1: Single message with 4 `Agent` tool calls (parallel)**

В одном сообщении:

**Subagent A — Backend static analysis:**

```
subagent_type: general-purpose
description: "Backend static analysis"
prompt: """
Run в репозитории Лидерра (cwd `c:\моя\проекты\портал crm\Документация\app`):
1. composer pint:test (test-mode per квирк 63 — НЕ `composer pint --test`)
2. composer stan
3. composer audit --locked

Верни **raw** exit codes + полный stderr+stdout для каждой команды.
**НЕ summary**, не выводы — только raw output.
Решения принимаю я (главный агент).
"""
```

**Subagent B — Frontend static analysis:**

```
subagent_type: general-purpose
description: "Frontend static analysis"
prompt: """
Run в cwd `c:\моя\проекты\портал crm\Документация\app`:
1. npm run lint:vue
2. npx vue-tsc --noEmit
3. npx prettier --check .
4. npx knip --production

Верни **raw** exit codes + полный stderr+stdout для каждой команды.
**НЕ summary** — raw output. Решения принимаю я.
"""
```

**Subagent C — Docs static analysis:**

```
subagent_type: general-purpose
description: "Docs static analysis"
prompt: """
Run в cwd `c:\моя\проекты\портал crm\Документация`:
1. npm run lint:md
2. npm run spell
3. npm run links

Верни **raw** exit codes + полный stderr+stdout для каждой команды.
**НЕ summary** — raw output. Решения принимаю я.
"""
```

**Subagent D — SQL static analysis:**

```
subagent_type: general-purpose
description: "SQL static analysis"
prompt: """
Run в cwd `c:\моя\проекты\портал crm\Документация`:
1. ./bin/squawk.exe db/schema.sql (или `npx squawk lint db/schema.sql`)
2. ./bin/pg_format -o /tmp/schema-fmt.sql db/schema.sql && diff db/schema.sql /tmp/schema-fmt.sql | wc -l

Верни **raw** exit codes + diff line count + первый hunk pgFormatter diff.
**НЕ summary** — raw output. Решения принимаю я.
"""
```

Expected: 4 raw outputs returned in parallel.

### Task 1.2: Record Phase 1 findings

- [ ] **Step 1: Parse каждый subagent output**

Append к findings.md секция `## Phase 1 — Static analysis`:

```markdown
## Phase 1 — Static analysis

### Subagent A — Backend (Pint + Larastan + composer audit)

**Exit codes:** pint=<N>, stan=<N>, audit=<N>.

**Findings:**
- <bullets с file:line refs если errors>

### Subagent B — Frontend (ESLint + vue-tsc + Prettier + knip)

**Exit codes:** eslint=<N>, vue-tsc=<N>, prettier=<N>, knip=<N>.

**Findings:**
- <bullets с file:line refs если errors>

### Subagent C — Docs (markdownlint + cspell + lychee)

**Exit codes:** lint:md=<N>, spell=<N>, lychee=<N>.

**Findings:**
- <bullets с counts and example file:line>

### Subagent D — SQL (squawk + pgFormatter)

**Exit codes:** squawk=<N>, pgFormatter diff lines=<N>.

**Findings:**
- <bullets>

### Phase 1 итог

**Severity rollup:** P0=<N>, P1=<N>, P2=<N>, P3=<N>.

**FIX-NOW count:** <N>.
**FIX-DEFER count:** <N>.
**BLOCKED count:** <N>.
```

Для каждой non-trivial находки — ≥3 гипотезы systematic-debugging (per economy 0%).

- [ ] **Step 2: Commit Phase 1 findings (если есть updates)**

Run:

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 1 static analysis findings"
```

Expected: lefthook clean.

---

## Phase 2 — Test suites (sequential)

### Task 2.1: Pest sequential (наблюдение квирка 62)

- [ ] **Step 1: Run без --parallel**

Run: `cd ../../../app && composer test 2>&1 | tee /tmp/pest-seq.log`

Expected: 742 tests / ~736 passed / ~3 failed (cumulative state, квирк 62) / 3 skipped (Browser).

- [ ] **Step 2: Record в findings.md**

Append section `## Phase 2 — Test suites` с подсекциями:

```markdown
### Pest sequential

**Exit code:** <N>. **<X> tests / <Y> passed / <Z> failed / <W> skipped / <T>s.**

**Failed (если):**
- P1 [pest] tests/Feature/...:<line> — <error message>
- ... (≥3 гипотезы корня)
```

### Task 2.2: Pest --parallel --recreate-databases

- [ ] **Step 1: Run**

Run: `cd ../../../app && composer test -- --parallel --recreate-databases 2>&1 | tee /tmp/pest-par.log`

Expected: 742 / 739 / 0 / 3 / ~33s.

- [ ] **Step 2: Diff между sequential и parallel в findings.md**

```markdown
### Diff between Pest runs

- Регрессия sequential → parallel: <N>
- Stable failures (упали в обоих): <N>
```

### Task 2.3: Vitest

- [ ] **Step 1: Run**

Run: `cd ../../../app && npx vitest run --reporter=verbose 2>&1 | tee /tmp/vitest.log`

Expected: 88 files / 683 passed / 3 skipped / ~60s.

- [ ] **Step 2: Record в findings.md (полные failed file:line если есть)**

### Task 2.4: Histoire build

- [ ] **Step 1: Run**

Run: `cd ../../../app && npm run story:build 2>&1 | tee /tmp/histoire.log`

Expected: 35 stories / 63 variants / ~30s. Exit 0.

- [ ] **Step 2: Если EXIT 1 — P0**

Записать как P0 в findings.md. Включить ≥3 гипотезы корня (как 12.05 BulkActionsBar story bug).

### Task 2.5: Vite production build

- [ ] **Step 1: Run**

Run: `cd ../../../app && npm run build 2>&1 | tee /tmp/vite.log`

Expected: ~3.5s, 0 warnings, 0 errors, ~688 modules.

- [ ] **Step 2: Record top-10 chunks в findings.md**

### Task 2.6: Commit Phase 2 findings

- [ ] **Step 1: Commit**

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 2 test suite findings"
```

---

## Phase 3 — Schema integrity (Boost MCP)

### Task 3.1: Метрики через Boost MCP

- [ ] **Step 1: Run каждый query через `mcp__laravel-boost__database-query`**

Queries:

```sql
-- 1. Base tables (root)
SELECT count(*) FROM pg_class c JOIN pg_namespace n ON c.relnamespace=n.oid WHERE n.nspname='public' AND c.relkind='r' AND c.relispartition=false;

-- 2. Partition children
SELECT count(*) FROM pg_class WHERE relispartition=true AND relkind='r';

-- 3. Indexes
SELECT count(*) FROM pg_indexes WHERE schemaname='public';

-- 4. RLS policies
SELECT count(*) FROM pg_policies WHERE schemaname='public';

-- 5. User functions
SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON p.pronamespace=n.oid WHERE n.nspname='public' AND p.prokind='f' AND p.proname NOT IN (SELECT proname FROM pg_proc JOIN pg_depend ON objid=oid WHERE deptype='e');

-- 6. Triggers
SELECT count(*) FROM pg_trigger WHERE tgisinternal=false;

-- 7. DB roles
SELECT count(*) FROM pg_roles WHERE rolname LIKE 'crm_%';

-- 8. Orphan FK check
SELECT conname, conrelid::regclass FROM pg_constraint WHERE contype='f' AND NOT EXISTS (
  SELECT 1 FROM pg_constraint inner_c WHERE inner_c.oid=pg_constraint.confrelid
);
```

- [ ] **Step 2: Записать в findings.md таблицу drift'а**

```markdown
## Phase 3 — Schema integrity

| Метрика | CLAUDE.md baseline v8.19 | Dev `liderra` factual | Diff | Severity |
|---|---|---|---|---|
| Base tables | 62 | <N> | <D> | <P> |
| Partitions | 12 | <N> | <D> | <P> |
| Indexes | 117 | <N> | <D> | <P> |
| RLS policies | 39 | <N> | 0 | ✅ |
| User functions | 5 | <N> | <D> | <P> |
| Triggers | 13 | <N> | <D> | <P> |
| DB roles | 5 (prod) | 0 (dev) | by-design | ✅ |
| Orphan FK | 0 | <N> | <D> | <P> |
```

Memory `project_state.md` ожидает dev-actual: 75/102/289/39/5/19/0.

### Task 3.2: Commit Phase 3 findings

- [ ] **Step 1: Commit**

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 3 schema integrity findings"
```

---

## Phase 4 — Security

### Task 4.1: CI workflows enumeration FIRST (Pravila v1.12 §4.6 methodology gap closure)

- [ ] **Step 1: List workflows**

Run: `ls -la .github/workflows/ 2>&1`

Expected: список workflow файлов (`sast.yml`, `tests.yml`, etc.).

- [ ] **Step 2: Прочитать sast.yml содержимое**

Read: `.github/workflows/sast.yml`

Записать: factual state SAST coverage в Phase 4 findings.md секцию.

### Task 4.2: Gitleaks full history

- [ ] **Step 1: Run**

Run: `./bin/gitleaks.exe detect --no-banner --redact --config .gitleaks.toml 2>&1`

Expected: 0 leaks, `N`00 commits scanned.

- [ ] **Step 2: Record**

```markdown
### gitleaks full history

**Exit code:** <N>. **<N> leaks.** <N> commits scanned, <M> MB, <T>s.
```

### Task 4.3: Composer audit (cross-link Phase 1.A)

- [ ] **Step 1: Verify Phase 1 composer audit result**

Just cross-link Phase 1 finding в Phase 4 section.

### Task 4.4: Production secrets grep

- [ ] **Step 1: AWS prefix scan**

Run через Grep tool:

- pattern: `AKIA[0-9A-Z]{16}`
- path: `app/`
- output_mode: content

Expected: 0 matches.

- [ ] **Step 2: SK prefix scan**

Run через Grep tool:

- pattern: `SK[a-z0-9]{32}`
- path: `app/`
- output_mode: content

Expected: 0 matches (или test fixtures).

- [ ] **Step 3: .env.example vs config/*.php references diff**

Run через Grep tool:

- pattern: `env\\(['"]([A-Z_]+)['"]`
- path: `app/config/`
- output_mode: content
- head_limit: 0

Compare keys с `app/.env.example` keys. Missing → P1.

### Task 4.5: Commit Phase 4 findings

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 4 security findings"
```

---

## Phase 5 — UI smoke (Playwright MCP)

### Task 5.1: Start dev servers

- [ ] **Step 1: Seed DB через DemoSeeder**

Run: `cd ../../../app && php artisan db:seed --class=DemoSeeder`

Expected: «Database seeding completed successfully.», admin@demo.local / password, 3 projects, 14 deals.

- [ ] **Step 2: Start Laravel server (background)**

Run в background: `cd ../../../app && php artisan serve`

Expected: «Server running on [http://127.0.0.1:8000]».

- [ ] **Step 3: Start Vite (background)**

Run в background: `cd ../../../app && npm run dev`

Expected: «VITE v6.x ready in `<some>ms` on http://localhost:5173/».

### Task 5.2: 24 views smoke (Playwright MCP iterations)

- [ ] **Step 1: For каждой URL из 24-view списка:**

URLs (8 auth + 8 main + 8 admin + 24-я ErrorView):

```
01 /login         02 /register      03 /forgot        04 /2fa
05 /recovery      06 /use-recovery  07 /reset/test    08 /dashboard
09 /deals         10 /kanban        11 /projects      12 /reports
13 /billing       14 /settings      15 /reminders     16 /admin/tenants
17 /admin/tenants/1 18 /admin/billing 19 /admin/incidents 20 /admin/system
21 /admin/impersonation 22 /admin/pricing-tiers 23 /admin/supplier-prices 24 /no-such-path-anywhere
```

Per URL:

1. `mcp__playwright__browser_navigate` → URL
2. `mcp__playwright__browser_console_messages` → check 0 errors expected
3. `mcp__playwright__browser_network_requests` → API responses
4. `mcp__playwright__browser_take_screenshot` → `audit-screens/2026-05-13/NN-name.png`
5. **CTO-19 verification:** Lucide icon rendering check (visual inspection screenshot)

- [ ] **Step 2: Records в findings.md**

Per-view table (24 rows) с status + console + net + notes columns.

### Task 5.3: Login/logout flow

- [ ] **Step 1: Login**

Sequence:

1. `browser_navigate` /login
2. `browser_fill_form` (email=admin@demo.local, password=password) — учитывать квирк 67 (label-based locators ломаются на кириллице; использовать id-based).
3. `browser_click` «Войти»
4. Verify redirect to /dashboard, network 200 на /api/auth/login.

- [ ] **Step 2: Logout**

1. `browser_click` avatar dropdown
2. `browser_click` «Выйти»
3. Verify redirect to /login.

### Task 5.4: Commit Phase 5 + screenshots

- [ ] **Step 1: Stage screenshots + findings**

```bash
git add audit-screens/2026-05-13/
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 5 UI smoke (24 views + login flow)"
```

---

## Phase 6 — Cross-doc integrity

### Task 6.1: Версии нормативных файлов

- [ ] **Step 1: Read shapкa каждого**

Files и expected versions (per memory `reference_archive.md`):

| File | Expected |
|---|---|
| `CLAUDE.md` | v1.91 |
| `docs/Pravila_raboty_Claude_v1_1.md` | v1.12 |
| `docs/Plugin_stack_rules_v1.md` | v2.0 |
| `docs/Tooling_v8_3.md` | v1.16 |
| `docs/Открытые_вопросы_v8_3.md` | v1.83 |
| `db/schema.sql` | v8.20 |
| `docs/README_АРХИВ_v8_5.md` | v8.5 |

Use Read tool на первые 5 строк каждого → grep version.

- [ ] **Step 2: Record drift table в findings.md**

### Task 6.2: routes/web.php explicit Route::view completeness

- [ ] **Step 1: Read routes/web.php**

Read: `../../../app/routes/web.php`

- [ ] **Step 2: Inventory всех `Route::view('/path', 'welcome')` lines**

Expected per 12.05 audit `b9038bc` fix: должны быть `/, /login, /register, /forgot, /reset/:token, /2fa, /recovery, /recovery-use, /dashboard, /deals, /kanban, /projects, /billing, /settings, /reports, /reminders, /admin/tenants, /admin/tenants/{id}, /admin/billing, /admin/incidents, /admin/system, /admin/pricing-tiers, /admin/supplier-prices, /admin/impersonation, /403, /500`.

Missing → P1/P2 depending on test impact.

### Task 6.3: Vue Router routes vs views inventory

- [ ] **Step 1: Read router/index.ts**

Read: `../../../app/resources/js/router/index.ts`

- [ ] **Step 2: Glob views**

Glob pattern: `app/resources/js/views/**/*.vue`

- [ ] **Step 3: Cross-check каждый view → router route exists**

Записать missing/orphan finding в findings.md.

### Task 6.4: Memory description sync

- [ ] **Step 1: Re-Read memory files**

Files:

- `c:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/MEMORY.md`
- `c:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/reference_archive.md`
- `c:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/project_state.md`

- [ ] **Step 2: Diff memory claims vs Task 6.1 factual versions**

Forward-stale (memory предсказывает версии файлов в будущем) → P2 [memory-drift].
Backward-stale (memory отстаёт) → P2 [memory-drift].

### Task 6.5: Commit Phase 6 findings

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 6 cross-doc integrity findings"
```

---

## Phase 7 — Categorize

### Task 7.1: Severity rollup table

- [ ] **Step 1: Build таблицу**

В findings.md append `## Phase 7 — Fix Queue`:

```markdown
## Phase 7 — Fix Queue (categorized)

### Severity rollup всей сессии (Phases 0-6)

| Phase | P0 | P1 | P2 | P3 |
|---|---|---|---|---|
| Phase 0 | 0 | 0 | 0 | 0 |
| Phase 1 | <N> | <N> | <N> | <N> |
| Phase 2 | <N> | <N> | <N> | <N> |
| Phase 3 | <N> | <N> | <N> | <N> |
| Phase 4 | <N> | <N> | <N> | <N> |
| Phase 5 | <N> | <N> | <N> | <N> |
| Phase 6 | <N> | <N> | <N> | <N> |
| **TOTAL** | <N> | <N> | <N> | <N> |

### P0 (fix немедленно)
<list>

### P1 (fix атомарным commit'ом в Phase 8)
<list ordered by Phase>

### P2 (только запись в findings.md, без commits per hybrid)
<list>

### P3 (defer/cosmetic — informational only)
<list>

### BLOCKED (вопросы заказчику в blocked.md)
<list>

### Fix order (Phase 8 plan)
1. <Fix #1 (P0): ...>
2. <Fix #2 (P1): ...>
...
```

### Task 7.2: Move BLOCKED items to blocked.md

- [ ] **Step 1: For each BLOCKED finding — write Q.{HARD|PRODUCT|DEFER|INFO}.NNN entry в blocked.md**

Per шаблон из blocked.md (in Task 0.3 Step 3).

### Task 7.3: Commit Phase 7

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md
git commit -m "docs(audit): Phase 7 fix queue + blocked questions"
```

---

## Phase 8 — Fix loop (hybrid policy)

**Применяется только если есть P0/P1 findings из Phases 1-6.** Если нет — skip Phase 8 entirely.

### Task 8.N: For each P0/P1 fix (ordered per Phase 7 fix-order)

(Generic template — повторить для каждого P0/P1 fix per Phase 7 ordering)

- [ ] **Step 1: Read affected file**

Read: `<file_path>`

- [ ] **Step 2: Write failing test (if code change)**

Per `superpowers:test-driven-development` skill:

- For PHP code: `app/tests/Feature/...` или `app/tests/Unit/...`
- For Vue/TS: `app/tests/Frontend/...`

```php
// Example (replace per actual fix)
test('<behavior>', function () {
    // arrange
    // act
    // assert
});
```

- [ ] **Step 3: Run test, verify it fails**

Run: `cd ../../../app && composer test -- --filter=<test_name>` (PHP)
OR: `cd ../../../app && npx vitest run <spec_path>` (TS)

Expected: FAIL with expected error.

- [ ] **Step 4: Apply fix (minimal)**

Edit/Write на target file.

- [ ] **Step 5: Run test, verify GREEN**

Same command. Expected: PASS.

- [ ] **Step 6: Run full relevant suite (regression check)**

Run: `cd ../../../app && composer test -- --parallel --recreate-databases`
OR: `cd ../../../app && npx vitest run`

Expected: ≥ baseline.

- [ ] **Step 7: Commit**

```bash
git add <files>
git commit -m "<type>(<scope>): <description>

<body if multi-line>

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

Type: `fix` / `feat` / `chore` / `refactor` / `test` / `docs`.

- [ ] **Step 8: Self-review §8 после каждых 3 fix-commit'ов**

Run: `git diff HEAD~3..HEAD --stat`

Check:

- Файлы touched per change scope.
- Nothing accidentally included.
- Commit messages informative.

---

## Phase 9 — Final regression verification

### Task 9.1: Pest --parallel --recreate-databases

- [ ] **Step 1: Run**

Run: `cd ../../../app && composer test -- --parallel --recreate-databases 2>&1 | tee /tmp/pest-final.log`

Expected: ≥742 / ≥739 passed / 0 failed / ≤3 skipped.

- [ ] **Step 2: Record в report.md метрики до/после таблицу**

### Task 9.2: Vitest

- [ ] **Step 1: Run**

Run: `cd ../../../app && npx vitest run --reporter=verbose 2>&1 | tee /tmp/vitest-final.log`

Expected: ≥88 files / ≥683 passed / 0 failed.

### Task 9.3: Vite build

- [ ] **Step 1: Run**

Run: `cd ../../../app && npm run build 2>&1 | tee /tmp/vite-final.log`

Expected: ≥0 errors / 0 warnings.

### Task 9.4: Histoire build

- [ ] **Step 1: Run**

Run: `cd ../../../app && npm run story:build 2>&1 | tee /tmp/histoire-final.log`

Expected: ≥35 stories / ≥63 variants.

### Task 9.5: Regression decision gate

- [ ] **Step 1: Compare к Phase 2 baseline**

Если регрессия (any metric below baseline):

1. Systematic-debugging (≥3 гипотезы per economy 0%)
2. Rollback affected commit OR forward-fix
3. Re-run Phase 9 после fix

Если 0 регрессий: proceed Phase 10.

### Task 9.6: Update report.md метрики

- [ ] **Step 1: Fill «Phase 9 final» column в report.md**

### Task 9.7: Commit Phase 9 verification

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-report.md
git commit -m "docs(audit): Phase 9 regression verification metrics"
```

---

## Phase 10 — Live Pa11y / axe-core

### Task 10.1: Pa11y CLI on 4 guest URLs

- [ ] **Step 1: For each guest URL run Pa11y**

URLs:

- http://127.0.0.1:8000/login
- http://127.0.0.1:8000/register
- http://127.0.0.1:8000/forgot
- http://127.0.0.1:8000/no-such-path-anywhere

Per URL:
Run: `npx pa11y --standard WCAG2AA --timeout 30000 --wait 1500 <URL> 2>&1`

Expected: 0 errors (после Q.DEFER.002 closure 12.05.2026).

- [ ] **Step 2: Record results в findings.md `## Phase 10`**

### Task 10.2: Auth-required views ×16 via Playwright MCP + axe-core

- [ ] **Step 1: Login через Playwright MCP**

См. Task 5.3 Step 1.

- [ ] **Step 2: For each auth-required URL:**

URLs (16):

```
/dashboard /deals /kanban /projects /reports /billing /settings /reminders
/admin/tenants /admin/tenants/1 /admin/billing /admin/incidents
/admin/system /admin/pricing-tiers /admin/supplier-prices /admin/impersonation
```

Per URL:

1. `mcp__playwright__browser_navigate` → URL
2. **WAIT 500ms** (per Q.DEFER.004 false-alarm lesson) — use `browser_wait_for` или `browser_evaluate` with setTimeout.
3. **Hard reload:** `browser_navigate` again (или `browser_press_key F5`)
4. **WAIT 500ms** again
5. `browser_evaluate` inject axe-core 4.10:

```javascript
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/axe-core@4.10.0/axe.min.js';
document.head.appendChild(script);
await new Promise((r) => setTimeout(r, 1000));
```

1. `browser_evaluate` run axe:

```javascript
const results = await axe.run();
return {
  violations: results.violations.map(v => ({id: v.id, impact: v.impact, nodes: v.nodes.length, help: v.help}))
};
```

1. Record violations в findings.md per URL.

- [ ] **Step 3: Закрытие Q.DEFER.002 residual**

Если 0 violations на всех 16 — Q.DEFER.002 fully closed.
Если есть — записать как Q.DEFER.NNN new entry в blocked.md.

### Task 10.3: Commit Phase 10

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md docs/superpowers/audits/2026-05-13-portal-full-audit-blocked.md
git commit -m "docs(audit): Phase 10 live Pa11y + axe-core findings"
```

---

## Phase 11 — TODO/FIXME sweep

### Task 11.1: Grep over app/

- [ ] **Step 1: Run Grep**

Tool: Grep

- pattern: `\b(TODO|FIXME|XXX|HACK)\b`
- path: `app/`
- output_mode: content
- -n: true
- head_limit: 0
- glob: `*.{php,vue,ts,js}`

Expected: `N` matches (12.05 baseline было 19; на 13.05 могло измениться).

- [ ] **Step 2: Categorize в findings.md**

```markdown
## Phase 11 — TODO/FIXME sweep

**Total:** <N> matches in <M> files.

### Категоризация

**MVP-defer ⏸ Б-1 (saas-admin auth) — cross-link Q.HARD.001:**
- <file:line> — <quote>

**Feature-defer (Plan 6+):**
- <file:line> — <quote>

**Production-readiness:**
- <file:line> — <quote>

**Test infra (known quirks):**
- <file:line> — <quote>

**False-positive:**
- <file:line> — <quote>
```

### Task 11.2: Commit Phase 11

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 11 TODO/FIXME sweep"
```

---

## Phase 12 — Bundle analyzer (1 subagent)

### Task 12.1: Subagent dispatch

- [ ] **Step 1: Single Agent call**

```
subagent_type: general-purpose
description: "Bundle analyzer"
prompt: """
Run в cwd `c:\моя\проекты\портал crm\Документация\app`:
  BUILD_ANALYZE=1 npm run build:analyze

Затем парси `storage/bundle-analyze.html` (rollup-plugin-visualizer).

Верни **raw**:
- Polный exit code build команды
- Top-15 chunks с raw size + gzip size + label
- Critical-path payload eager total (gzip)

**НЕ summary**. Решения по optimizations принимаю я.
"""
```

- [ ] **Step 2: Record в findings.md**

```markdown
## Phase 12 — Bundle analyzer

**Top-15 chunks:**

| # | Chunk | Raw | Gzip | Notes |
|---|---|---:|---:|---|
| 1 | <name> | <kB> | <kB> | <quirk если есть> |
...

**Critical-path payload eager (gzip):** <kB>.

**Findings:**

- P2 [bundle code-split] <chunk> — <гипотеза 1 / 2 / 3> [FIX-DEFER]
```

### Task 12.2: Commit Phase 12

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 12 bundle analyzer findings"
```

---

## Phase 13 — Vitest coverage (1 subagent)

### Task 13.1: Subagent dispatch

- [ ] **Step 1: Single Agent call**

```
subagent_type: general-purpose
description: "Vitest coverage"
prompt: """
Run в cwd `c:\моя\проекты\портал crm\Документация\app`:
  npx vitest run --coverage --coverage.reporter=text-summary --coverage.reporter=text

Coverage tool: @vitest/coverage-v8.

Верни **raw** output. **НЕ summary**. Решения принимаю я.
"""
```

- [ ] **Step 2: Record totals + lowest-coverage files в findings.md**

```markdown
## Phase 13 — Vitest coverage

**Totals:**
- Stmts: <X>%
- Branches: <X>%
- Funcs: <X>%
- Lines: <X>%

**Comparison to baselines:**
- 12.05 baseline: Stmts 75% / Branch 75% / Funcs 67% / Lines 77%
- Q.DEFER.003 post-closure: Stmts 78.67% / Branch 76.21% / Funcs 70.56% / Lines 80.89%
- Now: <X>% / <X>% / <X>% / <X>%

**Lowest-coverage files (top-10):**

| # | File | Stmts | Branch | Funcs | Lines |
|---|---|---:|---:|---:|---:|
...
```

### Task 13.2: Commit Phase 13

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 13 Vitest coverage"
```

---

## Phase 14 — Pre-production readiness (новое)

### Task 14.1: Sentry integration audit

- [ ] **Step 1: Grep TODO(production) + Sentry::captureException**

Tool: Grep

- pattern: `TODO\(production\)|Sentry::captureException`
- path: `app/`
- output_mode: content
- -n: true
- head_limit: 0

Expected baseline: 1 TODO в `app/app/Jobs/ProcessWebhookJob.php:375`.

- [ ] **Step 2: Status report в findings.md `## Phase 14`**

```markdown
## Phase 14 — Pre-production readiness

### 14.1 Sentry integration

- `app/app/Jobs/ProcessWebhookJob.php:375` — TODO(production) Sentry::captureException. Status: ⏸ pre-prod readiness defer.
- Other TODOs: <list если есть>
```

### Task 14.2: DB roles deployment scripts validity

- [ ] **Step 1: Read db/00_create_roles.sql**

Read: `db/00_create_roles.sql`

Verify: 5 ролей `crm_*` (anon, authenticated, supplier_worker, system, owner) с proper grants.

- [ ] **Step 2: Read db/02_grants.sql**

Read: `db/02_grants.sql`

Verify: grant matrix consistent с tables существующими (cross-link Phase 3 schema 75 tables).

- [ ] **Step 3: Record в findings.md 14.2**

### Task 14.3: Mock-data prod-gate revisit (Q.PRODUCT.002)

- [ ] **Step 1: Glob mock-composables**

Glob: `app/resources/js/composables/mock*.ts`

- [ ] **Step 2: Read каждый**

Read каждый mock file.

- [ ] **Step 3: Status — все ещё (B) prod-fallback per Q.PRODUCT.002 closure 12.05.2026?**

Если Plan 6 близок к реализации настоящих API — flag P2 [Q.PRODUCT.002 revisit needed].
Если нет — confirmed B.

### Task 14.4: CI workflows audit

- [ ] **Step 1: List workflows**

Run: `ls -la .github/workflows/`

- [ ] **Step 2: Read каждый workflow**

For each `.yml`:

1. Triggers (push/PR/schedule)
2. Jobs (build/test/sast/deploy)
3. Path-filters (если есть)
4. Secrets dependencies

- [ ] **Step 3: Coverage matrix в findings.md**

```markdown
### 14.4 CI workflows

| Workflow | Triggers | Jobs | Path-filters | Status |
|---|---|---|---|---|
| sast.yml | push/PR main | Semgrep | app/app/** + app/resources/js/** + app/database/migrations/** | ✅ |
| ... | | | | |
```

### Task 14.5: Environment validation

- [ ] **Step 1: Extract .env.example keys**

Tool: Grep

- pattern: `^[A-Z_]+=`
- path: `app/.env.example`
- output_mode: content
- head_limit: 0

- [ ] **Step 2: Extract env() references в config/**

Tool: Grep

- pattern: `env\(['"]([A-Z_]+)['"]`
- path: `app/config/`
- output_mode: content
- head_limit: 0

- [ ] **Step 3: Diff keys**

Записать missing keys (referenced в config, нет в .env.example) → P1.

### Task 14.6: Queue/cron infrastructure

- [ ] **Step 1: Schedule list**

Run: `cd ../../../app && php artisan schedule:list`

Expected: `partitions:create-months` + другие scheduled commands.

- [ ] **Step 2: Queue config inspection**

Read: `app/config/queue.php` (connections + default).

- [ ] **Step 3: Status в findings.md 14.6**

### Task 14.7: Backup/log rotation references

- [ ] **Step 1: Grep backup/logrotate mentions**

Tool: Grep

- pattern: `BACKUP|log-rotation|logrotate`
- path: `docs/`
- output_mode: content
- head_limit: 0

- [ ] **Step 2: Read app/config/logging.php**

Inventory channels (daily, slack, sentry).

- [ ] **Step 3: Status в findings.md 14.7**

### Task 14.8: Deployment runbook

- [ ] **Step 1: Glob runbook docs**

Glob: `deploy*.md`, `DEPLOY*.md`, `RUNBOOK*.md`, `docs/deploy*.md`.

- [ ] **Step 2: Read found (если есть)**

Capture status: present / missing.

- [ ] **Step 3: Если missing — P2 [pre-prod readiness gap]**

### Task 14.9: Commit Phase 14

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 14 pre-production readiness findings"
```

---

## Finalization

### Task F.1: Update report.md summary

- [ ] **Step 1: Fill all sections в report.md**

Sections:

- TL;DR: total findings (P0/P1/P2/P3), fixed count, deferred count, blocked count.
- По phase'ам: один-два предложения per phase.
- Метрики до/после: Phase 0 baseline vs Phase 9 final.
- Blocked questions for user: list IDs.
- Что НЕ зафиксировано в коде: list (P2/P3 findings + BLOCKED + FIX-DEFER).
- Verdict: 🟢 GREEN если 0 P0+P1 open после Phase 8 / 🟡 YELLOW если есть FIX-DEFER P1 / 🔴 RED если есть P0 open.
- Commits made в этой сессии: `git log --oneline 21262ef..HEAD`.
- Lessons captured: новые quirks для memory + Pravila.

### Task F.2: Memory updates если новые quirks

- [ ] **Step 1: Identify новые quirks**

В ходе audit'а если encountered unexpected behavior:

- Per Pravila §13.2 systematic-debugging — ≥3 гипотезы → root cause documented.
- Capture в memory `feedback_environment.md` (квирки 1-N → append N+1).

- [ ] **Step 2: Memory edit (via Edit tool)**

Update:

- `c:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/feedback_environment.md` — новые quirks.
- `c:/Users/Administrator/.claude/projects/c---------------------crm-------------/memory/project_state.md` — обновить metric baselines.

### Task F.3: Final commit (audit-finalize)

- [ ] **Step 1: Commit**

```bash
git add docs/superpowers/audits/2026-05-13-portal-full-audit-report.md
# (если screenshot directory ещё не committed)
git add audit-screens/2026-05-13/ 2>/dev/null
git commit -m "$(cat <<'EOF'
docs(audit): finalize 2026-05-13 portal full audit (report + screens)

14-phase audit на main 21262ef post-merge plan5→main, hybrid fix-policy.

Findings: P0=<N>, P1=<N>, P2=<N>, P3=<N>. Fixed: <N> P0+P1 atomic commits.
Deferred: <N> P2/P3 в findings.md only. Blocked: <N> Q-items в blocked.md.

Verdict: <emoji>.

Final regression baseline: Pest <X>/<Y>/<Z>/<W>, Vitest <A>f/<B>/<C>sk,
Vite <T>s/0err, Histoire <S>/<V>.

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

### Task F.4: Pre-push verification

- [ ] **Step 1: Manual lefthook pre-push run**

Run: `npx lefthook run pre-push`

Expected:

- gitleaks-full-history: 0 leaks, all commits scanned.
- lychee-links: 0 broken (новые audit-docs все ссылки relative и валидны).

Если fail — investigate (≥3 гипотезы) + fix перед push.

### Task F.5: Push на origin/main

- [ ] **Step 1: Push**

Run: `git push origin main`

Expected: lefthook pre-push runs (повторно) — clean. Push success.

- [ ] **Step 2: Verify remote state**

Run: `git log origin/main --oneline -5`

Expected: HEAD matches local HEAD.

---

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

**1. Spec coverage:**

| Spec section | Plan task(s) | Gap? |
|---|---|---|
| §4 Phase 0 Pre-flight | Task 0.1-0.4 | ✅ |
| §4 Phase 1 Static analysis ×4 subagents | Task 1.1-1.2 | ✅ |
| §4 Phase 2 Test suites | Task 2.1-2.6 | ✅ |
| §4 Phase 3 Schema integrity | Task 3.1-3.2 | ✅ |
| §4 Phase 4 Security + methodology gap | Task 4.1-4.5 | ✅ |
| §4 Phase 5 UI smoke 24 views + CTO-19 verify | Task 5.1-5.4 | ✅ |
| §4 Phase 6 Cross-doc | Task 6.1-6.5 | ✅ |
| §4 Phase 7 Categorize | Task 7.1-7.3 | ✅ |
| §4 Phase 8 Fix loop hybrid | Task 8.N template | ✅ |
| §4 Phase 9 Regression | Task 9.1-9.7 | ✅ |
| §4 Phase 10 Live Pa11y + axe-core | Task 10.1-10.3 | ✅ |
| §4 Phase 11 TODO sweep | Task 11.1-11.2 | ✅ |
| §4 Phase 12 Bundle analyzer | Task 12.1-12.2 | ✅ |
| §4 Phase 13 Vitest coverage | Task 13.1-13.2 | ✅ |
| §4 Phase 14 Pre-prod readiness 8 sub-tasks | Task 14.1-14.9 | ✅ |
| §6 Verification gates | Каждый Phase commit step | ✅ |
| §7 Lessons-applied (5 guardrails) | Inline в Phase 4/5/9/10 | ✅ |
| §8 Decision-tree hard-stops | Phase 7 BLOCKED bucket + Pravila reference inline | ✅ |
| §9 Baseline metrics | Phase 2 capture + Phase 9 verify | ✅ |
| §11 Success criteria | Task F.1-F.5 | ✅ |

**2. Placeholder scan:** ✅ нет «TBD», «implement later», `<N>` plot placeholders — это template-vars которые заполняются в ходе execution из real data, не плейсхолдеры дизайна. Каждый шаг имеет concrete tool/command/expected output.

**3. Type consistency:** ✅

- `audit-screens/2026-05-13/` paths consistent.
- `findings.md` / `blocked.md` / `report.md` filenames consistent.
- Subagent prompt cwd paths consistent (`c:\моя\проекты\портал crm\Документация\app`).
- Baseline metrics (742/739/0/3 Pest, 88/683/3 Vitest, 35/63 Histoire) consistent с spec section 9.

**4. Relative paths (Pravila v1.12 §4.7 п.4):** ✅

- `../specs/...` для spec link (one up from plans/ — correct).
- `../../../app/...` для app refs (3 up: plans/ → superpowers/ → docs/ → root).
- `../audits/...` для audit references.

---

*План готов. Total phases: 14 + finalization. Total tasks: ~50+. Все verifiable steps с concrete commands + expected output.*
