app-analyzer-optimizer ยท diff

git:20260726.8401a15 to git:20260729.c8863c0

159 added, 54 removed. Audit A to A.

---
name: app-analyzer-optimizer
description: "Deeply analyzes application architecture and structure to perform audit, bottleneck detection, and code/performance optimization / Mempelajari arsitektur dan struktur aplikasi secara mendalam untuk melakukan audit, deteksi bottleneck, serta optimasi performa dan kode."
author: "Roedy Rustam"
---
- # App Analyzer & Optimizer (2026 Master Edition)
+ # App Analyzer & Optimizer (2026 Edition)
[English](#english) | [Bahasa Indonesia](#bahasa-indonesia)
---
<a name="english"></a>
## English
### Description
- Master auditing and optimization skill instructing the agent to deeply analyze application structure, multi-language architecture, dependencies, performance, and security across the entire codebase. It safely executes targeted optimizations by orchestrating guidelines from all active `vibes-plug` specialized skills.
+ Deep application analysis and optimization skill. Performs architectural audits, bottleneck detection, bundle analysis, database query profiling, and AI-assisted code review across Next.js, React, Node.js, Go, Python, and Rust applications.
- ### Instructions
+ ### Trigger Conditions
+ - Auditing an existing codebase for architectural issues or technical debt.
+ - Detecting performance bottlenecks (slow API routes, large bundles, N+1 queries).
+ - Analyzing bundle size and suggesting code splitting opportunities.
+ - Reviewing code quality (complexity, duplication, dead code).
+ - Using AI-assisted tools to accelerate code review and analysis.
- #### 1. Deep Analysis & Audit Protocol
- Before making any code changes or optimizations, run the following auditing steps:
- - **Application Structure & Monorepo Mapping**: Explore directory trees, Turborepo / pnpm workspace dependencies, frontend/backend separation, and asset organization (`monorepo-architect`).
- - **Build & Ecosystem Configuration Review**:
- - Inspect `package.json`, `tsconfig.json`, `next.config.js`, `vite.config.ts`, `Cargo.toml`, `go.mod`, `pyproject.toml` (`uv`).
- - Align tech stack with modern 2026 ecosystem standards (React 19, Next.js 15, Tailwind v4 `@theme`, Node 22 LTS, Bun 1.2+, Python 3.12+ PEP 695, Go 1.23+, Rust 2024 / v1.85+, Expo SDK 52+, Tauri v2).
- - **Bottleneck & Security Audit**:
- - **Frontend / UI**: Check Core Web Vitals (LCP, INP, CLS), bundle size, render loops, and WCAG 2.2 AAA accessibility compliance (`design-system-architect`, `senior-frontend`).
- - **Backend / APIs**: Audit memory leaks, unhandled async promises, Event Loop blocking, ORM N+1 queries, and connection poolers (`js-backend-expert`, `go-programming-expert`, `python-programming-expert`, `rust-programming-expert`).
- - **AI / MCP Systems**: Audit MCP server tools for input parameter validation (Zod/Pydantic), permission boundaries, and recursion limits in multi-agent state graphs (`mcp-server-architect`, `multi-agent-orchestration`).
- - **Security & RLS**: Review PostgreSQL Row-Level Security (RLS), Supabase policies, Firebase Security Rules, CORS, and CSP headers (`supabase-security-expert`, `firebase-security-expert`, `saas-multi-tenant`).
+ ### Analysis Protocol (5 Phases)
- #### 2. Optimization Alignment Across Vibes-Plug Skills
- Execute optimizations based on matching guidelines from active skills:
- - **Design & UI**: Align styling with `tailwind-expert` (CSS-first, OKLCH, responsive modifiers) and `design-system-architect` (Radix/Base UI headless primitives, CVA, ARIA roles).
- - **State & Data Fetching**: Optimize query key factories, `useSuspenseQuery`, and optimistic mutations via `tanstack-query-expert`.
- - **Architecture & Clean Code**: Apply SOLID, DRY, Clean Architecture, and loose coupling via `scalability-clean-code`.
- - **SEO & GEO**: Enhance Generative Engine Optimization for AI Overviews, Perplexity, ChatGPT Search, JSON-LD schemas, and `/llms.txt` via `seo` and `seo-geo`.
- - **Session Protection**: If performing large-scale multi-file refactoring, save a `STATE_HANDOFF.md` checkpoint via `session-handoff-resume` before switching sessions or accounts.
+ #### Phase 1: Architecture Discovery
+ ```bash
+ # Map the entire project structure
+ find . -type f -name "*.ts" -o -name "*.tsx" -o -name "*.go" | head -100
+ # Count lines per file (find largest files)
+ find . -name "*.ts" -exec wc -l {} + | sort -rn | head -20
+ # Find circular dependencies (TypeScript/JS)
+ npx madge --circular --extensions ts,tsx src/
+ ```
- #### 3. Safe Optimization Workflow
- 1. **Create Initial Audit Report**: Document weaknesses, redundancies, and proposed refactoring in an audit proposal.
- 2. **Incremental Implementation**: Apply changes modularly (one component/module at a time) to prevent breaking changes.
- 3. **Validation & Benchmarking**:
- - Run unit tests (`vitest`, `pytest`, `go test`), build tests, or linters (`Ruff`, `ESLint`).
- - Run Playwright E2E specs (`e2e-testing-expert`) or fuzz tests (`secure-fuzz-testing`).
- 4. **Auto-Documentation**: Invoke `auto-doc-updater` to automatically write optimization changes to `CHANGELOG.md` and `BLUEPRINT.md`.
+ #### Phase 2: Bundle Analysis (Next.js / Vite)
+ ```bash
+ # Next.js bundle analyzer
+ ANALYZE=true next build
+ # Or install dedicated tool
+ npx @next/bundle-analyzer
+
+ # Vite bundle visualization
+ npx vite-bundle-visualizer
+
+ # Check for duplicate dependencies
+ npx depcheck
+ npx bundle-phobia-cli check package.json
+ ```
+
+ Key bundle red flags:
+ - Any single chunk > 500KB (uncompressed).
+ - Importing entire libraries (`import _ from 'lodash'` vs `import debounce from 'lodash/debounce'`).
+ - Moment.js (replace with `date-fns` or `Temporal`).
+ - `node_modules` leaking into client bundle.
+
+ #### Phase 3: Database Query Analysis
+ ```sql
+ -- PostgreSQL: Find slow queries
+ SELECT query, mean_exec_time, calls, total_exec_time
+ FROM pg_stat_statements
+ ORDER BY mean_exec_time DESC
+ LIMIT 20;
+
+ -- Find missing indexes (sequential scans on large tables)
+ SELECT schemaname, tablename, attname, n_distinct, correlation
+ FROM pg_stats
+ WHERE tablename = 'your_table'
+ ORDER BY n_distinct DESC;
+
+ -- Detect N+1 queries: Enable query logging
+ -- In Drizzle:
+ const db = drizzle(client, { logger: true });
+ -- In Prisma:
+ DATABASE_URL="...?connection_limit=5" prisma studio
+ ```
+
+ #### Phase 4: AI-Assisted Code Review
+ Use AI tools to accelerate analysis:
+
+ | Tool | Purpose |
+ |---|---|
+ | **CodeRabbit** | Automated PR review, pattern detection |
+ | **Sourcegraph Cody** | Codebase-wide semantic search and explanation |
+ | **GitHub Copilot** | Inline suggestions and refactoring |
+ | **Cursor / Windsurf** | AI IDE with full-repo context |
+
+ AI review prompts for Gemini Agent:
+ ```
+ Analyze all files in src/features/ and identify:
+ 1. Functions longer than 30 lines
+ 2. Duplicated business logic across files
+ 3. Missing error handling in async functions
+ 4. Components that directly call APIs (violating separation of concerns)
+ ```
+
+ #### Phase 5: Performance Profiling
+
+ **Frontend (React / Next.js):**
+ ```bash
+ # React DevTools Profiler โ€” identify render bottlenecks
+ # Chrome DevTools > Performance tab > Record interaction
+
+ # Lighthouse CI โ€” automated CWV tracking
+ npm install -g @lhci/cli
+ lhci autorun
+ ```
+
+ **Backend (Node.js):**
+ ```bash
+ # Built-in Node.js profiler
+ node --prof server.js
+ node --prof-process isolate-*.log > processed.txt
+
+ # Clinic.js โ€” flamegraph, bubble chart, doctor
+ npm install -g clinic
+ clinic doctor -- node server.js
+ clinic flame -- node server.js
+ ```
+
+ **Go:**
+ ```bash
+ # Built-in pprof profiler
+ go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
+ go tool pprof -http=:8080 profile.out
+ ```
+
+ ### Common Bottleneck Patterns & Fixes
+
+ | Bottleneck | Symptom | Fix |
+ |---|---|---|
+ | N+1 queries | DB calls proportional to list length | Add `.include()` / JOIN or DataLoader |
+ | Missing indexes | Slow queries on filtered columns | `CREATE INDEX CONCURRENTLY` |
+ | Unoptimized images | Large LCP, slow page load | Next.js `<Image>`, WebP, lazy loading |
+ | Over-fetching | Fetching full objects when only 1 field needed | Select specific columns |
+ | No pagination | Fetching entire tables | Add `LIMIT/OFFSET` or cursor pagination |
+ | Blocking main thread | High INP, unresponsive UI | `useTransition`, web workers |
+ | No caching | Same data fetched repeatedly | Redis, React Query staleTime, HTTP cache |
+ | Bundle bloat | Large JS payload | Tree-shaking, code splitting, lazy imports |
+
---
<a name="bahasa-indonesia"></a>
## Bahasa Indonesia
### Deskripsi
- Skill master audit dan optimasi yang menginstruksikan agen untuk menganalisis struktur aplikasi, arsitektur multi-bahasa, dependensi, performa, dan keamanan di seluruh codebase secara mendalam. Skill ini melakukan optimasi terarah secara aman dengan mengorkestrasikan pedoman dari seluruh skill spesialis `vibes-plug`.
+ Skill analisis dan optimasi aplikasi mendalam. Melakukan audit arsitektur, deteksi bottleneck, analisis bundle, profiling query database, dan code review berbantuan AI di aplikasi Next.js, React, Node.js, Go, Python, dan Rust.
- ### Instruksi
+ ### Kondisi Pemicu
+ - Mengaudit codebase yang ada untuk masalah arsitektur atau hutang teknis.
+ - Mendeteksi bottleneck performa (rute API lambat, bundle besar, query N+1).
+ - Menganalisis ukuran bundle dan menyarankan peluang code splitting.
+ - Meninjau kualitas kode (kompleksitas, duplikasi, kode mati).
+ - Menggunakan tool berbantuan AI untuk mempercepat code review dan analisis.
- #### 1. Protokol Analisis Mendalam (Deep Analysis Protocol)
- Sebelum melakukan perubahan kode atau optimasi apa pun pada proyek, jalankan langkah-langkah audit berikut:
- - **Pemetaan Struktur Aplikasi & Monorepo**: Telusuri direktori, dependensi workspace pnpm/Turborepo, pembagian frontend/backend, dan organisasi aset (`monorepo-architect`).
- - **Analisis Konfigurasi Build & Ekosistem**:
- - Periksa `package.json`, `tsconfig.json`, `next.config.js`, `vite.config.ts`, `Cargo.toml`, `go.mod`, `pyproject.toml` (`uv`).
- - Selaraskan stack teknologi dengan standar 2026 (React 19, Next.js 15, Tailwind v4 `@theme`, Node 22 LTS, Bun 1.2+, Python 3.12+ PEP 695, Go 1.23+, Rust 2024 / v1.85+, Expo SDK 52+, Tauri v2).
- - **Deteksi Bottleneck & Isu Keamanan**:
- - **Frontend / UI**: Periksa Core Web Vitals (LCP, INP, CLS), ukuran bundle, loop render, dan kepatuhan aksesibilitas WCAG 2.2 AAA (`design-system-architect`, `senior-frontend`).
- - **Backend / API**: Audit memory leaks, unhandled async promises, blocking event loop, kueri ORM N+1, dan connection poolers (`js-backend-expert`, `go-programming-expert`, `python-programming-expert`, `rust-programming-expert`).
- - **Sistem AI / MCP**: Audit alat MCP Server untuk validasi parameter (Zod/Pydantic), batasan izin, dan batas rekursi pada graf agen (`mcp-server-architect`, `multi-agent-orchestration`).
- - **Keamanan & RLS**: Periksa Row-Level Security (RLS) PostgreSQL, Supabase, Firebase Security Rules, CORS, dan header CSP (`supabase-security-expert`, `firebase-security-expert`, `saas-multi-tenant`).
+ ### Protokol Analisis (5 Fase)
- #### 2. Penyelarasan Optimasi dengan Vibes-Plug Skills
- - **Desain & UI**: Sesuaikan layout dengan `tailwind-expert` (CSS-first, OKLCH, responsive modifiers) dan `design-system-architect` (Radix/Base UI headless primitives, CVA, ARIA roles).
- - **Pengelolaan State & Data Fetching**: Gunakan query key factory, `useSuspenseQuery`, dan mutasi optimistik dari `tanstack-query-expert`.
- - **Arsitektur & Kualitas Kode**: Terapkan prinsip SOLID, DRY, dan Clean Architecture dari `scalability-clean-code`.
- - **SEO & GEO**: Tingkatkan Generative Engine Optimization untuk AI Overviews, Perplexity, ChatGPT Search, JSON-LD, dan `/llms.txt` via `seo` dan `seo-geo`.
- - **Proteksi Sesi**: Jika melakukan refactoring skala besar, simpan checkpoint `STATE_HANDOFF.md` via `session-handoff-resume` sebelum berganti akun/sesi.
+ #### Fase 1: Penemuan Arsitektur
+ Petakan seluruh struktur proyek, hitung baris per file untuk menemukan file terbesar, dan deteksi dependensi circular dengan `npx madge --circular`.
- #### 3. Alur Kerja Optimasi Aman (Safe Optimization Workflow)
- 1. **Buat Laporan Audit Awal**: Dokumentasikan kelemahan, redundansi, dan usulan refactoring.
- 2. **Implementasi Inkremental**: Lakukan perubahan secara modular (satu file/komponen pada satu waktu) untuk menghindari breaking changes.
- 3. **Validasi & Benchmarking**:
- - Jalankan unit test (`vitest`, `pytest`, `go test`), build test, atau linter (`Ruff`, `ESLint`).
- - Jalankan Playwright E2E (`e2e-testing-expert`) atau fuzz testing (`secure-fuzz-testing`).
- 4. **Pencatatan Riwayat (Auto-Document)**: Gunakan `auto-doc-updater` untuk secara otomatis menulis perubahan optimasi ke `CHANGELOG.md` dan `BLUEPRINT.md`.
+ #### Fase 2: Analisis Bundle (Next.js / Vite)
+ Gunakan `ANALYZE=true next build` atau `npx vite-bundle-visualizer`. Tanda bahaya bundle: chunk tunggal > 500KB, mengimpor library penuh, Moment.js, atau `node_modules` yang bocor ke bundle klien.
+
+ #### Fase 3: Analisis Query Database
+ Gunakan `pg_stat_statements` untuk menemukan query lambat. Cari scan sequential pada tabel besar (tanda indeks yang hilang). Aktifkan logging query di Drizzle/Prisma untuk mendeteksi pola N+1.
+
+ #### Fase 4: Code Review Berbantuan AI
+ Gunakan CodeRabbit untuk review PR otomatis, Sourcegraph Cody untuk pencarian semantik seluruh codebase, dan Gemini Agent dengan prompt analisis spesifik untuk menemukan fungsi panjang, logika bisnis yang diduplikasi, dan error handling yang hilang.
+
+ #### Fase 5: Profiling Performa
+ - **Frontend**: React DevTools Profiler, Lighthouse CI.
+ - **Backend Node.js**: `node --prof`, Clinic.js untuk flamegraph.
+ - **Go**: `go tool pprof` untuk CPU dan memory profiling.
+
+ ### Pola Bottleneck Umum & Perbaikan
+
+ | Bottleneck | Gejala | Perbaikan |
+ |---|---|---|
+ | Query N+1 | Panggilan DB proporsional dengan panjang daftar | Tambahkan `.include()` / JOIN atau DataLoader |
+ | Indeks yang hilang | Query lambat pada kolom yang difilter | `CREATE INDEX CONCURRENTLY` |
+ | Gambar tidak dioptimalkan | LCP besar, halaman lambat | Next.js `<Image>`, WebP, lazy loading |
+ | Over-fetching | Mengambil objek penuh saat hanya 1 field dibutuhkan | Pilih kolom spesifik |
+ | Tanpa paginasi | Mengambil seluruh tabel | Tambahkan `LIMIT/OFFSET` atau cursor pagination |
+ | Memblokir thread utama | INP tinggi, UI tidak responsif | `useTransition`, web workers |
+ | Tanpa caching | Data yang sama diambil berulang kali | Redis, React Query staleTime, HTTP cache |
+ | Bundle membengkak | Payload JS besar | Tree-shaking, code splitting, lazy imports |