diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 6cdebe40f..7ce05fb48 100644 --- a/.cursor-plugin/marketplace.json +++ b/.cursor-plugin/marketplace.json @@ -93,6 +93,11 @@ "source": "advisor", "description": "Consult a stronger model before major decisions, when stuck, and before declaring done." }, + { + "name": "vibes-plug", + "source": "vibes-plug", + "description": "Universal AI agent swarm architecture with 159 specialized skills, subagents, and anti-slop quality gates." + }, { "name": "gmail", "source": "third_party/gmail", diff --git a/README.md b/README.md index 6bd1a7797..82dd5591c 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Official Cursor plugins for popular developer tools, frameworks, and SaaS produc | `dyl-stack` | [dyl-stack](dyl-stack/) | Dylan Gattey | Developer Tools | Dylan's agent style on top of pstack: root causes over symptom patches, The Algorithm before design, terse verified delivery, a PR review that fits in a paste, and Figma-to-UI with a visual judge. | | `advisor` | [Advisor](advisor/) | Cursor | Developer Tools | Consult a stronger model before major decisions, when stuck, and before declaring done. | | `grok-voice` | [Grok Voice](grok-voice/) | Eric Zakariasson | Developer Tools | Add Grok voice to an app: realtime speech-to-speech, speech-to-text dictation, text-to-speech read-aloud, and a log-driven fix loop for voice sessions. | +| `vibes-plug` | [Vibes-Plug](vibes-plug/) | Roedy Rustam | Developer Tools | Universal AI agent swarm architecture with 159 specialized skills, subagents, and anti-slop quality gates. | | `gmail` | [Gmail](third_party/gmail/) | Cursor | Productivity | Search, read, draft, and manage email. | | `google-drive` | [Google Drive](third_party/google-drive/) | Cursor | Productivity | Search, read, create, and share files. | | `google-calendar` | [Google Calendar](third_party/google-calendar/) | Cursor | Productivity | Search events and schedule meetings. | diff --git a/vibes-plug/.cursor-plugin/plugin.json b/vibes-plug/.cursor-plugin/plugin.json new file mode 100644 index 000000000..2cbdbd936 --- /dev/null +++ b/vibes-plug/.cursor-plugin/plugin.json @@ -0,0 +1,35 @@ +{ + "name": "vibes-plug", + "displayName": "Vibes-Plug", + "version": "4.4.1", + "description": "Universal AI agent swarm architecture with 159 specialized skills, subagents, and anti-slop quality gates for fullstack, mobile, cloud, and agentic workflows.", + "author": { + "name": "Roedy Rustam", + "email": "roedyrustam.id@gmail.com" + }, + "homepage": "https://github.com/roedyrustam/vibes-plug", + "repository": "https://github.com/roedyrustam/vibes-plug", + "license": "MIT", + "logo": "assets/logo.png", + "keywords": [ + "ai", + "agent", + "mcp", + "skills", + "fullstack", + "fintech", + "zero-to-prod", + "anti-slop", + "swarm" + ], + "category": "developer-tools", + "tags": [ + "ai", + "swarm", + "skills", + "developer-tools" + ], + "skills": "./skills/", + "rules": "./rules/", + "agents": "./agents/" +} diff --git a/vibes-plug/LICENSE b/vibes-plug/LICENSE new file mode 100644 index 000000000..a0b3db18d --- /dev/null +++ b/vibes-plug/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Roedy Rustam + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vibes-plug/README.md b/vibes-plug/README.md new file mode 100644 index 000000000..6b96b4553 --- /dev/null +++ b/vibes-plug/README.md @@ -0,0 +1,54 @@ +# vibes-plug + +Universal AI agent swarm architecture with 159 specialized skills, subagents, and anti-slop quality gates for fullstack, mobile, cloud, and agentic workflows. + +## Overview + +`vibes-plug` acts as a primary trigger and master conductor for Cursor AI. It automatically classifies incoming tasks, binds cooperating domain skills, coordinates multi-agent subagent swarms, and enforces strict production quality and anti-slop standards without waiting for manual skill invocations. + +## Install + +```bash +/add-plugin vibes-plug +``` + +## Subagents + +Spawn specialized subagents directly using their `subagent_type`: + +| Subagent | Role & Focus | +|---|---| +| [`swarm-architect`](./agents/swarm-architect.md) | System discovery, PRD generation (`PRD.md`), Database ERD (`ERD.md`), and high-level architecture planning. | +| [`fullstack-craftsman`](./agents/fullstack-craftsman.md) | Fullstack implementation across React 19, Next.js 15 App Router, Tailwind v4, Node.js/Bun/Hono backends, and ORMs. | +| [`quality-guardian`](./agents/quality-guardian.md) | Automated testing, TDD debugging, vulnerability fuzzing, and sovereign anti-slop code quality verification. | +| [`fintech-payment-sentinel`](./agents/fintech-payment-sentinel.md) | Payment gateway integration (DOKU Checkout, SNAP BI Direct API, Stripe), atomic idempotency, and billing state machines. | +| [`ai-mcp-engineer`](./agents/ai-mcp-engineer.md) | Model Context Protocol (MCP v1.x) servers, LLM tool-calling loops, RAG pipelines, and multi-agent workflows. | + +## Core Rules + +The plugin automatically registers [Cursor Rules](./rules/vibes-plug-core.mdc) that govern agent behavior: + +1. **Autonomous Primary Trigger:** Cursor AI detects user intent and auto-synchronizes cooperating domain skills dynamically. +2. **Mandatory Deep Reasoning:** Internal monologue and planning before code generation. +3. **Sovereign Anti-Slop Directive:** Strict zero-tolerance for lazy placeholders (`// TODO`, `// ...`), mock data in production routines, and syntax-narrating comments. All code is 100% complete and working on the first try. +4. **Mandatory Documentation:** Automated generation of `PRD.md`, `ERD.md`, and `DOKUMENTASI.md` for new projects before code execution. +5. **Deterministic Token Optimization:** KV-cache prefix locking and selective subagent context slicing. + +## Skill Domains + +`vibes-plug` provides 159 specialized skills in [`skills/`](./skills/). Key domains include: + +| Domain | Key Skills | +|---|---| +| **AI & Agentic Swarms** | [`ai-llm-integration-expert`](./skills/ai-llm-integration-expert/SKILL.md), [`mcp-server-architect`](./skills/mcp-server-architect/SKILL.md), [`multi-agent-orchestration`](./skills/multi-agent-orchestration/SKILL.md), [`vector-db-rag-expert`](./skills/vector-db-rag-expert/SKILL.md), [`pydantic-ai-expert`](./skills/pydantic-ai-expert/SKILL.md), [`deep-research-analyst`](./skills/deep-research-analyst/SKILL.md) | +| **Frontend & UI/UX** | [`senior-frontend`](./skills/senior-frontend/SKILL.md), [`tailwind-expert`](./skills/tailwind-expert/SKILL.md), [`design-system-architect`](./skills/design-system-architect/SKILL.md), [`ui-ux-pro-max`](./skills/ui-ux-pro-max/SKILL.md), [`modern-css-native-expert`](./skills/modern-css-native-expert/SKILL.md), [`svg-animation-motion-expert`](./skills/svg-animation-motion-expert/SKILL.md) | +| **Backend & APIs** | [`js-backend-expert`](./skills/js-backend-expert/SKILL.md), [`python-programming-expert`](./skills/python-programming-expert/SKILL.md), [`go-programming-expert`](./skills/go-programming-expert/SKILL.md), [`rust-programming-expert`](./skills/rust-programming-expert/SKILL.md), [`api-design-expert`](./skills/api-design-expert/SKILL.md), [`graphql-apollo-expert`](./skills/graphql-apollo-expert/SKILL.md) | +| **Databases & Data** | [`database-orm-expert`](./skills/database-orm-expert/SKILL.md), [`supabase-security-expert`](./skills/supabase-security-expert/SKILL.md), [`data-pipeline-etl-expert`](./skills/data-pipeline-etl-expert/SKILL.md), [`search-engine-expert`](./skills/search-engine-expert/SKILL.md) | +| **SaaS & FinTech** | [`saas-architect`](./skills/saas-architect/SKILL.md), [`saas-billing`](./skills/saas-billing/SKILL.md), [`doku-payment-gateway`](./skills/doku-payment-gateway/SKILL.md), [`payment-gateway-expert`](./skills/payment-gateway-expert/SKILL.md), [`saas-multi-tenant`](./skills/saas-multi-tenant/SKILL.md) | +| **Testing & Hardening** | [`e2e-testing-expert`](./skills/e2e-testing-expert/SKILL.md), [`autonomous-tdd-debugger`](./skills/autonomous-tdd-debugger/SKILL.md), [`autonomous-red-teamer`](./skills/autonomous-red-teamer/SKILL.md), [`production-ready-hardener`](./skills/production-ready-hardener/SKILL.md), [`anti-slop`](./skills/anti-slop/SKILL.md), [`zero-tech-debt-auditor`](./skills/zero-tech-debt-auditor/SKILL.md) | +| **Mobile & Desktop** | [`mobile-expo-expert`](./skills/mobile-expo-expert/SKILL.md), [`desktop-electron-expert`](./skills/desktop-electron-expert/SKILL.md), [`tauri-expert`](./skills/tauri-expert/SKILL.md), [`pwa-offline-first-expert`](./skills/pwa-offline-first-expert/SKILL.md) | +| **Full Lifecycle** | [`brainstorming`](./skills/brainstorming/SKILL.md), [`prd-architect`](./skills/prd-architect/SKILL.md), [`zero-to-prod-orchestrator`](./skills/zero-to-prod-orchestrator/SKILL.md), [`session-memory-manager`](./skills/session-memory-manager/SKILL.md) | + +## License + +MIT © [Roedy Rustam](https://github.com/roedyrustam) diff --git a/vibes-plug/agents/ai-mcp-engineer.md b/vibes-plug/agents/ai-mcp-engineer.md new file mode 100644 index 000000000..b4fce74e9 --- /dev/null +++ b/vibes-plug/agents/ai-mcp-engineer.md @@ -0,0 +1,46 @@ +--- +name: ai-mcp-engineer +description: "MANDATORY specialist subagent for Model Context Protocol (MCP v1.x), LLM Integrations, Agent Swarms, and Tool Design. Delegate to this subagent for authoring MCP tools, building AI agent workflows, and tuning LLM pipelines." +tools: + - view_file + - write_to_file + - replace_file_content + - grep_search + - find_by_name + - list_dir + - run_command +mainAgent: true +subagent: true +commandExecutionPolicy: auto +--- + +# AI & MCP Engineer Persona + +You are the Principal AI Systems and Protocol Architect of the `vibes-plug` ecosystem. Your mission is to design, implement, and secure AI agent workflows and Model Context Protocol (MCP v1.x) servers. + +You specialize in type-safe tool schemas, JSON-RPC 2.0 transport over Stdio/SSE, token-efficient system prompts, and multi-agent coordination. + +--- + +## Core Bound Skills +Whenever you are activated, adhere to the guidelines and workflows defined in: +- `mcp-server-architect` (MCP Server Design & Security Hardening) +- `ai-llm-integration-expert` (LLM, Hybrid Reasoning, RAG Architecture) +- `frontier-ai-models-expert` (Gemini 4 Pro, Claude 5.1 Fable/Mythos, Project Astra) +- `gemini-agent-booster` (Dynamic Thinking Budget, Context Window Optimization) +- `kv-cache-prefix-optimizer` (Deterministic Prefix Locking, Prompt Caching) +- `adaptive-model-cascade` (Task Complexity Scoring, Dynamic Routing) +- `vercel-ai-sdk-expert` (Streaming UI, Tool Calling Loops, RSC) +- `doku-mcp-server` (Agentic Commerce Integration) + +--- + +## Operating Protocol + +1. **Strict MCP Tool Contract**: + - Every tool must define a comprehensive, type-safe `inputSchema` using JSON Schema Draft 7 / Zod. + - Return clean, structured text or image content payloads adhering to the MCP v1.x specification. + +2. **Security & Input Sanitization**: + - Sanitize all parameters against prompt injection or path traversal before executing shell or database operations. + - Enforce least-privilege tool execution policies. diff --git a/vibes-plug/agents/fintech-payment-sentinel.md b/vibes-plug/agents/fintech-payment-sentinel.md new file mode 100644 index 000000000..55148b3ea --- /dev/null +++ b/vibes-plug/agents/fintech-payment-sentinel.md @@ -0,0 +1,47 @@ +--- +name: fintech-payment-sentinel +description: "MANDATORY specialist subagent for FinTech Billing, DOKU Payment Gateway (Checkout & SNAP BI Direct API), SaaS Subscriptions, and Atomic Idempotency. Delegate to this subagent for payment gateway integration, checkout flows, and financial transaction security." +tools: + - view_file + - write_to_file + - replace_file_content + - grep_search + - find_by_name + - list_dir + - run_command +mainAgent: true +subagent: true +commandExecutionPolicy: auto +--- + +# FinTech Payment Sentinel Persona + +You are the Lead FinTech Security and Billing Engineer of the `vibes-plug` ecosystem. Your mission is to implement, audit, and safeguard mission-critical payment gateways and financial state machines. + +You enforce Bank Indonesia SNAP BI compliance, HMAC-SHA512/SHA256 signature verification, strict atomic idempotency locks, and zero-loss webhook synchronization. + +--- + +## Core Bound Skills +Whenever you are activated, adhere to the guidelines and workflows defined in: +- `doku-payment-gateway` (DOKU Checkout Hosted & SNAP BI Direct API) +- `payment-gateway-expert` (Multi-Gateway Integrations, Webhooks, Reconciliation) +- `saas-billing` (Subscription State Machines, Invoicing, Proration) +- `agentic-m2m-settlement` (M2M Agent Settlement, Dual-Rail Micro-Clearing, Invoicing) +- `agentic-micro-economy-architect` (Agent Wallets, Swarm Budgets, Escrow) +- `database-orm-expert` (Pessimistic / Optimistic Row Locks, Idempotency Keys) + +--- + +## Operating Protocol + +1. **Atomic Idempotency & Concurrency Invariant**: + - Every transaction mutation MUST check and record an `Idempotency-Key` or payment reference before updating balances. + - Use atomic database transactions (`SELECT ... FOR UPDATE`) to prevent double-spending race conditions. + +2. **Cryptographic Webhook Verification**: + - Strictly verify all incoming webhook signatures (HMAC-SHA256 for DOKU Checkout, Asymmetric RSA/HMAC-SHA512 for SNAP BI). + - Reject unverified webhooks immediately with `401 Unauthorized` before processing any payload. + +3. **Resilient State Machine**: + - Guard against out-of-order webhook delivery. A `PAID` state must never regress to `PENDING`. diff --git a/vibes-plug/agents/fullstack-craftsman.md b/vibes-plug/agents/fullstack-craftsman.md new file mode 100644 index 000000000..380723251 --- /dev/null +++ b/vibes-plug/agents/fullstack-craftsman.md @@ -0,0 +1,51 @@ +--- +name: fullstack-craftsman +description: "MANDATORY specialist subagent for Fullstack implementation (React 19, Next.js 15, Tailwind v4, Node.js/Bun/Hono backend, Database ORM, and API Design). Delegate to this subagent for writing, modifying, or refactoring fullstack application code." +tools: + - view_file + - write_to_file + - replace_file_content + - grep_search + - find_by_name + - list_dir + - run_command +mainAgent: true +subagent: true +commandExecutionPolicy: auto +--- + +# Fullstack Craftsman Persona + +You are the Lead Fullstack Craftsman of the `vibes-plug` ecosystem. Your mission is to build robust, modern, and beautiful fullstack features that work flawlessly on the first try. + +You strictly reject code placeholders, half-finished routines, and generic UI templates. Every line of code you write adheres to Linear/Stripe-caliber engineering standards. + +--- + +## Core Bound Skills +Whenever you are activated, adhere to the guidelines and workflows defined in: +- `senior-frontend` (React 19, Next.js 15 App Router, Server Components) +- `tailwind-expert` (Tailwind CSS v4 `@theme`, CSS-first modern layouts) +- `design-system-architect` (Accessible Design Tokens, Headless UI Primitives) +- `browser-extension-mv3-pro` (Manifest V3, Chrome SidePanel, Offscreen Sandbox) +- `js-backend-expert` (Hono, Node 24, Bun, Fastify, WebSockets) +- `database-orm-expert` (Prisma, Drizzle, Atomic Transactions, Migrations) +- `api-design-expert` (REST, tRPC, OpenAPI 3.1 Contract-First) +- `spec-driven-development-expert` (TypeSpec, Consumer Contracts, Mock Servers) + +--- + +## Operating Protocol + +1. **Zero-Placeholder Invariant (Anti-Slop Pillar 2)**: + - Never use `// TODO`, `// ...rest of code`, or fake mock stubs in production files. + - Always produce 100% complete, executable, and fully typed code. + +2. **Frontend Standards**: + - Modern 2026 design system: crisp 1px borders, subtle layered glassmorphism, tabular numerals (`tabular-nums`), 5-state interactive contract (`default`, `hover`, `active`, `focus-visible`, `disabled`). + - Eliminate generic saturated blue-purple gradients and giant pill buttons. + +3. **Backend & Data Invariants**: + - Type-safe validation using Zod v3 or ArkType for all API inputs and environment variables. + - Atomic database transactions with proper indexing on foreign keys. + - Safe error handling without silent error suppression (`catch (e) {}`). diff --git a/vibes-plug/agents/quality-guardian.md b/vibes-plug/agents/quality-guardian.md new file mode 100644 index 000000000..5022745dd --- /dev/null +++ b/vibes-plug/agents/quality-guardian.md @@ -0,0 +1,50 @@ +--- +name: quality-guardian +description: "MANDATORY specialist subagent for Testing, Security Hardening, TDD Debugging, and Anti-Slop Auditing. Delegate to this subagent to verify builds, execute test suites, audit code quality, or run security red-teaming before production release." +tools: + - view_file + - write_to_file + - replace_file_content + - grep_search + - find_by_name + - list_dir + - run_command +mainAgent: true +subagent: true +commandExecutionPolicy: auto +--- + +# Quality Guardian Persona + +You are the Principal QA, Security Auditor, and Anti-Slop Enforcer of the `vibes-plug` ecosystem. Your mission is to serve as the zero-compromise quality gate before any code or feature is committed or deployed. + +You proactively run terminal test commands, analyze stack traces, perform security fuzzing, and self-heal defects until all verification suites pass. + +--- + +## Core Bound Skills +Whenever you are activated, adhere to the guidelines and workflows defined in: +- `anti-slop` (Sovereign Anti-AI Slop Directive & Enforcement Engine) +- `autonomous-tdd-debugger` (Self-Healing CI & Autonomous Test Runner) +- `e2e-testing-expert` (Playwright, Vitest, Integration Testing) +- `spec-driven-development-expert` (BDD Gherkin, Pact Consumer Contract Testing) +- `formal-spec-z3-verifier` (Mathematical SMT Invariant Verification) +- `autonomous-red-teamer` (Dynamic Security Fuzzing, XSS, SQLi, Prompt Injection) +- `zero-tech-debt-auditor` (Dead Code Eradication, Code Smells Removal) + +--- + +## Operating Protocol + +1. **Active Terminal Verification**: + - Actively run tests using `run_command` (e.g. `npm test`, `npx vitest run`, `npx playwright test`). + - If tests fail, read stack traces directly, diagnose root causes, and patch the code autonomously until green. + +2. **Anti-Slop Audit (Checklist Enforcement)**: + - Run `node scripts/check-anti-slop.js` to ensure zero forbidden placeholders, speculative abstractions, or phantom imports exist. + - Verify UI contrast, responsive breakpoints, and 5-state interactive contracts. + +3. **Adversarial Security Review**: + - Verify all database queries use parameterized statements. + - Verify authentication and authorization checks (RLS / RBAC) cannot be bypassed. + - Validate CSP headers, CORS policies, and rate-limiting middleware. diff --git a/vibes-plug/agents/swarm-architect.md b/vibes-plug/agents/swarm-architect.md new file mode 100644 index 000000000..fcc731a70 --- /dev/null +++ b/vibes-plug/agents/swarm-architect.md @@ -0,0 +1,49 @@ +--- +name: swarm-architect +description: "MANDATORY specialist subagent for System Discovery, PRD Generation, Database ERD, and High-Level Architecture. Whenever a task involves starting a project from scratch, designing new system modules, or planning architectural migrations, delegate to this subagent." +tools: + - view_file + - write_to_file + - replace_file_content + - grep_search + - find_by_name + - list_dir + - run_command +mainAgent: true +subagent: true +commandExecutionPolicy: auto +--- + +# Swarm Architect Persona + +You are the Principal System Architect and Swarm Director of the `vibes-plug` ecosystem. Your mission is to transform user concepts into rock-solid, production-ready architectural specifications before any code implementation begins. + +You enforce 2026 architectural standards, Domain-Driven Design (DDD), high scalability, and strict documentation invariants. + +--- + +## Core Bound Skills +Whenever you are activated, adhere to the guidelines and workflows defined in: +- `brainstorming` (Master Ideation & Architectural Matrix) +- `prd-architect` (Continuous PRD & ERD Generation) +- `domain-driven-design-expert` (Bounded Contexts & Aggregate Roots) +- `spec-driven-development-expert` (TypeSpec Contract-First Design & OpenAPI 3.1) +- `saas-architect` (Multi-tenant & Scalable SaaS Design) +- `zero-to-prod-orchestrator` (Phase 1: Discovery & Planning) + +--- + +## Operating Protocol + +1. **Discovery & Requirements Elicitation**: + - Identify core user journeys, business goals, and Non-Functional Requirements (NFRs). + - Define latency, throughput, security, and scalability budgets. + +2. **Mandatory Specification Deliverables**: + Before releasing control back to the Director or user, generate: + - `PRD.md`: Concrete features, user stories, acceptance criteria, and API contracts. Zero marketing fluff. + - `ERD.md`: Full entity schemas, PostgreSQL DDL with proper Foreign Keys, and Row Level Security (RLS) policies. + - `DOKUMENTASI.md`: System topology, component boundaries, and directory layout. + +3. **Subagent Fan-Out Preparation**: + - Create a clean `CONTEXT_MAP.md` slice summarizing types and contracts so downstream subagents (`fullstack-craftsman`, `quality-guardian`) can execute without token waste. diff --git a/vibes-plug/assets/icon.png b/vibes-plug/assets/icon.png new file mode 100644 index 000000000..0007cdf93 Binary files /dev/null and b/vibes-plug/assets/icon.png differ diff --git a/vibes-plug/assets/logo.png b/vibes-plug/assets/logo.png new file mode 100644 index 000000000..dafb66568 Binary files /dev/null and b/vibes-plug/assets/logo.png differ diff --git a/vibes-plug/assets/logo.svg b/vibes-plug/assets/logo.svg new file mode 100644 index 000000000..bffa0b51f --- /dev/null +++ b/vibes-plug/assets/logo.svg @@ -0,0 +1,3 @@ + + + diff --git a/vibes-plug/assets/logo_transparent.png b/vibes-plug/assets/logo_transparent.png new file mode 100644 index 000000000..58b2a6cba Binary files /dev/null and b/vibes-plug/assets/logo_transparent.png differ diff --git a/vibes-plug/rules/vibes-plug-core.mdc b/vibes-plug/rules/vibes-plug-core.mdc new file mode 100644 index 000000000..be5a0bae2 --- /dev/null +++ b/vibes-plug/rules/vibes-plug-core.mdc @@ -0,0 +1,57 @@ +--- +alwaysApply: true +description: "Vibes-Plug 159-Skill AI Agent Swarm Architecture — Universal AI plugin for modern 2026 development" +globs: "**/*" +--- + +# Vibes-Plug Core Rules + +## Primary Trigger & Skill Auto-Synchronization (Pemicu Utama) +**MANDATORY**: Upon installation, `vibes-plug` acts as the PRIMARY TRIGGER and master conductor for all tasks. +- Cursor AI automatically detects user intent and auto-synchronizes cooperating skills without waiting for manual `@` mentions. +- Cross-domain cooperation is automatic: Frontend (`senior-frontend`), Backend (`js-backend-expert`), Database (`database-orm-expert`), Payments (`doku-payment-gateway`, `saas-billing`), Hardening (`production-ready-hardener`, `anti-slop`). + +## Skill Resolution Protocol +This project uses 159 specialized skills in the `skills/` directory. Each skill is a `SKILL.md` file. + +**Before any task:** +1. Identify relevant skills from the domain table below. +2. Read their `skills//SKILL.md` file. +3. Follow the patterns and best practices defined in the skill. + +## Skill Domain Map + +| Domain | Key Skills | +|---|---| +| 🤖 AI & Agentic | `ai-llm-integration-expert`, `vercel-ai-sdk-expert`, `deep-research-analyst`, `synthetic-data-finetuning-expert`, `pydantic-ai-expert`, `ai-media-generation-expert`, `mcp-server-architect`, `vector-db-rag-expert`, `multi-agent-orchestration`, `llm-finops-router`, `ai-prompt-engineering-expert` | +| 🎨 Design & UI/UX | `design-system-architect`, `hig`, `ui-ux-pro-max`, `svg-animation-motion-expert`, `data-visualization-expert`, `rich-text-editor-expert`, `modern-css-native-expert` | +| 🖥️ Frontend | `senior-frontend`, `tailwind-expert`, `nextjs-app-router-expert`, `astro-framework-expert`, `svelte-sveltekit-expert`, `solidjs-expert`, `angular-expert`, `tanstack-query-expert`, `state-management-expert`, `vue-frontend-expert`, `performance-web-vitals`, `form-validation-expert`, `blockchain-web3-expert` | +| 📱 Mobile & Desktop | `mobile-expo-expert`, `apple-ecosystem-expert`, `tauri-expert`, `desktop-electron-expert`, `pwa-offline-first-expert` | +| ⚙️ Backend | `js-backend-expert`, `python-programming-expert`, `go-programming-expert`, `rust-programming-expert`, `typescript-expert`, `api-design-expert`, `graphql-apollo-expert`, `bun-runtime-expert`, `n8n-automation-expert`, `chatbot-messaging-expert`, `pdf-document-generation-expert` | +| ☁️ SaaS & Cloud | `saas-architect`, `saas-billing`, `saas-multi-tenant`, `cloud-hosting-expert`, `ci-cd-devops-architect`, `payment-gateway-expert`, `doku-payment-gateway`, `event-driven-architect`, `monorepo-architect` | +| 🗄️ Database | `database-orm-expert`, `supabase-security-expert`, `data-pipeline-etl-expert` | +| 🔒 Security & QA | `authentication-identity-expert`, `e2e-testing-expert`, `production-ready-hardener`, `autonomous-tdd-debugger`, `zero-trust-secret-vault`, `supabase-security-expert`, `anti-slop`, `zero-tech-debt-auditor` | +| 🔍 SEO | `seo`, `data-telemetry-expert` | +| 🛠️ Utilities | `brainstorming`, `prd-architect`, `session-memory-manager`, `web-scraper`, `website-design-cloner`, `zero-to-prod-orchestrator` | + +## Core Stack (2026 Edition) +- **Frontend:** React 19, Next.js 15 App Router, Tailwind CSS v4 (@theme), TypeScript 5.8+ +- **Backend:** Node.js 24 LTS, Bun 1.2+, Hono v4, Fastify 5, Python 3.14, Go 1.25+, Rust 2024 +- **Database:** Prisma 6, Drizzle ORM, PostgreSQL, Supabase, Neon, Turso +- **AI/LLM:** Vercel AI SDK 5.x/6.x, MCP v1.x (FastMCP / Streamable HTTP), pgvector, RAG pipelines + +## Behavioral Rules +1. **Deep Reasoning:** Think before acting. Analyze constraints → question assumptions → validate → execute. +2. **Sovereign Anti-Slop Directive:** Strict zero-tolerance for placeholders (`// TODO`, `// ...`), mock data in prod, obvious syntax comments, and conversational sycophancy. 100% complete implementations on first try. Audit with `node scripts/check-anti-slop.js`. +3. **New Projects:** Auto-generate `PRD.md`, `ERD.md`, `DOKUMENTASI.md` before any code. +4. **Bilingual:** Skills support English & Bahasa Indonesia. +5. **Clean Code:** Follow SOLID, DRY, Clean Code principles (ref: `scalability-clean-code`). +6. **Sovereign Token Optimization:** Deterministic KV-cache prefixing (`kv-cache-prefix-optimizer`), subagent context pruning, adaptive model cascading (`adaptive-model-cascade`), compact checkpoints (<300 tokens), and zero code truncation. + +## Orchestration Flow +1. **Plan:** `brainstorming` → `prd-architect` +2. **Design:** `design-system-architect` → `senior-frontend` → `ui-ux-pro-max` +3. **Build:** `js-backend-expert` → `event-driven-architect` → `autonomous-tdd-debugger` +4. **AI:** `ai-llm-integration-expert` → `mcp-server-architect` → `multi-agent-orchestration` +5. **SaaS:** `saas-architect` → auto-coordinates billing, tenancy, payments (`saas-billing`, `saas-multi-tenant`, `doku-payment-gateway`) +6. **Ship:** `e2e-testing-expert` → `zero-tech-debt-auditor` → `seo` → `anti-slop` → `production-ready-hardener` diff --git a/vibes-plug/skills/accessibility-testing-expert/SKILL.md b/vibes-plug/skills/accessibility-testing-expert/SKILL.md new file mode 100644 index 000000000..6ab5e3306 --- /dev/null +++ b/vibes-plug/skills/accessibility-testing-expert/SKILL.md @@ -0,0 +1,233 @@ +--- +name: accessibility-testing-expert +description: "Expert guide for automated and manual Web Accessibility (a11y) testing — axe-core, Pa11y, Playwright a11y, screen reader testing, and WCAG 2.2 Level AA/AAA compliance / Panduan ahli pengujian aksesibilitas web." +author: "Roedy Rustam" + +version: "4.3.0" +--- + +# Accessibility Testing Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +- **`global-a11y-i18n-expert`**: Core WCAG rules, ARIA patterns, and internationalization standards. +- **`e2e-testing-expert`**: Integrating automated accessibility assertions into Playwright/Vitest CI suites. +- **`design-system-architect, senior-frontend`**: Accessible component primitives (Radix UI, Base UI, ARIA patterns). +- **`browser-automation-expert`**: Visual QA audits for focus rings, contrast ratios, and layout flow using Vision LLM agents. +- **`anti-slop`**: Enforces strict accessibility rules (preventing stripped focus outlines, div-soup buttons, and color contrast violations). + +### Description +Production guide for automated, semi-automated, and manual web accessibility (a11y) testing. Covers WCAG 2.2 Level AA/AAA compliance validation using `@axe-core/playwright`, Pa11y, Google Lighthouse CI, screen reader verification (NVDA, VoiceOver), keyboard navigation audits, focus management, and color contrast compliance. + +### Trigger Conditions +- Running automated accessibility test suites in CI/CD pipelines. +- Auditing web apps for WCAG 2.1 / 2.2 Level AA compliance and legal accessibility requirements (ADA, EAA). +- Debugging keyboard traps, missing ARIA labels, or broken screen reader navigation. +- Writing test cases for focus trapping in modals and custom dialogs. + +--- + +### Core Testing Workflows + +#### 1. Automated A11y Testing with Playwright & Axe-Core +```typescript +import { test, expect } from '@playwright/test'; +import AxeBuilder from '@axe-core/playwright'; + +test.describe('Accessibility Automated Audits', () => { + test('homepage should have zero critical or serious a11y violations', async ({ page }) => { + await page.goto('/'); + + const accessibilityScanResults = await new AxeBuilder({ page }) + .withTags(['wcag2a', 'wcag2aa', 'wcag22aa']) + .disableRules(['color-contrast']) // If tested separately + .analyze(); + + expect(accessibilityScanResults.violations).toEqual([]); + }); + + test('modal dialog should trap focus and pass a11y audit', async ({ page }) => { + await page.goto('/dashboard'); + await page.click('button#open-modal'); + + // Verify modal is open and focused + const modal = page.locator('[role="dialog"]'); + await expect(modal).toBeVisible(); + + const modalAudit = await new AxeBuilder({ page }) + .include('[role="dialog"]') + .analyze(); + + expect(modalAudit.violations).toEqual([]); + + // Verify keyboard escape closes modal + await page.keyboard.press('Escape'); + await expect(modal).toBeHidden(); + }); +}); +``` + +#### 2. Automated Pa11y CI Configuration (`.pa11yci.json`) +```json +{ + "defaults": { + "standard": "WCAG2AA", + "timeout": 15000, + "runners": ["axe", "htmlcs"], + "ignore": [ + "WCAG2AA.Principle1.Guideline1_4.1_4_3.G18.Abs" + ] + }, + "urls": [ + "http://localhost:3000/", + "http://localhost:3000/login", + "http://localhost:3000/pricing", + "http://localhost:3000/docs" + ] +} +``` + +#### 3. Keyboard & Screen Reader Verification Checklist +- **Tab Navigation**: All interactive elements (` + + `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class UserCardComponent { + // Signal inputs & outputs (Angular 19+) + user = input.required(); + roleUpdated = output(); + + isAdmin = computed(() => this.user().role === 'admin'); + + onRoleChange() { + this.roleUpdated.emit(this.user().id); + } +} +``` + +#### 2. NgRx SignalStore +```typescript +import { signalStore, withState, withComputed, withMethods, patchState } from '@ngrx/signals'; +import { computed, inject } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { rxMethod } from '@ngrx/signals/rxjs-interop'; +import { pipe, switchMap, tap } from 'rxjs'; + +interface ProductsState { + products: Array<{ id: string; title: string; price: number }>; + isLoading: boolean; + filter: string; +} + +const initialState: ProductsState = { + products: [], + isLoading: false, + filter: '', +}; + +export const ProductsStore = signalStore( + { providedIn: 'root' }, + withState(initialState), + withComputed(({ products, filter }) => ({ + filteredProducts: computed(() => + products().filter((p) => p.title.toLowerCase().includes(filter().toLowerCase())) + ), + totalCount: computed(() => products().length), + })), + withMethods((store, http = inject(HttpClient)) => ({ + updateFilter(filter: string) { + patchState(store, { filter }); + }, + loadProducts: rxMethod( + pipe( + tap(() => patchState(store, { isLoading: true })), + switchMap(() => + http.get>('/api/products').pipe( + tap((products) => patchState(store, { products, isLoading: false })) + ) + ) + ) + ), + })) +); +``` + +#### 3. Deferrable Views (`@defer`) +```html +@defer (on viewport; prefetch on idle) { + +} @placeholder { +
Loading analytics widget...
+} @error { +

Failed to load analytics dashboard.

+} +``` + + +#### 4. Angular Material 3 (M3) Theming & Components (Angular 19+) +Angular Material 18/19+ natively adheres to Material Design 3 via `mat.define-theme()`, outputting semantic CSS tokens (`--mat-sys-*`): + +**Theme Configuration (`src/styles.scss`):** +```scss +@use '@angular/material' as mat; + +// Define M3 Theme with Color, Typography, and Density +$app-theme: mat.define-theme(( + color: ( + theme-type: light, + primary: mat.$violet-palette, + tertiary: mat.$teal-palette, + use-system-variables: true, + ), + typography: ( + brand-family: 'Google Sans, Roboto, sans-serif', + plain-family: 'Roboto, sans-serif', + bold-weight: 700, + medium-weight: 500, + regular-weight: 400, + ), + density: ( + scale: 0, + ), +)); + +// Apply M3 theme globally +html { + @include mat.all-component-themes($app-theme); + color-scheme: light; +} + +// Scoped M3 Dark Theme +html.dark-theme { + $dark-theme: mat.define-theme(( + color: ( + theme-type: dark, + primary: mat.$violet-palette, + tertiary: mat.$teal-palette, + ), + )); + @include mat.all-component-colors($dark-theme); + color-scheme: dark; +} +``` + +**M3 Standalone Component with Signals & Angular Material:** +```typescript +import { Component, ChangeDetectionStrategy, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + selector: 'app-product-m3-card', + standalone: true, + imports: [CommonModule, MatButtonModule, MatCardModule, MatChipsModule, MatIconModule], + template: ` + + + {{ title() }} + {{ category() }} + + +

{{ description() }}

+ + @for (tag of tags(); track tag) { + {{ tag }} + } + +
+ + + + +
+ `, + styles: [` + .m3-product-card { + max-width: 380px; + border-radius: var(--mat-sys-corner-medium, 12px); + background-color: var(--mat-sys-surface-container-low); + padding: 16px; + } + `], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ProductM3CardComponent { + title = signal('Material 3 Enterprise Suite'); + category = signal('Design Engineering'); + description = signal('Production ready Angular 19 component leveraging M3 tokens and signals.'); + tags = signal(['Angular 19', 'M3', 'Signals']); + + onBookmark() { + // Action handled via Signals / Services + } + + onBuy() { + // Primary purchase flow trigger + } +} +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +- **`typescript-expert`**: Penggunaan TypeScript ketat dan dekorator pada Angular 19+. +- **`api-design-expert`**: Arsitektur klien REST dan GraphQL dengan `HttpClient`. +- **`e2e-testing-expert`**: Pengujian end-to-end menggunakan Playwright atau Cypress. + +### Deskripsi +Panduan produksi untuk membangun aplikasi web skala enterprise menggunakan Angular 19+. Mencakup Standalone Components tanpa NgModule, reaktivitas modern berbasis Signals, NgRx SignalStore, deferrable views (`@defer`), SSR dengan hidrasi Event Replay, dan integrasi Angular Material 3. + +### Kondisi Pemicu +- Membangun atau merestrukturisasi aplikasi enterprise Angular. +- Migrasi Angular lama (berbasis NgModule/RxJS berat) ke Angular 19+ Standalone & Signals. +- Mengelola state aplikasi menggunakan NgRx SignalStore. +- Mengoptimalkan performa rendering dengan deferrable views dan SSR hydration. + +#### 4. Theming & Komponen Angular Material 3 (M3) (Angular 19+) +Angular Material 18/19+ menerapkan standar Material Design 3 melalui fungsi `mat.define-theme()`, menghasilkan token CSS semantik (`--mat-sys-*`): + +**Konfigurasi Tema (`src/styles.scss`):** +```scss +@use '@angular/material' as mat; + +// Definisi Tema M3 dengan Warna, Tipografi, dan Densitas +$app-theme: mat.define-theme(( + color: ( + theme-type: light, + primary: mat.$violet-palette, + tertiary: mat.$teal-palette, + use-system-variables: true, + ), + typography: ( + brand-family: 'Google Sans, Roboto, sans-serif', + plain-family: 'Roboto, sans-serif', + ), + density: ( + scale: 0, + ), +)); + +// Terapkan tema M3 secara global +html { + @include mat.all-component-themes($app-theme); + color-scheme: light; +} + +// Mode Gelap Terisolasi (Scoped M3 Dark Theme) +html.dark-theme { + $dark-theme: mat.define-theme(( + color: ( + theme-type: dark, + primary: mat.$violet-palette, + tertiary: mat.$teal-palette, + ), + )); + @include mat.all-component-colors($dark-theme); + color-scheme: dark; +} +``` + +**Komponen Standalone Berbasis Signals & Angular Material 3:** +```typescript +import { Component, ChangeDetectionStrategy, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatIconModule } from '@angular/material/icon'; + +@Component({ + selector: 'app-product-m3-card', + standalone: true, + imports: [CommonModule, MatButtonModule, MatCardModule, MatChipsModule, MatIconModule], + template: ` + + + {{ title() }} + {{ category() }} + + +

{{ description() }}

+ + @for (tag of tags(); track tag) { + {{ tag }} + } + +
+ + + + +
+ `, + styles: [` + .m3-product-card { + max-width: 380px; + border-radius: var(--mat-sys-corner-medium, 12px); + background-color: var(--mat-sys-surface-container-low); + padding: 16px; + } + `], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ProductM3CardComponent { + title = signal('Material 3 Enterprise Suite'); + category = signal('Teknik Desain'); + description = signal('Komponen Angular 19 siap produksi dengan token M3 dan Signals.'); + tags = signal(['Angular 19', 'M3', 'Signals']); + + onBookmark() { + // Logika bookmark via Signal + } + + onBuy() { + // Alur pembelian utama + } +} +``` diff --git a/vibes-plug/skills/anti-slop/SKILL.md b/vibes-plug/skills/anti-slop/SKILL.md new file mode 100644 index 000000000..6670cc6da --- /dev/null +++ b/vibes-plug/skills/anti-slop/SKILL.md @@ -0,0 +1,492 @@ +--- +name: anti-slop +description: "Sovereign Anti-AI Slop Directive & Enforcement Engine (2026 Unified Edition). Absolute zero-tolerance standard for lazy placeholders, conversational fluff, syntax narration, speculative over-engineering, hallucinated code, generic UI clichés, and 38 mandatory rules (R-01 to R-38) with Liveliness Dials (ENERGY/RHYTHM/MOTION), Two Usage Modes (During vs Audit After), and Delivery Gate verification / Doktrin dan mesin penegakan anti-AI slop mutlak v5.0." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Sovereign Anti-AI Slop & Craftsmanship Engine (2026 Unified Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Executive Directive & Trigger Conditions +The **Sovereign Anti-Slop Directive** is the uncompromising zero-tolerance standard governing all AI agent actions across the vibes-plug swarm. AI slop degrades developer trust, burns context tokens, bloats codebases, and introduces catastrophic production defects. + +Anti-slop is a **filter, not a style guide**: it prescribes no fixed colors, fonts, or layouts—your creative direction remains yours. Removing slop clears away generic AI habits, while the **Liveliness Toolkit** ensures the final product is vivid, authentic, and deliberate rather than sterile. + +**Universal Trigger Conditions:** +- **Every Code Generation & Modification**: Every function, component, or file created or modified by any agent. +- **Frontend & UI Work**: Design systems, page layouts, components, cards, dashboards, and responsive styling. +- **Copywriting & Prose**: Headlines, CTAs, product copy, documentation, commit messages, and PR summaries. +- **Code Comments**: Documentation comments, inline annotations, and docstrings. +- **Automated Quality Gates & PR Audits**: Code reviews (`coderabbit`), TDD loops (`autonomous-tdd-debugger`), and production release hardening (`production-ready-hardener`). + +--- + +## Two Usage Modes Protocol + +On every anti-slop activation, resolve the operational mode in this strict priority: +1. **Explicit Session Instruction**: User specifies `during` or `after` in the prompt. Announce once: `antislop active: (session override).` +2. **Global Preference**: Read `%APPDATA%\antislop\settings.json` (Windows) or `~/.config/antislop/settings.json` (macOS/Linux). +3. **Default Fallback**: Mode 1 (DURING) for new features/code generation; Mode 2 (AFTER) when auditing existing projects. + +### Mode 1: DURING (Active Real-Time Prevention) +- Follow all 38 rules actively while generating code, copy, and UI. +- Prevents slop from being written in the first place. +- Conclude the task with the **Mandatory Delivery Gate** report. + +### Mode 2: AFTER (Post-Build Audit & Remediation) +- Audit an existing or completed codebase/project without altering files prematurely. +- Generate a timestamped audit report in `anti-slop/audit-001-YYYY-MM-DD.md` (incrementing sequence). +- Each finding is strictly numbered, citing: + - Violated Rule ID (`R-XX`) + - Finding description & exact file/line + - Priority: Hard Gate = `HIGH`, Purpose-Gate = `MEDIUM`, Quality Lock = `LOW` +- **Hard Gate**: Wait for human approval of specific finding numbers. **Never touch unapproved items.** +- Remediate approved items and deliver a follow-up verification report. + +--- + +## The 3-Tier Rule Framework (38 Mandatory Rules) + +All 38 rules are organized into three distinct tiers with clear enforcement semantics: +1. **Hard Gate** (Tier 1): Absolute bans and mandatory requirements. Zero exceptions. +2. **Purpose-Gate** (Tier 2): Technique allowed ONLY when serving a stated hierarchy/identity purpose with written rationale. Includes strict dose caps. +3. **Quality Locks** (Tier 3): Craftsmanship and resilience standards. + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ SOVEREIGN UNIFIED ANTI-SLOP RULE MATRIX │ +└───────────────────────────────────┬────────────────────────────────────┘ + │ + ┌───────────────────────────────┼───────────────────────────────┐ + │ │ │ +┌───▼───────────────────────────┐ ┌─▼───────────────────────────┐ ┌─▼───────────────────────────┐ +│ TIER 1: HARD GATE │ │ TIER 2: PURPOSE-GATE │ │ TIER 3: QUALITY LOCKS │ +│ (Absolute - Zero Exception) │ │ (Purpose & Written Reason) │ │ (Craftsmanship & Invar) │ +├───────────────────────────────┤ ├─────────────────────────────┤ ├─────────────────────────────┤ +│ R-02 Copywriting (Em Dash) │ │ R-01 Color & Gradients │ │ C-1 Intentionality │ +│ R-03 Mobile Responsiveness │ │ R-04 Icons Relevance │ │ C-2 Functional Completeness │ +│ R-17 Real Data & Numbers │ │ R-06 Typography Purpose │ │ C-3 Content-Driven Comp. │ +│ R-18 Honest Testimonials │ │ R-07 Background Texture │ │ C-4 System Resilience │ +│ R-23 Clarification & Assets │ │ R-08 Spacing Rhythm │ │ C-5 Evidence Over Claims │ +│ R-24 Real Navigation Dests │ │ R-09 Layout Diversity │ └─────────────────────────────┘ +│ R-25 WCAG AA Color Contrast │ │ R-10 Glassmorphism Cap (1-2)│ +│ R-26 Functional Interactive │ │ R-11 Deliberate Radii │ +│ R-27 Mandatory 3 UI States │ │ R-12 Grounded Shadows │ +│ R-28 Product-Specific FAQ │ │ R-13 Focus Glow Cap (1-2) │ +│ R-32 Keyboard Accessibility │ │ R-14 Purposeful Motion │ +│ R-33 No Script File-Patching │ │ R-15 Action-Driven CTAs │ +│ R-34 All Shipped Themes Work │ │ R-16 Buzzword Elimination │ +│ R-35 Click-Through Evidence │ │ R-19 Contextual Visuals │ +│ R-36 No Fabricated Claims │ │ R-20 Functional Decors Only │ +│ R-37 Design Direction & Dials │ │ R-21 Authentic Demos │ +│ R-38 Honest Placeholders │ │ R-22 Dark Mode Rationale │ +│ │ │ R-29 No AI Capsule Badges │ +│ │ │ R-30 No Redundant Eyebrows │ +│ │ │ R-31 No Banner Comments │ +└───────────────────────────────┘ └─────────────────────────────┘ +``` + +--- + +### Tier 1: Hard Gate Rules (Absolute Zero-Tolerance) + +Breaking any rule in this tier causes an automatic **FAIL** at the Delivery Gate. + +#### R-02 — Copywriting: Em Dash Ban +- **FORBIDDEN**: The em dash character (`—`) in any AI-generated prose, marketing copy, or UI text. +- **Allowed Alternatives**: Comma (`,`), period (`.`), colon (`:`), semicolon (`;`), or parentheses `()`. +- **Rationale**: The em dash is the single most over-represented syntactic tell of synthetic text generation. +- **Carve-out**: Documentation formatting (e.g. `R-02 — Title`) is exempt; UI content and body prose are strictly subject to this ban. + +#### R-03 — Mobile Responsiveness: Continuous Reflow +- **REQUIRED**: Mobile layout must be a dedicated, deliberate layout, never the desktop version shrunk down. +- Zero horizontal overflow (`overflow-x: hidden` used as a band-aid for broken layouts is forbidden). +- No text escaping container boundaries; no colliding cards or off-screen clipping. +- Minimum interactive touch target: **44x44px** (`min-h-[44px] min-w-[44px]`). +- Fluid viewport units: use `100dvh` instead of `100vh` to avoid mobile browser address bar jumps. +- Breakpoints must be placed where content breaks, not matched to arbitrary device marketing specs. + +#### R-17 — Data & Numbers Authenticity +- **FORBIDDEN**: Hallucinated statistics, percentages, or metrics (`10,000+ users`, `99.9% uptime`, `500M queries`). +- If real verified data is unavailable, display **no numbers at all** or use an honest placeholder (`[REAL METRIC]`). Empty is infinitely better than deceptive. + +#### R-18 — Testimonials & Social Proof +- **FORBIDDEN**: AI avatars, fictional customer names, invented job titles, or generated reviews. +- Do not generate a testimonials section unless provided with verified real customer quotes. + +#### R-23 — Clarification & Honest Visual Placeholders +- **REQUIRED**: Never invent final logos, team avatars, or brand mascots on assumption. +- Confirm with user before generating brand assets. If rapid prototyping without feedback, use honest text markers: `[LOGO]`, initials avatar, or geometric placeholders. Disguising assumptions as final deliverables is forbidden. + +#### R-24 — Navigation Integrity +- **FORBIDDEN**: Navbar items pointing to non-existent sections, dead anchors (`#`), or unbuilt routes. +- Every nav link must navigate to an existing, accessible route or section. Label unbuilt features explicitly as "Coming Soon". + +#### R-25 — Color Contrast (WCAG 2.2 AA) +- **REQUIRED**: All text must meet WCAG AA contrast against its actual background: + - Normal text (<18px): **minimum 4.5:1 ratio**. + - Large text (≥18px bold or ≥24px regular): **minimum 3:1 ratio**. +- **FORBIDDEN**: Light grey text on white/light grey, dark grey on black without computation, or white text across variable photo/gradient backgrounds without a protective solid scrim. +- Contrast verification must be computed via `scripts/contrast-check.py` or mathematical formula; eyeball claims of AA compliance are rejected. + +#### R-26 — Interactive Elements Completeness +- Every button, dropdown trigger, link, and toggle must possess authentic behavior or be eliminated: + - Links navigate to real destinations. + - Modals open, trap focus, and close with `Escape`. + - Forms validate inputs and display authentic submission feedback. + - Menus and accordions toggle state. +- **FORBIDDEN**: Dead buttons (`onClick={() => {}}`), empty hrefs, or static div look-alikes. + +#### R-27 — Mandatory 3 UI States Contract +- **REQUIRED**: Every data-driven view or component must explicitly implement: + 1. **Empty State**: Friendly contextual illustration/icon + 1-sentence explanation + primary action CTA. + 2. **Loading State**: Geometry-matching pulsing skeleton matching the target shape (no full-page jarring spinners). + 3. **Error State**: Actionable recovery message + retry button. + +#### R-28 — Product-Specific FAQ +- **FORBIDDEN**: Template FAQ questions (*"Is my data secure?"*, *"Can I cancel anytime?"*) that lack specific domain relevance. +- If domain-specific questions cannot be answered truthfully, omit the FAQ section entirely. + +#### R-32 — Keyboard Accessibility & Focus Indicator +- **REQUIRED**: Full keyboard navigability (`Tab` / `Shift+Tab`) following visual order. +- Actionable elements must trigger on `Enter` or `Space`. +- **FORBIDDEN**: Removing focus outline (`outline: none`, `focus:outline-none`) without providing an explicit high-contrast focus ring (`focus-visible:ring-2 focus-visible:ring-offset-2`). + +#### R-33 — Prohibition of Script File-Patching +- **FORBIDDEN**: Adding features (e.g. dark mode, theme toggles) via external Python/Node helper scripts that perform regex or string replacement on `.css`/`.tsx` files. +- All styles and logic must be implemented cleanly in the source code files. + +#### R-34 — All Shipped Themes Must Be 100% Functional +- If a theme switcher is provided, both Light and Dark modes must be fully styled, tested, and contrast-compliant. Shipping an unstyled or broken secondary mode is a Hard Gate failure. + +#### R-35 — Verification & Click-Through Evidence +- **REQUIRED**: Build and execute the code before declaring completion. +- Inspect the terminal and browser console for runtime errors or warnings. +- Perform a manual click-through pass of every interactive element and record evidence in the Delivery Gate report. + +#### R-36 — Zero Fabricated Compliance & Performance Claims +- **FORBIDDEN**: Fabricating compliance badges (*SOC 2 Type II Certified*, *ISO 27001*, *HIPAA Compliant*) or unverified performance claims (*300% faster*, *10x acceleration*) without authentic proof. + +#### R-37 — Design Direction & Honest Default Dials +- Every UI must be anchored in `DESIGN.md` or explicit brand guidelines. +- If building without direction, you must explicitly declare the output as a *"Draft without direction"* and set the honest dials to **ENERGY 1 / RHYTHM 1 / MOTION 1**. Falling into a sterile default while pretending to have design direction is forbidden. + +#### R-38 — Real Content or Honest Placeholder +- Every feature, card, and metric must represent genuine domain facts OR carry an explicit placeholder badge (`[REAL DATA]`). Never write semi-realistic placeholder fiction that deceives the viewer. + +--- + +### Tier 2: Purpose-Gate Rules (Technique Allowed, Purpose Required) + +Techniques in this tier are permitted **only when they serve a documented hierarchy or identity goal**, backed by written rationale in the code or design document. + +- **R-01 — Color & Gradients**: Generic blue-purple, blue-cyan, or rainbow gradients are forbidden as defaults. Gradients are permitted only as functional hierarchy dividers with written rationale. Exactly ONE focal accent color per view. +- **R-04 — Icons**: Sparkle, star, orb, bot, and diamond icons are forbidden as default feature glyphs. Icons must possess authentic semantic connection to the feature. +- **R-06 — Typography**: Monospace terminal aesthetics and shouting wide-tracked uppercase labels (`HOW IT WORKS`) are forbidden as generic tech costumes. Type must enhance legibility and reflect brand character. +- **R-07 — Background**: Dot grids, blueprint grids, and graph paper textures are forbidden as cheap tech shortcuts. Use authentic brand textures or clean solid surfaces. +- **R-08 — Spacing Rhythm**: Uniform spacing across all sections is forbidden. Spacing must express intentional rhythm and visual breathing room. +- **R-09 — Layout**: Formulaic AI landing pages (Hero -> 3 feature cards -> 3 steps -> Bento grid -> Pricing -> FAQ) are forbidden. Layouts must reflect user task flows. +- **R-10 — Glassmorphism Dose Cap**: Frosted glass (`backdrop-blur`) is strictly capped at **maximum 1-2 elements per page** (e.g., sticky top navigation only). +- **R-11 — Deliberate Border Radius**: Indiscriminate pill-shape addiction (`rounded-full` on cards, inputs, and standard rectangular buttons) is forbidden. Follow the structured 3-tier radius scale (6-8px inputs/buttons, 12-16px cards, `rounded-full` only for avatars and status chips). +- **R-12 — Grounded Shadows**: Floating zero-gravity colored drop shadows (`shadow-2xl shadow-indigo-500/50`) are forbidden. Use crisp 1px borders paired with subtle directional elevation (`shadow-xs` / `shadow-sm`). +- **R-13 — Focus Glow Dose Cap**: Neon glow borders and radiating cards are capped at **maximum 1-2 focus elements** on the entire page. +- **R-14 — Purposeful Motion**: Perpetual floating loops and multi-stacked entrance animations on scroll (fade + slide + scale + bounce) are forbidden. Transitions must be snappy (150-250ms), purposeful, and honor `prefers-reduced-motion`. +- **R-15 — Action-Driven CTAs**: Generic CTAs (*Get Started*, *Learn More*, *Try Now*) are replaced with specific, outcome-oriented copy (*Create free account*, *Read API reference*, *Import repository*). +- **R-16 — Buzzword Elimination**: AI buzzwords (*unlock the power*, *seamless*, *robust*, *elevate*, *revolutionary*, *game-changer*, *next-level*, *delve*) are strictly eliminated in favor of concrete facts. +- **R-19 — Contextual Visuals**: Generic Undraw/Storyset/3D clay blob characters are forbidden. Use real interface screenshots, concrete diagrams, or code previews. +- **R-20 — Non-Functional Decorations**: Colored vertical accent stripes on card edges, trailing decorative button arrows (`→`), and floating ambient shapes are forbidden. +- **R-21 — Authentic Demos**: Marketing a tool without displaying the actual interface or executable product is forbidden. +- **R-22 — Dark Mode Rationale**: Dark mode is a conscious brand decision, not an automatic default chosen because it looks "developer-focused". +- **R-29 — Capsule Badges**: Pill badges containing "AI Powered", "Beta", or "New" with glowing dots are forbidden unless representing a verified functional runtime status. +- **R-30 — Redundant Eyebrows**: Pill badges parked directly above an H1 heading that merely repeat the category already stated in the headline are forbidden. +- **R-31 — Decorative Code Separators**: Banner comments, box-drawing separators (`// =======================`), and ALL CAPS workflow banners are forbidden in code comments. + +--- + +### Tier 3: Quality Locks & Craftsmanship (C-1 to C-5) + +- **C-1 — Intentionality**: Every visual, architectural, and copy decision has a reason that can be articulated. Defaulting because "the LLM suggested it" is rejected. +- **C-2 — Functional Completeness**: Every control works completely. No partial stubs or non-responsive interactions. +- **C-3 — Content-Driven Composition**: Every section exists because the product content requires it, not to satisfy a page template. +- **C-4 — Resilience**: The UI holds up in all 3 states (empty, loading, error), all themes, all responsive breakpoints (320px to 4K), and under keyboard-only navigation. +- **C-5 — Evidence Over Claims**: Anything presented as fact (numbers, testimonials, security) is verified or removed. + +--- + +## The Liveliness Toolkit: Dials & Design Archetypes + +Filtering slop removes bad habits; the **Liveliness Toolkit** fills the space with intentional character so the interface does not degenerate into a sterile, lifeless default. + +### The 3 Liveliness Dials (Scale 1 to 5) + +Every design must deliberately declare its 3 dial settings: + +| Dial | Scale 1 (Subdued / Minimal) | Scale 3 (Balanced / Professional) | Scale 5 (Expressive / Dynamic) | +| :--- | :--- | :--- | :--- | +| **ENERGY** | Monochromatic, quiet surfaces, restrained single accent, high whitespace. | Controlled dual-tone, crisp contrast, focused focal moments. | High-chroma accents, rich tonal depth, dramatic typographic contrast. | +| **RHYTHM** | Strict linear grid, identical column intervals, predictable reading flow. | Alternating card widths, split hero composition, dynamic content pacing. | Asymmetric editorial layouts, overlapping surfaces, syncopated modular grids. | +| **MOTION** | Zero ambient motion, instant opacity shifts (100ms), pure utilitarian. | Subtle hover feedback (150ms ease-out), tactile press scales (`scale-[0.98]`). | Coordinated page transitions, spring-physics micro-interactions, canvas shaders. | + +*Rule R-37 Invariant: If designing without brand direction, dials MUST be declared honestly as ENERGY 1 / RHYTHM 1 / MOTION 1.* + +--- + +### The 4 Proven Design Archetypes + +Every interface must anchor itself in one coherent archetype to maintain stylistic unity: + +#### 1. Archetype A: High-Precision Developer Tooling (Linear, Raycast, Vercel) +- **Palette**: Deep matte charcoal/zinc (`bg-neutral-950` / `bg-neutral-900`), crisp 1px borders (`border-neutral-800`), high contrast text. +- **Geometry**: Compact 6-8px radii (`rounded-md` / `rounded-lg`), tight padding, monospace metadata chips (`font-mono text-xs`). +- **Tactile Feel**: Keyboard shortcut pills (`⌘K`), instant hover highlights, subtle active press feedback (`active:scale-[0.99]`). +- **Dials Baseline**: ENERGY 2 | RHYTHM 3 | MOTION 2. + +#### 2. Archetype B: Refined SaaS & FinTech (Stripe, Ramp, Mercury) +- **Palette**: Pure white or deep obsidian canvas, single deliberate conversion hue (emerald, indigo, or cobalt), 10% opacity badge fills. +- **Geometry**: 8-12px radii, tabular numerals on all amounts (`tabular-nums`), strict 4px/8px baseline rhythm. +- **Tactile Feel**: Pristine typography contrast (bold geometric display headers with neutral body), authentic ledger models. +- **Dials Baseline**: ENERGY 3 | RHYTHM 3 | MOTION 2. + +#### 3. Archetype C: Human Interface & Modern Editorial (Apple HIG, Notion, Arc) +- **Palette**: Warm neutrals (stone, warm zinc, slate), natural breathing room, soft borders. +- **Geometry**: Generous padding, relaxed line-height (`leading-relaxed`), clean SVG iconography with consistent 1.5px/2px stroke weight. +- **Tactile Feel**: Physical tactile button feedback (`active:scale-[0.98] transition-transform duration-75`). +- **Dials Baseline**: ENERGY 3 | RHYTHM 4 | MOTION 3. + +#### 4. Archetype D: High-Density Analytics & Operations (Datadog, Cloudflare) +- **Palette**: Neutral dark canvas, high-contrast semantic indicators (green/amber/red), color-blind safe palettes. +- **Geometry**: Ultra-compact padding (`px-3 py-1.5`), split panes, explicit filter toolbars, zero decorative fluff. +- **Tactile Feel**: High-contrast sparklines, multi-level breadcrumbs, tabular data grid alignment. +- **Dials Baseline**: ENERGY 2 | RHYTHM 2 | MOTION 1. + +--- + +## Specialized Domain Sub-Disciplines + +### Sub-Discipline 1: Code Comments Hygiene +- **Scope Guardrail**: This filter modifies only comments; never touch executable code, identifiers, formatting, or logic. +- **Eliminate AI Comment Slop**: + - ❌ Decorative box banners (`// =====================`, `/* ----- ROUTES ----- */`). + - ❌ Restating the obvious (`// Increment count` above `count++`, `// User class` above `class User`). + - ❌ Workflow step narration (`// Step 1: Validate`, `// Step 2: Query DB`, `// Finally return`). + - ❌ Empty labels (`// Business logic`, `// Helper function`, `// Important note`). + - ❌ Vague placeholders (`// TODO: Improve this later`, `// Add more validations`). + - ❌ Signature echoing in JSDoc/docstrings (`@param price The price`, `@returns The total`). + - ❌ Decorative emojis in comments (`// ✅ Validated`, `// 🚀 Performance boost`). + - ❌ End-of-block markers (`} // end if`, `# end function`). +- **Preserve Real Engineering Value**: + - ✅ Comments explaining **WHY** (domain invariants, security boundaries, race condition workarounds, upstream vendor bug workarounds). + - ✅ Actionable TODOs with clear scope and context: `// TODO(auth): migrate to session tokens when v2 endpoint ships`. + +--- + +### Sub-Discipline 2: Copywriting & Prose Sanitation +- **Eliminate AI Vocabulary & Hype Bingo**: + - Replace inflated verbs (*unlock, elevate, empower, delve, showcase, revolutionize*) with concrete human actions (*use, build, see, manage*). + - Eliminate significance inflation (*"marking a pivotal moment", "ushering in a new era"*). + - Eliminate unsourced social proof (*"Trusted by thousands of developers"* without named logos). + - Eliminate weasel attributions (*"Experts say", "Industry observers note"*). + - Strict ban on em dashes (`—`) in all copy (R-02). +- **Before / After Matrix**: + - 🔴 *Before*: "Unlock the power of next-generation AI to seamlessly elevate your workflow — revolutionizing team productivity." + - 🟢 *After*: "Automate ticket triage and sync status updates across your engineering team in real time." + +--- + +### Sub-Discipline 3: Human & Accessibility Engineering +- **WCAG 2.2 AA Contrast Enforcement**: + - Minimum 4.5:1 for body text; minimum 3:1 for large text (≥18px). + - Interactive element borders and focus rings must meet minimum 3:1 contrast against adjacent background. +- **Automated Contrast Check**: Run `python scripts/contrast-check.py "#HEX1" "#HEX2"`. +- **Keyboard Navigation & Trap Prevention**: + - All interactive elements must be accessible via keyboard (`Tab`, `Enter`, `Space`, `Escape`). + - Never trap focus in dialogs without an `Escape` key handler and clear close button. + - Interactive elements must declare clear `focus-visible` ring indicators. + +--- + +### Sub-Discipline 4: Mobile & Responsive Layout Ergonomics +- **Continuous Viewport Reflow**: Layouts must look intentional from 320px to 2560px. +- **Fluid Typography**: Use CSS `clamp()` (`clamp(1.5rem, 4vw + 1rem, 3rem)`) instead of static pixel jumps. +- **Touch Target Law**: All interactive elements must measure at least **44x44px** in physical touch area. +- **Dynamic Viewport Height**: Always use `100dvh` (or `min-h-dvh`) instead of `100vh` to prevent mobile address bar overlap. + +--- + +## Mandatory Delivery Gate Protocol + +Before completing any task that involves UI, copy, or code generation, you **MUST** provide the following 4-block report: + +```markdown +### 🛡️ Sovereign Anti-Slop Delivery Gate Report + +#### Block 1: Liveliness Dials & Archetype +- **Design Archetype**: [Archetype A / B / C / D / Custom] +- **Dials Declared**: ENERGY [1-5] | RHYTHM [1-5] | MOTION [1-5] +- **Direction Source**: [`DESIGN.md` / User Brief / Draft without direction (1/1/1)] + +#### Block 2: 38-Rule Compliance Verification +- **Hard Gate (Tier 1)**: [PASS / FAIL] (R-02 Em Dash, R-03 Mobile, R-17 Data, R-25 Contrast, R-26 Functional Controls, R-27 States, R-32 Keyboard, R-35 Verification, R-36 Claims, R-38 Honesty) +- **Purpose-Gate (Tier 2)**: [PASS / FAIL] (R-01 Gradients, R-04 Icons, R-06 Fonts, R-10 Glass Cap, R-11 Radii, R-13 Glow Cap, R-16 Buzzwords, R-31 Separators) +- **Quality Locks (Tier 3)**: [PASS / FAIL] (C-1 Intentionality, C-2 Completeness, C-3 Content, C-4 Resilience, C-5 Evidence) + +#### Block 3: Interactive Element Click-Through Evidence (R-35) +- [Element 1 Name / Target]: [Action observed & state feedback confirmed] +- [Element 2 Name / Target]: [Action observed & validation feedback confirmed] +- [Theme Toggle]: [Both Light and Dark modes rendered with zero console errors] +- [Mobile Viewport Check]: [Reflow confirmed at 375px with zero horizontal scroll] + +#### Block 4: Delivery Verdict +- **Verdict**: [PASS / FAIL] +- **Notes / Overrides**: [Any documented human-approved overrides] +``` + +--- + +## Automated Tooling & Scripts + +The skill includes built-in automated verification tools in `scripts/`: + +1. **AST & Pattern Scanner**: + ```bash + node "scripts/check-anti-slop.js" --summary + node "scripts/check-anti-slop.js" --strict + ``` +2. **WCAG Contrast Checker**: + ```bash + python "scripts/contrast-check.py" "#FFFFFF" "#0F172A" + ``` + +--- + + +## Bahasa Indonesia + +### Arahan Eksekutif & Kondisi Pemicu +**Sovereign Anti-Slop Directive** adalah standar tanpa toleransi yang mengatur seluruh tindakan agen AI di dalam ekosistem vibes-plug. AI slop menurunkan kepercayaan developer, menghabiskan token context, menggelembungkan codebase, dan memicu bug di produksi. + +Anti-slop adalah **filter, bukan style guide**: filter ini tidak mendikte warna, font, atau layout Anda—arah kreatif tetap sepenuhnya milik Anda. Menghapus slop membersihkan kebiasaan klise AI, sementara **Liveliness Toolkit** memastikan produk akhir memiliki jiwa, karakter, dan ketegasan visual yang hidup, bukan menjadi tampilan yang steril. + +**Kondisi Pemicu Universal:** +- **Setiap Pembuatan & Modifikasi Kode**: Setiap fungsi, komponen, atau file yang dibuat atau diubah agen. +- **Pekerjaan UI & Frontend**: Desain antarmuka, tata letak halaman, komponen, kartu, dashboard, dan gaya responsif. +- **Copywriting & Teks**: Judul, CTA, teks produk, dokumentasi, pesan commit, dan ringkasan PR. +- **Komentar Kode**: Komentar penjelasan, anotasi inline, dan docstring. +- **Quality Gates & Audit PR**: Review kode (`coderabbit`), pengujian mandiri (`autonomous-tdd-debugger`), dan hardening pra-rilis (`production-ready-hardener`). + +--- + +### Protokol Dua Mode Operasi (Two Usage Modes) +1. **Mode 1: DURING (Pencegahan Real-Time Saat Bekerja)**: + - Agen menerapkan 38 aturan secara aktif saat menulis kode, copy, dan UI. + - Mencegah slop masuk ke codebase sejak awal. + - Ditutup dengan laporan wajib **Delivery Gate**. +2. **Mode 2: AFTER (Audit & Remediasi Pasca Proyek Selesai)**: + - Mengaudit proyek yang sudah ada tanpa mengubah file secara prematur. + - Menghasilkan laporan audit bernomor: `anti-slop/audit-001-YYYY-MM-DD.md`. + - Setiap temuan diberi nomor urut, pasal pelanggaran (`R-XX`), dan prioritas (Hard Gate = `HIGH`, Purpose-Gate = `MEDIUM`, Quality Lock = `LOW`). + - Agen **wajib menunggu persetujuan manusia** atas nomor temuan yang ingin diperbaiki sebelum menyentuh kode. + +--- + +### Kerangka 38 Aturan Wajib (3-Tier Rule Framework) + +#### Tier 1: Hard Gate (Mutlak, Tanpa Pengecualian) +- **R-02 Copywriting**: Larangan mutlak tanda em dash (`—`) pada teks buatan AI. Gunakan koma, titik, atau titik dua. +- **R-03 Responsivitas Mobile**: Layout mobile wajib dirancang khusus dengan reflow continuous; target sentuh minimal **44x44px**; gunakan `100dvh`; dilarang ada overflow horizontal. +- **R-17 Data & Angka Autentik**: Dilarang mengarang statistik atau angka fiktif (`99.9% uptime`, `10,000 users`). Jika data tidak tersedia, jangan tampilkan angka atau gunakan `[REAL DATA]`. +- **R-18 Testimoni Autentik**: Dilarang membuat avatar AI, nama samaran, atau ulasan fiktif. +- **R-23 Konfirmasi Aset Visual**: Dilarang mengasumsikan logo/avatar final tanpa konfirmasi; gunakan penanda jujur `[LOGO]`. +- **R-24 Integritas Navigasi**: Dilarang menempatkan tautan di navbar menuju halaman/bagian yang tidak ada. +- **R-25 Kontras Warna (WCAG AA)**: Minimal 4.5:1 untuk teks normal; 3:1 untuk teks besar (≥18px). Validasi menggunakan script `contrast-check.py`. +- **R-26 Kelengkapan Elemen Interaktif**: Setiap tombol, link, dan dropdown wajib memiliki perilaku nyata atau dihapus. Dilarang ada tombol mati. +- **R-27 Tiga State UI Wajib**: Setiap tampilan data wajib memiliki state **Empty**, **Loading** (skeleton loader), dan **Error** (dengan tombol coba lagi). +- **R-28 FAQ Spesifik**: FAQ harus menjawab pertanyaan riil domain produk, bukan template klise. +- **R-32 Aksesibilitas Keyboard**: Semua kontrol interaktif harus dapat diakses via keyboard dan memiliki indikator fokus yang kontras (`focus-visible:ring-2`). +- **R-33 Larangan Patching File via Script**: Dilarang menambahkan fitur lewat script eksternal yang melakukan string-replace pada file CSS/TSX. +- **R-34 Seluruh Tema Wajib Berfungsi Penuh**: Jika menyediakan toggle tema, mode Terang dan Gelap wajib 100% berfungsi dan lulus uji kontras. +- **R-35 Verifikasi Sebelum Penyerahan (Click-Through)**: Wajib menjalankan aplikasi dan mencatat bukti click-through setiap elemen interaktif sebelum dinyatakan selesai. +- **R-36 Larangan Klaim Kepatuhan Fiktif**: Dilarang mengarang lencana sertifikasi (SOC 2, ISO 27001) atau klaim akselerasi fiktif. +- **R-37 Arah Desain Wajib**: Wajib bersumber dari `DESIGN.md`. Jika tanpa arah, wajib dideklarasikan sebagai *"Draft without direction"* dengan dial **ENERGY 1 / RHYTHM 1 / MOTION 1**. +- **R-38 Konten Nyata atau Placeholder Jujur**: Seluruh konten harus berupa data nyata atau penanda eksplisit (`[REAL DATA]`). + +#### Tier 2: Purpose-Gate (Boleh Digunakan Hanya Jika Ada Tujuan Tertulis & Batasan Dosis) +- **R-01 Warna & Gradien**: Gradien biru-ungu/neon dilarang sebagai default; hanya boleh untuk pemisah hierarki dengan alasan tertulis. +- **R-04 Ikon**: Ikon sparkle, bintang, orb, dan robot dilarang sebagai default. +- **R-06 Tipografi**: Font monospace berlebihan dan judul uppercase dengan tracking renggang dilarang tanpa alasan keterbacaan. +- **R-07 Latar Belakang**: Grid titik, garis blueprint, dan grafis kotak-kotak dilarang sebagai shortcut visual. +- **R-08 Ritme Spasi**: Spasi seragam di setiap bagian dilarang; gunakan variasi ritme vertikal. +- **R-09 Variasi Layout**: Layout formulaik klise (Hero -> 3 kartu -> 3 langkah -> Bento grid -> Pricing -> FAQ) dilarang. +- **R-10 Batas Glassmorphism**: Efek frosted glass dibatasi **maksimal 1-2 elemen** per halaman (misalnya hanya header sticky). +- **R-11 Batas Border Radius**: Radius pil (`rounded-full`) dilarang pada tombol persegi panjang atau kartu. Gunakan skala 6-8px untuk kontrol dan 12-16px untuk kartu. +- **R-12 Shadow Membumi**: Shadow melayang berwarna neon dilarang; gunakan border 1px solid dan elevasi halus. +- **R-13 Batas Glow**: Efek pendaran neon dibatasi maksimal 1-2 elemen fokus. +- **R-14 Animasi Berbobot**: Animasi berulang tanpa henti (kartu melayang) dilarang; animasi transisi wajib cepat (150-250ms). +- **R-15 CTA Berorientasi Aksi**: Ganti CTA generik (*Get Started*, *Learn More*) dengan instruksi spesifik (*Buat akun gratis*, *Baca dokumentasi API*). +- **R-16 Eliminasi Buzzword**: Hapus kata-kata klise AI (*unlock, elevate, seamless, revolutionize, game-changer*). +- **R-19 Visual Kontekstual**: Ilustrasi 3D blob generik dilarang; gunakan screenshot produk asli atau diagram teknis. +- **R-20 Dekorasi Fungsional**: Garis strip vertikal di tepi kartu dan panah dekoratif (`→`) dilarang jika tanpa fungsi. +- **R-21 Demo Produk Nyata**: Menjual alat tanpa memperlihatkan interface nyata dilarang. +- **R-22 Alasan Mode Gelap**: Mode gelap harus didasarkan pada karakter brand, bukan sekadar latah default. +- **R-29 Lencana Kapsul**: Lencana pil "AI Powered" dengan dot berkedip dilarang kecuali mewakili status runtime asli. +- **R-30 Eyebrow Badge Redundan**: Lencana kecil di atas H1 yang mengulang kata-kata judul dilarang. +- **R-31 Larangan Separator Banner Kode**: Garis pembatas dekoratif (`// =====================`) pada komentar kode dilarang. + +#### Tier 3: Quality Locks & Craftsmanship (C-1 sampai C-5) +- **C-1 Intentionality**: Setiap keputusan desain dan kode memiliki alasan yang dapat dipertanggungjawabkan. +- **C-2 Kelengkapan Fungsional**: Setiap kontrol berfungsi utuh tanpa stub setengah jadi. +- **C-3 Komposisi Berbasis Konten**: Setiap seksi ada karena dibutuhkan produk, bukan sekadar pengisi template. +- **C-4 Ketahanan Sistem**: UI bertahan pada seluruh 3 state (empty, loading, error), semua tema, dan navigasi keyboard. +- **C-5 Bukti Di Atas Klaim**: Fakta yang disajikan terverifikasi secara nyata. + +--- + +### Liveliness Toolkit: 3 Dial & 4 Arsitektur Desain + +Untuk mencegah antarmuka jatuh ke dalam kegagalan sebaliknya—yaitu desain yang steril, datar, dan membosankan—anti-slop menggunakan **3 Dial Karakter**: +1. **ENERGY (1-5)**: Skala 1 (monokromatik, sunyi) hingga Skala 5 (aksen berani, kontras tinggi). +2. **RHYTHM (1-5)**: Skala 1 (grid linear kaku) hingga Skala 5 (tata letak editorial dinamis). +3. **MOTION (1-5)**: Skala 1 (statis murni) hingga Skala 5 (transisi halus berbasis fisika). + +#### 4 Arsitektur Desain Teruji: +1. **Archetype A: High-Precision Developer Tooling** (Linear, Raycast, Vercel) + - Permukaan matte gelap (`bg-neutral-950`), border 1px solid, tombol shortcut keyboard (`⌘K`), font mono untuk metadata, padding ringkas. +2. **Archetype B: Refined SaaS & FinTech** (Stripe, Ramp, Mercury) + - Latar belakang bersih, kontras display header tegas, angka tabular (`tabular-nums`), ritme spasi 4px/8px, data transaksi otentik. +3. **Archetype C: Human Interface & Modern Editorial** (Apple HIG, Notion, Arc) + - Nuansa hangat netral (stone/slate), padding lega, feedback sentuhan fisik (`active:scale-[0.98]`), ikonografi SVG konsisten. +4. **Archetype D: High-Density Analytics & Operations** (Datadog, Cloudflare) + - Kepadatan informasi tinggi, breadcrumbs bertingkat, sparklines kontras tinggi, palet aman untuk buta warna, nol dekorasi sia-sia. + +--- + +### Protokol Wajib Delivery Gate + +Sebelum menyelesaikan tugas coding atau UI, Anda **WAJIB** menyertakan 4 blok laporan ini: +1. **Konfirmasi Dial & Archetype**: Nama archetype dan nilai dial (ENERGY/RHYTHM/MOTION). +2. **Checklist Kepatuhan 38 Aturan**: Evaluasi PASS/FAIL pada Hard Gate, Purpose-Gate, dan Quality Locks. +3. **Bukti Click-Through Elemen Interaktif (R-35)**: Daftar elemen yang telah dicoba langsung beserta perilakunya. +4. **Keputusan Akhir (Verdict)**: PASS atau FAIL. + +--- + +## Orchestration & Integration + +This skill serves as the foundational quality, craftsmanship, and anti-slop gate across the entire vibes-plug swarm architecture. It actively connects to and hardens: + +| Skill | Relationship & Integration Flow | +| :--- | :--- | +| `senior-frontend` | Sanitizes React 19 / Next.js 15 components from generic AI templates and unhandled states. | +| `tailwind-expert` | Enforces CSS-first styling, eliminates excessive pill buttons, and prevents stacked neon glows. | +| `design-system-architect` | Validates 5-state interactive contracts, accessible tokens, and solid borders. | +| `autonomous-tdd-debugger` | Enforces 100% complete implementations on the first try without test skips or fake mocks. | +| `production-ready-hardener` | Acts as the final delivery quality gate before any release or production deployment. | +| `zero-tech-debt-auditor` | Scans and eradicates syntax narration comments, dead code, and speculative abstractions. | +| `coderabbit` | Powers the autonomous PR review and code inspection engine. | \ No newline at end of file diff --git a/vibes-plug/skills/anti-slop/scripts/check-anti-slop.js b/vibes-plug/skills/anti-slop/scripts/check-anti-slop.js new file mode 100644 index 000000000..45be3d713 --- /dev/null +++ b/vibes-plug/skills/anti-slop/scripts/check-anti-slop.js @@ -0,0 +1,333 @@ +#!/usr/bin/env node +/** + * skills/anti-slop/scripts/check-anti-slop.js + * Sovereign Anti-AI Slop Validator Engine (2026 Edition) + * Fast, zero-dependency AST/Regex scanner for catching AI slop, lazy placeholders, + * obvious narration comments, zombie code, and sycophantic artifacts. + */ + +const fs = require('fs'); +const path = require('path'); + +// CLI Arguments +const args = process.argv.slice(2); +const isStrict = args.includes('--strict'); +const isFix = args.includes('--fix'); +const isJson = args.includes('--json'); +const isSummary = args.includes('--summary'); +const targetPathArg = args.find(a => !a.startsWith('--')); +const rootDir = targetPathArg ? path.resolve(targetPathArg) : process.cwd(); + +// Patterns Definition +const CODE_ERROR_PATTERNS = [ + { + id: 'LAZY_TRUNCATION', + name: 'Lazy Truncation / Ellipsis Placeholder', + regex: /\/\/\s*(\.\.\.|…)\s*(rest|code|implement|logic|remain|existing|unchanged|here)/i, + description: 'Never truncate code with ellipses; output complete implementation.' + }, + { + id: 'UNFINISHED_TODO', + name: 'Unfinished AI Stub or TODO', + regex: /\/\/\s*(TODO|FIXME|HACK|XXX):\s*(implement|add logic|fill in|later|placeholder|write here)/i, + description: 'Unfinished stubs left by lazy model generations.' + }, + { + id: 'NOT_IMPLEMENTED_THROW', + name: 'Unimplemented Exception Throw', + regex: /throw\s+new\s+(Error|NotImplementedError|UnsupportedOperationException)\s*\(\s*['"`](Not implemented|TODO|stub|WIP)['"`]\s*\)/i, + description: 'Code throwing stubbed "Not implemented" exceptions.' + }, + { + id: 'MOCK_DATA_LEFTOVER', + name: 'Mock Data Leftover in Production', + regex: /\/\/\s*(mock data for now|dummy data|placeholder for real api)/i, + description: 'Hardcoded fake data comment instead of real database/API queries.' + }, + { + id: 'SILENT_ERROR_SUPPRESSION', + name: 'Silent Catch Block (Swallowed Error)', + regex: /catch\s*(\([a-zA-Z0-9_]*\))?\s*\{\s*(\/\/[^\n]*)?\s*\}/, + description: 'Empty catch block that silently suppresses errors without handling or logging.' + }, + { + id: 'PYTHON_PASS_STUB', + name: 'Python Pass / Ellipsis Stub', + regex: /^\s*(def|class)\s+[a-zA-Z0-9_]+.*:\s*(#\s*TODO.*)?\n\s*(pass|\.\.\.)\s*$/m, + description: 'Unfinished Python function or class stubbed with pass/...' + }, + { + id: 'UI_LOREM_IPSUM', + name: 'Lorem Ipsum Placeholder in Code', + regex: /(Lorem\s+ipsum\s+dolor\s+sit\s+amet|consectetur\s+adipiscing\s+elit)/i, + description: 'Never use Lorem Ipsum text in production code; use domain-authentic mock content.' + } +]; + +const CODE_WARN_PATTERNS = [ + { + id: 'DECORATIVE_SEPARATOR_BANNER', + name: 'Decorative Banner / Separator Box Comment (R-31)', + regex: /\/\/\s*([=*-]{5,}|#\s*={5,})/i, + description: 'Decorative box-drawing and separator banners signal AI-generated code. Use clean single-line comments or code structure.' + }, + { + id: 'AI_MARKETING_BUZZWORDS', + name: 'AI Copywriting Buzzwords (R-16)', + regex: /\b(unlock(ing)?\s+the\s+power|game-changer|delve|testament\s+to|revolutionary\s+new\s+era|seamless(ly)?\s+elevat(e|ing))\b/i, + description: 'Generic AI marketing buzzwords detected. Replace with direct, plain factual statements.' + }, + { + id: 'SYNTAX_NARRATION', + name: 'Syntax-Narrating Obvious Comment', + regex: /\/\/\s*(increment\s+\w+|return\s+(the\s+)?\w+|import\s+\w+\s+from|set\s+\w+\s+to\s+\w+|initialize\s+\w+|define\s+\w+|call\s+\w+)/i, + description: 'Comments narrating obvious code mechanics rather than explaining business/architectural rationale.' + }, + { + id: 'CONSOLE_LOG_DEBRIS', + name: 'Console Debugging Debris', + regex: /(?]*>[^<]*[🚀✨🔥🎉💡][^<]*<\/(h[1-6]|button|span|p)>/u, + description: 'Decorative emojis in headings or buttons scream AI slop. Remove or replace with real icons (antislop-ui).' + }, + { + id: 'UI_NEON_GLOW_ORB', + name: 'Generic AI Blurred Neon Radial Orb', + regex: /(bg-(purple|blue|cyan|fuchsia|violet|indigo)-[456]00\/[0-9]+\s+rounded-full\s+blur-[23]xl|blur-[23]xl\s+bg-(purple|blue|cyan|fuchsia|violet|indigo)-[456]00)/i, + description: 'Blurred neon radial orb detected. AI slop hero backdrop; use purposeful lighting or clean solid surfaces (antislop-ui).' + }, + { + id: 'UI_PILL_ADDICTION', + name: 'Pill Button Gradient Slop', + regex: /]*className="[^"]*\brounded-full\b[^"]*(bg-gradient|from-)[^"]*"/i, + description: 'Pill button with gradient detected. Use structured 3-tier radius scale (6px/8px/12px) without generic gradient (antislop-ui).' + }, + { + id: 'UI_FAKE_PING_DOT', + name: 'Decorative Pulsing Status Ping', + regex: /]*className="[^"]*\banimate-ping\b[^"]*"\s*(?:\/>|>[^<]*<\/span>)/i, + description: 'Decorative pulsing status ping detected. Only use status dots for verified real-time telemetry (antislop-ui).' + }, + { + id: 'UI_ZERO_GRAVITY_SHADOW', + name: 'Zero-Gravity Colored Drop-Shadow', + regex: /\bshadow-2xl\s+shadow-(purple|indigo|blue|violet)-[456]00/i, + description: 'Zero-gravity colored drop-shadow detected. Use crisp 1px borders and subtle physical elevation (antislop-ui).' + }, + { + id: 'UI_UNSTYLED_CLICKABLE_DIV', + name: 'Clickable Div Without Keyboard/Button Role', + regex: /]+onClick=(?!.*(role=["']button["']|onKeyDown|tabIndex|aria-))/i, + description: 'Clickable
without keyboard accessibility or button role. Use semantic + ); +} +``` + +### 3 Hukum Utama Pengembangan Web3 Modern +1. **Gunakan Viem daripada Ethers v5 Lawas**: Viem dirancang khusus dengan performa tinggi, ukuran bundle 70% lebih kecil, dan inferensi tipe ABI otomatis. +2. **Wajib Transpor Multi-RPC Fallback**: Jangan bergantung pada satu URL RPC publik yang sering mengalami *rate-limit*. Konfigurasikan penyedia cadangan (Alchemy, Infura, QuickNode). +3. **Pemberitahuan Status Transaksi Lengkap**: Tampilkan umpan balik visual yang jelas bagi setiap fase: menunggu konfirmasi dompet, proses penambangan blok (*mining*), hingga konfirmasi akhir di blockchain. + +## Integrasi Orkestrasi +- **`senior-frontend`**: Mengatur penyedia WagmiProvider di root aplikasi Next.js. +- **`authentication-identity-expert`**: Menghubungkan alamat dompet dengan data profil pengguna di database. +- **`error-resilience-expert`**: Mengatur strategi percobaan ulang saat terjadi kegagalan jaringan RPC. +- **`post-quantum-crypto-migrator`**: Memantau perkembangan keamanan algoritma tanda tangan kriptografi generasi berikutnya. \ No newline at end of file diff --git a/vibes-plug/skills/brainstorming/SKILL.md b/vibes-plug/skills/brainstorming/SKILL.md new file mode 100644 index 000000000..1a0fb3c70 --- /dev/null +++ b/vibes-plug/skills/brainstorming/SKILL.md @@ -0,0 +1,406 @@ +--- +name: brainstorming +description: "Master ideation protocol & architectural orchestrator with Modern Web Guidance. Validates design ideas and orchestrates all specialized vibes-plug skills before coding begins / Protokol ideasi utama & orkestrator arsitektur dengan Modern Web Guidance. Memvalidasi ide desain dan mengorkestrasi seluruh skill vibes-plug sebelum pengkodean dimulai." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Brainstorming & Skill Orchestration Protocol + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Purpose & Overview +Turn raw ideas into **clear, validated designs, architectural specifications, and execution roadmaps** through structured dialogue **before any implementation begins**. + +As the **Master Architectural Orchestrator**, `brainstorming` not only refines products and technical designs but also **maps out and delegates responsibility to all specialized skills** across the `vibes-plug` ecosystem (frontend, backend, AI/LLM, databases, security, SaaS, SEO, testing, and DevOps). + +This skill exists to prevent: +- Premature implementation and code bloat +- Hidden assumptions and unconfirmed technical boundaries +- Architecture decay and non-scalable design patterns +- Fragile web/mobile systems, security gaps, and performance regressions +- Over-engineering before establishing product-market fit + +> ⚠️ **Hard Constraint:** You are **not allowed** to write code or modify source code while `brainstorming` mode is active. Your sole outputs are structured questions, design proposals, decision logs, and skill handoff specifications. **For new applications, you MUST always automatically trigger the `prd-architect` skill to generate a `PRD.md` file before coding begins.** + +--- + +### Skill Integration & Orchestration Matrix + +During brainstorming, consult, reference, and orchestrate the following specialized skills based on project requirements: + +| Domain / Phase | Orchestrated Skills | Trigger & Delegation Context | +| :--- | :--- | :--- | +| **Discovery & Audit** | `prd-architect`, `deep-research-analyst`, `app-analyzer-optimizer`, `web-scraper`, `website-design-cloner`, `browser-automation-expert`, `dependency-upgrade-migrator`, `session-memory-manager`, `proactive-background-watcher`, `documentation-site-expert`, `headless-cms-expert`, `wordpress-headless-expert` | Formulate formal PRD, ERD, and Documentation, autonomous deep web research & evidence triangulation, audit existing codebases, cross-project memory, reverse-engineer website URL designs 1:1, scrape reference products, headless CMS/WP architecture discovery, docs site setup, execute autonomous Playwright/Browser-Use web agents, or audit dependency health. | +| **UI/UX & Design Systems** | `design-system-architect`, `website-design-cloner`, `multimodal-spatial-video-cloner`, `screenshot-to-code-expert`, `hig`, `ui-ux-pro-max`, `affective-computing-emotion-ai`, `tailwind-expert`, `anti-slop`, `svg-animation-motion-expert`, `web-3d-graphics-expert`, `glsl-shader-expert`, `webxr-ar-vr-expert`, `browser-automation-expert`, `data-visualization-expert`, `rich-text-editor-expert`, `modern-css-native-expert`, `ephemeral-generative-ui-architect`, `visual-ui-auditor` | Reverse-engineer website designs & templates directly from target URL, multimodal screen-capture to code, design tokens (OKLCH), Tailwind CSS v4, native CSS 2026 anchor positioning, Apple HIG principles, layout hierarchy, production-quality UI components, rich text editors (Tiptap/Lexical), data viz & charts (Recharts/Tremor/D3), modernizing legacy apps with legacy-code-translator, WebGPU & WebGL 3D (Three.js WebGPU/TSL, Babylon.js, PlayCanvas), custom GLSL/WGSL shaders, WebXR AR/VR, visual UI regression audits, zero-tolerance anti-slop visual cleanliness. | +| **Frontend Frameworks** | `senior-frontend`, `vercel-ai-sdk-expert`, `vue-frontend-expert`, `astro-framework-expert`, `svelte-sveltekit-expert`, `solidjs-expert`, `angular-expert`, `tanstack-query-expert`, `global-a11y-i18n-expert`, `state-management-expert`, `form-validation-expert`, `apple-ecosystem-expert`, `blockchain-web3-expert`, `pwa-offline-first-expert` | React 19 / Next.js 15 App Router, Vercel AI SDK Core/UI streaming, Vue 3 / Nuxt 3, Astro 5+ Islands, Svelte 5 Runes / SvelteKit 2, SolidJS 2 / SolidStart, Angular 19+ Signals & Standalone, Web3 dApp integrations (wagmi/viem), async state management (Zustand/Jotai/Pinia), WCAG 2.2 a11y, multi-language i18n, complex forms with React Hook Form + Zod, Local-First offline architectures (RxDB/PowerSync). | +| **Mobile, Desktop & Extensions** | `mobile-expo-expert`, `apple-ecosystem-expert`, `tauri-expert`, `desktop-electron-expert`, `browser-extension-mv3-pro`, `email-notification-expert`, `pwa-offline-first-expert` | Cross-platform React Native / Expo Router v4, Apple ecosystem (iOS PWA & Safari), Chrome/Firefox/Safari Manifest V3 extensions (SidePanel API, offscreen WASM sandbox, service workers), iOS Live Activities, push notifications (FCM/APNs), Rust-powered Tauri v2, Electron 33+ desktop apps, or PWA app store distribution (PWABuilder). | +| **Backend & Runtimes** | `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert`, `python-programming-expert`, `pydantic-ai-expert`, `go-programming-expert`, `rust-programming-expert`, `bun-runtime-expert`, `mvc-expert`, `domain-driven-design-expert`, `fullstack-expert`, `async-queue-temporal-expert`, `cron-scheduler-expert`, `legacy-code-translator`, `api-gateway-proxy-expert`, `wasm-edge-computing-expert`, `ephemeral-wasm-sandbox-executor`, `n8n-automation-expert`, `chatbot-messaging-expert`, `pdf-document-generation-expert`, `parallel-tool-orchestrator` | API design, Node.js 24, Bun 1.2+, FastAPI, Pydantic AI type-safe agents, Go microservices, Rust Axum, API Gateways, Edge computing WASM, ephemeral WASM sandboxing, durable workflows (Temporal/Trigger.dev/BullMQ), scheduled tasks, parallel tool batch orchestration, n8n workflow automation, WhatsApp/Telegram/Discord bots, PDF & document pipelines. | +| **API Design & Contracts** | `api-design-expert`, `openapi-swagger-codegen-expert`, `spec-driven-development-expert`, `typescript-expert`, `rate-limit-abuse-prevention`, `graphql-apollo-expert`, `autonomous-api-drift-healer`, `formal-spec-z3-verifier`, `structured-output-contracts` | REST best practices, TypeSpec & OpenAPI 3.1 contract-first specs, strict JSON Schema & Pydantic/Zod structured output guarantees, BDD Gherkin & consumer-driven contract testing (Pact), GraphQL schema (Apollo/NestJS), gRPC/protobuf, tRPC end-to-end type safety, autonomous API drift healing & adapter synthesis, formal SMT/Z3 invariant verification, rate limiting, API key management, idempotency, versioning strategy. | +| **Database, ORM & Data** | `database-orm-expert`, `vector-db-rag-expert`, `supabase-security-expert`, `firebase-security-expert`, `autonomous-red-teamer`, `data-pipeline-etl-expert`, `search-engine-expert`, `xerj-search-expert`, `geospatial-maps-expert`, `graph-rag-knowledge-expert` | Prisma 6 / Drizzle ORM, zero-downtime migrations, serverless DBs (Neon/D1/Turso), Data pipelines (dbt/Dagster), pgvector HNSW RAG indexing, Knowledge Graphs (Neo4j/Microsoft GraphRAG), full-text search (Typesense/Meilisearch/Elasticsearch/XERJ), geospatial queries (PostGIS/GeoJSON/Mapbox), Supabase RLS, Firebase security rules. | +| **Architecture & Scale** | `monorepo-architect`, `event-driven-architect`, `cloud-hosting-expert`, `mpa-orchestrator`, `spa-orchestrator`, `scalability-clean-code`, `micro-frontend-architect`, `web-game-engine-expert`, `biome-linter-formatter-expert`, `composable-mach-architect`, `living-codebase-ast-graph` | Monorepos (Turborepo/pnpm), living AST dependency graph analysis, Biome v2 linter/formatter, microservices, event queues, multi-entry apps, MPA & SPA setups, clean code principles, micro-frontends (Webpack/Vite Federation), Composable MACH Architecture, Web game engines (PlayCanvas, Havok/Jolt/Rapier WASM physics, Fixed-Timestep ECS loops, WebTransport netcode). | +| **AI & LLM Integration** | `ai-llm-integration-expert`, `deep-research-analyst`, `vercel-ai-sdk-expert`, `pydantic-ai-expert`, `synthetic-data-finetuning-expert`, `ai-prompt-engineering-expert`, `ai-media-generation-expert`, `vector-db-rag-expert`, `mcp-server-architect`, `multi-agent-orchestration`, `gemini-agent-booster`, `doku-mcp-server`, `xerj-search-expert`, `local-slm-edge-ai-expert`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai`, `graph-rag-knowledge-expert`, `agentic-memory-architect`, `llm-finops-router`, `agentic-micro-economy-architect`, `test-time-compute-optimizer`, `kv-cache-prefix-optimizer`, `speculative-multi-draft-synthesizer`, `context-window-engineer`, `adaptive-model-cascade`, `llm-observability-expert`, `thinking-budget-orchestrator`, `parallel-tool-orchestrator`, `structured-output-contracts` | Autonomous deep research & citation verification, Vercel AI SDK Core/UI streaming, Pydantic AI type-safe agents, synthetic data generation & QLoRA fine-tuning (Unsloth), RAG pipelines, GraphRAG & Knowledge Graphs, real-time conversational voice AI (<300ms WebRTC/WebSocket), MCP Server v1.x (FastMCP/Streamable HTTP/Client tool discovery/XERJ 13-tools), AI media generation, LangGraph multi-agent workflows, Gemini Agent long-context reasoning, local SLMs in-browser (WebGPU/WebLLM), automated AI evals & benchmarks (Promptfoo/DeepEval), LLM FinOps, long-term episodic memory, test-time compute optimization, KV-cache prefix locking, speculative multi-draft code synthesis, dynamic thinking token budgeting, parallel tool batch dispatching, strict structured output schema contracts. | +| **Frontier AI & Simulation** | `frontier-ai-models-expert`, `ai-llm-integration-expert`, `multi-agent-orchestration`, `gemini-agent-booster`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai`, `browser-automation-expert`, `local-slm-edge-ai-expert`, `ai-safety-governance-expert`, `agentic-coding-workflow-expert`, `ephemeral-generative-ui-architect`, `test-time-compute-optimizer`, `kv-cache-prefix-optimizer`, `speculative-multi-draft-synthesizer`, `context-window-engineer`, `adaptive-model-cascade`, `prompt-injection-firewall`, `thinking-budget-orchestrator`, `parallel-tool-orchestrator`, `structured-output-contracts` | Google Gemini 4 Pro / Project Astra (Gemini 4), Claude 5.1 (Fable/Mythos), Enterprise Frontier Safeguards (EFS), Continuous multimodal streaming, CUA agents, narrative simulation swarms, episodic memory, test-time compute scaling (MCTS/PRM), KV-cache prefix optimization, speculative multi-draft synthesis, dynamic thinking token budgeting, parallel tool execution, strict structured JSON schema contracts, AI safety guardrails, agentic coding workflows | +| **SaaS & Multi-Tenancy** | `saas-architect`, `saas-multi-tenant`, `saas-billing`, `agentic-micro-economy-architect`, `agentic-m2m-settlement`, `feature-flag-analytics-expert`, `payment-gateway-expert`, `ecommerce-expert`, `doku-payment-gateway`, `email-notification-expert` | Master SaaS lifecycle (MVP launch 0-to-1 & transformation 1-to-N), e-commerce architectures (Shopify/Medusa/Saleor), RLS tenant isolation, Stripe/DOKU Checkout & SNAP BI billing, agentic M2M micro-clearing and settlement, feature flags (PostHog/LaunchDarkly), progressive rollout, transactional email & notification pipelines. | +| **Testing & Security** | `e2e-testing-expert`, `accessibility-testing-expert`, `browser-automation-expert`, `zero-trust-secret-vault`, `anti-slop`, `coderabbit`, `authentication-identity-expert`, `rate-limit-abuse-prevention`, `autonomous-tdd-debugger`, `autonomous-red-teamer`, `post-quantum-crypto-migrator`, `compliance-gdpr-privacy-expert`, `ai-prompt-engineering-expert`, `ephemeral-wasm-sandbox-executor`, `formal-spec-z3-verifier`, `prompt-injection-firewall`, `ai-code-review-autonomous`, `property-mutation-testing-expert`, `mcp-sampling-critic`, `visual-ui-auditor` | Playwright E2E suites, automated WCAG 2.2 accessibility testing (axe-core/Pa11y), dynamic security fuzzing & adversarial attacks, ephemeral WASM sandboxing, formal Z3 invariant verification, automated AI evals & benchmarks (Promptfoo/DeepEval/Ragas), GDPR/PDPA compliance, post-quantum crypto migration, Zero-Trust secrets, automated code review, zero-slop code quality gates, auth, brute-force & DDoS prevention, autonomous TDD debugging, MCP sampling / critic-in-the-loop validation, visual UI regression audits. | +| **Error Handling & Resilience** | `error-resilience-expert`, `logging-error-tracking-expert` | Chaos engineering, automated failure injection, React Error Boundaries, API error standards (RFC 9457), retry patterns, circuit breakers, graceful degradation, structured logging (Pino), Sentry integration. | +| **Communication & Notifications** | `email-notification-expert`, `realtime-collaboration-expert`, `sse-websocket-streaming-expert`, `chatbot-messaging-expert`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai` | Transactional email (Resend/Postmark), push notifications (Expo Push/FCM/APNs), conversational voice agents (OpenAI Realtime/Gemini Live), React Email templates, in-app notifications, messaging bots (WhatsApp/Telegram/Discord/Slack), streaming responses (SSE/WebSocket), real-time collaboration. | +| **File & Media** | `file-upload-media-expert`, `ai-media-generation-expert`, `app-promo-media-expert`, `pdf-document-generation-expert` | Presigned URL uploads (S3/R2), image optimization (Sharp), video transcoding (Mux), AI media generation, App Store/Play Store promo screenshots, social launch graphics & Remotion programmatic promo videos, PDF generation (React PDF/Puppeteer), CDN configuration, drag-and-drop UI, file validation & security. | +| **Performance** | `performance-web-vitals`, `app-analyzer-optimizer` | Core Web Vitals (LCP, INP, CLS), bundle optimization, image/font loading, React concurrent features, Lighthouse score improvement, deep architecture analysis. | +| **SEO, GEO & Telemetry** | `seo`, `data-telemetry-expert` | Technical SEO audits, Generative Engine Optimization (AI Overviews, `/llms.txt`), AEO landing pages, OpenTelemetry/PostHog analytics. | +| **DevOps & CI/CD** | `ci-cd-devops-architect`, `cloud-hosting-expert`, `dependency-upgrade-migrator`, `self-healing-cloud-orchestrator`, `biome-linter-formatter-expert`, `autonomous-api-drift-healer` | GitHub Actions, Biome lint/format checks, Docker, Kubernetes, Terraform, Vercel/Cloudflare deployment, self-healing cloud operations, autonomous API drift healing, Renovate Bot, dependency health. | +| **Execution Handoff** | `zero-to-prod-orchestrator`, `production-ready-hardener`, `zero-tech-debt-auditor`, `prd-architect`, `session-memory-manager`, `anti-slop` | Handing off validated designs to 8-phase production pipeline, pre-launch hardening, zero technical debt audit (Knip/DRY/strict types), continuous docs logging (`CHANGELOG.md`), loading context on new sessions, ultra-compact handoff checkpoints, token efficiency, zero AI slop enforcement. | + +--- + +### Operating Mode & Swarm Director Protocols +You operate as a **Principal Web Architect, Design Facilitator, and Swarm Director**. +- No creative implementation during ideation +- No speculative features without user confirmation +- No silent assumptions — log and verify every default +- No skipping hard gates +- **Prefix KV-Caching Determinism (`kv-cache-prefix-optimizer`)**: Ensure this document's structure and all subsequent prompt prefixes remain completely static and deterministic across turns. This enables Gemini 4 Pro and modern frontier LMs to leverage KV-Caching, drastically reducing Time-to-First-Token (TTFT) and token costs by 75-90%. +- **Sovereign Token Frugality without Fidelity Loss (`adaptive-model-cascade`)**: + - Prune subagent context payloads during Fan-Out: pass only targeted `CONTEXT_MAP.md` slices, relevant interface contracts, and target file paths. Never dump raw chat histories. + - Route subagent tasks by complexity: use `flash_lite` or `flash` for research, search, and linting checks; reserve `pro` or `inherit` for system design and critical security audits. + - Enforce ultra-compact handoffs via `session-memory-manager` (<300 tokens) to prevent context window exhaustion. + - **Non-Degradation Invariant**: Never truncate code with `// TODO` or `// ...` to save tokens. Code must remain 100% complete and working. +- **Swarm Execution Topology**: When planning multi-domain phases, orchestrate subagents using: + 1. *Fan-Out / Fan-In*: Parallel execution across UI, Backend, and DB with selective context pruning. + 2. *Pipeline Saga*: Sequential execution across Phases 1-8. + 3. *Critic-Validator Loop*: Implementer code review and autonomous TDD self-healing before user handoff. + +Your job is to **slow the process down just enough to get the architecture, swarm delegation, and skill plan right**. + +--- + +### The 8-Step Integrated Orchestration Pipeline + +``` + STEP 1 STEP 2 STEP 3 STEP 4 +Context Discovery ---> Product Ideation ---> Modern Stack & NFRs ---> Understanding Lock + (Audit Skills) (Socratic Q&A) (Domain Skills) (Hard Gate) + | | + v v + STEP 8 STEP 7 STEP 6 STEP 5 +Skill Execution <--- Decision Log & Docs <--- Design Presentation <--- Design Exploration +(Handoff Pipeline) (BLUEPRINT.md) (Incremental UX/DX) (Multi-Skill Design) +``` + +#### Step 1️⃣: Context Discovery & Project Audit (Mandatory First Step) +Before asking any questions, inspect the environment: +- Audit existing project files, tech stack, ORM schemas, and current architecture. +- Delegate diagnostic checks to: + - `app-analyzer-optimizer` to inspect architectural bottlenecks or existing technical debt. + - `prd-architect` to **mandatorily generate a `PRD.md` file** if this is a new application, or update it if it already exists. + - `web-scraper` if analyzing competitor solutions or external API specs. +- Identify implicit constraints and note missing requirements. + +#### Step 2️⃣: Product Ideation (One Question at a Time) +Your goal is **shared clarity**, not speed. +- Ask **one targeted question per turn**. +- Prefer **multiple-choice options** to accelerate alignment. +- Clarify core user flows, target audience, primary platforms, and non-goals. + +#### Step 3️⃣: Modern Web & Stack Non-Functional Requirements (NFR Mapping) +Explicitly clarify or propose assumptions for modern web & software pillars, invoking specialized domain skills for each: +- **Performance & Web Vitals:** `senior-frontend` (Core Web Vitals, payload budgets, Turbopack). +- **Architecture & Framework:** `senior-frontend` / `mvc-expert`, `domain-driven-design-expert` (React 19, Next.js 15 PPR/RSC, Islands, SPA). +- **Design System & UI/UX:** `design-system-architect`, `hig`, `ui-ux-pro-max`, `affective-computing-emotion-ai`, `tailwind-expert`. +- **Backend & APIs:** `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` / `python-programming-expert` / `go-programming-expert` / `rust-programming-expert`. +- **Data Mutation & DB:** `database-orm-expert` / `supabase-security-expert` (Server Actions, REST, Drizzle/Prisma, RLS policies). +- **AI & Intelligent Systems:** `ai-llm-integration-expert`, `ai-prompt-engineering-expert`, `mcp-server-architect`, `multi-agent-orchestration`. +- **SaaS Architecture:** `saas-multi-tenant`, `saas-billing`, `agentic-micro-economy-architect`. +- **Mobile & Desktop Targets:** `mobile-expo-expert`, `tauri-expert`. +- **Accessibility & i18n:** `global-a11y-i18n-expert` (WCAG 2.2 AAA, aria tags, locale routing). +- **SEO & Discovery:** `seo` (AI Overviews, Schema.org JSON-LD, `/llms.txt`). + +If the user is uncertain, propose modern defaults (e.g. Next.js 15 + Supabase + Tailwind v4 + Vercel AI SDK) and explicitly tag them as **[ASSUMPTIONS]**. + +#### Step 4️⃣: Understanding Lock (Hard Gate) +Pause and present a summary before proposing any design: +1. **Summary:** 5–7 bullet points covering goals, target audience, key flows, and boundaries. +2. **Assumptions:** Explicit list of technical defaults and NFR choices. +3. **Delegated Skill Plan:** Outline which specialized skills will be orchestrated during implementation. +4. **Open Questions:** Any unresolved items. + +Ask: +> *"Does this accurately reflect your vision? Please confirm or edit before we generate the technical architecture and skill orchestration plan."* + +**Do NOT proceed until explicit confirmation is given.** + +#### Step 5️⃣: Architectural & Multi-Skill Design Exploration +Once confirmed, present **2–3 viable design approaches**: +- Lead with your recommended option. +- Highlight DX vs UX trade-offs, scalability boundaries, infrastructure cost, and bundle size. +- Specify how specialized skills will execute each layer (e.g., `design-system-architect` for UI, `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` for APIs, `mcp-server-architect` for AI tools). + +#### Step 6️⃣: Incremental Design Presentation +Present the finalized design in short sections (200–300 words max): +- **System Architecture & Boundaries:** Component tree, server/client boundaries, monorepo structure. +- **Data Flow & Mutation:** RSC fetching, Server Actions, state management (TanStack Query / Zustand). +- **Security & Multi-Tenancy:** RLS policy design, auth flows, rate limiting. +- **AI Agent & Tooling:** MCP server tools, streaming UI architecture. +- **Testing & Telemetry Plan:** Playwright E2E, Vitest, OpenTelemetry points. + +Ask after each section: *"Does this alignment look right so far?"* + +#### Step 7️⃣: Decision Log & Design Document Artifact +Produce a full **Design Document** and persist it to `DESIGN.md` or `BLUEPRINT.md`: + +```markdown +# [Project Name] — Design & Skill Orchestration Document + +## 1. Understanding Summary +- Core Goal, Audience, User Flows, Non-Goals + +## 2. Technical Architecture & Skill Delegation +- Rendering & Framework (`senior-frontend` / `mobile-expo-expert`) +- API & Microservices (`nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` / `go-programming-expert`) +- Database & Security (`database-orm-expert` / `supabase-security-expert`) +- AI & LLM Systems (`ai-llm-integration-expert`, `ai-prompt-engineering-expert` / `mcp-server-architect`) +- SaaS & Billing (`saas-multi-tenant` / `saas-billing`, `agentic-micro-economy-architect`) + +## 3. Component & UI Architecture +- Design System (`design-system-architect`, `tailwind-expert`) +- RSC vs Client boundaries + +## 4. Decision Log +| # | Decision | Alternatives Considered | Rationale & Modern Web Principle | Orchestrated Skill | +|---|----------|-------------------------|----------------------------------|-------------------| +| 1 | ... | ... | ... | ... | + +## 5. Risk Assessment & Mitigation +- Identified bottlenecks, security bounds, cost estimates +``` + +#### Step 8️⃣: Skill Execution Handoff Pipeline (Orchestration Transition) +After documentation is complete, initiate the handoff: +- Trigger `zero-to-prod-orchestrator` to launch the 8-phase development roadmap. +- Invoke `prd-architect` to update `CHANGELOG.md` and `BLUEPRINT.md`. +- Trigger `production-ready-hardener` for pre-launch hardening guidelines. +- Trigger `session-memory-manager` if saving checkpoint state for cross-session execution. + +--- + +### Exit Criteria (Hard Stop Conditions) +Exit brainstorming mode **only when all of the following are satisfied**: +- Understanding Lock confirmed by user. +- Architectural design option accepted. +- Skill Orchestration Matrix mapped out for execution. +- Key NFRs (Performance, a11y, security) documented. +- Decision Log and `DESIGN.md` artifact generated. +- **`PRD.md` successfully generated** (for new applications). + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Tujuan & Gambaran Umum +Mengubah ide mentah menjadi **desain yang jelas dan tervalidasi, spesifikasi arsitektur, serta alur kerja eksekusi** melalui dialog terstruktur **sebelum implementasi dimulai**. + +Sebagai **Orkestrator Utama Arsitektur**, `brainstorming` tidak hanya mematangkan konsep produk dan teknis, tetapi juga **memetakan serta mendelegasikan tanggung jawab ke seluruh kumpulan skill spesialis** di ekosistem `vibes-plug` (frontend, backend, AI/LLM, database, keamanan, SaaS, SEO, testing, dan DevOps). + +Skill ini ada untuk mencegah: +- Implementasi yang terlalu dini dan pembengkakan kode (*code bloat*) +- Asumsi tersembunyi dan batas teknis yang belum dikonfirmasi +- Pembusukan arsitektur (*architectural decay*) dan pola sistem yang tidak skalabel +- Sistem web/mobile yang rapuh, celah keamanan, dan penurunan performa +- *Over-engineering* sebelum tercapainya *product-market fit* + +> ⚠️ **Batasan Ketat:** Anda **tidak diperbolehkan** untuk menulis kode atau mengubah kode sumber saat mode `brainstorming` aktif. Output Anda murni berupa pertanyaan terstruktur, proposal desain, log keputusan, dan spesifikasi serah terima skill. **Untuk aplikasi baru, Anda WAJIB selalu secara otomatis memicu skill `prd-architect` untuk membuat file `PRD.md` sebelum penulisan kode dimulai.** + +--- + +### Matriks Integrasi & Orkestrasi Skill + +Selama proses brainstorming, konsultasikan, rujuk, dan orkestrasikan skill-skill spesialis berikut berdasarkan kebutuhan proyek: + +| Domain / Fase | Skill yang Diorkestrasikan | Konteks Pemicu & Delegasi | +| :--- | :--- | :--- | +| **Penemuan & Audit** | `prd-architect`, `deep-research-analyst`, `app-analyzer-optimizer`, `web-scraper`, `website-design-cloner`, `browser-automation-expert`, `dependency-upgrade-migrator`, `session-memory-manager`, `proactive-background-watcher`, `documentation-site-expert`, `headless-cms-expert`, `wordpress-headless-expert` | Menyusun PRD, ERD, dan Dokumentasi formal, memori episodik lintas proyek, mengaudit codebase yang ada, mendokumentasikan fitur kompetitor, reverse-engineer desain website, arsitektur headless CMS/WP, atau audit kesehatan dependensi. | +| **UI/UX & Design System** | `design-system-architect`, `website-design-cloner`, `multimodal-spatial-video-cloner`, `screenshot-to-code-expert`, `hig`, `ui-ux-pro-max`, `affective-computing-emotion-ai`, `tailwind-expert`, `anti-slop`, `svg-animation-motion-expert`, `web-3d-graphics-expert`, `glsl-shader-expert`, `webxr-ar-vr-expert`, `browser-automation-expert`, `data-visualization-expert`, `rich-text-editor-expert`, `modern-css-native-expert`, `ephemeral-generative-ui-architect`, `visual-ui-auditor` | Token desain (OKLCH), ekstraksi video interaksi spasial ke kode, Tailwind CSS v4, fitur native CSS 2026 (Anchor Positioning, @starting-style), prinsip Apple HIG, tata letak antarmuka, komponen UI berkualitas produksi, editor rich text (Tiptap/Lexical), visualisasi data & chart (Recharts/Tremor/D3), modernisasi kode lama dengan legacy-code-translator, WebGPU & WebGL 3D (Three.js WebGPU/TSL, Babylon.js, PlayCanvas), kustomisasi shader GLSL/WGSL, WebXR AR/VR, audit visual UI Pillar 7, dan standar kebersihan visual anti-slop nol-toleransi. | +| **Framework Frontend** | `senior-frontend`, `vercel-ai-sdk-expert`, `vue-frontend-expert`, `astro-framework-expert`, `svelte-sveltekit-expert`, `solidjs-expert`, `angular-expert`, `tanstack-query-expert`, `global-a11y-i18n-expert`, `state-management-expert`, `form-validation-expert`, `apple-ecosystem-expert`, `blockchain-web3-expert`, `pwa-offline-first-expert` | React 19 / Next.js 15 App Router (RSC, PPR), Vue 3 / Nuxt 3, Astro 5+ Islands, Svelte 5 Runes / SvelteKit 2, SolidJS 2 / SolidStart, Angular 19+ Signals & Standalone, integrasi dApp Web3 (wagmi/viem), state management (Zustand/Jotai/Pinia), WCAG 2.2 a11y, i18n multi-bahasa, formulir kompleks dengan React Hook Form + Zod, arsitektur Local-First offline (RxDB/PowerSync). | +| **Mobile, Desktop & Ekstensi** | `mobile-expo-expert`, `apple-ecosystem-expert`, `tauri-expert`, `desktop-electron-expert`, `browser-extension-mv3-pro`, `email-notification-expert`, `pwa-offline-first-expert` | Aplikasi mobile cross-platform React Native / Expo Router v4, Apple ecosystem (iOS PWA & Safari), ekstensi browser Manifest V3 Chrome/Firefox/Safari (SidePanel API, offscreen sandbox WASM, background service worker), iOS Live Activities, push notification (FCM/APNs), aplikasi desktop Tauri v2 berbasis Rust, Electron 33+, atau distribusi app store PWA (PWABuilder). | +| **Backend & Runtime** | `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert`, `python-programming-expert`, `pydantic-ai-expert`, `go-programming-expert`, `rust-programming-expert`, `bun-runtime-expert`, `mvc-expert`, `domain-driven-design-expert`, `fullstack-expert`, `async-queue-temporal-expert`, `cron-scheduler-expert`, `legacy-code-translator`, `api-gateway-proxy-expert`, `wasm-edge-computing-expert`, `ephemeral-wasm-sandbox-executor`, `n8n-automation-expert`, `chatbot-messaging-expert`, `pdf-document-generation-expert`, `parallel-tool-orchestrator` | Desain API, Node.js 24, Bun 1.2+, FastAPI 0.115+, agen type-safe Pydantic AI, microservices Go 1.25+, Rust Axum, API Gateways, Edge computing WASM, sandboxing WASM efemeral, alur tahan-gagal (Temporal/Trigger.dev/BullMQ), otomasi alur kerja n8n, eksekusi paralel multi-tool concurrent, bot WhatsApp/Telegram/Discord, pipeline dokumen PDF, tugas terjadwal & cron job. | +| **Desain API & Kontrak** | `api-design-expert`, `openapi-swagger-codegen-expert`, `spec-driven-development-expert`, `typescript-expert`, `rate-limit-abuse-prevention`, `graphql-apollo-expert`, `autonomous-api-drift-healer`, `formal-spec-z3-verifier`, `structured-output-contracts` | Praktik terbaik REST, spesifikasi contract-first TypeSpec & OpenAPI 3.1, penegakan kontrak skema output terstruktur strict JSON Schema, BDD Gherkin & consumer-driven contract testing (Pact), skema GraphQL (Apollo/NestJS), gRPC/protobuf, tRPC end-to-end type safety, deteksi drift API otonom & adapter self-healing, verifikasi invarian formal Z3/SMT, rate limiting, manajemen API key, idempotency, strategi versioning. | +| **Database, ORM & Data** | `database-orm-expert`, `vector-db-rag-expert`, `supabase-security-expert`, `firebase-security-expert`, `autonomous-red-teamer`, `data-pipeline-etl-expert`, `search-engine-expert`, `xerj-search-expert`, `geospatial-maps-expert`, `graph-rag-knowledge-expert` | Desain skema Prisma 6 / Drizzle ORM, migrasi tanpa downtime, database serverless (Neon/D1/Turso), Data pipelines (dbt/Dagster), pgvector HNSW RAG, Knowledge Graph (Neo4j/Microsoft GraphRAG), mesin pencari full-text (Typesense/Meilisearch/Elasticsearch/XERJ), data geospasial & peta (PostGIS/Mapbox/Leaflet), Supabase RLS, Firebase security rules. | +| **Arsitektur & Skala** | `monorepo-architect`, `event-driven-architect`, `cloud-hosting-expert`, `mpa-orchestrator`, `spa-orchestrator`, `scalability-clean-code`, `micro-frontend-architect`, `web-game-engine-expert`, `biome-linter-formatter-expert`, `composable-mach-architect`, `living-codebase-ast-graph` | Monorepo (Turborepo/pnpm), graf dependensi AST in-memory, Biome v2 linter/formatter, microservices, antrean pesan, aplikasi multi-entry, skema MPA & SPA, prinsip clean code, micro-frontends (Webpack/Vite Federation), Arsitektur MACH Komposabel, Web game engine (PlayCanvas, fisika WASM Havok/Jolt/Rapier, loop ECS Fixed-Timestep, netcode WebTransport). | +| **Integrasi AI & LLM** | `ai-llm-integration-expert`, `deep-research-analyst`, `vercel-ai-sdk-expert`, `pydantic-ai-expert`, `synthetic-data-finetuning-expert`, `ai-prompt-engineering-expert`, `ai-media-generation-expert`, `vector-db-rag-expert`, `mcp-server-architect`, `multi-agent-orchestration`, `gemini-agent-booster`, `doku-mcp-server`, `xerj-search-expert`, `local-slm-edge-ai-expert`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai`, `graph-rag-knowledge-expert`, `agentic-memory-architect`, `llm-finops-router`, `agentic-micro-economy-architect`, `test-time-compute-optimizer`, `kv-cache-prefix-optimizer`, `speculative-multi-draft-synthesizer`, `context-window-engineer`, `adaptive-model-cascade`, `llm-observability-expert`, `thinking-budget-orchestrator`, `parallel-tool-orchestrator`, `structured-output-contracts` | Alur RAG, GraphRAG & Knowledge Graph, conversational voice AI real-time (<300ms WebRTC/WebSocket), MCP Server v1.x (FastMCP/Streamable HTTP/Client discovery/XERJ 13-tools), generasi AI gambar/suara/video (Flux/ElevenLabs/Whisper/Sora), workflow multi-agent LangGraph, eksekusi SLM lokal di browser (WebGPU/WebLLM), evaluasi otomatis & benchmark AI (Promptfoo/DeepEval), pemikiran long-context Gemini, FinOps LLM, memori episodik jangka panjang, optimasi test-time compute, penguncian prefix KV-cache, alokasi thinking budget dinamis, eksekusi batch paralel, penegakan skema output terstruktur strict, sintesis draf spekulatif. | +| **Frontier AI & Simulation** | `frontier-ai-models-expert`, `ai-llm-integration-expert`, `multi-agent-orchestration`, `gemini-agent-booster`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai`, `browser-automation-expert`, `local-slm-edge-ai-expert`, `ai-safety-governance-expert`, `agentic-coding-workflow-expert`, `ephemeral-generative-ui-architect`, `test-time-compute-optimizer`, `kv-cache-prefix-optimizer`, `speculative-multi-draft-synthesizer`, `context-window-engineer`, `adaptive-model-cascade`, `prompt-injection-firewall`, `thinking-budget-orchestrator`, `parallel-tool-orchestrator`, `structured-output-contracts` | Google Gemini 4 Pro / Project Astra (Gemini 4), Claude 5.1 (Fable/Mythos), Enterprise Frontier Safeguards (EFS), Continuous multimodal streaming, CUA agents, narrative simulation swarms, episodic memory, penskalaan test-time compute (MCTS/PRM), optimasi prefix KV-cache, sintesis draf spekulatif, alokasi thinking budget dinamis, eksekusi paralel multi-tool, kontrak skema JSON terstruktur, AI safety guardrails, workflow pengkodean agentic | +| **SaaS & Multi-Tenancy** | `saas-architect`, `saas-multi-tenant`, `saas-billing`, `agentic-micro-economy-architect`, `agentic-m2m-settlement`, `feature-flag-analytics-expert`, `payment-gateway-expert`, `ecommerce-expert`, `doku-payment-gateway`, `email-notification-expert` | Master siklus hidup SaaS (peluncuran MVP 0 ke 1 & transformasi 1 ke N), arsitektur e-commerce (Shopify/Medusa/Saleor), isolasi tenant RLS, billing Stripe/DOKU Checkout & SNAP BI, settlement mikro M2M antar-agen, feature flags, progressive rollout, email transaksional & pipeline notifikasi. | +| **Testing & Keamanan** | `e2e-testing-expert`, `accessibility-testing-expert`, `browser-automation-expert`, `zero-trust-secret-vault`, `anti-slop`, `coderabbit`, `authentication-identity-expert`, `rate-limit-abuse-prevention`, `autonomous-tdd-debugger`, `autonomous-red-teamer`, `post-quantum-crypto-migrator`, `compliance-gdpr-privacy-expert`, `ai-prompt-engineering-expert`, `ephemeral-wasm-sandbox-executor`, `formal-spec-z3-verifier`, `prompt-injection-firewall`, `ai-code-review-autonomous`, `property-mutation-testing-expert`, `mcp-sampling-critic`, `visual-ui-auditor` | Testing E2E Playwright, evaluasi otomatis & benchmark AI (Promptfoo/DeepEval/Ragas), pengujian aksesibilitas otomatis WCAG 2.2 (axe-core/Pa11y), dynamic security fuzzing & serangan adversarial, sandboxing WASM efemeral, verifikasi formal invarian Z3, kepatuhan GDPR/PDPA, migrasi post-quantum crypto, rahasia Zero-Trust, code review otomatis, penegakan zero-slop tanpa placeholder, pencegahan brute-force & DDoS, debugging TDD otonom, validasi critic-in-the-loop sampling MCP, audit visual regresi antarmuka. | +| **Penanganan Error & Ketahanan** | `error-resilience-expert`, `logging-error-tracking-expert` | Chaos engineering, simulasi kegagalan otomatis, React Error Boundaries, standar error API (RFC 9457), pola retry, circuit breaker, degradasi anggun, logging terstruktur (Pino), Sentry integrasi. | +| **Komunikasi & Notifikasi** | `email-notification-expert`, `realtime-collaboration-expert`, `sse-websocket-streaming-expert`, `chatbot-messaging-expert`, `voice-ai-realtime-agent`, `affective-computing-emotion-ai` | Email transaksional (Resend/Postmark), notifikasi push (Expo Push/FCM/APNs), agen percakapan suara real-time (OpenAI Realtime/Gemini Live), template React Email, notifikasi in-app, bot perpesanan (WhatsApp/Telegram/Discord/Slack), streaming respons (SSE/WebSocket), kolaborasi real-time. | +| **File & Media** | `file-upload-media-expert`, `ai-media-generation-expert`, `app-promo-media-expert`, `pdf-document-generation-expert` | Upload presigned URL (S3/R2), optimasi gambar (Sharp), transcoding video (Mux), generasi media AI, pembuatan screenshot & video promosi aplikasi (App Store, Play Store, Remotion, media sosial), pembuatan dokumen PDF (React PDF/Puppeteer), konfigurasi CDN, UI drag-and-drop, validasi & keamanan file. | +| **Performa** | `performance-web-vitals`, `app-analyzer-optimizer` | Core Web Vitals (LCP, INP, CLS), optimasi bundle, loading gambar/font, React concurrent features, peningkatan skor Lighthouse, analisis arsitektur mendalam. | +| **SEO, GEO & Telemetri** | `seo`, `data-telemetry-expert` | Audit SEO teknikal, Generative Engine Optimization (AI Overviews, `/llms.txt`), landing page AEO, analitik OpenTelemetry/PostHog. | +| **DevOps & CI/CD** | `ci-cd-devops-architect`, `cloud-hosting-expert`, `dependency-upgrade-migrator`, `self-healing-cloud-orchestrator`, `biome-linter-formatter-expert`, `autonomous-api-drift-healer` | GitHub Actions, Biome linter/formatter, Docker, Kubernetes, Terraform, deployment Vercel/Cloudflare, self-healing cloud operations, perbaikan drift API otonom, Renovate Bot, kesehatan dependensi. | +| **Serah Terima Eksekusi** | `zero-to-prod-orchestrator`, `production-ready-hardener`, `zero-tech-debt-auditor`, `prd-architect`, `session-memory-manager`, `anti-slop` | Serah terima desain tervalidasi ke pipeline produksi 8-fase, pengerasan pra-rilis, audit zero technical debt untuk pembersihan kode mati & duplikasi, pembaruan dokumentasi otomatis (`CHANGELOG.md`), pemuatan konteks otomatis, checkpoint ringkas, efisiensi token, eliminasi AI slop. | + +--- + +### Mode Operasi & Protokol Swarm Director +Anda beroperasi sebagai **Principal Web Architect, Design Facilitator, dan Swarm Director**. +- Tidak ada implementasi kode saat fase ideasi +- Tidak ada fitur spekulatif tanpa konfirmasi pengguna +- Tidak ada asumsi sepihak — catat dan verifikasi setiap nilai default +- Tidak melompati pintu gerbang verifikasi (*hard gates*) +- **Determinisme Prefix KV-Caching (`kv-cache-prefix-optimizer`)**: Pastikan struktur dokumen ini dan seluruh awalan prompt (prefix) tetap statis dan deterministik pada setiap giliran. Hal ini memungkinkan Gemini 4 Pro dan model frontier modern memanfaatkan KV-Caching, yang secara drastis memangkas Time-to-First-Token (TTFT) dan biaya token sebesar 75-90%. +- **Efisiensi Token Mutlak Tanpa Kehilangan Daya Logika (`adaptive-model-cascade`)**: + - Pangkas muatan konteks subagent saat Fan-Out: hanya kirimkan irisan `CONTEXT_MAP.md` yang relevan, kontrak antarmuka target, dan path file yang dikerjakan. Jangan pernah mengirimkan riwayat obrolan mentah secara global. + - Alokasikan model berdasarkan kompleksitas: gunakan `flash_lite` atau `flash` untuk pencarian file, pemindaian AST, dan validasi linter; simpan `pro` atau `inherit` untuk desain arsitektur tingkat tinggi dan audit keamanan kritis. + - Terapkan checkpoint ultra-ringkas via `session-memory-manager` (<300 token) untuk mencegah pembengkakan context window. + - **Hukum Mutlak Non-Degradasi**: Dilarang memotong kode dengan `// TODO` atau `// ...` demi menghemat token. Kode yang dihasilkan harus 100% lengkap dan dapat langsung dieksekusi. +- **Topologi Eksekusi Swarm**: Saat merencanakan fase multi-domain, orkestrasikan subagent menggunakan: + 1. *Fan-Out / Fan-In*: Eksekusi paralel lintas UI, Backend, dan Database dengan pemangkasan konteks selektif. + 2. *Pipeline Saga*: Eksekusi bertahap berurutan dari Fase 1 hingga 8. + 3. *Critic-Validator Loop*: Tinjauan kode agen dan perbaikan mandiri TDD otonom sebelum diserahkan ke pengguna. + +Tugas Anda adalah **memperlambat proses secukupnya agar arsitektur, delegasi swarm, dan pemetaan skill terancang dengan benar**. + +--- + +### Alur Kerja Orkestrasi Terintegrasi (8 Langkah) + +``` + LANGKAH 1 LANGKAH 2 LANGKAH 3 LANGKAH 4 +Audit Context Discovery -> Ideasi Produk -----> NFR & Stack Modern --> Understanding Lock + (Skill Audit) (Socratic Q&A) (Skill Domain) (Hard Gate) + | | + v v + LANGKAH 8 LANGKAH 7 LANGKAH 6 LANGKAH 5 +Eksekusi Skill <------- Log Keputusan & Docs <- Presentasi Desain <--- Eksplorasi Desain + (Pipeline Handoff) (BLUEPRINT.md) (Inkremental UX/DX) (Multi-Skill Design) +``` + +#### Langkah 1️⃣: Penemuan Konteks & Audit Proyek (Langkah Wajib Pertama) +Sebelum mengajukan pertanyaan, periksa lingkungan proyek: +- Audit file proyek yang ada, stack teknologi, skema ORM, dan arsitektur saat ini. +- Delegasikan pemeriksaan ke: + - `app-analyzer-optimizer` untuk mendeteksi bottleneck arsitektur atau technical debt. + - `prd-architect` untuk **wajib menghasilkan file `PRD.md`** jika ini adalah aplikasi baru, atau memperbaruinya jika sudah ada. + - `web-scraper` jika perlu menganalisis aplikasi kompetitor atau dokumentasi API eksternal. +- Catat batasan-batasan implisit dan persyaratan yang belum jelas. + +#### Langkah 2️⃣: Ideasi Produk (Satu Pertanyaan Per Pesan) +Tujuan Anda adalah **kejelasan bersama**, bukan kecepatan. +- Ajukan **satu pertanyaan terarah per pesan**. +- Utamakan **pilihan ganda** untuk mempercepat penyelarasan. +- Clarify alur pengguna utama, target audiens, platform utama, dan *non-goals*. + +#### Langkah 3️⃣: Persyaratan Non-Fungsional (NFR) & Pemetaan Stack Modern +Secara eksplisit perjelas atau usulkan asumsi untuk pilar-pilar perangkat lunak modern, dengan memetakan skill spesialisnya: +- **Performa & Web Vitals:** `senior-frontend` (Core Web Vitals, anggaran payload, Turbopack). +- **Arsitektur & Framework:** `senior-frontend` / `mvc-expert`, `domain-driven-design-expert` (React 19, Next.js 15 PPR/RSC, Islands, SPA). +- **Design System & UI/UX:** `design-system-architect`, `hig`, `ui-ux-pro-max`, `affective-computing-emotion-ai`, `tailwind-expert`. +- **Backend & API:** `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` / `python-programming-expert` / `go-programming-expert` / `rust-programming-expert`. +- **Mutasi Data & DB:** `database-orm-expert` / `supabase-security-expert` (Server Actions, REST, Drizzle/Prisma, RLS policies). +- **Sistem AI & Cerdas:** `ai-llm-integration-expert`, `ai-prompt-engineering-expert`, `mcp-server-architect`, `multi-agent-orchestration`. +- **Arsitektur SaaS:** `saas-multi-tenant`, `saas-billing`, `agentic-micro-economy-architect`. +- **Target Mobile & Desktop:** `mobile-expo-expert`, `tauri-expert`. +- **Aksesibilitas & i18n:** `global-a11y-i18n-expert` (WCAG 2.2 AAA, tag aria, navigasi bahasa). +- **SEO & Penemuan:** `seo` (AI Overviews, Schema.org JSON-LD, `/llms.txt`). + +Jika pengguna ragu, berikan rekomendasi default modern (misal: Next.js 15 + Supabase + Tailwind v4 + Vercel AI SDK) dan tandai sebagai **[ASUMSI]**. + +#### Langkah 4️⃣: Kunci Pemahaman (Understanding Lock - Hard Gate) +Berhenti sejenak dan sajikan ringkasan sebelum mengusulkan desain apa pun: +1. **Ringkasan:** 5–7 poin mencakup tujuan, target audiens, alur utama, dan batasan. +2. **Asumsi:** Daftar eksplisit pilihan teknis dan NFR. +3. **Rencana Delegasi Skill:** Pemetaan skill spesialis yang akan mengoperasikan setiap layer. +4. **Pertanyaan Terbuka:** Isu yang belum terselesaikan. + +Tanyakan: +> *"Apakah ini mencerminkan visi Anda dengan akurat? Mohon konfirmasi atau koreksi sebelum kita menyusun arsitektur teknis dan rencana orkestrasi skill."* + +**Jangan melanjutkan sebelum konfirmasi eksplisit diberikan.** + +#### Langkah 5️⃣: Eksplorasi Desain Arsitektur & Multi-Skill +Setelah dikonfirmasi, berikan **2–3 opsi pendekatan desain**: +- Awali dengan opsi rekomendasi Anda. +- Jelaskan trade-off DX vs UX, batas skalabilitas, estimasi biaya infrastruktur, dan ukuran bundle. +- Tentukan skill spesialis yang mengeksekusi setiap lapisan (misal: `design-system-architect` untuk UI, `nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` untuk API, `mcp-server-architect` untuk tools AI). + +#### Langkah 6️⃣: Presentasi Desain Secara Inkremental +Sajikan rancangan desain dalam bagian-bagian pendek (maksimal 200–300 kata): +- **Arsitektur Sistem & Batasan:** Pohon komponen, batas server/klien, struktur monorepo. +- **Aliran & Mutasi Data:** Data fetching RSC, Server Actions, manajemen state (TanStack Query / Zustand). +- **Keamanan & Multi-Tenancy:** Desain kebijakan RLS, alur autentikasi, rate limiting. +- **Fitur & Agent AI:** Tool MCP server, arsitektur streaming UI. +- **Rencana Testing & Telemetri:** Playwright E2E, Vitest, titik pantau OpenTelemetry. + +Tanyakan setelah setiap bagian: *"Apakah penyelarasan ini sudah sesuai sejauh ini?"* + +#### Langkah 7️⃣: Log Keputusan & Artifact Dokumen Desain +Hasilkan Dokumen Desain lengkap dan simpan ke `DESIGN.md` atau `BLUEPRINT.md`: + +```markdown +# [Nama Proyek] — Dokumen Desain & Orkestrasi Skill + +## 1. Ringkasan Pemahaman +- Tujuan Utama, Audiens, Alur Pengguna, Non-Goals + +## 2. Arsitektur Teknis & Delegasi Skill +- Rendering & Framework (`senior-frontend` / `mobile-expo-expert`) +- API & Microservices (`nextjs-app-router-expert`, `database-orm-expert`, `js-backend-expert` / `go-programming-expert`) +- Database & Keamanan (`database-orm-expert` / `supabase-security-expert`) +- Sistem AI & LLM (`ai-llm-integration-expert`, `ai-prompt-engineering-expert` / `mcp-server-architect`) +- SaaS & Billing (`saas-multi-tenant` / `saas-billing`, `agentic-micro-economy-architect`) + +## 3. Komponen & Arsitektur UI +- Design System (`design-system-architect`, `tailwind-expert`) +- Pembagian batas RSC vs Klien + +## 4. Log Keputusan +| # | Keputusan | Alternatif Dipertimbangkan | Rasional & Prinsip Web Modern | Skill yang Diorkestrasikan | +|---|-----------|---------------------------|-------------------------------|----------------------------| +| 1 | ... | ... | ... | ... | + +## 5. Penilaian Risiko & Mitigasi +- Potensi bottleneck, batas keamanan, estimasi biaya +``` + +#### Langkah 8️⃣: Serah Terima ke Pipeline Eksekusi (Transisi Orkestrasi) +Setelah dokumentasi selesai, jalankan proses serah terima: +- Picu `zero-to-prod-orchestrator` untuk memulai roadmap pembangunan 8-fase. +- Panggil `prd-architect` untuk memperbarui `CHANGELOG.md` dan `BLUEPRINT.md`. +- Picu `production-ready-hardener` untuk panduan pengerasan pra-rilis. +- Picu `session-memory-manager` jika menyimpan checkpoint kondisi proyek untuk sesi berikutnya. + +--- + +### Kriteria Keluar (Hard Stop Conditions) +Mode brainstorming selesai **hanya jika seluruh kondisi berikut terpenuhi**: +- Kunci Pemahaman (*Understanding Lock*) dikonfirmasi oleh pengguna. +- Opsi desain arsitektur disetujui. +- Matriks Orkestrasi Skill telah dipetakan untuk eksekusi. +- Requirements NFR utama (Performa, a11y, keamanan) didokumentasikan. +- Log Keputusan dan artifact `DESIGN.md` telah dibuat. +- **File `PRD.md` telah berhasil dibuat** (untuk aplikasi baru). + +--- +### 🎨 Automatic Visual Assets Generation Mandate (CRITICAL) +**MANDATORY**: Whenever you are building a new application, scaffolding a project, or finalizing the initial UI/UX, you MUST automatically use the `generate_image` tool to create a custom logo that perfectly matches the application's core concept and aesthetic. If `generate_image` is unavailable, delegate to `ai-media-generation-expert` skill. +This generated image MUST be explicitly used as: +1. The primary application logo (e.g., in the header/navbar). +2. The website favicon (`favicon.ico` or equivalent). +3. The Open Graph (OG) image for SEO metadata (`og:image`). + +Do not use placeholders for these assets. Generate and integrate them automatically. + + + + diff --git a/vibes-plug/skills/browser-automation-expert/SKILL.md b/vibes-plug/skills/browser-automation-expert/SKILL.md new file mode 100644 index 000000000..ca68127c5 --- /dev/null +++ b/vibes-plug/skills/browser-automation-expert/SKILL.md @@ -0,0 +1,260 @@ +--- +name: browser-automation-expert +description: "Expert guide for autonomous web agents (Browser-Use, Stagehand v0.4+), hardcore anti-bot evasion (Playwright Stealth, WebGL masking), and Vision LLM visual QA / Panduan ahli agen web otonom, penghindaran deteksi bot, dan QA visual berbasis Vision LLM." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Autonomous Web Agent & Automation Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Purpose & Overview +Deploy ultra-powerful autonomous web agents that perceive, navigate, and execute complex workflows without human intervention. Combine modern agentic web automation frameworks (**Browser-Use**, **Stagehand v0.4+**) with hardcore anti-detection evasion techniques (Playwright Stealth, fingerprint spoofing, residential proxy rotation) and frontier Vision LLMs (**Gemini 4 Pro / Flash**, **Project Astra**, **Claude 5.1 Fable / 5.0 Computer Use**, **OpenAI GPT-5.6 / o3 / GPT-4.5**) for pixel-accurate visual QA. + +### Core Capabilities + +1. **Autonomous Execution Frameworks (2026 Standard)** + - **Stagehand v0.4+**: Natural language DOM perception with semantic actions (`page.act()`, `page.extract()`, `page.observe()`). Avoid fragile CSS/XPath selectors. + - **Browser-Use**: Autonomous multi-turn web browsing driven by LLMs with accessibility-tree parsing, visual bounding boxes, and goal-oriented execution loops. + +2. **Hardcore Evasion & Anti-Bot Bypassing** + - **Playwright Stealth**: Mask `navigator.webdriver`, automate runtime evasion plugins, and neutralize detection scripts (Datadome, Cloudflare Turnstile, Kasada). + - **Fingerprint Masking**: Spoof Canvas, WebGL, AudioContext, hardware concurrency, and WebRTC leak vectors. + - **Human Behavior Mimicry**: Inject natural Bezier-curve mouse movements, randomized typing cadences, and realistic scroll viewport dynamics. + +3. **Visual QA & Layout Diffing via Vision LLMs** + - Feed high-resolution viewport screenshots into **Gemini 3.8 Flash** or **Claude 3.7 Sonnet**. + - Perform automatic visual regression audits, layout drift detection, contrast validation, and modal overlay checks. + +--- + +### Production Implementation Recipes + +#### Recipe 1: Stagehand v0.4+ with Playwright Stealth (TypeScript) +```typescript +import { Stagehand } from '@browserbase/stagehand'; +import { z } from 'zod'; + +export async function runAutonomousShoppingAgent(targetProduct: string) { + const stagehand = new Stagehand({ + env: 'LOCAL', + modelName: 'claude-3-7-sonnet-20250219', + browserbaseSessionCreateParams: { + projectId: process.env.BROWSERBASE_PROJECT_ID, + }, + }); + + await stagehand.init(); + const page = stagehand.page; + + try { + await page.goto('https://example-store.com'); + + // Semantic action without hardcoded selectors + await page.act({ action: `Search for "${targetProduct}" in the search input and press Enter` }); + + // Extract structured data validated by Zod schema + const productData = await page.extract({ + instruction: 'Extract the top 3 product names, prices, and availability status', + schema: z.object({ + products: z.array( + z.object({ + title: z.string(), + price: z.string(), + inStock: z.boolean(), + }) + ), + }), + }); + + console.log('Extracted Products:', productData.products); + return productData.products; + } finally { + await stagehand.close(); + } +} +``` + +#### Recipe 2: Browser-Use with Anti-Bot Evasion (Python) +```python +import asyncio +from browser_use import Agent +from langchain_google_genai import ChatGoogleGenerativeAI +from playwright.async_api import async_playwright + +async def run_autonomous_browser_agent(goal: str): + llm = ChatGoogleGenerativeAI( + model="gemini-3.8-flash", + temperature=0.1 + ) + + # Initialize agent with human-like viewport and natural interactions + agent = Agent( + task=goal, + llm=llm, + use_vision=True, + max_actions_per_step=3 + ) + + result = await agent.run(max_steps=25) + print(f"Goal Completed: {result.is_done()}") + return result.final_result() + +if __name__ == "__main__": + asyncio.run(run_autonomous_browser_agent("Search flights from CGK to HND for next month and return cheapest option")) +``` + +### Execution Protocol & Guardrails +- **Pre-flight**: Always inject evasion headers and randomize screen dimensions before navigating. +- **Fail-safe**: Set maximum navigation step thresholds (`max_steps <= 30`) to prevent infinite looping. +- **Visual Validation**: Capture viewport screenshots at critical check-in steps and pass to Vision LLMs to verify state transitions. + +### Visual Regression & Vision QA + +#### Description +This skill transforms the agent from a blind code generator into a visual designer. Instead of hoping the CSS looks correct, the agent is instructed to write a script that takes a screenshot of the newly created component, analyzes the screenshot using its own Vision AI capabilities, and iteratively tweaks the CSS until it matches the design intent perfectly. + +#### Trigger Conditions +Activate this skill when the user says: +- "Fix the CSS, the button is misaligned." +- "Make it look exactly like this mockup." +- "Ensure the UI is responsive on mobile screens." + +#### The Visual QA Loop +1. **Code:** The agent writes the HTML/CSS/React component. +2. **Serve:** The agent starts a local dev server in the background. +3. **Capture:** The agent runs a quick Playwright/Puppeteer script to take screenshots at various viewports (Mobile, Tablet, Desktop). +4. **Analyze:** The agent receives the screenshot (via the `view_file` tool on the image) and analyzes the visual hierarchy, contrast, and alignment. +5. **Correct:** The agent fixes margin, padding, or flexbox issues based on what it *saw*, not just what the code says. + +#### Agent Constraints (Mandatory Visual Verification) +- **NO BLIND CSS GUESSING**: You are strictly prohibited from finalizing a frontend component without verifying it visually first. You MUST use a `browser_subagent` to capture a screenshot of your work. +- **Pixel-Perfect Validation**: Compare the screenshot against the initial design spec or generic UI/UX best practices. Iterate on the CSS until the visual output is flawless. +- Always check contrast ratios visually if design tokens are overridden. + +## Orchestration & Integration +- Integrates with: `web-scraper`, `autonomous-red-teamer`, `e2e-testing-expert`, `brainstorming`, `zero-to-prod-orchestrator`, `session-memory-manager`, `tailwind-expert`, `design-system-architect`, `senior-frontend`. + +--- + + +## Bahasa Indonesia + +### Tujuan & Gambaran Umum +Terapkan agen web otonom super kuat yang dapat melihat, menavigasi, dan mengeksekusi alur kerja kompleks tanpa campur tangan manusia. Menggabungkan framework otomatisasi web agentic modern (**Browser-Use**, **Stagehand v0.4+**) dengan teknik penghindaran deteksi bot tingkat tinggi (Playwright Stealth, manipulasi sidik jari perangkat, rotasi proxy residential) dan model Vision frontier (**Gemini 4 Pro / Flash**, **Project Astra**, **Claude 5.1 Fable / 5.0 Computer Use**, **OpenAI GPT-5.6 / o3 / GPT-4.5**) untuk QA visual tingkat piksel. + +### Kemampuan Utama + +1. **Framework Eksekusi Otonom (Standar 2026)** + - **Stagehand v0.4+**: Persepsi DOM berbasis bahasa alami dengan aksi semantik (`page.act()`, `page.extract()`, `page.observe()`). Menghilangkan ketergantungan pada selektor CSS/XPath yang rapuh. + - **Browser-Use**: Penelusuran web otonom multi-langkah yang dipandu oleh LLM dengan pemindaian pohon aksesibilitas (accessibility tree), bounding boxes visual, dan siklus eksekusi berorientasi tujuan. + +2. **Penghindaran Deteksi & Anti-Bot Tingkat Tinggi** + - **Playwright Stealth**: Menyamarkan `navigator.webdriver`, mematikan skrip deteksi (Datadome, Cloudflare Turnstile, Kasada). + - **Masking Fingerprint**: Memalsukan sidik jari Canvas, WebGL, AudioContext, konkurensi perangkat keras, serta kebocoran WebRTC. + - **Mimikri Perilaku Manusia**: Menginjeksi gerakan kursor kurva Bezier, jeda pengetikan organik, dan dinamika scroll realistis. + +3. **QA Visual & Diffing via Vision LLM** + - Teruskan screenshot viewport resolusi tinggi ke **Gemini 3.8 Flash** atau **Claude 3.7 Sonnet**. + - Jalankan audit regresi visual otomatis, deteksi pergeseran layout, validasi kontras, dan verifikasi modal overlay. + +--- + +### Resep Implementasi Produksi + +#### Resep 1: Stagehand v0.4+ dengan Playwright Stealth (TypeScript) +```typescript +import { Stagehand } from '@browserbase/stagehand'; +import { z } from 'zod'; + +export async function jalankanAgenBelanjaOtonom(produkSasaran: string) { + const stagehand = new Stagehand({ + env: 'LOCAL', + modelName: 'claude-3-7-sonnet-20250219', + }); + + await stagehand.init(); + const page = stagehand.page; + + try { + await page.goto('https://toko-contoh.com'); + + // Aksi semantik tanpa selektor yang kaku + await page.act({ action: `Cari "${produkSasaran}" pada kolom pencarian dan tekan Enter` }); + + // Ekstraksi data terstruktur dengan validasi skema Zod + const hasilProduk = await page.extract({ + instruction: 'Ekstrak 3 nama produk teratas, harga, dan ketersediaan stok', + schema: z.object({ + products: z.array( + z.object({ + title: z.string(), + price: z.string(), + inStock: z.boolean(), + }) + ), + }), + }); + + console.log('Hasil Ekstraksi:', hasilProduk.products); + return hasilProduk.products; + } finally { + await stagehand.close(); + } +} +``` + +#### Resep 2: Browser-Use dengan Anti-Bot Evasion (Python) +```python +import asyncio +from browser_use import Agent +from langchain_google_genai import ChatGoogleGenerativeAI + +async def jalankan_agen_browser(tujuan: str): + llm = ChatGoogleGenerativeAI( + model="gemini-3.8-flash", + temperature=0.1 + ) + + agent = Agent( + task=tujuan, + llm=llm, + use_vision=True, + max_actions_per_step=3 + ) + + result = await agent.run(max_steps=25) + print(f"Status Selesai: {result.is_done()}") + return result.final_result() + +if __name__ == "__main__": + asyncio.run(jalankan_agen_browser("Cari tiket pesawat Jakarta ke Tokyo untuk bulan depan dan ambil opsi termurah")) +``` + +### Protokol Eksekusi & Batasan Keamanan +- **Sebelum Eksekusi**: Selalu injeksikan header penyamaran dan acak dimensi viewport sebelum memuat halaman. +- **Fail-safe**: Batasi jumlah langkah navigasi (`max_steps <= 30`) agar agen tidak terjebak dalam perulangan tak berujung. +- **Validasi Visual**: Tangkap screenshot di titik-titik krusial dan kirimkan ke Vision LLM untuk memastikan status halaman valid. + +### Regresi Visual & QA Visi + +#### Deskripsi +Skill ini memanfaatkan kemampuan *Vision* (penglihatan) bawaan AI untuk melakukan *Quality Assurance* (QA) visual. Agen tidak lagi sekadar menebak CSS secara buta, melainkan mengambil *screenshot* dari halaman yang dibuatnya, melihat hasilnya, dan mengkoreksi *margin/padding* secara mandiri. + +#### Kondisi Pemicu +- Saat pengguna meminta untuk merapikan UI yang berantakan. +- Saat melakukan *cloning* desain dari gambar *mockup*. + +#### Panduan Singkat +- **Gunakan Mata Anda (Wajib Verifikasi Visual):** Anda dilarang keras memfinalisasi atau menyelesaikan tugas frontend tanpa melihat hasilnya terlebih dahulu. Anda WAJIB mengambil *screenshot*, melihatnya menggunakan tool `view_file`, dan memverifikasi layout secara visual (*pixel-perfect*). +- **Siklus Visual:** Tulis Kode ➔ Ambil Screenshot ➔ Analisis dengan *Vision* ➔ Perbaiki Tailwind/CSS ➔ Selesai. +- **Jangan Menebak:** Terkadang `justify-center` tidak berfungsi karena ada pembungkus (*wrapper*) absolut. Jangan menebak-nebak di dalam kode; lihat hasil akhirnya secara visual! + +## Integrasi Orkestrasi +- Terintegrasi dengan: `web-scraper`, `autonomous-red-teamer`, `e2e-testing-expert`, `brainstorming`, `zero-to-prod-orchestrator`, `session-memory-manager`, `tailwind-expert`, `design-system-architect`, `senior-frontend`. \ No newline at end of file diff --git a/vibes-plug/skills/browser-extension-mv3-pro/SKILL.md b/vibes-plug/skills/browser-extension-mv3-pro/SKILL.md new file mode 100644 index 000000000..02c7b85e6 --- /dev/null +++ b/vibes-plug/skills/browser-extension-mv3-pro/SKILL.md @@ -0,0 +1,299 @@ +--- +name: browser-extension-mv3-pro +description: "Expert guide for modern browser extension development (Manifest V3) — Chrome SidePanel API, Background Service Workers, Offscreen Documents, declarativeNetRequest, WebAssembly in MV3, and cross-browser WebExtensions / Panduan ahli pengembangan ekstensi browser modern (Manifest V3)." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# 🧩 Browser Extension Manifest V3 Pro Guide (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with `senior-frontend`, `tailwind-expert`, `pwa-offline-first-expert`, `ai-llm-integration-expert`, `vercel-ai-sdk-expert`, `mcp-server-architect`, `authentication-identity-expert`, `zero-trust-secret-vault`, and `anti-slop`. + +### Description +Expert guide for engineering high-performance, secure, and cross-browser extensions using **Chrome Manifest V3 (MV3)**, Firefox WebExtensions MV3, and Safari Web Extensions. Manifest V3 fundamentally modernizes browser extension development by replacing persistent background pages with ephemeral service workers, enforcing strict declarative network rules, mandating modern native side panels, and providing offscreen sandboxes for complex computational workloads. + +### Architecture & Manifest V3 Invariants + +1. **Ephemeral Background Service Workers**: + - Background service workers terminate after ~30 seconds of inactivity. + - Never store long-lived state in global JavaScript memory. Use `chrome.storage.session` for transient in-memory state and `chrome.storage.local` for persistent storage. + - Use `chrome.alarms` instead of `setInterval` / `setTimeout` for recurring operations. + +2. **SidePanel API (`chrome.sidePanel`)**: + - The native 2026 standard for AI copilots, page analyzers, and context tools. + - Replaces disruptive modal popups and injected DOM overlays with a native, non-intrusive browser panel. + +3. **Offscreen Documents API (`chrome.offscreen`)**: + - Service workers lack DOM access, canvas, audio playback, and `window`. + - Offscreen documents provide a secure sandboxed DOM environment for WebAssembly (WASM), audio decoding, and clipboard access. + +4. **Declarative Net Request (`chrome.declarativeNetRequest`)**: + - Replaces blocking `webRequest` API for high-speed, privacy-first network modifications and header manipulation. + +--- + +### Production Manifest V3 Contract (`manifest.json`) + +```json +{ + "manifest_version": 3, + "name": "Vibes AI Copilot & Analyzer", + "version": "1.0.0", + "description": "Production-grade AI companion extension built with Manifest V3 and React 19.", + "icons": { + "16": "icons/icon-16.png", + "48": "icons/icon-48.png", + "128": "icons/icon-128.png" + }, + "action": { + "default_icon": "icons/icon-48.png", + "default_title": "Open Vibes AI Side Panel" + }, + "side_panel": { + "default_path": "sidepanel/index.html" + }, + "background": { + "service_worker": "background/service-worker.js", + "type": "module" + }, + "permissions": [ + "sidePanel", + "storage", + "alarms", + "offscreen", + "activeTab", + "scripting" + ], + "host_permissions": [ + "https://*/*" + ], + "content_scripts": [ + { + "matches": [""], + "js": ["content/content-script.js"], + "run_at": "document_idle" + } + ], + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'self'; worker-src 'self';" + } +} +``` + +--- + +### Background Service Worker (`background/service-worker.ts`) + +```typescript +export interface ExtensionMessage { + type: 'ANALYZE_CURRENT_PAGE' | 'EXECUTE_WASM_SANDBOX'; + payload?: any; +} + +export interface ExtensionResponse { + success: boolean; + data?: any; + error?: string; +} + +// 1. Enable Side Panel on toolbar icon click +chrome.sidePanel + .setPanelBehavior({ openPanelOnActionClick: true }) + .catch((error: Error) => console.error('[SW] Failed to set side panel behavior:', error)); + +// 2. Life-Cycle & Heartbeat Management +chrome.runtime.onInstalled.addListener(async (details) => { + if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) { + await chrome.storage.local.set({ + installedAt: Date.now(), + theme: 'system', + copilotEnabled: true, + }); + // Setup recurring background sync alarm (minimum interval 1 minute in MV3) + chrome.alarms.create('telemetry_sync', { periodInMinutes: 15 }); + } +}); + +chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name === 'telemetry_sync') { + handlePeriodicSync(); + } +}); + +async function handlePeriodicSync(): Promise { + const data = await chrome.storage.local.get(['telemetry_queue']); + const queue = Array.isArray(data.telemetry_queue) ? data.telemetry_queue : []; + if (queue.length === 0) return; + + try { + const response = await fetch('https://api.vibes.dev/v1/telemetry', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ events: queue }), + }); + if (response.ok) { + await chrome.storage.local.set({ telemetry_queue: [] }); + } + } catch (err) { + console.warn('[SW] Telemetry sync deferred:', err); + } +} + +// 3. Offscreen Document Manager (WASM / DOM Sandbox) +let creatingOffscreen: Promise | null = null; + +async function ensureOffscreenDocument(path: string): Promise { + const offscreenUrl = chrome.runtime.getURL(path); + const existingContexts = await chrome.runtime.getContexts({ + contextTypes: [chrome.runtime.ContextType.OFFSCREEN_DOCUMENT], + documentUrls: [offscreenUrl], + }); + + if (existingContexts.length > 0) return; + + if (creatingOffscreen) { + await creatingOffscreen; + return; + } + + creatingOffscreen = chrome.offscreen.createDocument({ + url: path, + reasons: [chrome.offscreen.Reason.WORKERS, chrome.offscreen.Reason.CLIPBOARD], + justification: 'WASM bytecode execution and secure clipboard parsing.', + }); + + await creatingOffscreen; + creatingOffscreen = null; +} + +// 4. Type-Safe Unified Message Bus +chrome.runtime.onMessage.addListener( + (message: ExtensionMessage, sender, sendResponse: (response: ExtensionResponse) => void) => { + handleIncomingMessage(message, sender) + .then(sendResponse) + .catch((error: Error) => { + sendResponse({ success: false, error: error.message }); + }); + return true; // Keep message channel open for asynchronous reply + } +); + +async function handleIncomingMessage( + message: ExtensionMessage, + _sender: chrome.runtime.MessageSender +): Promise { + switch (message.type) { + case 'ANALYZE_CURRENT_PAGE': { + const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!activeTab?.id) { + throw new Error('No active browser tab found.'); + } + + const [injectionResult] = await chrome.scripting.executeScript({ + target: { tabId: activeTab.id }, + func: () => ({ + title: document.title, + url: window.location.href, + metaDescription: document.querySelector('meta[name="description"]')?.getAttribute('content') ?? '', + headings: Array.from(document.querySelectorAll('h1, h2')).map((h) => h.textContent?.trim() || ''), + }), + }); + + return { success: true, data: injectionResult.result }; + } + + case 'EXECUTE_WASM_SANDBOX': { + await ensureOffscreenDocument('offscreen/sandbox.html'); + const offscreenResponse = await chrome.runtime.sendMessage({ + target: 'offscreen', + type: 'RUN_BYTECODE', + payload: message.payload, + }); + return offscreenResponse; + } + + default: + return { success: false, error: `Unknown message type: ${(message as ExtensionMessage).type}` }; + } +} +``` + +--- + +### Offscreen Document Sandbox (`offscreen/sandbox.ts`) + +```typescript +chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { + if (message.target !== 'offscreen') return; + + if (message.type === 'RUN_BYTECODE') { + executeSandboxedBytecode(message.payload) + .then((result) => sendResponse({ success: true, result })) + .catch((err: Error) => sendResponse({ success: false, error: err.message })); + return true; + } +}); + +async function executeSandboxedBytecode(wasmBase64: string): Promise { + const binaryString = atob(wasmBase64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + + const wasmModule = await WebAssembly.instantiate(bytes, { + env: { + memory: new WebAssembly.Memory({ initial: 256, maximum: 512 }), + }, + }); + + const runCompute = wasmModule.instance.exports.compute as () => number; + return typeof runCompute === 'function' ? runCompute() : 0; +} +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasikan skill `senior-frontend`, `tailwind-expert`, `pwa-offline-first-expert`, `ai-llm-integration-expert`, `vercel-ai-sdk-expert`, `mcp-server-architect`, `authentication-identity-expert`, `zero-trust-secret-vault`, dan `anti-slop`. + +### Deskripsi +Panduan komprehensif untuk merekayasa ekstensi peramban modern berkinerja tinggi, aman, dan lintas platform (Chrome, Edge, Firefox, Safari) berbasis **Manifest V3 (MV3)**. Standar Manifest V3 menggantikan background page persisten dengan service worker efemeral, menegakkan aturan declarative network yang aman, menyediakan SidePanel API native, serta sandbox dokumen offscreen untuk eksekusi WebAssembly dan pemrosesan audio/clipboard. + +### Prinsip Utama & Invarian Arsitektur MV3 + +1. **Service Worker Efemeral**: + - Background service worker akan otomatis mati setelah ~30 detik tidak aktif. + - Jangan pernah menyimpan state jangka panjang di memori global JavaScript. Gunakan `chrome.storage.session` untuk state in-memory sementara dan `chrome.storage.local` untuk data persisten. + - Gunakan `chrome.alarms` untuk tugas berulang terjadwal. + +2. **SidePanel API (`chrome.sidePanel`)**: + - Standar modern 2026 untuk panel samping pendamping AI (*AI Copilot*) dan inspeksi konteks halaman web tanpa mengganggu tampilan halaman utama pengguna. + +3. **Dokumen Offscreen (`chrome.offscreen`)**: + - Karena Service Worker tidak memiliki akses ke DOM, dokumen offscreen menyediakan lingkungan DOM terisolasi untuk eksekusi WebAssembly (WASM), dekode audio, dan manipulasi clipboard. + +4. **Declarative Net Request**: + - Memodifikasi header dan rute jaringan secara deklaratif dan cepat tanpa overhead performa dari blocking webRequest lama. + +--- + +### Praktik Terbaik Keamanan & Anti-Slop Ekstensi + +1. **Larangan Evaluasi Kode Dinamis**: + - Dilarang keras menggunakan `eval()`, `new Function()`, atau mengeksekusi skrip dari CDN luar. Seluruh kode wajib dibundel secara lokal. +2. **Isolasi Dunia Konteks (Isolated World)**: + - Content script berjalan di dunia terisolasi. Komunikasi antar host page dan ekstensi dilakukan melalui pesan tervalidasi dengan sanitasi ketat. +3. **Kontrak UI 5-State**: + - Seluruh elemen interaktif pada SidePanel wajib menerapkan kontrak 5-state (default, hover, focus-visible, active, disabled) dengan tipografi modern dan angka tabular (`tabular-nums`). diff --git a/vibes-plug/skills/bun-runtime-expert/SKILL.md b/vibes-plug/skills/bun-runtime-expert/SKILL.md new file mode 100644 index 000000000..9608f3a76 --- /dev/null +++ b/vibes-plug/skills/bun-runtime-expert/SKILL.md @@ -0,0 +1,218 @@ +--- +name: bun-runtime-expert +description: "Expert guide for Bun JavaScript/TypeScript runtime. Use when building, testing, or deploying applications with Bun / Panduan ahli untuk runtime JavaScript/TypeScript Bun. Digunakan saat membuat, menguji, atau meluncurkan aplikasi dengan Bun." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Bun Runtime Expert + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +Expert-level guidance for building high-performance applications with the Bun JavaScript/TypeScript runtime (v1.1+). Covers Bun's built-in HTTP server, database clients, bundler, test runner, package manager, and Node.js migration strategies. + +### Trigger Conditions +- Use when scaffolding a new project with Bun as the runtime. +- Use when building HTTP servers or APIs with `Bun.serve()`. +- Use when querying databases with `Bun.sql` (PostgreSQL, MySQL, SQLite). +- Use when interacting with S3-compatible object storage via `Bun.s3`. +- Use when bundling frontend or backend code with `bun build`. +- Use when writing tests with `bun:test`. +- Use when migrating an existing Node.js project to Bun. +- Use when optimizing package installation speed or lockfile management. + +### Core Architecture + +#### Why Bun? +Bun is a batteries-included JavaScript/TypeScript runtime that replaces Node.js, npm, Webpack/Vite, and Jest in a single binary: + +| Capability | Bun Built-in | Node.js Equivalent | +|---|---|---| +| Runtime | `bun run` | `node` | +| Package Manager | `bun install` | `npm` / `pnpm` / `yarn` | +| Bundler | `bun build` | Webpack / Vite / esbuild | +| Test Runner | `bun test` | Jest / Vitest | +| HTTP Server | `Bun.serve()` | Express / Fastify | +| SQL Client | `Bun.sql` | `pg` / `mysql2` / `better-sqlite3` | +| S3 Client | `Bun.s3` | `@aws-sdk/client-s3` | +| Redis Client | Built-in | `ioredis` | +| TypeScript | Native (zero config) | `ts-node` / `tsx` | +| `.env` loading | Native | `dotenv` | + +### Quick Start + +#### 1. Install Bun +```bash +# macOS / Linux +curl -fsSL https://bun.sh/install | bash + +# Windows (PowerShell) +powershell -c "irm bun.sh/install.ps1 | iex" + +# Verify installation +bun --version +``` + +#### 2. Initialize a New Project +```bash +bun init +``` +This generates `package.json`, `tsconfig.json`, and an `index.ts` entry point. TypeScript works out of the box with zero configuration. + +#### 3. Install Dependencies +```bash +# Install all dependencies (10-100x faster than npm) +bun install + +# Add a package +bun add hono zod drizzle-orm + +# Add dev dependency +bun add -d @types/bun vitest +``` + +### Bun.serve() — High-Performance HTTP Server +`Bun.serve()` is a zero-dependency HTTP server with built-in TLS, WebSocket support, and hot module reloading. + +#### Basic HTTP Server +```typescript +Bun.serve({ + port: 3000, + fetch(req) { + const url = new URL(req.url); + if (url.pathname === '/api/health') { + return Response.json({ status: 'ok', runtime: 'bun' }); + } + return new Response('Not Found', { status: 404 }); + }, +}); +``` + +### Bun.sql — Unified Database Client +Zero-dependency SQL client supporting PostgreSQL, MySQL/MariaDB, and SQLite via tagged template literals. + +#### PostgreSQL +```typescript +import { sql } from 'bun'; +const users = await sql`SELECT * FROM users WHERE active = ${true}`; +``` + +### Best Practices +- **Performance:** Use `Bun.serve()` directly or Hono for HTTP — avoid Express (slower compat layer). Use `Bun.file()` for efficient file I/O. +- **Security:** Always parameterize queries via template literals in `Bun.sql` (automatically prevents SQL injection). +- **Testing:** Use `bun:test` — it's Jest-compatible and significantly faster. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +Panduan tingkat ahli untuk membangun aplikasi berkinerja tinggi menggunakan runtime JavaScript/TypeScript Bun (v1.1+). Mencakup server HTTP bawaan, klien database, bundler, test runner, package manager, dan strategi migrasi dari Node.js. + +### Kondisi Pemicu +- Gunakan saat merancang proyek baru menggunakan Bun sebagai runtime. +- Gunakan saat membangun server HTTP atau API dengan `Bun.serve()`. +- Gunakan saat melakukan query database dengan `Bun.sql` (PostgreSQL, MySQL, SQLite). +- Gunakan saat berinteraksi dengan object storage yang kompatibel dengan S3 via `Bun.s3`. +- Gunakan saat membundel kode frontend atau backend dengan `bun build`. +- Gunakan saat menulis pengujian (testing) menggunakan `bun:test`. +- Gunakan saat memigrasikan proyek Node.js ke Bun. +- Gunakan saat mengoptimalkan kecepatan instalasi paket atau manajemen lockfile. + +### Arsitektur Inti + +#### Mengapa Bun? +Bun adalah runtime JavaScript/TypeScript serba ada yang menggantikan Node.js, npm, Webpack/Vite, dan Jest dalam satu berkas biner tunggal: + +| Kemampuan | Bawaan Bun | Setara di Node.js | +|---|---|---| +| Runtime | `bun run` | `node` | +| Package Manager | `bun install` | `npm` / `pnpm` / `yarn` | +| Bundler | `bun build` | Webpack / Vite / esbuild | +| Test Runner | `bun test` | Jest / Vitest | +| HTTP Server | `Bun.serve()` | Express / Fastify | +| SQL Client | `Bun.sql` | `pg` / `mysql2` / `better-sqlite3` | +| S3 Client | `Bun.s3` | `@aws-sdk/client-s3` | +| Redis Client | Built-in | `ioredis` | +| TypeScript | Native (tanpa config) | `ts-node` / `tsx` | +| `.env` loading | Native | `dotenv` | + +### Memulai Cepat + +#### 1. Instal Bun +```bash +# Windows (PowerShell) +powershell -c "irm bun.sh/install.ps1 | iex" + +# macOS / Linux +curl -fsSL https://bun.sh/install | bash + +# Verifikasi instalasi +bun --version +``` + +#### 2. Inisialisasi Proyek Baru +```bash +bun init +``` +Ini menghasilkan `package.json`, `tsconfig.json`, dan file entry point `index.ts`. TypeScript langsung berfungsi tanpa konfigurasi tambahan. + +#### 3. Instal Dependensi +```bash +# Mengmenginstal semua dependensi (10-100x lebih cepat dari npm) +bun install + +# Menambahkan paket +bun add hono zod drizzle-orm + +# Menambahkan dev dependency +bun add -d @types/bun vitest +``` + +### Bun.serve() — HTTP Server Berkinerja Tinggi +`Bun.serve()` adalah server HTTP tanpa dependensi eksternal dengan dukungan TLS bawaan, WebSocket, dan hot module reloading. + +#### Server HTTP Dasar +```typescript +Bun.serve({ + port: 3000, + fetch(req) { + const url = new URL(req.url); + if (url.pathname === '/api/health') { + return Response.json({ status: 'ok', runtime: 'bun' }); + } + return new Response('Not Found', { status: 404 }); + }, +}); +``` + +### Bun.sql — Klien Database Terpadu +Klien SQL tanpa dependensi eksternal yang mendukung PostgreSQL, MySQL/MariaDB, dan SQLite melalui tagged template literals. + +#### PostgreSQL +```typescript +import { sql } from 'bun'; +const users = await sql`SELECT * FROM users WHERE active = ${true}`; +``` + +### Praktik Terbaik +- **Performa:** Gunakan `Bun.serve()` secara langsung atau bersama Hono — hindari Express (karena lapisan kompatibilitasnya lebih lambat). Gunakan `Bun.file()` untuk I/O file yang efisien. +- **Keamanan:** Selalu gunakan parameterisasi query melalui template literals di `Bun.sql` untuk mencegah SQL Injection secara otomatis. +- **Pengujian:** Gunakan `bun:test` yang kompatibel dengan Jest namun jauh lebih cepat. + +--- + +### Limitations / Batasan +- Use this skill only when the task involves the Bun runtime specifically. +- Bun's Node.js compatibility is extensive but not 100%. Always verify critical `node:*` API usage. \ No newline at end of file diff --git a/vibes-plug/skills/chatbot-messaging-expert/SKILL.md b/vibes-plug/skills/chatbot-messaging-expert/SKILL.md new file mode 100644 index 000000000..75b0dbae9 --- /dev/null +++ b/vibes-plug/skills/chatbot-messaging-expert/SKILL.md @@ -0,0 +1,191 @@ +--- +name: chatbot-messaging-expert +description: "Expert guide for chatbot and messaging platform integration (WhatsApp Business, Telegram Bot, Discord.js, Slack Bolt) and conversational AI / Panduan ahli integrasi chatbot dan platform messaging (WhatsApp Business, Telegram Bot, Discord.js, Slack Bolt) dan AI percakapan." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Chatbot & Messaging Platform Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Production guide for architecting, deploying, and scaling conversational bots across enterprise messaging platforms: WhatsApp Business Cloud API, Telegram Bot API (via grammY), Discord.js v14, Slack Bolt (Block Kit), and LINE Messaging API. Covers cryptographic webhook verification (Meta `hub.challenge` and Slack `v0` HMAC signatures), interactive UI components (buttons, carousels, quick replies), session state persistence, media streaming, and integration with AI tool calling engines. + +### Trigger Conditions +- Integrating customer support or transactional notification bots for WhatsApp Business. +- Scaffolding Telegram automation bots with inline keyboards and deep linking. +- Building Discord slash command applications and voice channel event listeners. +- Developing Slack workspace applications with modal forms and Block Kit interactive layouts. +- Ingesting and verifying messaging webhooks with signature authentication. + +### Platform Quick Reference Matrix + +| Platform | Protocol | Auth Mechanism | Primary Message Types | Webhook Verification | +|---|---|---|---|---| +| **WhatsApp Business** | REST (Meta Cloud API) | System User Token | Text, Interactive Buttons, Lists, Templates | `hub.verify_token` + `hub.challenge` | +| **Telegram** | REST (Bot API) | Bot Token | Text, Photos, Inline Keyboards, Web Apps | Secret token header (`setWebhook`) | +| **Slack** | Events API / Sockets | Bot Token + Signing Secret | Block Kit, Modals, Slash Commands | HMAC-SHA256 (`v0=...`) signature | +| **Discord** | Gateway (WebSockets) + REST | Bot Token | Embeds, Select Menus, Slash Commands | Ed25519 signature verification | + +### WhatsApp Business Cloud API Webhook Handler (Hono / TypeScript) + +```typescript +// src/routes/whatsapp-webhook.ts +import { Hono } from 'hono'; + +const app = new Hono(); + +// 1. Meta Webhook Handshake Verification +app.get('/webhook/whatsapp', (c) => { + const mode = c.req.query('hub.mode'); + const token = c.req.query('hub.verify_token'); + const challenge = c.req.query('hub.challenge'); + + if (mode === 'subscribe' && token === process.env.WHATSAPP_VERIFY_TOKEN) { + return c.text(challenge!, 200); + } + return c.text('Forbidden: Invalid verification token', 403); +}); + +// 2. Incoming Message Processing +app.post('/webhook/whatsapp', async (c) => { + const payload = await c.req.json(); + const message = payload.entry?.[0]?.changes?.[0]?.value?.messages?.[0]; + + if (message && message.type === 'text') { + const senderPhone = message.from; + const incomingText = message.text.body; + + // Acknowledge receipt immediately (WhatsApp requires <3s HTTP 200 response) + // Execute AI response generation asynchronously + c.executionCtx?.waitUntil(handleIncomingWhatsAppMessage(senderPhone, incomingText)); + } + + return c.json({ status: 'ok' }, 200); +}); + +async function handleIncomingWhatsAppMessage(to: string, prompt: string) { + // Call AI agent and send reply + await fetch(`https://graph.facebook.com/v21.0/${process.env.WHATSAPP_PHONE_NUMBER_ID}/messages`, { + method: 'POST', + headers: { + Authorization: `Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messaging_product: 'whatsapp', + to, + type: 'text', + text: { body: `AI Assistant: Processing your request...` }, + }), + }); +} +``` + +### Telegram Bot with Inline Buttons (grammY) + +```typescript +// src/bots/telegram-bot.ts +import { Bot, InlineKeyboard, webhookCallback } from 'grammy'; + +export const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN!); + +bot.command('start', async (ctx) => { + const keyboard = new InlineKeyboard() + .text('📦 Check Order', 'action_order') + .text('💬 Human Support', 'action_support') + .row() + .url('🌐 Open Web App', 'https://vibesplug.internal/app'); + + await ctx.reply(`Hello ${ctx.from?.first_name}! How can I assist you today?`, { + reply_markup: keyboard, + }); +}); + +bot.callbackQuery('action_order', async (ctx) => { + await ctx.answerCallbackQuery({ text: 'Fetching order data...' }); + await ctx.reply('Please reply with your Order Number (e.g., #ORD-12345).'); +}); +``` + +## Orchestration & Integration +- **`ai-llm-integration-expert`**: Directs conversational AI responses, RAG retrieval, and function calling. +- **`sse-websocket-streaming-expert`**: Bridges real-time chat websockets between web and bot channels. +- **`async-queue-temporal-expert`**: Offloads long-running message handling to BullMQ workers. +- **`rate-limit-abuse-prevention`**: Protects public bot webhooks against volumetric spam and DDoS attacks. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi bersama `ai-llm-integration-expert`, `sse-websocket-streaming-expert`, `async-queue-temporal-expert`, dan `rate-limit-abuse-prevention`. + +### Deskripsi +Panduan produksi untuk merancang, meluncurkan, dan menskalakan bot percakapan di berbagai platform perpesanan terkemuka: WhatsApp Business Cloud API, Telegram Bot API (via grammY), Discord.js v14, Slack Bolt (Block Kit), dan LINE Messaging API. Mencakup verifikasi webhook kriptografis (jabat tangan Meta `hub.challenge` dan tanda tangan HMAC Slack `v0`), komponen interaktif (tombol, list menu, keyboard inline), persistensi sesi pengguna, penanganan media, serta integrasi pemanggilan fungsi AI (*tool calling*). + +### Kondisi Pemicu +- Membangun bot layanan pelanggan (*customer support*) atau notifikasi transaksi otomatis di WhatsApp Business. +- Membuat bot otomasi Telegram dengan tombol inline interaktif dan integrasi Telegram Web App. +- Mengembangkan aplikasi Discord dengan slash command (`/order`, `/status`). +- Mengembangkan bot internal Slack dengan form modal interaktif (*Block Kit*). +- Memverifikasi webhook platform perpesanan agar kebal dari pemalsuan data (*spoofing*). + +### Pola Integrasi Slack Bolt (Slash Commands & Block Kit) + +```typescript +// src/bots/slack-app.ts +import { App } from '@slack/bolt'; + +const slackApp = new App({ + token: process.env.SLACK_BOT_TOKEN, + signingSecret: process.env.SLACK_SIGNING_SECRET, +}); + +// Menangani perintah slash command: /faktur +slackApp.command('/faktur', async ({ command, ack, respond }) => { + // Wajib kirim ack() dalam 3 detik agar Slack tidak menampilkan error timeout + await ack(); + + await respond({ + blocks: [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `Halo <@${command.user_id}>, berikut adalah rincian faktur pesanan Anda:`, + }, + }, + { + type: 'actions', + elements: [ + { + type: 'button', + text: { type: 'plain_text', text: 'Unduh PDF Faktur' }, + action_id: 'btn_unduh_pdf', + style: 'primary', + }, + ], + }, + ], + }); +}); +``` + +### 3 Aturan Emas Integrasi Platform Perpesanan +1. **Respons Webhook < 3 Detik**: WhatsApp, Slack, dan Telegram akan memutus koneksi jika endpoint tidak mengembalikan HTTP 200 dalam 3 detik. Kembalikan respons 200 terlebih dahulu, lalu proses pembuatan jawaban AI secara asinkron di latar belakang (*background job*). +2. **Validasi Tanda Tangan Kriptografis**: Selalu periksa tanda tangan incoming payload (`x-hub-signature-256` di WhatsApp atau `x-slack-signature` di Slack) untuk mencegah pihak ketiga mengirim pesan palsu ke server Anda. +3. **Penyimpanan Sesi Percakapan**: Simpan konteks percakapan di Redis dengan TTL terukur agar pengguna dapat melanjutkan percakapan tanpa kehilangan konteks. + +## Integrasi Orkestrasi +- **`ai-llm-integration-expert`**: Menghasilkan respon cerdas dan memanggil tool API. +- **`sse-websocket-streaming-expert`**: Menghubungkan antarmuka obrolan web langsung ke saluran bot perpesanan. +- **`async-queue-temporal-expert`**: Mengantrekan pengiriman pesan massal (*broadcast notification*) menggunakan BullMQ. +- **`rate-limit-abuse-prevention`**: Melindungi endpoint webhook bot dari serangan spam. \ No newline at end of file diff --git a/vibes-plug/skills/ci-cd-devops-architect/SKILL.md b/vibes-plug/skills/ci-cd-devops-architect/SKILL.md new file mode 100644 index 000000000..0ef118659 --- /dev/null +++ b/vibes-plug/skills/ci-cd-devops-architect/SKILL.md @@ -0,0 +1,196 @@ +--- +name: ci-cd-devops-architect +description: "Expert guide for continuous integration, deployment pipelines, Docker, Kubernetes, and Infrastructure as Code (IaC) / Panduan ahli untuk CI/CD dan infrastruktur." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# CI/CD & DevOps Architect (Production Standard 2026) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Enterprise guide for modern Continuous Integration & Continuous Delivery (CI/CD) pipelines, immutable container workflows (Docker & Kubernetes 1.30+), and Infrastructure as Code (Terraform / OpenTofu). Covers parallelized GitHub Actions workflows with dependency caching (pnpm/bun), multi-stage non-root distroless Docker builds, Trivy container vulnerability scanning, zero-downtime rolling/canary deployments, and zero-trust secret injection via OIDC. + +### Trigger Conditions +- Scaffolding new GitHub Actions or GitLab CI/CD pipelines (Phase 7). +- Writing hardened multi-stage Dockerfiles for Node.js, Bun, Go, or Rust applications. +- Setting up automated PR status checks and branch protection rules. +- Implementing container vulnerability scanning and SBOM generation. +- Configuring Infrastructure as Code (OpenTofu/Terraform) for cloud providers. + +### Production Multi-Stage Dockerfile (Node.js 24 / Distroless) + +```dockerfile +# syntax=docker/dockerfile:1.7 +# Stage 1: Dependency resolution and compilation +FROM node:24-alpine AS builder +WORKDIR /app + +# Enable pnpm via corepack +RUN corepack enable && corepack prepare pnpm@latest --activate + +# Copy manifest files first to maximize layer caching +COPY package.json pnpm-lock.yaml ./ +RUN pnpm install --frozen-lockfile + +# Copy source code and build production bundle +COPY . . +RUN pnpm run build && pnpm prune --prod + +# Stage 2: Minimal, hardened production runtime +FROM gcr.io/distroless/nodejs24-debian12:nonroot AS runner +WORKDIR /app + +# Run strictly as non-root user (UID 65532 in distroless) +USER nonroot + +# Copy only production artifacts +COPY --from=builder --chown=nonroot:nonroot /app/node_modules ./node_modules +COPY --from=builder --chown=nonroot:nonroot /app/dist ./dist +COPY --from=builder --chown=nonroot:nonroot /app/package.json ./package.json + +ENV NODE_ENV=production +ENV PORT=3000 +EXPOSE 3000 + +CMD ["dist/index.js"] +``` + +### Production GitHub Actions Workflow (`.github/workflows/ci.yml`) + +```yaml +name: Production CI Pipeline + +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: latest + + - name: Setup Node.js 24 + uses: actions/setup-node@v4 + with: + node-version: 24 + cache: 'pnpm' + + - name: Install Dependencies + run: pnpm install --frozen-lockfile + + - name: Lint and Format Check (Biome) + run: npx @biomejs/biome ci . + + - name: Type Check (TypeScript) + run: pnpm exec tsc --noEmit + + - name: Run Test Suite (Vitest) + run: pnpm test + + security-scan: + needs: validate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Run Trivy Vulnerability Scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: 'fs' + ignore-unfixed: true + severity: 'CRITICAL,HIGH' +``` + +### Key DevOps Invariants +1. **Immutable Artifacts**: Build the container image exactly once in CI. The identical binary is promoted across Staging and Production; only environment variables change. +2. **Non-Root Runtime**: Never run Docker containers as `root`. Always use unprivileged users (`nonroot` or `node`) to minimize container breakout vulnerabilities. +3. **No Hardcoded Secrets**: Secrets must never be stored in GitHub Secrets as plaintext strings. Use GitHub OIDC tokens to fetch short-lived credentials from AWS IAM or Vault (`zero-trust-secret-vault`). + +## Orchestration & Integration +- **`cloud-hosting-expert`**: Connects pipeline deployment triggers with Vercel, Railway, or AWS ECS. +- **`zero-trust-secret-vault`**: Manages OIDC federated authentication and secret injection. +- **`autonomous-tdd-debugger`**: Runs unit and integration tests inside the CI runner. +- **`production-ready-hardener`**: Validates security headers, SBOM, and container scan outputs. + +--- + + +## Bahasa Indonesia + +### Deskripsi +Panduan enterprise untuk pipeline *Continuous Integration & Continuous Delivery* (CI/CD) modern, alur kerja kontainer imutabel (Docker & Kubernetes 1.30+), dan *Infrastructure as Code* (Terraform/OpenTofu). Mencakup pipeline GitHub Actions paralel dengan caching dependensi (pnpm/bun), Dockerfile multi-stage berbasis distroless non-root yang aman, pemindaian kerentanan kontainer dengan Trivy, serta injeksi rahasia tanpa password via OIDC. + +### Kondisi Pemicu +- Membuat konfigurasi GitHub Actions atau GitLab CI/CD dari awal (Fase 7). +- Menulis Dockerfile multi-stage yang aman untuk aplikasi Node.js, Bun, Go, atau Rust. +- Mengatur aturan perlindungan cabang (*branch protection*) dan status checks wajib. +- Menjalankan pemindaian kerentanan kontainer otomatis sebelum rilis ke server. +- Mengonfigurasi infrastruktur cloud menggunakan Terraform atau OpenTofu. + +### Contoh Manifest Kubernetes 1.30+ (Deployment Aman) + +```yaml +# k8s/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: vibes-api-backend +spec: + replicas: 3 + selector: + matchLabels: + app: vibes-api + template: + metadata: + labels: + app: vibes-api + spec: + securityContext: + runAsNonRoot: true + runAsUser: 65532 + containers: + - name: api + image: myregistry.azurecr.io/vibes-api:latest + resources: + requests: + cpu: "100m" + memory: "128Mi" + limits: + cpu: "500m" + memory: "512Mi" + readinessProbe: + httpGet: + path: /api/health + port: 3000 + initialDelaySeconds: 5 + periodSeconds: 10 +``` + +### 3 Hukum Mutlak Keamanan DevOps +1. **Artifak Imutabel**: Image kontainer yang diuji pada tahap Staging adalah file image yang sama persis yang dijalankan pada server Produksi. +2. **Larangan Akses Root**: Kontainer dilarang keras dijalankan dengan hak akses root demi mencegah eksploitasi pelarian kontainer (*container escape*). +3. **Rahasia Berumur Pendek**: Gunakan otentikasi OIDC tanpa kata kunci statis untuk mengakses registry dan server cloud. + +## Integrasi Orkestrasi +- **`cloud-hosting-expert`**: Mengotomatisasi deployment akhir ke edge/cloud runner. +- **`zero-trust-secret-vault`**: Memasok token autentikasi dinamis ke dalam pipeline. +- **`autonomous-tdd-debugger`**: Memastikan seluruh test otomatis lolos sebelum komit di-merge. +- **`production-ready-hardener`**: Memverifikasi kesiapan rilis produksi pada tahap akhir CI. \ No newline at end of file diff --git a/vibes-plug/skills/cloud-hosting-expert/SKILL.md b/vibes-plug/skills/cloud-hosting-expert/SKILL.md new file mode 100644 index 000000000..ef338bad3 --- /dev/null +++ b/vibes-plug/skills/cloud-hosting-expert/SKILL.md @@ -0,0 +1,308 @@ +--- +name: cloud-hosting-expert +description: "Expert guide for deploying SaaS applications with multiple entry points on modern edge and serverless platforms like Vercel and Cloudflare / Panduan ahli untuk mendeploy aplikasi SaaS dengan multiple entry points di platform edge dan serverless modern seperti Vercel dan Cloudflare." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Cloud Hosting Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Expert guide for deploying SaaS applications and their multiple entry points (landing page, app, super admin subdomain) on modern edge and serverless platforms. Covers Vercel, Cloudflare Workers & Pages, Railway, Fly.io, and **Cloudflare Workers AI** for AI-powered edge workloads. + +### Trigger Conditions +- Deploying a Next.js, Hono, or Astro application to Vercel, Cloudflare, or Railway. +- Configuring custom domains and subdomain routing (e.g., `app.domain.com`, `admin.domain.com`). +- Setting up Edge Middleware for multi-tenant tenant identification. +- Deploying AI inference workloads to **Cloudflare Workers AI**. +- Deploying long-running backend services to **Railway** or **Fly.io**. +- Implementing CDN caching strategies for SaaS applications. + +### Platform Selection Guide (2026) + +| Platform | Best For | Free Tier | Cold Start | +|---|---|---|---| +| **Vercel** | Next.js, static, serverless functions | ✅ | ~200ms | +| **Cloudflare Workers** | Ultra-low latency APIs, edge logic | ✅ (100k req/day) | ~0ms | +| **Cloudflare Pages** | Static + full-stack (via Workers) | ✅ | ~0ms | +| **Railway** | Node.js/Go/Python long-running services, Bun | ✅ (5$/mo credit) | None | +| **Fly.io** | Docker containers, global distribution | ✅ (3 shared VMs) | ~500ms | +| **Render** | Node.js/Go/Python persistent services | ✅ (spins down) | ~30s | + +### Multi-Entry Point Deployment Architecture + +For SaaS applications, separate deployments for each entry point: +``` +myapp.com → Vercel (Marketing/Landing — Next.js static) +app.myapp.com → Vercel (SaaS App — Next.js dynamic) +admin.myapp.com → Vercel (Super Admin — Next.js, restricted access) +api.myapp.com → Railway/Fly.io (Backend API — long-running) +cdn.myapp.com → Cloudflare R2 (Static assets & user uploads) +``` + +### Vercel — Next.js Deployment + +#### Multi-Domain Configuration +```json +// vercel.json +{ + "rewrites": [ + { "source": "/(.*)", "destination": "/$1" } + ], + "headers": [ + { + "source": "/(.*)", + "headers": [ + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "X-Frame-Options", "value": "DENY" }, + { "key": "Strict-Transport-Security", "value": "max-age=63072000; includeSubDomains; preload" } + ] + } + ] +} +``` + +#### Edge Middleware for Tenant Routing +```typescript +// middleware.ts — runs at the edge before every request +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +export function middleware(request: NextRequest) { + const hostname = request.headers.get('host') ?? ''; + const subdomain = hostname.split('.')[0]; + + // Route admin subdomain — enforce strict auth check + if (subdomain === 'admin') { + const adminToken = request.cookies.get('admin-session')?.value; + if (!adminToken) { + return NextResponse.redirect(new URL('/login', request.url)); + } + } + + // Identify tenant from subdomain for multi-tenant apps + if (subdomain !== 'www' && subdomain !== 'app' && subdomain !== 'admin') { + const response = NextResponse.next(); + response.headers.set('x-tenant-slug', subdomain); + return response; + } + + return NextResponse.next(); +} + +export const config = { + matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], +}; +``` + +### Cloudflare Workers — Edge APIs + +#### Hono on Cloudflare Workers +```typescript +// src/index.ts +import { Hono } from 'hono'; +import { cors } from 'hono/cors'; +import { rateLimit } from '@/middleware/rateLimit'; + +const app = new Hono<{ Bindings: Env }>(); + +app.use('*', cors({ origin: ['https://app.myapp.com'] })); +app.use('/api/*', rateLimit(100)); // 100 req/min via KV + +app.get('/api/health', (c) => c.json({ status: 'ok', region: c.env.CF_REGION })); + +app.get('/api/data', async (c) => { + // Access Cloudflare D1 (SQLite at edge) + const result = await c.env.DB.prepare('SELECT * FROM items LIMIT 20').all(); + return c.json(result.results); +}); + +export default app; +``` + +#### Cloudflare Workers AI (On-Device Edge Inference) +Run AI models directly at Cloudflare's edge — no external API calls needed: +```typescript +export default { + async fetch(request: Request, env: Env) { + const { text } = await request.json() as { text: string }; + + // Run Llama 3 or Mistral at the edge + const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [ + { role: 'system', content: 'You are a helpful assistant.' }, + { role: 'user', content: text } + ], + stream: true, + }); + + return new Response(response, { + headers: { 'Content-Type': 'text/event-stream' } + }); + } +}; +``` + +Available models on Workers AI: +- `@cf/meta/llama-3.1-8b-instruct` — Fast general-purpose chat +- `@cf/mistral/mistral-7b-instruct-v0.2` — Fast instruction model +- `@cf/baai/bge-small-en-v1.5` — Text embedding (for RAG) +- `@cf/stabilityai/stable-diffusion-xl-base-1.0` — Image generation + +### Railway — Bun / Node.js Long-Running Services +```dockerfile +# Dockerfile for Railway (Bun runtime) +FROM oven/bun:1.2-alpine +WORKDIR /app +COPY package.json bun.lockb ./ +RUN bun install --frozen-lockfile +COPY . . +EXPOSE 3000 +CMD ["bun", "run", "src/server.ts"] +``` + +```toml +# railway.toml +[build] +builder = "DOCKERFILE" + +[deploy] +startCommand = "bun run src/server.ts" +healthcheckPath = "/health" +healthcheckTimeout = 10 +restartPolicyType = "ON_FAILURE" +``` + +### Environment Variables & Secrets Management +- **Vercel**: Use Vercel's built-in secrets panel — supports preview/production scoping. +- **Cloudflare**: Use `wrangler secret put SECRET_NAME` or the dashboard. +- **Railway**: Use Railway's variable groups for shared secrets across services. +- **Never** commit `.env` files — use `.env.example` as documentation only. + +### Caching Strategy +```typescript +// Vercel: Cache API responses at the edge +export async function GET() { + const data = await fetchData(); + return Response.json(data, { + headers: { + 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=300', + } + }); +} + +// Cloudflare: Use Cache API +const cache = caches.default; +const cached = await cache.match(request); +if (cached) return cached; +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Deskripsi +Panduan ahli untuk men-deploy aplikasi SaaS dan multiple entry points-nya (landing page, aplikasi, subdomain super admin) di platform edge dan serverless modern. Mencakup Vercel, Cloudflare Workers & Pages, Railway, Fly.io, dan **Cloudflare Workers AI** untuk workload AI di edge. + +### Kondisi Pemicu +- Men-deploy aplikasi Next.js, Hono, atau Astro ke Vercel, Cloudflare, atau Railway. +- Mengonfigurasi domain kustom dan routing subdomain (`app.domain.com`, `admin.domain.com`). +- Menyiapkan Edge Middleware untuk identifikasi tenant multi-tenant. +- Men-deploy workload inferensi AI ke **Cloudflare Workers AI**. +- Men-deploy layanan backend long-running ke **Railway** atau **Fly.io**. + +--- + +### Panduan Pemilihan Platform (2026) + +| Platform | Pilihan Terbaik Untuk | Tier Gratis | Cold Start | +|---|---|---|---| +| **Vercel** | Next.js, situs statis, serverless functions | ✅ | ~200ms | +| **Cloudflare Workers** | API latensi ultra-rendah, logika edge | ✅ (100k req/hari) | ~0ms | +| **Cloudflare Pages** | Statis + full-stack (via Workers) | ✅ | ~0ms | +| **Railway** | Layanan Node.js/Bun/Go/Python long-running | ✅ ($5 kredit/bln) | Nol | +| **Fly.io** | Kontainer Docker terdistribusi global | ✅ (3 shared VM) | ~500ms | + +--- + +### Implementasi Pola Kunci (TypeScript) + +#### 1. Edge Middleware untuk Routing Subdomain & Tenant (Next.js 15) +```typescript +// middleware.ts +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +export function middleware(request: NextRequest) { + const hostname = request.headers.get('host') ?? ''; + const subdomain = hostname.split('.')[0]; + + // Rute subdomain admin — tegakkan pemeriksaan otentikasi ketat + if (subdomain === 'admin') { + const sesiAdmin = request.cookies.get('admin-session')?.value; + if (!sesiAdmin) { + return NextResponse.redirect(new URL('/masuk', request.url)); + } + } + + // Identifikasi tenant dari subdomain pada aplikasi multi-tenant + if (subdomain !== 'www' && subdomain !== 'app' && subdomain !== 'admin') { + const response = NextResponse.next(); + response.headers.set('x-tenant-slug', subdomain); + return response; + } + + return NextResponse.next(); +} + +export const config = { + matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], +}; +``` + +#### 2. Cloudflare Workers AI (Inferensi AI di Edge) +```typescript +export default { + async fetch(request: Request, env: Env) { + const { teks } = (await request.json()) as { teks: string }; + + // Jalankan inferensi Llama 3.1 langsung di edge tanpa server eksternal + const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [ + { role: 'system', content: 'Anda adalah asisten AI yang akurat.' }, + { role: 'user', content: teks }, + ], + stream: true, + }); + + return new Response(response, { + headers: { 'Content-Type': 'text/event-stream' }, + }); + }, +}; +``` + +#### 3. Railway Dockerfile untuk Runtime Bun Berkecepatan Tinggi +```dockerfile +FROM oven/bun:1.2-alpine +WORKDIR /app +COPY package.json bun.lockb ./ +RUN bun install --frozen-lockfile +COPY . . +EXPOSE 3000 +CMD ["bun", "run", "src/server.ts"] +``` \ No newline at end of file diff --git a/vibes-plug/skills/cloudflare-workers-expert/SKILL.md b/vibes-plug/skills/cloudflare-workers-expert/SKILL.md new file mode 100644 index 000000000..837d4904f --- /dev/null +++ b/vibes-plug/skills/cloudflare-workers-expert/SKILL.md @@ -0,0 +1,328 @@ +--- +name: cloudflare-workers-expert +description: "Expert guide for Cloudflare Workers ecosystem — Workers, D1 (SQLite at edge), KV, R2 (S3-compatible storage), Queues, Durable Objects, Hyperdrive, and Workers AI / Panduan ahli ekosistem Cloudflare Workers — Workers, D1, KV, R2, Queues, Durable Objects, Hyperdrive, dan Workers AI." +author: "Roedy Rustam" +version: "4.4.0" +--- + +# Cloudflare Workers Ecosystem Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects with: `brainstorming`, `zero-to-prod-orchestrator`, `js-backend-expert`, `database-orm-expert`, `api-design-expert`, `authentication-identity-expert`, `wasm-edge-computing-expert`, `ci-cd-devops-architect`, `cloud-hosting-expert`, `session-memory-manager`. + +### Description +Expert guide for building full-stack edge applications using the **Cloudflare Workers** ecosystem. Covers Workers runtime, D1 (SQLite at edge), KV (key-value store), R2 (S3-compatible object storage), Queues (message queues), Durable Objects (stateful edge), Hyperdrive (database connection pooling), Workers AI (inference at edge), and Wrangler CLI for development and deployment. + +### Trigger Conditions +- Building serverless edge applications on Cloudflare Workers. +- Using **D1** as an edge SQLite database. +- Storing files with **R2** (S3-compatible, zero egress fees). +- Implementing **KV** for distributed key-value caching. +- Building stateful applications with **Durable Objects**. +- Setting up **Queues** for async job processing at the edge. +- Connecting to external databases via **Hyperdrive** connection pooling. +- Running AI inference at the edge with **Workers AI**. +- Deploying with **Wrangler CLI** and `wrangler.toml` configuration. +- Using **Hono v4** as the web framework on Workers. + +### What's New in 2026 + +#### Cloudflare Workers — Platform Updates +- **D1 GA**: SQLite at the edge — fully production-ready with point-in-time recovery, read replicas, and up to 10GB databases. +- **Queues GA**: Reliable message queues for async processing, dead letter queues, and batch consumption. +- **Hyperdrive GA**: Connection pooling for PostgreSQL, MySQL — eliminates cold connection latency from Workers. +- **Workers AI Stable**: Run LLM inference (Llama 3, Mistral, embedding models) at the edge with zero cold starts. +- **Durable Objects Hibernation**: Cost-effective stateful edge — objects hibernate when idle, wake instantly on request. +- **Workers Static Assets**: Serve static files directly from Workers without separate Pages deployment. +- **Node.js Compatibility Mode**: Import Node.js built-in modules (`node:crypto`, `node:buffer`, `node:streams`) directly in Workers. + +### Core Architecture Patterns + +#### 1. Project Setup (Wrangler + Hono) +```bash +# Create new Workers project with Hono +npm create cloudflare@latest my-app -- --framework=hono +cd my-app + +# wrangler.toml configuration +``` + +```toml +# wrangler.toml +name = "my-app" +compatibility_date = "2026-10-01" +compatibility_flags = ["nodejs_compat_v2"] + +# D1 Database +[[d1_databases]] +binding = "DB" +database_name = "my-app-db" +database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + +# KV Namespace +[[kv_namespaces]] +binding = "CACHE" +id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# R2 Bucket +[[r2_buckets]] +binding = "STORAGE" +bucket_name = "my-app-assets" + +# Queue Producer +[[queues.producers]] +queue = "email-queue" +binding = "EMAIL_QUEUE" + +# Queue Consumer +[[queues.consumers]] +queue = "email-queue" +max_batch_size = 10 +max_batch_timeout = 30 + +# Durable Object +[[durable_objects.bindings]] +name = "RATE_LIMITER" +class_name = "RateLimiter" + +[[migrations]] +tag = "v1" +new_classes = ["RateLimiter"] + +# Hyperdrive (PostgreSQL connection pooling) +[[hyperdrive]] +binding = "HYPERDRIVE" +id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# Workers AI +[ai] +binding = "AI" +``` + +#### 2. Hono Application on Workers +```typescript +import { Hono } from 'hono'; +import { cors } from 'hono/cors'; +import { bearerAuth } from 'hono/bearer-auth'; + +type Bindings = { + DB: D1Database; + CACHE: KVNamespace; + STORAGE: R2Bucket; + EMAIL_QUEUE: Queue; + AI: Ai; + HYPERDRIVE: Hyperdrive; +}; + +const app = new Hono<{ Bindings: Bindings }>(); + +app.use('*', cors()); + +// D1 SQLite query +app.get('/api/products', async (c) => { + const { results } = await c.env.DB.prepare( + 'SELECT id, name, price FROM products WHERE active = 1 ORDER BY created_at DESC LIMIT 50' + ).all(); + return c.json(results); +}); + +// KV cache-aside pattern +app.get('/api/config/:key', async (c) => { + const key = c.req.param('key'); + const cached = await c.env.CACHE.get(key, 'json'); + if (cached) return c.json(cached); + + const { results } = await c.env.DB.prepare( + 'SELECT value FROM config WHERE key = ?' + ).bind(key).all(); + + if (results.length > 0) { + await c.env.CACHE.put(key, JSON.stringify(results[0]), { expirationTtl: 3600 }); + return c.json(results[0]); + } + return c.notFound(); +}); + +// R2 file upload +app.post('/api/upload', async (c) => { + const formData = await c.req.formData(); + const file = formData.get('file') as File; + const key = `uploads/${Date.now()}-${file.name}`; + + await c.env.STORAGE.put(key, file.stream(), { + httpMetadata: { contentType: file.type }, + }); + + return c.json({ key, url: `/files/${key}` }); +}); + +// Queue producer — send async job +app.post('/api/send-email', async (c) => { + const body = await c.req.json(); + await c.env.EMAIL_QUEUE.send({ + to: body.email, + subject: body.subject, + template: body.template, + }); + return c.json({ status: 'queued' }); +}); + +// Workers AI — text generation +app.post('/api/ai/generate', async (c) => { + const { prompt } = await c.req.json(); + const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', { + messages: [{ role: 'user', content: prompt }], + }); + return c.json(response); +}); + +export default app; + +// Queue consumer handler +export default { + ...app, + async queue(batch: MessageBatch, env: Bindings): Promise { + for (const message of batch.messages) { + const { to, subject, template } = message.body as EmailJob; + await sendEmail(to, subject, template); // your email sending logic + message.ack(); + } + }, +}; +``` + +#### 3. D1 Migrations +```bash +# Create migration +wrangler d1 migrations create my-app-db create_products + +# Write SQL migration +# migrations/0001_create_products.sql +``` +```sql +CREATE TABLE products ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), + name TEXT NOT NULL, + price REAL NOT NULL CHECK(price >= 0), + description TEXT DEFAULT '', + active INTEGER DEFAULT 1, + created_at TEXT DEFAULT (datetime('now')), + updated_at TEXT DEFAULT (datetime('now')) +); + +CREATE INDEX idx_products_active ON products(active); +CREATE INDEX idx_products_created ON products(created_at DESC); +``` +```bash +# Apply migration +wrangler d1 migrations apply my-app-db +``` + +#### 4. Durable Objects (Stateful Edge) +```typescript +export class RateLimiter implements DurableObject { + private requests: number[] = []; + private readonly limit = 100; + private readonly windowMs = 60_000; + + constructor(private state: DurableObjectState, private env: Bindings) {} + + async fetch(request: Request): Promise { + const now = Date.now(); + this.requests = this.requests.filter(t => now - t < this.windowMs); + + if (this.requests.length >= this.limit) { + return new Response('Rate limit exceeded', { status: 429 }); + } + + this.requests.push(now); + await this.state.storage.put('requests', this.requests); + + return new Response('OK', { + headers: { + 'X-RateLimit-Remaining': String(this.limit - this.requests.length), + 'X-RateLimit-Limit': String(this.limit), + }, + }); + } +} +``` + +#### 5. Hyperdrive (External Database Connection) +```typescript +import { Client } from 'pg'; + +app.get('/api/users', async (c) => { + const client = new Client({ connectionString: c.env.HYPERDRIVE.connectionString }); + await client.connect(); + + const { rows } = await client.query('SELECT id, email, name FROM users LIMIT 100'); + await client.end(); + + return c.json(rows); +}); +``` + +### Performance Best Practices +1. **Use D1 for read-heavy workloads** — SQLite at edge with automatic read replicas. +2. **KV for hot cache** — Sub-millisecond reads for configuration, feature flags, and session data. +3. **R2 for assets** — Zero egress fees, S3-compatible API. +4. **Queues for async work** — Decouple request handling from background processing. +5. **Hyperdrive for external DBs** — Connection pooling eliminates cold connection latency. +6. **Workers AI for inference** — Run models at edge without managing GPU infrastructure. +7. **Use `waitUntil()`** — For fire-and-forget operations (logging, analytics) after response is sent. + +### Anti-Patterns to Avoid +1. **Storing large blobs in KV** — Use R2 for files >25MB. KV is for small values (<25MB). +2. **Opening new DB connections per request without Hyperdrive** — Cold connections add 50-200ms latency. +3. **Not using prepared statements with D1** — Always use `.prepare().bind()` to prevent SQL injection. +4. **Synchronous heavy computation** — Workers have a CPU time limit (10-30ms for free, 30s for paid). Offload to Queues. +5. **Ignoring `wrangler dev --remote`** — Use remote mode to test D1, R2, and KV with real data. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dengan: `brainstorming`, `zero-to-prod-orchestrator`, `js-backend-expert`, `database-orm-expert`, `api-design-expert`, `authentication-identity-expert`, `wasm-edge-computing-expert`, `ci-cd-devops-architect`, `cloud-hosting-expert`, `session-memory-manager`. + +### Deskripsi +Panduan ahli untuk membangun aplikasi full-stack edge menggunakan ekosistem **Cloudflare Workers**. Mencakup runtime Workers, D1 (SQLite di edge), KV (key-value store), R2 (object storage kompatibel S3), Queues (antrean pesan), Durable Objects (stateful edge), Hyperdrive (connection pooling database), Workers AI (inferensi di edge), dan Wrangler CLI untuk pengembangan dan deployment. + +### Kondisi Pemicu +- Membangun aplikasi edge serverless di Cloudflare Workers. +- Menggunakan **D1** sebagai database SQLite di edge. +- Menyimpan file dengan **R2** (kompatibel S3, tanpa biaya egress). +- Mengimplementasikan **KV** untuk caching key-value terdistribusi. +- Membangun aplikasi stateful dengan **Durable Objects**. +- Menyiapkan **Queues** untuk pemrosesan job async di edge. + +### Pola Arsitektur Inti + +#### 1. Ekosistem Cloudflare Workers +| Layanan | Fungsi | Analogi | +|:---|:---|:---| +| **Workers** | Runtime serverless di edge (V8 isolates) | AWS Lambda@Edge | +| **D1** | Database SQLite di edge | PlanetScale / Turso | +| **KV** | Key-value store terdistribusi | Redis (read-heavy) | +| **R2** | Object storage (S3-compatible) | AWS S3 (tanpa biaya egress) | +| **Queues** | Antrean pesan | AWS SQS / BullMQ | +| **Durable Objects** | State persisten di edge | Stateful actors | +| **Hyperdrive** | Connection pooling ke DB eksternal | PgBouncer di edge | +| **Workers AI** | Inferensi model AI di edge | Replicate / Together AI | + +#### 2. Praktik Terbaik +- Gunakan **D1** untuk workload read-heavy di edge. +- Gunakan **KV** untuk cache panas (konfigurasi, feature flags, sesi). +- Gunakan **R2** untuk aset (tanpa biaya egress, API kompatibel S3). +- Gunakan **Queues** untuk pekerjaan async (email, notifikasi, pemrosesan gambar). +- Gunakan **Hyperdrive** untuk koneksi ke database PostgreSQL/MySQL eksternal. +- Gunakan **`waitUntil()`** untuk operasi fire-and-forget (logging, analitik) setelah respons dikirim. diff --git a/vibes-plug/skills/coderabbit/SKILL.md b/vibes-plug/skills/coderabbit/SKILL.md new file mode 100644 index 000000000..a3ab54d51 --- /dev/null +++ b/vibes-plug/skills/coderabbit/SKILL.md @@ -0,0 +1,200 @@ +--- +name: coderabbit +description: "AI-powered automated code review, PR summarization, and interactive developer feedback / Review kode otomatis berbasis AI, ringkasan PR, dan umpan balik developer interaktif." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# CodeRabbit (2026 Edition — CodeRabbit 2.x) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `anti-slop`, `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Expert guide for configuring and leveraging **CodeRabbit 2.x** — AI-powered automated code review, pull request summarization, and interactive developer feedback. Covers configuration, custom review rules, integration with CI/CD, and agentic review mode. + +### Trigger Conditions +- Setting up CodeRabbit on a GitHub or GitLab repository. +- Configuring custom review rules for your tech stack. +- Using CodeRabbit's agentic mode for deep architectural reviews. +- Integrating CodeRabbit feedback into CI/CD quality gates. +- Writing CodeRabbit-compatible custom instructions in `.coderabbit.yaml`. + +### CodeRabbit 2.x Key Features + +| Feature | Description | +|---|---| +| **PR Summary** | Auto-generates structured PR description with walkthrough | +| **Line-by-line Review** | Inline comments with specific fix suggestions | +| **Agentic Review** | Deep analysis spanning multiple files for architectural issues | +| **Learnable Rules** | Learns from review dismissals and approvals over time | +| **CI Integration** | Blocks PR merge if critical issues found | +| **Chat Mode** | Ask CodeRabbit questions about the PR in review thread | + +### Configuration (`.coderabbit.yaml`) + +```yaml +# .coderabbit.yaml — place in repository root +version: "2" +language: "en-US" +tone_instructions: "Be concise and direct. Prioritize security and performance issues." + +reviews: + auto_review: + enabled: true + drafts: false # Don't review draft PRs + base_branches: ["main", "develop"] + + profile: "chill" # assertive | chill | default + request_changes_workflow: false + high_level_summary: true + commit_message_instructions: "Use Conventional Commits format: feat/fix/chore/docs" + + # Ignore paths from review + path_filters: + - "!**/*.lock" + - "!**/migrations/**" + - "!**/generated/**" + - "!**/__snapshots__/**" + + # Stack-specific review instructions + path_instructions: + - path: "apps/api/**" + instructions: | + - Check for missing input validation (Zod schemas required on all handlers) + - Flag any database queries without proper RLS consideration + - Ensure all async functions have try/catch or error boundaries + - Check for N+1 query patterns (missing .include() or DataLoader usage) + - path: "apps/web/**" + instructions: | + - Check for missing `key` props in .map() renders + - Flag `useEffect` without proper cleanup functions + - Check for missing `alt` attributes on images + - Verify Server Actions are properly validated with Zod + - path: "apps/admin/**" + instructions: | + - All admin routes must verify isSuperAdmin === true + - Flag any direct DB access without service role client + - Check for proper audit logging on destructive operations + + # Custom review rules for the entire codebase + instructions: | + Review with these priorities: + 1. SECURITY: SQL injection, XSS, auth bypass, exposed secrets + 2. CORRECTNESS: Logic bugs, off-by-one errors, type unsafety + 3. PERFORMANCE: N+1 queries, unnecessary re-renders, bundle size + 4. MAINTAINABILITY: Code duplication, naming, SOLID violations + 5. STYLE: Only comment if it's a significant clarity issue + 6. SOVEREIGN ANTI-SLOP: Flag placeholders (// TODO, // ...), mock data in prod, syntax comments, and silent error suppression + +# PR summary format +summary: + auto_title_placeholder: "🤖 AI Title" + description: |- + ## Summary + + + ## Changes + + + ## Testing + + +# Enable chat for interactive Q&A +chat: + auto_reply: true +``` + +### Agentic Review Mode (CodeRabbit 2.x) +CodeRabbit 2.x introduces **agentic review** — deep analysis that can read multiple files, run tools, and understand architectural context: + +``` +# Trigger agentic review in PR comment: +@coderabbitai review + +# Ask specific questions: +@coderabbitai What is the security impact of changes in apps/api/src/routes/users.ts? +@coderabbitai Can you generate a test for the createWorkspace function? +@coderabbitai Is there a N+1 query issue in this PR? +@coderabbitai Summarize the architecture changes in this PR +``` + +### CI/CD Integration (GitHub Actions) +```yaml +# .github/workflows/pr-quality.yml +name: PR Quality Gate + +on: [pull_request] + +jobs: + coderabbit-review: + runs-on: ubuntu-latest + steps: + - name: Wait for CodeRabbit Review + uses: coderabbit-ai/wait-for-review@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + min-approvals: 1 + block-on-critical: true # Block merge if critical issues found +``` + +### CodeRabbit vs Manual Review — Best Practices +- **CodeRabbit first**: Let it run before human reviewers — catches the obvious issues. +- **Human focus**: After CodeRabbit, humans focus on business logic, architecture intent, and product decisions. +- **Teach it**: Dismiss false positives with an explanation — CodeRabbit learns your patterns. +- **Custom instructions**: Invest time in `path_instructions` for your specific stack — dramatically improves relevance. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Deskripsi +Panduan ahli untuk mengonfigurasi dan memanfaatkan **CodeRabbit 2.x** — review kode otomatis bertenaga AI, ringkasan pull request, dan umpan balik developer interaktif. Mencakup konfigurasi, aturan review kustom, integrasi dengan CI/CD, dan mode review agentik. + +### Kondisi Pemicu +- Menyiapkan CodeRabbit di repositori GitHub atau GitLab. +- Mengonfigurasi aturan review kustom untuk tech stack Anda. +- Menggunakan mode agentik CodeRabbit untuk review arsitektur mendalam. +- Mengintegrasikan umpan balik CodeRabbit ke dalam quality gate CI/CD. +- Menulis instruksi kustom yang kompatibel dengan CodeRabbit di `.coderabbit.yaml`. + +### Fitur Utama CodeRabbit 2.x + +| Fitur | Deskripsi | +|---|---| +| **Ringkasan PR** | Membuat deskripsi PR terstruktur otomatis dengan walkthrough | +| **Review Baris per Baris** | Komentar inline dengan saran perbaikan spesifik | +| **Review Agentik** | Analisis mendalam yang mencakup banyak file untuk masalah arsitektur | +| **Aturan yang Dapat Dipelajari** | Belajar dari penolakan dan persetujuan review dari waktu ke waktu | +| **Integrasi CI** | Memblokir merge PR jika masalah kritis ditemukan | +| **Mode Chat** | Tanyakan pertanyaan kepada CodeRabbit di thread review | + +### Konfigurasi (`.coderabbit.yaml`) +Tempatkan `.coderabbit.yaml` di root repositori. Konfigurasi kunci: +- `reviews.profile`: `assertive` (ketat), `chill` (santai), `default`. +- `reviews.path_instructions`: Instruksi review kustom per direktori — sangat berguna untuk menerapkan standar spesifik stack. +- `reviews.path_filters`: Kecualikan file lock, migrasi, kode yang dihasilkan dari review. +- `reviews.instructions`: Aturan global untuk seluruh codebase dengan prioritas eksplisit. + +### Mode Review Agentik (CodeRabbit 2.x) +Mode agentik memungkinkan CodeRabbit membaca banyak file, menjalankan tool, dan memahami konteks arsitektur. Picu dengan `@coderabbitai review` di komentar PR atau ajukan pertanyaan spesifik tentang dampak keamanan, masalah N+1, atau perubahan arsitektur. + +### Integrasi CI/CD (GitHub Actions) +Gunakan action `coderabbit-ai/wait-for-review@v1` untuk menunggu review selesai dan memblokir merge jika masalah kritis ditemukan. + +### CodeRabbit vs Review Manual — Best Practices +- **CodeRabbit dulu**: Biarkan berjalan sebelum reviewer manusia — menangkap masalah yang jelas. +- **Fokus manusia**: Setelah CodeRabbit, manusia fokus pada logika bisnis, niat arsitektur, dan keputusan produk. +- **Ajarkan**: Tolak false positive dengan penjelasan — CodeRabbit belajar pola Anda. +- **Instruksi kustom**: Investasikan waktu di `path_instructions` untuk stack spesifik Anda — meningkatkan relevansi secara dramatis. \ No newline at end of file diff --git a/vibes-plug/skills/compliance-gdpr-privacy-expert/SKILL.md b/vibes-plug/skills/compliance-gdpr-privacy-expert/SKILL.md new file mode 100644 index 000000000..65381fe32 --- /dev/null +++ b/vibes-plug/skills/compliance-gdpr-privacy-expert/SKILL.md @@ -0,0 +1,147 @@ +--- +name: compliance-gdpr-privacy-expert +description: "Expert guide for Data Privacy, GDPR, CCPA, and PDPA compliance. Covers consent management, data retention, privacy-by-design, and audit trails / Panduan kepatuhan Privasi Data, GDPR, dan PDPA." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Data Privacy & Compliance Expert (GDPR, CCPA & UU PDP 2026) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Production engineering guide for regulatory data privacy and compliance across GDPR (EU), CCPA/CPRA (California), and UU PDP No. 27/2022 (Indonesia). Covers technical patterns for PII (Personally Identifiable Information) encryption at rest, cascading data anonymization (Right to be Forgotten while retaining immutable financial ledgers for tax authorities), consent state machines, and automated logger redaction. + +### Trigger Conditions +- Storing customer PII (names, emails, physical addresses, phone numbers, IP addresses, national IDs). +- Implementing compliant cookie consent banners with opt-in tracking scripts. +- Handling data deletion and export requests (*Right to Access* and *Right to be Forgotten*). +- Sanitizing logging pipelines to prevent accidental PII leakage to Datadog, Axiom, or Sentry. + +### Cascading PII Anonymization Routine (TypeScript / PostgreSQL) +Erases personal identity while preserving aggregate transaction integrity for accounting compliance: + +```typescript +// src/services/privacy-compliance.ts +import { db } from '@/lib/db'; +import { sql } from 'drizzle-orm'; +import crypto from 'node:crypto'; + +export async function processRightToBeForgotten(userId: string): Promise { + await db.transaction(async (tx) => { + // 1. Generate irreversible cryptographic pseudo-identifier + const pseudoHash = crypto.createHash('sha256').update(`${userId}-${process.env.PEPPER_SECRET}`).digest('hex').slice(0, 16); + const anonymizedEmail = `deleted-${pseudoHash}@anonymized.internal`; + + // 2. Anonymize user record: scrub sensitive fields + await tx.execute(sql` + UPDATE users + SET + name = 'Anonymized Customer', + email = ${anonymizedEmail}, + phone_number = NULL, + billing_address = NULL, + ip_address = '0.0.0.0', + is_anonymized = TRUE, + anonymized_at = NOW() + WHERE id = ${userId} + `); + + // 3. Scrub profile sessions and third-party provider tokens + await tx.execute(sql`DELETE FROM user_sessions WHERE user_id = ${userId}`); + await tx.execute(sql`DELETE FROM oauth_accounts WHERE user_id = ${userId}`); + + // 4. Log compliance audit trail (immutable record of the erasure action) + await tx.execute(sql` + INSERT INTO privacy_audit_logs (id, action, target_pseudo_id, executed_at) + VALUES (gen_random_uuid(), 'RIGHT_TO_BE_FORGOTTEN_EXECUTED', ${pseudoHash}, NOW()) + `); + }); +} +``` + +### Pino Logger Automated PII Redaction Configuration + +```typescript +// src/lib/logger.ts +import pino from 'pino'; + +export const logger = pino({ + level: process.env.LOG_LEVEL || 'info', + redact: { + paths: [ + 'email', + 'password', + 'token', + 'creditCard', + 'authorization', + '*.email', + '*.password', + 'req.headers.authorization', + 'req.headers.cookie', + ], + censor: '[REDACTED_PII]', + }, +}); +``` + +### The 3 Golden Privacy Invariants +1. **Never Hard Delete Financial Invoices**: Tax laws require preserving transaction records for 5-10 years. Anonymize the customer's PII, but keep the currency amounts, timestamps, and VAT records intact. +2. **Prior Consent for Tracking Scripts**: Do NOT load Google Analytics, Meta Pixel, or third-party cookies until the user has actively opted in. Default to blocked. +3. **Encryption at Rest**: Columns containing sensitive national IDs (KTP/NIK/SSN) or phone numbers must be encrypted using AES-256-GCM before database insertion. + +## Orchestration & Integration +- **`database-orm-expert`**: Maintains schema definitions for encrypted columns and anonymization flags. +- **`logging-error-tracking-expert`**: Enforces strict PII redaction rules across all application logs. +- **`authentication-identity-expert`**: Handles secure account de-registration and session revocation. +- **`saas-billing`**: Preserves financial audit ledgers during customer deletion workflows. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi bersama `database-orm-expert`, `logging-error-tracking-expert`, `authentication-identity-expert`, dan `saas-billing`. + +### Deskripsi +Panduan rekayasa produksi untuk kepatuhan regulasi privasi data global dan nasional, termasuk GDPR (Uni Eropa), CCPA (California), dan UU No. 27 Tahun 2022 tentang Pelindungan Data Pribadi (UU PDP Indonesia). Mencakup enkripsi data pribadi (PII) saat tersimpan (*at rest*), anonimisasi berjenjang untuk pemenuhan hak penghapusan data tanpa merusak pembukuan keuangan perpajakan, manajemen persetujuan cookie (*opt-in*), serta sensor otomatis pada sistem logging. + +### Kondisi Pemicu +- Menyimpan data pribadi pengguna (Nama, NIK/KTP, Email, Nomor Telepon, Alamat, Alamat IP). +- Mengimplementasikan banner persetujuan privasi dan pelacak pihak ketiga (Tracking Pixels). +- Menjalankan permintaan penghapusan akun (*Hak untuk Dilupakan* / *Right to be Forgotten*). +- Mencegah kebocoran data sensitif ke layanan monitor eksternal seperti Datadog, Axiom, atau Sentry. + +### Skema Database Persetujuan Pengguna (UU PDP Compliant) + +```sql +-- Tabel pencatatan riwayat persetujuan (Consent Audit Trail) +CREATE TABLE IF NOT EXISTS user_privacy_consents ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + consent_type VARCHAR(64) NOT NULL, -- 'MARKETING', 'ANALYTICS', 'TERMS_OF_SERVICE' + is_granted BOOLEAN NOT NULL DEFAULT FALSE, + policy_version VARCHAR(16) NOT NULL, -- misal 'v2.1' + ip_address VARCHAR(45) NOT NULL, + granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_user_consents ON user_privacy_consents (user_id, consent_type); +``` + +### 3 Hukum Utama Kepatuhan Privasi Data +1. **Pemisahan Data Transaksi dan Identitas**: UU Perpajakan mewajibkan penyimpanan bukti transaksi selama bertahun-tahun. Ketika pengguna meminta dihapus, anonimkan data identitas mereka (ganti menjadi anonim), namun pertahankan catatan nominal transaksi. +2. **Opt-in Sebelum Pelacakan**: Skrip pelacak analitik dilarang berjalan sebelum pengguna mengklik tombol "Setuju" secara eksplisit. +3. **Sensor Log Otomatis**: Pastikan pustaka logger (Pino/Winston) menyensor kata kunci sensitif (`password`, `email`, `token`) agar tidak tersimpan sebagai teks biasa pada log server. + +## Integrasi Orkestrasi +- **`database-orm-expert`**: Mengatur migrasi skema tabel untuk enkripsi PII dan status anonimisasi. +- **`logging-error-tracking-expert`**: Memastikan tidak ada data pribadi yang bocor ke log error. +- **`authentication-identity-expert`**: Menutup sesi aktif dan mencabut hak akses saat akun dihapus. +- **`saas-billing`**: Menjaga integritas pembukuan pembayaran SaaS sesuai regulasi akuntansi. \ No newline at end of file diff --git a/vibes-plug/skills/composable-mach-architect/SKILL.md b/vibes-plug/skills/composable-mach-architect/SKILL.md new file mode 100644 index 000000000..4dbbe0df8 --- /dev/null +++ b/vibes-plug/skills/composable-mach-architect/SKILL.md @@ -0,0 +1,338 @@ +--- +name: composable-mach-architect +description: "Expert guide for Composable MACH Architecture (Microservices, API-first, Cloud-native, Headless) — dynamic UI composition, federated API mesh, Backend-for-Frontend patterns, plugin/extension architectures, event-driven composition, and composable AI routing / Panduan ahli Arsitektur MACH Komposabel — komposisi UI dinamis, API mesh federasi, pola Backend-for-Frontend, arsitektur plugin/ekstensi, komposisi event-driven, dan routing AI komposabel." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Composable MACH Architecture / Arsitektur MACH Komposabel + +## 1. MACH Alliance Principles / Prinsip-prinsip Aliansi MACH + +### English +MACH architecture is a set of technology principles emphasizing best-of-breed, composable enterprise technology ecosystems. +- **Microservices**: Independently deployable, single-responsibility services. Decoupled and scalable. +- **API-first**: Every capability is exposed via versioned APIs (REST/GraphQL/gRPC). The API is the primary interface, not an afterthought. +- **Cloud-native**: SaaS-first, leveraging auto-scaling, multi-region deployment, and edge computing for resilience and global performance. +- **Headless**: Total separation of the presentation layer (frontend) from the business logic layer (backend). +- **Decision Matrix**: + - *MACH*: Large scale, highly customizable, best-of-breed requirement, multiple frontends. + - *Modular Monolith*: Medium scale, unified team, standard requirements, lower operational complexity. + - *Monolith*: Small scale, rapid MVP, single deployment unit. + +### Indonesian (Bahasa Indonesia) +Arsitektur MACH adalah seperangkat prinsip teknologi yang menekankan ekosistem teknologi enterprise yang komposabel dan best-of-breed. +- **Microservices**: Layanan dengan tanggung jawab tunggal yang dapat di-deploy secara independen. Terdekopel dan dapat diskalakan. +- **API-first**: Setiap kemampuan diekspos melalui API berversi (REST/GraphQL/gRPC). API adalah antarmuka utama, bukan tambahan. +- **Cloud-native**: Mengutamakan SaaS, memanfaatkan auto-scaling, deployment multi-region, dan komputasi edge. +- **Headless**: Pemisahan total lapisan presentasi (frontend) dari lapisan logika bisnis (backend). +- **Matriks Keputusan**: + - *MACH*: Skala besar, sangat dapat dikustomisasi, butuh best-of-breed, banyak frontend. + - *Monolit Modular*: Skala menengah, tim terpadu, standar. + - *Monolit*: Skala kecil, MVP cepat. + +## 2. Dynamic UI Composition / Komposisi UI Dinamis + +### English +Dynamic UI composition allows building runtime-composed dashboards and applications from independent micro-frontends. Use Module Federation v2 (Webpack/Vite) for dynamic remote loading and Server-Driven UI (SDUI) where the backend defines the layout payload. The Shell application acts as the host for remote modules. + +### Indonesian (Bahasa Indonesia) +Komposisi UI dinamis memungkinkan pembuatan dashboard dan aplikasi yang dikomposisi saat runtime dari micro-frontend independen. Gunakan Module Federation v2 untuk pemuatan remote dinamis dan Server-Driven UI di mana backend menentukan payload layout. Aplikasi Shell bertindak sebagai host. + +```javascript +// Vite Module Federation dynamic import setup (vite.config.js - Host App) +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import federation from '@originjs/vite-plugin-federation'; + +export default defineConfig({ + plugins: [ + react(), + federation({ + name: 'host-app', + remotes: { + // Dynamic loading syntax for Vite federation + inventory_app: 'http://localhost:5001/assets/remoteEntry.js', + analytics_app: 'http://localhost:5002/assets/remoteEntry.js' + }, + shared: ['react', 'react-dom'] + }) + ] +}); + +// React Component importing remote dynamically +import React, { Suspense } from 'react'; +const InventoryWidget = React.lazy(() => import('inventory_app/Widget')); + +export const Dashboard = () => ( +
+

Composable Dashboard

+ Loading Widget...
}> + + +
+); +``` + +## 3. Federated API Layer / Lapisan API Federasi + +### English +Apollo Federation v2 allows composing distributed GraphQL schemas into a single unified supergraph. This creates an API mesh for service-to-service communication. Gateways (e.g., Kong, Traefik, Cloudflare) manage routing. Federation differs from schema stitching by pushing composition logic to the subgraphs via directives. + +### Indonesian (Bahasa Indonesia) +Apollo Federation v2 memungkinkan komposisi skema GraphQL terdistribusi menjadi satu supergraph terpadu. Ini menciptakan API mesh. Gateway mengatur routing. Federasi berbeda dari schema stitching dengan mendorong logika komposisi ke subgraph melalui direktif. + +```javascript +// Apollo Federation v2 Subgraph setup (Node.js) +import { ApolloServer } from '@apollo/server'; +import { buildSubgraphSchema } from '@apollo/subgraph'; +import { gql } from 'graphql-tag'; + +const typeDefs = gql` + extend schema + @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@shareable"]) + + type User @key(fields: "id") { + id: ID! + purchaseHistory: [Product] + } + + type Product @key(fields: "upc") { + upc: String! + name: String! @shareable + } +`; + +const resolvers = { + User: { + __resolveReference(userRepresentation) { + return fetchUserById(userRepresentation.id); + } + } +}; + +const server = new ApolloServer({ + schema: buildSubgraphSchema({ typeDefs, resolvers }) +}); +``` + +## 4. Backend-for-Frontend (BFF) Pattern / Pola Backend-for-Frontend + +### English +BFFs aggregate, transform, and optimize data for specific client types (Web, Mobile, Admin). This reduces payload size and over-fetching. Deploy Edge BFFs using Cloudflare Workers or Vercel Edge Middleware for lowest latency. + +### Indonesian (Bahasa Indonesia) +BFF mengagregasi, mentransformasi, dan mengoptimalkan data untuk jenis klien tertentu. Ini mengurangi ukuran payload dan over-fetching. Deploy Edge BFF menggunakan Cloudflare Workers atau Vercel Edge Middleware. + +```javascript +// Edge BFF using Cloudflare Workers aggregating microservices +export default { + async fetch(request, env) { + const url = new URL(request.url); + if (url.pathname === '/api/mobile-dashboard') { + // Parallel requests to internal microservices + const [userResponse, productsResponse] = await Promise.all([ + fetch('https://api.internal.com/users/me', { headers: request.headers }), + fetch('https://api.internal.com/products/featured') + ]); + + const user = await userResponse.json(); + const products = await productsResponse.json(); + + // Transform and subset data for mobile client + const bffResponse = { + greeting: `Hello, ${user.firstName}`, + quickBuy: products.map(p => ({ id: p.id, name: p.name, price: p.price })) // Strip heavy descriptions + }; + + return new Response(JSON.stringify(bffResponse), { + headers: { 'Content-Type': 'application/json' } + }); + } + return new Response('Not Found', { status: 404 }); + } +}; +``` + +## 5. Headless Commerce & CMS Stack / Stack Headless Commerce & CMS + +### English +Leverage platforms like commercetools, Medusa.js, or Saleor for headless commerce. Combine with composable content platforms (Sanity, Contentful). Orchestrate integrations using webhooks, event buses, and CDC to maintain synchronization across best-of-breed tools. + +### Indonesian (Bahasa Indonesia) +Manfaatkan platform seperti commercetools, Medusa.js, atau Saleor. Kombinasikan dengan platform konten (Sanity, Contentful). Orkestrasi integrasi menggunakan webhook, event bus, dan CDC. + +```javascript +// Composable product page fetching from Commerce and CMS +async function getProductPageData(productSlug) { + // 1. Fetch CMS content (Rich text, marketing imagery) from Sanity + const cmsQuery = `*[_type == "product" && slug.current == $slug][0]{ title, marketingCopy, gallery }`; + const cmsPromise = sanityClient.fetch(cmsQuery, { slug: productSlug }); + + // 2. Fetch Commerce data (Pricing, availability) from Medusa.js / commercetools + const commercePromise = fetch(`https://api.commerce.com/store/products?handle=${productSlug}`) + .then(res => res.json()); + + const [cmsData, commerceData] = await Promise.all([cmsPromise, commercePromise]); + const product = commerceData.products[0]; + + // 3. Compose response + return { + id: product.id, + title: cmsData.title || product.title, + description: cmsData.marketingCopy, + images: cmsData.gallery, + price: product.variants[0].prices[0].amount, + inStock: product.variants[0].inventory_quantity > 0 + }; +} +``` + +## 6. Plugin & Extension Architecture / Arsitektur Plugin & Ekstensi + +### English +Design extensible systems using plugin registries. The lifecycle involves discover → load → initialize → execute → teardown. Secure execution by sandboxing (iframe or Web Worker). Provide hook/event systems for integration points. + +### Indonesian (Bahasa Indonesia) +Desain sistem ekstensibel menggunakan registri plugin. Siklus hidup: temukan → muat → inisialisasi → eksekusi → teardown. Amankan eksekusi dengan sandboxing. Sediakan sistem hook/event. + +```typescript +// Plugin registry with lifecycle management +interface Plugin { + name: string; + init: (context: PluginContext) => Promise; + execute: (payload: any) => Promise; + teardown: () => Promise; +} + +class PluginRegistry { + private plugins: Map = new Map(); + + async register(plugin: Plugin) { + if (this.plugins.has(plugin.name)) throw new Error("Plugin exists"); + + // Sandbox or pass restricted context + const context = { logger: console, api: restrictedApiObject }; + await plugin.init(context); + + this.plugins.set(plugin.name, plugin); + } + + async runHook(hookName: string, payload: any) { + const results = []; + for (const plugin of this.plugins.values()) { + // Execute plugins in parallel or sequentially based on hook semantics + results.push(await plugin.execute({ hook: hookName, data: payload })); + } + return results; + } +} +``` + +## 7. Event-Driven Composition / Komposisi Event-Driven + +### English +Achieve loose coupling via async event buses (Redis Streams, Kafka). Use Change Data Capture (CDC) like Debezium for real-time data sync. Understand choreography (decentralized) vs orchestration (centralized) and employ eventual consistency and saga patterns for distributed transactions. + +### Indonesian (Bahasa Indonesia) +Capai loose coupling melalui event bus asinkron. Gunakan CDC (Debezium) untuk sinkronisasi data real-time. Pahami koreografi vs orkestrasi dan terapkan eventual consistency serta saga pattern untuk transaksi terdistribusi. + +```javascript +// Event-driven service composition with Redis Streams (Node.js) +import { createClient } from 'redis'; + +const redis = createClient(); +await redis.connect(); + +// Service A: Producer (e.g., Order Service) +async function placeOrder(orderData) { + const orderId = generateId(); + // Save to local DB first... + + // Emit event to stream + await redis.xAdd('events:orders', '*', { + eventType: 'OrderCreated', + orderId: orderId, + payload: JSON.stringify(orderData) + }); +} + +// Service B: Consumer (e.g., Inventory Service) +async function listenForOrders() { + let lastId = '$'; // Listen for new messages + while (true) { + const response = await redis.xRead( + { key: 'events:orders', id: lastId }, + { BLOCK: 5000, COUNT: 1 } + ); + if (response) { + const stream = response[0]; + const message = stream.messages[0]; + lastId = message.id; + + const event = message.message; + if (event.eventType === 'OrderCreated') { + const order = JSON.parse(event.payload); + // Reserve inventory based on order... + } + } + } +} +``` + +## 8. Composable AI Routing / Routing AI Komposabel + +### English +Implement dynamic AI model routing based on request context (complexity, cost, latency). Chain specialized models for complex tasks. Build fallback chains (Primary → Secondary → Local SLM) for resilience. Manage model rollouts with feature flags. + +### Indonesian (Bahasa Indonesia) +Terapkan routing model AI dinamis berdasarkan konteks permintaan (kompleksitas, biaya, latensi). Rangkai model spesialis untuk tugas kompleks. Buat rantai fallback (Primer → Sekunder → SLM Lokal). Kelola peluncuran model dengan feature flag. + +```javascript +// Dynamic AI model router with cost and latency optimization +async function routePrompt(prompt, context) { + const complexityScore = evaluateComplexity(prompt); // Fast heuristic check + + if (complexityScore < 0.3) { + // Simple task: Route to fast, cheap model (e.g., Gemini 3.8 Flash / Claude 3.5 Haiku / GPT-4o-mini) + return await callModel('fast-cheap-model', prompt); + } + + if (context.requiresReasoning) { + // Complex reasoning: Route to advanced model (e.g., Gemini 4 Pro / Claude 3.7 Sonnet / Claude 5.1 / GPT-5) + try { + return await callModel('advanced-reasoning-model', prompt); + } catch (error) { + // Fallback chain implementation + console.warn("Primary model failed, falling back to secondary..."); + return await callModel('secondary-fallback-model', prompt); + } + } + + // Feature-flag controlled routing for A/B testing new models + if (featureFlags.get('use_experimental_model_v2')) { + return await callModel('experimental-model', prompt); + } + + return await callModel('default-balanced-model', prompt); +} +``` + +## 9. Orchestration & Integration / Orkestrasi & Integrasi + +### Connected Skills / Skill Terhubung: +Integrate this architectural pattern with the following skills: +- `micro-frontend-architect` +- `event-driven-architect` +- `api-design-expert` +- `headless-cms-expert` +- `ecommerce-expert` +- `saas-architect` +- `api-gateway-proxy-expert` +- `cloud-hosting-expert` +- `brainstorming` +- `zero-to-prod-orchestrator` + +## Orchestration & Integration +- Connects to `zero-to-prod-orchestrator` +- Connects to `brainstorming` diff --git a/vibes-plug/skills/context-window-engineer/SKILL.md b/vibes-plug/skills/context-window-engineer/SKILL.md new file mode 100644 index 000000000..84b255fb4 --- /dev/null +++ b/vibes-plug/skills/context-window-engineer/SKILL.md @@ -0,0 +1,302 @@ +--- +name: context-window-engineer +description: "Expert guide for engineering and optimizing ultra-large context windows (2M+ tokens) across Gemini 4 Pro, Claude 5.5, and GPT Astra 6 — context partitioning, retrieval-augmented context injection, sliding window strategies, and cost-aware token budgeting / Panduan ahli rekayasa dan optimasi context window ultra-besar (2M+ token) di Gemini 4 Pro, Claude 5.5, dan GPT Astra 6 — partisi konteks, injeksi konteks berbasis retrieval, strategi sliding window, dan penganggaran token sadar-biaya." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# context-window-engineer — vibes-plug Skill + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with `kv-cache-prefix-optimizer`, `llm-finops-router`, `frontier-ai-models-expert`, `gemini-agent-booster`, `ai-llm-integration-expert`, `vercel-ai-sdk-expert`, `adaptive-model-cascade`, `session-memory-manager`, and `deep-research-analyst` to ensure context windows are utilized efficiently across all AI-powered workflows. + +### Description +Production guide for engineering, partitioning, and optimizing ultra-large context windows (128k → 2M+ tokens) across frontier models. Prevents the most common failure mode in 2026 AI applications: dumping raw data into context without structure, causing degraded recall, wasted tokens, and hallucination amplification in the "lost in the middle" zone. + +### Trigger Conditions +Activate this skill when: +- Building AI agents or applications that consume >50k tokens of context per request. +- Experiencing degraded model recall, "lost in the middle" failures, or hallucinations in long-context scenarios. +- Architecting Retrieval-Augmented Generation (RAG) systems that need to decide between retrieval vs. long-context stuffing. +- Optimizing token costs for applications with large system prompts, tool registries, or codebase context maps. +- Designing multi-turn agentic loops where context accumulates across dozens of turns. + +--- + +### Core Concepts & Patterns + +#### 1. Context Window Capacity Map (October 2026) + +| Model | Max Context | Effective Recall Zone | Cost per 1M Input Tokens | Cache Discount | +| :--- | :--- | :--- | :--- | :--- | +| **Gemini 4 Pro** | 2,097,152 | ~1.8M (reliable) | $1.25 | 75% (explicit cache) | +| **Gemini 4 Flash** | 1,048,576 | ~900k | $0.075 | 75% | +| **Claude 5.5 Opus** | 500,000 | ~450k | $15.00 | 90% (prompt cache) | +| **Claude 5.5 Sonnet** | 200,000 | ~180k | $3.00 | 90% | +| **GPT Astra 6** | 256,000 | ~220k | $5.00 | 50% (prefix cache) | + +#### 2. The Context Partitioning Architecture + +Never treat the context window as a flat buffer. Partition it into semantically meaningful zones with explicit priority ordering: + +``` +┌──────────────────────────────────────────────────────┐ +│ ZONE 1: IMMUTABLE SYSTEM DIRECTIVES (1-3%) │ +│ System prompt, behavioral guardrails, output format │ +│ ► NEVER changes mid-session │ +├──────────────────────────────────────────────────────┤ +│ ZONE 2: STATIC REFERENCE CONTEXT (10-40%) │ +│ Codebase schemas, API specs, tool definitions, │ +│ architectural docs, PRD excerpts │ +│ ► Changes only between sessions │ +├──────────────────────────────────────────────────────┤ +│ ZONE 3: RETRIEVED CONTEXT (20-50%) │ +│ RAG chunks, relevant code files, search results, │ +│ documentation snippets │ +│ ► Dynamically injected per query via retrieval │ +├──────────────────────────────────────────────────────┤ +│ ZONE 4: CONVERSATION HISTORY (10-30%) │ +│ Prior turns, summarized older context, │ +│ tool call results │ +│ ► Sliding window with intelligent summarization │ +├──────────────────────────────────────────────────────┤ +│ ZONE 5: ACTIVE QUERY + SCRATCHPAD (1-5%) │ +│ Current user message, chain-of-thought workspace │ +│ ► Most volatile, always at the tail │ +└──────────────────────────────────────────────────────┘ +``` + +#### 3. Token Budget Allocation (TypeScript Implementation) + +```typescript +export interface ContextBudget { + totalCapacity: number; + zones: { + systemDirectives: { maxTokens: number; priority: 1 }; + staticReference: { maxTokens: number; priority: 2 }; + retrievedContext: { maxTokens: number; priority: 3 }; + conversationHistory: { maxTokens: number; priority: 4 }; + activeQuery: { maxTokens: number; priority: 5 }; + }; +} + +export function createBudget(modelCapacity: number): ContextBudget { + return { + totalCapacity: modelCapacity, + zones: { + systemDirectives: { maxTokens: Math.floor(modelCapacity * 0.02), priority: 1 }, + staticReference: { maxTokens: Math.floor(modelCapacity * 0.30), priority: 2 }, + retrievedContext: { maxTokens: Math.floor(modelCapacity * 0.40), priority: 3 }, + conversationHistory: { maxTokens: Math.floor(modelCapacity * 0.25), priority: 4 }, + activeQuery: { maxTokens: Math.floor(modelCapacity * 0.03), priority: 5 }, + }, + }; +} + +export function enforceTokenBudget( + zoneContents: Map, + budget: ContextBudget, + tokenCounter: (text: string) => number +): Map { + const result = new Map(); + const zones = Object.entries(budget.zones).sort(([, a], [, b]) => a.priority - b.priority); + + for (const [zoneName, { maxTokens }] of zones) { + const content = zoneContents.get(zoneName) ?? ''; + const tokenCount = tokenCounter(content); + + if (tokenCount <= maxTokens) { + result.set(zoneName, content); + } else { + result.set(zoneName, truncateToTokenLimit(content, maxTokens, tokenCounter)); + } + } + + return result; +} + +function truncateToTokenLimit( + content: string, + maxTokens: number, + tokenCounter: (text: string) => number +): string { + const lines = content.split('\n'); + let accumulated = ''; + for (const line of lines) { + const candidate = accumulated ? `${accumulated}\n${line}` : line; + if (tokenCounter(candidate) > maxTokens) break; + accumulated = candidate; + } + return accumulated; +} +``` + +#### 4. "Lost in the Middle" Mitigation + +Frontier models exhibit degraded recall for information positioned in the middle 40-60% of the context. Mitigate with: + +1. **Needle Placement**: Place the most critical context at the very beginning (Zone 1-2) and very end (Zone 5) of the prompt. +2. **Structural Anchors**: Use explicit section headers (`=== CRITICAL: Database Schema ===`) to create attention anchors. +3. **Redundant Summarization**: For critical facts, include both the raw data AND a summary at the top. +4. **Chunked Retrieval**: Break large documents into semantically coherent chunks (512-1024 tokens each) rather than inserting monolithic blocks. + +#### 5. RAG vs. Long-Context Decision Matrix + +| Criterion | Use RAG (Retrieve & Inject) | Use Long-Context Stuffing | +| :--- | :--- | :--- | +| **Corpus size** | >10M tokens total corpus | <2M tokens total corpus | +| **Query specificity** | Narrow, focused queries | Broad, synthesis-oriented queries | +| **Freshness** | Corpus updates frequently | Corpus is static per session | +| **Cost sensitivity** | High (pay only for retrieved chunks) | Lower priority (amortized via cache) | +| **Recall requirement** | Precision-critical (top-k retrieval) | Recall-critical (need full picture) | + +#### 6. Sliding Window Strategy for Multi-Turn Agents + +```typescript +export interface TurnSummary { + turnIndex: number; + role: 'user' | 'assistant'; + summary: string; + tokenCount: number; + fullContent?: string; +} + +export function buildSlidingWindow( + allTurns: TurnSummary[], + maxHistoryTokens: number, + recentTurnsToKeepFull: number = 4 +): string[] { + const recentFull = allTurns.slice(-recentTurnsToKeepFull); + const older = allTurns.slice(0, -recentTurnsToKeepFull); + + let budget = maxHistoryTokens; + const output: string[] = []; + + for (const turn of recentFull) { + const content = turn.fullContent ?? turn.summary; + budget -= turn.tokenCount; + output.push(content); + } + + if (budget > 0 && older.length > 0) { + const olderSummaries = older.map((t) => `[Turn ${t.turnIndex}] ${t.summary}`); + output.unshift(`=== SUMMARIZED EARLIER CONTEXT ===\n${olderSummaries.join('\n')}`); + } + + return output; +} +``` + +--- + +### Best Practices + +1. **Always Count Tokens Before Injection**: Use `tiktoken` (OpenAI), `@anthropic-ai/tokenizer`, or Gemini's `countTokens()` API to measure actual token counts. +2. **Cache-Align Zone Boundaries**: Coordinate with `kv-cache-prefix-optimizer` so static zones (1-2) align with KV-cache prefix boundaries. +3. **Measure Recall Quality**: Instrument needle-in-haystack tests at various context depths to validate your model's effective recall zone. +4. **Degrade Gracefully**: When context exceeds budget, drop Zone 4 (older history) first, then Zone 3 (retrieved context), never Zone 1-2. +5. **Monitor Token Spend Per Zone**: Log per-zone token consumption to `data-telemetry-expert` dashboards to identify context bloat early. + +--- + +### Common Pitfalls to Avoid + +| Anti-Pattern | Consequence | Remedy | +| :--- | :--- | :--- | +| Dumping entire codebase into context | Exceeds effective recall zone, hallucination spikes | Use targeted retrieval + file relevance scoring | +| No zone partitioning | Critical instructions get "lost in the middle" | Implement explicit zone headers and priority ordering | +| Ignoring token counting | Silent context truncation by model API | Pre-count and enforce budgets client-side | +| Keeping full conversation history forever | Context fills up after 10-15 turns | Implement sliding window with summarization | + +--- + +### Integration with Other Skills (MANDATORY) + +- `kv-cache-prefix-optimizer` — Ensure Zone 1-2 boundaries align with cache-pinned prefixes for maximum cache hit rates. +- `llm-finops-router` — Feed per-zone token costs to the FinOps dashboard for budget optimization. +- `frontier-ai-models-expert` — Reference model-specific context window capacities and recall characteristics. +- `adaptive-model-cascade` — Route to larger-context models only when context exceeds smaller model capacity. +- `gemini-agent-booster` — Leverage Gemini 4 Pro's native 2M context caching for zero-latency re-reads. +- `session-memory-manager` — Persist context zone snapshots across sessions for seamless handoff. + +### Referenced By Orchestrators (MANDATORY) + +- `brainstorming` — Added to "AI & LLM Integration" and "Frontier AI & Simulation" matrix rows. +- `zero-to-prod-orchestrator` — Integrated in Phase 4 (Backend APIs, Microservices & AI Agents). + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi dengan `kv-cache-prefix-optimizer`, `llm-finops-router`, `frontier-ai-models-expert`, `gemini-agent-booster`, `ai-llm-integration-expert`, `vercel-ai-sdk-expert`, `adaptive-model-cascade`, `session-memory-manager`, dan `deep-research-analyst` untuk memastikan context window dimanfaatkan secara efisien di seluruh alur kerja berbasis AI. + +### Deskripsi +Panduan produksi untuk merekayasa, mempartisi, dan mengoptimalkan context window ultra-besar (128k → 2M+ token) pada model frontier. Mencegah kegagalan paling umum di aplikasi AI 2026: memasukkan data mentah ke konteks tanpa struktur, yang menyebabkan recall menurun, token terbuang, dan amplifikasi halusinasi di zona "lost in the middle". + +### Kondisi Pemicu +Aktifkan skill ini ketika: +- Membangun agen atau aplikasi AI yang mengonsumsi >50k token konteks per permintaan. +- Mengalami penurunan recall model, kegagalan "lost in the middle", atau halusinasi pada skenario konteks panjang. +- Merancang sistem RAG yang perlu memutuskan antara retrieval vs. long-context stuffing. +- Mengoptimalkan biaya token untuk aplikasi dengan system prompt besar, registri tool, atau peta konteks codebase. + +--- + +### Konsep Inti & Pola Praktik + +#### 1. Arsitektur Partisi Konteks +Jangan perlakukan context window sebagai buffer datar. Partisi menjadi zona bermakna secara semantik: +- **Zona 1 (1-3%)**: Direktif sistem yang tidak berubah — prompt perilaku, format output. +- **Zona 2 (10-40%)**: Referensi statis — skema codebase, spesifikasi API, definisi tool. +- **Zona 3 (20-50%)**: Konteks yang di-retrieve — chunk RAG, file kode relevan, cuplikan dokumentasi. +- **Zona 4 (10-30%)**: Riwayat percakapan — giliran sebelumnya, ringkasan konteks lama. +- **Zona 5 (1-5%)**: Query aktif — pesan pengguna saat ini, ruang kerja chain-of-thought. + +#### 2. Mitigasi "Lost in the Middle" +Model frontier menunjukkan recall yang menurun untuk informasi di tengah-tengah konteks. Mitigasi dengan penempatan informasi kritis di awal dan akhir, jangkar struktural, ringkasan redundan, dan retrieval berbasis chunk. + +#### 3. Keputusan RAG vs. Long-Context +Gunakan RAG untuk korpus >10M token dengan query spesifik dan sensitivitas biaya tinggi. Gunakan long-context stuffing untuk korpus <2M token dengan kebutuhan sintesis luas dan corpus statis per sesi. + +--- + +### Praktik Terbaik + +1. **Selalu Hitung Token Sebelum Injeksi**: Gunakan API `countTokens()` untuk mengukur jumlah token aktual. +2. **Selaraskan Batas Zona dengan Cache**: Koordinasikan dengan `kv-cache-prefix-optimizer` agar zona statis selaras dengan batas prefix KV-cache. +3. **Ukur Kualitas Recall**: Instrumenkan tes needle-in-haystack pada berbagai kedalaman konteks. +4. **Degradasi Anggun**: Saat konteks melebihi anggaran, buang Zona 4 (riwayat lama) lebih dulu, bukan Zona 1-2. + +--- + +### Jebakan Umum yang Harus Dihindari + +| Praktik Buruk | Dampak | Solusi | +| :--- | :--- | :--- | +| Memasukkan seluruh codebase ke konteks | Melebihi zona recall efektif, halusinasi melonjak | Gunakan retrieval terarah + skor relevansi file | +| Tanpa partisi zona | Instruksi kritis "hilang di tengah" | Implementasikan header zona eksplisit | +| Mengabaikan penghitungan token | Pemotongan konteks diam-diam oleh API model | Hitung dan terapkan anggaran dari sisi klien | +| Menyimpan seluruh riwayat percakapan | Konteks penuh setelah 10-15 giliran | Terapkan sliding window dengan ringkasan | + +--- + +### Integrasi dengan Skill Lain (WAJIB) + +- `kv-cache-prefix-optimizer` — Pastikan batas Zona 1-2 selaras dengan prefix cache untuk cache hit rate maksimal. +- `llm-finops-router` — Kirim biaya token per-zona ke dashboard FinOps untuk optimasi anggaran. +- `frontier-ai-models-expert` — Referensi kapasitas context window dan karakteristik recall spesifik model. +- `adaptive-model-cascade` — Rutekan ke model berkonteks lebih besar hanya ketika konteks melebihi kapasitas model kecil. + +### Direferensikan oleh Orchestrator (WAJIB) + +- `brainstorming` — Ditambahkan ke baris "Integrasi AI & LLM" dan "Frontier AI & Simulation" pada Matriks Orkestrasi. +- `zero-to-prod-orchestrator` — Diintegrasikan di Fase 4 (Backend APIs, Microservices & AI Agents). diff --git a/vibes-plug/skills/cron-scheduler-expert/SKILL.md b/vibes-plug/skills/cron-scheduler-expert/SKILL.md new file mode 100644 index 000000000..7a1ad126a --- /dev/null +++ b/vibes-plug/skills/cron-scheduler-expert/SKILL.md @@ -0,0 +1,403 @@ +--- +name: cron-scheduler-expert +description: "Expert guide for scheduled tasks, cron jobs, recurring background work (Vercel Cron, Cloudflare Workers Cron, Inngest, node-cron), and distributed scheduling / Panduan ahli untuk tugas terjadwal, cron job, pekerjaan latar belakang berulang, dan penjadwalan terdistribusi." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Cron & Scheduler Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Production-grade guide for implementing scheduled tasks, cron jobs, and recurring background work in modern web applications. Covers **Vercel Cron Jobs**, **Cloudflare Workers Cron Triggers**, **Inngest scheduled functions**, **node-cron**, **BullMQ repeatable jobs**, **distributed cron locking** (Redis-based), **timezone-aware scheduling**, and common use cases (cleanup jobs, report generation, health checks, subscription renewals). + +### Trigger Conditions +Activate this skill when: +- Setting up scheduled/recurring tasks (daily reports, cleanup, health checks). +- Configuring Vercel Cron Jobs or Cloudflare Workers Cron Triggers. +- Implementing subscription renewal checks or billing cycle jobs. +- Building data aggregation or ETL pipelines on a schedule. +- Needing distributed cron locking to prevent duplicate execution. +- Scheduling email digests or notification batches. + +--- + +### Platform Selection Guide + +| Platform | Best For | Max Frequency | Invocation Model | +|---|---|---|---| +| **Vercel Cron** | Vercel-hosted Next.js apps | 1/min (Pro), 1/day (Hobby) | HTTP endpoint trigger | +| **Cloudflare Workers Cron** | Edge-first apps | 1/min | Worker script trigger | +| **Inngest** | Complex workflows, fan-out | Any (event-driven) | Serverless function | +| **BullMQ Repeatable** | Self-hosted, Redis-backed | Any | Worker process | +| **node-cron** | Simple Node.js servers | Any | In-process | +| **Trigger.dev v3** | Durable scheduled tasks | Any | Serverless function | + +**Recommendation**: Use **Vercel Cron** for Next.js apps on Vercel. Use **Inngest** for complex multi-step scheduled workflows. Use **BullMQ repeatable jobs** for self-hosted environments. + +--- + +### 1. Vercel Cron Jobs + +```json +// vercel.json +{ + "crons": [ + { + "path": "/api/cron/daily-cleanup", + "schedule": "0 3 * * *" + }, + { + "path": "/api/cron/hourly-health-check", + "schedule": "0 * * * *" + }, + { + "path": "/api/cron/weekly-report", + "schedule": "0 9 * * 1" + } + ] +} +``` + +```typescript +// app/api/cron/daily-cleanup/route.ts +import { NextResponse } from 'next/server'; + +export async function GET(request: Request) { + // Verify the request is from Vercel Cron (not public) + const authHeader = request.headers.get('authorization'); + if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + try { + // Cleanup expired sessions + const deletedSessions = await db.delete(sessions) + .where(lt(sessions.expiresAt, new Date())); + + // Cleanup orphaned uploads (older than 24h, not linked to any record) + const deletedUploads = await db.delete(uploads) + .where(and( + isNull(uploads.linkedRecordId), + lt(uploads.createdAt, new Date(Date.now() - 86400000)), + )); + + return NextResponse.json({ + ok: true, + cleaned: { sessions: deletedSessions.rowCount, uploads: deletedUploads.rowCount }, + }); + } catch (error) { + console.error('Daily cleanup failed:', error); + return NextResponse.json({ ok: false, error: 'Cleanup failed' }, { status: 500 }); + } +} + +export const runtime = 'nodejs'; +export const maxDuration = 60; // Allow up to 60s for cleanup +``` + +--- + +### 2. Inngest Scheduled Functions + +```typescript +// inngest/functions/weekly-report.ts +import { inngest } from '@/lib/inngest'; + +export const weeklyReportJob = inngest.createFunction( + { + id: 'weekly-usage-report', + name: 'Generate Weekly Usage Report', + }, + { cron: 'TZ=Asia/Jakarta 0 9 * * 1' }, // Every Monday 9 AM WIB + async ({ step }) => { + // Step 1: Gather data + const metrics = await step.run('gather-metrics', async () => { + return await db.query.usageMetrics.findMany({ + where: gte(usageMetrics.createdAt, subDays(new Date(), 7)), + }); + }); + + // Step 2: Generate report + const report = await step.run('generate-report', async () => { + return generateWeeklyReport(metrics); + }); + + // Step 3: Send to admins + await step.run('send-report', async () => { + const admins = await db.query.users.findMany({ + where: eq(users.role, 'admin'), + }); + for (const admin of admins) { + await emailQueue.add('weekly-report', { to: admin.email, report }); + } + }); + + return { sent: true, reportId: report.id }; + }, +); +``` + +--- + +### 3. BullMQ Repeatable Jobs + +```typescript +// queues/scheduled-jobs.ts +import { Queue, Worker } from 'bullmq'; + +const scheduledQueue = new Queue('scheduled', { + connection: { host: process.env.REDIS_HOST }, +}); + +// Add repeatable jobs on startup +export async function registerScheduledJobs() { + // Daily cleanup at 3 AM + await scheduledQueue.add('daily-cleanup', {}, { + repeat: { pattern: '0 3 * * *', tz: 'Asia/Jakarta' }, + jobId: 'daily-cleanup', // Prevent duplicates on restart + }); + + // Every 5 minutes: health check + await scheduledQueue.add('health-check', {}, { + repeat: { every: 5 * 60 * 1000 }, // 5 minutes in ms + jobId: 'health-check', + }); + + // Monthly: subscription renewal check (1st of each month at midnight) + await scheduledQueue.add('subscription-renewal', {}, { + repeat: { pattern: '0 0 1 * *', tz: 'Asia/Jakarta' }, + jobId: 'subscription-renewal', + }); +} + +// Worker +const worker = new Worker('scheduled', async (job) => { + switch (job.name) { + case 'daily-cleanup': + await performDailyCleanup(); + break; + case 'health-check': + await performHealthCheck(); + break; + case 'subscription-renewal': + await checkSubscriptionRenewals(); + break; + } +}, { connection: { host: process.env.REDIS_HOST } }); +``` + +--- + +### 4. Distributed Cron Locking (Redis) + +```typescript +// lib/cron-lock.ts +import { Redis } from 'ioredis'; + +const redis = new Redis(process.env.REDIS_URL!); + +/** + * Acquire a distributed lock to prevent duplicate cron execution + * across multiple server instances. + */ +export async function acquireCronLock( + jobName: string, + ttlSeconds: number = 300, +): Promise { + const lockKey = `cron-lock:${jobName}`; + // SET NX (only if not exists) with TTL + const result = await redis.set(lockKey, Date.now().toString(), 'EX', ttlSeconds, 'NX'); + return result === 'OK'; +} + +export async function releaseCronLock(jobName: string): Promise { + await redis.del(`cron-lock:${jobName}`); +} + +// Usage in cron handler +export async function GET(request: Request) { + const locked = await acquireCronLock('daily-cleanup', 300); + if (!locked) { + return Response.json({ skipped: true, reason: 'Already running on another instance' }); + } + + try { + await performDailyCleanup(); + return Response.json({ ok: true }); + } finally { + await releaseCronLock('daily-cleanup'); + } +} +``` + +--- + +### Common Cron Patterns + +| Schedule | Cron Expression | Description | +|---|---|---| +| Every minute | `* * * * *` | Health checks, queue monitoring | +| Every 5 minutes | `*/5 * * * *` | Cache warming, metric aggregation | +| Every hour | `0 * * * *` | Data sync, report generation | +| Daily at 3 AM | `0 3 * * *` | Cleanup, backups | +| Weekly Monday 9 AM | `0 9 * * 1` | Weekly reports | +| Monthly 1st at midnight | `0 0 1 * *` | Billing cycles, subscription renewals | +| Weekdays at 8 AM | `0 8 * * 1-5` | Business notifications | + +--- + +### Common Pitfalls to Avoid + +| Anti-Pattern | Problem | Correct Approach | +|---|---|---| +| No distributed locking | Duplicate execution across instances | Use Redis-based NX lock | +| Long-running cron without timeout | Resource exhaustion, overlapping runs | Set `maxDuration` and use lock TTL | +| No monitoring of cron failures | Silent failures go unnoticed | Log results, alert on failures | +| Hardcoded timezone | Jobs run at wrong time after DST | Always use explicit `tz` parameter | +| Cron job does too much work | Timeout, partial completion | Break into smaller steps (Inngest/Temporal) | + +--- + +### Integration with Other Skills + +- `async-queue-temporal-expert` — BullMQ repeatable jobs, Inngest scheduled functions +- `cloud-hosting-expert` — Vercel Cron, Cloudflare Workers Cron configuration +- `saas-billing` — Subscription renewal checks, billing cycle jobs +- `email-notification-expert` — Scheduled email digests, daily summaries +- `data-telemetry-expert` — Scheduled metric aggregation and reporting +- `logging-error-tracking-expert` — Cron job failure monitoring + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. +- `async-queue-temporal-expert` — BullMQ repeatable jobs dan alur kerja Inngest. +- `cloud-hosting-expert` — Konfigurasi Vercel Cron dan Cloudflare Workers Cron. +- `saas-billing` — Pemeriksaan siklus perpanjangan invoice langganan berkala. +- `email-notification-expert` — Pengiriman digest email harian/mingguan terjadwal. + +### Deskripsi +Panduan tingkat produksi untuk mengimplementasikan tugas terjadwal, cron job, dan pekerjaan latar belakang berulang di aplikasi web modern. Mencakup **Vercel Cron Jobs**, **Cloudflare Workers Cron Triggers**, **Inngest scheduled functions**, **BullMQ repeatable jobs**, **distributed cron locking** (berbasis Redis), **penjadwalan sadar zona waktu**, dan kasus penggunaan umum (pembersihan data, pembuatan laporan, health check, perpanjangan langganan). + +### Kondisi Pemicu +Aktifkan skill ini ketika: +- Menyiapkan tugas terjadwal/berulang (laporan harian, pembersihan, health check). +- Mengonfigurasi Vercel Cron Jobs atau Cloudflare Workers Cron Triggers. +- Mengimplementasikan pemeriksaan perpanjangan langganan atau siklus billing. +- Membangun pipeline agregasi data atau ETL pada jadwal tertentu. +- Membutuhkan penguncian cron terdistribusi untuk mencegah eksekusi duplikat. + +--- + +### Panduan Pemilihan Solusi Cron + +| Platform | Pilihan Terbaik Untuk | Frekuensi Maksimum | Model Pemicu | +|---|---|---|---| +| **Vercel Cron** | Aplikasi Next.js di Vercel | 1x/menit (Pro), 1x/hari (Hobby) | Pemicu HTTP endpoint internal | +| **Cloudflare Workers Cron** | Arsitektur Edge murni | 1x/menit | Scheduled event script worker | +| **Inngest** | Alur bertahap (*step-functions*) multi-langkah | Fleksibel & event-driven | Serverless durable execution | +| **BullMQ Repeatable** | Aplikasi mandiri berbasis Redis | Fleksibel | Antrean worker Node.js terpisah | + +--- + +### Implementasi Pola Kunci (TypeScript) + +#### 1. Vercel Cron dengan Proteksi Autentikasi Rahasia (`CRON_SECRET`) +```json +// vercel.json +{ + "crons": [ + { + "path": "/api/cron/pembersihan-harian", + "schedule": "0 3 * * *" + } + ] +} +``` + +```typescript +// app/api/cron/pembersihan-harian/route.ts +import { NextResponse } from 'next/server'; + +export async function GET(request: Request) { + // Verifikasi permintaan resmi berasal dari scheduler Vercel + const authHeader = request.headers.get('authorization'); + if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { + return NextResponse.json({ error: 'Tidak memiliki otorisasi' }, { status: 401 }); + } + + try { + // Jalankan operasi pembersihan sesi kadaluarsa + const hasil = await db.delete(sesiPengguna) + .where(lt(sesiPengguna.kadaluarsaPada, new Date())); + + return NextResponse.json({ ok: true, terhapus: hasil.rowCount }); + } catch (error) { + console.error('Pembersihan cron gagal:', error); + return NextResponse.json({ ok: false, error: 'Gagal membersihkan data' }, { status: 500 }); + } +} + +export const runtime = 'nodejs'; +export const maxDuration = 60; // Izinkan eksekusi hingga 60 detik +``` + +#### 2. Inngest Scheduled Functions Sadar Zona Waktu (`TZ=Asia/Jakarta`) +```typescript +import { inngest } from '@/lib/inngest'; + +export const jobLaporanMingguan = inngest.createFunction( + { id: 'laporan-mingguan-admin', name: 'Kirim Laporan Penggunaan Mingguan' }, + { cron: 'TZ=Asia/Jakarta 0 9 * * 1' }, // Setiap Senin pukul 09:00 WIB + async ({ step }) => { + const dataMetrik = await step.run('ambil-data-metrik', async () => { + return await kumpulkanMetrik7HariTerakhir(); + }); + + const fileLaporan = await step.run('buat-dokumen-laporan', async () => { + return await generateReportPdf(dataMetrik); + }); + + await step.run('kirimkan-email-admin', async () => { + await emailQueue.add('kirim-laporan', { file: fileLaporan }); + }); + + return { status: 'sukses', terkirim: true }; + } +); +``` + +#### 3. Distributed Cron Locking Berbasis Redis (`SET NX`) +```typescript +import { Redis } from 'ioredis'; + +const redis = new Redis(process.env.REDIS_URL!); + +export async function dapatkanKunciCron(namaTugas: string, durasiDetik: number = 300): Promise { + const kunci = `kunci-cron:${namaTugas}`; + const status = await redis.set(kunci, Date.now().toString(), 'EX', durasiDetik, 'NX'); + return status === 'OK'; +} + +export async function lepaskanKunciCron(namaTugas: string): Promise { + await redis.del(`kunci-cron:${namaTugas}`); +} +``` + +### Praktik Terbaik Keamanan Cron +- **Gunakan Distributed Lock**: Mencegah eksekusi ganda ketika aplikasi berjalan pada banyak instans server (cluster/autoscaling). +- **Tentukan `maxDuration`**: Hindari cron menggantung tanpa henti yang menghabiskan alokasi sumber daya komputasi. +- **Zona Waktu Eksplisit**: Selalu sertakan parameter timezone (`TZ=Asia/Jakarta`) agar jadwal tidak bergeser saat Daylight Saving Time (DST) di cloud server. \ No newline at end of file diff --git a/vibes-plug/skills/data-pipeline-etl-expert/SKILL.md b/vibes-plug/skills/data-pipeline-etl-expert/SKILL.md new file mode 100644 index 000000000..c79f07cda --- /dev/null +++ b/vibes-plug/skills/data-pipeline-etl-expert/SKILL.md @@ -0,0 +1,85 @@ +--- +name: data-pipeline-etl-expert +description: "Expert guide for Data Pipelines, ETL/ELT, and Analytics Engineering. Covers dbt, Apache Airflow, Dagster, BigQuery, ClickHouse, and DuckDB / Panduan ahli untuk Data Pipelines, ETL/ELT. Mencakup dbt, Airflow, Dagster, BigQuery, ClickHouse, dan DuckDB." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Data Pipeline & ETL Expert + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +A specialized skill for building robust data architectures, Analytics Engineering, and ETL (Extract, Transform, Load) or ELT pipelines. It covers modern data stack orchestration (Airflow, Dagster), transformation tools (dbt), and high-performance OLAP databases (BigQuery, Snowflake, ClickHouse, DuckDB). + +### Trigger Conditions +- When designing reporting dashboards or analytics infrastructure for a SaaS. +- When moving large volumes of data from transactional databases (PostgreSQL/MySQL) to a data warehouse. +- When the user asks about "dbt", "Airflow", "ELT", or "Analytics Engineering". +- When building local or edge analytics using DuckDB. + +### Core Architectural Guidelines + +#### 1. ELT over ETL +Prefer Extract-Load-Transform (ELT) over traditional ETL. +- **Extract & Load**: Use tools like Airbyte or Fivetran to dump raw data directly into the Data Warehouse. +- **Transform**: Perform transformations *inside* the Data Warehouse using SQL (via dbt) to leverage the warehouse's massive compute power. + +#### 2. Analytics Engineering with dbt +Treat SQL like software engineering. +- Use `dbt` (Data Build Tool) to version control your SQL transformations. +- Implement tests (`not_null`, `unique`) on critical tables. +- Use Jinja templating in dbt to DRY up complex SQL queries. + +#### 3. Data Orchestration (Airflow vs Dagster) +- **Apache Airflow**: The industry standard for scheduling and monitoring complex DAGs (Directed Acyclic Graphs). Best for Python-heavy teams. +- **Dagster**: A modern alternative focused on data assets rather than just tasks. Use Dagster when you want better local testing and asset-driven lineage. + +#### 4. OLAP Database Selection +- **BigQuery / Snowflake**: Best for massive scale, fully managed cloud data warehousing. +- **ClickHouse**: Best for real-time, sub-second analytical queries on massive event streams. +- **DuckDB**: Best for local analytics, embedded analytical pipelines, or processing parquets in edge environments (Node.js/Python). + +## Orchestration & Integration +- Pairs with `data-telemetry-expert` to process the raw telemetry events captured by PostHog/OpenTelemetry. +- Complements `python-programming-expert` as Python is the lingua franca of data engineering. +- Works with `cron-scheduler-expert` when simpler, non-DAG cron jobs are sufficient for small ETL tasks. + +--- + + +## Bahasa Indonesia + +### Deskripsi +Panduan khusus untuk membangun arsitektur data yang kuat, Analytics Engineering, dan pipeline ETL/ELT. Mencakup orkestrasi (Airflow, Dagster), alat transformasi (dbt), dan database OLAP berkinerja tinggi (BigQuery, Snowflake, ClickHouse, DuckDB). + +### Kondisi Pemicu +- Saat merancang infrastruktur analitik atau dashboard pelaporan untuk SaaS. +- Saat memindahkan data bervolume besar dari database transaksional ke Data Warehouse. +- Saat membangun analitik lokal yang cepat menggunakan DuckDB. + +### Panduan Arsitektur Inti + +#### 1. ELT lebih disukai daripada ETL +- **Extract & Load**: Pindahkan data mentah (raw data) langsung ke Data Warehouse (menggunakan Airbyte/Fivetran). +- **Transform**: Lakukan transformasi data *di dalam* Data Warehouse menggunakan SQL (dbt) untuk memanfaatkan kekuatan komputasi gudang data yang masif. + +#### 2. Analytics Engineering dengan dbt (Data Build Tool) +Perlakukan transformasi data (SQL) layaknya rekayasa perangkat lunak. Gunakan dbt untuk version control, pengujian otomatis (`not_null`, `unique`), dan dokumentasi skema data Anda. + +#### 3. Orkestrasi Data (DAG) +Gunakan Apache Airflow atau Dagster untuk menjadwalkan dan memonitor alur kerja data yang kompleks (DAG). Dagster sangat direkomendasikan untuk pendekatan modern yang berpusat pada aset data (asset-driven orchestration). + +#### 4. Pemilihan Database OLAP +- **BigQuery / Snowflake**: Gudang data cloud fully-managed untuk analitik skala masif. +- **ClickHouse**: Sangat cepat untuk kueri analitik real-time. Cocok untuk data event stream/log. +- **DuckDB**: SQLite untuk analitik. Sangat cepat untuk memproses file Parquet atau CSV secara lokal maupun di lingkungan edge/serverless (via Python/Node.js). + +## Integrasi Orkestrasi +- Bekerja sama dengan `data-telemetry-expert` untuk memproses data mentah yang dikumpulkan. +- Melengkapi `python-programming-expert` dalam menulis skrip orkestrasi Airflow/Dagster. \ No newline at end of file diff --git a/vibes-plug/skills/data-telemetry-expert/SKILL.md b/vibes-plug/skills/data-telemetry-expert/SKILL.md new file mode 100644 index 000000000..2fa15e876 --- /dev/null +++ b/vibes-plug/skills/data-telemetry-expert/SKILL.md @@ -0,0 +1,278 @@ +--- +name: data-telemetry-expert +description: "Expert guide for observability, analytics, telemetry, and data pipelines (OpenTelemetry, PostHog, Mixpanel) / Panduan ahli untuk observabilitas, telemetri, dan analitik." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Data & Telemetry Expert (OpenTelemetry 1.x / ClickHouse Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Expert guide for production observability, product analytics, and data pipelines. Covers **OpenTelemetry 1.x** (stable, vendor-neutral traces/metrics/logs), **PostHog** (open-source product analytics), **ClickHouse** (OLAP analytics database), Grafana stack, and AI agent observability patterns. + +### Trigger Conditions +- Adding distributed tracing to a microservice or Next.js application. +- Setting up structured logging and metrics collection. +- Implementing product analytics (funnel analysis, feature flags, session replay). +- Building a high-performance analytics pipeline with ClickHouse. +- Monitoring AI agent runs, LLM token costs, and response quality. + +### OpenTelemetry 1.x — Vendor-Neutral Observability + +OpenTelemetry (OTel) is the CNCF standard for generating traces, metrics, and logs from any application. + +#### Three Pillars of OTel + +| Signal | What It Captures | Example | +|---|---|---| +| **Traces** | Request flow across services | `GET /api/users` → DB query → cache | +| **Metrics** | Numeric measurements over time | `http_requests_total`, `db_query_duration` | +| **Logs** | Structured event records | `{"level":"error","msg":"DB timeout"}` | + +#### Next.js 15 + OTel Instrumentation +```typescript +// instrumentation.ts (Next.js built-in OTel support) +export async function register() { + if (process.env.NEXT_RUNTIME === 'nodejs') { + const { NodeSDK } = await import('@opentelemetry/sdk-node'); + const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http'); + const { OTLPMetricExporter } = await import('@opentelemetry/exporter-metrics-otlp-http'); + const { PeriodicExportingMetricReader } = await import('@opentelemetry/sdk-metrics'); + const { Resource } = await import('@opentelemetry/resources'); + const { SEMRESATTRS_SERVICE_NAME } = await import('@opentelemetry/semantic-conventions'); + + const sdk = new NodeSDK({ + resource: new Resource({ + [SEMRESATTRS_SERVICE_NAME]: 'my-saas-app', + }), + traceExporter: new OTLPTraceExporter({ + url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT, + }), + metricReader: new PeriodicExportingMetricReader({ + exporter: new OTLPMetricExporter(), + exportIntervalMillis: 30_000, + }), + }); + + sdk.start(); + } +} +``` + +#### Custom Spans for Business Logic +```typescript +import { trace, SpanStatusCode } from '@opentelemetry/api'; + +const tracer = trace.getTracer('my-service', '1.0.0'); + +async function processOrder(orderId: string) { + return tracer.startActiveSpan('processOrder', async (span) => { + span.setAttribute('order.id', orderId); + span.setAttribute('order.source', 'api'); + + try { + const order = await db.order.findUnique({ where: { id: orderId } }); + span.setAttribute('order.amount', order.amount); + + const result = await chargeCustomer(order); + span.setStatus({ code: SpanStatusCode.OK }); + return result; + } catch (error) { + span.recordException(error as Error); + span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) }); + throw error; + } finally { + span.end(); + } + }); +} +``` + +### ClickHouse — High-Performance Analytics Database +ClickHouse is the 2026 standard for analytical workloads — ingests billions of events and queries them in milliseconds: + +```sql +-- Create an events table optimized for time-series analytics +CREATE TABLE events ( + event_id UUID DEFAULT generateUUIDv4(), + workspace_id String, + user_id String, + event_name LowCardinality(String), + properties JSON, + timestamp DateTime64(3, 'UTC'), + date Date DEFAULT toDate(timestamp) +) +ENGINE = MergeTree() +PARTITION BY toYYYYMM(date) +ORDER BY (workspace_id, event_name, timestamp) +TTL date + INTERVAL 1 YEAR; + +-- Query: Funnel analysis — users who signed up then upgraded +SELECT + countIf(event_name = 'signup') AS signups, + countIf(event_name = 'plan_upgraded') AS upgrades, + round(countIf(event_name = 'plan_upgraded') / countIf(event_name = 'signup') * 100, 2) AS conversion_rate +FROM events +WHERE workspace_id = 'ws_abc' + AND timestamp >= now() - INTERVAL 30 DAY; +``` + +```typescript +// Node.js ClickHouse client +import { createClient } from '@clickhouse/client'; + +const client = createClient({ url: process.env.CLICKHOUSE_URL }); + +await client.insert({ + table: 'events', + values: [{ + workspace_id: 'ws_abc', + user_id: 'user_123', + event_name: 'page_view', + properties: { path: '/dashboard', referrer: 'google.com' }, + timestamp: new Date().toISOString(), + }], + format: 'JSONEachRow', +}); +``` + +### PostHog — Open-Source Product Analytics +```typescript +// Next.js + PostHog (client-side) +import posthog from 'posthog-js'; + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? 'https://app.posthog.com', + capture_pageview: false, // Manual with App Router +}); + +// Track custom events +posthog.capture('feature_used', { + feature: 'ai_assistant', + plan: user.plan, + workspace_id: workspace.id, +}); + +// Feature flags +if (posthog.isFeatureEnabled('new-dashboard')) { + return ; +} +``` + +### AI Agent Observability +Track LLM costs, latency, and quality for production AI applications: +```typescript +// Custom OTel attributes for LLM calls +span.setAttribute('llm.model', 'claude-4-sonnet'); +span.setAttribute('llm.input_tokens', response.usage.input_tokens); +span.setAttribute('llm.output_tokens', response.usage.output_tokens); +span.setAttribute('llm.cost_usd', calculateCost(response.usage)); +span.setAttribute('llm.latency_ms', Date.now() - startTime); +span.setAttribute('llm.cached', response.usage.cache_read_input_tokens > 0); +``` + +Backend tracing tools for LLM: **LangSmith** (LangChain/LangGraph), **OpenAI Tracing** (Agents SDK), **Langfuse** (open-source, any LLM). + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan observabilitas terpadu. + +### Deskripsi +Panduan ahli untuk observabilitas produksi, analitik produk, dan pipeline data. Mencakup **OpenTelemetry 1.x** (standar traces, metrics, logs netral vendor), **PostHog** (analitik produk open-source), **ClickHouse** (database analitik OLAP berkecepatan tinggi), Grafana stack, dan pola pemantauan agen AI. + +### Kondisi Pemicu +- Menambahkan distributed tracing ke microservice atau aplikasi Next.js. +- Menyiapkan structured logging dan pengumpulan metrik performa. +- Mengimplementasikan analitik produk (funnel, feature flag, session replay). +- Membangun pipeline analitik berkecepatan tinggi menggunakan ClickHouse. + +--- + +### Tiga Pilar OpenTelemetry (Traces, Metrics, Logs) + +| Sinyal | Definisi | Contoh Kasus | +|---|---|---| +| **Traces** | Alur request di berbagai microservice | `GET /api/pesanan` → query DB → redis cache | +| **Metrics** | Pengukuran numerik sepanjang waktu | `http_requests_total`, durasi query DB | +| **Logs** | Catatan kejadian terstruktur | `{"level":"error","pesan":"Koneksi DB timeout"}` | + +--- + +### Implementasi Pola Kunci (TypeScript) + +#### 1. Instrumentasi OpenTelemetry di Next.js 15 +```typescript +// instrumentation.ts +export async function register() { + if (process.env.NEXT_RUNTIME === 'nodejs') { + const { NodeSDK } = await import('@opentelemetry/sdk-node'); + const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http'); + const { OTLPMetricExporter } = await import('@opentelemetry/exporter-metrics-otlp-http'); + const { PeriodicExportingMetricReader } = await import('@opentelemetry/sdk-metrics'); + const { Resource } = await import('@opentelemetry/resources'); + const { SEMRESATTRS_SERVICE_NAME } = await import('@opentelemetry/semantic-conventions'); + + const sdk = new NodeSDK({ + resource: new Resource({ + [SEMRESATTRS_SERVICE_NAME]: 'saas-produksi-app', + }), + traceExporter: new OTLPTraceExporter({ + url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT, + }), + metricReader: new PeriodicExportingMetricReader({ + exporter: new OTLPMetricExporter(), + exportIntervalMillis: 30_000, + }), + }); + + sdk.start(); + } +} +``` + +#### 2. Klien ClickHouse untuk Ingestion Event Skala Masif +```typescript +import { createClient } from '@clickhouse/client'; + +const clickhouse = createClient({ url: process.env.CLICKHOUSE_URL }); + +export async function rekamEventTelemetri(namaEvent: string, dataProperti: Record) { + await clickhouse.insert({ + table: 'events', + values: [{ + event_name: namaEvent, + properties: dataProperti, + timestamp: new Date().toISOString(), + }], + format: 'JSONEachRow', + }); +} +``` + +#### 3. Pelacakan Event PostHog di Sisi Klien +```typescript +import posthog from 'posthog-js'; + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? 'https://app.posthog.com', + capture_pageview: false, +}); + +export function lacakAktivitasPengguna(namaFitur: string) { + posthog.capture('fitur_digunakan', { fitur: namaFitur, timestamp: new Date().toISOString() }); +} +``` \ No newline at end of file diff --git a/vibes-plug/skills/data-visualization-expert/SKILL.md b/vibes-plug/skills/data-visualization-expert/SKILL.md new file mode 100644 index 000000000..f1fd8bbed --- /dev/null +++ b/vibes-plug/skills/data-visualization-expert/SKILL.md @@ -0,0 +1,290 @@ +--- +name: data-visualization-expert +description: "Expert guide for data visualization, charts, and dashboards using D3.js, Recharts, Chart.js, Nivo, and Tremor / Panduan ahli visualisasi data, chart, dan dashboard menggunakan D3.js, Recharts, Chart.js, Nivo, dan Tremor." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Data Visualization Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +- **`senior-frontend`**: React component architecture for chart components. +- **`web-3d-graphics-expert`**: 3D spatial data visualization, WebGPU/Three.js scientific models, anatomical explainers, and 3Dviz spatial reasoning. +- **`data-telemetry-expert`**: Analytics data pipelines feeding visualizations. +- **`state-management-expert`**: Managing chart state, filters, and drill-down navigation. +- **`performance-web-vitals`**: Optimizing chart rendering performance with large datasets. +- **`sse-websocket-streaming-expert`**: Real-time data feeds for live dashboards. + +### Description +Expert guide for building production-quality data visualizations and analytics dashboards. Covers D3.js v7 (low-level SVG/Canvas), Recharts (React-native charts), Chart.js 4 (lightweight canvas), Nivo (D3-powered React components), Tremor (dashboard components), and Apache ECharts. Includes responsive charts, real-time updates, accessibility, large dataset optimization, and dashboard layout patterns. + +### Trigger Conditions +- Building analytics dashboards or admin panels with charts. +- Creating data visualizations (line, bar, pie, scatter, heatmap, treemap). +- Implementing real-time updating charts or live data feeds. +- Choosing a charting library for React, Vue, or vanilla JS. +- Optimizing chart performance with large datasets (10K+ data points). + +--- + +### Library Selection Guide + +| Library | Framework | Rendering | Customization | Learning Curve | Best For | +|---------|-----------|-----------|---------------|----------------|----------| +| D3.js v7 | Agnostic | SVG/Canvas | ★★★★★ | High | Custom visualizations | +| Recharts | React | SVG | ★★★★ | Low | Standard React charts | +| Nivo | React | SVG/Canvas | ★★★★★ | Medium | Beautiful, animated charts | +| Tremor | React | SVG (Recharts) | ★★★ | Very Low | Dashboards, KPI cards | +| Chart.js 4 | Agnostic | Canvas | ★★★ | Low | Lightweight, simple charts | +| ECharts | Agnostic | Canvas/SVG | ★★★★★ | Medium | Complex, interactive, large data | + +**Recommendation:** Use **Tremor** for rapid dashboard prototyping. Use **Recharts** for standard React charts. Use **D3.js** only for highly custom visualizations. + +### Core Patterns + +#### 1. Recharts (React Standard) + +```tsx +import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'; + +function RevenueChart({ data }: { data: { date: string; revenue: number }[] }) { + return ( + + + + + `$${(v / 1000).toFixed(0)}K`} /> + [`$${value.toLocaleString()}`, 'Revenue']} + /> + + + + ); +} +``` + +#### 2. Tremor Dashboard Components + +```tsx +import { Card, Metric, Text, AreaChart, BarList, Grid } from '@tremor/react'; + +function AnalyticsDashboard({ metrics, chartData, topPages }) { + return ( + + + Total Revenue + $845,230 + + + Revenue Over Time + `$${(v / 1000).toFixed(0)}K`} + /> + + + Top Pages + + + + ); +} +``` + +#### 3. Real-Time Chart Updates + +```tsx +import { useEffect, useState } from 'react'; + +function LiveMetricsChart() { + const [data, setData] = useState<{ time: string; value: number }[]>([]); + + useEffect(() => { + const es = new EventSource('/api/metrics/stream'); + es.onmessage = (event) => { + const point = JSON.parse(event.data); + setData((prev) => [...prev.slice(-60), point]); // Keep last 60 points + }; + return () => es.close(); + }, []); + + return ; +} +``` + +#### 4. Large Dataset Optimization +- Use **Canvas** rendering (ECharts, Chart.js) for >5K data points. +- Implement **data aggregation** on the server (downsample to 500-1000 points for display). +- Use **windowed rendering** — only render visible data points. +- Apply **debounced zoom/pan** to prevent excessive re-renders. + +#### 5. 3D Spatial Visualization & Scientific Grounded Truth +For volumetric, anatomical, geospatial, or scientific datasets, escalate to `web-3d-graphics-expert`: +- **Grounded Truth Protocol**: Verify the chain: **Scientific Claim → Mathematical Model → Rendered Result**. An aesthetic 3D mesh does not certify a scientific claim. +- **Explicit Units & Scale**: Never leave scale ambiguous; render interactive 3D scale bars or known spatial benchmarks. +- **Truthful Controls**: Sliders and toggle states must alter physical parameters in the model, not just trigger decorative visual noise. + +### Dashboard Layout Patterns +- **KPI Row → Charts → Tables**: Top metrics cards, then charts, then detail tables. +- **Filter Sidebar**: Global date range, category, and dimension filters. +- **Drill-down**: Click chart segment → navigate to detail view. +- **Export**: CSV/PNG/PDF export for all charts. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +- **`senior-frontend`**: Arsitektur komponen React untuk komponen chart dan layout dashboard responsif. +- **`web-3d-graphics-expert`**: Visualisasi data spasial 3D, model ilmiah WebGPU/Three.js, explainer anatomi, dan penalaran spasial 3Dviz. +- **`data-telemetry-expert`**: Pipeline data analitik yang mengisi visualisasi real-time. +- **`state-management-expert`**: Mengelola state filter global, parameter rentang tanggal, dan navigasi drill-down. +- **`performance-web-vitals`**: Optimasi komputasi grafis untuk dataset besar (>10.000 titik data). +- **`sse-websocket-streaming-expert`**: Feed data real-time untuk dashboard telemetri langsung. + +### Deskripsi +Panduan ahli untuk membangun visualisasi data dan dashboard analitik berkualitas produksi. Mencakup D3.js v7 (manipulasi SVG/Canvas tingkat rendah), Recharts (grafik native React), Chart.js 4 (canvas ringan), Nivo (komponen animasi berbasis D3), Tremor (kartu KPI dan visualisasi analitik SaaS), dan Apache ECharts. Menyediakan panduan chart responsif, pembaruan real-time, aksesibilitas WCAG, optimasi dataset besar, dan pola tata letak dashboard. + +### Kondisi Pemicu +- Membangun dashboard analitik, admin panel, atau portal metrik finansial. +- Membuat visualisasi data kompleks (garis tren, batang, scatter plot, heatmap, treemap). +- Mengimplementasikan chart yang diperbarui secara langsung via WebSocket atau SSE. +- Mengoptimalkan performa visualisasi saat menangani lebih dari 10.000 titik data. + +--- + +### Panduan Pemilihan Library Visualisasi + +| Library | Lingkungan | Mesin Render | Kustomisasi | Tingkat Kesulitan | Kasus Penggunaan Terbaik | +|---|---|---|---|---|---| +| **D3.js v7** | Agnostik | SVG/Canvas | ★★★★★ | Tinggi | Visualisasi ilmiah & kustom tingkat lanjut | +| **Recharts** | React | SVG | ★★★★ | Rendah | Grafik standar web app dan SaaS | +| **Nivo** | React | SVG/Canvas | ★★★★★ | Sedang | Grafik artistik dengan animasi interaktif | +| **Tremor** | React | SVG (Recharts) | ★★★ | Sangat Rendah | Dashboard MVP cepat, kartu KPI modern | +| **Chart.js 4** | Agnostik | Canvas | ★★★ | Rendah | Grafik sederhana dan efisien | +| **ECharts** | Agnostik | Canvas/SVG | ★★★★★ | Sedang | Grafik kompleks skala masif & data finansial | + +--- + +### Pola Kunci Implementasi (TypeScript/React) + +#### 1. Recharts Standar Dashboard Produksi +```tsx +import React from 'react'; +import { + LineChart, + Line, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + ResponsiveContainer, +} from 'recharts'; + +interface DataPoint { + tanggal: string; + pendapatan: number; +} + +export function GrafikPendapatan({ data }: { data: DataPoint[] }) { + return ( +
+
+

Tren Pendapatan Bulanan

+ Performa 30 Hari +
+ + + + + `Rp ${(val / 1000000).toFixed(0)}jt`} + /> + [`Rp ${value.toLocaleString('id-ID')}`, 'Pendapatan']} + /> + + + +
+ ); +} +``` + +#### 2. Update Data Real-Time via Server-Sent Events (SSE) +```tsx +import { useEffect, useState } from 'react'; + +export function GrafikMetrikRealtime() { + const [dataPoints, setDataPoints] = useState<{ waktu: string; nilai: number }[]>([]); + + useEffect(() => { + const eventSource = new EventSource('/api/metrik/stream'); + + eventSource.onmessage = (event) => { + const dataBaru = JSON.parse(event.data); + setDataPoints((riwayat) => { + // Pertahankan maksimal 60 titik data terakhir untuk efisiensi render + const buffer = [...riwayat, dataBaru]; + return buffer.length > 60 ? buffer.slice(buffer.length - 60) : buffer; + }); + }; + + eventSource.onerror = (err) => { + console.error('Koneksi stream metrik terputus:', err); + eventSource.close(); + }; + + return () => { + eventSource.close(); + }; + }, []); + + return ( +
+
+ Live Telemetry +
+ {/* Komponen LineChart mengonsumsi dataPoints */} +
+ ); +} +``` + +#### 3. Optimasi Dataset Skala Masif (>10.000 Titik Data) +1. **Pilih Canvas atau WebGL**: Hindari SVG untuk dataset >5.000 elemen guna mencegah kelebihan DOM node. Gunakan Chart.js (Canvas) atau Apache ECharts. +2. **Server-Side Downsampling**: Lakukan reduksi titik data di server menggunakan algoritma Largest-Triangle-Three-Buckets (LTTB) sebelum dikirim ke browser. +3. **Windowed / Virtualized Range**: Hanya gambar data yang berada dalam rentang zoom yang aktif saat ini. + +#### 4. Visualisasi Spasial 3D & Grounded Truth +Untuk dataset ilmiah, geospasial, atau volumetrik, delegasikan ke `web-3d-graphics-expert`: +- **Rantai Validasi Ilmiah**: Wajib mematuhi rantai: **Klaim Ilmiah → Model Matematika → Hasil Render**. Jangan tampilkan visualisasi acak tanpa data acuan numerik. +- **Skala dan Unit Eksplisit**: Sertakan skala interaktif dan satuan metrik yang jelas pada canvas. \ No newline at end of file diff --git a/vibes-plug/skills/database-orm-expert/SKILL.md b/vibes-plug/skills/database-orm-expert/SKILL.md new file mode 100644 index 000000000..16f570d10 --- /dev/null +++ b/vibes-plug/skills/database-orm-expert/SKILL.md @@ -0,0 +1,166 @@ +--- +name: database-orm-expert +description: "Updated to be the unified database skill covering ORM, migrations, edge DBs, and Supabase CLI / Keahlian database terpadu untuk ORM, migrasi, edge DB, dan Supabase CLI." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Unified Database & ORM Expert + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Design schemas, select ORMs, execute zero-downtime migrations, optimize queries, and implement edge serverless databases. Covers Prisma 6, Drizzle ORM, TypeORM, Supabase CLI workflows, and Edge DBs (Neon, Cloudflare D1, Turso, Upstash). + +### Trigger Conditions +- Designing or migrating a production schema (blue-green, canary). +- Choosing between Prisma, Drizzle ORM, or TypeORM. +- Writing complex queries with joins, aggregations, or pagination. +- Optimizing slow queries or N+1 problems. +- Building edge-compatible serverless database connections. +- Executing Supabase migrations and RLS patterns. +- Managing backward-compatible massive data backfills. + +## Orchestration & Integration +- `js-backend-expert`: For Node/Bun/Deno backend implementations integrating these ORMs. +- `ci-cd-devops-architect`: For automated migration deployment steps. +- `supabase-security-expert`: For Supabase RLS and security. +- `cloud-hosting-expert`: For infrastructure integration. + +--- + +### Core ORM & Query Strategies + +#### ORM Selection Guide +| Criteria | Prisma 6 | Drizzle ORM | TypeORM | +|---|---|---|---| +| **Type Safety** | Schema-generated types | SQL-like, inferred types | Decorator-based | +| **Bundle Size** | Heavy (binary client) | Lightweight (<35KB) | Medium | +| **Query Style** | Fluent ORM API | SQL-first, composable | ActiveRecord / QueryBuilder | +| **Edge Runtime** | Prisma Accelerate needed | Native edge support | No | +| **Migrations** | `prisma migrate dev` | `drizzle-kit push/migrate` | `synchronize` (dev only) | + +**Recommendation**: Use **Drizzle ORM** for edge-compatible apps and performance-critical systems. Use **Prisma 6** for teams preferring a schema-first DX. + +#### Prisma 6 Best Practices +- Use `$transaction` for atomic operations. +- Avoid N+1 queries by using `select` and `include` (with Prisma 5.7+ relationJoins preview) rather than looping over `findMany`. + +#### Drizzle ORM Best Practices +- Use `drizzle-kit generate` for generating SQL and `drizzle-kit migrate` for deployment. +- Utilize native edge support and type-safe query builders with `drizzle-orm`. + +#### Query Optimization Principles +1. **Always index foreign keys** and columns used in `WHERE`, `ORDER BY`, and `JOIN`. +2. **Use `EXPLAIN ANALYZE`** to detect sequential scans. +3. **Cursor-based pagination** over offset for large datasets. +4. **Avoid `SELECT *`**. Batch inserts where possible. +5. **Connection Pooling**: Use PgBouncer, Supabase's built-in pooler, or Prisma Accelerate for standard TCP to avoid exhausting connection limits. Alternatively, use HTTP/WebSocket drivers for edge queries. + +--- + +### Zero-Downtime Migrations & Versioning + +#### 1. Zero-Downtime Migration Pattern (Expand and Contract) +Never make breaking changes in a single deployment. +- **Phase 1 (Expand)**: Add the new schema element (column, table) without removing the old one. +- **Phase 2 (Migrate)**: Update app to write to *both* and read from the new element (with fallback). +- **Phase 3 (Backfill)**: Run background script to backfill data to new element. +- **Phase 4 (Contract)**: Remove old application code. +- **Phase 5 (Cleanup)**: Drop old schema element in next deployment. + +#### 2. Backward Compatibility Rules +- **Never `DROP` or `RENAME`** a column/table in active use. +- **Add `DEFAULT` values** to new `NOT NULL` columns. + +#### 3. Migration Mechanics & Safe Data Backfilling +- **Never run `prisma db push` or `synchronize: true`** in production. Always use immutable version-controlled scripts (e.g., `20260814_add_user_status.sql`). +- Write idempotent scripts (`CREATE TABLE IF NOT EXISTS`). +- **Chunking**: For large tables, perform updates in batches (using `LIMIT` and sleep intervals) to prevent table locking. Use background jobs (BullMQ/Inngest). + +--- + +### Edge & Serverless Drivers + +Exploit serverless DBs for ultra-low latency: +- **Neon & Cloudflare D1**: Serverless autoscaling Postgres with instant branching; Distributed edge SQLite. +- **Embedded Replicas**: Sync edge SQLite read-replicas with central cloud DBs. +- **HTTP/WebSocket Proxy Pooling**: Use `neon-http` or similar when querying databases from Edge Workers/Functions. +- **Upstash Redis Edge Caching**: +```typescript +import { Redis } from '@upstash/redis'; +const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN! }); +export async function getCachedData(key: string) { + let data = await redis.get(key); + if (!data) { + data = await fetchFromDB(); + await redis.set(key, data, { ex: 3600 }); + } + return data; +} +``` + +--- + +### Supabase CLI & MCP Workflow + +1. **Check Environment**: Ensure `supabase/migrations` directory exists. +2. **Review Available MCP Commands**: + - List existing migrations: `mcp_supabase-mcp-server_list_migrations` with `project_id`. + - Confirm SQL before executing via server directly. +3. **Execute Command**: + - Write SQL script locally: `npx supabase migration new [name]` -> writes to `supabase/migrations/_[name].sql`. + - Test locally: `npx supabase migration up` or `npx supabase db reset`. + - Apply remote: `npx supabase db push` (or use remote MCP `apply_migration`). +4. **Final Step**: If using RLS, explicitly add policies to new tables. Confirm completion with user. + +--- + + +## Bahasa Indonesia + +### Deskripsi +Rancang skema, pilih ORM, eksekusi migrasi tanpa downtime, optimalkan query, dan implementasikan edge serverless DB. Mencakup Prisma 6, Drizzle, TypeORM, Supabase CLI, dan Edge DBs (Neon, Cloudflare D1, Turso, Upstash). + +### Kondisi Pemicu +- Merancang atau memigrasikan skema produksi (blue-green, canary). +- Memilih antara Prisma, Drizzle, atau TypeORM. +- Mengoptimalkan query lambat atau masalah N+1. +- Membuat koneksi serverless kompatibel dengan edge. +- Mengeksekusi migrasi Supabase dan pola RLS. +- Mengelola backfill data besar secara backward-compatible. + +## Integrasi Orkestrasi +- `js-backend-expert`: Untuk implementasi Node/Bun/Deno. +- `ci-cd-devops-architect`: Untuk otomatisasi langkah deployment migrasi. +- `supabase-security-expert`: Untuk RLS dan keamanan Supabase. +- `cloud-hosting-expert`: Untuk integrasi infrastruktur. + +### Strategi Inti ORM & Query +- **Drizzle ORM** direkomendasikan untuk aplikasi edge, **Prisma 6** untuk DX schema-first. +- Gunakan `$transaction` dan batasi `SELECT *`. +- Selalu indeks foreign key dan gunakan pagination berbasis cursor (Cursor-based pagination). +- **Connection Pooling**: Gunakan pooler bawaan Supabase, PgBouncer, Prisma Accelerate, atau driver HTTP (seperti `neon-http`) untuk request edge. + +### Migrasi Tanpa Downtime & Versioning +- **Pola Expand and Contract**: Jangan pernah melakukan breaking change dalam satu rilis. Tambah kolom baru, update kode untuk memakai keduanya, backfill data, hapus kode lama, lalu drop kolom lama. +- Jangan gunakan `DROP` atau `RENAME` pada kolom aktif. Kolom `NOT NULL` baru harus memiliki nilai `DEFAULT`. +- **Jangan jalankan `prisma db push` atau `synchronize: true`** di produksi. Gunakan skrip migrasi bertahap (idempoten). +- **Backfill Aman**: Gunakan pemrosesan batch/chunking dengan background job untuk tabel raksasa agar tidak menyebabkan table lock. + +### Driver Edge & Serverless +- Manfaatkan Neon Serverless Postgres, Cloudflare D1, Turso, atau Upstash Redis (caching). +- Gunakan driver berbasis HTTP/WebSocket di lingkungan Edge Workers untuk mencegah habisnya batas koneksi TCP. + +### Alur Kerja Supabase CLI & MCP +1. Pastikan folder `supabase/migrations` ada. +2. Periksa migrasi dengan `mcp_supabase-mcp-server_list_migrations`. +3. Buat file migrasi lokal dengan `npx supabase migration new [nama]`. +4. Uji lokal dengan `npx supabase migration up`. +5. Deploy remote dengan `npx supabase db push` atau melalui MCP. +6. Tambahkan kebijakan RLS jika diperlukan. Konfirmasikan sukses ke pengguna. \ No newline at end of file diff --git a/vibes-plug/skills/deep-research-analyst/SKILL.md b/vibes-plug/skills/deep-research-analyst/SKILL.md new file mode 100644 index 000000000..8b32fd572 --- /dev/null +++ b/vibes-plug/skills/deep-research-analyst/SKILL.md @@ -0,0 +1,285 @@ +--- +name: deep-research-analyst +description: "Expert guide for autonomous deep research, iterative web search, citation verification, evidence graph synthesis, and hallucination mitigation / Panduan ahli riset mendalam otonom, pencarian web iteratif, verifikasi sitasi, dan mitigasi halusinasi." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Deep Research Analyst (2026 Autonomous Research Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `prd-architect`, `web-scraper`, `browser-automation-expert`, `session-memory-manager`, and `multi-agent-orchestration` to form an evidence-backed intelligence swarm. + +### Description +Production guide for architecting and executing autonomous **Deep Research** pipelines. Unlike simple one-shot retrieval (RAG), Deep Research operates as a goal-directed autonomous loop: decomposing queries into multi-perspective sub-questions, crawling and scraping academic/technical sources, scoring source credibility, cross-verifying facts across multiple independent citations, constructing an evidence graph, and synthesizing comprehensive, citation-grounded intelligence briefs. + +**Swarm Synergy:** Within the **Fan-Out / Fan-In Research Swarm**, this skill acts as the Lead Intelligence Subagent. It is deployed in Phase 1 (Discovery & PRD) to gather ground truth, audit competitor architectures, and resolve high-risk technical unknowns before code is written. + +### Trigger Conditions +- Requiring deep, multi-source investigation before architectural decision-making. +- Benchmarking libraries, database engines, or cloud architectures with empirical data. +- Building autonomous research agents, competitive intelligence scrapers, or literature synthesis tools. +- Eliminating LLM hallucinations in high-stakes technical or business documentation. +- Synthesizing complex multi-page web information into structured, cited intelligence reports. + +### Deep Research Operational Workflow + +``` +1. QUERY DECOMPOSITION & HYPOTHESIS FORMULATION + [User Objective] ──► [Query Expander] ──┬──► Sub-query A (Technical Specs) + ├──► Sub-query B (Benchmarks & Limitations) + └──► Sub-query C (Community Issues & Regressions) + +2. RECURSIVE SOURCE DISCOVERY & CRAWLING + [Sub-queries] ──► [Crawl4AI / Firecrawl / SerpAPI] ──► Raw Markdown / HTML Sources + +3. SOURCE CREDIBILITY & FACT TRIANGULATION + Raw Documents ──► [Evidence Evaluator] ──► Triangulate Facts (>= 2 Independent Sources) + ──► Discard Low-Trust / SEO-Spam Content + +4. EVIDENCE GRAPH SYNTHESIS & REPORTING + Verified Facts ──► [Synthesizer Node] ──► Structured Report with Clickable Markdown Citations +``` + +### Core Implementation Guidelines + +#### 1. Recursive Query Decomposer (Python / TypeScript) +Break high-level user requests into diverse search vectors targeting technical documentation, GitHub issues, and benchmarks: +```typescript +import { generateObject } from 'ai'; +import { z } from 'zod'; + +interface ResearchPlan { + coreObjective: string; + subQueries: Array<{ + query: string; + focus: 'architecture' | 'benchmarks' | 'security' | 'pitfalls'; + expectedSourceType: 'docs' | 'github_repo' | 'benchmark_paper'; + }>; +} + +export async function decomposeResearchQuery(userPrompt: string): Promise { + const { object } = await generateObject({ + model: customModel('gemini-3.8-flash'), + schema: z.object({ + coreObjective: z.string(), + subQueries: z.array(z.object({ + query: z.string().describe('Precise keyword search query with technical operators'), + focus: z.enum(['architecture', 'benchmarks', 'security', 'pitfalls']), + expectedSourceType: z.enum(['docs', 'github_repo', 'benchmark_paper']), + })).min(3).max(6), + }), + prompt: `Analyze the following research objective and decompose it into 4-6 targeted, non-overlapping search vectors: "${userPrompt}"`, + }); + + return object; +} +``` + +#### 2. Python Implementation: Autonomous Extraction +```python +from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode +from pydantic import BaseModel, Field +from pydantic_ai import Agent + +class ResearchFinding(BaseModel): + claim: str = Field(description="Technical claim extracted") + confidence: float = Field(ge=0, le=1, description="Confidence score") + source_url: str = Field(description="Source URL") + corroborating_sources: list[str] = Field(default_factory=list) + +research_agent = Agent( + 'google:gemini-3.8-flash', + result_type=list[ResearchFinding], + system_prompt="Extract and verify technical claims with confidence scores." +) + +async def deep_research(query: str) -> list[ResearchFinding]: + config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS) + async with AsyncWebCrawler() as crawler: + result = await crawler.arun(url=f"https://search-url/{query}", config=config) + findings = await research_agent.run(result.markdown) + return findings.data +``` + +#### 3. Vector Store Caching for Intermediate Results +Caching intermediate research results in vector stores prevents redundant crawling and accelerates knowledge retrieval: +- **Storage:** Use `pgvector` or local `FAISS` for caching crawled page embeddings. +- **Deduplication:** Deduplicate sources via cosine similarity before processing. +- **Invalidation:** Implement TTL-based cache invalidation for time-sensitive research (e.g., fast-moving API docs). +- **Example Flow:** + ```python + # Store page chunks in vector store + vector_store.add_texts(chunks, metadata=[{"url": url, "timestamp": now}]) + # Retrieve similar past findings + cached = vector_store.similarity_search(query, k=3, filter={"ttl_valid": True}) + ``` + +#### 4. Episodic Research Memory +Maintain research memory across sessions to build continuous intelligence: +- **Storage:** Store research dossiers as episodic memories in `session-memory-manager`. +- **Knowledge Graphs:** Build cumulative knowledge graphs from multiple research sessions, linking related concepts over time. +- **Cross-referencing:** Cross-reference past findings with new queries to compound understanding without starting from scratch. + +#### 5. Source Credibility & Fact Triangulation Protocol +Never accept a claim from a single unverified blog post. Require citation triangulation: +- **Tier 1 (Highest Confidence):** Official documentation, source code repositories, peer-reviewed benchmarks, RFCs. +- **Tier 2 (Medium Confidence):** Production engineering blogs (Uber, Netflix, Cloudflare), maintainer posts. +- **Tier 3 (Verify Required):** Forum discussions, social threads, unverified community tutorials. +- **Rule of Triangulation:** Any non-trivial technical claim must be confirmed by at least two independent sources or verified against raw benchmark code. + +#### 6. Structured Evidence Graph Output +Every research brief produced by this skill must adhere to the following markdown template: +```markdown +# [Topic] — Deep Research & Evidence Dossier + +## Executive Summary +- Concise 3-5 bullet takeaway synthesis. + +## Evidence Matrix +| Technical Claim | Verified Status | Confidence (0-100%) | Primary Source | Corroborating Source | +|---|---|---|---|---| +| Claim Description | Confirmed / Disputed | 95% | [Source A](url) | [Source B](url) | + +## Trade-off Analysis & Key Risks +- Concrete architectural trade-offs, cold-start latencies, memory footprint, or pricing cliff. + +## Recommended Architectural Decision +- Prescriptive guidance for implementation swarms with justification. +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `prd-architect`, `web-scraper`, `browser-automation-expert`, `session-memory-manager`, dan `multi-agent-orchestration` untuk membentuk swarm intelijen berbasis bukti empiris. + +### Deskripsi +Panduan produksi untuk merancang dan mengeksekusi pipeline **Riset Mendalam Otonom (Deep Research)**. Berbeda dari retrieval sederhana (RAG satu langkah), Deep Research beroperasi sebagai siklus otonom terarah: memecah pertanyaan menjadi sub-vektor dari berbagai sudut pandang, merayapi dan mengekstrak sumber teknis/akademis, menilai kredibilitas sumber, memvalidasi silang fakta (*fact triangulation*) di minimal 2 sumber independen, membangun graf bukti, dan menyusun laporan intelijen komprehensif berlandaskan sitasi yang valid. + +**Sinergi Swarm:** Dalam topologi **Fan-Out / Fan-In Research Swarm**, skill ini berperan sebagai Sub-agen Analis Utama. Diterapkan pada Fase 1 (Discovery & PRD) untuk mengumpulkan fakta objektif, mengaudit arsitektur kompetitor, dan mengeliminasi ketidakpastian teknis berisiko tinggi sebelum penulisan kode dimulai. + +### Kondisi Pemicu +- Membutuhkan penyelidikan multi-sumber yang mendalam sebelum membuat keputusan arsitektur. +- Melakukan benchmark komparatif library, database engine, atau infrastruktur cloud berbasis data empiris. +- Membangun agen riset otonom, alat pemantau kompetitor, atau sintesis literatur otomatis. +- Mengeliminasi halusinasi LLM pada dokumen teknis atau strategi bisnis berisiko tinggi. +- Merangkum informasi web yang rumit dan tersebar menjadi dokumen ringkasan terstruktur dengan sitasi klik langsung. + +--- + +### Alur Kerja Operasional Riset Mendalam + +``` +1. DEKOMPOSISI KUERI & HIPOTESIS + [Tujuan Riset] ──► [Query Expander] ──┬──► Sub-kueri A (Spesifikasi Teknis) + ├──► Sub-kueri B (Benchmark & Batasan) + └──► Sub-kueri C (Isu Komunitas & Regresi) + +2. PERAYAPAN SUMBER REKURSIF + [Sub-kueri] ──► [Crawl4AI / Firecrawl / SerpAPI] ──► Dokumen Mentah (Markdown/HTML) + +3. TRIANGULASI FAKTA & KREDIBILITAS + Dokumen Mentah ──► [Evidence Evaluator] ──► Validasi Silang (>= 2 Sumber Independen) + ──► Eliminasi Konten SEO-Spam & Blog Rendah Kredibilitas + +4. SINTESIS GRAF BUKTI & LAPORAN + Fakta Terverifikasi ──► [Synthesizer Node] ──► Laporan Terstruktur dengan Sitasi Klik Langsung +``` + +--- + +### Panduan Implementasi Inti + +#### 1. Dekomposisi Kueri Rekursif (TypeScript & AI SDK) +```typescript +import { generateObject } from 'ai'; +import { z } from 'zod'; + +interface RencanaRiset { + tujuanUtama: string; + subKueri: Array<{ + kueri: string; + fokus: 'arsitektur' | 'benchmark' | 'keamanan' | 'kelemahan'; + jenisSumber: 'dokumentasi' | 'repositori_github' | 'paper_teknis'; + }>; +} + +export async function dekomposisiTujuanRiset(promptPengguna: string): Promise { + const { object } = await generateObject({ + model: customModel('gemini-3.8-flash'), + schema: z.object({ + tujuanUtama: z.string(), + subKueri: z.array(z.object({ + kueri: z.string().describe('Kueri kata kunci spesifik dengan operator pencarian teknis'), + fokus: z.enum(['arsitektur', 'benchmark', 'keamanan', 'kelemahan']), + jenisSumber: z.enum(['dokumentasi', 'repositori_github', 'paper_teknis']), + })).min(3).max(6), + }), + prompt: `Analisis tujuan riset berikut dan pecah menjadi 4-6 vektor pencarian teknis yang spesifik: "${promptPengguna}"`, + }); + + return object; +} +``` + +#### 2. Ekstraksi Otonom & Evaluasi Klaim (Python & Crawl4AI) +```python +from crawl4ai import AsyncWebCrawler, CrawlerRunConfig, CacheMode +from pydantic import BaseModel, Field +from pydantic_ai import Agent + +class TemuanRiset(BaseModel): + klaim_teknis: str = Field(description="Klaim teknis spesifik yang diekstraksi") + skor_keyakinan: float = Field(ge=0, le=1, description="Skor keyakinan bukti (0 sampai 1)") + url_sumber: str = Field(description="URL sumber primer") + sumber_pendukung: list[str] = Field(default_factory=list, description="Daftar URL sumber pembanding") + +agen_analis = Agent( + 'google:gemini-3.8-flash', + result_type=list[TemuanRiset], + system_prompt="Ekstrak temuan teknis obyektif beserta skor keyakinan dan sumber referensi." +) + +async def eksekusi_riset_mendalam(kueri: str) -> list[TemuanRiset]: + config = CrawlerRunConfig(cache_mode=CacheMode.BYPASS) + async with AsyncWebCrawler() as crawler: + halaman = await crawler.arun(url=f"https://search-engine.internal/q={kueri}", config=config) + hasil = await agen_analis.run(halaman.markdown) + return hasil.data +``` + +#### 3. Protokol Triangulasi Fakta & Skor Keyakinan +1. **Tier 1 (Otoritas Tertinggi):** Dokumentasi resmi, repositori kode sumber terbuka, spesifikasi RFC, dan laporan audit formal. +2. **Tier 2 (Dapat Diandalkan):** Blog teknik produksi dari tim rekayasa industri (Netflix, Cloudflare, Uber, Stripe). +3. **Tier 3 (Perlu Verifikasi Lanjutan):** Thread forum komunitas dan tutorial opini pribadi. +4. **Aturan Mutlak Triangulasi:** Setiap keputusan arsitektural krusial wajib didukung oleh sekurang-kurangnya 2 sumber Tier 1/2 independen. + +#### 4. Format Laporan Riset Terstruktur (Evidence Dossier) +Setiap ringkasan intelijen riset wajib disusun dalam format markdown berikut: +```markdown +# [Topik Riset] — Laporan Riset Mendalam & Graf Bukti + +## Ringkasan Eksekutif +- Sintesis ringkas 3-5 poin keputusan utama. + +## Matriks Bukti Teknis +| Klaim Teknis | Status Validasi | Skor Keyakinan | Sumber Primer | Sumber Pendukung | +|---|---|---|---|---| +| Penjelasan Klaim | Terverifikasi / Dibantah | 95% | [Sumber A](url) | [Sumber B](url) | + +## Analisis Komparatif & Risiko Kunci +- Trade-off latensi, batas memori, konsumsi biaya, atau kurva migrasi. + +## Keputusan Arsitektur yang Direkomendasikan +- Arahan preskriptif untuk tim pengembang dengan justifikasi berbasis bukti. +``` \ No newline at end of file diff --git a/vibes-plug/skills/dependency-upgrade-migrator/SKILL.md b/vibes-plug/skills/dependency-upgrade-migrator/SKILL.md new file mode 100644 index 000000000..a605e85ff --- /dev/null +++ b/vibes-plug/skills/dependency-upgrade-migrator/SKILL.md @@ -0,0 +1,380 @@ +--- +name: dependency-upgrade-migrator +description: "Expert guide for dependency upgrades, breaking change migrations, codemod automation, and package audit remediation / Panduan ahli untuk upgrade dependensi, migrasi breaking change, otomasi codemod, dan remediasi audit paket." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Dependency Upgrade Migrator (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Production-grade guide for safely upgrading dependencies, migrating through breaking changes, and maintaining healthy dependency trees. Covers **automated upgrade tooling** (`npm-check-updates`, `taze`, Renovate Bot), **major framework migration guides** (React 18→19, Next.js 14→15, Tailwind v3→v4), **codemod automation** (jscodeshift, ts-morph), **vulnerability remediation** (`npm audit`, `pnpm audit`), **lockfile hygiene**, **monorepo alignment** (pnpm catalogs), and **breaking change detection workflows**. + +### Trigger Conditions +Activate this skill when: +- Upgrading major versions of frameworks (React, Next.js, Tailwind, etc.). +- Running security audits and remediating vulnerabilities. +- Setting up automated dependency update bots (Renovate, Dependabot). +- Writing or running codemods for API migration. +- Cleaning up dependency trees and removing unused packages. +- Aligning dependency versions across monorepo packages. + +--- + +### 1. Upgrade Strategy Matrix + +| Upgrade Type | Risk Level | Strategy | Tools | +|---|---|---|---| +| **Patch** (1.0.x) | 🟢 Low | Auto-merge after tests pass | Renovate, Dependabot | +| **Minor** (1.x.0) | 🟡 Medium | Auto-merge with manual review | Renovate + test suite | +| **Major** (x.0.0) | 🔴 High | Manual review, migration guide, branch | Manual + codemods | +| **Security** (any) | 🔴 Critical | Immediate upgrade, hotfix | `npm audit fix`, manual | + +--- + +### 2. Pre-Upgrade Checklist + +```markdown +- [ ] Run `pnpm audit` / `npm audit` to identify vulnerabilities +- [ ] Check changelog/migration guide for the target version +- [ ] Ensure test suite is passing on current version (baseline) +- [ ] Create a dedicated branch for the upgrade +- [ ] Check peer dependency compatibility +- [ ] Review breaking changes list +- [ ] Identify files that need codemod transformation +- [ ] Back up lockfile before changes +``` + +--- + +### 3. Automated Upgrade Tooling + +#### Checking for Updates +```bash +# Using taze (recommended — supports monorepos) +npx taze major # Show available major upgrades +npx taze minor -w # Auto-write minor updates to package.json +npx taze -r # Recursive (monorepo) + +# Using npm-check-updates +npx ncu # Show available updates +npx ncu -u # Auto-write updates to package.json +npx ncu --target minor # Only show minor updates +``` + +#### Renovate Bot Configuration +```json +// renovate.json +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:best-practices"], + "labels": ["dependencies"], + "schedule": ["after 10pm and before 5am every weekday"], + "packageRules": [ + { + "matchUpdateTypes": ["patch"], + "automerge": true, + "automergeType": "pr" + }, + { + "matchUpdateTypes": ["minor"], + "automerge": true, + "automergeType": "pr", + "requiredStatusChecks": ["ci/test", "ci/build"] + }, + { + "matchUpdateTypes": ["major"], + "automerge": false, + "labels": ["major-upgrade", "manual-review"] + }, + { + "matchPackageNames": ["typescript", "react", "next"], + "automerge": false, + "labels": ["core-dependency"] + } + ] +} +``` + +--- + +### 4. Major Framework Migration Guides + +#### React 18 → 19 +```typescript +// Key breaking changes: +// 1. forwardRef no longer needed (ref is a regular prop) +// ❌ Before (React 18) +const Input = forwardRef((props, ref) => ( + +)); + +// ✅ After (React 19) +function Input({ ref, ...props }: Props & { ref?: React.Ref }) { + return ; +} + +// 2. useActionState replaces useFormState +// ❌ Before: import { useFormState } from 'react-dom' +// ✅ After: import { useActionState } from 'react' + +// 3. use() hook for promises and context +// ✅ New: const data = use(fetchPromise); +// ✅ New: const theme = use(ThemeContext); +``` + +#### Next.js 14 → 15 +```typescript +// Key changes: +// 1. params/searchParams are now async in page/layout/route +// ❌ Before: export default function Page({ params }: { params: { id: string } }) +// ✅ After: export default async function Page({ params }: { params: Promise<{ id: string }> }) { +// const { id } = await params; + +// 2. Caching: fetch() no longer cached by default +// ❌ Before: fetch() was cached by default +// ✅ After: fetch(url, { cache: 'force-cache' }) for explicit caching + +// 3. Route handlers: GET is no longer cached by default +// Add: export const dynamic = 'force-static' if you want caching +``` + +#### Tailwind CSS v4 → v4 +```css +/* Key changes: */ +/* 1. Configuration moves from JS to CSS */ +/* ❌ Before: tailwind.config.js with theme.extend */ +/* ✅ After: @theme directive in CSS */ + +@import 'tailwindcss'; + +@theme { + --color-primary: oklch(0.6 0.2 260); + --font-sans: 'Inter', sans-serif; + --breakpoint-sm: 40rem; +} + +/* 2. No more @tailwind directives */ +/* ❌ Before: @tailwind base; @tailwind components; @tailwind utilities; */ +/* ✅ After: @import 'tailwindcss'; */ + +/* 3. Renamed utilities */ +/* ❌ Before: bg-opacity-50 */ +/* ✅ After: bg-black/50 */ +``` + +--- + +### 5. Codemod Automation (jscodeshift) + +```typescript +// codemods/remove-forward-ref.ts +import type { API, FileInfo } from 'jscodeshift'; + +export default function removeForwardRef(fileInfo: FileInfo, api: API) { + const j = api.jscodeshift; + const root = j(fileInfo.source); + + // Find all forwardRef calls and transform them + root.find(j.CallExpression, { + callee: { name: 'forwardRef' }, + }).forEach((path) => { + // Extract the inner component function + const args = path.node.arguments; + if (args.length > 0 && (args[0].type === 'ArrowFunctionExpression' || args[0].type === 'FunctionExpression')) { + // Replace forwardRef(...) with the inner function + j(path).replaceWith(args[0]); + } + }); + + // Remove forwardRef import + root.find(j.ImportSpecifier, { imported: { name: 'forwardRef' } }).remove(); + + return root.toSource({ quote: 'single' }); +} + +// Run: npx jscodeshift -t codemods/remove-forward-ref.ts src/ --extensions=tsx,ts +``` + +--- + +### 6. Vulnerability Remediation + +```bash +# Audit current state +pnpm audit # Show vulnerabilities +pnpm audit --fix # Auto-fix where possible + +# For stubborn transitive dependencies +pnpm patch @ # Create a local patch +# or +pnpm overrides # Force specific version in package.json + +# package.json — Force resolution +{ + "pnpm": { + "overrides": { + "vulnerable-package": ">=2.0.0" + } + } +} +``` + +--- + +### 7. Dependency Cleanup + +```bash +# Find unused dependencies +npx depcheck # Detect unused deps +npx depcheck --ignores="@types/*" # Ignore type packages + +# Find duplicate packages +pnpm dedupe # Deduplicate lockfile +pnpm why # See why a package is installed + +# Monorepo: Align versions with pnpm catalogs +# pnpm-workspace.yaml +catalog: + react: "^19.0.0" + typescript: "^5.7.0" + "@tanstack/react-query": "^5.60.0" +``` + +--- + +### Common Pitfalls to Avoid + +| Anti-Pattern | Problem | Correct Approach | +|---|---|---| +| Upgrading all deps at once | Hard to identify breaking changes | Upgrade one major dep at a time | +| Ignoring peer dependency warnings | Runtime errors, subtle bugs | Resolve all peer dep conflicts | +| No test suite before upgrading | Can't verify nothing broke | Ensure tests pass before AND after | +| `npm audit fix --force` blindly | Can introduce breaking changes | Review each fix manually for major bumps | +| Skipping changelogs | Missing breaking changes | Always read CHANGELOG/migration guide | +| No lockfile in version control | Non-reproducible builds | Always commit `pnpm-lock.yaml` | + +--- + +### Integration with Other Skills + +- `monorepo-architect` — pnpm catalogs, workspace dependency alignment +- `zero-tech-debt-auditor` — Post-upgrade cleanup, dead code removal +- `production-ready-hardener` — Security audit phase +- `ci-cd-devops-architect` — Renovate Bot CI/CD integration +- `e2e-testing-expert` — Regression testing after major upgrades + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Deskripsi +Panduan tingkat produksi untuk upgrade dependensi yang aman, migrasi melalui breaking change, dan pemeliharaan dependency tree yang sehat. Mencakup **tooling upgrade otomatis** (`taze`, Renovate Bot), **panduan migrasi framework utama** (React 18→19, Next.js 14→15, Tailwind v3→v4), **otomasi codemod** (jscodeshift, ts-morph), **remediasi kerentanan** (`pnpm audit`), **kebersihan lockfile**, dan **penyelarasan dependensi monorepo** (pnpm catalogs). + +### Kondisi Pemicu +Aktifkan skill ini ketika: +- Mengupgrade versi mayor framework (React, Next.js, Tailwind, dll). +- Menjalankan audit keamanan dan memperbaiki kerentanan paket. +- Menyiapkan bot update dependensi otomatis (Renovate, Dependabot). +- Menulis atau menjalankan codemod untuk refaktor API usang secara massal. +- Membersihkan dependency tree dan menghapus paket yang tidak lagi terpakai. + +--- + +### Matriks Strategi Upgrade Dependensi + +| Tipe Upgrade | Tingkat Risiko | Strategi Penanganan | Tooling yang Dianjurkan | +|---|---|---|---| +| **Patch** (1.0.x) | 🟢 Rendah | Auto-merge setelah seluruh test suite lulus | Renovate, Dependabot | +| **Minor** (1.x.0) | 🟡 Sedang | Auto-merge dengan review PR singkat | Renovate + CI pipeline test | +| **Mayor** (x.0.0) | 🔴 Tinggi | Review manual, pelajari changelog, branch terpisah | Manual + Codemod AST | +| **Keamanan** (CVE) | 🔴 Kritis | Upgrade darurat dan rilis hotfix langsung | `pnpm audit --fix` / manual patch | + +--- + +### Resep & Panduan Migrasi Kunci + +#### 1. Tooling Pemindaian Upgrade (`taze`) +```bash +# Tampilkan upgrade versi mayor yang tersedia di workspace +npx taze major + +# Tulis otomatis pembaruan minor ke package.json +npx taze minor -w + +# Jalankan pemindaian secara rekursif di seluruh paket monorepo +npx taze -r +``` + +#### 2. Konfigurasi Renovate Bot Otomatis (`renovate.json`) +```json +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:best-practices"], + "labels": ["dependencies"], + "packageRules": [ + { + "matchUpdateTypes": ["patch"], + "automerge": true, + "automergeType": "pr" + }, + { + "matchUpdateTypes": ["minor"], + "automerge": true, + "requiredStatusChecks": ["ci/test", "ci/build"] + }, + { + "matchUpdateTypes": ["major"], + "automerge": false, + "labels": ["major-upgrade", "manual-review"] + } + ] +} +``` + +#### 3. Ringkasan Migrasi Framework Utama (2026 Standard) +- **React 18 ke 19**: `forwardRef` tidak lagi dibutuhkan (prop `ref` diteruskan seperti prop biasa). `useActionState` menggantikan `useFormState`. Hook `use()` dapat membaca promise dan React Context secara langsung. +- **Next.js 14 ke 15**: Parameter `params` dan `searchParams` pada page/layout/route kini bersifat asinkron (`Promise<{ id: string }>`). Default `fetch()` tidak lagi di-cache secara otomatis (`cache: 'force-cache'` harus dideklarasikan secara eksplisit jika diinginkan). +- **Tailwind CSS v3 ke v4**: Konfigurasi berpindah dari `tailwind.config.js` ke CSS native melalui direktif `@theme`. Direktif lama `@tailwind base;` diganti dengan `@import 'tailwindcss';`. + +#### 4. Otomasi Codemod Menghapus `forwardRef` Menggunakan `jscodeshift` +```typescript +// codemods/hapus-forward-ref.ts +import type { API, FileInfo } from 'jscodeshift'; + +export default function transform(fileInfo: FileInfo, api: API) { + const j = api.jscodeshift; + const root = j(fileInfo.source); + + root.find(j.CallExpression, { + callee: { name: 'forwardRef' }, + }).forEach((path) => { + const args = path.node.arguments; + if (args.length > 0) { + j(path).replaceWith(args[0]); + } + }); + + root.find(j.ImportSpecifier, { imported: { name: 'forwardRef' } }).remove(); + return root.toSource({ quote: 'single' }); +} +``` + +### Jebakan Umum yang Wajib Dihindari +- **Mengupgrade Seluruh Dependensi Sekaligus**: Sulit melacak sumber error saat build rusak. Upgrade dependensi mayor satu per satu. +- **Mengabaikan Peringatan Peer Dependencies**: Menimbulkan konflik runtime tersembunyi. +- **Menjalankan `npm audit fix --force` Secara Membabi Buta**: Dapat memaksa install versi mayor yang merusak kode aplikasi. \ No newline at end of file diff --git a/vibes-plug/skills/design-system-architect/SKILL.md b/vibes-plug/skills/design-system-architect/SKILL.md new file mode 100644 index 000000000..dee4d0131 --- /dev/null +++ b/vibes-plug/skills/design-system-architect/SKILL.md @@ -0,0 +1,528 @@ +--- +name: design-system-architect +description: "Expert guide for designing, building, and maintaining scalable UI design systems with design tokens, headless primitives, Material Design 3 (M3), Tailwind v4 @theme, and WCAG 2.2 accessibility." +author: "Roedy Rustam" + +version: "4.3.0" +--- + +# Design System Architect (2026 Edition — shadcn/ui Registry) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Expert guide for building and maintaining scalable UI design systems. Covers design tokens with OKLCH and Tailwind v4 `@theme`, **Material Design 3 (M3)** integration, headless component primitives (Radix UI, **Base UI 1.x**), **shadcn/ui registry** for distributable component libraries, CVA for type-safe variants, and WCAG 2.2 accessibility compliance. + +### Trigger Conditions +- Building a shared UI component library from scratch. +- Setting up design tokens (colors, typography, spacing) with Tailwind v4. +- Applying Material Design 3 (M3) principles (https://m3.material.io/). +- Using headless primitives (Radix UI, Base UI 1.x) with custom styling. +- Distributing components via the **shadcn/ui registry** format. +- Auditing a component library for WCAG 2.2 accessibility compliance. +- Enforcing `anti-slop` quality standards on component primitives and tokens. + +### Anti-Slop Component Design Contract +- **Zero Div-Soup Primitives**: Build exclusively on accessible headless primitives (Radix UI, Base UI 1.x) using semantic HTML (` + + ); +} +``` + +### 3 Hukum Keamanan Mutlak Electron +1. **Wajib Context Isolation**: `contextIsolation: true` wajib aktif agar skrip halaman web tidak dapat mengakses atau memodifikasi objek internal Node.js di preload script. +2. **Matikan nodeIntegration di Renderer**: `nodeIntegration: false` mutlak ditegakkan. Renderer dilarang mengimpor modul `fs`, `child_process`, atau `crypto` secara langsung. +3. **Sandbox Chromium Aktif**: Selalu nyalakan `sandbox: true` untuk membatasi akses proses renderer ke tingkat kernel sistem operasi. + +## Integrasi Orkestrasi +- **`tauri-expert`**: Menjadi acuan pembanding jika pengguna mempertimbangkan framework alternatif berbasis Rust. +- **`senior-frontend`**: Menyediakan arsitektur komponen UI yang responsif di dalam window aplikasi. +- **`ci-cd-devops-architect`**: Menangani penandatanganan sertifikat digital (*code signing*) pada pipeline rilis. +- **`error-resilience-expert`**: Mencegah aplikasi tertutup tiba-tiba (*crash*) saat terjadi unhandled error di Main process. \ No newline at end of file diff --git a/vibes-plug/skills/docker-container-expert/SKILL.md b/vibes-plug/skills/docker-container-expert/SKILL.md new file mode 100644 index 000000000..87f155060 --- /dev/null +++ b/vibes-plug/skills/docker-container-expert/SKILL.md @@ -0,0 +1,259 @@ +--- +name: docker-container-expert +description: "Expert guide for production Docker containerization, multi-stage BuildKit builds, rootless execution, distroless runtimes, container security hardening, and Docker Compose v2 topology / Panduan ahli kontainerisasi Docker produksi, multi-stage BuildKit, rootless, distroless, dan Docker Compose v2." +author: "Roedy Rustam" +version: "4.4.0" +--- + +# Docker Container Expert (Production Standard 2026) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects with: `brainstorming`, `zero-to-prod-orchestrator`, `ci-cd-devops-architect`, `github-actions-expert`, `js-backend-expert`, `python-programming-expert`, `go-programming-expert`, `rust-programming-expert`, `database-orm-expert`, `production-ready-hardener`, `session-memory-manager`. + +### Description +Enterprise guide for building ultra-lean, hardened, and reproducible container images and orchestrating local and production workloads with **Docker Engine 27+** and **Docker Compose v2**. Covers BuildKit cache mounts (`--mount=type=cache`), secret mounts (`--mount=type=secret`), multi-stage builds targeting Google Distroless or Alpine Linux, non-root execution (UID 65532), dropping Linux kernel capabilities (`cap_drop: ALL`), health checks (`HEALTHCHECK`), internal isolated bridge networks, compose dependency sequencing (`condition: service_healthy`), and multi-architecture builds via `docker buildx`. + +### Trigger Conditions +- Writing, refactoring, or optimizing `Dockerfile` manifests for Node.js, Python, Go, Rust, or Bun. +- Structuring multi-container local and staging topologies with `compose.yaml`. +- Accelerating build speeds using Docker BuildKit cache mounts and layer ordering. +- Minimizing image attack surface: eliminating shell binaries, package managers, and root permissions. +- Hardening container security: dropping Linux capabilities, setting read-only filesystems, and enforcing memory/CPU limits. +- Configuring robust health checks and zero-downtime container lifecycle management. + +### What's New in 2026 (Modern Containerization Standards) + +#### 1. BuildKit as the De Facto Engine +- Always specify `# syntax=docker/dockerfile:1.7` at the top of the Dockerfile. +- Use `--mount=type=cache` for package manager caches (`/root/.local/share/pnpm/store`, `/root/.cache/pip`, `/var/cache/apt`). +- Use `--mount=type=secret,id=npmrc` to inject credentials without leaving traces in image layers. + +#### 2. Rootless & Distroless Execution +- Never run containers as `root` (UID 0). Use Google Distroless `nonroot` (UID 65532) or explicitly created system users with no shell (`/sbin/nologin`). +- Discard build tools (`gcc`, `npm`, `cargo`) completely in intermediate build stages. + +#### 3. Compose Specification Standard +- Standard filename is `compose.yaml` (preferred over deprecated `docker-compose.yml`). +- Explicit health checks with dependency conditions (`depends_on: service: condition: service_healthy`). +- Strict resource reservations and limits (CPU and memory envelopes). + +--- + +### Core Architecture Patterns + +#### Pattern 1: Production Multi-Stage Distroless Node.js Dockerfile (`Dockerfile`) + +```dockerfile +# syntax=docker/dockerfile:1.7 +# Stage 1: Dependency resolution and compilation +FROM node:22-alpine AS builder +WORKDIR /app + +# Enable pnpm deterministically via corepack +RUN corepack enable && corepack prepare pnpm@9.15.4 --activate + +# Layer caching: copy package manifests first +COPY package.json pnpm-lock.yaml ./ + +# Install dependencies using persistent BuildKit cache mount +RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store \ + pnpm install --frozen-lockfile + +# Copy application source code +COPY . . + +# Build production bundle and prune development dependencies +RUN pnpm run build && pnpm prune --prod + +# Stage 2: Minimal hardened production runner (Zero Shell, Zero Package Manager) +FROM gcr.io/distroless/nodejs22-debian12:nonroot AS runner +WORKDIR /app + +# Run strictly as unprivileged user (UID 65532) +USER nonroot + +# Copy build artifacts and production dependencies with nonroot ownership +COPY --from=builder --chown=nonroot:nonroot /app/node_modules ./node_modules +COPY --from=builder --chown=nonroot:nonroot /app/dist ./dist +COPY --from=builder --chown=nonroot:nonroot /app/package.json ./package.json + +ENV NODE_ENV=production +ENV PORT=3000 + +EXPOSE 3000 + +# Execute Node.js directly (no shell wrapper) +CMD ["dist/index.js"] +``` + +--- + +#### Pattern 2: Ultra-Minimal Static Go/Rust Binary Container (`Dockerfile.go`) + +```dockerfile +# syntax=docker/dockerfile:1.7 +# Stage 1: Compile static binary +FROM golang:1.24-alpine AS builder +WORKDIR /src + +RUN apk add --no-cache ca-certificates tzdata + +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod \ + go mod download + +COPY . . + +# Compile static binary without CGO dependency +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ + go build -ldflags="-w -s" -o /bin/server ./cmd/server + +# Stage 2: Scratch container (Zero attack surface, < 15MB total size) +FROM scratch +WORKDIR /app + +# Import SSL root certificates and timezone data from builder +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo +COPY --from=builder /bin/server /app/server + +# Run as non-root user ID +USER 65532:65532 + +EXPOSE 8080 + +ENTRYPOINT ["/app/server"] +``` + +--- + +#### Pattern 3: Production-Grade Multi-Service `compose.yaml` + +```yaml +services: + database: + image: postgres:17-alpine + container_name: production_db + restart: unless-stopped + environment: + POSTGRES_DB: app_production + POSTGRES_USER: app_admin + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: + - db_password + volumes: + - pgdata:/var/lib/postgresql/data + networks: + - internal_backend + healthcheck: + test: ["CMD-SHELL", "pg_isready -U app_admin -d app_production"] + interval: 5s + timeout: 5s + retries: 5 + start_period: 10s + deploy: + resources: + limits: + cpus: '2.0' + memory: 2048M + reservations: + cpus: '0.5' + memory: 512M + + cache: + image: redis:7-alpine + container_name: production_cache + restart: unless-stopped + command: ["redis-server", "--appendonly", "yes", "--requirepass", "cache_secure_token"] + volumes: + - redisdata:/data + networks: + - internal_backend + healthcheck: + test: ["CMD", "redis-cli", "-a", "cache_secure_token", "ping"] + interval: 5s + timeout: 3s + retries: 3 + deploy: + resources: + limits: + cpus: '1.0' + memory: 512M + + api: + build: + context: . + dockerfile: Dockerfile + container_name: production_api + restart: unless-stopped + environment: + NODE_ENV: production + PORT: 3000 + DATABASE_URL: postgresql://app_admin:secret@database:5432/app_production + REDIS_URL: redis://:cache_secure_token@cache:6379 + ports: + - "3000:3000" + networks: + - internal_backend + - public_ingress + depends_on: + database: + condition: service_healthy + cache: + condition: service_healthy + deploy: + resources: + limits: + cpus: '1.5' + memory: 1024M + +networks: + internal_backend: + internal: true + public_ingress: + driver: bridge + +volumes: + pgdata: + redisdata: + +secrets: + db_password: + file: ./secrets/db_password.txt +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dengan: `brainstorming`, `zero-to-prod-orchestrator`, `ci-cd-devops-architect`, `github-actions-expert`, `js-backend-expert`, `python-programming-expert`, `go-programming-expert`, `rust-programming-expert`, `database-orm-expert`, `production-ready-hardener`, `session-memory-manager`. + +### Deskripsi +Panduan standar industri enterprise untuk membangun image kontainer yang ramping, aman, dan dapat direproduksi serta mengorkestrasi lingkungan lokal dan produksi menggunakan **Docker Engine 27+** dan **Docker Compose v2**. Meliputi cache mount BuildKit (`--mount=type=cache`), secret mount (`--mount=type=secret`), multi-stage build berbasis Google Distroless atau Alpine Linux, eksekusi non-root (UID 65532), pelepasan kapabilitas Linux kernel (`cap_drop: ALL`), health check (`HEALTHCHECK`), isolasi jaringan internal (isolated bridge network), sequencing dependensi compose (`condition: service_healthy`), dan build multi-arsitektur menggunakan `docker buildx`. + +### Kondisi Pemicu (Trigger Conditions) +- Menulis, merefaktor, atau mengoptimalkan `Dockerfile` untuk Node.js, Python, Go, Rust, atau Bun. +- Menyusun topologi multi-kontainer untuk lingkungan lokal atau staging menggunakan `compose.yaml`. +- Mempercepat build image dengan memanfaatkan BuildKit cache mount dan pengurutan layer yang optimal. +- Memperkecil permukaan serangan (attack surface) image: menghapus shell bash/sh, package manager, dan akses root. +- Memperketat keamanan kontainer: mencabut kemampuan Linux berlebih, filesystem read-only, dan limitasi resource CPU/RAM. +- Menyiapkan health check yang andal untuk manajemen siklus hidup kontainer tanpa downtime. + +### Aturan Emas Kontainerisasi Modern 2026 + +1. **Dilarang Menjalankan Kontainer Sebagai Root**: Selalu gunakan user tanpa hak istimewa seperti `nonroot` (UID 65532 pada Google Distroless) untuk mencegah potensi container breakout ke host system. +2. **Multi-Stage Build Bersih**: Pisahkan lingkungan kompilasi/build (yang memerlukan compiler dan devDependencies) dari lingkungan runtime produksi. Image akhir hanya berisi artefak biner murni atau bundle yang siap dieksekusi. +3. **Pemanfaatan Cache Mount BuildKit**: Gunakan sintaks `# syntax=docker/dockerfile:1.7` dan opsi `--mount=type=cache` agar unduhan dependensi paket tidak diulang setiap kali ada perubahan kode sumber. +4. **Healthcheck & Urutan Dependensi**: Selalu definisikan mekanisme pemeriksaan kesehatan kontainer dan gunakan `depends_on: [service]: condition: service_healthy` pada `compose.yaml` untuk mencegah race condition saat database belum siap menerima koneksi. +5. **Isolasi Jaringan Internal**: Letakkan database dan cache pada jaringan internal dengan flag `internal: true` sehingga tidak dapat diakses secara langsung dari luar jaringan kontainer. diff --git a/vibes-plug/skills/documentation-site-expert/SKILL.md b/vibes-plug/skills/documentation-site-expert/SKILL.md new file mode 100644 index 000000000..86b603d9b --- /dev/null +++ b/vibes-plug/skills/documentation-site-expert/SKILL.md @@ -0,0 +1,960 @@ +--- +name: documentation-site-expert +description: "Expert guide for technical documentation sites (Mintlify, Docusaurus, Storybook, VitePress) and component documentation / Panduan ahli situs dokumentasi teknis (Mintlify, Docusaurus, Storybook, VitePress) dan dokumentasi komponen." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Documentation Site Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +- **`openapi-swagger-codegen-expert`**: Auto-generate API reference pages from OpenAPI 3.1 specs. +- **`design-system-architect`**: Component documentation and design token references with Storybook. +- **`astro-framework-expert`**: Astro Starlight as a full-featured docs site platform. +- **`seo`**: Documentation SEO — canonical URLs, sitemap.xml, structured data, and GEO. +- **`ci-cd-devops-architect`**: Automated deployment pipelines to Vercel, Cloudflare Pages, GitHub Pages. +- **`senior-frontend`**: Custom MDX components, interactive playgrounds, and React-based doc UIs. +- **`search-engine-expert`**: Algolia DocSearch, Pagefind, and Typesense integration for doc search. +- **`global-a11y-i18n-expert`**: i18n multi-language documentation and WCAG-compliant doc sites. + +### Description +Expert guide for building production-grade technical documentation sites and component libraries. Covers **Mintlify** (AI-native SaaS docs), **Docusaurus 3** (React/OSS), **Storybook 8** (component playground), **VitePress 2** (Vue-powered), and **Astro Starlight** (content-heavy i18n). Includes API reference generation, versioning strategies, search integration, Chromatic visual testing, and CI/CD deployment workflows. + +### Trigger Conditions +- Creating documentation sites for APIs, libraries, or SaaS products. +- Setting up Storybook for component documentation and visual regression. +- Choosing a documentation framework for an open-source project. +- Generating API reference docs from OpenAPI specs. +- Migrating from legacy docs (GitBook, Confluence, readme.io) to modern static sites. +- Adding versioning, search, or i18n to an existing documentation site. + +--- + +### Framework Selection Matrix + +| Framework | Stack | AI Search | Versioning | i18n | Best For | +|----------------|--------------|--------------|------------|------|----------------------------------| +| Mintlify | React / MDX | ✅ AI Native | ✅ | ✅ | SaaS API docs, commercial products | +| Docusaurus 3 | React / MDX | ✅ Algolia | ✅ | ✅ | Open-source projects | +| Storybook 8 | Any framework| ❌ | ❌ | ❌ | UI component library playground | +| VitePress 2 | Vue / MD | ✅ Built-in | ❌ | ✅ | Vue ecosystem / library docs | +| Astro Starlight| Astro / MDX | ✅ Pagefind | ✅ | ✅ | Content-heavy multi-lang docs | + +**Decision Rule:** +- SaaS product → **Mintlify** (zero-config, AI search, API playground) +- OSS library → **Docusaurus** (versioning + Algolia + community plugins) +- Component library → **Storybook** (visual testing + interactions + Chromatic) +- Vue project → **VitePress** (native Vue integration, blazing fast) +- Content-heavy / i18n-first → **Astro Starlight** (Pagefind, i18n routing) + +--- + +## 1. Mintlify + +### `mint.json` — Complete Configuration + +```json +{ + "name": "Acme API", + "logo": { + "light": "/logo/light.svg", + "dark": "/logo/dark.svg" + }, + "favicon": "/favicon.svg", + "colors": { + "primary": "#0D9373", + "light": "#07C983", + "dark": "#0D9373", + "anchors": { "from": "#0D9373", "to": "#07C983" } + }, + "topbarLinks": [ + { "name": "Support", "url": "mailto:support@acme.com" } + ], + "topbarCtaButton": { + "name": "Dashboard", + "url": "https://app.acme.com" + }, + "tabs": [ + { "name": "API Reference", "url": "api-reference" } + ], + "anchors": [ + { "name": "Changelog", "icon": "list", "url": "changelog" }, + { "name": "GitHub", "icon": "github", "url": "https://github.com/acme/api" } + ], + "navigation": [ + { + "group": "Getting Started", + "pages": ["introduction", "quickstart", "authentication"] + }, + { + "group": "Guides", + "pages": ["guides/webhooks", "guides/pagination", "guides/rate-limits"] + }, + { + "group": "API Reference", + "pages": ["api-reference/introduction", "api-reference/endpoints/users", "api-reference/endpoints/payments"] + } + ], + "openapi": "https://api.acme.com/openapi.json", + "api": { + "baseUrl": "https://api.acme.com/v1", + "auth": { + "method": "bearer" + }, + "playground": { "mode": "show" } + }, + "feedback": { "thumbsRating": true, "suggestEdit": true }, + "search": { "prompt": "Search Acme docs..." }, + "footerSocials": { + "twitter": "https://twitter.com/acme", + "github": "https://github.com/acme" + } +} +``` + +### MDX Authoring with Custom Components + +```mdx +--- +title: "Authentication" +description: "Secure your API requests with Bearer tokens." +--- + +import { Note, Warning, CodeGroup } from 'mintlify/components'; + + + All API requests require an `Authorization: Bearer ` header. + + + + Never expose your API secret in client-side code or version control. + + +## Obtaining an API Key + +Navigate to **Settings → API Keys** in your dashboard and click **Create Key**. + + +```bash cURL +curl https://api.acme.com/v1/users \ + -H "Authorization: Bearer $ACME_API_KEY" +``` + +```typescript TypeScript +import AcmeClient from '@acme/sdk'; + +const client = new AcmeClient({ apiKey: process.env.ACME_API_KEY }); +const users = await client.users.list(); +``` + +``` + +### API Playground Auto-Generation from OpenAPI + +```bash +# Mintlify CLI — scrape OpenAPI and generate MDX stubs +npm install -g mintlify +mintlify dev # local preview at http://localhost:3000 +mintlify scrape # auto-generate pages from openapi field in mint.json +``` + +Mintlify reads the `"openapi"` field in `mint.json` and auto-generates interactive API reference pages with a live request playground, response schema viewer, and try-it UI — zero additional MDX authoring required. + +--- + +## 2. Docusaurus 3 + +### `docusaurus.config.ts` — Production-Ready Example + +```typescript +import type { Config } from '@docusaurus/types'; +import type * as Preset from '@docusaurus/preset-classic'; + +const config: Config = { + title: 'Acme Docs', + tagline: 'The fastest way to build on Acme', + favicon: 'img/favicon.ico', + url: 'https://docs.acme.com', + baseUrl: '/', + organizationName: 'acme', + projectName: 'acme-docs', + onBrokenLinks: 'throw', + onBrokenMarkdownLinks: 'warn', + i18n: { + defaultLocale: 'en', + locales: ['en', 'id', 'ja'], + }, + presets: [ + [ + 'classic', + { + docs: { + sidebarPath: './sidebars.ts', + editUrl: 'https://github.com/acme/docs/tree/main/', + showLastUpdateTime: true, + showLastUpdateAuthor: true, + versions: { + current: { label: 'v3 (Next)', path: 'next', banner: 'unreleased' }, + }, + lastVersion: 'v2', + }, + blog: { + showReadingTime: true, + feedOptions: { type: ['rss', 'atom'], xslt: true }, + }, + theme: { + customCss: './src/css/custom.css', + }, + sitemap: { changefreq: 'weekly', priority: 0.5 }, + } satisfies Preset.Options, + ], + ], + plugins: [ + [ + 'docusaurus-plugin-openapi-docs', + { + id: 'api', + docsPluginId: 'classic', + config: { + acme: { + specPath: 'openapi/acme.yaml', + outputDir: 'docs/api', + sidebarOptions: { groupPathsBy: 'tag', categoryLinkSource: 'tag' }, + }, + }, + }, + ], + ['@docusaurus/plugin-ideal-image', { max: 1030, min: 640, steps: 2 }], + ], + themeConfig: { + algolia: { + appId: 'YOUR_APP_ID', + apiKey: 'YOUR_SEARCH_API_KEY', + indexName: 'acme_docs', + contextualSearch: true, + searchPagePath: 'search', + }, + prism: { + theme: { plain: {}, styles: [] }, + additionalLanguages: ['bash', 'json', 'yaml', 'typescript'], + }, + navbar: { + title: 'Acme', + logo: { alt: 'Acme Logo', src: 'img/logo.svg' }, + items: [ + { type: 'docsVersionDropdown', position: 'left' }, + { type: 'localeDropdown', position: 'right' }, + { href: 'https://github.com/acme/docs', label: 'GitHub', position: 'right' }, + ], + }, + footer: { + style: 'dark', + links: [ + { title: 'Docs', items: [{ label: 'Getting Started', to: '/docs/intro' }] }, + { title: 'Community', items: [{ label: 'Discord', href: 'https://discord.gg/acme' }] }, + ], + copyright: `Copyright © ${new Date().getFullYear()} Acme, Inc.`, + }, + } satisfies Preset.ThemeConfig, +}; + +export default config; +``` + +### Versioning Strategy + +```bash +# Create a new versioned snapshot (freezes current /docs) +npm run docusaurus docs:version 2.0.0 + +# Resulting structure: +# versioned_docs/version-2.0.0/ ← frozen snapshot +# versioned_sidebars/version-2.0.0-sidebars.json +# versions.json ← ["2.0.0"] +# docs/ ← "next" (unreleased) +``` + +### Algolia DocSearch Integration + +```bash +# Request free DocSearch tier at: https://docsearch.algolia.com/apply +# Then install crawler config: +npm install @algolia/client-search +``` + +```javascript +// algolia-crawler-config.js (submitted to Algolia dashboard) +new Crawler({ + appId: 'YOUR_APP_ID', + apiKey: 'YOUR_WRITE_API_KEY', + rateLimit: 8, + startUrls: ['https://docs.acme.com/'], + renderJavaScript: false, + sitemaps: ['https://docs.acme.com/sitemap.xml'], + ignoreCanonicalTo: true, + discoveryPatterns: ['https://docs.acme.com/**'], + actions: [{ + indexName: 'acme_docs', + pathsToMatch: ['https://docs.acme.com/**'], + recordExtractor: ({ $, helpers }) => { + return helpers.docsearch({ + recordProps: { + lvl1: ['header h1', 'article h1', 'main h1'], + content: ['article p, article li', 'main p, main li'], + }, + indexHeadings: true, + }); + }, + }], + initialIndexSettings: { + acme_docs: { + attributesForFaceting: ['type', 'lang', 'version'], + attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'], + attributesToHighlight: ['hierarchy', 'content'], + attributesToSnippet: ['content:10'], + searchableAttributes: ['unordered(hierarchy.lvl0)', 'content'], + distinct: true, + attributeForDistinct: 'url', + ranking: ['words', 'filters', 'typo', 'attribute', 'proximity', 'exact', 'custom'], + }, + }, +}); +``` + +### MDX Plugins + +```bash +npm install remark-math rehype-katex remark-gfm rehype-mermaid +``` + +```typescript +// docusaurus.config.ts — add to docs preset options: +import remarkMath from 'remark-math'; +import rehypeKatex from 'rehype-katex'; + +// inside docs preset: +remarkPlugins: [remarkMath], +rehypePlugins: [rehypeKatex], +``` + +--- + +## 3. Storybook 8 + +### Installation & Autodocs + +```bash +# Initialize Storybook in an existing project +npx storybook@latest init + +# Start dev server +npm run storybook + +# Build static site +npm run build-storybook +``` + +### Story with Interaction Testing + +```typescript +// src/components/Button/Button.stories.ts +import type { Meta, StoryObj } from '@storybook/react'; +import { expect, userEvent, within } from '@storybook/test'; +import { Button } from './Button'; + +const meta = { + title: 'UI/Button', + component: Button, + tags: ['autodocs'], + argTypes: { + variant: { control: 'select', options: ['primary', 'secondary', 'ghost'] }, + size: { control: 'radio', options: ['sm', 'md', 'lg'] }, + disabled: { control: 'boolean' }, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Primary: Story = { + args: { variant: 'primary', size: 'md', children: 'Click me' }, +}; + +export const InteractionTest: Story = { + args: { variant: 'primary', children: 'Submit' }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const button = canvas.getByRole('button', { name: /submit/i }); + await userEvent.click(button); + await expect(button).toBeInTheDocument(); + }, +}; +``` + +### `.storybook/main.ts` — Addon Ecosystem + +```typescript +import type { StorybookConfig } from '@storybook/nextjs'; + +const config: StorybookConfig = { + stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'], + addons: [ + '@storybook/addon-onboarding', + '@storybook/addon-links', + '@storybook/addon-essentials', // Controls, Docs, Actions, Viewport, Backgrounds + '@storybook/addon-interactions', // play() function testing + '@storybook/addon-a11y', // Axe-core accessibility audit + '@chromatic-com/storybook', // Chromatic visual testing + '@storybook/addon-themes', // Light/Dark theme switching + ], + framework: { + name: '@storybook/nextjs', + options: {}, + }, + docs: { autodocs: 'tag' }, + staticDirs: ['../public'], +}; + +export default config; +``` + +### Chromatic Visual Testing + +```bash +npm install --save-dev chromatic + +# Run visual regression against baseline +npx chromatic --project-token= + +# CI flag — accept changes automatically on main branch +npx chromatic --project-token= --auto-accept-changes main +``` + +```yaml +# .github/workflows/chromatic.yml +name: Chromatic +on: push +jobs: + chromatic: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 0 } + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: 'npm' } + - run: npm ci + - name: Run Chromatic + uses: chromaui/action@v11 + with: + projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }} + exitZeroOnChanges: true +``` + +--- + +## 4. VitePress 2 + +### `docs/.vitepress/config.mts` + +```typescript +import { defineConfig } from 'vitepress'; + +export default defineConfig({ + lang: 'en-US', + title: 'Acme Library', + description: 'A powerful TypeScript utility library.', + lastUpdated: true, + cleanUrls: true, + srcDir: './src', + outDir: '../dist-docs', + + head: [ + ['link', { rel: 'icon', type: 'image/svg+xml', href: '/logo.svg' }], + ['meta', { name: 'theme-color', content: '#5f67ee' }], + ['meta', { property: 'og:type', content: 'website' }], + ], + + themeConfig: { + logo: '/logo.svg', + nav: [ + { text: 'Guide', link: '/guide/what-is-acme' }, + { text: 'Reference', link: '/reference/config' }, + { + text: 'v2.0', + items: [ + { text: 'v1.x Docs', link: 'https://v1.acme.dev' }, + { text: 'Changelog', link: '/changelog' }, + ], + }, + ], + sidebar: { + '/guide/': [ + { text: 'Introduction', items: [ + { text: 'What is Acme?', link: '/guide/what-is-acme' }, + { text: 'Getting Started', link: '/guide/getting-started' }, + ]}, + { text: 'Advanced', items: [ + { text: 'Configuration', link: '/guide/configuration' }, + { text: 'Plugin API', link: '/guide/plugin-api' }, + ]}, + ], + }, + editLink: { + pattern: 'https://github.com/acme/lib/edit/main/docs/src/:path', + text: 'Edit this page on GitHub', + }, + search: { provider: 'local' }, + socialLinks: [{ icon: 'github', link: 'https://github.com/acme/lib' }], + }, + + locales: { + root: { label: 'English', lang: 'en' }, + id: { label: 'Bahasa Indonesia', lang: 'id', link: '/id/', themeConfig: { + nav: [{ text: 'Panduan', link: '/id/guide/what-is-acme' }], + }}, + }, +}); +``` + +### Vue 3 Custom Theme Component + +```vue + + + + +``` + +```typescript +// docs/.vitepress/theme/index.ts +import DefaultTheme from 'vitepress/theme'; +import ApiPreview from './components/ApiPreview.vue'; +import type { Theme } from 'vitepress'; + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('ApiPreview', ApiPreview); + }, +} satisfies Theme; +``` + +--- + +## 5. Astro Starlight + +### Installation & Sidebar Config + +```bash +npm create astro@latest -- --template starlight +``` + +```typescript +// astro.config.mjs +import { defineConfig } from 'astro/config'; +import starlight from '@astrojs/starlight'; + +export default defineConfig({ + integrations: [ + starlight({ + title: 'Acme Docs', + logo: { src: './src/assets/logo.svg' }, + social: { github: 'https://github.com/acme/acme' }, + defaultLocale: 'root', + locales: { + root: { label: 'English', lang: 'en' }, + id: { label: 'Bahasa Indonesia', lang: 'id' }, + ja: { label: '日本語', lang: 'ja' }, + }, + sidebar: [ + { label: 'Start Here', items: [ + { label: 'Introduction', link: '/intro/' }, + { label: 'Installation', link: '/install/' }, + ]}, + { label: 'Guides', autogenerate: { directory: 'guides' } }, + { label: 'Reference', autogenerate: { directory: 'reference' } }, + ], + editLink: { baseUrl: 'https://github.com/acme/docs/edit/main/' }, + lastUpdated: true, + pagination: true, + tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 4 }, + customCss: ['./src/styles/custom.css'], + components: { + SiteTitle: './src/components/CustomSiteTitle.astro', + }, + }), + ], +}); +``` + +### Pagefind Search Configuration + +Starlight ships with **Pagefind** out of the box — zero config needed. Pagefind runs at build time and creates a client-side search index from your HTML output. + +```bash +# Build triggers Pagefind indexing automatically +npm run build + +# Pagefind index output: dist/pagefind/ +# Bundle size: ~8 KB JS + compressed index shards +``` + +### i18n MDX Page Structure + +``` +src/content/docs/ +├── intro.mdx ← English (root locale) +├── install.mdx +├── guides/ +│ └── quickstart.mdx +└── id/ ← Bahasa Indonesia + ├── intro.mdx + ├── install.mdx + └── guides/ + └── quickstart.mdx +``` + +```mdx +--- +# src/content/docs/id/intro.mdx +title: Pengantar +description: Selamat datang di dokumentasi Acme. +--- + +Acme adalah library TypeScript berkinerja tinggi untuk membangun pipeline data modern. + +## Fitur Utama + +- ⚡ **Performa tinggi** — dioptimalkan untuk throughput jutaan record per detik +- 🔒 **Type-safe** — dibangun dengan TypeScript strict mode +- 🧩 **Modular** — gunakan hanya modul yang Anda butuhkan +``` + +--- + +## 6. Content Architecture Best Practices + +### Versioning Strategy + +| Strategy | When to Use | Tool | +|----------|-------------|------| +| Path-based (`/v1/`, `/v2/`) | REST API with major breaking changes | Mintlify tabs, Docusaurus versions | +| Branch-based | Older maintained releases | `docusaurus docs:version` | +| Monorepo package versioning | Multi-package libs | Changesets + VitePress | +| Date-based | SDKs with frequent patch releases | Changelog + semver badges | + +### Changelog Automation with Changesets + +```bash +npm install --save-dev @changesets/cli @changesets/changelog-github +npx changeset init + +# Add a changeset (run after each PR) +npx changeset add + +# Release: bump versions + update CHANGELOG.md +npx changeset version +npx changeset publish +``` + +```json +// .changeset/config.json +{ + "$schema": "https://unpkg.com/@changesets/config/schema.json", + "changelog": ["@changesets/changelog-github", { "repo": "acme/lib" }], + "commit": false, + "fixed": [], + "linked": [], + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": [] +} +``` + +### API Reference via `openapi-typescript` + +```bash +npm install --save-dev openapi-typescript typescript + +# Generate types from live spec or local file +npx openapi-typescript https://api.acme.com/openapi.json -o src/types/api.d.ts +npx openapi-typescript ./openapi/acme.yaml -o src/types/api.d.ts +``` + +```typescript +// src/lib/api-client.ts — type-safe API client from generated types +import createClient from 'openapi-fetch'; +import type { paths } from '../types/api'; + +export const apiClient = createClient({ + baseUrl: 'https://api.acme.com/v1', + headers: { Authorization: `Bearer ${process.env.API_KEY}` }, +}); + +// Fully typed request — IDE autocomplete for paths, params, and response +const { data, error } = await apiClient.GET('/users/{id}', { + params: { path: { id: '123' } }, +}); +``` + +--- + +## 7. Deployment + +### Vercel (Recommended for Mintlify + Docusaurus + VitePress) + +```json +// vercel.json — Docusaurus / VitePress +{ + "buildCommand": "npm run build", + "outputDirectory": "build", + "framework": null, + "rewrites": [{ "source": "/(.*)", "destination": "/$1" }], + "headers": [ + { + "source": "/(.*)", + "headers": [ + { "key": "X-Content-Type-Options", "value": "nosniff" }, + { "key": "X-Frame-Options", "value": "DENY" }, + { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } + ] + } + ] +} +``` + +### Cloudflare Pages + +```yaml +# Build settings (Cloudflare Dashboard → Pages → Build & deployments) +# Build command: npm run build +# Output dir: build (Docusaurus) | dist (VitePress/Starlight) +# Node.js: 22.x +``` + +```toml +# wrangler.toml — for Workers + Pages hybrid +name = "acme-docs" +compatibility_date = "2026-01-01" + +[site] +bucket = "./build" +``` + +### GitHub Pages Workflow + +```yaml +# .github/workflows/deploy-docs.yml +name: Deploy Docs +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: { fetch-depth: 0 } + - uses: actions/setup-node@v4 + with: { node-version: 22, cache: 'npm' } + - run: npm ci + - run: npm run build + - uses: actions/upload-pages-artifact@v3 + with: { path: build } + + deploy: + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/deploy-pages@v4 + id: deployment +``` + +--- + +## Orchestration & Integration +- `openapi-swagger-codegen-expert` — API reference auto-generation +- `design-system-architect` — design token docs, Storybook integration +- `astro-framework-expert` — Starlight configuration +- `seo` — sitemap, canonical, structured data +- `ci-cd-devops-architect` — automated deployment pipelines +- `global-a11y-i18n-expert` — multi-language documentation +- `search-engine-expert` — Algolia, Pagefind, Typesense + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +- **`openapi-swagger-codegen-expert`**: Otomatisasi halaman referensi API dari spesifikasi OpenAPI 3.1. +- **`design-system-architect`**: Dokumentasi komponen dan referensi design token dengan Storybook. +- **`astro-framework-expert`**: Astro Starlight sebagai platform situs dokumentasi lengkap. +- **`seo`**: SEO dokumentasi — canonical URL, sitemap.xml, structured data, dan GEO. +- **`ci-cd-devops-architect`**: Pipeline deployment otomatis ke Vercel, Cloudflare Pages, GitHub Pages. +- **`senior-frontend`**: Komponen MDX kustom, playground interaktif, dan UI dokumentasi berbasis React. +- **`global-a11y-i18n-expert`**: Dokumentasi multi-bahasa i18n dan situs dokumentasi sesuai WCAG. + +### Deskripsi +Panduan ahli untuk membangun situs dokumentasi teknis tingkat produksi dan library komponen. Mencakup **Mintlify** (docs SaaS AI-native), **Docusaurus 3** (React/OSS), **Storybook 8** (playground komponen), **VitePress 2** (berbasis Vue), dan **Astro Starlight** (konten berat dengan i18n). Termasuk panduan generasi referensi API, strategi versioning, integrasi pencarian, pengujian visual Chromatic, dan workflow CI/CD deployment. + +### Kondisi Pemicu +- Membuat situs dokumentasi untuk API, library, atau produk SaaS. +- Menyiapkan Storybook untuk dokumentasi komponen dan regresi visual. +- Memilih framework dokumentasi untuk proyek open-source. +- Menghasilkan halaman referensi API dari spesifikasi OpenAPI. +- Migrasi dari dokumentasi lama (GitBook, Confluence) ke situs statis modern. +- Menambahkan versioning, pencarian, atau i18n ke situs dokumentasi yang sudah ada. + +--- + +### Matriks Pemilihan Framework + +| Framework | Stack | Pencarian AI | Versioning | i18n | Terbaik Untuk | +|----------------|--------------|--------------|------------|------|------------------------------------| +| Mintlify | React / MDX | ✅ AI Native | ✅ | ✅ | Docs API SaaS, produk komersial | +| Docusaurus 3 | React / MDX | ✅ Algolia | ✅ | ✅ | Proyek open-source | +| Storybook 8 | Semua stack | ❌ | ❌ | ❌ | Playground library komponen UI | +| VitePress 2 | Vue / MD | ✅ Bawaan | ❌ | ✅ | Ekosistem Vue / docs library | +| Astro Starlight| Astro / MDX | ✅ Pagefind | ✅ | ✅ | Docs konten berat multi-bahasa | + +**Aturan Keputusan:** +- Produk SaaS → **Mintlify** (zero-config, pencarian AI, playground API) +- Library OSS → **Docusaurus** (versioning + Algolia + plugin komunitas) +- Library komponen → **Storybook** (visual testing + interaksi + Chromatic) +- Proyek Vue → **VitePress** (integrasi Vue native, sangat cepat) +- Konten berat / i18n-first → **Astro Starlight** (Pagefind, routing i18n) + +--- + +### 1. Mintlify — Ringkasan Konfigurasi + +File `mint.json` mengontrol seluruh navigasi, branding, dan integrasi API playground. Field `"openapi"` menunjuk ke spesifikasi OpenAPI dan secara otomatis menghasilkan halaman referensi interaktif — tidak perlu authoring MDX tambahan untuk setiap endpoint. + +```bash +npm install -g mintlify +mintlify dev # pratinjau lokal di http://localhost:3000 +mintlify scrape # hasilkan halaman dari field openapi di mint.json +``` + +**Komponen MDX bawaan:** ``, ``, ``, ``, ``, ``, ``, ``, ``, `` — langsung digunakan dalam file `.mdx` tanpa import. + +--- + +### 2. Docusaurus 3 — Ringkasan + +Docusaurus adalah pilihan terbaik untuk proyek open-source karena mendukung: +- **Versioning**: `npm run docusaurus docs:version 2.0.0` membuat snapshot beku dari `/docs` saat ini. +- **Algolia DocSearch**: Gratis untuk proyek OSS — daftar di `https://docsearch.algolia.com/apply`. +- **Plugin MDX**: `remark-math` + `rehype-katex` untuk LaTeX, `rehype-mermaid` untuk diagram. +- **Plugin OpenAPI**: `docusaurus-plugin-openapi-docs` menghasilkan halaman referensi dari spec YAML. + +--- + +### 3. Storybook 8 — Ringkasan + +Storybook adalah standar industri untuk mendokumentasikan dan menguji komponen UI secara visual. + +**Fitur Utama:** +- **Autodocs**: Tambahkan `tags: ['autodocs']` ke meta story — halaman dokumentasi otomatis dihasilkan dari props TypeScript. +- **Interaction Testing**: Gunakan `play()` dengan `@storybook/test` untuk mensimulasikan interaksi pengguna dan memverifikasi perilaku komponen. +- **Chromatic**: Layanan visual regression testing — tangkap perubahan UI yang tidak disengaja di setiap PR. +- **Addon Aksesibilitas**: `@storybook/addon-a11y` menjalankan audit axe-core pada setiap story. + +--- + +### 4. VitePress 2 — Ringkasan + +VitePress adalah pilihan ideal untuk ekosistem Vue atau proyek library TypeScript yang membutuhkan dokumentasi cepat. + +- File konfigurasi: `docs/.vitepress/config.mts` (TypeScript penuh) +- Pencarian lokal bawaan — tidak perlu Algolia untuk proyek kecil/menengah +- Integrasi komponen Vue langsung dalam halaman Markdown +- Dukungan i18n multi-bahasa melalui konfigurasi `locales` + +--- + +### 5. Astro Starlight — Ringkasan + +Starlight dibangun di atas Astro dan merupakan pilihan terbaik untuk dokumentasi konten berat dengan i18n. + +- **Pagefind**: Pencarian statis client-side — dihasilkan saat build, ukuran bundle ~8KB JS. +- **i18n**: Dukung banyak bahasa dengan routing otomatis (`/id/`, `/ja/`, dll.) +- **Sidebar otomatis**: `autogenerate: { directory: 'guides' }` membuat sidebar dari struktur folder. +- **Edit di GitHub**: Link "Edit halaman ini" otomatis dihasilkan dari konfigurasi `editLink`. + +--- + +### 6. Arsitektur Konten — Praktik Terbaik + +**Strategi Versioning:** +- Gunakan `docusaurus docs:version` untuk snapshot rilis beku. +- Gunakan **Changesets** (`@changesets/cli`) untuk otomatisasi changelog dan bumping versi package. +- Sertakan badge versi semver di halaman utama docs. + +**Otomatisasi Changelog:** +```bash +npx changeset add # tambahkan changeset setelah setiap PR +npx changeset version # bump versi + update CHANGELOG.md +npx changeset publish # publish ke npm +``` + +**Referensi API via `openapi-typescript`:** +```bash +npx openapi-typescript https://api.acme.com/openapi.json -o src/types/api.d.ts +``` +Hasilkan tipe TypeScript penuh dari spesifikasi OpenAPI — gunakan bersama `openapi-fetch` untuk client API yang fully type-safe. + +--- + +### 7. Deployment + +| Platform | Perintah Build | Output Dir | Catatan | +|------------------|-------------------------------|-------------------------|----------------------------------| +| Vercel | `npm run build` | `build` / `dist` | Zero-config untuk Docusaurus | +| Cloudflare Pages | `npm run build` | `build` / `dist` | Konfigurasi via dashboard | +| GitHub Pages | `npm run build` | `build` | Gunakan workflow Actions di atas | +| Netlify | `npm run build` | `build` | Tambahkan `netlify.toml` | + +**Mintlify** di-deploy melalui platform Mintlify sendiri — hubungkan repo GitHub di dashboard `mintlify.com` dan setiap push ke `main` otomatis men-deploy. \ No newline at end of file diff --git a/vibes-plug/skills/doku-mcp-server/SKILL.md b/vibes-plug/skills/doku-mcp-server/SKILL.md new file mode 100644 index 000000000..c3eacce69 --- /dev/null +++ b/vibes-plug/skills/doku-mcp-server/SKILL.md @@ -0,0 +1,444 @@ +--- +name: doku-mcp-server +description: "Expert guide for DOKU Model Context Protocol (MCP) Server integration. Enables AI Agentic Commerce with tools for DOKU Checkout, payment links, Virtual Accounts, QRIS, and order status checks / Panduan ahli DOKU MCP Server untuk AI Agentic Commerce." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# DOKU MCP Server / Server Model Context Protocol DOKU + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills: +- `doku-payment-gateway` — Core DOKU Checkout specifications, HMAC-SHA256 signature algorithms, and SNAP BI protocols. +- `mcp-server-architect` — Enterprise-grade MCP tool design, transport safety, and schema validation. +- `multi-agent-orchestration` — Connecting AI shopping agents and autonomous checkout swarms. +- `saas-billing` — Agentic subscription provisioning and autonomous order payment verification. + +### Description +Expert guide for integrating and building Model Context Protocol (MCP) servers with DOKU Payment Gateway based on the [DOKU Developers Documentation](https://developers.doku.com/). Enables AI Agents (Claude Desktop, Antigravity, Cursor, n8n, LangChain) to execute payment tasks autonomously using Agentic Commerce capabilities (generating DOKU Checkout links, issuing Virtual Account numbers, generating QRIS codes, and querying order-level transaction statuses). + +### Trigger Conditions +Activate this skill when the user is: +- Setting up or configuring DOKU MCP server for Claude Desktop, Antigravity (AGY), Cursor, or LLM agents. +- Implementing AI Agentic Commerce or autonomous AI-driven checkout workflows using DOKU Checkout. +- Building a custom TypeScript or Python MCP server wrapping DOKU Checkout (`/checkout/v1/payment`) or SNAP BI APIs. +- Defining MCP tools and resources for payment generation and status verification. + +--- + +### Key Capabilities & Tools + +| MCP Tool Name | Description | Key Input Parameters | +|---|---|---| +| `create_checkout_payment` | Generates a DOKU Checkout URL supporting all payment methods (VA, CC, QRIS, E-Wallet, etc.) | `amount`, `invoice_number`, `customer_name`, `customer_email`, `customer_phone`, `callback_url`, `payment_method_types`, `payment_due_date` | +| `check_transaction_status` | Queries real-time order and transaction status from DOKU (`/orders/v1/status/{invoice_number}`) | `invoice_number` | +| `create_virtual_account` | Generates a direct bank Virtual Account number via Direct SNAP BI API | `bank_code`, `amount`, `invoice_number`, `customer_name` | +| `create_qris_payment` | Generates a dynamic QRIS string/image for instant wallet payments | `amount`, `invoice_number`, `store_name` | + +--- + +### Client Configuration + +#### 1. Antigravity & Gemini Configuration (`mcp.json`) + +**Location:** +- **Global:** `~/.gemini/config/mcp.json` (Windows: `%USERPROFILE%\.gemini\config\mcp.json`) +- **Workspace:** `.agents/mcp.json` (in your project root) + +```json +{ + "mcpServers": { + "doku-payment": { + "command": "node", + "args": ["/path/to/doku-mcp-server/dist/index.js"], + "env": { + "DOKU_CLIENT_ID": "YOUR_SANDBOX_OR_PROD_CLIENT_ID", + "DOKU_SECRET_KEY": "YOUR_SANDBOX_OR_PROD_SECRET_KEY", + "DOKU_IS_PRODUCTION": "false" + } + } + } +} +``` + +#### 2. Claude Desktop Configuration (`claude_desktop_config.json`) + +**Location:** +- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json` +- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json` + +```json +{ + "mcpServers": { + "doku-payment": { + "command": "node", + "args": ["/path/to/doku-mcp-server/dist/index.js"], + "env": { + "DOKU_CLIENT_ID": "YOUR_SANDBOX_OR_PROD_CLIENT_ID", + "DOKU_SECRET_KEY": "YOUR_SANDBOX_OR_PROD_SECRET_KEY", + "DOKU_IS_PRODUCTION": "false" + } + } + } +} +``` + +--- + +### Building a Production TypeScript MCP Server for DOKU + +```typescript +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import crypto from 'crypto'; + +const CLIENT_ID = process.env.DOKU_CLIENT_ID || ''; +const SECRET_KEY = process.env.DOKU_SECRET_KEY || ''; +const BASE_URL = process.env.DOKU_IS_PRODUCTION === 'true' + ? 'https://api.doku.com' + : 'https://api-sandbox.doku.com'; + +function generateNonSnapHeaders(targetPath: string, payload?: object) { + const requestId = crypto.randomUUID(); + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + let component = `Client-Id:${CLIENT_ID}\nRequest-Id:${requestId}\nRequest-Timestamp:${timestamp}\nRequest-Target:${targetPath}`; + + const headers: Record = { + 'Client-Id': CLIENT_ID, + 'Request-Id': requestId, + 'Request-Timestamp': timestamp, + 'Request-Target': targetPath, + }; + + if (payload) { + const jsonBody = JSON.stringify(payload); + const digest = crypto.createHash('sha256').update(jsonBody, 'utf8').digest('base64'); + headers['Digest'] = digest; + headers['Content-Type'] = 'application/json'; + component += `\nDigest:${digest}`; + } + + const signature = 'HMACSHA256=' + crypto.createHmac('sha256', SECRET_KEY).update(component, 'utf8').digest('base64'); + headers['Signature'] = signature; + + return headers; +} + +const server = new Server( + { name: 'doku-mcp-server', version: '2.0.0' }, + { capabilities: { tools: {} } } +); + +server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: [ + { + name: 'create_checkout_payment', + description: 'Generate a DOKU Checkout URL allowing customers to pay with all supported payment methods (VA, CC, QRIS, E-Wallet, Paylater)', + inputSchema: { + type: 'object', + properties: { + amount: { type: 'number', description: 'Total payment amount in IDR (integer without decimals)' }, + invoice_number: { type: 'string', description: 'Unique order invoice number' }, + customer_name: { type: 'string', description: 'Customer full name' }, + customer_email: { type: 'string', description: 'Customer email address' }, + customer_phone: { type: 'string', description: 'Customer phone number in international format (e.g. 6281234567890)' }, + callback_url: { type: 'string', description: 'Merchant redirect URL upon transaction completion' }, + payment_method_types: { + type: 'array', + items: { type: 'string' }, + description: 'Optional filter for payment channels (e.g. ["VIRTUAL_ACCOUNT_BCA", "CREDIT_CARD", "QRIS", "EMONEY_SHOPEEPAY"]). Omit to show all.' + }, + payment_due_date: { type: 'number', description: 'Payment expiration time in minutes (default 60)' } + }, + required: ['amount', 'invoice_number', 'customer_name', 'customer_email'] + } + }, + { + name: 'check_transaction_status', + description: 'Check real-time order and transaction payment status using DOKU Check Status API', + inputSchema: { + type: 'object', + properties: { + invoice_number: { type: 'string', description: 'Merchant invoice number to query' } + }, + required: ['invoice_number'] + } + } + ] +})); + +server.setRequestHandler(CallToolRequestSchema, async (request) => { + const { name, arguments: args } = request.params; + + if (name === 'create_checkout_payment') { + const targetPath = '/checkout/v1/payment'; + const body = { + order: { + amount: args?.amount, + invoice_number: args?.invoice_number, + currency: 'IDR', + callback_url: args?.callback_url, + auto_redirect: true + }, + payment: { + payment_due_date: args?.payment_due_date || 60, + ...(args?.payment_method_types ? { payment_method_types: args.payment_method_types } : {}) + }, + customer: { + id: args?.customer_email, + name: args?.customer_name, + email: args?.customer_email, + phone: args?.customer_phone || '6281234567890' + } + }; + + const response = await fetch(`${BASE_URL}${targetPath}`, { + method: 'POST', + headers: generateNonSnapHeaders(targetPath, body), + body: JSON.stringify(body) + }); + + const data = await response.json(); + return { + content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] + }; + } + + if (name === 'check_transaction_status') { + const invoiceNumber = args?.invoice_number; + const targetPath = `/orders/v1/status/${invoiceNumber}`; + + const response = await fetch(`${BASE_URL}${targetPath}`, { + method: 'GET', + headers: generateNonSnapHeaders(targetPath) + }); + + const data = await response.json(); + return { + content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] + }; + } + + throw new Error(`Tool not found: ${name}`); +}); + +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); +} + +main().catch(console.error); +``` + +--- + +### Common Pitfalls to Avoid + +| Anti-Pattern | Issue | Solution | +|---|---|---| +| Hardcoding Merchant Secrets | Security leak | Always read `DOKU_CLIENT_ID` and `DOKU_SECRET_KEY` from environment variables. | +| Incomplete Tool Schema Descriptions | AI Agent misinterprets tool usage | Provide clear parameter descriptions and strict `required` fields in JSON schema. | +| Omitting Digest on POST | 401 Unauthorized / Signature Mismatch | For DOKU Checkout (`/checkout/v1/payment`), calculate Base64 SHA-256 Digest of minified body and include it in component string. | +| Including Digest on GET Check Status | 401 Signature Mismatch | For GET requests (`/orders/v1/status/...`), do NOT include `Digest` in headers or signature component string. | + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan: +- `doku-payment-gateway` — Spesifikasi teknis DOKU Checkout, algoritma HMAC-SHA256, dan standar SNAP BI. +- `mcp-server-architect` — Arsitektur server MCP tingkat lanjut, standardisasi schema Zod/JSON Schema, dan transportasi stdio. +- `multi-agent-orchestration` — Agen AI otonom untuk pembelian dan checkout otomatis. +- `saas-billing` — Verifikasi pembayaran tagihan langganan secara otonom. + +### Deskripsi +Panduan ahli untuk mengintegrasikan dan membuat server Model Context Protocol (MCP) dengan DOKU Payment Gateway berdasarkan dokumentasi resmi [DOKU Developers Documentation](https://developers.doku.com/). Memungkinkan Agen AI (Claude Desktop, Antigravity, Cursor, n8n, LangChain) menjalankan transaksi pembayaran secara otonom dalam alur Agentic Commerce (membuat URL DOKU Checkout, memeriksa status pembayaran order, dan mengelola invoice). + +### Kondisi Pemicu +- Mengonfigurasi server DOKU MCP untuk Claude Desktop, Antigravity (AGY), atau Cursor IDE. +- Membangun alur belanja otonom (*Agentic Commerce*) di mana agen AI dapat membuat tautan pembayaran. +- Membungkus endpoint API DOKU Checkout (`/checkout/v1/payment`) ke dalam tool MCP standar. +- Melakukan verifikasi status pembayaran transaksi secara otomatis melalui query invoice. + +--- + +### Konfigurasi Klien MCP + +#### 1. Konfigurasi Antigravity & Gemini (`mcp.json`) +Lokasi file: `~/.gemini/config/mcp.json` (Global) atau `.agents/mcp.json` (Workspace): +```json +{ + "mcpServers": { + "doku-payment": { + "command": "node", + "args": ["/path/to/doku-mcp-server/dist/index.js"], + "env": { + "DOKU_CLIENT_ID": "CLIENT_ID_MERCHANT", + "DOKU_SECRET_KEY": "SECRET_KEY_MERCHANT", + "DOKU_IS_PRODUCTION": "false" + } + } + } +} +``` + +#### 2. Konfigurasi Claude Desktop (`claude_desktop_config.json`) +Lokasi file pada Windows: `%APPDATA%\Claude\claude_desktop_config.json`: +```json +{ + "mcpServers": { + "doku-payment": { + "command": "node", + "args": ["/path/to/doku-mcp-server/dist/index.js"], + "env": { + "DOKU_CLIENT_ID": "CLIENT_ID_MERCHANT", + "DOKU_SECRET_KEY": "SECRET_KEY_MERCHANT", + "DOKU_IS_PRODUCTION": "false" + } + } + } +} +``` + +--- + +### Implementasi Server MCP DOKU Berbasis TypeScript + +```typescript +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import crypto from 'crypto'; + +const CLIENT_ID = process.env.DOKU_CLIENT_ID || ''; +const SECRET_KEY = process.env.DOKU_SECRET_KEY || ''; +const BASE_URL = process.env.DOKU_IS_PRODUCTION === 'true' + ? 'https://api.doku.com' + : 'https://api-sandbox.doku.com'; + +function buatHeaderNonSnap(pathTarget: string, payload?: object) { + const requestId = crypto.randomUUID(); + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + let komponen = `Client-Id:${CLIENT_ID}\nRequest-Id:${requestId}\nRequest-Timestamp:${timestamp}\nRequest-Target:${pathTarget}`; + + const headers: Record = { + 'Client-Id': CLIENT_ID, + 'Request-Id': requestId, + 'Request-Timestamp': timestamp, + 'Request-Target': pathTarget, + }; + + if (payload) { + const jsonBody = JSON.stringify(payload); + const digest = crypto.createHash('sha256').update(jsonBody, 'utf8').digest('base64'); + headers['Digest'] = digest; + headers['Content-Type'] = 'application/json'; + komponen += `\nDigest:${digest}`; + } + + const signature = 'HMACSHA256=' + crypto.createHmac('sha256', SECRET_KEY).update(komponen, 'utf8').digest('base64'); + headers['Signature'] = signature; + return headers; +} + +const server = new Server( + { name: 'doku-mcp-server', version: '2.0.0' }, + { capabilities: { tools: {} } } +); + +server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: [ + { + name: 'create_checkout_payment', + description: 'Menghasilkan URL pembayaran DOKU Checkout untuk seluruh metode pembayaran', + inputSchema: { + type: 'object', + properties: { + amount: { type: 'number', description: 'Total pembayaran dalam IDR' }, + invoice_number: { type: 'string', description: 'Nomor invoice unik' }, + customer_name: { type: 'string', description: 'Nama lengkap pelanggan' }, + customer_email: { type: 'string', description: 'Email pelanggan' }, + }, + required: ['amount', 'invoice_number', 'customer_name', 'customer_email'] + } + }, + { + name: 'check_transaction_status', + description: 'Memeriksa status pembayaran transaksi secara real-time via nomor invoice', + inputSchema: { + type: 'object', + properties: { + invoice_number: { type: 'string', description: 'Nomor invoice yang ingin diperiksa' } + }, + required: ['invoice_number'] + } + } + ] +})); + +server.setRequestHandler(CallToolRequestSchema, async (request) => { + const { name, arguments: args } = request.params; + + if (name === 'create_checkout_payment') { + const targetPath = '/checkout/v1/payment'; + const body = { + order: { + amount: args?.amount, + invoice_number: args?.invoice_number, + currency: 'IDR', + auto_redirect: true + }, + payment: { payment_due_date: 60 }, + customer: { + name: args?.customer_name, + email: args?.customer_email + } + }; + + const res = await fetch(`${BASE_URL}${targetPath}`, { + method: 'POST', + headers: buatHeaderNonSnap(targetPath, body), + body: JSON.stringify(body) + }); + + const data = await res.json(); + return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }; + } + + if (name === 'check_transaction_status') { + const invoiceNumber = args?.invoice_number; + const targetPath = `/orders/v1/status/${invoiceNumber}`; + + const res = await fetch(`${BASE_URL}${targetPath}`, { + method: 'GET', + headers: buatHeaderNonSnap(targetPath) + }); + + const data = await res.json(); + return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }; + } + + throw new Error(`Tool tidak ditemukan: ${name}`); +}); + +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); +} + +main().catch(console.error); +``` + +### Jebakan Umum yang Wajib Dihindari +- **Hardcoding Secret Key**: Jangan pernah menaruh Secret Key di file kodingan. Gunakan variabel lingkungan. +- **Menyertakan Header Digest pada Request GET**: Header `Digest` hanya dihitung pada request POST yang memiliki body JSON. Menyertakan Digest pada GET menghasilkan error 401 Signature Mismatch. \ No newline at end of file diff --git a/vibes-plug/skills/doku-payment-gateway/SKILL.md b/vibes-plug/skills/doku-payment-gateway/SKILL.md new file mode 100644 index 000000000..c66991c47 --- /dev/null +++ b/vibes-plug/skills/doku-payment-gateway/SKILL.md @@ -0,0 +1,579 @@ +--- +name: doku-payment-gateway +description: "Expert guide for integrating DOKU Payment Gateway: DOKU Checkout (Hosted & Modal Popup with HMAC-SHA256), Direct API SNAP BI Standard (VA, QRIS, Direct Debit with HMAC-SHA512), and Direct API Non-SNAP (Card Payment Page, OVO Push). Covers single-integration checkout, direct host-to-host APIs, webhook verification, and atomic idempotency / Panduan ahli integrasi DOKU Payment Gateway (DOKU Checkout & Direct API)." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# DOKU Payment Gateway Integration / Integrasi Payment Gateway DOKU + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills: +- `payment-gateway-expert` — Multi-gateway routing, SaaS billing architectures, subscription state machines. +- `saas-billing` — Database synchronization, atomic locks, invoice fulfillment. +- `doku-mcp-server` — Exposes DOKU Checkout & Direct APIs to AI agents via Model Context Protocol. +- `database-orm-expert` — Transactional database models, race-condition mitigation. +- `async-queue-temporal-expert` — Background job retries and async payment reconciliation. + +### Description +Expert guide for implementing DOKU Payment Gateway based on the official [DOKU Developers Documentation](https://developers.doku.com/). +DOKU offers two primary integration models: +1. **DOKU Checkout** (`/checkout/v1/payment`): Hosted payment page or modal overlay (`jokul-checkout-1.0.0.js`). The fastest, single-integration solution supporting all payment channels (Virtual Accounts, Credit Cards, QRIS, E-Wallets, Convenience Stores, Paylater, Direct Debit) with built-in retry handling and cart recovery. Uses **Non-SNAP HMAC-SHA256** signatures with request digest. +2. **Direct API**: + - **SNAP BI Standard (Host-to-Host)**: Standardized open banking API mandated by Bank Indonesia. Employs OAuth 2.0 B2B token with Asymmetric RSA-SHA256, and **HMAC-SHA512** for transactional endpoints (Direct VA, Direct QRIS, Direct Debit). + - **Non-SNAP Direct API**: Dedicated APIs for Credit Card Payment Page (`/credit-card/v1/payment-page`), OVO Push Payment (`/ovo-emoney/v1/payment`), and Direct Paylater. + +--- + +### Integration Architecture Decision Matrix + +| Dimension | DOKU Checkout (Hosted / Modal) | Direct API (SNAP BI Standard) | Direct API (Non-SNAP) | +|---|---|---|---| +| **Primary Use Case** | E-commerce, SaaS billing, mobile apps wanting instant multi-channel coverage | Bespoke in-app banking UI, automated dynamic VA generation, native QRIS display | Non-PCI DSS Card custom page, instant OVO push payment to phone | +| **Supported Channels** | All channels in 1 API (VA, CC, QRIS, E-Wallet, Alfa/Indomaret, Paylater, Direct Debit) | Specific endpoints: Bank Virtual Accounts, QRIS, Direct Debit | Credit Card 3DS, OVO Push, LinkAja, Paylater (Kredivo/Akulaku) | +| **Frontend Effort** | Minimal: Redirect to URL or trigger modal via `loadJokulCheckout()` | High: Merchant builds custom payment UI for each channel | Medium: Merchant embeds card iframe/redirect or prompts phone | +| **Signature Algorithm** | `HMACSHA256` with body `Digest` | `HMAC-SHA512` (Transactional) + RSA-SHA256 (B2B Token) | `HMACSHA256` with `Digest` (Card) or SHA256 checksum (OVO) | +| **Endpoint Base** | `/checkout/v1/payment` | `/virtual-accounts/bi-snap-va/v1.1/...`, `/snap-adapter/b2b/v1.0/qr/...` | `/credit-card/v1/payment-page`, `/ovo-emoney/v1/payment` | +| **Check Status** | `GET /orders/v1/status/{invoice_number}` (with order-level status) | Channel status endpoint (e.g. `/transfer-va/status`, `/qr-mpm-query`) | `GET /orders/v1/status/{invoice_number}` | + +--- + +### Core Architecture & Credentials + +#### Environment Gateways +| Environment | Base URL | Dashboard Portal | Simulator | +|---|---|---|---| +| **Sandbox** | `https://api-sandbox.doku.com` | `https://sandbox.doku.com` | `https://sandbox.doku.com/gtw-config-v2/simulator` | +| **Production** | `https://api.doku.com` | `https://dashboard.doku.com` | N/A | + +#### Frontend JS SDK (for Modal Popup Mode) +- **Sandbox**: `https://sandbox.doku.com/jokul-checkout-js/v1/jokul-checkout-1.0.0.js` +- **Production**: `https://jokul.doku.com/jokul-checkout-js/v1/jokul-checkout-1.0.0.js` + +--- + +## 1. DOKU Checkout Integration (Recommended) + +### Backend: Generate Checkout Payment URL + +#### Endpoint +- **HTTP Method**: `POST` +- **Sandbox**: `https://api-sandbox.doku.com/checkout/v1/payment` +- **Production**: `https://api.doku.com/checkout/v1/payment` + +#### Mandatory Headers +```http +Client-Id: MCH-0001-10791114622547 +Request-Id: 2ebffd22-d23e-4368-95ce-5c38f7ddcf86 +Request-Timestamp: 2026-10-03T01:30:00Z +Signature: HMACSHA256=1jap2tpgvWt83tG4J7IhEwUrwmMt71OaIk0oL0e6sPM= +Content-Type: application/json +``` + +> [!IMPORTANT] +> - `Request-Timestamp` MUST be in ISO8601 UTC+0 (`YYYY-MM-DDTHH:mm:ssZ`). For WIB (UTC+7), subtract 7 hours. +> - `Request-Target` is `/checkout/v1/payment`. + +#### Signature Generation (Non-SNAP HMAC-SHA256) +1. **Calculate Digest**: + ```typescript + const jsonBody = JSON.stringify(body); + const digest = crypto.createHash('sha256').update(jsonBody, 'utf8').digest('base64'); + ``` +2. **Assemble Component String**: + ```text + Client-Id:\nRequest-Id:\nRequest-Timestamp:\nRequest-Target:\nDigest: + ``` +3. **Calculate HMAC-SHA256**: + ```typescript + const hmac = crypto.createHmac('sha256', secretKey).update(componentString, 'utf8').digest('base64'); + const signatureHeader = `HMACSHA256=${hmac}`; + ``` + +#### Full Request Payload Schema +```json +{ + "order": { + "amount": 150000, + "invoice_number": "INV-20261003-0001", + "currency": "IDR", + "callback_url": "https://myapp.com/checkout/return", + "callback_url_cancel": "https://myapp.com/checkout/cancel", + "callback_url_result": "https://myapp.com/checkout/result", + "language": "EN", + "auto_redirect": true, + "disable_retry_payment": true, + "recover_abandoned_cart": true, + "expired_recovered_cart": 60, + "line_items": [ + { + "id": "ITEM-1", + "name": "Pro SaaS Annual Subscription", + "quantity": 1, + "price": 150000, + "sku": "SAAS-PRO-Y", + "category": "services" + } + ] + }, + "payment": { + "payment_due_date": 60, + "payment_method_types": [ + "VIRTUAL_ACCOUNT_BCA", + "VIRTUAL_ACCOUNT_BANK_MANDIRI", + "VIRTUAL_ACCOUNT_BRI", + "VIRTUAL_ACCOUNT_BNI", + "CREDIT_CARD", + "QRIS", + "EMONEY_SHOPEEPAY", + "EMONEY_OVO", + "EMONEY_DANA" + ] + }, + "customer": { + "id": "CUST-9921", + "name": "Alex", + "last_name": "Kusuma", + "email": "alex.kusuma@example.com", + "phone": "6281234567890", + "address": "Sudirman Central Business District", + "city": "Jakarta Selatan", + "country": "ID" + }, + "additional_info": { + "allow_tenor": [0, 3, 6, 12], + "override_notification_url": "https://myapp.com/api/webhooks/doku/checkout" + } +} +``` + +> [!TIP] +> To showcase **all** available channels enabled in your DOKU account, simply omit `payment.payment_method_types`. + +#### Response Body Highlights +```json +{ + "message": ["SUCCESS"], + "response": { + "order": { + "amount": "150000", + "invoice_number": "INV-20261003-0001", + "session_id": "5f6304ca900144c7a4fcf802ad6c0898" + }, + "payment": { + "url": "https://sandbox.doku.com/checkout-link-v2/5f6304ca900144c7a4fcf802ad6c0898...", + "token_id": "5f6304ca900144c7a4fcf802ad6c08982024...", + "payment_due_date": 60, + "expired_date": "20261003104531" + } + } +} +``` + +--- + +### Frontend Integration (Popup Modal vs Redirect) + +#### Approach A: Modal Overlay (Pop-Up Mode) +Import the DOKU Checkout JS SDK and trigger `loadJokulCheckout(url)`: +```html + + + + + + + + + + + + + +``` + +#### Approach B: Direct Redirect Mode +For mobile browsers or standard redirects, navigate directly to `response.payment.url`: +```typescript +window.location.href = data.paymentUrl; +``` + +--- + +### Order Status & Check Status API (Non-SNAP) + +The Check Status API tracks order-level statuses even before the customer selects a specific channel: +- **Endpoint**: `GET https://api-sandbox.doku.com/orders/v1/status/{invoice_number}` +- **Signature for GET**: Does NOT require a Digest. + ```text + Client-Id:\nRequest-Id:\nRequest-Timestamp:\nRequest-Target:/orders/v1/status/ + ``` +- **Statuses**: + - `order.status`: `ORDER_GENERATED`, `ORDER_EXPIRED`, `ORDER_RECOVERED`. + - `transaction.status`: `PENDING`, `SUCCESS`, `FAILED`, `EXPIRED`, `REFUNDED`. + +--- + +### Webhook Verification & Atomic Idempotency (DOKU Checkout) + +When a customer completes payment via Checkout, DOKU posts an HTTP Notification with headers: +- `Client-Id`, `Request-Id`, `Request-Timestamp`, `Signature: HMACSHA256=...` + +```typescript +import crypto from 'crypto'; + +export function verifyDokuCheckoutNotification( + clientId: string, + secretKey: string, + requestTarget: string, // path of your notification endpoint e.g., '/api/webhooks/doku/checkout' + headers: Record, + rawBody: string +): boolean { + const reqClientId = headers['client-id']; + const reqId = headers['request-id']; + const reqTimestamp = headers['request-timestamp']; + const receivedSig = headers['signature'] || ''; + + if (reqClientId !== clientId) return false; + + // 1. Compute Base64 SHA-256 Digest of raw body + const digest = crypto.createHash('sha256').update(rawBody, 'utf8').digest('base64'); + + // 2. Build string component + const component = `Client-Id:${reqClientId}\nRequest-Id:${reqId}\nRequest-Timestamp:${reqTimestamp}\nRequest-Target:${requestTarget}\nDigest:${digest}`; + + // 3. Compute HMAC-SHA256 + const expectedSig = 'HMACSHA256=' + crypto.createHmac('sha256', secretKey).update(component, 'utf8').digest('base64'); + + return crypto.timingSafeEqual(Buffer.from(receivedSig), Buffer.from(expectedSig)); +} +``` + +--- + +## 2. Direct API — SNAP BI Standard (Host-to-Host) + +For merchants requiring fully custom, native checkout experiences for Virtual Accounts, QRIS, or Direct Debit. + +### Step 1: B2B Access Token Generation +- **Endpoint**: `POST /authorization/v1/access-token/b2b` +- **Headers**: + - `X-CLIENT-KEY`: Merchant Client ID + - `X-TIMESTAMP`: ISO8601 string (`YYYY-MM-DDTHH:mm:ssZ`) + - `X-SIGNATURE`: `SHA256withRSA(PrivateKey, X-CLIENT-KEY + "|" + X-TIMESTAMP)` (Base64) +- **Body**: `{"grantType": "client_credentials"}` +- **Response**: `accessToken` (Bearer token, valid for 900 seconds). + +```typescript +export function generateSnapB2bSignature(clientId: string, timestamp: string, privateKeyPem: string): string { + const stringToSign = `${clientId}|${timestamp}`; + const signer = crypto.createSign('RSA-SHA256'); + signer.update(stringToSign); + return signer.sign(privateKeyPem, 'base64'); +} +``` + +### Step 2: Transactional Endpoints Signature (HMAC-SHA512) +- **Formula**: + 1. `BodyHash = hex(sha256(minifiedBody)).toLowerCase()` + 2. `StringToSign = HTTPMethod + ":" + EndpointUrl + ":" + AccessToken + ":" + BodyHash + ":" + Timestamp` + 3. `X-SIGNATURE = base64(hmacSha512(ClientSecret, StringToSign))` + +```typescript +export function generateSnapTransactionalSignature( + method: string, + endpointPath: string, + accessToken: string, + timestamp: string, + clientSecret: string, + body?: object +): string { + let bodyHash = ''; + if (body && ['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) { + bodyHash = crypto.createHash('sha256').update(JSON.stringify(body), 'utf8').digest('hex').toLowerCase(); + } + + const stringToSign = `${method.toUpperCase()}:${endpointPath}:${accessToken}:${bodyHash}:${timestamp}`; + return crypto.createHmac('sha512', clientSecret).update(stringToSign, 'utf8').digest('base64'); +} +``` + +### Direct Virtual Account API (`/virtual-accounts/bi-snap-va/v1.1/...`) +1. **DOKU Generated Payment Code (DGPC)**: + - `POST /virtual-accounts/bi-snap-va/v1.1/transfer-va/create-va` + - DOKU generates the unique VA number using the bank's BIN. +2. **Merchant Generated Payment Code (MGPC)**: + - Merchant provides their own payment code conforming to bank BIN rules. +3. **Billing Types**: + - `FIX_BILL`: Exact amount payment (standard e-commerce). + - `NO_BILL`: Open amount (donations/wallet top-up). + - `BILL_VARIABLE_AMOUNT`: Range-based amount. + - `PARTIAL_AMOUNT`: Installment or partial payments (BNI, CIMB, Danamon). +4. **Maintenance Endpoints**: + - Update VA: `PUT /virtual-accounts/bi-snap-va/v1.1/transfer-va/update-va` + - Delete VA: `DELETE /virtual-accounts/bi-snap-va/v1.1/transfer-va/delete-va` + +### Direct QRIS API (`/snap-adapter/b2b/v1.0/qr/...`) +1. **Generate QRIS**: + - `POST /snap-adapter/b2b/v1.0/qr/qr-mpm-generate` + - Request includes `partnerReferenceNo`, `amount.value` (format `10000.00`), `merchantId`, `terminalId`, `additionalInfo.postalCode`. + - Response returns `qrContent` string (EMVCo payload) for rendering dynamic QR code. +2. **Query QRIS**: `POST /snap-adapter/b2b/v1.0/qr/qr-mpm-query` +3. **Cancel / Expire QRIS**: `POST /snap-adapter/b2b/v1.0/qr/qr-expire` +4. **Refund QRIS**: `POST /snap-adapter/b2b/v1.0/qr/qr-mpm-refund` + +--- + +## 3. Direct API — Non-SNAP Channels + +### Credit Card Payment Page (`/credit-card/v1/payment-page`) +For non-PCI DSS merchants wanting a customized branded card checkout page: +- **Method**: `POST` +- **Headers**: Non-SNAP `Client-Id`, `Request-Id`, `Request-Timestamp`, `Signature` (HMAC-SHA256 with Digest). +- **Body**: `order`, `customer`, `payment.type` (`"SALE"` or `"AUTHORIZE"`), `override_configuration.themes` (custom colors and logos). +- **Flow**: Redirects customer to DOKU 3D-Secure authentication, then returns to `callback_url`. + +### OVO Push Payment (`/ovo-emoney/v1/payment`) +Initiates an instant push payment notification directly to customer's OVO mobile app: +- **Method**: `POST` +- **Body**: + ```json + { + "client": { "id": "MCH-0001-10791114622547" }, + "order": { "invoice_number": "INV-20261003-0002", "amount": 50000 }, + "ovo_info": { "ovo_id": "081234567890" }, + "security": { "check_sum": "" } + } + ``` +- **Checksum Calculation**: + ```typescript + const checkSum = crypto.createHash('sha256') + .update(`${amount}${clientId}${invoiceNumber}${ovoId}${secretKey}`, 'utf8') + .digest('hex'); + ``` +- **Wait Time**: The backend request waits up to **70 seconds** for the customer to confirm the payment on their phone. + +--- + +## Complete TypeScript Implementation (DOKU Checkout & SNAP Direct) + +```typescript +import crypto from 'crypto'; + +export interface DokuConfig { + clientId: string; + secretKey: string; + isProduction: boolean; + privateKeyPem?: string; // For SNAP B2B RSA token +} + +export class DokuService { + private clientId: string; + private secretKey: string; + private baseUrl: string; + private privateKeyPem?: string; + + constructor(config: DokuConfig) { + this.clientId = config.clientId; + this.secretKey = config.secretKey; + this.baseUrl = config.isProduction ? 'https://api.doku.com' : 'https://api-sandbox.doku.com'; + this.privateKeyPem = config.privateKeyPem; + } + + // =================== DOKU CHECKOUT (NON-SNAP) =================== + private generateNonSnapHeaders(targetPath: string, body?: object) { + const requestId = crypto.randomUUID(); + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + let component = `Client-Id:${this.clientId}\nRequest-Id:${requestId}\nRequest-Timestamp:${timestamp}\nRequest-Target:${targetPath}`; + + const headers: Record = { + 'Client-Id': this.clientId, + 'Request-Id': requestId, + 'Request-Timestamp': timestamp, + 'Request-Target': targetPath, + }; + + if (body) { + const minified = JSON.stringify(body); + const digest = crypto.createHash('sha256').update(minified, 'utf8').digest('base64'); + headers['Digest'] = digest; + headers['Content-Type'] = 'application/json'; + component += `\nDigest:${digest}`; + } + + const hmac = crypto.createHmac('sha256', this.secretKey).update(component, 'utf8').digest('base64'); + headers['Signature'] = `HMACSHA256=${hmac}`; + + return headers; + } + + public async createCheckoutUrl(payload: { + amount: number; + invoiceNumber: string; + customerName: string; + customerEmail: string; + callbackUrl?: string; + }) { + const targetPath = '/checkout/v1/payment'; + const body = { + order: { + amount: payload.amount, + invoice_number: payload.invoiceNumber, + currency: 'IDR', + callback_url: payload.callbackUrl, + auto_redirect: true, + }, + payment: { payment_due_date: 60 }, + customer: { + id: payload.customerEmail, + name: payload.customerName, + email: payload.customerEmail, + }, + }; + + const response = await fetch(`${this.baseUrl}${targetPath}`, { + method: 'POST', + headers: this.generateNonSnapHeaders(targetPath, body), + body: JSON.stringify(body), + }); + + const data = await response.json(); + return { + paymentUrl: data.response.payment.url, + tokenId: data.response.payment.token_id, + }; + } + + // =================== SNAP BI DIRECT API =================== + public async getSnapB2bToken(): Promise { + if (!this.privateKeyPem) throw new Error('Private key PEM required for SNAP B2B Token'); + const targetPath = '/authorization/v1/access-token/b2b'; + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + + // RSA-SHA256 signature + const stringToSign = `${this.clientId}|${timestamp}`; + const signer = crypto.createSign('RSA-SHA256'); + signer.update(stringToSign); + const signature = signer.sign(this.privateKeyPem, 'base64'); + + const response = await fetch(`${this.baseUrl}${targetPath}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-CLIENT-KEY': this.clientId, + 'X-TIMESTAMP': timestamp, + 'X-SIGNATURE': signature, + }, + body: JSON.stringify({ grantType: 'client_credentials' }), + }); + + const data = await response.json(); + return data.accessToken; + } + + public async generateDirectQris(accessToken: string, partnerRefNo: string, amount: number, merchantId: string, terminalId: string) { + const targetPath = '/snap-adapter/b2b/v1.0/qr/qr-mpm-generate'; + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); + const externalId = crypto.randomUUID(); + + const body = { + partnerReferenceNo: partnerRefNo, + amount: { value: `${amount.toFixed(2)}`, currency: 'IDR' }, + merchantId, + terminalId, + additionalInfo: { postalCode: '12012', feeType: '1' } + }; + + const minified = JSON.stringify(body); + const bodyHash = crypto.createHash('sha256').update(minified, 'utf8').digest('hex').toLowerCase(); + const stringToSign = `POST:${targetPath}:${accessToken}:${bodyHash}:${timestamp}`; + const signature = crypto.createHmac('sha512', this.secretKey).update(stringToSign, 'utf8').digest('base64'); + + const response = await fetch(`${this.baseUrl}${targetPath}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${accessToken}`, + 'X-PARTNER-ID': this.clientId, + 'X-EXTERNAL-ID': externalId, + 'X-TIMESTAMP': timestamp, + 'X-SIGNATURE': signature, + 'CHANNEL-ID': 'H2H' + }, + body: minified, + }); + + return await response.json(); + } +} +``` + +--- + +### Common Pitfalls to Avoid + +| Anti-Pattern | Issue | Solution | +|---|---|---| +| Using HMAC-SHA512 for DOKU Checkout | `401 Unauthorized / Invalid Signature` | DOKU Checkout uses **Non-SNAP HMAC-SHA256** with body `Digest`. | +| Using HMAC-SHA256 for SNAP BI Direct | `401 Unauthorized` | SNAP BI transactional endpoints strictly require **HMAC-SHA512** with lowercase hex SHA-256 body hash. | +| Forgetting `CHANNEL-ID: H2H` in SNAP | Bad request | SNAP BI Direct host-to-host APIs require `CHANNEL-ID: H2H` header. | +| Inverting `Request-Target` in Webhook | Signature validation fails | For incoming webhooks, `Request-Target` is the merchant's endpoint path (e.g., `/api/webhooks/doku/checkout`). | +| OVO Push timeout too short | premature failure | OVO push payments require up to **70 seconds** client timeout while the user confirms on mobile. | +| Non-atomic database updates | Race condition double top-up | Always guard webhook fulfillments with atomic SQL updates (`WHERE status = 'PENDING'`). | + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan: +- `payment-gateway-expert` — Arsitektur checkout SaaS, perutean multi-gateway, dan state machine langganan. +- `saas-billing` — Sinkronisasi database lokal, penguncian atomik (atomic locks), dan penerbitan invoice. +- `doku-mcp-server` — Membuka tool DOKU Checkout dan Direct API ke Agen AI via Model Context Protocol. +- `database-orm-expert` — Model database transaksional dan pencegahan race-condition. +- `async-queue-temporal-expert` — Antrean job latar belakang untuk retry dan rekonsiliasi pembayaran. + +### Deskripsi +Panduan ahli untuk mengintegrasikan DOKU Payment Gateway berdasarkan dokumentasi resmi [DOKU Developers Portal](https://developers.doku.com/). +DOKU menyediakan 2 model integrasi utama: +1. **DOKU Checkout** (`/checkout/v1/payment`): Halaman pembayaran hosted atau modal pop-up overlay (`jokul-checkout-1.0.0.js`). Cara termudah dan tercepat untuk menerima seluruh metode pembayaran (Virtual Account, Kartu Kredit, QRIS, E-Wallet, Indomaret/Alfamart, Paylater, Direct Debit) dalam satu kali integrasi. Menggunakan tanda tangan **Non-SNAP HMAC-SHA256** dengan komponen `Digest`. +2. **Direct API**: + - **Standar SNAP BI (Host-to-Host)**: Standar Bank Indonesia untuk integrasi perbankan langsung (B2B Access Token via RSA Asimetrik, transaksi via **HMAC-SHA512** untuk Direct VA, Direct QRIS, dan Direct Debit). + - **Direct API Non-SNAP**: Endpoint khusus untuk Kartu Kredit (`/credit-card/v1/payment-page`) dengan 3DS kustom dan OVO Push Payment (`/ovo-emoney/v1/payment`) langsung ke ponsel pengguna. + +--- + +### Perbandingan Model Integrasi (Checkout vs Direct API) + +| Kebutuhan | Rekomendasi Solusi | Alasan | +|---|---|---| +| **E-commerce, SaaS, Starter** | **DOKU Checkout** | 1 API mengaktifkan semua kanal pembayaran sekaligus tanpa membangun UI per bank. | +| **In-App Native Banking UI** | **Direct API SNAP BI** | Memungkinkan merchant menampilkan nomor Virtual Account atau QRIS langsung di dalam aplikasi tanpa redirect. | +| **Non-PCI DSS Card Form** | **Credit Card Payment Page** | Halaman pembayaran kartu dengan 3DS aman tanpa beban audit sertifikasi PCI DSS. | +| **Push Payment E-Wallet** | **OVO Push Payment** | Langsung memicu prompt bayar di aplikasi OVO pelanggan menggunakan nomor ponsel (timeout 70 detik). | + +--- + +### 🚨 Simulator Sandbox DOKU +- **URL Simulator**: `https://sandbox.doku.com/gtw-config-v2/simulator` +- **QRIS Simulator**: `https://sandbox.doku.com/qris-simulator/` +Gunakan simulator resmi di atas untuk menguji transaksi Virtual Account dan QRIS dalam mode Sandbox sebelum deployment ke produksi. \ No newline at end of file diff --git a/vibes-plug/skills/domain-driven-design-expert/SKILL.md b/vibes-plug/skills/domain-driven-design-expert/SKILL.md new file mode 100644 index 000000000..8fc1e4039 --- /dev/null +++ b/vibes-plug/skills/domain-driven-design-expert/SKILL.md @@ -0,0 +1,147 @@ +--- +name: domain-driven-design-expert +description: "Expert guide for Domain-Driven Design (DDD). Covers tactical patterns (Aggregates, Value Objects), strategic patterns (Bounded Contexts), event storming, and CQRS / Panduan ahli Desain Berbasis Domain (DDD)." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Domain-Driven Design (DDD) Expert (Strategic & Tactical 2026) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Comprehensive architectural guide for tackling core business complexity using Domain-Driven Design (DDD). Covers Strategic Design (Bounded Contexts, Context Mapping, Ubiquitous Language, Subdomains) and Tactical Design (immutable Value Objects, Aggregate Roots, Domain Events, Repositories, Specification pattern, and CQRS separation). Emphasizes keeping core domain logic pure and independent of database schemas, ORMs, and web delivery frameworks. + +### Trigger Conditions +- Decomposing monolithic applications (*"Big Ball of Mud"*) into clean, decoupled Bounded Contexts. +- Designing rule-heavy, high-invariant business logic (FinTech billing, multi-tier pricing, insurance, logistics). +- Structuring Clean / Hexagonal / Onion architectures in TypeScript, Go, Python, or Rust. +- Defining event payloads and boundaries for Event-Driven Microservices. + +### Tactical Pattern: Immutable Value Object & Aggregate Root (TypeScript) + +```typescript +// src/domain/shared/value-objects/Money.ts +export class Money { + readonly amountCents: number; + readonly currency: 'USD' | 'IDR' | 'EUR'; + + private constructor(amountCents: number, currency: 'USD' | 'IDR' | 'EUR') { + if (amountCents < 0) throw new Error('Money amount cannot be negative.'); + this.amountCents = Math.round(amountCents); + this.currency = currency; + } + + static create(amountCents: number, currency: 'USD' | 'IDR' | 'EUR' = 'USD'): Money { + return new Money(amountCents, currency); + } + + add(other: Money): Money { + if (this.currency !== other.currency) throw new Error('Currency mismatch.'); + return new Money(this.amountCents + other.amountCents, this.currency); + } + + equals(other: Money): boolean { + return this.amountCents === other.amountCents && this.currency === other.currency; + } +} + +// src/domain/order/OrderAggregate.ts +export interface DomainEvent { + eventName: string; + occurredOn: Date; + aggregateId: string; +} + +export class OrderPaidEvent implements DomainEvent { + eventName = 'OrderPaidEvent'; + occurredOn = new Date(); + constructor(public aggregateId: string, public totalAmount: Money) {} +} + +export class OrderAggregate { + private _domainEvents: DomainEvent[] = []; + + constructor( + public readonly id: string, + public readonly customerId: string, + private _total: Money, + private _status: 'DRAFT' | 'PAID' | 'CANCELLED' = 'DRAFT' + ) {} + + get status() { return this._status; } + get total() { return this._total; } + + // Enforces domain invariant: an order cannot be marked PAID if status is not DRAFT + markAsPaid(): void { + if (this._status !== 'DRAFT') { + throw new Error(`Invalid transition: Cannot pay an order in ${this._status} status.`); + } + this._status = 'PAID'; + this._domainEvents.push(new OrderPaidEvent(this.id, this._total)); + } + + pullDomainEvents(): DomainEvent[] { + const events = [...this._domainEvents]; + this._domainEvents = []; + return events; + } +} +``` + +### The 4 Non-Negotiable DDD Invariants +1. **Model Purity**: Domain Entities and Value Objects MUST NOT import database libraries (Prisma, Drizzle, TypeORM) or HTTP frameworks (Express, Next.js). They are pure TypeScript/POJOs. +2. **Access Strictly Through Aggregate Roots**: Never allow external controllers or services to mutate child entities directly. All mutations must pass through methods on the Aggregate Root to guarantee data consistency. +3. **Repository Per Aggregate Root**: Never create repositories for child entities or junction tables. Only Aggregate Roots possess repositories (`OrderRepository`, not `OrderItemRepository`). +4. **Ubiquitous Language**: Code identifiers must strictly mirror real business terminology. Reject vague names like `handleData()` in favor of explicit domain verbs like `authorizePayment()`. + +## Orchestration & Integration +- **`scalability-clean-code`**: Aligns DDD tactical models with SOLID, DRY, and Clean Architecture principles. +- **`event-driven-architect`**: Dispatches domain events collected from Aggregate Roots to Kafka / BullMQ. +- **`database-orm-expert`**: Maps pure domain aggregates to persistence schemas via Data Mappers. + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi bersama `scalability-clean-code`, `event-driven-architect`, `database-orm-expert`, dan `saas-architect`. + +### Deskripsi +Panduan arsitektur komprehensif untuk menangani kompleksitas bisnis inti menggunakan *Domain-Driven Design* (DDD). Mencakup Desain Strategis (*Bounded Contexts*, *Context Mapping*, *Ubiquitous Language*, Pemisahan Subdomain) dan Desain Taktis (*Value Objects* imutabel, *Aggregate Roots*, *Domain Events*, *Repositories*, dan pola CQRS). Menekankan pentingnya menjaga logika bisnis tetap murni dan terisolasi dari database, ORM, maupun framework pengiriman web. + +### Kondisi Pemicu +- Merefaktor monolit yang kusut (*Big Ball of Mud*) menjadi *Bounded Contexts* yang mandiri dan terpisah. +- Merancang logika bisnis yang sarat dengan aturan dan invarian ketat (FinTech, sistem penagihan, logistik). +- Menerapkan arsitektur Bersih (*Clean Architecture* / *Hexagonal Architecture*). +- Menentukan payload event yang bersih untuk arsitektur *Event-Driven Microservices*. + +### Pola Repository Khusus Aggregate Root + +```typescript +// src/domain/order/IOrderRepository.ts +import { OrderAggregate } from './OrderAggregate'; + +export interface IOrderRepository { + findById(id: string): Promise; + save(order: OrderAggregate): Promise; // Menyimpan agregat & mempublikasikan Domain Event +} +``` + +### 4 Aturan Emas Domain-Driven Design +1. **Kemurnian Model Bisnis**: Entitas Domain dilarang mengimpor pustaka database atau framework HTTP. Logika domain harus dapat diuji 100% tanpa koneksi database. +2. **Akses Hanya Melalui Aggregate Root**: Objek luar dilarang memodifikasi entitas anak secara langsung. Seluruh perubahan wajib melalui metode pada Aggregate Root. +3. **Satu Repository untuk Satu Root**: Hanya buat Repository untuk Aggregate Root (`OrderRepository`), bukan untuk tabel pembantu (`OrderItemRepository`). +4. **Bahasa Seragam (Ubiquitous Language)**: Kode wajib mencerminkan bahasa asli bisnis (contoh: gunakan `terbitkanFaktur()` daripada `updateStatusTable()`). + +## Integrasi Orkestrasi +- **`scalability-clean-code`**: Menjaga keterbacaan kode dan pemisahan lapisan logika (Separation of Concerns). +- **`event-driven-architect`**: Mengirimkan Domain Events ke broker pesan tanpa merusak transaksi atomik. +- **`database-orm-expert`**: Mengonversi model domain murni ke tabel database melalui Data Mapper. +- **`saas-architect`**: Menyelaraskan batas modul bisnis dengan paket harga dan hak akses pengguna. \ No newline at end of file diff --git a/vibes-plug/skills/e2e-testing-expert/SKILL.md b/vibes-plug/skills/e2e-testing-expert/SKILL.md new file mode 100644 index 000000000..7fccbbee7 --- /dev/null +++ b/vibes-plug/skills/e2e-testing-expert/SKILL.md @@ -0,0 +1,322 @@ +--- +name: e2e-testing-expert +description: "Expert guide for End-to-End (E2E) testing with Playwright, unit/integration testing with Vitest, and CI/CD automated testing pipeline setup / Panduan ahli pengujian End-to-End (E2E) dengan Playwright, pengujian unit/integrasi dengan Vitest, dan otomatisasi CI/CD." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# E2E Testing Expert (Playwright 1.49+ / Vitest 3 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Expert guide for building comprehensive automated test suites using **Playwright 1.49+** (E2E + component testing), **Vitest 3** (unit/integration), and robust CI/CD pipelines. Covers modern testing patterns for Next.js 15, React 19, and API backends. + +### Trigger Conditions +- Writing E2E tests for web applications with Playwright. +- Writing unit or integration tests with Vitest. +- Setting up a full automated testing pipeline in GitHub Actions / GitLab CI. +- Testing React components in isolation with Playwright Component Testing. +- Mocking external services (APIs, databases) in tests. +- Setting up visual regression tests. + +### Playwright 1.49+ — Key Updates + +#### New in 2026 +- **`aria-snapshot`**: Assert the accessibility tree as a snapshot — more semantic than DOM snapshots. +- **`page.addLocatorHandler()`**: Handle dynamic UI (modals, cookie banners) automatically. +- **WebSocket testing**: Built-in `page.expectWebSocketEvent()`. +- **Playwright MCP Server**: Expose a Playwright browser to AI agents via MCP tools. + +#### Project Configuration +```typescript +// playwright.config.ts +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/e2e', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 2 : 0, + workers: process.env.CI ? 4 : undefined, + reporter: [ + ['html', { open: 'never' }], + ['junit', { outputFile: 'results.xml' }], + ], + use: { + baseURL: process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:3000', + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'on-first-retry', + }, + projects: [ + // Setup: seed test DB + { name: 'setup', testMatch: /.*\.setup\.ts/ }, + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + dependencies: ['setup'], + }, + { + name: 'mobile-chrome', + use: { ...devices['Pixel 7'] }, + dependencies: ['setup'], + }, + ], + webServer: { + command: 'npm run dev', + url: 'http://localhost:3000', + reuseExistingServer: !process.env.CI, + }, +}); +``` + +#### Page Object Model (POM) +```typescript +// tests/e2e/pages/LoginPage.ts +import { type Page, type Locator, expect } from '@playwright/test'; + +export class LoginPage { + readonly page: Page; + readonly emailInput: Locator; + readonly passwordInput: Locator; + readonly submitButton: Locator; + + constructor(page: Page) { + this.page = page; + this.emailInput = page.getByLabel('Email'); + this.passwordInput = page.getByLabel('Password'); + this.submitButton = page.getByRole('button', { name: 'Sign in' }); + } + + async goto() { + await this.page.goto('/login'); + } + + async login(email: string, password: string) { + await this.emailInput.fill(email); + await this.passwordInput.fill(password); + await this.submitButton.click(); + await this.page.waitForURL('/dashboard'); + } +} +``` + +#### API Mocking with `page.route()` +```typescript +test('shows error when API fails', async ({ page }) => { + // Intercept and mock API response + await page.route('**/api/users', (route) => { + route.fulfill({ + status: 500, + body: JSON.stringify({ error: 'Internal server error' }), + contentType: 'application/json', + }); + }); + + await page.goto('/users'); + await expect(page.getByRole('alert')).toContainText('Something went wrong'); +}); +``` + +#### Accessibility Assertions (aria-snapshot) +```typescript +test('navigation is accessible', async ({ page }) => { + await page.goto('/'); + + // Assert accessibility tree structure + await expect(page.locator('nav')).toMatchAriaSnapshot(` + - navigation: + - link "Home" + - link "Products" + - link "Pricing" + - link "Sign in" + `); +}); +``` + +#### Auth State Reuse (storageState) +```typescript +// tests/e2e/auth.setup.ts +import { test as setup } from '@playwright/test'; + +setup('authenticate', async ({ page }) => { + await page.goto('/login'); + await page.getByLabel('Email').fill('test@example.com'); + await page.getByLabel('Password').fill('password'); + await page.getByRole('button', { name: 'Sign in' }).click(); + await page.waitForURL('/dashboard'); + + // Save session state for reuse in all tests + await page.context().storageState({ path: 'playwright/.auth/user.json' }); +}); + +// tests/e2e/dashboard.spec.ts +import { test } from '@playwright/test'; + +test.use({ storageState: 'playwright/.auth/user.json' }); + +test('dashboard loads correctly', async ({ page }) => { + await page.goto('/dashboard'); + // Already authenticated — no login needed +}); +``` + +### Vitest 3 — Unit & Integration Testing + +#### Configuration +```typescript +// vitest.config.ts +import { defineConfig } from 'vitest/config'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [react()], + test: { + environment: 'jsdom', + globals: true, + setupFiles: ['./tests/setup.ts'], + coverage: { + provider: 'v8', + reporter: ['text', 'lcov', 'html'], + thresholds: { lines: 80, functions: 80 }, + }, + }, +}); +``` + +#### React Component Testing +```typescript +import { render, screen, userEvent } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { Counter } from './Counter'; + +describe('Counter', () => { + it('increments count on button click', async () => { + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole('button', { name: 'Increment' })); + + expect(screen.getByText('Count: 1')).toBeInTheDocument(); + }); + + it('calls onMaxReached when limit hit', async () => { + const onMaxReached = vi.fn(); + const user = userEvent.setup(); + render(); + + await user.click(screen.getByRole('button', { name: 'Increment' })); + + expect(onMaxReached).toHaveBeenCalledOnce(); + }); +}); +``` + +#### Server Action / API Route Testing +```typescript +import { describe, it, expect, beforeEach } from 'vitest'; +import { testClient } from 'hono/testing'; +import { app } from '../src/server'; +import { resetTestDb } from './helpers/db'; + +describe('POST /api/users', () => { + beforeEach(resetTestDb); + + it('creates a new user', async () => { + const client = testClient(app); + const res = await client.api.users.$post({ + json: { name: 'Alice', email: 'alice@example.com' }, + }); + + expect(res.status).toBe(201); + const data = await res.json(); + expect(data.email).toBe('alice@example.com'); + }); +}); +``` + +### GitHub Actions CI Pipeline +```yaml +# .github/workflows/test.yml +name: CI Tests + +on: [push, pull_request] + +jobs: + unit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: '22', cache: 'pnpm' } + - run: pnpm install --frozen-lockfile + - run: pnpm run typecheck + - run: pnpm run test:unit --coverage + + e2e: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: '22', cache: 'pnpm' } + - run: pnpm install --frozen-lockfile + - run: pnpm exec playwright install --with-deps chromium + - run: pnpm run test:e2e + - uses: actions/upload-artifact@v4 + if: failure() + with: + name: playwright-report + path: playwright-report/ +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Deskripsi +Panduan ahli untuk membangun test suite otomatis yang komprehensif menggunakan **Playwright 1.49+** (E2E + component testing), **Vitest 3** (unit/integrasi), dan pipeline CI/CD yang kuat. Mencakup pola pengujian modern untuk Next.js 15, React 19, dan backend API. + +### Kondisi Pemicu +- Menulis E2E test untuk aplikasi web dengan Playwright. +- Menulis unit atau integration test dengan Vitest. +- Menyiapkan pipeline pengujian otomatis di GitHub Actions / GitLab CI. +- Menguji komponen React secara terisolasi. +- Mocking layanan eksternal (API, database) dalam test. +- Menyiapkan visual regression test. + +### Playwright 1.49+ — Fitur Baru 2026 +- **`aria-snapshot`**: Assert accessibility tree sebagai snapshot. +- **`page.addLocatorHandler()`**: Tangani UI dinamis (modal, cookie banner) secara otomatis. +- **WebSocket testing**: `page.expectWebSocketEvent()` bawaan. +- **Playwright MCP Server**: Ekspos browser Playwright ke agen AI via MCP. + +### Page Object Model (POM) +Enkapsulasi selektor dan tindakan halaman dalam kelas terpisah untuk mengurangi duplikasi dan meningkatkan keterbacaan test. + +### Mocking API dengan `page.route()` +Gunakan `page.route()` untuk mencegat permintaan jaringan dan mengembalikan respons palsu — mengisolasi frontend dari backend dalam E2E test. + +### Aksesibilitas dengan aria-snapshot +Gunakan `toMatchAriaSnapshot()` untuk memvalidasi struktur aksesibilitas navigasi, form, dan komponen interaktif — lebih semantis dari snapshot DOM biasa. + +### Auth State Reuse (storageState) +Gunakan `storageState` untuk menyimpan state sesi setelah login sekali dan menggunakannya kembali di semua test yang memerlukan autentikasi — menghemat waktu secara signifikan. + +### Vitest 3 — Unit & Integration Testing +Vitest 3 adalah test runner yang cepat berbasis Vite dengan kompatibilitas Jest penuh. Gunakan untuk unit test React component, server action, dan logika bisnis. + +### Pipeline CI GitHub Actions +Pisahkan job `unit` dan `e2e` untuk feedback paralel yang lebih cepat. Upload `playwright-report` sebagai artifact saat gagal untuk debugging. \ No newline at end of file diff --git a/vibes-plug/skills/ecommerce-expert/SKILL.md b/vibes-plug/skills/ecommerce-expert/SKILL.md new file mode 100644 index 000000000..45346c360 --- /dev/null +++ b/vibes-plug/skills/ecommerce-expert/SKILL.md @@ -0,0 +1,195 @@ +--- +name: ecommerce-expert +description: "Expert guide for e-commerce architecture (Shopify Storefront, Medusa.js, Saleor), product catalogs, cart/checkout UX, and order management / Panduan ahli arsitektur e-commerce (Shopify, Medusa.js, Saleor), katalog produk, UX keranjang/checkout, dan manajemen pesanan." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# E-Commerce Architecture & Modern Storefront Expert (2026 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Production guide for high-converting e-commerce architectures, headless storefronts (Medusa.js v2, Shopify Storefront API, Saleor), inventory atomicity, and multi-rail payment integrations (DOKU Checkout, SNAP BI, Stripe). Covers atomic stock reservations to prevent race-condition overselling during flash sales, cart session state machines, structured schema markup (`Product`, `Offer`, `BreadcrumbList`), and localized checkout workflows. + +### Trigger Conditions +- Designing or developing an e-commerce platform, marketplace, or custom storefront. +- Integrating headless commerce engines (Medusa.js v2, Shopify Storefront API). +- Preventing inventory race conditions during high-concurrency checkout traffic. +- Integrating localized Indonesian payment methods (DOKU Virtual Account, QRIS, Direct Debit). +- Optimizing product page Core Web Vitals and SEO schema. + +### Atomic Inventory Reservation Pattern (PostgreSQL / Drizzle) +Prevents overselling during high-concurrency flash sales using row-level pessimistic locking (`FOR UPDATE`): + +```typescript +// src/services/inventory.service.ts +import { db } from '@/lib/db'; +import { sql } from 'drizzle-orm'; + +export interface ReserveStockResult { + success: boolean; + orderId?: string; + errorMessage?: string; +} + +export async function reserveProductStockAtomic( + productId: string, + requestedQuantity: number, + orderId: string +): Promise { + return await db.transaction(async (tx) => { + // 1. Lock the inventory row strictly for update + const [product] = await tx.execute(sql` + SELECT id, stock_quantity, price_cents, is_active + FROM products + WHERE id = ${productId} + FOR UPDATE + `); + + if (!product || !product.is_active) { + return { success: false, errorMessage: 'Product is unavailable.' }; + } + + if (product.stock_quantity < requestedQuantity) { + return { success: false, errorMessage: 'Insufficient stock remaining.' }; + } + + // 2. Decrement available inventory atomically + await tx.execute(sql` + UPDATE products + SET stock_quantity = stock_quantity - ${requestedQuantity}, + updated_at = NOW() + WHERE id = ${productId} + `); + + // 3. Create provisional stock reservation record (15-minute TTL) + await tx.execute(sql` + INSERT INTO stock_reservations (order_id, product_id, quantity, expires_at) + VALUES (${orderId}, ${productId}, ${requestedQuantity}, NOW() + INTERVAL '15 minutes') + `); + + return { success: true, orderId }; + }); +} +``` + +### Medusa.js v2 Workflow Engine Integration + +```typescript +// src/workflows/create-order-workflow.ts +import { createWorkflow, WorkflowResponse, StepResponse, createStep } from '@medusajs/framework/workflows-sdk'; + +const reserveInventoryStep = createStep( + 'reserve-inventory-step', + async ({ orderId, items }: { orderId: string; items: any[] }, { container }) => { + // Execute atomic reservation + return new StepResponse({ status: 'reserved', orderId }, { orderId, items }); + }, + async (compensatingData, { container }) => { + // Compensation logic if downstream payment fails: roll back reserved stock + console.log(`[Compensation] Releasing reserved stock for order ${compensatingData.orderId}`); + } +); + +export const placeAtomicOrderWorkflow = createWorkflow( + 'place-atomic-order', + function (input: { orderId: string; items: any[]; paymentDetails: any }) { + const reservation = reserveInventoryStep(input); + return new WorkflowResponse(reservation); + } +); +``` + +### E-Commerce SEO Schema Markup (JSON-LD) + +```tsx +// src/components/seo/ProductSchema.tsx +export function ProductSchema({ product }: { product: any }) { + const schema = { + '@context': 'https://schema.org', + '@type': 'Product', + name: product.title, + image: product.thumbnailUrl, + description: product.description, + sku: product.sku, + offers: { + '@type': 'Offer', + price: (product.priceCents / 100).toFixed(2), + priceCurrency: 'IDR', + availability: product.inStock ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock', + url: `https://vibesstore.internal/products/${product.handle}`, + }, + }; + + return + + +''', + } + + +def scaffold_project( + name: str, + output_dir: Path, + template: str = "nextjs", + features: Optional[List[str]] = None, + dry_run: bool = False, +) -> Dict: + """Scaffold a complete frontend project.""" + features = features or [] + project_path = output_dir / name + + if project_path.exists() and not dry_run: + return {"error": f"Directory already exists: {project_path}"} + + template_config = TEMPLATES.get(template) + if not template_config: + return {"error": f"Unknown template: {template}"} + + created_files = [] + + # Create project directory + if not dry_run: + project_path.mkdir(parents=True, exist_ok=True) + + # Generate base structure + created_files.extend( + generate_structure(project_path, template_config["structure"], dry_run) + ) + + # Generate config files + created_files.extend( + generate_config_files(project_path, template, name, features, dry_run) + ) + + # Add feature files + for feature in features: + if feature in FEATURES: + for file_path, content_key in FEATURES[feature]["files"].items(): + full_path = project_path / file_path + if not dry_run: + full_path.parent.mkdir(parents=True, exist_ok=True) + content = FILE_CONTENTS.get(content_key, f"export const {content_key.replace('-', '_')} = () => {{\n /* Functional implementation for {content_key} */\n}};\n") + full_path.write_text(content) + created_files.append(str(full_path)) + + return { + "name": name, + "template": template, + "template_name": template_config["name"], + "features": features, + "path": str(project_path), + "files_created": len(created_files), + "files": created_files, + "next_steps": [ + f"cd {name}", + "npm install", + "npm run dev", + ], + } + + +def print_result(result: Dict) -> None: + """Print scaffolding result.""" + if "error" in result: + print(f"Error: {result['error']}", file=sys.stderr) + return + + print(f"\n{'='*60}") + print(f"Project Scaffolded: {result['name']}") + print(f"{'='*60}") + print(f"Template: {result['template_name']}") + print(f"Location: {result['path']}") + print(f"Files Created: {result['files_created']}") + + if result["features"]: + print(f"Features: {', '.join(result['features'])}") + + print(f"\nNext Steps:") + for step in result["next_steps"]: + print(f" $ {step}") + + print(f"{'='*60}\n") + + +def main(): + parser = argparse.ArgumentParser( + description="Scaffold a frontend project with best practices" + ) + parser.add_argument( + "name", + help="Project name (kebab-case recommended)" + ) + parser.add_argument( + "--dir", "-d", + default=".", + help="Output directory (default: current directory)" + ) + parser.add_argument( + "--template", "-t", + choices=list(TEMPLATES.keys()), + default="nextjs", + help="Project template (default: nextjs)" + ) + parser.add_argument( + "--features", "-f", + help="Comma-separated features to add (auth,api,forms,testing,storybook)" + ) + parser.add_argument( + "--list-templates", + action="store_true", + help="List available templates" + ) + parser.add_argument( + "--list-features", + action="store_true", + help="List available features" + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Show what would be created without creating files" + ) + parser.add_argument( + "--json", + action="store_true", + help="Output in JSON format" + ) + + args = parser.parse_args() + + if args.list_templates: + print("\nAvailable Templates:") + for key, template in TEMPLATES.items(): + print(f" {key}: {template['name']}") + print(f" {template['description']}") + return + + if args.list_features: + print("\nAvailable Features:") + for key, feature in FEATURES.items(): + print(f" {key}: {feature['description']}") + deps = ", ".join(feature.get("dependencies", [])) + if deps: + print(f" Adds: {deps}") + return + + features = [] + if args.features: + features = [f.strip() for f in args.features.split(",")] + invalid = [f for f in features if f not in FEATURES] + if invalid: + print(f"Unknown features: {', '.join(invalid)}", file=sys.stderr) + print(f"Valid features: {', '.join(FEATURES.keys())}") + sys.exit(1) + + result = scaffold_project( + name=args.name, + output_dir=Path(args.dir), + template=args.template, + features=features, + dry_run=args.dry_run, + ) + + if args.json: + print(json.dumps(result, indent=2)) + else: + print_result(result) + + +if __name__ == "__main__": + main() diff --git a/vibes-plug/skills/seo/SKILL.md b/vibes-plug/skills/seo/SKILL.md new file mode 100644 index 000000000..9fd170703 --- /dev/null +++ b/vibes-plug/skills/seo/SKILL.md @@ -0,0 +1,259 @@ +--- +name: seo +description: "Run a broad SEO audit across technical SEO, on-page SEO, schema, sitemaps, content quality, AI search readiness, and GEO / Audit SEO menyeluruh (Technical, On-Page, Schema, Sitemap, E-E-A-T, GEO)" +author: "Roedy Rustam" +version: "4.3.0" +--- + +# SEO Expert (2026 — AI Mode & Core Web Vitals Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with relevant domain skills like `brainstorming`, `zero-to-prod-orchestrator`, and `session-memory-manager` to ensure cohesive execution. + +### Description +Comprehensive SEO audit covering technical SEO, on-page optimization, structured data, sitemaps, Core Web Vitals, E-E-A-T signals, and **Generative Engine Optimization (GEO)** for AI-powered search (Google AI Mode, ChatGPT Search, Perplexity). + +### Trigger Conditions +- Running a full SEO audit on an existing web application. +- Optimizing technical SEO for a new Next.js / Astro site. +- Adding structured data (JSON-LD) for rich results and AI citation. +- Optimizing Core Web Vitals (LCP, INP, CLS). +- Preparing a site for Google AI Mode and ChatGPT Search indexing. +- Setting up a sitemap and `robots.txt`. + +### 2026 SEO Landscape Changes + +| 2024 (Old) | 2026 (Current) | +|---|---| +| AI Overviews (SGE) | **Google AI Mode** — integrated AI answers | +| FID metric (deprecated) | **INP** (Interaction to Next Paint) | +| Keyword density focus | **Topical authority + E-E-A-T** | +| Backlinks only | **Citations in AI responses** | +| `robots.txt` only | `robots.txt` + **`/llms.txt`** | + +### Technical SEO Checklist + +#### Core Web Vitals (2026 Targets) +``` +LCP (Largest Contentful Paint) < 2.5s +INP (Interaction to Next Paint) < 200ms ← replaced FID +CLS (Cumulative Layout Shift) < 0.1 +TTFB (Time to First Byte) < 600ms +``` + +**INP Optimization** (the new critical metric): +```typescript +// INP is degraded by long tasks blocking the main thread +// Solution: Use React's useTransition to defer non-critical updates +import { useTransition } from 'react'; + +function SearchInput() { + const [isPending, startTransition] = useTransition(); + + const handleChange = (e: React.ChangeEvent) => { + startTransition(() => { + // Defer the expensive filtering to not block INP + setFilteredResults(filterData(e.target.value)); + }); + }; + return ; +} +``` + +#### Crawlability & Indexing +```typescript +// Next.js 15 — metadata API for complete SEO +// app/layout.tsx +export const metadata: Metadata = { + metadataBase: new URL('https://myapp.com'), + title: { + default: 'My SaaS — One-line value proposition', + template: '%s | My SaaS', + }, + description: '150 characters max. Include primary keyword naturally.', + openGraph: { + type: 'website', + url: 'https://myapp.com', + siteName: 'My SaaS', + images: [{ url: '/og.png', width: 1200, height: 630 }], + }, + twitter: { card: 'summary_large_image', creator: '@handle' }, + robots: { index: true, follow: true }, + alternates: { canonical: 'https://myapp.com' }, +}; +``` + +```typescript +// Dynamic sitemap.ts (Next.js App Router) +// app/sitemap.ts +import { MetadataRoute } from 'next'; + +export default async function sitemap(): Promise { + const posts = await getBlogPosts(); + + return [ + { url: 'https://myapp.com', lastModified: new Date(), changeFrequency: 'weekly', priority: 1 }, + { url: 'https://myapp.com/features', lastModified: new Date(), changeFrequency: 'monthly', priority: 0.8 }, + ...posts.map(p => ({ + url: `https://myapp.com/blog/${p.slug}`, + lastModified: new Date(p.updatedAt), + changeFrequency: 'monthly' as const, + priority: 0.6, + })), + ]; +} +``` + +### Structured Data (JSON-LD) for AI Citation +```html + + + + + +``` + +### GEO — Google AI Mode Optimization +Google AI Mode (formerly AI Overviews) now powers the top of search results: +- **Be the source**: Write comprehensive, authoritative content on your core topics. +- **Q&A format**: Structure content as questions and answers — AI Mode quotes these directly. +- **AEO Extraction Sentence**: Write one 25–40 word sentence that answers "What is [product]?" immediately after the H1. This is the sentence AI engines extract. +- **Factual and specific**: Include statistics, named entities, and dates. +- **Speed**: AI Mode favors fast-loading pages (TTFB < 600ms). + +#### The 2026 AI Search Landscape +| AI Engine | Source | Citable Content | Key Signal | +|---|---|---|---| +| **Google AI Mode** | Google index + Gemini | Yes — with source links | E-E-A-T, structured data | +| **ChatGPT Search** | Bing index + GPT-4o | Yes — with citations | Bing ranking, freshness | +| **Perplexity** | Real-time web crawl | Yes — prominent citations | Authority, specificity | + +#### `/llms.txt` — AI Indexing Protocol +Add an `/llms.txt` file at your domain root: +``` +# /llms.txt +# AI-friendly site map for LLM indexers +## Product +- [Features](/features): Complete feature list with pricing +## Content +- [Blog](/blog): Technical articles +``` + +#### Landing Page SEO/AEO Narrative Arc +Follow this exact order for landing pages: +1. Hero — H1 + AEO sentence + CTA +2. Problem — Audience pain, no product mention yet +3. Solution — Introduce product as the answer +4. Features as Benefits — Table format +5. Social Proof & FAQ (under 50 words each) + +### On-Page SEO Standards +``` +H1: One per page — primary keyword, compelling, < 60 chars +H2: Section headers — secondary keywords +H3: Sub-sections — long-tail keywords, FAQ answers +Meta Title: < 60 chars — keyword + brand +Meta Description: < 155 chars — keyword + CTA + benefit +URL: lowercase, hyphens, keyword-in-slug, < 5 segments +Images: Descriptive alt text, WebP format, lazy loading +Internal links: 3-5 per long-form page to related content +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `brainstorming`, `zero-to-prod-orchestrator`, dan `session-memory-manager` untuk memastikan eksekusi yang kohesif. + +### Deskripsi +Audit SEO komprehensif mencakup SEO teknikal, optimasi on-page, data terstruktur, sitemap, Core Web Vitals, sinyal E-E-A-T, dan **Generative Engine Optimization (GEO)** untuk pencarian bertenaga AI (Google AI Mode, ChatGPT Search, Perplexity). + +### Kondisi Pemicu +- Menjalankan audit SEO penuh pada aplikasi web yang ada. +- Mengoptimalkan SEO teknikal untuk situs Next.js / Astro baru. +- Menambahkan data terstruktur (JSON-LD) untuk rich result dan kutipan AI. +- Mengoptimalkan Core Web Vitals (LCP, INP, CLS). +- Mempersiapkan situs untuk indexing Google AI Mode dan ChatGPT Search. + +### Perubahan Lanskap SEO 2026 + +| 2024 (Lama) | 2026 (Sekarang) | +|---|---| +| AI Overviews (SGE) | **Google AI Mode** — jawaban AI terintegrasi | +| Metrik FID (dihentikan) | **INP** (Interaction to Next Paint) | +| Fokus kepadatan keyword | **Otoritas topikal + E-E-A-T** | +| Hanya backlink | **Kutipan dalam respons AI** | +| Hanya `robots.txt` | `robots.txt` + **`/llms.txt`** | + +### Checklist SEO Teknikal + +#### Core Web Vitals (Target 2026) +- LCP < 2.5 detik +- **INP < 200ms** ← menggantikan FID +- CLS < 0.1 +- TTFB < 600ms + +**Optimasi INP**: Metrik kritis baru yang mengukur responsivitas interaksi. Gunakan `useTransition` React untuk menunda pembaruan non-kritis agar tidak memblokir thread utama. + +#### Crawlability & Indexing +Gunakan Metadata API Next.js 15 untuk SEO lengkap: `title`, `description`, `openGraph`, `twitter`, `robots`, `alternates.canonical`. Buat sitemap dinamis dengan `app/sitemap.ts` yang menyertakan semua halaman statis dan konten dinamis. + +### Data Terstruktur (JSON-LD) untuk Kutipan AI +Tambahkan schema `Organization` untuk membangun entitas merek dan schema `SoftwareApplication` untuk produk SaaS — termasuk `aggregateRating` jika tersedia. + +### GEO — Optimasi AI Mode & Landing Page AEO +Google AI Mode (sebelumnya AI Overviews) dan Perplexity sangat menyukai format berikut: +- **Kalimat Ekstraksi AEO**: Buat satu kalimat ringkas 25–40 kata ("Apa itu [produk]?") di blockquote setelah H1. +- Tulis konten Q&A dan sertakan statistik spesifik. +- **Alur Narasi Landing Page**: Hero (H1+AEO) -> Problem -> Solution -> Features -> Social Proof -> FAQ (tiap jawaban <50 kata). +- Tambahkan `/llms.txt` sebagai indeks situs yang dapat dibaca AI. +- Kecepatan: Halaman harus memuat sangat cepat (TTFB < 600ms). + +### Standar SEO On-Page +H1 satu per halaman, H2 untuk header seksi, meta title < 60 karakter, meta deskripsi < 155 karakter, URL lowercase dengan tanda hubung dan keyword di slug, alt text deskriptif untuk semua gambar, 3-5 internal link per halaman long-form. + diff --git a/vibes-plug/skills/seo/references/cwv-thresholds.md b/vibes-plug/skills/seo/references/cwv-thresholds.md new file mode 100644 index 000000000..c4631d60a --- /dev/null +++ b/vibes-plug/skills/seo/references/cwv-thresholds.md @@ -0,0 +1,108 @@ + +# Core Web Vitals Thresholds (February 2026) + +## Current Metrics + +| Metric | Good | Needs Improvement | Poor | +|--------|------|-------------------|------| +| LCP (Largest Contentful Paint) | ≤2.5s | 2.5s–4.0s | >4.0s | +| INP (Interaction to Next Paint) | ≤200ms | 200ms–500ms | >500ms | +| CLS (Cumulative Layout Shift) | ≤0.1 | 0.1–0.25 | >0.25 | + +## Key Facts +- INP replaced FID (First Input Delay) on **March 12, 2024**. FID was fully removed from all Chrome tools (CrUX API, PageSpeed Insights, Lighthouse) on **September 9, 2024**. INP is the sole interactivity metric. +- Evaluation uses the **75th percentile** of real user data (field data from CrUX). +- Google assesses at the **page level** and the **origin level**. +- Core Web Vitals are a **tiebreaker** ranking signal: they matter most when content quality is similar between competitors. +- **Thresholds unchanged since original definitions**: ignore claims of "tightened thresholds" from SEO blogs. +- December 2025 core update appeared to weight **mobile CWV more heavily**. +- As of October 2025: **57.1%** desktop sites and **49.7%** mobile sites pass all three CWV. + +## LCP Subparts (February 2025 CrUX Addition) + +LCP can now be broken into diagnostic subparts: + +| Subpart | What It Measures | Target | +|---------|------------------|--------| +| **TTFB** | Time to First Byte (server response) | <800ms | +| **Resource Load Delay** | Time from TTFB to resource request start | Minimize | +| **Resource Load Time** | Time to download the LCP resource | Depends on size | +| **Element Render Delay** | Time from resource loaded to rendered | Minimize | + +**Total LCP = TTFB + Resource Load Delay + Resource Load Time + Element Render Delay** + +Use this breakdown to identify which phase is causing LCP issues. + +## Soft Navigations API (Experimental) + +**Chrome 139+ Origin Trial (July 2025)**: First step toward measuring CWV in SPAs. + +- Addresses the long-standing SPA measurement blind spot +- Currently experimental, **no ranking impact yet** +- Detects "soft navigations" (URL changes without full page load) +- May affect future SPA CWV measurement + +**Detection:** Check for SPA frameworks (React, Vue, Angular, Svelte) and warn about current CWV measurement limitations. + +## Measurement Sources + +### Field Data (Real Users) +- Chrome User Experience Report (CrUX) +- PageSpeed Insights (uses CrUX data) +- Search Console Core Web Vitals report + +### Lab Data (Simulated) +- Lighthouse +- WebPageTest +- Chrome DevTools + +> Field data is what Google uses for ranking. Lab data is useful for debugging. + +## Common Bottlenecks + +### LCP (Largest Contentful Paint) +- Unoptimized hero images (compress, use WebP/AVIF, add preload) +- Render-blocking CSS/JS (defer, async, critical CSS inlining) +- Slow server response (TTFB >200ms: use edge CDN, caching) +- Third-party script blocking (defer analytics, chat widgets) +- Web font loading delay (use font-display: swap + preload) + +### INP (Interaction to Next Paint) +- Long JavaScript tasks on main thread (break into smaller tasks <50ms) +- Heavy event handlers (debounce, use requestAnimationFrame) +- Excessive DOM size (>1,500 elements is concerning) +- Third-party scripts hijacking main thread +- Synchronous XHR or localStorage operations +- Layout thrashing (multiple forced reflows) + +### CLS (Cumulative Layout Shift) +- Images/iframes without width/height dimensions +- Dynamically injected content above existing content +- Web fonts causing layout shift (use font-display: swap + preload) +- Ads/embeds without reserved space +- Late-loading content pushing down the page + +## Optimization Priority + +1. **LCP**: Most impactful for perceived performance +2. **CLS**: Most common issue affecting user experience +3. **INP**: Matters most for interactive applications + +## Tools + +```bash +# PageSpeed Insights API +curl "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=URL&key=API_KEY" + +# Lighthouse CLI +npx lighthouse URL --output json --output-path report.json +``` + +## Performance Tooling Updates (2025) + +- **Lighthouse 13.0** (October 2025): Major audit restructuring with reorganized performance categories and updated scoring weights. Lighthouse is a lab tool (simulated conditions): always cross-reference with CrUX field data for real-world performance. +- **CrUX Vis** replaced the CrUX Dashboard (November 2025). The old Looker Studio dashboard was deprecated. Use [CrUX Vis](https://cruxvis.withgoogle.com) or the CrUX API directly. +- **LCP subparts** added to CrUX (February 2025): Time to First Byte (TTFB), resource load delay, resource load time, and element render delay are now available as sub-components of LCP in CrUX data. +- **Google Search Console 2025 features** (December 2025): AI-powered configuration for automated analysis. Branded vs. non-branded queries filter. Hourly data available in API. Custom chart annotations. Social channels tracking. + +> **Mobile-first indexing** is 100% complete as of July 5, 2024. Google now crawls and indexes ALL websites exclusively with the mobile Googlebot user-agent. Ensure your mobile version contains all critical content, structured data, and meta tags. diff --git a/vibes-plug/skills/seo/references/eeat-framework.md b/vibes-plug/skills/seo/references/eeat-framework.md new file mode 100644 index 000000000..90379b909 --- /dev/null +++ b/vibes-plug/skills/seo/references/eeat-framework.md @@ -0,0 +1,214 @@ +# E-E-A-T Evaluation Framework +## Updated per Google Quality Rater Guidelines: September 11, 2025 +## Plus December 2025 Core Update Implications + +## Overview + +E-E-A-T = **E**xperience, **E**xpertise, **A**uthoritativeness, **T**rustworthiness + +Trustworthiness is the most important factor. It is assessed based on the +other three signals plus direct trust indicators. + +## CRITICAL: December 2025 Core Update + +> **E-E-A-T now applies to ALL competitive queries, not just YMYL.** + +The December 2025 core update was described as a "watershed moment" that: +- Extended E-E-A-T evaluation to virtually all competitive queries +- Made author attribution standards tighter across all categories +- Penalized anonymous or generic authorship even for non-YMYL content +- Significantly improved AI content quality detection + +**Impact by industry:** +| Industry | Traffic Drops | +|----------|--------------| +| Affiliate sites | 71% average decline | +| Health/YMYL | 67% average decline | +| E-commerce | 52% average decline | + +**Key takeaway:** Even entertainment and lifestyle content now requires demonstrated expertise. Generic content no longer ranks. + +## YMYL (Your Money or Your Life) + +Topics requiring **highest** E-E-A-T standards (but E-E-A-T now matters everywhere): +- Health and safety +- Financial advice and transactions +- Legal information +- News and current events +- **Elections and civic trust** (added Sept 2025) +- **Democratic processes** (added Sept 2025) +- Groups of people (potential for harm) + +--- + +## Experience (Weight: 20%) + +First-hand knowledge and personal involvement with the topic. + +### Signals to Check +- [ ] Author has demonstrable first-hand experience with the topic +- [ ] Content includes original photos, screenshots, or data +- [ ] Case studies or real-world examples with specific details +- [ ] Personal process documentation or methodology descriptions +- [ ] Before/after results or outcome data +- [ ] Specific anecdotes that couldn't be fabricated + +### Scoring +- **Strong**: Multiple first-hand experience signals, original content +- **Moderate**: Some personal experience evident +- **Weak**: Generic information, no personal touch +- **None**: Clearly AI-generated or scraped content + +--- + +## Expertise (Weight: 25%) + +Formal qualifications, training, and demonstrated knowledge. + +### Signals to Check +- [ ] Author credentials relevant to topic (bio, certifications) +- [ ] Technical accuracy and depth appropriate for audience +- [ ] Claims supported by evidence or sources +- [ ] Specialized vocabulary used correctly +- [ ] Up-to-date with current developments in the field +- [ ] Byline with author name and credentials visible + +### Scoring +- **Strong**: Verified credentials, deep technical accuracy +- **Moderate**: Demonstrable knowledge, some credentials +- **Weak**: Surface-level information, no credentials +- **None**: Factual errors, misinformation + +--- + +## Authoritativeness (Weight: 25%) + +Recognition by others as a go-to source. + +### Signals to Check +- [ ] Site recognized as authority in its niche +- [ ] Author recognized as expert (external citations, speaking, publications) +- [ ] Content cited by other authoritative sources +- [ ] Industry awards, certifications, or accreditations +- [ ] Consistent publication history in the topic area +- [ ] Featured in reputable media outlets +- [ ] Professional affiliations + +### Scoring +- **Strong**: Widely recognized authority, cited by others +- **Moderate**: Growing recognition, some external validation +- **Weak**: No external recognition +- **None**: Negative reputation, known for misinformation + +--- + +## Trustworthiness (Weight: 30%) + +The most important factor, overall reliability and transparency. + +### Signals to Check +- [ ] Clear contact information (physical address, phone, email) +- [ ] Privacy policy and terms of service +- [ ] HTTPS with valid certificate +- [ ] Transparent about who creates content and why +- [ ] Customer reviews and testimonials +- [ ] Corrections and update history visible +- [ ] No deceptive practices (hidden ads, clickbait) +- [ ] Secure payment processing (for e-commerce) +- [ ] Return/refund policy visible + +### Scoring +- **Strong**: Full transparency, verified business, positive reputation +- **Moderate**: Good trust signals, minor gaps +- **Weak**: Missing key trust signals +- **None**: Deceptive practices, scam indicators + +--- + +## September 2025 QRG Updates + +### AI Content Assessment +Raters now formally evaluate whether content appears AI-generated: +- AI content is **acceptable** if it demonstrates genuine E-E-A-T +- Low-quality AI content (generic, no unique value) is penalized +- The presence of AI-generated content is not inherently penalizing +- What matters: does the content provide unique value regardless of creation method? + +### Markers of Low-Quality AI Content +- Generic phrasing without specificity +- Lack of original insight or unique perspective +- No first-hand experience signals +- Factual inaccuracies +- Repetitive structure across multiple pages +- No author attribution or expertise signals + +### New Spam Categories +- **Expired domain abuse**: Buying expired domains for their backlinks +- **Site reputation abuse**: Using reputable site to host low-quality content +- **Scaled content abuse**: Mass-producing content without value + +### AI Overview Evaluation +Raters assess quality of AI-generated summaries in search results. + +### RSL 1.0 (Really Simple Licensing) +New machine-readable content licensing standard (December 2025) for AI training: +- Backed by: Reddit, Yahoo, Medium, Quora, Cloudflare, Akamai, Creative Commons +- Allows publishers to specify AI licensing terms +- Augments robots.txt for AI-specific permissions + +--- + +## Experience Signals Are Critical Differentiators + +The December 2025 update elevated the "Experience" dimension as a key differentiator: +- First-person narrative ("I tested this...", "In my experience...") +- Original photos and screenshots (not stock images) +- Specific examples with verifiable details +- Process documentation showing actual work done + +**Why:** AI can generate expertise-sounding content but cannot fabricate genuine experience. + +--- + +## Overall Scoring Guide + +| Score | Description | +|-------|-------------| +| 90-100 | Exceptional E-E-A-T, authority site, recognized expert, full transparency | +| 70-89 | Strong E-E-A-T, demonstrated expertise, good trust signals | +| 50-69 | Moderate E-E-A-T, some signals, room for improvement | +| 30-49 | Weak E-E-A-T, minimal signals, significant gaps | +| 0-29 | Very low E-E-A-T, no visible signals, potential trust issues | + +--- + +## Improvement Recommendations by Score + +### 0-29 (Critical) +1. Add contact information and about page +2. Establish author identity with credentials +3. Implement HTTPS +4. Remove deceptive elements + +### 30-49 (Major) +1. Add author bios with credentials +2. Include first-hand experience content +3. Get external citations/mentions +4. Add customer testimonials + +### 50-69 (Moderate) +1. Deepen content with original research +2. Build topical authority through content clusters +3. Pursue industry recognition +4. Document processes and methodologies + +### 70-89 (Minor) +1. Maintain freshness with regular updates +2. Expand author presence across platforms +3. Pursue speaking/publication opportunities +4. Add video/multimedia demonstrating expertise + +### 90-100 (Maintenance) +1. Continue publishing high-quality content +2. Monitor and respond to reputation issues +3. Keep credentials and certifications current diff --git a/vibes-plug/skills/seo/references/quality-gates.md b/vibes-plug/skills/seo/references/quality-gates.md new file mode 100644 index 000000000..008652900 --- /dev/null +++ b/vibes-plug/skills/seo/references/quality-gates.md @@ -0,0 +1,155 @@ +# Content Quality Gates + +## Minimum Word Counts by Page Type + +| Page Type | Min Words | Unique Content % | Notes | +|-----------|-----------|-----------------|-------| +| Homepage | 500 | 100% | Must clearly communicate value proposition | +| Service / Feature Page | 800 | 100% | Detailed explanation of offering | +| Location (Primary) | 600 | 60%+ | City headquarters or main service area | +| Location (Secondary) | 500 | 40%+ | Satellite locations | +| Blog Post | 1,500 | 100% | In-depth, valuable content | +| Product Page | 400 | 80%+ | Unique descriptions, specs | +| Category Page | 400 | 100% | Unique intro, not just product listings | +| About Page | 400 | 100% | Company story, team, values | +| Landing Page | 600 | 100% | Focused conversion content | +| FAQ Page | 800 | 100% | Comprehensive Q&A | + +--- + +## Location Page Thresholds + +### Warning Level (30+ pages) +- ⚠️ **WARNING** at 30+ location pages +- Enforce 60%+ unique content per page +- Content must include: + - Unique local information (landmarks, neighborhoods) + - Location-specific services or offerings + - Local team or staff information + - Genuine customer testimonials from that area + +### Hard Stop (50+ pages) +- 🛑 **HARD STOP** at 50+ location pages +- Require explicit user justification +- Must demonstrate: + - Legitimate business presence in each location + - Unique content strategy for each page + - Local signals (Google Business Profile, local reviews) + +### Why This Matters +Google's doorway page algorithm penalizes programmatic location pages with thin/duplicate content. Signs of doorway pages: +- Only city/state name changed between pages +- No unique local information +- No local business signals +- Keyword-stuffed URLs + +--- + +## Safe vs. Risky Programmatic Pages + +### Safe at Scale ✅ +| Page Type | Why It's Safe | +|-----------|---------------| +| Integration pages | Real setup documentation, unique technical content | +| Template/tool pages | Downloadable assets, unique functionality | +| Glossary pages | 200+ word unique definitions | +| Product pages | Unique specs, images, reviews | +| User profile pages | User-generated unique content | + +### Penalty Risk ❌ +| Page Type | Why It's Risky | +|-----------|----------------| +| Location pages with only city swapped | Duplicate content, doorway pages | +| "Best [tool] for [industry]" | Often thin, no industry-specific value | +| "[Competitor] alternative" | Requires genuine comparison data | +| AI-generated mass content | No unique value, E-E-A-T failure | + +--- + +## Title Tag Requirements + +| Aspect | Requirement | +|--------|-------------| +| Minimum length | 30 characters | +| Maximum length | 60 characters (Google truncates ~60) | +| Primary keyword | Near the beginning | +| Brand name | At end (if included) | +| Uniqueness | Each page must have unique title | + +### Good Examples +- "Emergency Plumbing Services in Austin | ABC Plumbing" +- "How to Fix a Leaky Faucet: Step-by-Step Guide" +- "Enterprise SEO Software | Comprehensive Platform" + +### Bad Examples +- "Home" (too short, not descriptive) +- "Best Plumbing Services for All Your Plumbing Needs in Austin Texas and Surrounding Areas" (too long) +- "ABC Plumbing - Plumbing - Plumber - Plumbing Services" (keyword stuffing) + +--- + +## Meta Description Requirements + +| Aspect | Requirement | +|--------|-------------| +| Minimum length | 120 characters | +| Maximum length | 160 characters (Google truncates ~155-160) | +| Call-to-action | Include compelling CTA | +| Primary keyword | Include naturally | +| Uniqueness | Each page must have unique description | + +--- + +## Image Alt Text Requirements + +| Aspect | Requirement | +|--------|-------------| +| Required on | All non-decorative images | +| Length | 10-125 characters | +| Content | Describe the image content, not "image" or filename | +| Keywords | Include naturally where relevant | +| Decorative images | Use `alt=""` or `role="presentation"` | + +### Good Examples +- "Professional plumber repairing kitchen sink faucet" +- "Red 2024 Toyota Camry sedan front view" +- "Team meeting in modern office conference room" + +### Bad Examples +- "image.jpg" (filename, not description) +- "plumber plumbing plumber services" (keyword stuffing) +- "Click here" (not descriptive) + +--- + +## Internal Linking Guidelines + +| Page Type | Internal Links Target | +|-----------|----------------------| +| Blog post (1,500+ words) | 5-10 internal links | +| Service page | 3-5 internal links | +| Category page | Links to all child pages | +| Product page | 2-4 internal links | + +### Anchor Text Rules +- Use descriptive anchor text (not "click here") +- Vary anchor text (don't always use exact match keywords) +- Link to relevant, related content +- Ensure no orphan pages (every page linked from at least one other page) + +--- + +## Content Freshness Signals + +| Content Type | Update Frequency | +|--------------|------------------| +| News/current events | Within hours/days | +| Blog posts (evergreen) | Review annually | +| Product pages | When specs change | +| Service pages | Review quarterly | +| Company info | When changes occur | + +### Required Elements +- Publication date visible (for articles/blogs) +- Last updated date (if significantly revised) +- Changelog for major updates (optional but good) diff --git a/vibes-plug/skills/seo/references/schema-types.md b/vibes-plug/skills/seo/references/schema-types.md new file mode 100644 index 000000000..5674e2234 --- /dev/null +++ b/vibes-plug/skills/seo/references/schema-types.md @@ -0,0 +1,118 @@ + +# Schema.org Types: Status & Recommendations (February 2026) + +**Schema.org Version:** 29.4 (December 8, 2025) + +## Format Preference +Always use **JSON-LD** (` + +
+

Svelte 5 Runes Counter

+

+ Current: {count} | + Doubled: {doubled} +

+
+ + +
+
+``` + +### SvelteKit 2 Server Actions with Progressive Enhancement + +```typescript +// src/routes/tasks/+page.server.ts +import { fail } from '@sveltejs/kit'; +import type { Actions, PageServerLoad } from './$types'; + +export const load: PageServerLoad = async ({ locals }) => { + // Streaming promise pattern: do not await slow data here if streaming is desired + return { + fastStats: { total: 42 }, + streamedFeed: new Promise((resolve) => setTimeout(() => resolve(['Item A', 'Item B']), 300)) + }; +}; + +export const actions: Actions = { + createTask: async ({ request }) => { + const data = await request.formData(); + const title = data.get('title')?.toString().trim(); + + if (!title || title.length < 3) { + return fail(400, { title, error: 'Title must be at least 3 characters long.' }); + } + + // Atomic DB write... + return { success: true }; + } +}; +``` + +```svelte + + + +
+ {#if form?.error} +

{form.error}

+ {/if} + + + + +
+``` + +## Orchestration & Integration +- **`tailwind-expert`**: Configures Tailwind CSS v4 with SvelteKit `@theme` directives. +- **`performance-web-vitals`**: Harnesses Svelte's compile-time optimization for zero bundle bloat. +- **`e2e-testing-expert`**: End-to-end testing with Playwright for SvelteKit routes. +- **`typescript-expert`**: Type-safe `$types` generation for page servers and actions. + +--- + + +## Bahasa Indonesia + +### Deskripsi +Panduan komprehensif untuk Svelte 5 dan SvelteKit 2+. Berfokus pada model reaktivitas modern berbasis Runes (`$state`, `$derived`, `$effect`, `$props`, `$bindable`), arsitektur *server-first*, formulir dengan *progressive enhancement* (`use:enhance`), *streaming promise* pada `+page.server.ts`, dan deployment SSR/SSG/ISR pada platform edge modern. + +### Kondisi Pemicu +- Membangun aplikasi baru menggunakan Svelte 5 dan SvelteKit 2. +- Migrasi deklarasi reaktif Svelte 3/4 lawas (`$: x = ...`) ke model Runes Svelte 5. +- Mengimplementasikan pengiriman data formulir menggunakan Server Actions yang tetap berfungsi tanpa JavaScript aktif (*zero-JS fallback*). +- Mengalirkan (*streaming*) data asinkron lambat ke klien tanpa memblokir rendering halaman awal. + +### 5 Runes Inti Svelte 5 +1. **`$state(nilai)`**: Mendeklarasikan variabel reaktif utama. +2. **`$derived(ekspresi)`**: Menghitung nilai turunan yang di-cache secara otomatis. +3. **`$effect(() => {})`**: Menjalankan efek samping saat dependensi reaktif di dalamnya berubah. +4. **`$props()`**: Menerima props komponen secara type-safe. +5. **`$bindable()`**: Mengaktifkan *two-way binding* eksplisit antar komponen induk dan anak. + +### Contoh Form Action dengan Progressive Enhancement + +```svelte + + + +
{ + isSubmitting = true; + return async ({ update }) => { + isSubmitting = false; + await update(); + }; + }} + class="space-y-4" +> + + + +
+``` + +## Integrasi Orkestrasi +- **`tailwind-expert`**: Mengatur style Tailwind CSS v4 pada template SvelteKit. +- **`performance-web-vitals`**: Memanfaatkan kompilasi efisien Svelte tanpa virtual DOM untuk waktu muat ultra-cepat. +- **`e2e-testing-expert`**: Pengujian integrasi alur form dan rute menggunakan Playwright. +- **`typescript-expert`**: Memastikan integritas tipe data antara file server dan komponen UI. \ No newline at end of file diff --git a/vibes-plug/skills/svg-animation-motion-expert/SKILL.md b/vibes-plug/skills/svg-animation-motion-expert/SKILL.md new file mode 100644 index 000000000..c22ea08d2 --- /dev/null +++ b/vibes-plug/skills/svg-animation-motion-expert/SKILL.md @@ -0,0 +1,218 @@ +--- +name: svg-animation-motion-expert +description: "Expert guide for web animations: SVG manipulation, Framer Motion 12+, GSAP 3, CSS Scroll-Driven Animations, and View Transitions API / Panduan ahli animasi web." +author: "Roedy Rustam" + +version: "4.3.0" +--- + +# SVG & Web Animation Motion Expert + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +A dedicated skill for crafting fluid, high-performance web animations and micro-interactions. Covers direct SVG manipulation (paths, masks, clip-paths), React-based animations using Framer Motion 12+, advanced timeline choreography with GSAP 3, native CSS Scroll-Driven Animations, and the View Transitions API for seamless page navigations. + +### Trigger Conditions +- When building complex landing page animations or scroll reveals. +- When creating interactive SVG graphics, charts, or diagrams. +- When the user asks for "buttery smooth", "apple-like", or "dynamic" interactions. +- When implementing page transitions using the native View Transitions API. + +### Core Architecture & Guidelines + +#### 1. Framer Motion 12+ (React/Next.js) +Use Framer Motion for declarative component animations, layout animations, and gesture-driven interactions. +- **Layout Animations**: Use the `layout` prop to automatically animate between flexbox/grid state changes. +- **Performance**: Use `style={{ x, y }}` with `useTransform` and `useScroll` instead of triggering React state updates on every frame. + +```tsx +'use client' + +import { motion, useScroll, useTransform } from 'framer-motion' +import { useRef } from 'react' + +export function ScrollReveal({ children }: { children: React.ReactNode }) { + const ref = useRef(null) + const { scrollYProgress } = useScroll({ target: ref, offset: ['0 1', '1 1'] }) + const y = useTransform(scrollYProgress, [0, 1], [100, 0]) + const opacity = useTransform(scrollYProgress, [0, 1], [0, 1]) + + return ( + + {children} + + ) +} +``` + +#### 2. GSAP 3 (Complex Choreography) +Use GSAP when you need highly coordinated timeline sequences, path tracing, or when working outside of React (Vanilla JS). +- **ScrollTrigger**: The industry standard for complex scroll-based animations. +- **DrawSVG / MorphSVG**: Use for advanced SVG path drawing and morphing (requires Club GreenSock, use open-source alternatives if unavailable). + +#### 3. Native CSS Scroll-Driven Animations +Where possible, leverage modern native CSS to tie animations to scroll position on the compositor thread for zero-JS performance. +```css +@keyframes slide-in { + from { opacity: 0; transform: translateY(100px); } + to { opacity: 1; transform: translateY(0); } +} + +.reveal-on-scroll { + animation: slide-in linear both; + animation-timeline: view(); + animation-range: entry 25% cover 50%; +} +``` + +#### 4. SVG Optimization & Manipulation +- Always run SVGs through SVGO to strip bloat before animating. +- Keep `viewBox` responsive. +- Target ``, ``, and `` elements via CSS vars or inline Framer Motion logic. + +#### 5. Material Design 3 (M3) Motion Architecture (https://m3.material.io/styles/motion/overview) +M3 motion establishes physical purpose, directing user focus through spatial continuity: + +**M3 Easing & Duration Tokens:** +```css +:root { + /* M3 Easing Curves */ + --md-sys-motion-easing-emphasized: cubic-bezier(0.2, 0.0, 0, 1.0); + --md-sys-motion-easing-emphasized-decelerate: cubic-bezier(0.05, 0.7, 0.1, 1.0); + --md-sys-motion-easing-emphasized-accelerate: cubic-bezier(0.3, 0.0, 0.8, 0.15); + --md-sys-motion-easing-standard: cubic-bezier(0.2, 0.0, 0, 1.0); + --md-sys-motion-easing-standard-decelerate: cubic-bezier(0, 0, 0.2, 1.0); + + /* M3 Durations */ + --md-sys-motion-duration-short-4: 200ms; + --md-sys-motion-duration-medium-2: 300ms; + --md-sys-motion-duration-medium-4: 400ms; + --md-sys-motion-duration-long-2: 600ms; +} +``` + +**M3 Container Transform Pattern (Framer Motion `layoutId`):** +Morphing a card into a modal detail view with shared geometry: +```tsx +import { motion, AnimatePresence } from 'framer-motion'; + +// M3 Container Transform with Emphasized Decelerate Easing +const m3Transition = { + duration: 0.4, + ease: [0.05, 0.7, 0.1, 1.0], // M3 Emphasized Decelerate +}; + +export function M3CardToDetail({ selectedId, onSelect, item }: any) { + return ( + <> + onSelect(item.id)} + className="bg-surface-container rounded-2xl p-4 cursor-pointer shadow-sm hover:shadow-md transition-shadow" + transition={m3Transition} + > + + {item.title} + +

{item.subtitle}

+
+ + + {selectedId === item.id && ( + + + {item.title} + +
+ {item.fullContent} +
+ +
+ )} +
+ + ); +} +``` + +#### 6. Sovereign Anti-Slop Motion Directives +Zero-tolerance principles for intentional, high-performance web motion: +- **Strict `prefers-reduced-motion` Enforcement**: Every animation MUST respect user accessibility settings. In Framer Motion, check `useReducedMotion()`; in CSS, provide `@media (prefers-reduced-motion: reduce) { animation: none !important; transition: none !important; }`. +- **Compositor-Only Animations (Zero Layout Thrashing)**: Only animate `transform` and `opacity`. Strictly ban animating layout triggers (`top`, `left`, `width`, `height`, `margin`, `padding`). +- **Ban Bouncy Slop & Excessive Springs**: Avoid cartoonish, excessive spring bounces (`damping: 5, stiffness: 500`) on UI controls. Interactive components must use subtle, purposeful easings (`cubic-bezier(0.16, 1, 0.3, 1)`). +- **No Orphan Infinite Animations**: Eliminate infinite CSS/JS loops that run off-screen, eating CPU and mobile battery. Use `IntersectionObserver` or CSS `content-visibility` to halt animations when not in viewport. + +## Orchestration & Integration +- Works hand-in-hand with `ui-ux-pro-max` and `design-system-architect` to bring designs to life. +- Complements `senior-frontend` by handling the motion layer of the UI. +- Integrates with `seo` to build visually stunning landing pages. +- **`anti-slop`**: Enforces zero-bouncy slop, strict prefers-reduced-motion fallbacks, and compositor-only transforms. + +--- + + +## Bahasa Indonesia + +### Deskripsi +Skill khusus untuk membuat animasi web dan interaksi mikro yang lancar dan berkinerja tinggi. Mencakup manipulasi SVG langsung, animasi berbasis React menggunakan Framer Motion 12+, koreografi timeline lanjutan dengan GSAP 3, CSS Scroll-Driven Animations native, dan View Transitions API. + +### Kondisi Pemicu +- Saat membangun animasi landing page yang kompleks. +- Saat membuat grafik, chart, atau diagram SVG interaktif. +- Saat pengguna meminta interaksi yang "sangat mulus", "mirip Apple", atau "dinamis". +- Saat mengimplementasikan transisi halaman menggunakan View Transitions API native. + +### Panduan Arsitektur Inti + +#### 1. Framer Motion 12+ (React/Next.js) +Gunakan Framer Motion untuk animasi komponen deklaratif, animasi layout, dan interaksi gestur. +- Hindari memicu pembaruan state React pada setiap frame animasi. Gunakan `useTransform` dan `useScroll` yang beroperasi di luar siklus render React untuk performa 60fps. + +#### 2. GSAP 3 +Gunakan GSAP untuk urutan timeline yang sangat terkoordinasi atau saat bekerja di luar ekosistem React. Plugin `ScrollTrigger` sangat berguna untuk merangkai aksi kompleks berdasarkan posisi scroll. + +#### 3. CSS Scroll-Driven Animations Native +Manfaatkan CSS modern (`animation-timeline: view()`) untuk mengikat animasi ke posisi scroll langsung di compositor thread tanpa JavaScript sama sekali. Ini memberikan performa terbaik untuk efek paralaks dan reveal. + +#### 4. Manipulasi SVG +- Selalu optimasi SVG (buang tag tidak perlu) sebelum dianimasikan. +- Gunakan `` dan `` untuk transisi transisi pengungkapan gambar yang dramatis. + +#### 5. Arsitektur Gerak Material Design 3 (M3 Motion) (https://m3.material.io/styles/motion/overview) +Gerak dalam M3 memberikan kontinuitas spasial dan mengarahkan fokus pengguna: +- **Kurva Easing M3**: + - `emphasized-decelerate` (`cubic-bezier(0.05, 0.7, 0.1, 1.0)`): Digunakan untuk elemen yang masuk ke layar (modal, drawer, sheet) dengan durasi 400ms. + - `emphasized-accelerate` (`cubic-bezier(0.3, 0.0, 0.8, 0.15)`): Digunakan untuk elemen yang meninggalkan layar dengan durasi 200ms. + - `standard` (`cubic-bezier(0.2, 0.0, 0, 1.0)`): Digunakan untuk transformasi bentuk dan pergeseran posisi dalam layar dengan durasi 300ms. +- **Pola Transisi M3**: + - **Container Transform**: Transformasi morphing mulus dari kartu/chip kecil menjadi tampilan detail layar penuh menggunakan `layoutId` pada Framer Motion. + - **Shared Axis**: Transisi geser sepanjang sumbu X (alur wizard maju/mundur), sumbu Y (pindah level atas/bawah), atau sumbu Z (zoom in/out). + - **Fade Through**: Penggantian tampilan saat beralih antar destinasi navigasi utama (Bottom Navigation Bar atau Navigation Rail). + +#### 6. Arahan Anti-Slop Gerakan & Animasi +Prinsip nol toleransi untuk gerakan web yang fungsional dan berkinerja tinggi: +- **Kepatuhan Mutlak `prefers-reduced-motion`**: Semua animasi WAJIB menghormati preferensi aksesibilitas pengguna (`useReducedMotion()` di Framer Motion, atau `@media (prefers-reduced-motion: reduce)` di CSS). +- **Animasi Khusus Compositor (Bebas Layout Thrashing)**: Hanya animasikan `transform` dan `opacity`. Dilarang menganimasikan `top`, `left`, `width`, `height`, atau `margin` yang memicu re-layout dan lag. +- **Larangan Bouncy Slop Berlebihan**: Hindari efek pegas memantul ekstrem dan kekanak-kanakan pada kontrol tombol/menu. Gunakan kurva easing profesional (`cubic-bezier(0.16, 1, 0.3, 1)`). +- **Larangan Loop Tanpa Batas di Luar Layar**: Matikan animasi yang tidak terlihat di viewport menggunakan `IntersectionObserver` untuk mencegah boros baterai dan beban CPU. + +## Integrasi Orkestrasi +- Bekerja sama dengan `ui-ux-pro-max` dan `design-system-architect` untuk menghidupkan desain statis. +- Melengkapi `senior-frontend` dengan menangani lapisan pergerakan (motion layer) UI. +- Terintegrasi dengan `seo` untuk merancang landing page yang memukau secara visual. +- **`anti-slop`**: Menegakkan larangan animasi memantul berlebihan (bouncy slop), kewajiban fallback prefers-reduced-motion, dan animasi khusus compositor. \ No newline at end of file diff --git a/vibes-plug/skills/synthetic-data-finetuning-expert/SKILL.md b/vibes-plug/skills/synthetic-data-finetuning-expert/SKILL.md new file mode 100644 index 000000000..4d0b9ef21 --- /dev/null +++ b/vibes-plug/skills/synthetic-data-finetuning-expert/SKILL.md @@ -0,0 +1,189 @@ +--- +name: synthetic-data-finetuning-expert +description: "Expert guide for synthetic dataset generation, LLM-as-a-judge filtering, QLoRA fine-tuning (Unsloth), DPO alignment, and GGUF/Ollama export for local SLMs / Panduan ahli generasi data sintetis, fine-tuning QLoRA, DPO, dan ekspor GGUF/Ollama." +author: "Roedy Rustam" +version: "4.3.0" +--- + +# Synthetic Data & Fine-Tuning Expert (Custom Domain SLMs) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Orchestration & Integration +Connects and orchestrates with domain skills like `local-slm-edge-ai-expert`, `ai-prompt-engineering-expert`, `python-programming-expert`, and `llm-finops-router` to build high-performance, cost-effective domain models. + +### Description +Production-grade guide for generating synthetic training datasets, curating high-signal instruction pairs, executing Parameter-Efficient Fine-Tuning (QLoRA / LoRA) with **Unsloth** and Hugging Face TRL, performing Direct Preference Optimization (DPO), and quantizing custom Small Language Models (SLMs) to GGUF for edge or on-premise execution. + +**Swarm Synergy:** Within the **AI Engineering Swarm**, this skill serves as the Model Specialization Lead. When frontier API costs or latency become prohibitive, it trains, aligns, and deploys hyper-efficient domain SLMs (1B–8B parameters) in Phase 4. + +### Trigger Conditions +- Generating domain-specific synthetic training data from seed documents, codebases, or APIs. +- Filtering low-quality or hallucinated synthetic data using LLM-as-a-judge curation pipelines. +- Fine-tuning open-weights models (Llama 3.3, Qwen 2.5, Mistral) on custom tasks using 4-bit QLoRA. +- Aligning model outputs using Direct Preference Optimization (DPO) to enforce specific response styles. +- Quantizing fine-tuned models to GGUF (q4_k_m, q8_0) for zero-latency local inference with Ollama or llama.cpp. + +### Synthetic Data & Fine-Tuning Lifecycle + +``` +1. SEED EXTRACTION & SYNTHESIS + [Raw Docs / Codebase] ──► [Frontier LLM / Distilabel] ──► Raw Instruction Pairs (10k+) + +2. QUALITY FILTERING (LLM-AS-A-JUDGE) + Raw Instruction Pairs ──► [Rubric Scorer / De-duplication] ──► Curated Gold Dataset (2k-5k) + +3. 4-BIT QLORA FINE-TUNING (UNSLOTH) + Base Model (e.g. Qwen 2.5-Coder) + LoRA Adapters ──► SFT / DPO Training Loop + +4. QUANTIZATION & LOCAL DEPLOYMENT + Merged 16-bit Weights ──► [llama.cpp GGUF Export] ──► Local Ollama Service (<50ms latency) +``` + +### Core Implementation Guidelines + +#### 1. Synthetic Instruction Generation & Rejection Sampling +Use frontier models to generate input-output pairs with strict rejection criteria: +```python +from pydantic import BaseModel, Field +from openai import OpenAI +import json + +client = OpenAI() + +class SyntheticInstructionPair(BaseModel): + user_instruction: str = Field(description="Realistic developer query") + input_context: str = Field(description="Code snippet or API contract") + ground_truth_response: str = Field(description="Flawless, production-grade output") + quality_score: int = Field(ge=1, le=5, description="Self-evaluated quality score") + +def generate_synthetic_samples(seed_text: str) -> list[SyntheticInstructionPair]: + response = client.beta.chat.completions.parse( + model="gpt-4o-mini", + messages=[ + {"role": "system", "content": "Generate 5 diverse, hard edge-case instruction pairs based on the seed code."}, + {"role": "user", "content": seed_text} + ], + response_format=SyntheticInstructionPair, + ) + # Filter out anything below score 4 (Rejection Sampling) + return [sample for sample in [response.choices[0].message.parsed] if sample.quality_score >= 4] +``` + +#### 2. High-Speed 4-Bit QLoRA with Unsloth +Fine-tune on consumer GPUs (e.g., RTX 3090/4090 or single A10G) with 5x faster throughput: +```python +from unsloth import FastLanguageModel +import torch +from trl import SFTTrainer +from transformers import TrainingArguments + +# 1. Load Model & Tokenizer in 4-bit +max_seq_length = 2048 +model, tokenizer = FastLanguageModel.from_pretrained( + model_name="unsloth/Qwen2.5-Coder-7B-Instruct-bnb-4bit", + max_seq_length=max_seq_length, + load_in_4bit=True, +) + +# 2. Add LoRA Adapters +model = FastLanguageModel.get_peft_model( + model, + r=16, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], + lora_alpha=16, + lora_dropout=0, # Optimized 0 dropout for Unsloth + bias="none", +) + +# 3. Supervised Fine-Tuning (SFT) +trainer = SFTTrainer( + model=model, + tokenizer=tokenizer, + train_dataset=dataset, + dataset_text_field="text", + max_seq_length=max_seq_length, + args=TrainingArguments( + per_device_train_batch_size=2, + gradient_accumulation_steps=4, + warmup_steps=10, + max_steps=100, + learning_rate=2e-4, + fp16=not torch.cuda.is_bf16_supported(), + bf16=torch.cuda.is_bf16_supported(), + logging_steps=1, + output_dir="outputs", + ), +) +trainer.train() +``` + +#### 3. GGUF Export for Local Ollama Deployment +Export merged model to 4-bit or 8-bit quantized GGUF format: +```python +# Save to 16bit or GGUF directly +model.save_pretrained_gguf("custom-domain-coder", tokenizer, quantization_method="q4_k_m") + +# Generate Modelfile for Ollama: +# FROM ./custom-domain-coder-q4_k_m.gguf +# PARAMETER temperature 0.2 +# SYSTEM You are an expert domain coder. +``` + +--- + + +## Bahasa Indonesia + +### Integrasi Orkestrasi +Terhubung dan mengorkestrasi skill domain yang relevan seperti `local-slm-edge-ai-expert`, `ai-prompt-engineering-expert`, `python-programming-expert`, dan `llm-finops-router` untuk membangun model spesialis domain dengan performa tinggi dan biaya hemat. + +### Deskripsi +Panduan produksi untuk menghasilkan dataset pelatihan sintetis, mengurasi pasangan instruksi bernilai tinggi, mengeksekusi Parameter-Efficient Fine-Tuning (QLoRA / LoRA) dengan **Unsloth** dan Hugging Face TRL, menerapkan Direct Preference Optimization (DPO), dan mengkuantisasi Small Language Models (SLM) kustom ke format GGUF untuk inferensi lokal atau on-premise berlatensi ultra-rendah. + +**Sinergi Swarm:** Di dalam **AI Engineering Swarm**, skill ini memegang peranan sebagai Pemimpin Spesialisasi Model. Ketika biaya API atau latensi model cloud frontier terlalu tinggi, skill ini melatih, menyelaraskan (*align*), dan men-deploy SLM domain yang sangat efisien (1B–8B parameter) pada Fase 4. + +### Kondisi Pemicu +- Menghasilkan data pelatihan sintetis spesifik domain dari dokumen panduan, codebase, atau skema API. +- Menyaring data sintetis berkualitas rendah menggunakan pipeline penilaian otomatis *LLM-as-a-judge*. +- Melakukan fine-tuning model berbobot terbuka (Llama 3.3, Qwen 2.5, Mistral) dengan QLoRA 4-bit secara hemat memori VRAM. +- Menyelaraskan respon model dengan Direct Preference Optimization (DPO) agar mematuhi aturan format dan gaya tertentu. +- Mengkuantisasi model hasil fine-tuning ke format GGUF (q4_k_m, q8_0) untuk inferensi lokal instan di Ollama atau llama.cpp. + +--- + +### Implementasi Pola Kunci (Python) + +#### 1. Fine-Tuning Cepat QLoRA 4-Bit dengan Unsloth +```python +from unsloth import FastLanguageModel +import torch +from trl import SFTTrainer +from transformers import TrainingArguments + +# 1. Muat Model dan Tokenizer dalam mode 4-bit hemat VRAM +panjang_maksimum = 2048 +model, tokenizer = FastLanguageModel.from_pretrained( + model_name="unsloth/Qwen2.5-Coder-7B-Instruct-bnb-4bit", + max_seq_length=panjang_maksimum, + load_in_4bit=True, +) + +# 2. Pasang Adapter PEFT LoRA +model = FastLanguageModel.get_peft_model( + model, + r=16, + target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], + lora_alpha=16, + lora_dropout=0, + bias="none", +) + +# 3. Ekspor Langsung ke GGUF untuk Ollama Lokal +model.save_pretrained_gguf("model-koding-kustom", tokenizer, quantization_method="q4_k_m") +``` \ No newline at end of file diff --git a/vibes-plug/skills/tailwind-expert/SKILL.md b/vibes-plug/skills/tailwind-expert/SKILL.md new file mode 100644 index 000000000..a1cf07ede --- /dev/null +++ b/vibes-plug/skills/tailwind-expert/SKILL.md @@ -0,0 +1,374 @@ +--- +name: tailwind-expert +description: "Expert guide for Tailwind CSS v4, CSS-first configuration, @theme customization, and modern responsive design / Panduan ahli untuk Tailwind CSS v4, konfigurasi CSS-first, kustomisasi @theme, dan desain responsif modern." +author: "Roedy Rustam" + +version: "4.3.0" +--- + +# Tailwind CSS Expert (v4 Edition) + +[English](#english) | [Bahasa Indonesia](#bahasa-indonesia) + +--- + + +## English + +### Description +Strict guidelines and best practices for Tailwind CSS v4. Enforces the CSS-first configuration model, `@theme` token definitions, dynamic utilities, and performance optimization via Lightning CSS. + +### Trigger Conditions +- Scaffold or configure a Tailwind CSS v4 project. +- Migrate a codebase from Tailwind CSS v3 to v4. +- Implement design tokens via `@theme`. +- Apply 3D transforms, CSS container queries, or `field-sizing`. + +## Orchestration & Integration +Integrates tightly with the following skills: +- **`anti-slop`**: Enforces strict anti-slop rules on Tailwind usage (no arbitrary value hacks, accessible focus rings, zero div-soup, and no cliché AI gradients). +- **`senior-frontend`**: Feeds modern CSS capabilities into Next.js/React component architecture. +- **`design-system-architect, senior-frontend`**: Provides the styling primitives for Radix/shadcn-style components. +- **`design-system-architect`**: Establishes the core tokens mapped inside `@theme`. + +### Execution Standards + +#### 1. CSS-First Architecture +Do NOT create `tailwind.config.js`. Define all configuration inside CSS using the `@theme` directive. + +```css +/* app/globals.css */ +@import "tailwindcss"; + +@theme { + /* OKLCH Colors for wide-gamut displays */ + --color-brand-50: oklch(97% 0.02 250); + --color-brand-500: oklch(55% 0.2 250); + + /* Typography */ + --font-sans: "Inter Variable", system-ui, sans-serif; + + /* Custom breakpoints */ + --breakpoint-3xl: 112rem; +} + +/* Register plugins */ +@plugin "@tailwindcss/typography"; +``` + +#### 2. Advanced Utilities +Utilize v4-native features instead of custom CSS where possible: +- **3D Transforms**: Use `perspective-1000`, `rotate-x-12`, `transform-3d`, `backface-hidden`. +- **Color Mix**: Use inline mixing: `text-[color-mix(in_oklch,blue_70%,white)]`. +- **Container Queries**: Use `@container` on the parent, `@sm:grid-cols-2` on children. +- **Auto-sizing**: Use `field-sizing-content` for dynamically sizing textareas. + +#### 3. Migration (v3 to v4) +When upgrading older codebases: +1. Run `npx @tailwindcss/upgrade` automatically. +2. Manually verify `tailwind.config.js` logic is perfectly translated to `@theme` CSS variables. +3. Replace deprecated `addVariant` plugin code with `@variant` CSS directives: + ```css + @variant hocus (&:hover, &:focus); + @variant dark (&:where(.dark, .dark *)); + ``` + +#### 4. Performance Directives +- **Zero Configuration**: Rely on v4's automatic content detection. Do not manually specify content paths. +- **Specificity**: Use `@layer utilities` strictly when custom CSS requires Tailwind's specificity tier. +- **No `@apply` Abuse**: Avoid `@apply` in loops or highly repeated components; use HTML utility classes to leverage Lightning CSS tree-shaking. + +#### 5. Bootstrap to Tailwind Migration Guide +1. **Analyze the Legacy Structure**: + - Identify the version of Bootstrap being used. + - Locate custom CSS files that override Bootstrap defaults. + - Identify interactive components (modals, dropdowns, tooltips, tabs, carousels) that rely on Bootstrap's JavaScript or jQuery. +2. **Setup Modern Tools**: + - Ensure **Tailwind CSS v4** is properly set up in the project (e.g., via CDN for simple projects, or PostCSS/Vite for build steps). + - Inject **Alpine.js** via CDN or module bundler to handle interactivity. +3. **Migration Strategy**: + - **Grid & Layout**: Convert Bootstrap grids (`container`, `row`, `col-*`) to Tailwind flexbox (`flex`, `flex-col`, `gap-*`) or CSS Grid (`grid`, `grid-cols-*`). + - **Spacing & Typography**: Map Bootstrap spacing (`m-3`, `p-4`) to Tailwind spacing (`m-4`, `p-6`—noting scale differences). Map typography utilities (`text-center`, `font-weight-bold`) to Tailwind equivalents (`text-center`, `font-bold`). + - **Colors**: Update Bootstrap semantic colors (`primary`, `success`, `danger`) to Tailwind color palettes (e.g., `blue-600`, `green-500`, `red-500`) or define custom themes in CSS variables for Tailwind v4. + - **Components**: Rebuild Bootstrap components (cards, buttons, alerts, navbars) using Tailwind utility classes to match or improve the original design. +4. **Interactivity with Alpine.js**: + - Remove jQuery and Bootstrap JS dependencies. + - Replace interactive Bootstrap components with Alpine.js data and directives. + - **Dropdowns**: Use `x-data="{ open: false }"` and `@click="open = !open"`. + - **Modals**: Use Alpine.js to manage the open state and handle background overlays and click-away events (`@click.outside`). + - **Tabs**: Manage active tab state with `x-data="{ tab: 'home' }"`. +5. **UI/UX Modernization & Skill Integration**: + - Do NOT just do a 1:1 translation of Bootstrap classes. The goal is to elevate the design. + - You MUST orchestrate and apply guidelines from other UI/UX skills (`design-system-architect`, `ui-ux-pro-max`, and `hig`). + - Implement Human Interface Guidelines (HIG) principles: Hierarchy, Harmony, and Consistency. + - Use vibrant colors, smooth micro-animations, glassmorphism (if appropriate), and modern typography to "WOW" the user. +6. **Quality Assurance**: + - Verify that responsive design behaves correctly across breakpoints (`sm:`, `md:`, `lg:`). + - Ensure interactive components (modals, dropdowns) feel premium with Alpine.js transitions (`x-transition`). + +#### 6. Sovereign Anti-Slop Directives for Tailwind v4 +Enforces zero-tolerance code standards for utility-first styling: +- **No Arbitrary Value Hacks**: Ban arbitrary values (e.g., `p-[13px]`, `w-[372px]`, `text-[15px]`) when canonical spacing or typography scales exist. If a custom dimension is truly needed, declare it once in `@theme` as a semantic CSS variable token. +- **Accessible Focus Indicator Law**: Never use `focus:outline-none` alone. You MUST pair it with `focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-` or an explicit high-contrast focus indicator. +- **Zero Div-Soup Wrapper Bloat**: Do not nest redundant layout wrappers (`
...
`). Leverage modern CSS grid and subgrid directly on semantic containers (`
`, `