# Portal Full Audit #3 — 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-фазный аудит кодовой базы Лидерра портала на HEAD `08605cf`; закрыть все новые P0/P1 in-flight; задокументировать P2/P3 deferred; выпустить Audit #3 report.

**Architecture:** Pre-flight → ×4 parallel static-analysis subagents → sequential test/schema/security/UI-smoke/a11y/coverage/bundle/pre-prod/TODO sweeps → categorize → hybrid fix (P0+P1 only, atomic commits) → final regression → report. Каждая фаза пишет findings в `findings.md`. Blocked items → `blocked.md`. Summary → `report.md`.

**Tech Stack:** Laravel 13 / Pest 4 / Pint / Larastan / Vue 3 / Vuetify 3 / Vitest 4 / vue-tsc / ESLint / Prettier / knip / Histoire / Vite / Playwright MCP / Laravel Boost MCP / Redis MCP / gitleaks / lychee / markdownlint / cspell / squawk / Pa11y

**Hybrid fix policy:**

- `[FIX-NOW]` — P0/P1, fix ≤30 мин, один atomic commit per finding
- `[FIX-DEFER]` — P2/P3, только запись в findings.md, без кода
- `[BLOCKED]` — нужно явное «закрываем» от заказчика → `blocked.md`

**Baseline:** HEAD `08605cf` (origin/main, 2026-05-14)
**vs Audit #2:** `9e175a1` (+11 commits delta)
**Economy mode:** 0%

---

## Audit artefacts

- `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`
- `docs/superpowers/audits/2026-05-14-portal-full-audit-blocked.md`
- `docs/superpowers/audits/2026-05-14-portal-full-audit-report.md`
- `docs/superpowers/audits/audit-screens/2026-05-14/` (Playwright screenshots)

---

### Task 1: Pre-flight — git state, delta, skeletons

**Files:**

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

- [ ] **Step 1: Verify branch и HEAD**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git rev-parse --abbrev-ref HEAD
git status
```

Expected: branch=`main`, HEAD=`08605cf`, 3 untracked files (parse-bundle-analyze.mjs / 2 plan docs).

- [ ] **Step 2: Delta commits с Audit #2 baseline `9e175a1`**

```powershell
git log --oneline 9e175a1..HEAD
```

Expected 11 commits:

```
08605cf fix(tests): Bus::fake partial + session mock — close quirk #72
9a45346 fix(tests): RefreshDatabase on LookupsTest + ProjectExtensionsTest — close quirk #62
7ee78a9 feat(docs): interactive automation graph — 73 nodes, 6 conflicts
9b21bbc docs(spec): automation graph design spec — vis.js Solarized dark
7007379 docs(plans): add test-quality-preprod sprint plan + fix lychee/cspell
bf84568 fix(a11y): add aria-label to VTooltip on /admin/tenants impersonate btn
b241c79 docs: add RUNBOOK.md — production deployment runbook
9530d17 fix(schedule): register partitions:create-months as daily cron
219f262 fix(test): ProjectFactory unique name + test:parallel composer alias
e280edd style(frontend): apply prettier --write — fix formatting drift (4 files)
58986a2 test(vitest): add testTimeout: 10000 — fix quirk #80 router.spec.ts coverage timeout
```

- [ ] **Step 3: Composer install check**

```powershell
cd "C:\моя\проекты\портал crm\Документация\app"
composer install 2>&1 | Select-Object -Last 3
```

Expected: `Nothing to install...` exit 0.

- [ ] **Step 4: npm install check (квирк 74 — `--legacy-peer-deps` обязателен)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm install --legacy-peer-deps 2>&1 | Select-Object -Last 5
```

Expected: `up to date, 0 vulnerabilities` exit 0.

- [ ] **Step 5: Создать 3 skeleton файла**

Создать `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`:

```markdown
# Portal Full Audit #3 — Findings (2026-05-14)

> **Связано:** план `../plans/2026-05-14-portal-full-audit-3.md`, blocked `2026-05-14-portal-full-audit-blocked.md`, report `2026-05-14-portal-full-audit-report.md`
> **HEAD:** `main` `08605cf`
> **vs Audit #2:** `9e175a1` (+11 commits delta)
> **Режим:** экономия 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

## Hybrid fix policy
- `[FIX-NOW]` — P0/P1, atomic commit
- `[FIX-DEFER]` — P2/P3, только запись здесь
- `[BLOCKED]` — нужно явное «закрываем» → `blocked.md`
```

Создать `docs/superpowers/audits/2026-05-14-portal-full-audit-blocked.md`:

```markdown
# Portal Full Audit #3 — Blocked Items (2026-05-14)

Нет открытых blocked items.
```

Создать `docs/superpowers/audits/2026-05-14-portal-full-audit-report.md`:

```markdown
# Portal Full Audit #3 — Summary Report (2026-05-14)

> **HEAD start:** `main` `08605cf`
> **Режим:** экономия 0%
> *(Заполняется в Task 14)*
```

- [ ] **Step 6: Commit skeletons**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git rev-parse --abbrev-ref HEAD
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git add docs/superpowers/audits/2026-05-14-portal-full-audit-blocked.md
git add docs/superpowers/audits/2026-05-14-portal-full-audit-report.md
git commit -m "docs(audit): Phase 0 pre-flight skeletons (audit #3)"
```

Expected: HEAD moves to new commit on `main`.

---

### Task 2: Static analysis ×4 parallel subagents

Dispatch 4 subagents параллельно. Каждый пишет raw output + findings в Phase 1 секцию findings.md.

#### Subagent A — Backend: Pint + Larastan + composer audit

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Pint check**

```powershell
cd "C:\моя\проекты\портал crm\Документация\app"
composer pint:test 2>&1
```

Expected: `{"tool":"pint","result":"passed"}` exit 0. Если exit 1 → список файлов → P2 `[FIX-NOW]` если ≤5 файлов, иначе `[FIX-DEFER]`.

- [ ] **Step 2: Larastan**

```powershell
composer stan 2>&1
```

Expected: `{"tool":"phpstan","result":"passed","errors":0}` exit 0. Любая ошибка = P1 `[FIX-NOW]`.

- [ ] **Step 3: composer audit**

```powershell
composer audit --locked 2>&1
```

Expected: `No security vulnerability advisories found.` Любой CVE = P0 `[FIX-NOW]`.

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

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: ESLint**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run lint:vue 2>&1
```

Expected: empty stdout, exit 0. Любая ошибка = P1 `[FIX-NOW]`.

- [ ] **Step 2: vue-tsc**

```powershell
npx vue-tsc --noEmit 2>&1
```

Expected: нет вывода, exit 0. Любая type error = P1 `[FIX-NOW]`.

- [ ] **Step 3: Prettier check на реальных (не генерированных) файлах**

```powershell
npx prettier --check "app/resources/**/*.{ts,vue}" "app/tests/**/*.{ts,php}" "app/routes/**/*.php" "app/app/**/*.php" 2>&1
```

Expected: ≤4 mismatches (Audit #2 в `e280edd` исправил 4 файла; проверяем что дрейфа нет). Если >0 → P2 `[FIX-DEFER]`, задокументировать количество vs Audit #2 baseline.

- [ ] **Step 4: knip** (проверяем что lucide false-positive не исправлен — это ожидаемо)

```powershell
npx knip 2>&1 | Select-Object -First 50
```

Expected: только известный false-positive `lucide-vue-next` (dynamic IconSet в vuetify.ts:19). Любой новый unused export = P2 `[FIX-DEFER]`.

#### Subagent C — Docs: markdownlint + cspell + lychee

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: markdownlint**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run lint:md 2>&1
```

Expected: 0 ошибок (Audit #2 baseline = 0). Любые новые = P2 `[FIX-NOW если ≤5 мин]`.

- [ ] **Step 2: cspell**

```powershell
npm run spell 2>&1 | Select-Object -Last 10
```

Expected: 0 issues (Audit #2 baseline = 0). Новые опечатки из 11-commit delta = P2 `[FIX-NOW]`, добавить в `cspell-words.txt`.

- [ ] **Step 3: lychee**

```powershell
npm run links 2>&1 | Select-Object -Last 20
```

Expected: 0 broken links. Audit #2 baseline: 318 OK / 0 errors. Любые новые broken links = P2 `[FIX-NOW если ≤15 мин]`.

#### Subagent D — SQL: squawk + pgFormatter

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: squawk**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npx squawk 2>&1 | Select-Object -Last 20
```

Expected: 0 issues (Audit #2 baseline = 0).

- [ ] **Step 2: pgFormatter dry-run diff count**

```powershell
pg_format --dry-run db/schema.sql 2>&1 | Measure-Object -Line
```

Expected: ~6284 diff lines (Q.HARD.002 defer из Audit #2 — large-schema auto-format). Если меньше → прогресс, задокументировать.

- [ ] **Step 3: Записать Phase 1 findings в findings.md и commit**

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

---

### Task 3: Test suites

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Pest --parallel (baseline match)**

```powershell
cd "C:\моя\проекты\портал crm\Документация\app"
composer test:parallel 2>&1
```

Expected: `742 tests, 739 passed, 3 skipped, 0 failed`.
Полный вывод показать в findings. Если failed ≠ 0 → P1 `[FIX-NOW]` — investigate с ≥3 гипотезами (quirks 62/72 должны быть закрыты).

- [ ] **Step 2: Pest sequential**

```powershell
composer test 2>&1
```

Expected: `742 tests, 739 passed, 3 skipped, 0 failed` (quirk #62 fix в `9a45346` должен держать). Если fails → P1 `[FIX-NOW]`.

- [ ] **Step 3: Vitest**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run test:vue 2>&1
```

Expected: `88 files / 683 passed / 3 skipped` (Audit #2 baseline). Любые новые failures = P1 `[FIX-NOW]`.

- [ ] **Step 4: Histoire build**

```powershell
npm run story -- --build 2>&1 | Select-Object -Last 10
```

Expected: `35 stories / 63 variants` build OK. Failure = P1 `[FIX-NOW]`.

- [ ] **Step 5: Vite build**

```powershell
npm run build 2>&1 | Select-Object -Last 10
```

Expected: success, ~2–3.5s, 0 errors. Любая build error = P1 `[FIX-NOW]`.

- [ ] **Step 6: Записать Phase 2 findings + commit**

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

---

### Task 4: Schema integrity (Boost MCP)

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Root table count**

Boost MCP `database-query`:

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

Expected: 61 (Audit #2 dev-actual). Если ≠ 61 → разобраться; если добавились новые таблицы не из схемы → P1.

- [ ] **Step 2: RLS policies count (invariant)**

```sql
SELECT count(*) AS rls_policies
FROM pg_policies
WHERE schemaname = 'public';
```

Expected: **39** (строгий инвариант). Если ≠ 39 → P1 `[FIX-NOW]`.

- [ ] **Step 3: User functions — имена (invariant)**

```sql
SELECT proname FROM pg_proc
JOIN pg_namespace ON pg_namespace.oid = pg_proc.pronamespace
WHERE nspname = 'public' AND prokind = 'f'
ORDER BY proname;
```

Expected ровно 5: `audit_block_mutation`, `audit_chain_hash`, `calc_lead_score`, `report_jobs_log_export`, `set_pd_subject_request_deadline`. Любое отклонение = P1.

- [ ] **Step 4: Orphan FK check**

```sql
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
    ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage ccu
    ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
  AND ccu.table_name NOT IN (
      SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'
  );
```

Expected: 0 rows. Любой orphan FK = P0 `[FIX-NOW]`.

- [ ] **Step 5: Проверить schema.sql header drift (Audit #2 P2 open item)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
Select-String -Path db/schema.sql -Pattern "v8\." | Select-Object -First 3
```

Проверить: был ли обновлён header в 11-commit delta. Если header всё ещё показывает старые метрики (62/117/13) → P2 `[FIX-DEFER]` (тот же что в Audit #2).

- [ ] **Step 6: Записать Phase 3 findings + commit**

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

---

### Task 5: Security

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Enumerate CI workflows (methodology: `ls .github/workflows/` FIRST)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
Get-ChildItem .github/workflows/
```

Expected: `sast.yml`, `dependency-check.yml`, `trivy.yml`. Задокументировать список.

- [ ] **Step 2: Gitleaks delta scan (11 новых коммитов)**

```powershell
./bin/gitleaks.exe detect --source . --log-opts="9e175a1..HEAD" 2>&1
```

Expected: 0 leaks. Любой leak = P0 `[FIX-NOW]`.

- [ ] **Step 3: Gitleaks full history scan**

```powershell
./bin/gitleaks.exe detect --source . 2>&1 | Select-Object -Last 5
```

Expected: 0 leaks / ~419 commits (Audit #2 baseline: 0/401).

- [ ] **Step 4: No-git scan app/**

```powershell
./bin/gitleaks.exe detect --source app/ --no-git 2>&1 | Select-Object -Last 5
```

Expected: 0 secrets.

- [ ] **Step 5: Записать Phase 4 findings + commit**

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

---

### Task 6: UI smoke (Playwright MCP — 24-view sweep)

**Files:**

- Modify: `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`
- Create: `docs/superpowers/audits/audit-screens/2026-05-14/` (screenshots)

Перед smoke: убедиться что dev-сервер запущен (`php artisan serve` на :8000 + `npm run dev`).

- [ ] **Step 1: Запустить dev-сервер (если не запущен)**

```powershell
# В отдельном терминале:
cd "C:\моя\проекты\портал crm\Документация\app"
php artisan serve --port=8000
# И в другом:
cd "C:\моя\проекты\портал crm\Документация"
npm run dev
```

Проверить: `http://localhost:8000/login` доступен.

- [ ] **Step 2: Login + screenshot**

Playwright MCP `browser_navigate` → `http://localhost:8000/login`
Playwright MCP `browser_take_screenshot` → `audit-screens/2026-05-14/01-login.png`
Playwright MCP `browser_fill_form` (email + password) + `browser_click` submit
Expected: редирект на `/dashboard`. `browser_take_screenshot` → `02-dashboard.png`.

- [ ] **Step 3: Sweep аутентифицированных views**

Для каждого из 24 маршрутов (источник: `routes/web.php`):
`/dashboard`, `/projects`, `/reminders`, `/notifications`, `/profile`, `/billing`, `/admin/tenants`, `/admin/billing`, `/admin/pricing-tiers`, `/admin/supplier-prices`, `/admin/incidents`, `/admin/system`, `/login`, `/register`, `/2fa`, `/forgot`, `/recovery`

Для каждого:

- `browser_navigate` → URL
- `browser_take_screenshot` → `NN-<view>.png`
- Проверить: страница рендерится (не blank), 0 JS error в console, Lucide иконки видны
- DevIndexBadge не должен быть виден (должен tree-shaken в prod build; если dev-сервер — может присутствовать, задокументировать)

- [ ] **Step 4: Error views**

Navigate → `/this-page-does-not-exist` → check 404 page.
Navigate → любой protected route без auth (logout сначала) → check redirect.
`browser_take_screenshot` → `25-404.png`

- [ ] **Step 5: Logout flow**

Кликнуть logout button или navigate `/logout`.
Expected: redirect на `/login`.

- [ ] **Step 6: Записать Phase 5 findings + commit**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git add docs/superpowers/audits/audit-screens/2026-05-14/
git commit -m "docs(audit): Phase 5 UI smoke 24-view Playwright sweep (audit #3)"
```

---

### Task 7: Cross-doc integrity

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Проверить версии нормативных документов**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
(Select-String -Path CLAUDE.md -Pattern "Версия:").Line | Select-Object -First 1
(Select-String -Path docs/Pravila_raboty_Claude_v1_1.md -Pattern "^# ").Line | Select-Object -First 1
(Select-String -Path docs/Plugin_stack_rules_v1.md -Pattern "^# ").Line | Select-Object -First 1
(Select-String -Path docs/Tooling_v8_3.md -Pattern "^# ").Line | Select-Object -First 1
(Select-String -Path "docs/Открытые_вопросы_v8_3.md" -Pattern "^# ").Line | Select-Object -First 1
```

Expected:

- CLAUDE.md: v1.92 от 13.05.2026
- Pravila: v1.13 от 13.05.2026
- PSR_v1: v2.1 от 13.05.2026
- Tooling: v1.17 от 13.05.2026
- Реестр: v1.83 от 13.05.2026

Любое несоответствие с memory → P2 `[FIX-DEFER]`.

- [ ] **Step 2: Verify schema.sql version marker**

```powershell
Select-String -Path db/schema.sql -Pattern "v8\." | Select-Object -First 3
```

Expected: `v8.20` (Audit #2 baseline). Если другое — задокументировать.

- [ ] **Step 3: routes/web.php completeness**

```powershell
Select-String -Path app/routes/web.php -Pattern "Route::view" | Measure-Object
cat app/routes/web.php
```

Expected: 26+ явных `Route::view` + fallback + SPA-catch-all. Проверить что все известные views присутствуют.

- [ ] **Step 4: Verify .mcp.json servers**

```powershell
cat .mcp.json
```

Expected: 5 servers: `laravel-boost`, `playwright`, `github`, `sentry`, `redis`. Если какого нет → P2.

- [ ] **Step 5: Записать Phase 6 findings + commit**

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

---

### Task 8: A11y targeted — Pa11y + axe-core P3 follow-up

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Pa11y 4 guest URLs**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run a11y 2>&1
```

Expected: `No issues found!` на всех 4 guest URLs. Регрессия = P1 `[FIX-NOW]`.

- [ ] **Step 2: axe-core verify aria-label fix на /admin/tenants (bf84568)**

Playwright MCP (залогиненным как admin) `browser_navigate` → `http://localhost:8000/admin/tenants`
`browser_evaluate`:

```javascript
const { default: axe } = await import('https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.0/axe.min.js');
await new Promise(r => setTimeout(r, 500));
const results = await axe.run();
return results.violations.filter(v => v.id === 'aria-tooltip-name').map(v => ({ id: v.id, count: v.nodes.length, help: v.help }));
```

Expected: `[]` — 0 `aria-tooltip-name` violations (bf84568 fix должен держать). Если violation вернулся → P1 `[FIX-NOW]`.

- [ ] **Step 3: axe-core full scan /admin/tenants — все violations**

```javascript
const { default: axe } = await import('https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.0/axe.min.js');
await new Promise(r => setTimeout(r, 500));
const results = await axe.run();
return results.violations.map(v => ({ id: v.id, impact: v.impact, count: v.nodes.length, help: v.help }));
```

Задокументировать полный список violations. P3 known items из Audit #2: `region` (sitewide) + `empty-table-header` + `page-has-heading-one`. Любое новое critical/serious = P1 `[FIX-NOW]`.

- [ ] **Step 4: axe-core scan /dashboard + /projects (проверка P3 drift)**

Аналогично Step 3, на двух ключевых authenticated views. Задокументировать любое изменение vs Audit #2 P3 baseline.

- [ ] **Step 5: Записать Phase 7 a11y findings + commit**

```powershell
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 7 a11y targeted Pa11y+axe-core (audit #3)"
```

---

### Task 9: Coverage targeted (Vitest --coverage)

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Запустить coverage (quirk #80 fix `testTimeout:10000` должен держать)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run test:vue -- --coverage 2>&1
```

Показать полный вывод. Expected: 0 timeouts (quirk #80 закрыт в `58986a2`). Totals ≥ Audit #2 baseline:

- Stmts: ≥78.30%
- Branch: ≥75.78%
- Funcs: ≥70.12%
- Lines: ≥80.47%

Любое падение ниже baseline → P2 `[FIX-DEFER — coverage regression]`.

- [ ] **Step 2: Check known P2 low-coverage files**

Из coverage output найти:

- `ReminderDialog.vue` — Audit #2 baseline: 0%. Текущее %? Если всё ещё 0% → P2 `[FIX-DEFER — нужен новый spec]`.
- `AdminLayout.vue` — Audit #2 baseline: 9%. Текущее %?
- `api/admin.ts` — Audit #2 baseline: 11%. Текущее %?

Задокументировать дельту по каждому.

- [ ] **Step 3: Записать Phase 8 findings + commit**

```powershell
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 8 coverage targeted (audit #3)"
```

---

### Task 10: Bundle analyzer delta

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Build с visualizer (если не был только что запущен в Task 3)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run build -- --config app/vite.config.ts 2>&1 | Select-Object -Last 10
```

Expected: success. Проверить что `app/storage/bundle-analyze.html` обновился.

- [ ] **Step 2: Запустить parse-bundle-analyze.mjs**

```powershell
node app/scripts/parse-bundle-analyze.mjs 2>&1
```

Expected: Top-15 chunks table + Critical-path eager total. Audit #2 baseline: ~189 kB gzip.
Задокументировать: top-5 chunks + eager total gzip/brotli. Если eager total вырос >10 kB vs baseline → P2 `[FIX-DEFER — bundle bloat]`.

- [ ] **Step 3: Записать Phase 9 findings + commit**

```powershell
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 9 bundle analyzer delta (audit #3)"
```

---

### Task 11: Pre-prod gaps + TODO sweep + untracked files

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Verify partitions:create-months в schedule**

```powershell
cd "C:\моя\проекты\портал crm\Документация\app"
php artisan schedule:list 2>&1 | Select-String "partition"
```

Expected: `partitions:create-months` appears (закрыто `9530d17`). Если нет → P1 `[FIX-NOW]`.

- [ ] **Step 2: Verify RUNBOOK.md**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
Measure-Object -InputObject (Get-Content RUNBOOK.md -Raw) -Line
Select-String -Path RUNBOOK.md -Pattern "^## " | Select-Object -First 15
```

Expected: 100+ строк, 13 секций (закрыто `b241c79`). Если файл не найден → P1 `[FIX-NOW]`.

- [ ] **Step 3: .env.example full diff (Audit #2 Phase 14.5 был unverified)**

```powershell
cat app/.env.example | Measure-Object -Line
cat app/.env.example
```

Expected: ~80 key-value pairs. Проверить наличие критических групп: `APP_*`, `DB_*`, `REDIS_*`, `MAIL_*`, `QUEUE_*`, `SENTRY_*`. Если critical группа отсутствует → P2 `[FIX-DEFER]`.

- [ ] **Step 4: Sentry prod SDK статус**

```powershell
cd app
composer show sentry/sentry-laravel 2>&1
```

Expected: `Package sentry/sentry-laravel not found` → P2 `[FIX-DEFER pending Б-1]` (без изменений vs Audit #2).

- [ ] **Step 5: TODO/FIXME sweep**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
Select-String -Path app/app/, app/resources/ -Pattern "TODO|FIXME|HACK|XXX" -Recurse -Include "*.php", "*.vue", "*.ts" | Measure-Object
Select-String -Path app/app/, app/resources/ -Pattern "TODO|FIXME|HACK|XXX" -Recurse -Include "*.php", "*.vue", "*.ts"
```

Audit #2 baseline: 19 matches. Задокументировать delta. Любой новый TODO не связанный с Б-1 = P2 `[FIX-DEFER]`.

- [ ] **Step 6: Commit 3 untracked files (все полезные — закоммитить)**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git rev-parse --abbrev-ref HEAD
git add app/scripts/parse-bundle-analyze.mjs
git add docs/superpowers/plans/2026-05-13-automation-graph.md
git add docs/superpowers/plans/2026-05-13-pest-p1-quirks-fix.md
git commit -m "docs: commit untracked audit+plan artefacts (parse-bundle-analyze.mjs + 2 plan docs)"
```

- [ ] **Step 7: Записать Phase 10-12 findings + commit**

```powershell
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 10-12 pre-prod/TODO/untracked findings (audit #3)"
```

---

### Task 12: Categorize + fix loop (P0+P1 only)

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Подсчитать findings по severity**

Просмотреть все Phase 1-12 entries в findings.md. Составить rollup:

```
P0: N
P1: N
P2: N
P3: N
FIX-NOW eligible (P0+P1): list
```

Сравнить vs Audit #2: P0=0 / P1=5 / P2=15 / P3=18+.

- [ ] **Step 2: Если P0 найдены — fix немедленно**

Для каждого P0:

1. Понять root cause (≥3 гипотезы per `systematic-debugging`)
2. Написать failing test
3. Реализовать fix
4. Прогнать `composer test:parallel` → должен быть 0 failed
5. `git commit -m "fix: [description] (audit #3 P0)"`

- [ ] **Step 3: Если P1 FIX-NOW найдены — fix каждый атомарно**

Для каждого P1 `[FIX-NOW]`:

1. Один atomic commit per finding
2. После каждого: `composer test:parallel && npm run test:vue`
3. Шаблон commit: `fix: [description] — audit #3 P1`

**Ожидаемые кандидаты P1 (если появятся):**

*Larastan error (example):*

```php
// В app/app/SomeClass.php
// Исправить конкретный type annotation per Larastan output
```

*vue-tsc error (example):*

```typescript
// В app/resources/js/SomeComponent.vue
// Исправить конкретный type error per vue-tsc output
```

*Pest failure (unexpected):*

```
// Прогнать в isolation: composer test -- --filter "TestName"
// Найти root cause (quirk? regression?) → fix
```

- [ ] **Step 4: Обновить findings.md после fix loop**

Пометить каждый закрытый P1 как `[FIX-NOW ✅ fixed in <commit-hash>]`.

---

### Task 13: Final regression

**Files:** Modify `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`

- [ ] **Step 1: Full Pest --parallel**

```powershell
cd "C:\моя\проекты\портал crm\Документация\app"
composer test:parallel 2>&1
```

Expected: `742/739/3sk/0 failed`. Показать полный вывод. Если failed > 0 → STOP, investigate, fix до репорта.

- [ ] **Step 2: Full Vitest**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
npm run test:vue 2>&1
```

Expected: `88/683/3sk`. Показать полный вывод.

- [ ] **Step 3: Vite build**

```powershell
npm run build 2>&1 | Select-Object -Last 5
```

Expected: success, 0 errors.

- [ ] **Step 4: gitleaks delta (все audit commits)**

```powershell
./bin/gitleaks.exe detect --source . 2>&1 | Select-Object -Last 5
```

Expected: 0 leaks.

- [ ] **Step 5: lychee**

```powershell
npm run links 2>&1 | Select-Object -Last 5
```

Expected: 0 broken.

- [ ] **Step 6: Записать Phase 9 final regression + commit**

```powershell
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): Phase 9 final regression (audit #3)"
```

---

### Task 14: Report + memory update + push

**Files:**

- Modify: `docs/superpowers/audits/2026-05-14-portal-full-audit-report.md`
- Modify: `docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md`
- Create/Modify: `C:\Users\Administrator\.claude\projects\c---------------------crm-------------\memory\project_full_audit_2026-05-14.md`
- Modify: `C:\Users\Administrator\.claude\projects\c---------------------crm-------------\memory\project_state.md`
- Modify: `C:\Users\Administrator\.claude\projects\c---------------------crm-------------\memory\MEMORY.md`

- [ ] **Step 1: Написать итоговый report.md**

Заполнить `2026-05-14-portal-full-audit-report.md`:

```markdown
# Portal Full Audit #3 — Summary Report (2026-05-14)

## TL;DR

- **Findings:** N (P0: N, P1: N, P2: N, P3: N)
- **Fixed in code:** N atomic fix-commits
- **Deferred:** N P1 + N P2 + N P3 documented
- **Blocked Q-items:** 0
- **vs Audit #2:** [delta]

## По phase'ам (детали в findings.md)
[1-sentence per phase]

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

| Метрика | Phase 2 baseline | Audit #2 baseline | Delta |
|---|---|---|---|
| Pest --parallel | ... | 742/739/3sk | ... |
| Vitest | ... | 88/683/3sk | ... |
| Histoire | ... | 35/63 | ... |
| Vite build | ...s | ~2-3.5s | ... |
| ESLint | 0 | 0 | 0 |
| vue-tsc | 0 | 0 | 0 |
| Coverage Stmts/Branch/Funcs/Lines | ... | 78.30/75.78/70.12/80.47 | ... |
| gitleaks | 0 | 0/401 | ... |
| lychee | 0 | 0/318 | ... |
| RLS policies | 39 | 39 | 0 |

## Verdict

🟢/🟡/🔴 [reasoning]

## Commits made
[list]
```

- [ ] **Step 2: Update memory — project_full_audit_2026-05-14.md**

Создать `C:\Users\Administrator\.claude\projects\c---------------------crm-------------\memory\project_full_audit_2026-05-14.md` с результатами.

- [ ] **Step 3: Update memory — project_state.md**

Добавить секцию "Portal Full Audit #3 (2026-05-14)" с HEAD, metrics, open items.

- [ ] **Step 4: Update MEMORY.md index**

Добавить строку для нового memory файла audit #3.

- [ ] **Step 5: Финальный commit**

```powershell
cd "C:\моя\проекты\портал crm\Документация"
git rev-parse --abbrev-ref HEAD
git add docs/superpowers/audits/2026-05-14-portal-full-audit-report.md
git add docs/superpowers/audits/2026-05-14-portal-full-audit-findings.md
git commit -m "docs(audit): finalize portal full audit #3 — report (2026-05-14)"
```

- [ ] **Step 6: Push после user confirmation**

```powershell
git push origin main
```

Pre-push hooks: gitleaks-full-history + lychee. Expected: 0 leaks / 0 broken.

---

## Self-review

### Spec coverage

- ✅ Pre-flight (Task 1)
- ✅ Static analysis ×4 parallel (Task 2)
- ✅ Test suites Pest/Vitest/Histoire/Vite (Task 3)
- ✅ Schema integrity RLS/FK/functions (Task 4)
- ✅ Security gitleaks + CI workflows methodology (Task 5)
- ✅ UI smoke 24-view (Task 6)
- ✅ Cross-doc integrity normative docs (Task 7)
- ✅ A11y Pa11y + axe-core P3 follow-up (Task 8)
- ✅ Coverage targeted known P2 files (Task 9)
- ✅ Bundle analyzer delta vs Audit #2 (Task 10)
- ✅ Pre-prod gaps (schedule/RUNBOOK/.env/Sentry) (Task 11)
- ✅ TODO/FIXME sweep update (Task 11)
- ✅ Untracked files committed (Task 11)
- ✅ Categorize hybrid policy + fix loop P0/P1 (Task 12)
- ✅ Final regression all tools (Task 13)
- ✅ Report + memory + push (Task 14)

### Open P2 items carryforward из Audit #2 (tracked в этом плане)

- knip lucide false-positive → Task 2 Subagent B Step 4
- schema.sql header drift → Task 4 Step 5
- prettier drift (остаток 312-4=~38 файлов) → Task 2 Subagent B Step 3
- coverage debt ReminderDialog/AdminLayout/api/admin.ts → Task 9 Step 2
- KanbanView code-split candidate → Task 10 Step 2 (bundle delta)
- Sentry prod SDK → Task 11 Step 4
