Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d09626fd2 | ||
|
|
014da3e744 | ||
|
|
113bc99e47 | ||
|
|
3e46a495c9 | ||
|
|
faf478f389 | ||
|
|
266cbf4c6c | ||
|
|
f8eaf7bd50 |
8
.github/CODEOWNERS
vendored
Normal file
8
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
# Global owners
|
||||||
|
* @sickn33
|
||||||
|
|
||||||
|
# Skills
|
||||||
|
/skills/ @sickn33
|
||||||
|
|
||||||
|
# Documentation
|
||||||
|
*.md @sickn33
|
||||||
33
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
33
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
---
|
||||||
|
name: Bug Report
|
||||||
|
about: Create a report to help us improve the skills
|
||||||
|
title: "[BUG] "
|
||||||
|
labels: bug
|
||||||
|
assignees: sickn33
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
|
||||||
|
1. Go to '...'
|
||||||
|
2. Click on '...'
|
||||||
|
3. Scroll down to '...'
|
||||||
|
4. See error
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Screenshots**
|
||||||
|
If applicable, add screenshots to help explain your problem.
|
||||||
|
|
||||||
|
**Environment (please complete the following information):**
|
||||||
|
|
||||||
|
- OS: [e.g. macOS, Windows]
|
||||||
|
- Tool: [e.g. Claude Code, Antigravity]
|
||||||
|
- Version [if known]
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
||||||
19
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
19
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
---
|
||||||
|
name: Skill Request
|
||||||
|
about: Suggest a new skill for the collection
|
||||||
|
title: "[REQ] "
|
||||||
|
labels: enhancement
|
||||||
|
assignees: sickn33
|
||||||
|
---
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex: I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A description of the skill you want. What trigger should it have? What files should it effect?
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
||||||
18
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
18
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
## Description
|
||||||
|
|
||||||
|
Please describe your changes. What skill are you adding or modifying?
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] My skill follows the [creation guidelines](https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/skill-creator)
|
||||||
|
- [ ] I have run `validate_skills.py`
|
||||||
|
- [ ] I have added my name to the credits (if applicable)
|
||||||
|
|
||||||
|
## Type of Change
|
||||||
|
|
||||||
|
- [ ] New Skill
|
||||||
|
- [ ] Bug Fix
|
||||||
|
- [ ] Documentation Update
|
||||||
|
- [ ] Infrastructure
|
||||||
|
|
||||||
|
## Screenshots (if applicable)
|
||||||
132
README.md
132
README.md
@@ -1,4 +1,4 @@
|
|||||||
# 🌌 Antigravity Awesome Skills
|
# 🌌 Antigravity Awesome Skills: The Ultimate Claude Code Skills Collection
|
||||||
|
|
||||||
> **The Ultimate Collection of 60+ Agentic Skills for Claude Code (Antigravity)**
|
> **The Ultimate Collection of 60+ Agentic Skills for Claude Code (Antigravity)**
|
||||||
|
|
||||||
@@ -6,12 +6,12 @@
|
|||||||
[](https://claude.ai)
|
[](https://claude.ai)
|
||||||
[](https://github.com/guanyang/antigravity-skills)
|
[](https://github.com/guanyang/antigravity-skills)
|
||||||
|
|
||||||
**Antigravity Awesome Skills** is a curated, battle-tested collection of **62 high-performance skills** compatible with both **Antigravity** and **Claude Code**, including official skills from **Anthropic** and **Vercel Labs**.
|
**Antigravity Awesome Skills** is the ultimate **Claude Code Skills** collection—a curated, battle-tested library of **71 high-performance skills** compatible with both **Antigravity** and **Claude Code**. This repository provides the essential **Claude Code skills** needed to transform your AI assistant into a full-stack digital agency, including official capabilities from **Anthropic** and **Vercel Labs**.
|
||||||
|
|
||||||
## 📍 Table of Contents
|
## 📍 Table of Contents
|
||||||
|
|
||||||
- [Features & Categories](#features--categories)
|
- [Features & Categories](#features--categories)
|
||||||
- [Full Skill Registry](#full-skill-registry-6262)
|
- [Full Skill Registry](#full-skill-registry-7171)
|
||||||
- [Installation](#installation)
|
- [Installation](#installation)
|
||||||
- [How to Contribute](#how-to-contribute)
|
- [How to Contribute](#how-to-contribute)
|
||||||
- [Credits & Sources](#credits--sources)
|
- [Credits & Sources](#credits--sources)
|
||||||
@@ -36,55 +36,85 @@ The repository is organized into several key areas of expertise:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Full Skill Registry (62/62)
|
## Full Skill Registry (71/71)
|
||||||
|
|
||||||
Below is the complete list of available skills. Each skill folder contains a `SKILL.md` that can be imported into Antigravity or Claude Code.
|
Below is the complete list of available skills. Each skill folder contains a `SKILL.md` that can be imported into Antigravity or Claude Code.
|
||||||
|
|
||||||
> [!NOTE] > **Document Skills**: We provide both **community** and **official Anthropic** versions for DOCX, PDF, PPTX, and XLSX. Locally, the official versions are used by default (via symlinks). In the repository, both versions are available for flexibility.
|
> [!NOTE] > **Document Skills**: We provide both **community** and **official Anthropic** versions for DOCX, PDF, PPTX, and XLSX. Locally, the official versions are used by default (via symlinks). In the repository, both versions are available for flexibility.
|
||||||
|
|
||||||
| Skill Name | Description | Path |
|
| Skill Name | Description | Path |
|
||||||
| :------------------------------- | :------------------------------------------------------------ | :--------------------------------------------- |
|
| :--------------------------------- | :-------------------------------------------------------------- | :--------------------------------------------- |
|
||||||
| **Algorithmic Art** | Creative generative art using p5.js and seeded randomness. | `skills/algorithmic-art` |
|
| **Address GitHub Comments** | Systematic PR feedback handling using gh CLI. | `skills/address-github-comments` ⭐ NEW |
|
||||||
| **App Store Optimization** | Complete ASO toolkit for iOS and Android app performance. | `skills/app-store-optimization` |
|
| **Algorithmic Art** | Creative generative art using p5.js and seeded randomness. | `skills/algorithmic-art` |
|
||||||
| **AWS Pentesting** | Specialized security assessment for Amazon Web Services. | `skills/aws-penetration-testing` |
|
| **App Store Optimization** | Complete ASO toolkit for iOS and Android app performance. | `skills/app-store-optimization` |
|
||||||
| **Backend Guidelines** | Core architecture patterns for Node/Express microservices. | `skills/backend-dev-guidelines` |
|
| **Autonomous Agent Patterns** | Design patterns for autonomous coding agents and tools. | `skills/autonomous-agent-patterns` ⭐ NEW |
|
||||||
| **Brainstorming** | Requirement discovery and intent exploration framework. | `skills/brainstorming` |
|
| **AWS Pentesting** | Specialized security assessment for Amazon Web Services. | `skills/aws-penetration-testing` |
|
||||||
| **Brand Guidelines (Anthropic)** | Official Anthropic brand styling and visual standards. | `skills/brand-guidelines-anthropic` ⭐ NEW |
|
| **Backend Guidelines** | Core architecture patterns for Node/Express microservices. | `skills/backend-dev-guidelines` |
|
||||||
| **Brand Guidelines (Community)** | Community-contributed brand guidelines and templates. | `skills/brand-guidelines-community` |
|
| **Concise Planning** | Atomic, actionable task planning and checklists. | `skills/concise-planning` ⭐ NEW |
|
||||||
| **Canvas Design** | Beautiful static visual design in PDF and PNG. | `skills/canvas-design` |
|
| **Brainstorming** | Requirement discovery and intent exploration framework. | `skills/brainstorming` |
|
||||||
| **Claude D3.js** | Advanced data visualization with D3.js. | `skills/claude-d3js-skill` |
|
| **Brand Guidelines (Anthropic)** | Official Anthropic brand styling and visual standards. | `skills/brand-guidelines-anthropic` ⭐ NEW |
|
||||||
| **Content Creator** | SEO-optimized marketing and brand voice toolkit. | `skills/content-creator` |
|
| **Brand Guidelines (Community)** | Community-contributed brand guidelines and templates. | `skills/brand-guidelines-community` |
|
||||||
| **Core Components** | Design system tokens and baseline UI patterns. | `skills/core-components` |
|
| **Bun Development** | Modern JavaScript/TypeScript development with Bun runtime. | `skills/bun-development` ⭐ NEW |
|
||||||
| **Doc Co-authoring** | Structured workflow for technical documentation. | `skills/doc-coauthoring` |
|
| **Canvas Design** | Beautiful static visual design in PDF and PNG. | `skills/canvas-design` |
|
||||||
| **DOCX (Official)** | Official Anthropic MS Word document manipulation. | `skills/docx-official` ⭐ NEW |
|
| **Claude D3.js** | Advanced data visualization with D3.js. | `skills/claude-d3js-skill` |
|
||||||
| **Ethical Hacking** | Comprehensive penetration testing lifecycle methodology. | `skills/ethical-hacking-methodology` |
|
| **Content Creator** | SEO-optimized marketing and brand voice toolkit. | `skills/content-creator` |
|
||||||
| **Frontend Design** | Production-grade UI component implementation. | `skills/frontend-design` |
|
| **Core Components** | Design system tokens and baseline UI patterns. | `skills/core-components` |
|
||||||
| **Frontend Guidelines** | Modern React/TS development patterns and file structure. | `skills/frontend-dev-guidelines` |
|
| **Dispatching Parallel Agents** | Work on independent tasks without shared state. | `skills/dispatching-parallel-agents` |
|
||||||
| **Git Pushing** | Automated staging and conventional commits. | `skills/git-pushing` |
|
| **Doc Co-authoring** | Structured workflow for technical documentation. | `skills/doc-coauthoring` |
|
||||||
| **Internal Comms (Anthropic)** | Official Anthropic corporate communication templates. | `skills/internal-comms-anthropic` ⭐ NEW |
|
| **DOCX (Official)** | Official Anthropic MS Word document manipulation. | `skills/docx-official` ⭐ NEW |
|
||||||
| **Internal Comms (Community)** | Community-contributed communication templates. | `skills/internal-comms-community` |
|
| **Ethical Hacking** | Comprehensive penetration testing lifecycle methodology. | `skills/ethical-hacking-methodology` |
|
||||||
| **Kaizen** | Continuous improvement and error-proofing (Poka-Yoke). | `skills/kaizen` |
|
| **Executing Plans** | Execute written implementation plans in structured sessions. | `skills/executing-plans` |
|
||||||
| **Linux Shell Scripting** | Production-ready shell scripts for automation. | `skills/linux-shell-scripting` |
|
| **File Organizer** | Context-aware file organization and duplicate cleanup. | `skills/file-organizer` |
|
||||||
| **Loki Mode** | Fully autonomous startup development engine. | `skills/loki-mode` |
|
| **Finishing Dev Branch** | Structured workflow for merging, PRs, and branch cleanup. | `skills/finishing-a-development-branch` |
|
||||||
| **MCP Builder** | High-quality Model Context Protocol (MCP) server creation. | `skills/mcp-builder` |
|
| **Frontend Design** | Production-grade UI component implementation. | `skills/frontend-design` |
|
||||||
| **NotebookLM** | Source-grounded querying via Google NotebookLM. | `skills/notebooklm` |
|
| **Frontend Guidelines** | Modern React/TS development patterns and file structure. | `skills/frontend-dev-guidelines` |
|
||||||
| **PDF (Official)** | Official Anthropic PDF document manipulation. | `skills/pdf-official` ⭐ NEW |
|
| **Git Pushing** | Automated staging and conventional commits. | `skills/git-pushing` |
|
||||||
| **Pentest Checklist** | Structured security assessment planning and scoping. | `skills/pentest-checklist` |
|
| **GitHub Workflow Automation** | AI-powered PR reviews, issue triage, and CI/CD integration. | `skills/github-workflow-automation` ⭐ NEW |
|
||||||
| **PPTX (Official)** | Official Anthropic PowerPoint manipulation. | `skills/pptx-official` ⭐ NEW |
|
| **Internal Comms (Anthropic)** | Official Anthropic corporate communication templates. | `skills/internal-comms-anthropic` ⭐ NEW |
|
||||||
| **Product Toolkit** | RICE prioritization and product discovery frameworks. | `skills/product-manager-toolkit` |
|
| **Internal Comms (Community)** | Community-contributed communication templates. | `skills/internal-comms-community` |
|
||||||
| **Prompt Engineering** | Expert patterns for LLM instruction optimization. | `skills/prompt-engineering` |
|
| **JavaScript Mastery** | 33+ essential JavaScript concepts every developer should know. | `skills/javascript-mastery` ⭐ NEW |
|
||||||
| **React Best Practices** | Vercel's 40+ performance optimization rules for React. | `skills/react-best-practices` ⭐ NEW (Vercel) |
|
| **Kaizen** | Continuous improvement and error-proofing (Poka-Yoke). | `skills/kaizen` |
|
||||||
| **React UI Patterns** | Standardized loading states and error handling for React. | `skills/react-ui-patterns` |
|
| **Linux Shell Scripting** | Production-ready shell scripts for automation. | `skills/linux-shell-scripting` |
|
||||||
| **Senior Architect** | Scalable system design and architecture diagrams. | `skills/senior-architect` |
|
| **LLM App Patterns** | RAG pipelines, agent architectures, and LLMOps patterns. | `skills/llm-app-patterns` ⭐ NEW |
|
||||||
| **Skill Creator** | Meta-skill for building high-performance agentic skills. | `skills/skill-creator` |
|
| **Loki Mode** | Fully autonomous startup development engine. | `skills/loki-mode` |
|
||||||
| **Software Architecture** | Quality-focused design principles and analysis. | `skills/software-architecture` |
|
| **MCP Builder** | High-quality Model Context Protocol (MCP) server creation. | `skills/mcp-builder` |
|
||||||
| **Systematic Debugging** | Root cause analysis and structured fix verification. | `skills/systematic-debugging` |
|
| **NotebookLM** | Source-grounded querying via Google NotebookLM. | `skills/notebooklm` |
|
||||||
| **TDD** | Test-Driven Development workflow and red-green-refactor. | `skills/test-driven-development` |
|
| **PDF (Official)** | Official Anthropic PDF document manipulation. | `skills/pdf-official` ⭐ NEW |
|
||||||
| **UI/UX Pro Max** | Advanced design intelligence and 50+ styling options. | `skills/ui-ux-pro-max` |
|
| **Pentest Checklist** | Structured security assessment planning and scoping. | `skills/pentest-checklist` |
|
||||||
| **Web Artifacts** | Complex React/Tailwind/Shadcn UI artifact builder. | `skills/web-artifacts-builder` |
|
| **Planning With Files** | Manus-style file-based planning for complex tasks. | `skills/planning-with-files` |
|
||||||
| **Web Design Guidelines** | Vercel's 100+ UI/UX audit rules (accessibility, performance). | `skills/web-design-guidelines` ⭐ NEW (Vercel) |
|
| **Playwright Automation** | Complete browser automation and testing with Playwright. | `skills/playwright-skill` |
|
||||||
| **Webapp Testing** | Local web application testing with Playwright. | `skills/webapp-testing` |
|
| **PPTX (Official)** | Official Anthropic PowerPoint manipulation. | `skills/pptx-official` ⭐ NEW |
|
||||||
| **XLSX (Official)** | Official Anthropic Excel spreadsheet manipulation. | `skills/xlsx-official` ⭐ NEW |
|
| **Product Toolkit** | RICE prioritization and product discovery frameworks. | `skills/product-manager-toolkit` |
|
||||||
|
| **Prompt Engineering** | Expert patterns for LLM instruction optimization. | `skills/prompt-engineering` |
|
||||||
|
| **Prompt Library** | Curated role-based and task-specific prompt templates. | `skills/prompt-library` ⭐ NEW |
|
||||||
|
| **React Best Practices** | Vercel's 40+ performance optimization rules for React. | `skills/react-best-practices` ⭐ NEW (Vercel) |
|
||||||
|
| **React UI Patterns** | Standardized loading states and error handling for React. | `skills/react-ui-patterns` |
|
||||||
|
| **Receiving Code Review** | Technical verification of code review feedback. | `skills/receiving-code-review` |
|
||||||
|
| **Requesting Code Review** | Pre-merge requirements verification workflow. | `skills/requesting-code-review` |
|
||||||
|
| **Senior Architect** | Scalable system design and architecture diagrams. | `skills/senior-architect` |
|
||||||
|
| **Senior Fullstack** | Comprehensive fullstack guide (React, Node, Postgres). | `skills/senior-fullstack` |
|
||||||
|
| **Skill Creator** | Meta-skill for building high-performance agentic skills. | `skills/skill-creator` |
|
||||||
|
| **Skill Developer** | Create and manage skills using Anthropic best practices. | `skills/skill-developer` |
|
||||||
|
| **Slack GIF Creator** | Create animated GIFs optimized for Slack. | `skills/slack-gif-creator` |
|
||||||
|
| **Software Architecture** | Quality-focused design principles and analysis. | `skills/software-architecture` |
|
||||||
|
| **Subagent Driven Dev** | Orchestrate independent subtasks in current session. | `skills/subagent-driven-development` |
|
||||||
|
| **Systematic Debugging** | Root cause analysis and structured fix verification. | `skills/systematic-debugging` |
|
||||||
|
| **TDD** | Test-Driven Development workflow and red-green-refactor. | `skills/test-driven-development` |
|
||||||
|
| **Test Fixing** | Systematically fix failing tests using smart error grouping. | `skills/test-fixing` |
|
||||||
|
| **Testing Patterns** | Jest patterns, factories, and TDD workflow strategies. | `skills/testing-patterns` |
|
||||||
|
| **Theme Factory** | Toolkit for styling artifacts with pre-set or generated themes. | `skills/theme-factory` |
|
||||||
|
| **Top 100 Vulnerabilities** | OWASP-aligned web vulnerability taxonomy and mitigations. | `skills/top-web-vulnerabilities` |
|
||||||
|
| **UI/UX Pro Max** | Advanced design intelligence and 50+ styling options. | `skills/ui-ux-pro-max` |
|
||||||
|
| **Using Git Worktrees** | Isolated workspaces for safe feature development. | `skills/using-git-worktrees` |
|
||||||
|
| **Using Superpowers** | Establish skill usage protocols at conversation start. | `skills/using-superpowers` |
|
||||||
|
| **Verification Before Completion** | Run verification commands before claiming success. | `skills/verification-before-completion` |
|
||||||
|
| **Web Artifacts** | Complex React/Tailwind/Shadcn UI artifact builder. | `skills/web-artifacts-builder` |
|
||||||
|
| **Web Design Guidelines** | Vercel's 100+ UI/UX audit rules (accessibility, performance). | `skills/web-design-guidelines` ⭐ NEW (Vercel) |
|
||||||
|
| **Webapp Testing** | Local web application testing with Playwright. | `skills/webapp-testing` |
|
||||||
|
| **Workflow Automation** | Multi-step automations, API integration, AI-native pipelines. | `skills/workflow-automation` ⭐ NEW |
|
||||||
|
| **Writing Plans** | Create specs for multi-step tasks before coding. | `skills/writing-plans` |
|
||||||
|
| **Writing Skills** | Create and verify skills before deployment. | `skills/writing-skills` |
|
||||||
|
| **XLSX (Official)** | Official Anthropic Excel spreadsheet manipulation. | `skills/xlsx-official` ⭐ NEW |
|
||||||
|
|
||||||
> [!TIP]
|
> [!TIP]
|
||||||
> Use the `validate_skills.py` script in the `scripts/` directory to ensure all skills are properly formatted and ready for use.
|
> Use the `validate_skills.py` script in the `scripts/` directory to ensure all skills are properly formatted and ready for use.
|
||||||
@@ -122,7 +152,9 @@ This collection would not be possible without the incredible work of the Claude
|
|||||||
### Official Sources
|
### Official Sources
|
||||||
|
|
||||||
- **[anthropics/skills](https://github.com/anthropics/skills)**: Official Anthropic skills repository - Document manipulation (DOCX, PDF, PPTX, XLSX), Brand Guidelines, Internal Communications.
|
- **[anthropics/skills](https://github.com/anthropics/skills)**: Official Anthropic skills repository - Document manipulation (DOCX, PDF, PPTX, XLSX), Brand Guidelines, Internal Communications.
|
||||||
|
- **[anthropics/claude-cookbooks](https://github.com/anthropics/claude-cookbooks)**: Official notebooks and recipes for building with Claude.
|
||||||
- **[vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills)**: Vercel Labs official skills - React Best Practices, Web Design Guidelines.
|
- **[vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills)**: Vercel Labs official skills - React Best Practices, Web Design Guidelines.
|
||||||
|
- **[openai/skills](https://github.com/openai/skills)**: OpenAI Codex skills catalog - Agent skills, Skill Creator, Concise Planning.
|
||||||
|
|
||||||
### Community Contributors
|
### Community Contributors
|
||||||
|
|
||||||
@@ -133,6 +165,12 @@ This collection would not be possible without the incredible work of the Claude
|
|||||||
- **[travisvn/awesome-claude-skills](https://github.com/travisvn/awesome-claude-skills)**: Loki Mode and Playwright integration.
|
- **[travisvn/awesome-claude-skills](https://github.com/travisvn/awesome-claude-skills)**: Loki Mode and Playwright integration.
|
||||||
- **[zebbern/claude-code-guide](https://github.com/zebbern/claude-code-guide)**: Comprehensive Security suite.
|
- **[zebbern/claude-code-guide](https://github.com/zebbern/claude-code-guide)**: Comprehensive Security suite.
|
||||||
- **[alirezarezvani/claude-skills](https://github.com/alirezarezvani/claude-skills)**: Senior Engineering and PM toolkit.
|
- **[alirezarezvani/claude-skills](https://github.com/alirezarezvani/claude-skills)**: Senior Engineering and PM toolkit.
|
||||||
|
- **[karanb192/awesome-claude-skills](https://github.com/karanb192/awesome-claude-skills)**: A massive list of verified skills for Claude Code.
|
||||||
|
|
||||||
|
### Inspirations
|
||||||
|
|
||||||
|
- **[f/awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)**: Inspiration for the Prompt Library.
|
||||||
|
- **[leonardomso/33-js-concepts](https://github.com/leonardomso/33-js-concepts)**: Inspiration for JavaScript Mastery.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
55
skills/address-github-comments/SKILL.md
Normal file
55
skills/address-github-comments/SKILL.md
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
name: address-github-comments
|
||||||
|
description: Use when you need to address review or issue comments on an open GitHub Pull Request using the gh CLI.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Address GitHub Comments
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Efficiently address PR review comments or issue feedback using the GitHub CLI (`gh`). This skill ensures all feedback is addressed systematically.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
Ensure `gh` is authenticated.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh auth status
|
||||||
|
```
|
||||||
|
|
||||||
|
If not logged in, run `gh auth login`.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
### 1. Inspect Comments
|
||||||
|
|
||||||
|
Fetch the comments for the current branch's PR.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh pr view --comments
|
||||||
|
```
|
||||||
|
|
||||||
|
Or use a custom script if available to list threads.
|
||||||
|
|
||||||
|
### 2. Categorize and Plan
|
||||||
|
|
||||||
|
- List the comments and review threads.
|
||||||
|
- Propose a fix for each.
|
||||||
|
- **Wait for user confirmation** on which comments to address first if there are many.
|
||||||
|
|
||||||
|
### 3. Apply Fixes
|
||||||
|
|
||||||
|
Apply the code changes for the selected comments.
|
||||||
|
|
||||||
|
### 4. Respond to Comments
|
||||||
|
|
||||||
|
Once fixed, respond to the threads as resolved.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh pr comment <PR_NUMBER> --body "Addressed in latest commit."
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Mistakes
|
||||||
|
|
||||||
|
- **Applying fixes without understanding context**: Always read the surrounding code of a comment.
|
||||||
|
- **Not verifying auth**: Check `gh auth status` before starting.
|
||||||
761
skills/autonomous-agent-patterns/SKILL.md
Normal file
761
skills/autonomous-agent-patterns/SKILL.md
Normal file
@@ -0,0 +1,761 @@
|
|||||||
|
---
|
||||||
|
name: autonomous-agent-patterns
|
||||||
|
description: "Design patterns for building autonomous coding agents. Covers tool integration, permission systems, browser automation, and human-in-the-loop workflows. Use when building AI agents, designing tool APIs, implementing permission systems, or creating autonomous coding assistants."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🕹️ Autonomous Agent Patterns
|
||||||
|
|
||||||
|
> Design patterns for building autonomous coding agents, inspired by [Cline](https://github.com/cline/cline) and [OpenAI Codex](https://github.com/openai/codex).
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Building autonomous AI agents
|
||||||
|
- Designing tool/function calling APIs
|
||||||
|
- Implementing permission and approval systems
|
||||||
|
- Creating browser automation for agents
|
||||||
|
- Designing human-in-the-loop workflows
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Core Agent Architecture
|
||||||
|
|
||||||
|
### 1.1 Agent Loop
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ AGENT LOOP │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||||
|
│ │ Think │───▶│ Decide │───▶│ Act │ │
|
||||||
|
│ │ (Reason) │ │ (Plan) │ │ (Execute)│ │
|
||||||
|
│ └──────────┘ └──────────┘ └──────────┘ │
|
||||||
|
│ ▲ │ │
|
||||||
|
│ │ ┌──────────┐ │ │
|
||||||
|
│ └─────────│ Observe │◀─────────┘ │
|
||||||
|
│ │ (Result) │ │
|
||||||
|
│ └──────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
class AgentLoop:
|
||||||
|
def __init__(self, llm, tools, max_iterations=50):
|
||||||
|
self.llm = llm
|
||||||
|
self.tools = {t.name: t for t in tools}
|
||||||
|
self.max_iterations = max_iterations
|
||||||
|
self.history = []
|
||||||
|
|
||||||
|
def run(self, task: str) -> str:
|
||||||
|
self.history.append({"role": "user", "content": task})
|
||||||
|
|
||||||
|
for i in range(self.max_iterations):
|
||||||
|
# Think: Get LLM response with tool options
|
||||||
|
response = self.llm.chat(
|
||||||
|
messages=self.history,
|
||||||
|
tools=self._format_tools(),
|
||||||
|
tool_choice="auto"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Decide: Check if agent wants to use a tool
|
||||||
|
if response.tool_calls:
|
||||||
|
for tool_call in response.tool_calls:
|
||||||
|
# Act: Execute the tool
|
||||||
|
result = self._execute_tool(tool_call)
|
||||||
|
|
||||||
|
# Observe: Add result to history
|
||||||
|
self.history.append({
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": tool_call.id,
|
||||||
|
"content": str(result)
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
# No more tool calls = task complete
|
||||||
|
return response.content
|
||||||
|
|
||||||
|
return "Max iterations reached"
|
||||||
|
|
||||||
|
def _execute_tool(self, tool_call) -> Any:
|
||||||
|
tool = self.tools[tool_call.name]
|
||||||
|
args = json.loads(tool_call.arguments)
|
||||||
|
return tool.execute(**args)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 Multi-Model Architecture
|
||||||
|
|
||||||
|
```python
|
||||||
|
class MultiModelAgent:
|
||||||
|
"""
|
||||||
|
Use different models for different purposes:
|
||||||
|
- Fast model for planning
|
||||||
|
- Powerful model for complex reasoning
|
||||||
|
- Specialized model for code generation
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.models = {
|
||||||
|
"fast": "gpt-3.5-turbo", # Quick decisions
|
||||||
|
"smart": "gpt-4-turbo", # Complex reasoning
|
||||||
|
"code": "claude-3-sonnet", # Code generation
|
||||||
|
}
|
||||||
|
|
||||||
|
def select_model(self, task_type: str) -> str:
|
||||||
|
if task_type == "planning":
|
||||||
|
return self.models["fast"]
|
||||||
|
elif task_type == "analysis":
|
||||||
|
return self.models["smart"]
|
||||||
|
elif task_type == "code":
|
||||||
|
return self.models["code"]
|
||||||
|
return self.models["smart"]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Tool Design Patterns
|
||||||
|
|
||||||
|
### 2.1 Tool Schema
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Tool:
|
||||||
|
"""Base class for agent tools"""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def schema(self) -> dict:
|
||||||
|
"""JSON Schema for the tool"""
|
||||||
|
return {
|
||||||
|
"name": self.name,
|
||||||
|
"description": self.description,
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": self._get_parameters(),
|
||||||
|
"required": self._get_required()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def execute(self, **kwargs) -> ToolResult:
|
||||||
|
"""Execute the tool and return result"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
class ReadFileTool(Tool):
|
||||||
|
name = "read_file"
|
||||||
|
description = "Read the contents of a file from the filesystem"
|
||||||
|
|
||||||
|
def _get_parameters(self):
|
||||||
|
return {
|
||||||
|
"path": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Absolute path to the file"
|
||||||
|
},
|
||||||
|
"start_line": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Line to start reading from (1-indexed)"
|
||||||
|
},
|
||||||
|
"end_line": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Line to stop reading at (inclusive)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def _get_required(self):
|
||||||
|
return ["path"]
|
||||||
|
|
||||||
|
def execute(self, path: str, start_line: int = None, end_line: int = None) -> ToolResult:
|
||||||
|
try:
|
||||||
|
with open(path, 'r') as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
|
||||||
|
if start_line and end_line:
|
||||||
|
lines = lines[start_line-1:end_line]
|
||||||
|
|
||||||
|
return ToolResult(
|
||||||
|
success=True,
|
||||||
|
output="".join(lines)
|
||||||
|
)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return ToolResult(
|
||||||
|
success=False,
|
||||||
|
error=f"File not found: {path}"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Essential Agent Tools
|
||||||
|
|
||||||
|
```python
|
||||||
|
CODING_AGENT_TOOLS = {
|
||||||
|
# File operations
|
||||||
|
"read_file": "Read file contents",
|
||||||
|
"write_file": "Create or overwrite a file",
|
||||||
|
"edit_file": "Make targeted edits to a file",
|
||||||
|
"list_directory": "List files and folders",
|
||||||
|
"search_files": "Search for files by pattern",
|
||||||
|
|
||||||
|
# Code understanding
|
||||||
|
"search_code": "Search for code patterns (grep)",
|
||||||
|
"get_definition": "Find function/class definition",
|
||||||
|
"get_references": "Find all references to a symbol",
|
||||||
|
|
||||||
|
# Terminal
|
||||||
|
"run_command": "Execute a shell command",
|
||||||
|
"read_output": "Read command output",
|
||||||
|
"send_input": "Send input to running command",
|
||||||
|
|
||||||
|
# Browser (optional)
|
||||||
|
"open_browser": "Open URL in browser",
|
||||||
|
"click_element": "Click on page element",
|
||||||
|
"type_text": "Type text into input",
|
||||||
|
"screenshot": "Capture screenshot",
|
||||||
|
|
||||||
|
# Context
|
||||||
|
"ask_user": "Ask the user a question",
|
||||||
|
"search_web": "Search the web for information"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Edit Tool Design
|
||||||
|
|
||||||
|
```python
|
||||||
|
class EditFileTool(Tool):
|
||||||
|
"""
|
||||||
|
Precise file editing with conflict detection.
|
||||||
|
Uses search/replace pattern for reliable edits.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name = "edit_file"
|
||||||
|
description = "Edit a file by replacing specific content"
|
||||||
|
|
||||||
|
def execute(
|
||||||
|
self,
|
||||||
|
path: str,
|
||||||
|
search: str,
|
||||||
|
replace: str,
|
||||||
|
expected_occurrences: int = 1
|
||||||
|
) -> ToolResult:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
path: File to edit
|
||||||
|
search: Exact text to find (must match exactly, including whitespace)
|
||||||
|
replace: Text to replace with
|
||||||
|
expected_occurrences: How many times search should appear (validation)
|
||||||
|
"""
|
||||||
|
with open(path, 'r') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
# Validate
|
||||||
|
actual_occurrences = content.count(search)
|
||||||
|
if actual_occurrences != expected_occurrences:
|
||||||
|
return ToolResult(
|
||||||
|
success=False,
|
||||||
|
error=f"Expected {expected_occurrences} occurrences, found {actual_occurrences}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if actual_occurrences == 0:
|
||||||
|
return ToolResult(
|
||||||
|
success=False,
|
||||||
|
error="Search text not found in file"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply edit
|
||||||
|
new_content = content.replace(search, replace)
|
||||||
|
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
f.write(new_content)
|
||||||
|
|
||||||
|
return ToolResult(
|
||||||
|
success=True,
|
||||||
|
output=f"Replaced {actual_occurrences} occurrence(s)"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Permission & Safety Patterns
|
||||||
|
|
||||||
|
### 3.1 Permission Levels
|
||||||
|
|
||||||
|
```python
|
||||||
|
class PermissionLevel(Enum):
|
||||||
|
# Fully automatic - no user approval needed
|
||||||
|
AUTO = "auto"
|
||||||
|
|
||||||
|
# Ask once per session
|
||||||
|
ASK_ONCE = "ask_once"
|
||||||
|
|
||||||
|
# Ask every time
|
||||||
|
ASK_EACH = "ask_each"
|
||||||
|
|
||||||
|
# Never allow
|
||||||
|
NEVER = "never"
|
||||||
|
|
||||||
|
PERMISSION_CONFIG = {
|
||||||
|
# Low risk - can auto-approve
|
||||||
|
"read_file": PermissionLevel.AUTO,
|
||||||
|
"list_directory": PermissionLevel.AUTO,
|
||||||
|
"search_code": PermissionLevel.AUTO,
|
||||||
|
|
||||||
|
# Medium risk - ask once
|
||||||
|
"write_file": PermissionLevel.ASK_ONCE,
|
||||||
|
"edit_file": PermissionLevel.ASK_ONCE,
|
||||||
|
|
||||||
|
# High risk - ask each time
|
||||||
|
"run_command": PermissionLevel.ASK_EACH,
|
||||||
|
"delete_file": PermissionLevel.ASK_EACH,
|
||||||
|
|
||||||
|
# Dangerous - never auto-approve
|
||||||
|
"sudo_command": PermissionLevel.NEVER,
|
||||||
|
"format_disk": PermissionLevel.NEVER
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Approval UI Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
class ApprovalManager:
|
||||||
|
def __init__(self, ui, config):
|
||||||
|
self.ui = ui
|
||||||
|
self.config = config
|
||||||
|
self.session_approvals = {}
|
||||||
|
|
||||||
|
def request_approval(self, tool_name: str, args: dict) -> bool:
|
||||||
|
level = self.config.get(tool_name, PermissionLevel.ASK_EACH)
|
||||||
|
|
||||||
|
if level == PermissionLevel.AUTO:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if level == PermissionLevel.NEVER:
|
||||||
|
self.ui.show_error(f"Tool '{tool_name}' is not allowed")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if level == PermissionLevel.ASK_ONCE:
|
||||||
|
if tool_name in self.session_approvals:
|
||||||
|
return self.session_approvals[tool_name]
|
||||||
|
|
||||||
|
# Show approval dialog
|
||||||
|
approved = self.ui.show_approval_dialog(
|
||||||
|
tool=tool_name,
|
||||||
|
args=args,
|
||||||
|
risk_level=self._assess_risk(tool_name, args)
|
||||||
|
)
|
||||||
|
|
||||||
|
if level == PermissionLevel.ASK_ONCE:
|
||||||
|
self.session_approvals[tool_name] = approved
|
||||||
|
|
||||||
|
return approved
|
||||||
|
|
||||||
|
def _assess_risk(self, tool_name: str, args: dict) -> str:
|
||||||
|
"""Analyze specific call for risk level"""
|
||||||
|
if tool_name == "run_command":
|
||||||
|
cmd = args.get("command", "")
|
||||||
|
if any(danger in cmd for danger in ["rm -rf", "sudo", "chmod"]):
|
||||||
|
return "HIGH"
|
||||||
|
return "MEDIUM"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Sandboxing
|
||||||
|
|
||||||
|
```python
|
||||||
|
class SandboxedExecution:
|
||||||
|
"""
|
||||||
|
Execute code/commands in isolated environment
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, workspace_dir: str):
|
||||||
|
self.workspace = workspace_dir
|
||||||
|
self.allowed_commands = ["npm", "python", "node", "git", "ls", "cat"]
|
||||||
|
self.blocked_paths = ["/etc", "/usr", "/bin", os.path.expanduser("~")]
|
||||||
|
|
||||||
|
def validate_path(self, path: str) -> bool:
|
||||||
|
"""Ensure path is within workspace"""
|
||||||
|
real_path = os.path.realpath(path)
|
||||||
|
workspace_real = os.path.realpath(self.workspace)
|
||||||
|
return real_path.startswith(workspace_real)
|
||||||
|
|
||||||
|
def validate_command(self, command: str) -> bool:
|
||||||
|
"""Check if command is allowed"""
|
||||||
|
cmd_parts = shlex.split(command)
|
||||||
|
if not cmd_parts:
|
||||||
|
return False
|
||||||
|
|
||||||
|
base_cmd = cmd_parts[0]
|
||||||
|
return base_cmd in self.allowed_commands
|
||||||
|
|
||||||
|
def execute_sandboxed(self, command: str) -> ToolResult:
|
||||||
|
if not self.validate_command(command):
|
||||||
|
return ToolResult(
|
||||||
|
success=False,
|
||||||
|
error=f"Command not allowed: {command}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute in isolated environment
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
shell=True,
|
||||||
|
cwd=self.workspace,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=30,
|
||||||
|
env={
|
||||||
|
**os.environ,
|
||||||
|
"HOME": self.workspace, # Isolate home directory
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return ToolResult(
|
||||||
|
success=result.returncode == 0,
|
||||||
|
output=result.stdout.decode(),
|
||||||
|
error=result.stderr.decode() if result.returncode != 0 else None
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Browser Automation
|
||||||
|
|
||||||
|
### 4.1 Browser Tool Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
class BrowserTool:
|
||||||
|
"""
|
||||||
|
Browser automation for agents using Playwright/Puppeteer.
|
||||||
|
Enables visual debugging and web testing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, headless: bool = True):
|
||||||
|
self.browser = None
|
||||||
|
self.page = None
|
||||||
|
self.headless = headless
|
||||||
|
|
||||||
|
async def open_url(self, url: str) -> ToolResult:
|
||||||
|
"""Navigate to URL and return page info"""
|
||||||
|
if not self.browser:
|
||||||
|
self.browser = await playwright.chromium.launch(headless=self.headless)
|
||||||
|
self.page = await self.browser.new_page()
|
||||||
|
|
||||||
|
await self.page.goto(url)
|
||||||
|
|
||||||
|
# Capture state
|
||||||
|
screenshot = await self.page.screenshot(type='png')
|
||||||
|
title = await self.page.title()
|
||||||
|
|
||||||
|
return ToolResult(
|
||||||
|
success=True,
|
||||||
|
output=f"Loaded: {title}",
|
||||||
|
metadata={
|
||||||
|
"screenshot": base64.b64encode(screenshot).decode(),
|
||||||
|
"url": self.page.url
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
async def click(self, selector: str) -> ToolResult:
|
||||||
|
"""Click on an element"""
|
||||||
|
try:
|
||||||
|
await self.page.click(selector, timeout=5000)
|
||||||
|
await self.page.wait_for_load_state("networkidle")
|
||||||
|
|
||||||
|
screenshot = await self.page.screenshot()
|
||||||
|
return ToolResult(
|
||||||
|
success=True,
|
||||||
|
output=f"Clicked: {selector}",
|
||||||
|
metadata={"screenshot": base64.b64encode(screenshot).decode()}
|
||||||
|
)
|
||||||
|
except TimeoutError:
|
||||||
|
return ToolResult(
|
||||||
|
success=False,
|
||||||
|
error=f"Element not found: {selector}"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def type_text(self, selector: str, text: str) -> ToolResult:
|
||||||
|
"""Type text into an input"""
|
||||||
|
await self.page.fill(selector, text)
|
||||||
|
return ToolResult(success=True, output=f"Typed into {selector}")
|
||||||
|
|
||||||
|
async def get_page_content(self) -> ToolResult:
|
||||||
|
"""Get accessible text content of the page"""
|
||||||
|
content = await self.page.evaluate("""
|
||||||
|
() => {
|
||||||
|
// Get visible text
|
||||||
|
const walker = document.createTreeWalker(
|
||||||
|
document.body,
|
||||||
|
NodeFilter.SHOW_TEXT,
|
||||||
|
null,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
let text = '';
|
||||||
|
while (walker.nextNode()) {
|
||||||
|
const node = walker.currentNode;
|
||||||
|
if (node.textContent.trim()) {
|
||||||
|
text += node.textContent.trim() + '\\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
return ToolResult(success=True, output=content)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Visual Agent Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
class VisualAgent:
|
||||||
|
"""
|
||||||
|
Agent that uses screenshots to understand web pages.
|
||||||
|
Can identify elements visually without selectors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, llm, browser):
|
||||||
|
self.llm = llm
|
||||||
|
self.browser = browser
|
||||||
|
|
||||||
|
async def describe_page(self) -> str:
|
||||||
|
"""Use vision model to describe current page"""
|
||||||
|
screenshot = await self.browser.screenshot()
|
||||||
|
|
||||||
|
response = self.llm.chat([
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{"type": "text", "text": "Describe this webpage. List all interactive elements you see."},
|
||||||
|
{"type": "image", "data": screenshot}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
return response.content
|
||||||
|
|
||||||
|
async def find_and_click(self, description: str) -> ToolResult:
|
||||||
|
"""Find element by visual description and click it"""
|
||||||
|
screenshot = await self.browser.screenshot()
|
||||||
|
|
||||||
|
# Ask vision model to find element
|
||||||
|
response = self.llm.chat([
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": f"""
|
||||||
|
Find the element matching: "{description}"
|
||||||
|
Return the approximate coordinates as JSON: {{"x": number, "y": number}}
|
||||||
|
"""
|
||||||
|
},
|
||||||
|
{"type": "image", "data": screenshot}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
coords = json.loads(response.content)
|
||||||
|
await self.browser.page.mouse.click(coords["x"], coords["y"])
|
||||||
|
|
||||||
|
return ToolResult(success=True, output=f"Clicked at ({coords['x']}, {coords['y']})")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Context Management
|
||||||
|
|
||||||
|
### 5.1 Context Injection Patterns
|
||||||
|
|
||||||
|
````python
|
||||||
|
class ContextManager:
|
||||||
|
"""
|
||||||
|
Manage context provided to the agent.
|
||||||
|
Inspired by Cline's @-mention patterns.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, workspace: str):
|
||||||
|
self.workspace = workspace
|
||||||
|
self.context = []
|
||||||
|
|
||||||
|
def add_file(self, path: str) -> None:
|
||||||
|
"""@file - Add file contents to context"""
|
||||||
|
with open(path, 'r') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
self.context.append({
|
||||||
|
"type": "file",
|
||||||
|
"path": path,
|
||||||
|
"content": content
|
||||||
|
})
|
||||||
|
|
||||||
|
def add_folder(self, path: str, max_files: int = 20) -> None:
|
||||||
|
"""@folder - Add all files in folder"""
|
||||||
|
for root, dirs, files in os.walk(path):
|
||||||
|
for file in files[:max_files]:
|
||||||
|
file_path = os.path.join(root, file)
|
||||||
|
self.add_file(file_path)
|
||||||
|
|
||||||
|
def add_url(self, url: str) -> None:
|
||||||
|
"""@url - Fetch and add URL content"""
|
||||||
|
response = requests.get(url)
|
||||||
|
content = html_to_markdown(response.text)
|
||||||
|
|
||||||
|
self.context.append({
|
||||||
|
"type": "url",
|
||||||
|
"url": url,
|
||||||
|
"content": content
|
||||||
|
})
|
||||||
|
|
||||||
|
def add_problems(self, diagnostics: list) -> None:
|
||||||
|
"""@problems - Add IDE diagnostics"""
|
||||||
|
self.context.append({
|
||||||
|
"type": "diagnostics",
|
||||||
|
"problems": diagnostics
|
||||||
|
})
|
||||||
|
|
||||||
|
def format_for_prompt(self) -> str:
|
||||||
|
"""Format all context for LLM prompt"""
|
||||||
|
parts = []
|
||||||
|
for item in self.context:
|
||||||
|
if item["type"] == "file":
|
||||||
|
parts.append(f"## File: {item['path']}\n```\n{item['content']}\n```")
|
||||||
|
elif item["type"] == "url":
|
||||||
|
parts.append(f"## URL: {item['url']}\n{item['content']}")
|
||||||
|
elif item["type"] == "diagnostics":
|
||||||
|
parts.append(f"## Problems:\n{json.dumps(item['problems'], indent=2)}")
|
||||||
|
|
||||||
|
return "\n\n".join(parts)
|
||||||
|
````
|
||||||
|
|
||||||
|
### 5.2 Checkpoint/Resume
|
||||||
|
|
||||||
|
```python
|
||||||
|
class CheckpointManager:
|
||||||
|
"""
|
||||||
|
Save and restore agent state for long-running tasks.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, storage_dir: str):
|
||||||
|
self.storage_dir = storage_dir
|
||||||
|
os.makedirs(storage_dir, exist_ok=True)
|
||||||
|
|
||||||
|
def save_checkpoint(self, session_id: str, state: dict) -> str:
|
||||||
|
"""Save current agent state"""
|
||||||
|
checkpoint = {
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"session_id": session_id,
|
||||||
|
"history": state["history"],
|
||||||
|
"context": state["context"],
|
||||||
|
"workspace_state": self._capture_workspace(state["workspace"]),
|
||||||
|
"metadata": state.get("metadata", {})
|
||||||
|
}
|
||||||
|
|
||||||
|
path = os.path.join(self.storage_dir, f"{session_id}.json")
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
json.dump(checkpoint, f, indent=2)
|
||||||
|
|
||||||
|
return path
|
||||||
|
|
||||||
|
def restore_checkpoint(self, checkpoint_path: str) -> dict:
|
||||||
|
"""Restore agent state from checkpoint"""
|
||||||
|
with open(checkpoint_path, 'r') as f:
|
||||||
|
checkpoint = json.load(f)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"history": checkpoint["history"],
|
||||||
|
"context": checkpoint["context"],
|
||||||
|
"workspace": self._restore_workspace(checkpoint["workspace_state"]),
|
||||||
|
"metadata": checkpoint["metadata"]
|
||||||
|
}
|
||||||
|
|
||||||
|
def _capture_workspace(self, workspace: str) -> dict:
|
||||||
|
"""Capture relevant workspace state"""
|
||||||
|
# Git status, file hashes, etc.
|
||||||
|
return {
|
||||||
|
"git_ref": subprocess.getoutput(f"cd {workspace} && git rev-parse HEAD"),
|
||||||
|
"git_dirty": subprocess.getoutput(f"cd {workspace} && git status --porcelain")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. MCP (Model Context Protocol) Integration
|
||||||
|
|
||||||
|
### 6.1 MCP Server Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
from mcp import Server, Tool
|
||||||
|
|
||||||
|
class MCPAgent:
|
||||||
|
"""
|
||||||
|
Agent that can dynamically discover and use MCP tools.
|
||||||
|
'Add a tool that...' pattern from Cline.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, llm):
|
||||||
|
self.llm = llm
|
||||||
|
self.mcp_servers = {}
|
||||||
|
self.available_tools = {}
|
||||||
|
|
||||||
|
def connect_server(self, name: str, config: dict) -> None:
|
||||||
|
"""Connect to an MCP server"""
|
||||||
|
server = Server(config)
|
||||||
|
self.mcp_servers[name] = server
|
||||||
|
|
||||||
|
# Discover tools
|
||||||
|
tools = server.list_tools()
|
||||||
|
for tool in tools:
|
||||||
|
self.available_tools[tool.name] = {
|
||||||
|
"server": name,
|
||||||
|
"schema": tool.schema
|
||||||
|
}
|
||||||
|
|
||||||
|
async def create_tool(self, description: str) -> str:
|
||||||
|
"""
|
||||||
|
Create a new MCP server based on user description.
|
||||||
|
'Add a tool that fetches Jira tickets'
|
||||||
|
"""
|
||||||
|
# Generate MCP server code
|
||||||
|
code = self.llm.generate(f"""
|
||||||
|
Create a Python MCP server with a tool that does:
|
||||||
|
{description}
|
||||||
|
|
||||||
|
Use the FastMCP framework. Include proper error handling.
|
||||||
|
Return only the Python code.
|
||||||
|
""")
|
||||||
|
|
||||||
|
# Save and install
|
||||||
|
server_name = self._extract_name(description)
|
||||||
|
path = f"./mcp_servers/{server_name}/server.py"
|
||||||
|
|
||||||
|
with open(path, 'w') as f:
|
||||||
|
f.write(code)
|
||||||
|
|
||||||
|
# Hot-reload
|
||||||
|
self.connect_server(server_name, {"path": path})
|
||||||
|
|
||||||
|
return f"Created tool: {server_name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices Checklist
|
||||||
|
|
||||||
|
### Agent Design
|
||||||
|
|
||||||
|
- [ ] Clear task decomposition
|
||||||
|
- [ ] Appropriate tool granularity
|
||||||
|
- [ ] Error handling at each step
|
||||||
|
- [ ] Progress visibility to user
|
||||||
|
|
||||||
|
### Safety
|
||||||
|
|
||||||
|
- [ ] Permission system implemented
|
||||||
|
- [ ] Dangerous operations blocked
|
||||||
|
- [ ] Sandbox for untrusted code
|
||||||
|
- [ ] Audit logging enabled
|
||||||
|
|
||||||
|
### UX
|
||||||
|
|
||||||
|
- [ ] Approval UI is clear
|
||||||
|
- [ ] Progress updates provided
|
||||||
|
- [ ] Undo/rollback available
|
||||||
|
- [ ] Explanation of actions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Cline](https://github.com/cline/cline)
|
||||||
|
- [OpenAI Codex](https://github.com/openai/codex)
|
||||||
|
- [Model Context Protocol](https://modelcontextprotocol.io/)
|
||||||
|
- [Anthropic Tool Use](https://docs.anthropic.com/claude/docs/tool-use)
|
||||||
691
skills/bun-development/SKILL.md
Normal file
691
skills/bun-development/SKILL.md
Normal file
@@ -0,0 +1,691 @@
|
|||||||
|
---
|
||||||
|
name: bun-development
|
||||||
|
description: "Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun."
|
||||||
|
---
|
||||||
|
|
||||||
|
# ⚡ Bun Development
|
||||||
|
|
||||||
|
> Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun).
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Starting new JS/TS projects with Bun
|
||||||
|
- Migrating from Node.js to Bun
|
||||||
|
- Optimizing development speed
|
||||||
|
- Using Bun's built-in tools (bundler, test runner)
|
||||||
|
- Troubleshooting Bun-specific issues
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Getting Started
|
||||||
|
|
||||||
|
### 1.1 Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# macOS / Linux
|
||||||
|
curl -fsSL https://bun.sh/install | bash
|
||||||
|
|
||||||
|
# Windows
|
||||||
|
powershell -c "irm bun.sh/install.ps1 | iex"
|
||||||
|
|
||||||
|
# Homebrew
|
||||||
|
brew tap oven-sh/bun
|
||||||
|
brew install bun
|
||||||
|
|
||||||
|
# npm (if needed)
|
||||||
|
npm install -g bun
|
||||||
|
|
||||||
|
# Upgrade
|
||||||
|
bun upgrade
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 Why Bun?
|
||||||
|
|
||||||
|
| Feature | Bun | Node.js |
|
||||||
|
| :-------------- | :------------- | :-------------------------- |
|
||||||
|
| Startup time | ~25ms | ~100ms+ |
|
||||||
|
| Package install | 10-100x faster | Baseline |
|
||||||
|
| TypeScript | Native | Requires transpiler |
|
||||||
|
| JSX | Native | Requires transpiler |
|
||||||
|
| Test runner | Built-in | External (Jest, Vitest) |
|
||||||
|
| Bundler | Built-in | External (Webpack, esbuild) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Project Setup
|
||||||
|
|
||||||
|
### 2.1 Create New Project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Initialize project
|
||||||
|
bun init
|
||||||
|
|
||||||
|
# Creates:
|
||||||
|
# ├── package.json
|
||||||
|
# ├── tsconfig.json
|
||||||
|
# ├── index.ts
|
||||||
|
# └── README.md
|
||||||
|
|
||||||
|
# With specific template
|
||||||
|
bun create <template> <project-name>
|
||||||
|
|
||||||
|
# Examples
|
||||||
|
bun create react my-app # React app
|
||||||
|
bun create next my-app # Next.js app
|
||||||
|
bun create vite my-app # Vite app
|
||||||
|
bun create elysia my-api # Elysia API
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 package.json
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "my-bun-project",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"module": "index.ts",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "bun run --watch index.ts",
|
||||||
|
"start": "bun run index.ts",
|
||||||
|
"test": "bun test",
|
||||||
|
"build": "bun build ./index.ts --outdir ./dist",
|
||||||
|
"lint": "bunx eslint ."
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bun": "latest"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": "^5.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 tsconfig.json (Bun-optimized)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"lib": ["ESNext"],
|
||||||
|
"module": "esnext",
|
||||||
|
"target": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"composite": true,
|
||||||
|
"strict": true,
|
||||||
|
"downlevelIteration": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"allowJs": true,
|
||||||
|
"types": ["bun-types"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Package Management
|
||||||
|
|
||||||
|
### 3.1 Installing Packages
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install from package.json
|
||||||
|
bun install # or 'bun i'
|
||||||
|
|
||||||
|
# Add dependencies
|
||||||
|
bun add express # Regular dependency
|
||||||
|
bun add -d typescript # Dev dependency
|
||||||
|
bun add -D @types/node # Dev dependency (alias)
|
||||||
|
bun add --optional pkg # Optional dependency
|
||||||
|
|
||||||
|
# From specific registry
|
||||||
|
bun add lodash --registry https://registry.npmmirror.com
|
||||||
|
|
||||||
|
# Install specific version
|
||||||
|
bun add react@18.2.0
|
||||||
|
bun add react@latest
|
||||||
|
bun add react@next
|
||||||
|
|
||||||
|
# From git
|
||||||
|
bun add github:user/repo
|
||||||
|
bun add git+https://github.com/user/repo.git
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Removing & Updating
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Remove package
|
||||||
|
bun remove lodash
|
||||||
|
|
||||||
|
# Update packages
|
||||||
|
bun update # Update all
|
||||||
|
bun update lodash # Update specific
|
||||||
|
bun update --latest # Update to latest (ignore ranges)
|
||||||
|
|
||||||
|
# Check outdated
|
||||||
|
bun outdated
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 bunx (npx equivalent)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Execute package binaries
|
||||||
|
bunx prettier --write .
|
||||||
|
bunx tsc --init
|
||||||
|
bunx create-react-app my-app
|
||||||
|
|
||||||
|
# With specific version
|
||||||
|
bunx -p typescript@4.9 tsc --version
|
||||||
|
|
||||||
|
# Run without installing
|
||||||
|
bunx cowsay "Hello from Bun!"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 Lockfile
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# bun.lockb is a binary lockfile (faster parsing)
|
||||||
|
# To generate text lockfile for debugging:
|
||||||
|
bun install --yarn # Creates yarn.lock
|
||||||
|
|
||||||
|
# Trust existing lockfile
|
||||||
|
bun install --frozen-lockfile
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Running Code
|
||||||
|
|
||||||
|
### 4.1 Basic Execution
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run TypeScript directly (no build step!)
|
||||||
|
bun run index.ts
|
||||||
|
|
||||||
|
# Run JavaScript
|
||||||
|
bun run index.js
|
||||||
|
|
||||||
|
# Run with arguments
|
||||||
|
bun run server.ts --port 3000
|
||||||
|
|
||||||
|
# Run package.json script
|
||||||
|
bun run dev
|
||||||
|
bun run build
|
||||||
|
|
||||||
|
# Short form (for scripts)
|
||||||
|
bun dev
|
||||||
|
bun build
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Watch Mode
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Auto-restart on file changes
|
||||||
|
bun --watch run index.ts
|
||||||
|
|
||||||
|
# With hot reloading
|
||||||
|
bun --hot run server.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Environment Variables
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// .env file is loaded automatically!
|
||||||
|
|
||||||
|
// Access environment variables
|
||||||
|
const apiKey = Bun.env.API_KEY;
|
||||||
|
const port = Bun.env.PORT ?? "3000";
|
||||||
|
|
||||||
|
// Or use process.env (Node.js compatible)
|
||||||
|
const dbUrl = process.env.DATABASE_URL;
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run with specific env file
|
||||||
|
bun --env-file=.env.production run index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Built-in APIs
|
||||||
|
|
||||||
|
### 5.1 File System (Bun.file)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Read file
|
||||||
|
const file = Bun.file("./data.json");
|
||||||
|
const text = await file.text();
|
||||||
|
const json = await file.json();
|
||||||
|
const buffer = await file.arrayBuffer();
|
||||||
|
|
||||||
|
// File info
|
||||||
|
console.log(file.size); // bytes
|
||||||
|
console.log(file.type); // MIME type
|
||||||
|
|
||||||
|
// Write file
|
||||||
|
await Bun.write("./output.txt", "Hello, Bun!");
|
||||||
|
await Bun.write("./data.json", JSON.stringify({ foo: "bar" }));
|
||||||
|
|
||||||
|
// Stream large files
|
||||||
|
const reader = file.stream();
|
||||||
|
for await (const chunk of reader) {
|
||||||
|
console.log(chunk);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 HTTP Server (Bun.serve)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const server = Bun.serve({
|
||||||
|
port: 3000,
|
||||||
|
|
||||||
|
fetch(request) {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
|
||||||
|
if (url.pathname === "/") {
|
||||||
|
return new Response("Hello World!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url.pathname === "/api/users") {
|
||||||
|
return Response.json([
|
||||||
|
{ id: 1, name: "Alice" },
|
||||||
|
{ id: 2, name: "Bob" },
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response("Not Found", { status: 404 });
|
||||||
|
},
|
||||||
|
|
||||||
|
error(error) {
|
||||||
|
return new Response(`Error: ${error.message}`, { status: 500 });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Server running at http://localhost:${server.port}`);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 WebSocket Server
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const server = Bun.serve({
|
||||||
|
port: 3000,
|
||||||
|
|
||||||
|
fetch(req, server) {
|
||||||
|
// Upgrade to WebSocket
|
||||||
|
if (server.upgrade(req)) {
|
||||||
|
return; // Upgraded
|
||||||
|
}
|
||||||
|
return new Response("Upgrade failed", { status: 500 });
|
||||||
|
},
|
||||||
|
|
||||||
|
websocket: {
|
||||||
|
open(ws) {
|
||||||
|
console.log("Client connected");
|
||||||
|
ws.send("Welcome!");
|
||||||
|
},
|
||||||
|
|
||||||
|
message(ws, message) {
|
||||||
|
console.log(`Received: ${message}`);
|
||||||
|
ws.send(`Echo: ${message}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
close(ws) {
|
||||||
|
console.log("Client disconnected");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 SQLite (Bun.sql)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Database } from "bun:sqlite";
|
||||||
|
|
||||||
|
const db = new Database("mydb.sqlite");
|
||||||
|
|
||||||
|
// Create table
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
email TEXT UNIQUE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Insert
|
||||||
|
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
|
||||||
|
insert.run("Alice", "alice@example.com");
|
||||||
|
|
||||||
|
// Query
|
||||||
|
const query = db.prepare("SELECT * FROM users WHERE name = ?");
|
||||||
|
const user = query.get("Alice");
|
||||||
|
console.log(user); // { id: 1, name: "Alice", email: "alice@example.com" }
|
||||||
|
|
||||||
|
// Query all
|
||||||
|
const allUsers = db.query("SELECT * FROM users").all();
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.5 Password Hashing
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Hash password
|
||||||
|
const password = "super-secret";
|
||||||
|
const hash = await Bun.password.hash(password);
|
||||||
|
|
||||||
|
// Verify password
|
||||||
|
const isValid = await Bun.password.verify(password, hash);
|
||||||
|
console.log(isValid); // true
|
||||||
|
|
||||||
|
// With algorithm options
|
||||||
|
const bcryptHash = await Bun.password.hash(password, {
|
||||||
|
algorithm: "bcrypt",
|
||||||
|
cost: 12,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Testing
|
||||||
|
|
||||||
|
### 6.1 Basic Tests
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// math.test.ts
|
||||||
|
import { describe, it, expect, beforeAll, afterAll } from "bun:test";
|
||||||
|
|
||||||
|
describe("Math operations", () => {
|
||||||
|
it("adds two numbers", () => {
|
||||||
|
expect(1 + 1).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("subtracts two numbers", () => {
|
||||||
|
expect(5 - 3).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run all tests
|
||||||
|
bun test
|
||||||
|
|
||||||
|
# Run specific file
|
||||||
|
bun test math.test.ts
|
||||||
|
|
||||||
|
# Run matching pattern
|
||||||
|
bun test --grep "adds"
|
||||||
|
|
||||||
|
# Watch mode
|
||||||
|
bun test --watch
|
||||||
|
|
||||||
|
# With coverage
|
||||||
|
bun test --coverage
|
||||||
|
|
||||||
|
# Timeout
|
||||||
|
bun test --timeout 5000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 Matchers
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { expect, test } from "bun:test";
|
||||||
|
|
||||||
|
test("matchers", () => {
|
||||||
|
// Equality
|
||||||
|
expect(1).toBe(1);
|
||||||
|
expect({ a: 1 }).toEqual({ a: 1 });
|
||||||
|
expect([1, 2]).toContain(1);
|
||||||
|
|
||||||
|
// Comparisons
|
||||||
|
expect(10).toBeGreaterThan(5);
|
||||||
|
expect(5).toBeLessThanOrEqual(5);
|
||||||
|
|
||||||
|
// Truthiness
|
||||||
|
expect(true).toBeTruthy();
|
||||||
|
expect(null).toBeNull();
|
||||||
|
expect(undefined).toBeUndefined();
|
||||||
|
|
||||||
|
// Strings
|
||||||
|
expect("hello").toMatch(/ell/);
|
||||||
|
expect("hello").toContain("ell");
|
||||||
|
|
||||||
|
// Arrays
|
||||||
|
expect([1, 2, 3]).toHaveLength(3);
|
||||||
|
|
||||||
|
// Exceptions
|
||||||
|
expect(() => {
|
||||||
|
throw new Error("fail");
|
||||||
|
}).toThrow("fail");
|
||||||
|
|
||||||
|
// Async
|
||||||
|
await expect(Promise.resolve(1)).resolves.toBe(1);
|
||||||
|
await expect(Promise.reject("err")).rejects.toBe("err");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.4 Mocking
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { mock, spyOn } from "bun:test";
|
||||||
|
|
||||||
|
// Mock function
|
||||||
|
const mockFn = mock((x: number) => x * 2);
|
||||||
|
mockFn(5);
|
||||||
|
expect(mockFn).toHaveBeenCalled();
|
||||||
|
expect(mockFn).toHaveBeenCalledWith(5);
|
||||||
|
expect(mockFn.mock.results[0].value).toBe(10);
|
||||||
|
|
||||||
|
// Spy on method
|
||||||
|
const obj = {
|
||||||
|
method: () => "original",
|
||||||
|
};
|
||||||
|
const spy = spyOn(obj, "method").mockReturnValue("mocked");
|
||||||
|
expect(obj.method()).toBe("mocked");
|
||||||
|
expect(spy).toHaveBeenCalled();
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Bundling
|
||||||
|
|
||||||
|
### 7.1 Basic Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Bundle for production
|
||||||
|
bun build ./src/index.ts --outdir ./dist
|
||||||
|
|
||||||
|
# With options
|
||||||
|
bun build ./src/index.ts \
|
||||||
|
--outdir ./dist \
|
||||||
|
--target browser \
|
||||||
|
--minify \
|
||||||
|
--sourcemap
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Build API
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const result = await Bun.build({
|
||||||
|
entrypoints: ["./src/index.ts"],
|
||||||
|
outdir: "./dist",
|
||||||
|
target: "browser", // or "bun", "node"
|
||||||
|
minify: true,
|
||||||
|
sourcemap: "external",
|
||||||
|
splitting: true,
|
||||||
|
format: "esm",
|
||||||
|
|
||||||
|
// External packages (not bundled)
|
||||||
|
external: ["react", "react-dom"],
|
||||||
|
|
||||||
|
// Define globals
|
||||||
|
define: {
|
||||||
|
"process.env.NODE_ENV": JSON.stringify("production"),
|
||||||
|
},
|
||||||
|
|
||||||
|
// Naming
|
||||||
|
naming: {
|
||||||
|
entry: "[name].[hash].js",
|
||||||
|
chunk: "chunks/[name].[hash].js",
|
||||||
|
asset: "assets/[name].[hash][ext]",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
console.error(result.logs);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 Compile to Executable
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create standalone executable
|
||||||
|
bun build ./src/cli.ts --compile --outfile myapp
|
||||||
|
|
||||||
|
# Cross-compile
|
||||||
|
bun build ./src/cli.ts --compile --target=bun-linux-x64 --outfile myapp-linux
|
||||||
|
bun build ./src/cli.ts --compile --target=bun-darwin-arm64 --outfile myapp-mac
|
||||||
|
|
||||||
|
# With embedded assets
|
||||||
|
bun build ./src/cli.ts --compile --outfile myapp --embed ./assets
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Migration from Node.js
|
||||||
|
|
||||||
|
### 8.1 Compatibility
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Most Node.js APIs work out of the box
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
import crypto from "crypto";
|
||||||
|
|
||||||
|
// process is global
|
||||||
|
console.log(process.cwd());
|
||||||
|
console.log(process.env.HOME);
|
||||||
|
|
||||||
|
// Buffer is global
|
||||||
|
const buf = Buffer.from("hello");
|
||||||
|
|
||||||
|
// __dirname and __filename work
|
||||||
|
console.log(__dirname);
|
||||||
|
console.log(__filename);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 Common Migration Steps
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Install Bun
|
||||||
|
curl -fsSL https://bun.sh/install | bash
|
||||||
|
|
||||||
|
# 2. Replace package manager
|
||||||
|
rm -rf node_modules package-lock.json
|
||||||
|
bun install
|
||||||
|
|
||||||
|
# 3. Update scripts in package.json
|
||||||
|
# "start": "node index.js" → "start": "bun run index.ts"
|
||||||
|
# "test": "jest" → "test": "bun test"
|
||||||
|
|
||||||
|
# 4. Add Bun types
|
||||||
|
bun add -d @types/bun
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.3 Differences from Node.js
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ❌ Node.js specific (may not work)
|
||||||
|
require("module") // Use import instead
|
||||||
|
require.resolve("pkg") // Use import.meta.resolve
|
||||||
|
__non_webpack_require__ // Not supported
|
||||||
|
|
||||||
|
// ✅ Bun equivalents
|
||||||
|
import pkg from "pkg";
|
||||||
|
const resolved = import.meta.resolve("pkg");
|
||||||
|
Bun.resolveSync("pkg", process.cwd());
|
||||||
|
|
||||||
|
// ❌ These globals differ
|
||||||
|
process.hrtime() // Use Bun.nanoseconds()
|
||||||
|
setImmediate() // Use queueMicrotask()
|
||||||
|
|
||||||
|
// ✅ Bun-specific features
|
||||||
|
const file = Bun.file("./data.txt"); // Fast file API
|
||||||
|
Bun.serve({ port: 3000, fetch: ... }); // Fast HTTP server
|
||||||
|
Bun.password.hash(password); // Built-in hashing
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Performance Tips
|
||||||
|
|
||||||
|
### 9.1 Use Bun-native APIs
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Slow (Node.js compat)
|
||||||
|
import fs from "fs/promises";
|
||||||
|
const content = await fs.readFile("./data.txt", "utf-8");
|
||||||
|
|
||||||
|
// Fast (Bun-native)
|
||||||
|
const file = Bun.file("./data.txt");
|
||||||
|
const content = await file.text();
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.2 Use Bun.serve for HTTP
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Don't: Express/Fastify (overhead)
|
||||||
|
import express from "express";
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
// Do: Bun.serve (native, 4-10x faster)
|
||||||
|
Bun.serve({
|
||||||
|
fetch(req) {
|
||||||
|
return new Response("Hello!");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Or use Elysia (Bun-optimized framework)
|
||||||
|
import { Elysia } from "elysia";
|
||||||
|
new Elysia().get("/", () => "Hello!").listen(3000);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.3 Bundle for Production
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Always bundle and minify for production
|
||||||
|
bun build ./src/index.ts --outdir ./dist --minify --target node
|
||||||
|
|
||||||
|
# Then run the bundle
|
||||||
|
bun run ./dist/index.js
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
| Task | Command |
|
||||||
|
| :----------- | :----------------------------------------- |
|
||||||
|
| Init project | `bun init` |
|
||||||
|
| Install deps | `bun install` |
|
||||||
|
| Add package | `bun add <pkg>` |
|
||||||
|
| Run script | `bun run <script>` |
|
||||||
|
| Run file | `bun run file.ts` |
|
||||||
|
| Watch mode | `bun --watch run file.ts` |
|
||||||
|
| Run tests | `bun test` |
|
||||||
|
| Build | `bun build ./src/index.ts --outdir ./dist` |
|
||||||
|
| Execute pkg | `bunx <pkg>` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Bun Documentation](https://bun.sh/docs)
|
||||||
|
- [Bun GitHub](https://github.com/oven-sh/bun)
|
||||||
|
- [Elysia Framework](https://elysiajs.com/)
|
||||||
|
- [Bun Discord](https://bun.sh/discord)
|
||||||
62
skills/concise-planning/SKILL.md
Normal file
62
skills/concise-planning/SKILL.md
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
---
|
||||||
|
name: concise-planning
|
||||||
|
description: Use when a user asks for a plan for a coding task, to generate a clear, actionable, and atomic checklist.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Concise Planning
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Turn a user request into a **single, actionable plan** with atomic steps.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
### 1. Scan Context
|
||||||
|
|
||||||
|
- Read `README.md`, docs, and relevant code files.
|
||||||
|
- Identify constraints (language, frameworks, tests).
|
||||||
|
|
||||||
|
### 2. Minimal Interaction
|
||||||
|
|
||||||
|
- Ask **at most 1–2 questions** and only if truly blocking.
|
||||||
|
- Make reasonable assumptions for non-blocking unknowns.
|
||||||
|
|
||||||
|
### 3. Generate Plan
|
||||||
|
|
||||||
|
Use the following structure:
|
||||||
|
|
||||||
|
- **Approach**: 1-3 sentences on what and why.
|
||||||
|
- **Scope**: Bullet points for "In" and "Out".
|
||||||
|
- **Action Items**: A list of 6-10 atomic, ordered tasks (Verb-first).
|
||||||
|
- **Validation**: At least one item for testing.
|
||||||
|
|
||||||
|
## Plan Template
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
# Plan
|
||||||
|
|
||||||
|
<High-level approach>
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- In:
|
||||||
|
- Out:
|
||||||
|
|
||||||
|
## Action Items
|
||||||
|
|
||||||
|
[ ] <Step 1: Discovery>
|
||||||
|
[ ] <Step 2: Implementation>
|
||||||
|
[ ] <Step 3: Implementation>
|
||||||
|
[ ] <Step 4: Validation/Testing>
|
||||||
|
[ ] <Step 5: Rollout/Commit>
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
- <Question 1 (max 3)>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Checklist Guidelines
|
||||||
|
|
||||||
|
- **Atomic**: Each step should be a single logical unit of work.
|
||||||
|
- **Verb-first**: "Add...", "Refactor...", "Verify...".
|
||||||
|
- **Concrete**: Name specific files or modules when possible.
|
||||||
846
skills/github-workflow-automation/SKILL.md
Normal file
846
skills/github-workflow-automation/SKILL.md
Normal file
@@ -0,0 +1,846 @@
|
|||||||
|
---
|
||||||
|
name: github-workflow-automation
|
||||||
|
description: "Automate GitHub workflows with AI assistance. Includes PR reviews, issue triage, CI/CD integration, and Git operations. Use when automating GitHub workflows, setting up PR review automation, creating GitHub Actions, or triaging issues."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🔧 GitHub Workflow Automation
|
||||||
|
|
||||||
|
> Patterns for automating GitHub workflows with AI assistance, inspired by [Gemini CLI](https://github.com/google-gemini/gemini-cli) and modern DevOps practices.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Automating PR reviews with AI
|
||||||
|
- Setting up issue triage automation
|
||||||
|
- Creating GitHub Actions workflows
|
||||||
|
- Integrating AI into CI/CD pipelines
|
||||||
|
- Automating Git operations (rebases, cherry-picks)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Automated PR Review
|
||||||
|
|
||||||
|
### 1.1 PR Review Action
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/ai-review.yml
|
||||||
|
name: AI Code Review
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
review:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Get changed files
|
||||||
|
id: changed
|
||||||
|
run: |
|
||||||
|
files=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)
|
||||||
|
echo "files<<EOF" >> $GITHUB_OUTPUT
|
||||||
|
echo "$files" >> $GITHUB_OUTPUT
|
||||||
|
echo "EOF" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Get diff
|
||||||
|
id: diff
|
||||||
|
run: |
|
||||||
|
diff=$(git diff origin/${{ github.base_ref }}...HEAD)
|
||||||
|
echo "diff<<EOF" >> $GITHUB_OUTPUT
|
||||||
|
echo "$diff" >> $GITHUB_OUTPUT
|
||||||
|
echo "EOF" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: AI Review
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const { Anthropic } = require('@anthropic-ai/sdk');
|
||||||
|
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
|
||||||
|
|
||||||
|
const response = await client.messages.create({
|
||||||
|
model: "claude-3-sonnet-20240229",
|
||||||
|
max_tokens: 4096,
|
||||||
|
messages: [{
|
||||||
|
role: "user",
|
||||||
|
content: `Review this PR diff and provide feedback:
|
||||||
|
|
||||||
|
Changed files: ${{ steps.changed.outputs.files }}
|
||||||
|
|
||||||
|
Diff:
|
||||||
|
${{ steps.diff.outputs.diff }}
|
||||||
|
|
||||||
|
Provide:
|
||||||
|
1. Summary of changes
|
||||||
|
2. Potential issues or bugs
|
||||||
|
3. Suggestions for improvement
|
||||||
|
4. Security concerns if any
|
||||||
|
|
||||||
|
Format as GitHub markdown.`
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
await github.rest.pulls.createReview({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
pull_number: context.issue.number,
|
||||||
|
body: response.content[0].text,
|
||||||
|
event: 'COMMENT'
|
||||||
|
});
|
||||||
|
env:
|
||||||
|
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 Review Comment Patterns
|
||||||
|
|
||||||
|
````markdown
|
||||||
|
# AI Review Structure
|
||||||
|
|
||||||
|
## 📋 Summary
|
||||||
|
|
||||||
|
Brief description of what this PR does.
|
||||||
|
|
||||||
|
## ✅ What looks good
|
||||||
|
|
||||||
|
- Well-structured code
|
||||||
|
- Good test coverage
|
||||||
|
- Clear naming conventions
|
||||||
|
|
||||||
|
## ⚠️ Potential Issues
|
||||||
|
|
||||||
|
1. **Line 42**: Possible null pointer exception
|
||||||
|
```javascript
|
||||||
|
// Current
|
||||||
|
user.profile.name;
|
||||||
|
// Suggested
|
||||||
|
user?.profile?.name ?? "Unknown";
|
||||||
|
```
|
||||||
|
````
|
||||||
|
|
||||||
|
2. **Line 78**: Consider error handling
|
||||||
|
```javascript
|
||||||
|
// Add try-catch or .catch()
|
||||||
|
```
|
||||||
|
|
||||||
|
## 💡 Suggestions
|
||||||
|
|
||||||
|
- Consider extracting the validation logic into a separate function
|
||||||
|
- Add JSDoc comments for public methods
|
||||||
|
|
||||||
|
## 🔒 Security Notes
|
||||||
|
|
||||||
|
- No sensitive data exposure detected
|
||||||
|
- API key handling looks correct
|
||||||
|
|
||||||
|
````
|
||||||
|
|
||||||
|
### 1.3 Focused Reviews
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Review only specific file types
|
||||||
|
- name: Filter code files
|
||||||
|
run: |
|
||||||
|
files=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | \
|
||||||
|
grep -E '\.(ts|tsx|js|jsx|py|go)$' || true)
|
||||||
|
echo "code_files=$files" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
# Review with context
|
||||||
|
- name: AI Review with context
|
||||||
|
run: |
|
||||||
|
# Include relevant context files
|
||||||
|
context=""
|
||||||
|
for file in ${{ steps.changed.outputs.files }}; do
|
||||||
|
if [[ -f "$file" ]]; then
|
||||||
|
context+="=== $file ===\n$(cat $file)\n\n"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# Send to AI with full file context
|
||||||
|
````
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Issue Triage Automation
|
||||||
|
|
||||||
|
### 2.1 Auto-label Issues
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/issue-triage.yml
|
||||||
|
name: Issue Triage
|
||||||
|
|
||||||
|
on:
|
||||||
|
issues:
|
||||||
|
types: [opened]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
triage:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
issues: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Analyze issue
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const issue = context.payload.issue;
|
||||||
|
|
||||||
|
// Call AI to analyze
|
||||||
|
const analysis = await analyzeIssue(issue.title, issue.body);
|
||||||
|
|
||||||
|
// Apply labels
|
||||||
|
const labels = [];
|
||||||
|
|
||||||
|
if (analysis.type === 'bug') {
|
||||||
|
labels.push('bug');
|
||||||
|
if (analysis.severity === 'high') labels.push('priority: high');
|
||||||
|
} else if (analysis.type === 'feature') {
|
||||||
|
labels.push('enhancement');
|
||||||
|
} else if (analysis.type === 'question') {
|
||||||
|
labels.push('question');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (analysis.area) {
|
||||||
|
labels.push(`area: ${analysis.area}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await github.rest.issues.addLabels({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: issue.number,
|
||||||
|
labels: labels
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add initial response
|
||||||
|
if (analysis.type === 'bug' && !analysis.hasReproSteps) {
|
||||||
|
await github.rest.issues.createComment({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: issue.number,
|
||||||
|
body: `Thanks for reporting this issue!
|
||||||
|
|
||||||
|
To help us investigate, could you please provide:
|
||||||
|
- Steps to reproduce the issue
|
||||||
|
- Expected behavior
|
||||||
|
- Actual behavior
|
||||||
|
- Environment (OS, version, etc.)
|
||||||
|
|
||||||
|
This will help us resolve your issue faster. 🙏`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Issue Analysis Prompt
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const TRIAGE_PROMPT = `
|
||||||
|
Analyze this GitHub issue and classify it:
|
||||||
|
|
||||||
|
Title: {title}
|
||||||
|
Body: {body}
|
||||||
|
|
||||||
|
Return JSON with:
|
||||||
|
{
|
||||||
|
"type": "bug" | "feature" | "question" | "docs" | "other",
|
||||||
|
"severity": "low" | "medium" | "high" | "critical",
|
||||||
|
"area": "frontend" | "backend" | "api" | "docs" | "ci" | "other",
|
||||||
|
"summary": "one-line summary",
|
||||||
|
"hasReproSteps": boolean,
|
||||||
|
"isFirstContribution": boolean,
|
||||||
|
"suggestedLabels": ["label1", "label2"],
|
||||||
|
"suggestedAssignees": ["username"] // based on area expertise
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Stale Issue Management
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/stale.yml
|
||||||
|
name: Manage Stale Issues
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 0 * * *" # Daily
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
stale:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/stale@v9
|
||||||
|
with:
|
||||||
|
stale-issue-message: |
|
||||||
|
This issue has been automatically marked as stale because it has not had
|
||||||
|
recent activity. It will be closed in 14 days if no further activity occurs.
|
||||||
|
|
||||||
|
If this issue is still relevant:
|
||||||
|
- Add a comment with an update
|
||||||
|
- Remove the `stale` label
|
||||||
|
|
||||||
|
Thank you for your contributions! 🙏
|
||||||
|
|
||||||
|
stale-pr-message: |
|
||||||
|
This PR has been automatically marked as stale. Please update it or it
|
||||||
|
will be closed in 14 days.
|
||||||
|
|
||||||
|
days-before-stale: 60
|
||||||
|
days-before-close: 14
|
||||||
|
stale-issue-label: "stale"
|
||||||
|
stale-pr-label: "stale"
|
||||||
|
exempt-issue-labels: "pinned,security,in-progress"
|
||||||
|
exempt-pr-labels: "pinned,security"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. CI/CD Integration
|
||||||
|
|
||||||
|
### 3.1 Smart Test Selection
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/smart-tests.yml
|
||||||
|
name: Smart Test Selection
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
test_suites: ${{ steps.analyze.outputs.suites }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Analyze changes
|
||||||
|
id: analyze
|
||||||
|
run: |
|
||||||
|
# Get changed files
|
||||||
|
changed=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)
|
||||||
|
|
||||||
|
# Determine which test suites to run
|
||||||
|
suites="[]"
|
||||||
|
|
||||||
|
if echo "$changed" | grep -q "^src/api/"; then
|
||||||
|
suites=$(echo $suites | jq '. + ["api"]')
|
||||||
|
fi
|
||||||
|
|
||||||
|
if echo "$changed" | grep -q "^src/frontend/"; then
|
||||||
|
suites=$(echo $suites | jq '. + ["frontend"]')
|
||||||
|
fi
|
||||||
|
|
||||||
|
if echo "$changed" | grep -q "^src/database/"; then
|
||||||
|
suites=$(echo $suites | jq '. + ["database", "api"]')
|
||||||
|
fi
|
||||||
|
|
||||||
|
# If nothing specific, run all
|
||||||
|
if [ "$suites" = "[]" ]; then
|
||||||
|
suites='["all"]'
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "suites=$suites" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
test:
|
||||||
|
needs: analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
suite: ${{ fromJson(needs.analyze.outputs.test_suites) }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
run: |
|
||||||
|
if [ "${{ matrix.suite }}" = "all" ]; then
|
||||||
|
npm test
|
||||||
|
else
|
||||||
|
npm test -- --suite ${{ matrix.suite }}
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Deployment with AI Validation
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/deploy.yml
|
||||||
|
name: Deploy with AI Validation
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Get deployment changes
|
||||||
|
id: changes
|
||||||
|
run: |
|
||||||
|
# Get commits since last deployment
|
||||||
|
last_deploy=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
|
||||||
|
if [ -n "$last_deploy" ]; then
|
||||||
|
changes=$(git log --oneline $last_deploy..HEAD)
|
||||||
|
else
|
||||||
|
changes=$(git log --oneline -10)
|
||||||
|
fi
|
||||||
|
echo "changes<<EOF" >> $GITHUB_OUTPUT
|
||||||
|
echo "$changes" >> $GITHUB_OUTPUT
|
||||||
|
echo "EOF" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: AI Risk Assessment
|
||||||
|
id: assess
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
// Analyze changes for deployment risk
|
||||||
|
const prompt = `
|
||||||
|
Analyze these changes for deployment risk:
|
||||||
|
|
||||||
|
${process.env.CHANGES}
|
||||||
|
|
||||||
|
Return JSON:
|
||||||
|
{
|
||||||
|
"riskLevel": "low" | "medium" | "high",
|
||||||
|
"concerns": ["concern1", "concern2"],
|
||||||
|
"recommendations": ["rec1", "rec2"],
|
||||||
|
"requiresManualApproval": boolean
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Call AI and parse response
|
||||||
|
const analysis = await callAI(prompt);
|
||||||
|
|
||||||
|
if (analysis.riskLevel === 'high') {
|
||||||
|
core.setFailed('High-risk deployment detected. Manual review required.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return analysis;
|
||||||
|
env:
|
||||||
|
CHANGES: ${{ steps.changes.outputs.changes }}
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
needs: validate
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment: production
|
||||||
|
steps:
|
||||||
|
- name: Deploy
|
||||||
|
run: |
|
||||||
|
echo "Deploying to production..."
|
||||||
|
# Deployment commands here
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Rollback Automation
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/rollback.yml
|
||||||
|
name: Automated Rollback
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
reason:
|
||||||
|
description: "Reason for rollback"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
rollback:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Find last stable version
|
||||||
|
id: stable
|
||||||
|
run: |
|
||||||
|
# Find last successful deployment
|
||||||
|
stable=$(git tag -l 'v*' --sort=-version:refname | head -1)
|
||||||
|
echo "version=$stable" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Rollback
|
||||||
|
run: |
|
||||||
|
git checkout ${{ steps.stable.outputs.version }}
|
||||||
|
# Deploy stable version
|
||||||
|
npm run deploy
|
||||||
|
|
||||||
|
- name: Notify team
|
||||||
|
uses: slackapi/slack-github-action@v1
|
||||||
|
with:
|
||||||
|
payload: |
|
||||||
|
{
|
||||||
|
"text": "🔄 Production rolled back to ${{ steps.stable.outputs.version }}",
|
||||||
|
"blocks": [
|
||||||
|
{
|
||||||
|
"type": "section",
|
||||||
|
"text": {
|
||||||
|
"type": "mrkdwn",
|
||||||
|
"text": "*Rollback executed*\n• Version: `${{ steps.stable.outputs.version }}`\n• Reason: ${{ inputs.reason }}\n• Triggered by: ${{ github.actor }}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Git Operations
|
||||||
|
|
||||||
|
### 4.1 Automated Rebasing
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/auto-rebase.yml
|
||||||
|
name: Auto Rebase
|
||||||
|
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
rebase:
|
||||||
|
if: github.event.issue.pull_request && contains(github.event.comment.body, '/rebase')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Setup Git
|
||||||
|
run: |
|
||||||
|
git config user.name "github-actions[bot]"
|
||||||
|
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
|
||||||
|
- name: Rebase PR
|
||||||
|
run: |
|
||||||
|
# Fetch PR branch
|
||||||
|
gh pr checkout ${{ github.event.issue.number }}
|
||||||
|
|
||||||
|
# Rebase onto main
|
||||||
|
git fetch origin main
|
||||||
|
git rebase origin/main
|
||||||
|
|
||||||
|
# Force push
|
||||||
|
git push --force-with-lease
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Comment result
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
github.rest.issues.createComment({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: context.issue.number,
|
||||||
|
body: '✅ Successfully rebased onto main!'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Smart Cherry-Pick
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// AI-assisted cherry-pick that handles conflicts
|
||||||
|
async function smartCherryPick(commitHash: string, targetBranch: string) {
|
||||||
|
// Get commit info
|
||||||
|
const commitInfo = await exec(`git show ${commitHash} --stat`);
|
||||||
|
|
||||||
|
// Check for potential conflicts
|
||||||
|
const targetDiff = await exec(
|
||||||
|
`git diff ${targetBranch}...HEAD -- ${affectedFiles}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// AI analysis
|
||||||
|
const analysis = await ai.analyze(`
|
||||||
|
I need to cherry-pick this commit to ${targetBranch}:
|
||||||
|
|
||||||
|
${commitInfo}
|
||||||
|
|
||||||
|
Current state of affected files on ${targetBranch}:
|
||||||
|
${targetDiff}
|
||||||
|
|
||||||
|
Will there be conflicts? If so, suggest resolution strategy.
|
||||||
|
`);
|
||||||
|
|
||||||
|
if (analysis.willConflict) {
|
||||||
|
// Create branch for manual resolution
|
||||||
|
await exec(
|
||||||
|
`git checkout -b cherry-pick-${commitHash.slice(0, 7)} ${targetBranch}`
|
||||||
|
);
|
||||||
|
const result = await exec(`git cherry-pick ${commitHash}`, {
|
||||||
|
allowFail: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.failed) {
|
||||||
|
// AI-assisted conflict resolution
|
||||||
|
const conflicts = await getConflicts();
|
||||||
|
for (const conflict of conflicts) {
|
||||||
|
const resolution = await ai.resolveConflict(conflict);
|
||||||
|
await applyResolution(conflict.file, resolution);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await exec(`git checkout ${targetBranch}`);
|
||||||
|
await exec(`git cherry-pick ${commitHash}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Branch Cleanup
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/branch-cleanup.yml
|
||||||
|
name: Branch Cleanup
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 * * 0' # Weekly
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
cleanup:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Find stale branches
|
||||||
|
id: stale
|
||||||
|
run: |
|
||||||
|
# Branches not updated in 30 days
|
||||||
|
stale=$(git for-each-ref --sort=-committerdate refs/remotes/origin \
|
||||||
|
--format='%(refname:short) %(committerdate:relative)' | \
|
||||||
|
grep -E '[3-9][0-9]+ days|[0-9]+ months|[0-9]+ years' | \
|
||||||
|
grep -v 'origin/main\|origin/develop' | \
|
||||||
|
cut -d' ' -f1 | sed 's|origin/||')
|
||||||
|
|
||||||
|
echo "branches<<EOF" >> $GITHUB_OUTPUT
|
||||||
|
echo "$stale" >> $GITHUB_OUTPUT
|
||||||
|
echo "EOF" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Create cleanup PR
|
||||||
|
if: steps.stale.outputs.branches != ''
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const branches = `${{ steps.stale.outputs.branches }}`.split('\n').filter(Boolean);
|
||||||
|
|
||||||
|
const body = `## 🧹 Stale Branch Cleanup
|
||||||
|
|
||||||
|
The following branches haven't been updated in over 30 days:
|
||||||
|
|
||||||
|
${branches.map(b => `- \`${b}\``).join('\n')}
|
||||||
|
|
||||||
|
### Actions:
|
||||||
|
- [ ] Review each branch
|
||||||
|
- [ ] Delete branches that are no longer needed
|
||||||
|
- Comment \`/keep branch-name\` to preserve specific branches
|
||||||
|
`;
|
||||||
|
|
||||||
|
await github.rest.issues.create({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
title: 'Stale Branch Cleanup',
|
||||||
|
body: body,
|
||||||
|
labels: ['housekeeping']
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. On-Demand Assistance
|
||||||
|
|
||||||
|
### 5.1 @mention Bot
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/mention-bot.yml
|
||||||
|
name: AI Mention Bot
|
||||||
|
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
pull_request_review_comment:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
respond:
|
||||||
|
if: contains(github.event.comment.body, '@ai-helper')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Extract question
|
||||||
|
id: question
|
||||||
|
run: |
|
||||||
|
# Extract text after @ai-helper
|
||||||
|
question=$(echo "${{ github.event.comment.body }}" | sed 's/.*@ai-helper//')
|
||||||
|
echo "question=$question" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Get context
|
||||||
|
id: context
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event.issue.pull_request }}" != "" ]; then
|
||||||
|
# It's a PR - get diff
|
||||||
|
gh pr diff ${{ github.event.issue.number }} > context.txt
|
||||||
|
else
|
||||||
|
# It's an issue - get description
|
||||||
|
gh issue view ${{ github.event.issue.number }} --json body -q .body > context.txt
|
||||||
|
fi
|
||||||
|
echo "context=$(cat context.txt)" >> $GITHUB_OUTPUT
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: AI Response
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const response = await ai.chat(`
|
||||||
|
Context: ${process.env.CONTEXT}
|
||||||
|
|
||||||
|
Question: ${process.env.QUESTION}
|
||||||
|
|
||||||
|
Provide a helpful, specific answer. Include code examples if relevant.
|
||||||
|
`);
|
||||||
|
|
||||||
|
await github.rest.issues.createComment({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: context.issue.number,
|
||||||
|
body: response
|
||||||
|
});
|
||||||
|
env:
|
||||||
|
CONTEXT: ${{ steps.context.outputs.context }}
|
||||||
|
QUESTION: ${{ steps.question.outputs.question }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Command Patterns
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Available Commands
|
||||||
|
|
||||||
|
| Command | Description |
|
||||||
|
| :------------------- | :-------------------------- |
|
||||||
|
| `@ai-helper explain` | Explain the code in this PR |
|
||||||
|
| `@ai-helper review` | Request AI code review |
|
||||||
|
| `@ai-helper fix` | Suggest fixes for issues |
|
||||||
|
| `@ai-helper test` | Generate test cases |
|
||||||
|
| `@ai-helper docs` | Generate documentation |
|
||||||
|
| `/rebase` | Rebase PR onto main |
|
||||||
|
| `/update` | Update PR branch from main |
|
||||||
|
| `/approve` | Mark as approved by bot |
|
||||||
|
| `/label bug` | Add 'bug' label |
|
||||||
|
| `/assign @user` | Assign to user |
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Repository Configuration
|
||||||
|
|
||||||
|
### 6.1 CODEOWNERS
|
||||||
|
|
||||||
|
```
|
||||||
|
# .github/CODEOWNERS
|
||||||
|
|
||||||
|
# Global owners
|
||||||
|
* @org/core-team
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
/src/frontend/ @org/frontend-team
|
||||||
|
*.tsx @org/frontend-team
|
||||||
|
*.css @org/frontend-team
|
||||||
|
|
||||||
|
# Backend
|
||||||
|
/src/api/ @org/backend-team
|
||||||
|
/src/database/ @org/backend-team
|
||||||
|
|
||||||
|
# Infrastructure
|
||||||
|
/.github/ @org/devops-team
|
||||||
|
/terraform/ @org/devops-team
|
||||||
|
Dockerfile @org/devops-team
|
||||||
|
|
||||||
|
# Docs
|
||||||
|
/docs/ @org/docs-team
|
||||||
|
*.md @org/docs-team
|
||||||
|
|
||||||
|
# Security-sensitive
|
||||||
|
/src/auth/ @org/security-team
|
||||||
|
/src/crypto/ @org/security-team
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Branch Protection
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# Set up via GitHub API
|
||||||
|
- name: Configure branch protection
|
||||||
|
uses: actions/github-script@v7
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
await github.rest.repos.updateBranchProtection({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
branch: 'main',
|
||||||
|
required_status_checks: {
|
||||||
|
strict: true,
|
||||||
|
contexts: ['test', 'lint', 'ai-review']
|
||||||
|
},
|
||||||
|
enforce_admins: true,
|
||||||
|
required_pull_request_reviews: {
|
||||||
|
required_approving_review_count: 1,
|
||||||
|
require_code_owner_reviews: true,
|
||||||
|
dismiss_stale_reviews: true
|
||||||
|
},
|
||||||
|
restrictions: null,
|
||||||
|
required_linear_history: true,
|
||||||
|
allow_force_pushes: false,
|
||||||
|
allow_deletions: false
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- [ ] Store API keys in GitHub Secrets
|
||||||
|
- [ ] Use minimal permissions in workflows
|
||||||
|
- [ ] Validate all inputs
|
||||||
|
- [ ] Don't expose sensitive data in logs
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
|
||||||
|
- [ ] Cache dependencies
|
||||||
|
- [ ] Use matrix builds for parallel testing
|
||||||
|
- [ ] Skip unnecessary jobs with path filters
|
||||||
|
- [ ] Use self-hosted runners for heavy workloads
|
||||||
|
|
||||||
|
### Reliability
|
||||||
|
|
||||||
|
- [ ] Add timeouts to jobs
|
||||||
|
- [ ] Handle rate limits gracefully
|
||||||
|
- [ ] Implement retry logic
|
||||||
|
- [ ] Have rollback procedures
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Gemini CLI GitHub Action](https://github.com/google-github-actions/run-gemini-cli)
|
||||||
|
- [GitHub Actions Documentation](https://docs.github.com/en/actions)
|
||||||
|
- [GitHub REST API](https://docs.github.com/en/rest)
|
||||||
|
- [CODEOWNERS Syntax](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners)
|
||||||
645
skills/javascript-mastery/SKILL.md
Normal file
645
skills/javascript-mastery/SKILL.md
Normal file
@@ -0,0 +1,645 @@
|
|||||||
|
---
|
||||||
|
name: javascript-mastery
|
||||||
|
description: "Comprehensive JavaScript reference covering 33+ essential concepts every developer should know. From fundamentals like primitives and closures to advanced patterns like async/await and functional programming. Use when explaining JS concepts, debugging JavaScript issues, or teaching JavaScript fundamentals."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🧠 JavaScript Mastery
|
||||||
|
|
||||||
|
> 33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Explaining JavaScript concepts
|
||||||
|
- Debugging tricky JS behavior
|
||||||
|
- Teaching JavaScript fundamentals
|
||||||
|
- Reviewing code for JS best practices
|
||||||
|
- Understanding language quirks
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Fundamentals
|
||||||
|
|
||||||
|
### 1.1 Primitive Types
|
||||||
|
|
||||||
|
JavaScript has 7 primitive types:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// String
|
||||||
|
const str = "hello";
|
||||||
|
|
||||||
|
// Number (integers and floats)
|
||||||
|
const num = 42;
|
||||||
|
const float = 3.14;
|
||||||
|
|
||||||
|
// BigInt (for large integers)
|
||||||
|
const big = 9007199254740991n;
|
||||||
|
|
||||||
|
// Boolean
|
||||||
|
const bool = true;
|
||||||
|
|
||||||
|
// Undefined
|
||||||
|
let undef; // undefined
|
||||||
|
|
||||||
|
// Null
|
||||||
|
const empty = null;
|
||||||
|
|
||||||
|
// Symbol (unique identifiers)
|
||||||
|
const sym = Symbol("description");
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key points**:
|
||||||
|
|
||||||
|
- Primitives are immutable
|
||||||
|
- Passed by value
|
||||||
|
- `typeof null === "object"` is a historical bug
|
||||||
|
|
||||||
|
### 1.2 Type Coercion
|
||||||
|
|
||||||
|
JavaScript implicitly converts types:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// String coercion
|
||||||
|
"5" + 3; // "53" (number → string)
|
||||||
|
"5" - 3; // 2 (string → number)
|
||||||
|
|
||||||
|
// Boolean coercion
|
||||||
|
Boolean(""); // false
|
||||||
|
Boolean("hello"); // true
|
||||||
|
Boolean(0); // false
|
||||||
|
Boolean([]); // true (!)
|
||||||
|
|
||||||
|
// Equality coercion
|
||||||
|
"5" == 5; // true (coerces)
|
||||||
|
"5" === 5; // false (strict)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Falsy values** (8 total):
|
||||||
|
`false`, `0`, `-0`, `0n`, `""`, `null`, `undefined`, `NaN`
|
||||||
|
|
||||||
|
### 1.3 Equality Operators
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// == (loose equality) - coerces types
|
||||||
|
null == undefined; // true
|
||||||
|
"1" == 1; // true
|
||||||
|
|
||||||
|
// === (strict equality) - no coercion
|
||||||
|
null === undefined; // false
|
||||||
|
"1" === 1; // false
|
||||||
|
|
||||||
|
// Object.is() - handles edge cases
|
||||||
|
Object.is(NaN, NaN); // true (NaN === NaN is false!)
|
||||||
|
Object.is(-0, 0); // false (0 === -0 is true!)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rule**: Always use `===` unless you have a specific reason not to.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Scope & Closures
|
||||||
|
|
||||||
|
### 2.1 Scope Types
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Global scope
|
||||||
|
var globalVar = "global";
|
||||||
|
|
||||||
|
function outer() {
|
||||||
|
// Function scope
|
||||||
|
var functionVar = "function";
|
||||||
|
|
||||||
|
if (true) {
|
||||||
|
// Block scope (let/const only)
|
||||||
|
let blockVar = "block";
|
||||||
|
const alsoBlock = "block";
|
||||||
|
var notBlock = "function"; // var ignores blocks!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Closures
|
||||||
|
|
||||||
|
A closure is a function that remembers its lexical scope:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function createCounter() {
|
||||||
|
let count = 0; // "closed over" variable
|
||||||
|
|
||||||
|
return {
|
||||||
|
increment() {
|
||||||
|
return ++count;
|
||||||
|
},
|
||||||
|
decrement() {
|
||||||
|
return --count;
|
||||||
|
},
|
||||||
|
getCount() {
|
||||||
|
return count;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const counter = createCounter();
|
||||||
|
counter.increment(); // 1
|
||||||
|
counter.increment(); // 2
|
||||||
|
counter.getCount(); // 2
|
||||||
|
```
|
||||||
|
|
||||||
|
**Common use cases**:
|
||||||
|
|
||||||
|
- Data privacy (module pattern)
|
||||||
|
- Function factories
|
||||||
|
- Partial application
|
||||||
|
- Memoization
|
||||||
|
|
||||||
|
### 2.3 var vs let vs const
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// var - function scoped, hoisted, can redeclare
|
||||||
|
var x = 1;
|
||||||
|
var x = 2; // OK
|
||||||
|
|
||||||
|
// let - block scoped, hoisted (TDZ), no redeclare
|
||||||
|
let y = 1;
|
||||||
|
// let y = 2; // Error!
|
||||||
|
|
||||||
|
// const - like let, but can't reassign
|
||||||
|
const z = 1;
|
||||||
|
// z = 2; // Error!
|
||||||
|
|
||||||
|
// BUT: const objects are mutable
|
||||||
|
const obj = { a: 1 };
|
||||||
|
obj.a = 2; // OK
|
||||||
|
obj.b = 3; // OK
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Functions & Execution
|
||||||
|
|
||||||
|
### 3.1 Call Stack
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function first() {
|
||||||
|
console.log("first start");
|
||||||
|
second();
|
||||||
|
console.log("first end");
|
||||||
|
}
|
||||||
|
|
||||||
|
function second() {
|
||||||
|
console.log("second");
|
||||||
|
}
|
||||||
|
|
||||||
|
first();
|
||||||
|
// Output:
|
||||||
|
// "first start"
|
||||||
|
// "second"
|
||||||
|
// "first end"
|
||||||
|
```
|
||||||
|
|
||||||
|
Stack overflow example:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
function infinite() {
|
||||||
|
infinite(); // No base case!
|
||||||
|
}
|
||||||
|
infinite(); // RangeError: Maximum call stack size exceeded
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Hoisting
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Variable hoisting
|
||||||
|
console.log(a); // undefined (hoisted, not initialized)
|
||||||
|
var a = 5;
|
||||||
|
|
||||||
|
console.log(b); // ReferenceError (TDZ)
|
||||||
|
let b = 5;
|
||||||
|
|
||||||
|
// Function hoisting
|
||||||
|
sayHi(); // Works!
|
||||||
|
function sayHi() {
|
||||||
|
console.log("Hi!");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function expressions don't hoist
|
||||||
|
sayBye(); // TypeError
|
||||||
|
var sayBye = function () {
|
||||||
|
console.log("Bye!");
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 this Keyword
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Global context
|
||||||
|
console.log(this); // window (browser) or global (Node)
|
||||||
|
|
||||||
|
// Object method
|
||||||
|
const obj = {
|
||||||
|
name: "Alice",
|
||||||
|
greet() {
|
||||||
|
console.log(this.name); // "Alice"
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Arrow functions (lexical this)
|
||||||
|
const obj2 = {
|
||||||
|
name: "Bob",
|
||||||
|
greet: () => {
|
||||||
|
console.log(this.name); // undefined (inherits outer this)
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Explicit binding
|
||||||
|
function greet() {
|
||||||
|
console.log(this.name);
|
||||||
|
}
|
||||||
|
greet.call({ name: "Charlie" }); // "Charlie"
|
||||||
|
greet.apply({ name: "Diana" }); // "Diana"
|
||||||
|
const bound = greet.bind({ name: "Eve" });
|
||||||
|
bound(); // "Eve"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Event Loop & Async
|
||||||
|
|
||||||
|
### 4.1 Event Loop
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
console.log("1");
|
||||||
|
|
||||||
|
setTimeout(() => console.log("2"), 0);
|
||||||
|
|
||||||
|
Promise.resolve().then(() => console.log("3"));
|
||||||
|
|
||||||
|
console.log("4");
|
||||||
|
|
||||||
|
// Output: 1, 4, 3, 2
|
||||||
|
// Why? Microtasks (Promises) run before macrotasks (setTimeout)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Execution order**:
|
||||||
|
|
||||||
|
1. Synchronous code (call stack)
|
||||||
|
2. Microtasks (Promise callbacks, queueMicrotask)
|
||||||
|
3. Macrotasks (setTimeout, setInterval, I/O)
|
||||||
|
|
||||||
|
### 4.2 Callbacks
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Callback pattern
|
||||||
|
function fetchData(callback) {
|
||||||
|
setTimeout(() => {
|
||||||
|
callback(null, { data: "result" });
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error-first convention
|
||||||
|
fetchData((error, result) => {
|
||||||
|
if (error) {
|
||||||
|
console.error(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Callback hell (avoid this!)
|
||||||
|
getData((data) => {
|
||||||
|
processData(data, (processed) => {
|
||||||
|
saveData(processed, (saved) => {
|
||||||
|
notify(saved, () => {
|
||||||
|
// 😱 Pyramid of doom
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Promises
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Creating a Promise
|
||||||
|
const promise = new Promise((resolve, reject) => {
|
||||||
|
setTimeout(() => {
|
||||||
|
resolve("Success!");
|
||||||
|
// or: reject(new Error("Failed!"));
|
||||||
|
}, 1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Consuming Promises
|
||||||
|
promise
|
||||||
|
.then((result) => console.log(result))
|
||||||
|
.catch((error) => console.error(error))
|
||||||
|
.finally(() => console.log("Done"));
|
||||||
|
|
||||||
|
// Promise combinators
|
||||||
|
Promise.all([p1, p2, p3]); // All must succeed
|
||||||
|
Promise.allSettled([p1, p2]); // Wait for all, get status
|
||||||
|
Promise.race([p1, p2]); // First to settle
|
||||||
|
Promise.any([p1, p2]); // First to succeed
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 async/await
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function fetchUserData(userId) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/users/${userId}`);
|
||||||
|
if (!response.ok) throw new Error("Failed to fetch");
|
||||||
|
const user = await response.json();
|
||||||
|
return user;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error:", error);
|
||||||
|
throw error; // Re-throw for caller to handle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parallel execution
|
||||||
|
async function fetchAll() {
|
||||||
|
const [users, posts] = await Promise.all([
|
||||||
|
fetch("/api/users"),
|
||||||
|
fetch("/api/posts"),
|
||||||
|
]);
|
||||||
|
return { users, posts };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Functional Programming
|
||||||
|
|
||||||
|
### 5.1 Higher-Order Functions
|
||||||
|
|
||||||
|
Functions that take or return functions:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Takes a function
|
||||||
|
const numbers = [1, 2, 3];
|
||||||
|
const doubled = numbers.map((n) => n * 2); // [2, 4, 6]
|
||||||
|
|
||||||
|
// Returns a function
|
||||||
|
function multiply(a) {
|
||||||
|
return function (b) {
|
||||||
|
return a * b;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const double = multiply(2);
|
||||||
|
double(5); // 10
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Pure Functions
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Pure: same input → same output, no side effects
|
||||||
|
function add(a, b) {
|
||||||
|
return a + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Impure: modifies external state
|
||||||
|
let total = 0;
|
||||||
|
function addToTotal(value) {
|
||||||
|
total += value; // Side effect!
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Impure: depends on external state
|
||||||
|
function getDiscount(price) {
|
||||||
|
return price * globalDiscountRate; // External dependency
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 map, filter, reduce
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const users = [
|
||||||
|
{ name: "Alice", age: 25 },
|
||||||
|
{ name: "Bob", age: 30 },
|
||||||
|
{ name: "Charlie", age: 35 },
|
||||||
|
];
|
||||||
|
|
||||||
|
// map: transform each element
|
||||||
|
const names = users.map((u) => u.name);
|
||||||
|
// ["Alice", "Bob", "Charlie"]
|
||||||
|
|
||||||
|
// filter: keep elements matching condition
|
||||||
|
const adults = users.filter((u) => u.age >= 30);
|
||||||
|
// [{ name: "Bob", ... }, { name: "Charlie", ... }]
|
||||||
|
|
||||||
|
// reduce: accumulate into single value
|
||||||
|
const totalAge = users.reduce((sum, u) => sum + u.age, 0);
|
||||||
|
// 90
|
||||||
|
|
||||||
|
// Chaining
|
||||||
|
const result = users
|
||||||
|
.filter((u) => u.age >= 30)
|
||||||
|
.map((u) => u.name)
|
||||||
|
.join(", ");
|
||||||
|
// "Bob, Charlie"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 Currying & Composition
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Currying: transform f(a, b, c) into f(a)(b)(c)
|
||||||
|
const curry = (fn) => {
|
||||||
|
return function curried(...args) {
|
||||||
|
if (args.length >= fn.length) {
|
||||||
|
return fn.apply(this, args);
|
||||||
|
}
|
||||||
|
return (...moreArgs) => curried(...args, ...moreArgs);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const add = curry((a, b, c) => a + b + c);
|
||||||
|
add(1)(2)(3); // 6
|
||||||
|
add(1, 2)(3); // 6
|
||||||
|
add(1)(2, 3); // 6
|
||||||
|
|
||||||
|
// Composition: combine functions
|
||||||
|
const compose =
|
||||||
|
(...fns) =>
|
||||||
|
(x) =>
|
||||||
|
fns.reduceRight((acc, fn) => fn(acc), x);
|
||||||
|
|
||||||
|
const pipe =
|
||||||
|
(...fns) =>
|
||||||
|
(x) =>
|
||||||
|
fns.reduce((acc, fn) => fn(acc), x);
|
||||||
|
|
||||||
|
const addOne = (x) => x + 1;
|
||||||
|
const double = (x) => x * 2;
|
||||||
|
|
||||||
|
const addThenDouble = compose(double, addOne);
|
||||||
|
addThenDouble(5); // 12 = (5 + 1) * 2
|
||||||
|
|
||||||
|
const doubleThenAdd = pipe(double, addOne);
|
||||||
|
doubleThenAdd(5); // 11 = (5 * 2) + 1
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Objects & Prototypes
|
||||||
|
|
||||||
|
### 6.1 Prototypal Inheritance
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Prototype chain
|
||||||
|
const animal = {
|
||||||
|
speak() {
|
||||||
|
console.log("Some sound");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const dog = Object.create(animal);
|
||||||
|
dog.bark = function () {
|
||||||
|
console.log("Woof!");
|
||||||
|
};
|
||||||
|
|
||||||
|
dog.speak(); // "Some sound" (inherited)
|
||||||
|
dog.bark(); // "Woof!" (own method)
|
||||||
|
|
||||||
|
// ES6 Classes (syntactic sugar)
|
||||||
|
class Animal {
|
||||||
|
speak() {
|
||||||
|
console.log("Some sound");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Dog extends Animal {
|
||||||
|
bark() {
|
||||||
|
console.log("Woof!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Object Methods
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const obj = { a: 1, b: 2 };
|
||||||
|
|
||||||
|
// Keys, values, entries
|
||||||
|
Object.keys(obj); // ["a", "b"]
|
||||||
|
Object.values(obj); // [1, 2]
|
||||||
|
Object.entries(obj); // [["a", 1], ["b", 2]]
|
||||||
|
|
||||||
|
// Shallow copy
|
||||||
|
const copy = { ...obj };
|
||||||
|
const copy2 = Object.assign({}, obj);
|
||||||
|
|
||||||
|
// Freeze (immutable)
|
||||||
|
const frozen = Object.freeze({ x: 1 });
|
||||||
|
frozen.x = 2; // Silently fails (or throws in strict mode)
|
||||||
|
|
||||||
|
// Seal (no add/delete, can modify)
|
||||||
|
const sealed = Object.seal({ x: 1 });
|
||||||
|
sealed.x = 2; // OK
|
||||||
|
sealed.y = 3; // Fails
|
||||||
|
delete sealed.x; // Fails
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Modern JavaScript (ES6+)
|
||||||
|
|
||||||
|
### 7.1 Destructuring
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Array destructuring
|
||||||
|
const [first, second, ...rest] = [1, 2, 3, 4, 5];
|
||||||
|
// first = 1, second = 2, rest = [3, 4, 5]
|
||||||
|
|
||||||
|
// Object destructuring
|
||||||
|
const { name, age, city = "Unknown" } = { name: "Alice", age: 25 };
|
||||||
|
// name = "Alice", age = 25, city = "Unknown"
|
||||||
|
|
||||||
|
// Renaming
|
||||||
|
const { name: userName } = { name: "Bob" };
|
||||||
|
// userName = "Bob"
|
||||||
|
|
||||||
|
// Nested
|
||||||
|
const {
|
||||||
|
address: { street },
|
||||||
|
} = { address: { street: "123 Main" } };
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Spread & Rest
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Spread: expand iterable
|
||||||
|
const arr1 = [1, 2, 3];
|
||||||
|
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
|
const obj1 = { a: 1 };
|
||||||
|
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
|
||||||
|
|
||||||
|
// Rest: collect remaining
|
||||||
|
function sum(...numbers) {
|
||||||
|
return numbers.reduce((a, b) => a + b, 0);
|
||||||
|
}
|
||||||
|
sum(1, 2, 3, 4); // 10
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 Modules
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Named exports
|
||||||
|
export const PI = 3.14159;
|
||||||
|
export function square(x) {
|
||||||
|
return x * x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default export
|
||||||
|
export default class Calculator {}
|
||||||
|
|
||||||
|
// Importing
|
||||||
|
import Calculator, { PI, square } from "./math.js";
|
||||||
|
import * as math from "./math.js";
|
||||||
|
|
||||||
|
// Dynamic import
|
||||||
|
const module = await import("./dynamic.js");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.4 Optional Chaining & Nullish Coalescing
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Optional chaining (?.)
|
||||||
|
const user = { address: { city: "NYC" } };
|
||||||
|
const city = user?.address?.city; // "NYC"
|
||||||
|
const zip = user?.address?.zip; // undefined (no error)
|
||||||
|
const fn = user?.getName?.(); // undefined if no method
|
||||||
|
|
||||||
|
// Nullish coalescing (??)
|
||||||
|
const value = null ?? "default"; // "default"
|
||||||
|
const zero = 0 ?? "default"; // 0 (not nullish!)
|
||||||
|
const empty = "" ?? "default"; // "" (not nullish!)
|
||||||
|
|
||||||
|
// Compare with ||
|
||||||
|
const value2 = 0 || "default"; // "default" (0 is falsy)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Reference Card
|
||||||
|
|
||||||
|
| Concept | Key Point |
|
||||||
|
| :------------- | :-------------------------------- |
|
||||||
|
| `==` vs `===` | Always use `===` |
|
||||||
|
| `var` vs `let` | Prefer `let`/`const` |
|
||||||
|
| Closures | Function + lexical scope |
|
||||||
|
| `this` | Depends on how function is called |
|
||||||
|
| Event loop | Microtasks before macrotasks |
|
||||||
|
| Pure functions | Same input → same output |
|
||||||
|
| Prototypes | `__proto__` → prototype chain |
|
||||||
|
| `??` vs `\|\|` | `??` only checks null/undefined |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [33 JS Concepts](https://github.com/leonardomso/33-js-concepts)
|
||||||
|
- [JavaScript.info](https://javascript.info/)
|
||||||
|
- [MDN JavaScript Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide)
|
||||||
|
- [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS)
|
||||||
760
skills/llm-app-patterns/SKILL.md
Normal file
760
skills/llm-app-patterns/SKILL.md
Normal file
@@ -0,0 +1,760 @@
|
|||||||
|
---
|
||||||
|
name: llm-app-patterns
|
||||||
|
description: "Production-ready patterns for building LLM applications. Covers RAG pipelines, agent architectures, prompt IDEs, and LLMOps monitoring. Use when designing AI applications, implementing RAG, building agents, or setting up LLM observability."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🤖 LLM Application Patterns
|
||||||
|
|
||||||
|
> Production-ready patterns for building LLM applications, inspired by [Dify](https://github.com/langgenius/dify) and industry best practices.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Designing LLM-powered applications
|
||||||
|
- Implementing RAG (Retrieval-Augmented Generation)
|
||||||
|
- Building AI agents with tools
|
||||||
|
- Setting up LLMOps monitoring
|
||||||
|
- Choosing between agent architectures
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. RAG Pipeline Architecture
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
RAG (Retrieval-Augmented Generation) grounds LLM responses in your data.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||||
|
│ Ingest │────▶│ Retrieve │────▶│ Generate │
|
||||||
|
│ Documents │ │ Context │ │ Response │
|
||||||
|
└─────────────┘ └─────────────┘ └─────────────┘
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌─────────┐ ┌───────────┐ ┌───────────┐
|
||||||
|
│ Chunking│ │ Vector │ │ LLM │
|
||||||
|
│Embedding│ │ Search │ │ + Context│
|
||||||
|
└─────────┘ └───────────┘ └───────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 Document Ingestion
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Chunking strategies
|
||||||
|
class ChunkingStrategy:
|
||||||
|
# Fixed-size chunks (simple but may break context)
|
||||||
|
FIXED_SIZE = "fixed_size" # e.g., 512 tokens
|
||||||
|
|
||||||
|
# Semantic chunking (preserves meaning)
|
||||||
|
SEMANTIC = "semantic" # Split on paragraphs/sections
|
||||||
|
|
||||||
|
# Recursive splitting (tries multiple separators)
|
||||||
|
RECURSIVE = "recursive" # ["\n\n", "\n", " ", ""]
|
||||||
|
|
||||||
|
# Document-aware (respects structure)
|
||||||
|
DOCUMENT_AWARE = "document_aware" # Headers, lists, etc.
|
||||||
|
|
||||||
|
# Recommended settings
|
||||||
|
CHUNK_CONFIG = {
|
||||||
|
"chunk_size": 512, # tokens
|
||||||
|
"chunk_overlap": 50, # token overlap between chunks
|
||||||
|
"separators": ["\n\n", "\n", ". ", " "],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 Embedding & Storage
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Vector database selection
|
||||||
|
VECTOR_DB_OPTIONS = {
|
||||||
|
"pinecone": {
|
||||||
|
"use_case": "Production, managed service",
|
||||||
|
"scale": "Billions of vectors",
|
||||||
|
"features": ["Hybrid search", "Metadata filtering"]
|
||||||
|
},
|
||||||
|
"weaviate": {
|
||||||
|
"use_case": "Self-hosted, multi-modal",
|
||||||
|
"scale": "Millions of vectors",
|
||||||
|
"features": ["GraphQL API", "Modules"]
|
||||||
|
},
|
||||||
|
"chromadb": {
|
||||||
|
"use_case": "Development, prototyping",
|
||||||
|
"scale": "Thousands of vectors",
|
||||||
|
"features": ["Simple API", "In-memory option"]
|
||||||
|
},
|
||||||
|
"pgvector": {
|
||||||
|
"use_case": "Existing Postgres infrastructure",
|
||||||
|
"scale": "Millions of vectors",
|
||||||
|
"features": ["SQL integration", "ACID compliance"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Embedding model selection
|
||||||
|
EMBEDDING_MODELS = {
|
||||||
|
"openai/text-embedding-3-small": {
|
||||||
|
"dimensions": 1536,
|
||||||
|
"cost": "$0.02/1M tokens",
|
||||||
|
"quality": "Good for most use cases"
|
||||||
|
},
|
||||||
|
"openai/text-embedding-3-large": {
|
||||||
|
"dimensions": 3072,
|
||||||
|
"cost": "$0.13/1M tokens",
|
||||||
|
"quality": "Best for complex queries"
|
||||||
|
},
|
||||||
|
"local/bge-large": {
|
||||||
|
"dimensions": 1024,
|
||||||
|
"cost": "Free (compute only)",
|
||||||
|
"quality": "Comparable to OpenAI small"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 Retrieval Strategies
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Basic semantic search
|
||||||
|
def semantic_search(query: str, top_k: int = 5):
|
||||||
|
query_embedding = embed(query)
|
||||||
|
results = vector_db.similarity_search(
|
||||||
|
query_embedding,
|
||||||
|
top_k=top_k
|
||||||
|
)
|
||||||
|
return results
|
||||||
|
|
||||||
|
# Hybrid search (semantic + keyword)
|
||||||
|
def hybrid_search(query: str, top_k: int = 5, alpha: float = 0.5):
|
||||||
|
"""
|
||||||
|
alpha=1.0: Pure semantic
|
||||||
|
alpha=0.0: Pure keyword (BM25)
|
||||||
|
alpha=0.5: Balanced
|
||||||
|
"""
|
||||||
|
semantic_results = vector_db.similarity_search(query)
|
||||||
|
keyword_results = bm25_search(query)
|
||||||
|
|
||||||
|
# Reciprocal Rank Fusion
|
||||||
|
return rrf_merge(semantic_results, keyword_results, alpha)
|
||||||
|
|
||||||
|
# Multi-query retrieval
|
||||||
|
def multi_query_retrieval(query: str):
|
||||||
|
"""Generate multiple query variations for better recall"""
|
||||||
|
queries = llm.generate_query_variations(query, n=3)
|
||||||
|
all_results = []
|
||||||
|
for q in queries:
|
||||||
|
all_results.extend(semantic_search(q))
|
||||||
|
return deduplicate(all_results)
|
||||||
|
|
||||||
|
# Contextual compression
|
||||||
|
def compressed_retrieval(query: str):
|
||||||
|
"""Retrieve then compress to relevant parts only"""
|
||||||
|
docs = semantic_search(query, top_k=10)
|
||||||
|
compressed = llm.extract_relevant_parts(docs, query)
|
||||||
|
return compressed
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.4 Generation with Context
|
||||||
|
|
||||||
|
```python
|
||||||
|
RAG_PROMPT_TEMPLATE = """
|
||||||
|
Answer the user's question based ONLY on the following context.
|
||||||
|
If the context doesn't contain enough information, say "I don't have enough information to answer that."
|
||||||
|
|
||||||
|
Context:
|
||||||
|
{context}
|
||||||
|
|
||||||
|
Question: {question}
|
||||||
|
|
||||||
|
Answer:"""
|
||||||
|
|
||||||
|
def generate_with_rag(question: str):
|
||||||
|
# Retrieve
|
||||||
|
context_docs = hybrid_search(question, top_k=5)
|
||||||
|
context = "\n\n".join([doc.content for doc in context_docs])
|
||||||
|
|
||||||
|
# Generate
|
||||||
|
prompt = RAG_PROMPT_TEMPLATE.format(
|
||||||
|
context=context,
|
||||||
|
question=question
|
||||||
|
)
|
||||||
|
|
||||||
|
response = llm.generate(prompt)
|
||||||
|
|
||||||
|
# Return with citations
|
||||||
|
return {
|
||||||
|
"answer": response,
|
||||||
|
"sources": [doc.metadata for doc in context_docs]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Agent Architectures
|
||||||
|
|
||||||
|
### 2.1 ReAct Pattern (Reasoning + Acting)
|
||||||
|
|
||||||
|
```
|
||||||
|
Thought: I need to search for information about X
|
||||||
|
Action: search("X")
|
||||||
|
Observation: [search results]
|
||||||
|
Thought: Based on the results, I should...
|
||||||
|
Action: calculate(...)
|
||||||
|
Observation: [calculation result]
|
||||||
|
Thought: I now have enough information
|
||||||
|
Action: final_answer("The answer is...")
|
||||||
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
REACT_PROMPT = """
|
||||||
|
You are an AI assistant that can use tools to answer questions.
|
||||||
|
|
||||||
|
Available tools:
|
||||||
|
{tools_description}
|
||||||
|
|
||||||
|
Use this format:
|
||||||
|
Thought: [your reasoning about what to do next]
|
||||||
|
Action: [tool_name(arguments)]
|
||||||
|
Observation: [tool result - this will be filled in]
|
||||||
|
... (repeat Thought/Action/Observation as needed)
|
||||||
|
Thought: I have enough information to answer
|
||||||
|
Final Answer: [your final response]
|
||||||
|
|
||||||
|
Question: {question}
|
||||||
|
"""
|
||||||
|
|
||||||
|
class ReActAgent:
|
||||||
|
def __init__(self, tools: list, llm):
|
||||||
|
self.tools = {t.name: t for t in tools}
|
||||||
|
self.llm = llm
|
||||||
|
self.max_iterations = 10
|
||||||
|
|
||||||
|
def run(self, question: str) -> str:
|
||||||
|
prompt = REACT_PROMPT.format(
|
||||||
|
tools_description=self._format_tools(),
|
||||||
|
question=question
|
||||||
|
)
|
||||||
|
|
||||||
|
for _ in range(self.max_iterations):
|
||||||
|
response = self.llm.generate(prompt)
|
||||||
|
|
||||||
|
if "Final Answer:" in response:
|
||||||
|
return self._extract_final_answer(response)
|
||||||
|
|
||||||
|
action = self._parse_action(response)
|
||||||
|
observation = self._execute_tool(action)
|
||||||
|
prompt += f"\nObservation: {observation}\n"
|
||||||
|
|
||||||
|
return "Max iterations reached"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Function Calling Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Define tools as functions with schemas
|
||||||
|
TOOLS = [
|
||||||
|
{
|
||||||
|
"name": "search_web",
|
||||||
|
"description": "Search the web for current information",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"query": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Search query"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["query"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "calculate",
|
||||||
|
"description": "Perform mathematical calculations",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"expression": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Math expression to evaluate"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["expression"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
class FunctionCallingAgent:
|
||||||
|
def run(self, question: str) -> str:
|
||||||
|
messages = [{"role": "user", "content": question}]
|
||||||
|
|
||||||
|
while True:
|
||||||
|
response = self.llm.chat(
|
||||||
|
messages=messages,
|
||||||
|
tools=TOOLS,
|
||||||
|
tool_choice="auto"
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.tool_calls:
|
||||||
|
for tool_call in response.tool_calls:
|
||||||
|
result = self._execute_tool(
|
||||||
|
tool_call.name,
|
||||||
|
tool_call.arguments
|
||||||
|
)
|
||||||
|
messages.append({
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": tool_call.id,
|
||||||
|
"content": str(result)
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
return response.content
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Plan-and-Execute Pattern
|
||||||
|
|
||||||
|
```python
|
||||||
|
class PlanAndExecuteAgent:
|
||||||
|
"""
|
||||||
|
1. Create a plan (list of steps)
|
||||||
|
2. Execute each step
|
||||||
|
3. Replan if needed
|
||||||
|
"""
|
||||||
|
|
||||||
|
def run(self, task: str) -> str:
|
||||||
|
# Planning phase
|
||||||
|
plan = self.planner.create_plan(task)
|
||||||
|
# Returns: ["Step 1: ...", "Step 2: ...", ...]
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for step in plan:
|
||||||
|
# Execute each step
|
||||||
|
result = self.executor.execute(step, context=results)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
|
# Check if replan needed
|
||||||
|
if self._needs_replan(task, results):
|
||||||
|
new_plan = self.planner.replan(
|
||||||
|
task,
|
||||||
|
completed=results,
|
||||||
|
remaining=plan[len(results):]
|
||||||
|
)
|
||||||
|
plan = new_plan
|
||||||
|
|
||||||
|
# Synthesize final answer
|
||||||
|
return self.synthesizer.summarize(task, results)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 Multi-Agent Collaboration
|
||||||
|
|
||||||
|
```python
|
||||||
|
class AgentTeam:
|
||||||
|
"""
|
||||||
|
Specialized agents collaborating on complex tasks
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.agents = {
|
||||||
|
"researcher": ResearchAgent(),
|
||||||
|
"analyst": AnalystAgent(),
|
||||||
|
"writer": WriterAgent(),
|
||||||
|
"critic": CriticAgent()
|
||||||
|
}
|
||||||
|
self.coordinator = CoordinatorAgent()
|
||||||
|
|
||||||
|
def solve(self, task: str) -> str:
|
||||||
|
# Coordinator assigns subtasks
|
||||||
|
assignments = self.coordinator.decompose(task)
|
||||||
|
|
||||||
|
results = {}
|
||||||
|
for assignment in assignments:
|
||||||
|
agent = self.agents[assignment.agent]
|
||||||
|
result = agent.execute(
|
||||||
|
assignment.subtask,
|
||||||
|
context=results
|
||||||
|
)
|
||||||
|
results[assignment.id] = result
|
||||||
|
|
||||||
|
# Critic reviews
|
||||||
|
critique = self.agents["critic"].review(results)
|
||||||
|
|
||||||
|
if critique.needs_revision:
|
||||||
|
# Iterate with feedback
|
||||||
|
return self.solve_with_feedback(task, results, critique)
|
||||||
|
|
||||||
|
return self.coordinator.synthesize(results)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Prompt IDE Patterns
|
||||||
|
|
||||||
|
### 3.1 Prompt Templates with Variables
|
||||||
|
|
||||||
|
```python
|
||||||
|
class PromptTemplate:
|
||||||
|
def __init__(self, template: str, variables: list[str]):
|
||||||
|
self.template = template
|
||||||
|
self.variables = variables
|
||||||
|
|
||||||
|
def format(self, **kwargs) -> str:
|
||||||
|
# Validate all variables provided
|
||||||
|
missing = set(self.variables) - set(kwargs.keys())
|
||||||
|
if missing:
|
||||||
|
raise ValueError(f"Missing variables: {missing}")
|
||||||
|
|
||||||
|
return self.template.format(**kwargs)
|
||||||
|
|
||||||
|
def with_examples(self, examples: list[dict]) -> str:
|
||||||
|
"""Add few-shot examples"""
|
||||||
|
example_text = "\n\n".join([
|
||||||
|
f"Input: {ex['input']}\nOutput: {ex['output']}"
|
||||||
|
for ex in examples
|
||||||
|
])
|
||||||
|
return f"{example_text}\n\n{self.template}"
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
summarizer = PromptTemplate(
|
||||||
|
template="Summarize the following text in {style} style:\n\n{text}",
|
||||||
|
variables=["style", "text"]
|
||||||
|
)
|
||||||
|
|
||||||
|
prompt = summarizer.format(
|
||||||
|
style="professional",
|
||||||
|
text="Long article content..."
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Prompt Versioning & A/B Testing
|
||||||
|
|
||||||
|
```python
|
||||||
|
class PromptRegistry:
|
||||||
|
def __init__(self, db):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
def register(self, name: str, template: str, version: str):
|
||||||
|
"""Store prompt with version"""
|
||||||
|
self.db.save({
|
||||||
|
"name": name,
|
||||||
|
"template": template,
|
||||||
|
"version": version,
|
||||||
|
"created_at": datetime.now(),
|
||||||
|
"metrics": {}
|
||||||
|
})
|
||||||
|
|
||||||
|
def get(self, name: str, version: str = "latest") -> str:
|
||||||
|
"""Retrieve specific version"""
|
||||||
|
return self.db.get(name, version)
|
||||||
|
|
||||||
|
def ab_test(self, name: str, user_id: str) -> str:
|
||||||
|
"""Return variant based on user bucket"""
|
||||||
|
variants = self.db.get_all_versions(name)
|
||||||
|
bucket = hash(user_id) % len(variants)
|
||||||
|
return variants[bucket]
|
||||||
|
|
||||||
|
def record_outcome(self, prompt_id: str, outcome: dict):
|
||||||
|
"""Track prompt performance"""
|
||||||
|
self.db.update_metrics(prompt_id, outcome)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Prompt Chaining
|
||||||
|
|
||||||
|
```python
|
||||||
|
class PromptChain:
|
||||||
|
"""
|
||||||
|
Chain prompts together, passing output as input to next
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, steps: list[dict]):
|
||||||
|
self.steps = steps
|
||||||
|
|
||||||
|
def run(self, initial_input: str) -> dict:
|
||||||
|
context = {"input": initial_input}
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for step in self.steps:
|
||||||
|
prompt = step["prompt"].format(**context)
|
||||||
|
output = llm.generate(prompt)
|
||||||
|
|
||||||
|
# Parse output if needed
|
||||||
|
if step.get("parser"):
|
||||||
|
output = step["parser"](output)
|
||||||
|
|
||||||
|
context[step["output_key"]] = output
|
||||||
|
results.append({
|
||||||
|
"step": step["name"],
|
||||||
|
"output": output
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"final_output": context[self.steps[-1]["output_key"]],
|
||||||
|
"intermediate_results": results
|
||||||
|
}
|
||||||
|
|
||||||
|
# Example: Research → Analyze → Summarize
|
||||||
|
chain = PromptChain([
|
||||||
|
{
|
||||||
|
"name": "research",
|
||||||
|
"prompt": "Research the topic: {input}",
|
||||||
|
"output_key": "research"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "analyze",
|
||||||
|
"prompt": "Analyze these findings:\n{research}",
|
||||||
|
"output_key": "analysis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "summarize",
|
||||||
|
"prompt": "Summarize this analysis in 3 bullet points:\n{analysis}",
|
||||||
|
"output_key": "summary"
|
||||||
|
}
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. LLMOps & Observability
|
||||||
|
|
||||||
|
### 4.1 Metrics to Track
|
||||||
|
|
||||||
|
```python
|
||||||
|
LLM_METRICS = {
|
||||||
|
# Performance
|
||||||
|
"latency_p50": "50th percentile response time",
|
||||||
|
"latency_p99": "99th percentile response time",
|
||||||
|
"tokens_per_second": "Generation speed",
|
||||||
|
|
||||||
|
# Quality
|
||||||
|
"user_satisfaction": "Thumbs up/down ratio",
|
||||||
|
"task_completion": "% tasks completed successfully",
|
||||||
|
"hallucination_rate": "% responses with factual errors",
|
||||||
|
|
||||||
|
# Cost
|
||||||
|
"cost_per_request": "Average $ per API call",
|
||||||
|
"tokens_per_request": "Average tokens used",
|
||||||
|
"cache_hit_rate": "% requests served from cache",
|
||||||
|
|
||||||
|
# Reliability
|
||||||
|
"error_rate": "% failed requests",
|
||||||
|
"timeout_rate": "% requests that timed out",
|
||||||
|
"retry_rate": "% requests needing retry"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Logging & Tracing
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
from opentelemetry import trace
|
||||||
|
|
||||||
|
tracer = trace.get_tracer(__name__)
|
||||||
|
|
||||||
|
class LLMLogger:
|
||||||
|
def log_request(self, request_id: str, data: dict):
|
||||||
|
"""Log LLM request for debugging and analysis"""
|
||||||
|
log_entry = {
|
||||||
|
"request_id": request_id,
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"model": data["model"],
|
||||||
|
"prompt": data["prompt"][:500], # Truncate for storage
|
||||||
|
"prompt_tokens": data["prompt_tokens"],
|
||||||
|
"temperature": data.get("temperature", 1.0),
|
||||||
|
"user_id": data.get("user_id"),
|
||||||
|
}
|
||||||
|
logging.info(f"LLM_REQUEST: {json.dumps(log_entry)}")
|
||||||
|
|
||||||
|
def log_response(self, request_id: str, data: dict):
|
||||||
|
"""Log LLM response"""
|
||||||
|
log_entry = {
|
||||||
|
"request_id": request_id,
|
||||||
|
"completion_tokens": data["completion_tokens"],
|
||||||
|
"total_tokens": data["total_tokens"],
|
||||||
|
"latency_ms": data["latency_ms"],
|
||||||
|
"finish_reason": data["finish_reason"],
|
||||||
|
"cost_usd": self._calculate_cost(data),
|
||||||
|
}
|
||||||
|
logging.info(f"LLM_RESPONSE: {json.dumps(log_entry)}")
|
||||||
|
|
||||||
|
# Distributed tracing
|
||||||
|
@tracer.start_as_current_span("llm_call")
|
||||||
|
def call_llm(prompt: str) -> str:
|
||||||
|
span = trace.get_current_span()
|
||||||
|
span.set_attribute("prompt.length", len(prompt))
|
||||||
|
|
||||||
|
response = llm.generate(prompt)
|
||||||
|
|
||||||
|
span.set_attribute("response.length", len(response))
|
||||||
|
span.set_attribute("tokens.total", response.usage.total_tokens)
|
||||||
|
|
||||||
|
return response.content
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Evaluation Framework
|
||||||
|
|
||||||
|
```python
|
||||||
|
class LLMEvaluator:
|
||||||
|
"""
|
||||||
|
Evaluate LLM outputs for quality
|
||||||
|
"""
|
||||||
|
|
||||||
|
def evaluate_response(self,
|
||||||
|
question: str,
|
||||||
|
response: str,
|
||||||
|
ground_truth: str = None) -> dict:
|
||||||
|
scores = {}
|
||||||
|
|
||||||
|
# Relevance: Does it answer the question?
|
||||||
|
scores["relevance"] = self._score_relevance(question, response)
|
||||||
|
|
||||||
|
# Coherence: Is it well-structured?
|
||||||
|
scores["coherence"] = self._score_coherence(response)
|
||||||
|
|
||||||
|
# Groundedness: Is it based on provided context?
|
||||||
|
scores["groundedness"] = self._score_groundedness(response)
|
||||||
|
|
||||||
|
# Accuracy: Does it match ground truth?
|
||||||
|
if ground_truth:
|
||||||
|
scores["accuracy"] = self._score_accuracy(response, ground_truth)
|
||||||
|
|
||||||
|
# Harmfulness: Is it safe?
|
||||||
|
scores["safety"] = self._score_safety(response)
|
||||||
|
|
||||||
|
return scores
|
||||||
|
|
||||||
|
def run_benchmark(self, test_cases: list[dict]) -> dict:
|
||||||
|
"""Run evaluation on test set"""
|
||||||
|
results = []
|
||||||
|
for case in test_cases:
|
||||||
|
response = llm.generate(case["prompt"])
|
||||||
|
scores = self.evaluate_response(
|
||||||
|
question=case["prompt"],
|
||||||
|
response=response,
|
||||||
|
ground_truth=case.get("expected")
|
||||||
|
)
|
||||||
|
results.append(scores)
|
||||||
|
|
||||||
|
return self._aggregate_scores(results)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Production Patterns
|
||||||
|
|
||||||
|
### 5.1 Caching Strategy
|
||||||
|
|
||||||
|
```python
|
||||||
|
import hashlib
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
class LLMCache:
|
||||||
|
def __init__(self, redis_client, ttl_seconds=3600):
|
||||||
|
self.redis = redis_client
|
||||||
|
self.ttl = ttl_seconds
|
||||||
|
|
||||||
|
def _cache_key(self, prompt: str, model: str, **kwargs) -> str:
|
||||||
|
"""Generate deterministic cache key"""
|
||||||
|
content = f"{model}:{prompt}:{json.dumps(kwargs, sort_keys=True)}"
|
||||||
|
return hashlib.sha256(content.encode()).hexdigest()
|
||||||
|
|
||||||
|
def get_or_generate(self, prompt: str, model: str, **kwargs) -> str:
|
||||||
|
key = self._cache_key(prompt, model, **kwargs)
|
||||||
|
|
||||||
|
# Check cache
|
||||||
|
cached = self.redis.get(key)
|
||||||
|
if cached:
|
||||||
|
return cached.decode()
|
||||||
|
|
||||||
|
# Generate
|
||||||
|
response = llm.generate(prompt, model=model, **kwargs)
|
||||||
|
|
||||||
|
# Cache (only cache deterministic outputs)
|
||||||
|
if kwargs.get("temperature", 1.0) == 0:
|
||||||
|
self.redis.setex(key, self.ttl, response)
|
||||||
|
|
||||||
|
return response
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Rate Limiting & Retry
|
||||||
|
|
||||||
|
```python
|
||||||
|
import time
|
||||||
|
from tenacity import retry, wait_exponential, stop_after_attempt
|
||||||
|
|
||||||
|
class RateLimiter:
|
||||||
|
def __init__(self, requests_per_minute: int):
|
||||||
|
self.rpm = requests_per_minute
|
||||||
|
self.timestamps = []
|
||||||
|
|
||||||
|
def acquire(self):
|
||||||
|
"""Wait if rate limit would be exceeded"""
|
||||||
|
now = time.time()
|
||||||
|
|
||||||
|
# Remove old timestamps
|
||||||
|
self.timestamps = [t for t in self.timestamps if now - t < 60]
|
||||||
|
|
||||||
|
if len(self.timestamps) >= self.rpm:
|
||||||
|
sleep_time = 60 - (now - self.timestamps[0])
|
||||||
|
time.sleep(sleep_time)
|
||||||
|
|
||||||
|
self.timestamps.append(time.time())
|
||||||
|
|
||||||
|
# Retry with exponential backoff
|
||||||
|
@retry(
|
||||||
|
wait=wait_exponential(multiplier=1, min=4, max=60),
|
||||||
|
stop=stop_after_attempt(5)
|
||||||
|
)
|
||||||
|
def call_llm_with_retry(prompt: str) -> str:
|
||||||
|
try:
|
||||||
|
return llm.generate(prompt)
|
||||||
|
except RateLimitError:
|
||||||
|
raise # Will trigger retry
|
||||||
|
except APIError as e:
|
||||||
|
if e.status_code >= 500:
|
||||||
|
raise # Retry server errors
|
||||||
|
raise # Don't retry client errors
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 Fallback Strategy
|
||||||
|
|
||||||
|
```python
|
||||||
|
class LLMWithFallback:
|
||||||
|
def __init__(self, primary: str, fallbacks: list[str]):
|
||||||
|
self.primary = primary
|
||||||
|
self.fallbacks = fallbacks
|
||||||
|
|
||||||
|
def generate(self, prompt: str, **kwargs) -> str:
|
||||||
|
models = [self.primary] + self.fallbacks
|
||||||
|
|
||||||
|
for model in models:
|
||||||
|
try:
|
||||||
|
return llm.generate(prompt, model=model, **kwargs)
|
||||||
|
except (RateLimitError, APIError) as e:
|
||||||
|
logging.warning(f"Model {model} failed: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
raise AllModelsFailedError("All models exhausted")
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
llm_client = LLMWithFallback(
|
||||||
|
primary="gpt-4-turbo",
|
||||||
|
fallbacks=["gpt-3.5-turbo", "claude-3-sonnet"]
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Decision Matrix
|
||||||
|
|
||||||
|
| Pattern | Use When | Complexity | Cost |
|
||||||
|
| :------------------- | :--------------- | :--------- | :-------- |
|
||||||
|
| **Simple RAG** | FAQ, docs search | Low | Low |
|
||||||
|
| **Hybrid RAG** | Mixed queries | Medium | Medium |
|
||||||
|
| **ReAct Agent** | Multi-step tasks | Medium | Medium |
|
||||||
|
| **Function Calling** | Structured tools | Low | Low |
|
||||||
|
| **Plan-Execute** | Complex tasks | High | High |
|
||||||
|
| **Multi-Agent** | Research tasks | Very High | Very High |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [Dify Platform](https://github.com/langgenius/dify)
|
||||||
|
- [LangChain Docs](https://python.langchain.com/)
|
||||||
|
- [LlamaIndex](https://www.llamaindex.ai/)
|
||||||
|
- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)
|
||||||
322
skills/prompt-library/SKILL.md
Normal file
322
skills/prompt-library/SKILL.md
Normal file
@@ -0,0 +1,322 @@
|
|||||||
|
---
|
||||||
|
name: prompt-library
|
||||||
|
description: "Curated collection of high-quality prompts for various use cases. Includes role-based prompts, task-specific templates, and prompt refinement techniques. Use when user needs prompt templates, role-play prompts, or ready-to-use prompt examples for coding, writing, analysis, or creative tasks."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 📝 Prompt Library
|
||||||
|
|
||||||
|
> A comprehensive collection of battle-tested prompts inspired by [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) and community best practices.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when the user:
|
||||||
|
|
||||||
|
- Needs ready-to-use prompt templates
|
||||||
|
- Wants role-based prompts (act as X)
|
||||||
|
- Asks for prompt examples or inspiration
|
||||||
|
- Needs task-specific prompt patterns
|
||||||
|
- Wants to improve their prompting
|
||||||
|
|
||||||
|
## Prompt Categories
|
||||||
|
|
||||||
|
### 🎭 Role-Based Prompts
|
||||||
|
|
||||||
|
#### Expert Developer
|
||||||
|
|
||||||
|
```
|
||||||
|
Act as an expert software developer with 15+ years of experience. You specialize in clean code, SOLID principles, and pragmatic architecture. When reviewing code:
|
||||||
|
1. Identify bugs and potential issues
|
||||||
|
2. Suggest performance improvements
|
||||||
|
3. Recommend better patterns
|
||||||
|
4. Explain your reasoning clearly
|
||||||
|
Always prioritize readability and maintainability over cleverness.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Code Reviewer
|
||||||
|
|
||||||
|
```
|
||||||
|
Act as a senior code reviewer. Your role is to:
|
||||||
|
1. Check for bugs, edge cases, and error handling
|
||||||
|
2. Evaluate code structure and organization
|
||||||
|
3. Assess naming conventions and readability
|
||||||
|
4. Identify potential security issues
|
||||||
|
5. Suggest improvements with specific examples
|
||||||
|
|
||||||
|
Format your review as:
|
||||||
|
🔴 Critical Issues (must fix)
|
||||||
|
🟡 Suggestions (should consider)
|
||||||
|
🟢 Praise (what's done well)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Technical Writer
|
||||||
|
|
||||||
|
```
|
||||||
|
Act as a technical documentation expert. Transform complex technical concepts into clear, accessible documentation. Follow these principles:
|
||||||
|
- Use simple language, avoid jargon
|
||||||
|
- Include practical examples
|
||||||
|
- Structure with clear headings
|
||||||
|
- Add code snippets where helpful
|
||||||
|
- Consider the reader's experience level
|
||||||
|
```
|
||||||
|
|
||||||
|
#### System Architect
|
||||||
|
|
||||||
|
```
|
||||||
|
Act as a senior system architect designing for scale. Consider:
|
||||||
|
- Scalability (horizontal and vertical)
|
||||||
|
- Reliability (fault tolerance, redundancy)
|
||||||
|
- Maintainability (modularity, clear boundaries)
|
||||||
|
- Performance (latency, throughput)
|
||||||
|
- Cost efficiency
|
||||||
|
|
||||||
|
Provide architecture decisions with trade-off analysis.
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🛠️ Task-Specific Prompts
|
||||||
|
|
||||||
|
#### Debug This Code
|
||||||
|
|
||||||
|
```
|
||||||
|
Debug the following code. Your analysis should include:
|
||||||
|
|
||||||
|
1. **Problem Identification**: What exactly is failing?
|
||||||
|
2. **Root Cause**: Why is it failing?
|
||||||
|
3. **Fix**: Provide corrected code
|
||||||
|
4. **Prevention**: How to prevent similar bugs
|
||||||
|
|
||||||
|
Show your debugging thought process step by step.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Explain Like I'm 5 (ELI5)
|
||||||
|
|
||||||
|
```
|
||||||
|
Explain [CONCEPT] as if I'm 5 years old. Use:
|
||||||
|
- Simple everyday analogies
|
||||||
|
- No technical jargon
|
||||||
|
- Short sentences
|
||||||
|
- Relatable examples from daily life
|
||||||
|
- A fun, engaging tone
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Code Refactoring
|
||||||
|
|
||||||
|
```
|
||||||
|
Refactor this code following these priorities:
|
||||||
|
1. Readability first
|
||||||
|
2. Remove duplication (DRY)
|
||||||
|
3. Single responsibility per function
|
||||||
|
4. Meaningful names
|
||||||
|
5. Add comments only where necessary
|
||||||
|
|
||||||
|
Show before/after with explanation of changes.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Write Tests
|
||||||
|
|
||||||
|
```
|
||||||
|
Write comprehensive tests for this code:
|
||||||
|
1. Happy path scenarios
|
||||||
|
2. Edge cases
|
||||||
|
3. Error conditions
|
||||||
|
4. Boundary values
|
||||||
|
|
||||||
|
Use [FRAMEWORK] testing conventions. Include:
|
||||||
|
- Descriptive test names
|
||||||
|
- Arrange-Act-Assert pattern
|
||||||
|
- Mocking where appropriate
|
||||||
|
```
|
||||||
|
|
||||||
|
#### API Documentation
|
||||||
|
|
||||||
|
```
|
||||||
|
Generate API documentation for this endpoint including:
|
||||||
|
- Endpoint URL and method
|
||||||
|
- Request parameters (path, query, body)
|
||||||
|
- Request/response examples
|
||||||
|
- Error codes and meanings
|
||||||
|
- Authentication requirements
|
||||||
|
- Rate limits if applicable
|
||||||
|
|
||||||
|
Format as OpenAPI/Swagger or Markdown.
|
||||||
|
```
|
||||||
|
|
||||||
|
### 📊 Analysis Prompts
|
||||||
|
|
||||||
|
#### Code Complexity Analysis
|
||||||
|
|
||||||
|
```
|
||||||
|
Analyze the complexity of this codebase:
|
||||||
|
|
||||||
|
1. **Cyclomatic Complexity**: Identify complex functions
|
||||||
|
2. **Coupling**: Find tightly coupled components
|
||||||
|
3. **Cohesion**: Assess module cohesion
|
||||||
|
4. **Dependencies**: Map critical dependencies
|
||||||
|
5. **Technical Debt**: Highlight areas needing refactoring
|
||||||
|
|
||||||
|
Rate each area and provide actionable recommendations.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Performance Analysis
|
||||||
|
|
||||||
|
```
|
||||||
|
Analyze this code for performance issues:
|
||||||
|
|
||||||
|
1. **Time Complexity**: Big O analysis
|
||||||
|
2. **Space Complexity**: Memory usage patterns
|
||||||
|
3. **I/O Bottlenecks**: Database, network, disk
|
||||||
|
4. **Algorithmic Issues**: Inefficient patterns
|
||||||
|
5. **Quick Wins**: Easy optimizations
|
||||||
|
|
||||||
|
Prioritize findings by impact.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Security Review
|
||||||
|
|
||||||
|
```
|
||||||
|
Perform a security review of this code:
|
||||||
|
|
||||||
|
1. **Input Validation**: Check all inputs
|
||||||
|
2. **Authentication/Authorization**: Access control
|
||||||
|
3. **Data Protection**: Sensitive data handling
|
||||||
|
4. **Injection Vulnerabilities**: SQL, XSS, etc.
|
||||||
|
5. **Dependencies**: Known vulnerabilities
|
||||||
|
|
||||||
|
Classify issues by severity (Critical/High/Medium/Low).
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🎨 Creative Prompts
|
||||||
|
|
||||||
|
#### Brainstorm Features
|
||||||
|
|
||||||
|
```
|
||||||
|
Brainstorm features for [PRODUCT]:
|
||||||
|
|
||||||
|
For each feature, provide:
|
||||||
|
- Name and one-line description
|
||||||
|
- User value proposition
|
||||||
|
- Implementation complexity (Low/Med/High)
|
||||||
|
- Dependencies on other features
|
||||||
|
|
||||||
|
Generate 10 ideas, then rank top 3 by impact/effort ratio.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Name Generator
|
||||||
|
|
||||||
|
```
|
||||||
|
Generate names for [PROJECT/FEATURE]:
|
||||||
|
|
||||||
|
Provide 10 options in these categories:
|
||||||
|
- Descriptive (what it does)
|
||||||
|
- Evocative (how it feels)
|
||||||
|
- Acronyms (memorable abbreviations)
|
||||||
|
- Metaphorical (analogies)
|
||||||
|
|
||||||
|
For each, explain the reasoning and check domain availability patterns.
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔄 Transformation Prompts
|
||||||
|
|
||||||
|
#### Migrate Code
|
||||||
|
|
||||||
|
```
|
||||||
|
Migrate this code from [SOURCE] to [TARGET]:
|
||||||
|
|
||||||
|
1. Identify equivalent constructs
|
||||||
|
2. Handle incompatible features
|
||||||
|
3. Preserve functionality exactly
|
||||||
|
4. Follow target language idioms
|
||||||
|
5. Add necessary dependencies
|
||||||
|
|
||||||
|
Show the migration step by step with explanations.
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Convert Format
|
||||||
|
|
||||||
|
```
|
||||||
|
Convert this [SOURCE_FORMAT] to [TARGET_FORMAT]:
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
- Preserve all data
|
||||||
|
- Use idiomatic target format
|
||||||
|
- Handle edge cases
|
||||||
|
- Validate the output
|
||||||
|
- Provide sample verification
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prompt Engineering Techniques
|
||||||
|
|
||||||
|
### Chain of Thought (CoT)
|
||||||
|
|
||||||
|
```
|
||||||
|
Let's solve this step by step:
|
||||||
|
1. First, I'll understand the problem
|
||||||
|
2. Then, I'll identify the key components
|
||||||
|
3. Next, I'll work through the logic
|
||||||
|
4. Finally, I'll verify the solution
|
||||||
|
|
||||||
|
[Your question here]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Few-Shot Learning
|
||||||
|
|
||||||
|
```
|
||||||
|
Here are some examples of the task:
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
Input: [example input 1]
|
||||||
|
Output: [example output 1]
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
Input: [example input 2]
|
||||||
|
Output: [example output 2]
|
||||||
|
|
||||||
|
Now complete this:
|
||||||
|
Input: [actual input]
|
||||||
|
Output:
|
||||||
|
```
|
||||||
|
|
||||||
|
### Persona Pattern
|
||||||
|
|
||||||
|
```
|
||||||
|
You are [PERSONA] with [TRAITS].
|
||||||
|
Your communication style is [STYLE].
|
||||||
|
You prioritize [VALUES].
|
||||||
|
|
||||||
|
When responding:
|
||||||
|
- [Behavior 1]
|
||||||
|
- [Behavior 2]
|
||||||
|
- [Behavior 3]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Structured Output
|
||||||
|
|
||||||
|
```
|
||||||
|
Respond in the following JSON format:
|
||||||
|
{
|
||||||
|
"analysis": "your analysis here",
|
||||||
|
"recommendations": ["rec1", "rec2"],
|
||||||
|
"confidence": 0.0-1.0,
|
||||||
|
"caveats": ["caveat1"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prompt Improvement Checklist
|
||||||
|
|
||||||
|
When crafting prompts, ensure:
|
||||||
|
|
||||||
|
- [ ] **Clear objective**: What exactly do you want?
|
||||||
|
- [ ] **Context provided**: Background information included?
|
||||||
|
- [ ] **Format specified**: How should output be structured?
|
||||||
|
- [ ] **Examples given**: Are there reference examples?
|
||||||
|
- [ ] **Constraints defined**: Any limitations or requirements?
|
||||||
|
- [ ] **Success criteria**: How do you measure good output?
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
- [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)
|
||||||
|
- [prompts.chat](https://prompts.chat)
|
||||||
|
- [Learn Prompting](https://learnprompting.org/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> 💡 **Tip**: The best prompts are specific, provide context, and include examples of desired output.
|
||||||
@@ -1,11 +1,95 @@
|
|||||||
---
|
---
|
||||||
name: ui-ux-pro-max
|
name: ui-ux-pro-max
|
||||||
description: "UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
|
description: "UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 9 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient. Integrations: shadcn/ui MCP for component search and examples."
|
||||||
---
|
---
|
||||||
|
|
||||||
# UI/UX Pro Max - Design Intelligence
|
# UI/UX Pro Max - Design Intelligence
|
||||||
|
|
||||||
Searchable database of UI styles, color palettes, font pairings, chart types, product recommendations, UX guidelines, and stack-specific best practices.
|
Comprehensive design guide for web and mobile applications. Contains 50+ styles, 97 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types across 9 technology stacks. Searchable database with priority-based recommendations.
|
||||||
|
|
||||||
|
## When to Apply
|
||||||
|
|
||||||
|
Reference these guidelines when:
|
||||||
|
- Designing new UI components or pages
|
||||||
|
- Choosing color palettes and typography
|
||||||
|
- Reviewing code for UX issues
|
||||||
|
- Building landing pages or dashboards
|
||||||
|
- Implementing accessibility requirements
|
||||||
|
|
||||||
|
## Rule Categories by Priority
|
||||||
|
|
||||||
|
| Priority | Category | Impact | Domain |
|
||||||
|
|----------|----------|--------|--------|
|
||||||
|
| 1 | Accessibility | CRITICAL | `ux` |
|
||||||
|
| 2 | Touch & Interaction | CRITICAL | `ux` |
|
||||||
|
| 3 | Performance | HIGH | `ux` |
|
||||||
|
| 4 | Layout & Responsive | HIGH | `ux` |
|
||||||
|
| 5 | Typography & Color | MEDIUM | `typography`, `color` |
|
||||||
|
| 6 | Animation | MEDIUM | `ux` |
|
||||||
|
| 7 | Style Selection | MEDIUM | `style`, `product` |
|
||||||
|
| 8 | Charts & Data | LOW | `chart` |
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
### 1. Accessibility (CRITICAL)
|
||||||
|
|
||||||
|
- `color-contrast` - Minimum 4.5:1 ratio for normal text
|
||||||
|
- `focus-states` - Visible focus rings on interactive elements
|
||||||
|
- `alt-text` - Descriptive alt text for meaningful images
|
||||||
|
- `aria-labels` - aria-label for icon-only buttons
|
||||||
|
- `keyboard-nav` - Tab order matches visual order
|
||||||
|
- `form-labels` - Use label with for attribute
|
||||||
|
|
||||||
|
### 2. Touch & Interaction (CRITICAL)
|
||||||
|
|
||||||
|
- `touch-target-size` - Minimum 44x44px touch targets
|
||||||
|
- `hover-vs-tap` - Use click/tap for primary interactions
|
||||||
|
- `loading-buttons` - Disable button during async operations
|
||||||
|
- `error-feedback` - Clear error messages near problem
|
||||||
|
- `cursor-pointer` - Add cursor-pointer to clickable elements
|
||||||
|
|
||||||
|
### 3. Performance (HIGH)
|
||||||
|
|
||||||
|
- `image-optimization` - Use WebP, srcset, lazy loading
|
||||||
|
- `reduced-motion` - Check prefers-reduced-motion
|
||||||
|
- `content-jumping` - Reserve space for async content
|
||||||
|
|
||||||
|
### 4. Layout & Responsive (HIGH)
|
||||||
|
|
||||||
|
- `viewport-meta` - width=device-width initial-scale=1
|
||||||
|
- `readable-font-size` - Minimum 16px body text on mobile
|
||||||
|
- `horizontal-scroll` - Ensure content fits viewport width
|
||||||
|
- `z-index-management` - Define z-index scale (10, 20, 30, 50)
|
||||||
|
|
||||||
|
### 5. Typography & Color (MEDIUM)
|
||||||
|
|
||||||
|
- `line-height` - Use 1.5-1.75 for body text
|
||||||
|
- `line-length` - Limit to 65-75 characters per line
|
||||||
|
- `font-pairing` - Match heading/body font personalities
|
||||||
|
|
||||||
|
### 6. Animation (MEDIUM)
|
||||||
|
|
||||||
|
- `duration-timing` - Use 150-300ms for micro-interactions
|
||||||
|
- `transform-performance` - Use transform/opacity, not width/height
|
||||||
|
- `loading-states` - Skeleton screens or spinners
|
||||||
|
|
||||||
|
### 7. Style Selection (MEDIUM)
|
||||||
|
|
||||||
|
- `style-match` - Match style to product type
|
||||||
|
- `consistency` - Use same style across all pages
|
||||||
|
- `no-emoji-icons` - Use SVG icons, not emojis
|
||||||
|
|
||||||
|
### 8. Charts & Data (LOW)
|
||||||
|
|
||||||
|
- `chart-type` - Match chart type to data type
|
||||||
|
- `color-guidance` - Use accessible color palettes
|
||||||
|
- `data-table` - Provide table alternative for accessibility
|
||||||
|
|
||||||
|
## How to Use
|
||||||
|
|
||||||
|
Search specific domains using the CLI tool below.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
@@ -46,34 +130,52 @@ Extract key information from user request:
|
|||||||
- **Industry**: healthcare, fintech, gaming, education, etc.
|
- **Industry**: healthcare, fintech, gaming, education, etc.
|
||||||
- **Stack**: React, Vue, Next.js, or default to `html-tailwind`
|
- **Stack**: React, Vue, Next.js, or default to `html-tailwind`
|
||||||
|
|
||||||
### Step 2: Search Relevant Domains
|
### Step 2: Generate Design System (REQUIRED)
|
||||||
|
|
||||||
Use `search.py` multiple times to gather comprehensive information. Search until you have enough context.
|
**Always start with `--design-system`** to get comprehensive recommendations with reasoning:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<product_type> <industry> <keywords>" --design-system [-p "Project Name"]
|
||||||
|
```
|
||||||
|
|
||||||
|
This command:
|
||||||
|
1. Searches 5 domains in parallel (product, style, color, landing, typography)
|
||||||
|
2. Applies reasoning rules from `ui-reasoning.csv` to select best matches
|
||||||
|
3. Returns complete design system: pattern, style, colors, typography, effects
|
||||||
|
4. Includes anti-patterns to avoid
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```bash
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --design-system -p "Serenity Spa"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Supplement with Detailed Searches (as needed)
|
||||||
|
|
||||||
|
After getting the design system, use domain searches to get additional details:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]
|
||||||
```
|
```
|
||||||
|
|
||||||
**Recommended search order:**
|
**When to use detailed searches:**
|
||||||
|
|
||||||
1. **Product** - Get style recommendations for product type
|
| Need | Domain | Example |
|
||||||
2. **Style** - Get detailed style guide (colors, effects, frameworks)
|
|------|--------|---------|
|
||||||
3. **Typography** - Get font pairings with Google Fonts imports
|
| More style options | `style` | `--domain style "glassmorphism dark"` |
|
||||||
4. **Color** - Get color palette (Primary, Secondary, CTA, Background, Text, Border)
|
| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` |
|
||||||
5. **Landing** - Get page structure (if landing page)
|
| UX best practices | `ux` | `--domain ux "animation accessibility"` |
|
||||||
6. **Chart** - Get chart recommendations (if dashboard/analytics)
|
| Alternative fonts | `typography` | `--domain typography "elegant luxury"` |
|
||||||
7. **UX** - Get best practices and anti-patterns
|
| Landing structure | `landing` | `--domain landing "hero social-proof"` |
|
||||||
8. **Stack** - Get stack-specific guidelines (default: html-tailwind)
|
|
||||||
|
|
||||||
### Step 3: Stack Guidelines (Default: html-tailwind)
|
### Step 4: Stack Guidelines (Default: html-tailwind)
|
||||||
|
|
||||||
If user doesn't specify a stack, **default to `html-tailwind`**.
|
Get implementation-specific best practices. If user doesn't specify a stack, **default to `html-tailwind`**.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack html-tailwind
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack html-tailwind
|
||||||
```
|
```
|
||||||
|
|
||||||
Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`
|
Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`, `shadcn`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -90,6 +192,8 @@ Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`
|
|||||||
| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof |
|
| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof |
|
||||||
| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie |
|
| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie |
|
||||||
| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading |
|
| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading |
|
||||||
|
| `react` | React/Next.js performance | waterfall, bundle, suspense, memo, rerender, cache |
|
||||||
|
| `web` | Web interface guidelines | aria, focus, keyboard, semantic, virtualize |
|
||||||
| `prompt` | AI prompts, CSS keywords | (style name) |
|
| `prompt` | AI prompts, CSS keywords | (style name) |
|
||||||
|
|
||||||
### Available Stacks
|
### Available Stacks
|
||||||
@@ -104,6 +208,7 @@ Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`
|
|||||||
| `swiftui` | Views, State, Navigation, Animation |
|
| `swiftui` | Views, State, Navigation, Animation |
|
||||||
| `react-native` | Components, Navigation, Lists |
|
| `react-native` | Components, Navigation, Lists |
|
||||||
| `flutter` | Widgets, State, Layout, Theming |
|
| `flutter` | Widgets, State, Layout, Theming |
|
||||||
|
| `shadcn` | shadcn/ui components, theming, forms, patterns |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -111,33 +216,51 @@ Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`
|
|||||||
|
|
||||||
**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp"
|
**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp"
|
||||||
|
|
||||||
**AI should:**
|
### Step 1: Analyze Requirements
|
||||||
|
- Product type: Beauty/Spa service
|
||||||
|
- Style keywords: elegant, professional, soft
|
||||||
|
- Industry: Beauty/Wellness
|
||||||
|
- Stack: html-tailwind (default)
|
||||||
|
|
||||||
|
### Step 2: Generate Design System (REQUIRED)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. Search product type
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service elegant" --design-system -p "Serenity Spa"
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --domain product
|
|
||||||
|
|
||||||
# 2. Search style (based on industry: beauty, elegant)
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant minimal soft" --domain style
|
|
||||||
|
|
||||||
# 3. Search typography
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant luxury" --domain typography
|
|
||||||
|
|
||||||
# 4. Search color palette
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness" --domain color
|
|
||||||
|
|
||||||
# 5. Search landing page structure
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "hero-centric social-proof" --domain landing
|
|
||||||
|
|
||||||
# 6. Search UX guidelines
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "animation" --domain ux
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "accessibility" --domain ux
|
|
||||||
|
|
||||||
# 7. Search stack guidelines (default: html-tailwind)
|
|
||||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "layout responsive" --stack html-tailwind
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Then:** Synthesize all search results and implement the design.
|
**Output:** Complete design system with pattern, style, colors, typography, effects, and anti-patterns.
|
||||||
|
|
||||||
|
### Step 3: Supplement with Detailed Searches (as needed)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Get UX guidelines for animation and accessibility
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "animation accessibility" --domain ux
|
||||||
|
|
||||||
|
# Get alternative typography options if needed
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant luxury serif" --domain typography
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 4: Stack Guidelines
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "layout responsive form" --stack html-tailwind
|
||||||
|
```
|
||||||
|
|
||||||
|
**Then:** Synthesize design system + detailed searches and implement the design.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output Formats
|
||||||
|
|
||||||
|
The `--design-system` flag supports two output formats:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# ASCII box (default) - best for terminal display
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system
|
||||||
|
|
||||||
|
# Markdown - best for documentation
|
||||||
|
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system -f markdown
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -218,7 +341,7 @@ Before delivering UI code, verify these items:
|
|||||||
### Layout
|
### Layout
|
||||||
- [ ] Floating elements have proper spacing from edges
|
- [ ] Floating elements have proper spacing from edges
|
||||||
- [ ] No content hidden behind fixed navbars
|
- [ ] No content hidden behind fixed navbars
|
||||||
- [ ] Responsive at 320px, 768px, 1024px, 1440px
|
- [ ] Responsive at 375px, 768px, 1024px, 1440px
|
||||||
- [ ] No horizontal scroll on mobile
|
- [ ] No horizontal scroll on mobile
|
||||||
|
|
||||||
### Accessibility
|
### Accessibility
|
||||||
|
|||||||
101
skills/ui-ux-pro-max/data/icons.csv
Normal file
101
skills/ui-ux-pro-max/data/icons.csv
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
STT,Category,Icon Name,Keywords,Library,Import Code,Usage,Best For,Style
|
||||||
|
1,Navigation,menu,hamburger menu navigation toggle bars,Lucide,import { Menu } from 'lucide-react',<Menu />,Mobile navigation drawer toggle sidebar,Outline
|
||||||
|
2,Navigation,arrow-left,back previous return navigate,Lucide,import { ArrowLeft } from 'lucide-react',<ArrowLeft />,Back button breadcrumb navigation,Outline
|
||||||
|
3,Navigation,arrow-right,next forward continue navigate,Lucide,import { ArrowRight } from 'lucide-react',<ArrowRight />,Forward button next step CTA,Outline
|
||||||
|
4,Navigation,chevron-down,dropdown expand accordion select,Lucide,import { ChevronDown } from 'lucide-react',<ChevronDown />,Dropdown toggle accordion header,Outline
|
||||||
|
5,Navigation,chevron-up,collapse close accordion minimize,Lucide,import { ChevronUp } from 'lucide-react',<ChevronUp />,Accordion collapse minimize,Outline
|
||||||
|
6,Navigation,home,homepage main dashboard start,Lucide,import { Home } from 'lucide-react',<Home />,Home navigation main page,Outline
|
||||||
|
7,Navigation,x,close cancel dismiss remove exit,Lucide,import { X } from 'lucide-react',<X />,Modal close dismiss button,Outline
|
||||||
|
8,Navigation,external-link,open new tab external link,Lucide,import { ExternalLink } from 'lucide-react',<ExternalLink />,External link indicator,Outline
|
||||||
|
9,Action,plus,add create new insert,Lucide,import { Plus } from 'lucide-react',<Plus />,Add button create new item,Outline
|
||||||
|
10,Action,minus,remove subtract decrease delete,Lucide,import { Minus } from 'lucide-react',<Minus />,Remove item quantity decrease,Outline
|
||||||
|
11,Action,trash-2,delete remove discard bin,Lucide,import { Trash2 } from 'lucide-react',<Trash2 />,Delete action destructive,Outline
|
||||||
|
12,Action,edit,pencil modify change update,Lucide,import { Edit } from 'lucide-react',<Edit />,Edit button modify content,Outline
|
||||||
|
13,Action,save,disk store persist save,Lucide,import { Save } from 'lucide-react',<Save />,Save button persist changes,Outline
|
||||||
|
14,Action,download,export save file download,Lucide,import { Download } from 'lucide-react',<Download />,Download file export,Outline
|
||||||
|
15,Action,upload,import file attach upload,Lucide,import { Upload } from 'lucide-react',<Upload />,Upload file import,Outline
|
||||||
|
16,Action,copy,duplicate clipboard paste,Lucide,import { Copy } from 'lucide-react',<Copy />,Copy to clipboard,Outline
|
||||||
|
17,Action,share,social distribute send,Lucide,import { Share } from 'lucide-react',<Share />,Share button social,Outline
|
||||||
|
18,Action,search,find lookup filter query,Lucide,import { Search } from 'lucide-react',<Search />,Search input bar,Outline
|
||||||
|
19,Action,filter,sort refine narrow options,Lucide,import { Filter } from 'lucide-react',<Filter />,Filter dropdown sort,Outline
|
||||||
|
20,Action,settings,gear cog preferences config,Lucide,import { Settings } from 'lucide-react',<Settings />,Settings page configuration,Outline
|
||||||
|
21,Status,check,success done complete verified,Lucide,import { Check } from 'lucide-react',<Check />,Success state checkmark,Outline
|
||||||
|
22,Status,check-circle,success verified approved complete,Lucide,import { CheckCircle } from 'lucide-react',<CheckCircle />,Success badge verified,Outline
|
||||||
|
23,Status,x-circle,error failed cancel rejected,Lucide,import { XCircle } from 'lucide-react',<XCircle />,Error state failed,Outline
|
||||||
|
24,Status,alert-triangle,warning caution attention danger,Lucide,import { AlertTriangle } from 'lucide-react',<AlertTriangle />,Warning message caution,Outline
|
||||||
|
25,Status,alert-circle,info notice information help,Lucide,import { AlertCircle } from 'lucide-react',<AlertCircle />,Info notice alert,Outline
|
||||||
|
26,Status,info,information help tooltip details,Lucide,import { Info } from 'lucide-react',<Info />,Information tooltip help,Outline
|
||||||
|
27,Status,loader,loading spinner processing wait,Lucide,import { Loader } from 'lucide-react',<Loader className="animate-spin" />,Loading state spinner,Outline
|
||||||
|
28,Status,clock,time schedule pending wait,Lucide,import { Clock } from 'lucide-react',<Clock />,Pending time schedule,Outline
|
||||||
|
29,Communication,mail,email message inbox letter,Lucide,import { Mail } from 'lucide-react',<Mail />,Email contact inbox,Outline
|
||||||
|
30,Communication,message-circle,chat comment bubble conversation,Lucide,import { MessageCircle } from 'lucide-react',<MessageCircle />,Chat comment message,Outline
|
||||||
|
31,Communication,phone,call mobile telephone contact,Lucide,import { Phone } from 'lucide-react',<Phone />,Phone contact call,Outline
|
||||||
|
32,Communication,send,submit dispatch message airplane,Lucide,import { Send } from 'lucide-react',<Send />,Send message submit,Outline
|
||||||
|
33,Communication,bell,notification alert ring reminder,Lucide,import { Bell } from 'lucide-react',<Bell />,Notification bell alert,Outline
|
||||||
|
34,User,user,profile account person avatar,Lucide,import { User } from 'lucide-react',<User />,User profile account,Outline
|
||||||
|
35,User,users,team group people members,Lucide,import { Users } from 'lucide-react',<Users />,Team group members,Outline
|
||||||
|
36,User,user-plus,add invite new member,Lucide,import { UserPlus } from 'lucide-react',<UserPlus />,Add user invite,Outline
|
||||||
|
37,User,log-in,signin authenticate enter,Lucide,import { LogIn } from 'lucide-react',<LogIn />,Login signin,Outline
|
||||||
|
38,User,log-out,signout exit leave logout,Lucide,import { LogOut } from 'lucide-react',<LogOut />,Logout signout,Outline
|
||||||
|
39,Media,image,photo picture gallery thumbnail,Lucide,import { Image } from 'lucide-react',<Image />,Image photo gallery,Outline
|
||||||
|
40,Media,video,movie film play record,Lucide,import { Video } from 'lucide-react',<Video />,Video player media,Outline
|
||||||
|
41,Media,play,start video audio media,Lucide,import { Play } from 'lucide-react',<Play />,Play button video audio,Outline
|
||||||
|
42,Media,pause,stop halt video audio,Lucide,import { Pause } from 'lucide-react',<Pause />,Pause button media,Outline
|
||||||
|
43,Media,volume-2,sound audio speaker music,Lucide,import { Volume2 } from 'lucide-react',<Volume2 />,Volume audio sound,Outline
|
||||||
|
44,Media,mic,microphone record voice audio,Lucide,import { Mic } from 'lucide-react',<Mic />,Microphone voice record,Outline
|
||||||
|
45,Media,camera,photo capture snapshot picture,Lucide,import { Camera } from 'lucide-react',<Camera />,Camera photo capture,Outline
|
||||||
|
46,Commerce,shopping-cart,cart checkout basket buy,Lucide,import { ShoppingCart } from 'lucide-react',<ShoppingCart />,Shopping cart e-commerce,Outline
|
||||||
|
47,Commerce,shopping-bag,purchase buy store bag,Lucide,import { ShoppingBag } from 'lucide-react',<ShoppingBag />,Shopping bag purchase,Outline
|
||||||
|
48,Commerce,credit-card,payment card checkout stripe,Lucide,import { CreditCard } from 'lucide-react',<CreditCard />,Payment credit card,Outline
|
||||||
|
49,Commerce,dollar-sign,money price currency cost,Lucide,import { DollarSign } from 'lucide-react',<DollarSign />,Price money currency,Outline
|
||||||
|
50,Commerce,tag,label price discount sale,Lucide,import { Tag } from 'lucide-react',<Tag />,Price tag label,Outline
|
||||||
|
51,Commerce,gift,present reward bonus offer,Lucide,import { Gift } from 'lucide-react',<Gift />,Gift reward offer,Outline
|
||||||
|
52,Commerce,percent,discount sale offer promo,Lucide,import { Percent } from 'lucide-react',<Percent />,Discount percentage sale,Outline
|
||||||
|
53,Data,bar-chart,analytics statistics graph metrics,Lucide,import { BarChart } from 'lucide-react',<BarChart />,Bar chart analytics,Outline
|
||||||
|
54,Data,pie-chart,statistics distribution breakdown,Lucide,import { PieChart } from 'lucide-react',<PieChart />,Pie chart distribution,Outline
|
||||||
|
55,Data,trending-up,growth increase positive trend,Lucide,import { TrendingUp } from 'lucide-react',<TrendingUp />,Growth trend positive,Outline
|
||||||
|
56,Data,trending-down,decline decrease negative trend,Lucide,import { TrendingDown } from 'lucide-react',<TrendingDown />,Decline trend negative,Outline
|
||||||
|
57,Data,activity,pulse heartbeat monitor live,Lucide,import { Activity } from 'lucide-react',<Activity />,Activity monitor pulse,Outline
|
||||||
|
58,Data,database,storage server data backend,Lucide,import { Database } from 'lucide-react',<Database />,Database storage,Outline
|
||||||
|
59,Files,file,document page paper doc,Lucide,import { File } from 'lucide-react',<File />,File document,Outline
|
||||||
|
60,Files,file-text,document text page article,Lucide,import { FileText } from 'lucide-react',<FileText />,Text document article,Outline
|
||||||
|
61,Files,folder,directory organize group files,Lucide,import { Folder } from 'lucide-react',<Folder />,Folder directory,Outline
|
||||||
|
62,Files,folder-open,expanded browse files view,Lucide,import { FolderOpen } from 'lucide-react',<FolderOpen />,Open folder browse,Outline
|
||||||
|
63,Files,paperclip,attachment attach file link,Lucide,import { Paperclip } from 'lucide-react',<Paperclip />,Attachment paperclip,Outline
|
||||||
|
64,Files,link,url hyperlink chain connect,Lucide,import { Link } from 'lucide-react',<Link />,Link URL hyperlink,Outline
|
||||||
|
65,Files,clipboard,paste copy buffer notes,Lucide,import { Clipboard } from 'lucide-react',<Clipboard />,Clipboard paste,Outline
|
||||||
|
66,Layout,grid,tiles gallery layout dashboard,Lucide,import { Grid } from 'lucide-react',<Grid />,Grid layout gallery,Outline
|
||||||
|
67,Layout,list,rows table lines items,Lucide,import { List } from 'lucide-react',<List />,List view rows,Outline
|
||||||
|
68,Layout,columns,layout split dual sidebar,Lucide,import { Columns } from 'lucide-react',<Columns />,Column layout split,Outline
|
||||||
|
69,Layout,maximize,fullscreen expand enlarge zoom,Lucide,import { Maximize } from 'lucide-react',<Maximize />,Fullscreen maximize,Outline
|
||||||
|
70,Layout,minimize,reduce shrink collapse exit,Lucide,import { Minimize } from 'lucide-react',<Minimize />,Minimize reduce,Outline
|
||||||
|
71,Layout,sidebar,panel drawer navigation menu,Lucide,import { Sidebar } from 'lucide-react',<Sidebar />,Sidebar panel,Outline
|
||||||
|
72,Social,heart,like love favorite wishlist,Lucide,import { Heart } from 'lucide-react',<Heart />,Like favorite love,Outline
|
||||||
|
73,Social,star,rating review favorite bookmark,Lucide,import { Star } from 'lucide-react',<Star />,Star rating favorite,Outline
|
||||||
|
74,Social,thumbs-up,like approve agree positive,Lucide,import { ThumbsUp } from 'lucide-react',<ThumbsUp />,Like approve thumb,Outline
|
||||||
|
75,Social,thumbs-down,dislike disapprove disagree negative,Lucide,import { ThumbsDown } from 'lucide-react',<ThumbsDown />,Dislike disapprove,Outline
|
||||||
|
76,Social,bookmark,save later favorite mark,Lucide,import { Bookmark } from 'lucide-react',<Bookmark />,Bookmark save,Outline
|
||||||
|
77,Social,flag,report mark important highlight,Lucide,import { Flag } from 'lucide-react',<Flag />,Flag report,Outline
|
||||||
|
78,Device,smartphone,mobile phone device touch,Lucide,import { Smartphone } from 'lucide-react',<Smartphone />,Mobile smartphone,Outline
|
||||||
|
79,Device,tablet,ipad device touch screen,Lucide,import { Tablet } from 'lucide-react',<Tablet />,Tablet device,Outline
|
||||||
|
80,Device,monitor,desktop screen computer display,Lucide,import { Monitor } from 'lucide-react',<Monitor />,Desktop monitor,Outline
|
||||||
|
81,Device,laptop,notebook computer portable device,Lucide,import { Laptop } from 'lucide-react',<Laptop />,Laptop computer,Outline
|
||||||
|
82,Device,printer,print document output paper,Lucide,import { Printer } from 'lucide-react',<Printer />,Printer print,Outline
|
||||||
|
83,Security,lock,secure password protected private,Lucide,import { Lock } from 'lucide-react',<Lock />,Lock secure,Outline
|
||||||
|
84,Security,unlock,open access unsecure public,Lucide,import { Unlock } from 'lucide-react',<Unlock />,Unlock open,Outline
|
||||||
|
85,Security,shield,protection security safe guard,Lucide,import { Shield } from 'lucide-react',<Shield />,Shield protection,Outline
|
||||||
|
86,Security,key,password access unlock login,Lucide,import { Key } from 'lucide-react',<Key />,Key password,Outline
|
||||||
|
87,Security,eye,view show visible password,Lucide,import { Eye } from 'lucide-react',<Eye />,Show password view,Outline
|
||||||
|
88,Security,eye-off,hide invisible password hidden,Lucide,import { EyeOff } from 'lucide-react',<EyeOff />,Hide password,Outline
|
||||||
|
89,Location,map-pin,location marker place address,Lucide,import { MapPin } from 'lucide-react',<MapPin />,Location pin marker,Outline
|
||||||
|
90,Location,map,directions navigate geography location,Lucide,import { Map } from 'lucide-react',<Map />,Map directions,Outline
|
||||||
|
91,Location,navigation,compass direction pointer arrow,Lucide,import { Navigation } from 'lucide-react',<Navigation />,Navigation compass,Outline
|
||||||
|
92,Location,globe,world international global web,Lucide,import { Globe } from 'lucide-react',<Globe />,Globe world,Outline
|
||||||
|
93,Time,calendar,date schedule event appointment,Lucide,import { Calendar } from 'lucide-react',<Calendar />,Calendar date,Outline
|
||||||
|
94,Time,refresh-cw,reload sync update refresh,Lucide,import { RefreshCw } from 'lucide-react',<RefreshCw />,Refresh reload,Outline
|
||||||
|
95,Time,rotate-ccw,undo back revert history,Lucide,import { RotateCcw } from 'lucide-react',<RotateCcw />,Undo revert,Outline
|
||||||
|
96,Time,rotate-cw,redo forward repeat history,Lucide,import { RotateCw } from 'lucide-react',<RotateCw />,Redo forward,Outline
|
||||||
|
97,Development,code,develop programming syntax html,Lucide,import { Code } from 'lucide-react',<Code />,Code development,Outline
|
||||||
|
98,Development,terminal,console cli command shell,Lucide,import { Terminal } from 'lucide-react',<Terminal />,Terminal console,Outline
|
||||||
|
99,Development,git-branch,version control branch merge,Lucide,import { GitBranch } from 'lucide-react',<GitBranch />,Git branch,Outline
|
||||||
|
100,Development,github,repository code open source,Lucide,import { Github } from 'lucide-react',<Github />,GitHub repository,Outline
|
||||||
|
Can't render this file because it contains an unexpected character in line 28 and column 113.
|
45
skills/ui-ux-pro-max/data/react-performance.csv
Normal file
45
skills/ui-ux-pro-max/data/react-performance.csv
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
No,Category,Issue,Keywords,Platform,Description,Do,Don't,Code Example Good,Code Example Bad,Severity
|
||||||
|
1,Async Waterfall,Defer Await,async await defer branch,React/Next.js,Move await into branches where actually used to avoid blocking unused code paths,Move await operations into branches where they're needed,Await at top of function blocking all branches,"if (skip) return { skipped: true }; const data = await fetch()","const data = await fetch(); if (skip) return { skipped: true }",Critical
|
||||||
|
2,Async Waterfall,Promise.all Parallel,promise all parallel concurrent,React/Next.js,Execute independent async operations concurrently using Promise.all(),Use Promise.all() for independent operations,Sequential await for independent operations,"const [user, posts] = await Promise.all([fetchUser(), fetchPosts()])","const user = await fetchUser(); const posts = await fetchPosts()",Critical
|
||||||
|
3,Async Waterfall,Dependency Parallelization,better-all dependency parallel,React/Next.js,Use better-all for operations with partial dependencies to maximize parallelism,Use better-all to start each task at earliest possible moment,Wait for unrelated data before starting dependent fetch,"await all({ user() {}, config() {}, profile() { return fetch((await this.$.user).id) } })","const [user, config] = await Promise.all([...]); const profile = await fetchProfile(user.id)",Critical
|
||||||
|
4,Async Waterfall,API Route Optimization,api route waterfall promise,React/Next.js,In API routes start independent operations immediately even if not awaited yet,Start promises early and await late,Sequential awaits in API handlers,"const sessionP = auth(); const configP = fetchConfig(); const session = await sessionP","const session = await auth(); const config = await fetchConfig()",Critical
|
||||||
|
5,Async Waterfall,Suspense Boundaries,suspense streaming boundary,React/Next.js,Use Suspense to show wrapper UI faster while data loads,Wrap async components in Suspense boundaries,Await data blocking entire page render,"<Suspense fallback={<Skeleton />}><DataDisplay /></Suspense>","const data = await fetchData(); return <DataDisplay data={data} />",High
|
||||||
|
6,Bundle Size,Barrel Imports,barrel import direct path,React/Next.js,Import directly from source files instead of barrel files to avoid loading unused modules,Import directly from source path,Import from barrel/index files,"import Check from 'lucide-react/dist/esm/icons/check'","import { Check } from 'lucide-react'",Critical
|
||||||
|
7,Bundle Size,Dynamic Imports,dynamic import lazy next,React/Next.js,Use next/dynamic to lazy-load large components not needed on initial render,Use dynamic() for heavy components,Import heavy components at top level,"const Monaco = dynamic(() => import('./monaco'), { ssr: false })","import { MonacoEditor } from './monaco-editor'",Critical
|
||||||
|
8,Bundle Size,Defer Third Party,analytics defer third-party,React/Next.js,Load analytics and logging after hydration since they don't block interaction,Load non-critical scripts after hydration,Include analytics in main bundle,"const Analytics = dynamic(() => import('@vercel/analytics'), { ssr: false })","import { Analytics } from '@vercel/analytics/react'",Medium
|
||||||
|
9,Bundle Size,Conditional Loading,conditional module lazy,React/Next.js,Load large data or modules only when a feature is activated,Dynamic import when feature enabled,Import large modules unconditionally,"useEffect(() => { if (enabled) import('./heavy.js') }, [enabled])","import { heavyData } from './heavy.js'",High
|
||||||
|
10,Bundle Size,Preload Intent,preload hover focus intent,React/Next.js,Preload heavy bundles on hover/focus before they're needed,Preload on user intent signals,Load only on click,"onMouseEnter={() => import('./editor')}","onClick={() => import('./editor')}",Medium
|
||||||
|
11,Server,React.cache Dedup,react cache deduplicate request,React/Next.js,Use React.cache() for server-side request deduplication within single request,Wrap data fetchers with cache(),Fetch same data multiple times in tree,"export const getUser = cache(async () => await db.user.find())","export async function getUser() { return await db.user.find() }",Medium
|
||||||
|
12,Server,LRU Cache Cross-Request,lru cache cross request,React/Next.js,Use LRU cache for data shared across sequential requests,Use LRU for cross-request caching,Refetch same data on every request,"const cache = new LRUCache({ max: 1000, ttl: 5*60*1000 })","Always fetch from database",High
|
||||||
|
13,Server,Minimize Serialization,serialization rsc boundary,React/Next.js,Only pass fields that client actually uses across RSC boundaries,Pass only needed fields to client components,Pass entire objects to client,"<Profile name={user.name} />","<Profile user={user} /> // 50 fields serialized",High
|
||||||
|
14,Server,Parallel Fetching,parallel fetch component composition,React/Next.js,Restructure components to parallelize data fetching in RSC,Use component composition for parallel fetches,Sequential fetches in parent component,"<Header /><Sidebar /> // both fetch in parallel","const header = await fetchHeader(); return <><div>{header}</div><Sidebar /></>",Critical
|
||||||
|
15,Server,After Non-blocking,after non-blocking logging,React/Next.js,Use Next.js after() to schedule work after response is sent,Use after() for logging/analytics,Block response for non-critical operations,"after(async () => { await logAction() }); return Response.json(data)","await logAction(); return Response.json(data)",Medium
|
||||||
|
16,Client,SWR Deduplication,swr dedup cache revalidate,React/Next.js,Use SWR for automatic request deduplication and caching,Use useSWR for client data fetching,Manual fetch in useEffect,"const { data } = useSWR('/api/users', fetcher)","useEffect(() => { fetch('/api/users').then(setUsers) }, [])",Medium-High
|
||||||
|
17,Client,Event Listener Dedup,event listener deduplicate global,React/Next.js,Share global event listeners across component instances,Use useSWRSubscription for shared listeners,Register listener per component instance,"useSWRSubscription('global-keydown', () => { window.addEventListener... })","useEffect(() => { window.addEventListener('keydown', handler) }, [])",Low
|
||||||
|
18,Rerender,Defer State Reads,state read callback subscription,React/Next.js,Don't subscribe to state only used in callbacks,Read state on-demand in callbacks,Subscribe to state used only in handlers,"const handleClick = () => { const params = new URLSearchParams(location.search) }","const params = useSearchParams(); const handleClick = () => { params.get('ref') }",Medium
|
||||||
|
19,Rerender,Memoized Components,memo extract expensive,React/Next.js,Extract expensive work into memoized components for early returns,Extract to memo() components,Compute expensive values before early return,"const UserAvatar = memo(({ user }) => ...); if (loading) return <Skeleton />","const avatar = useMemo(() => compute(user)); if (loading) return <Skeleton />",Medium
|
||||||
|
20,Rerender,Narrow Dependencies,effect dependency primitive,React/Next.js,Specify primitive dependencies instead of objects in effects,Use primitive values in dependency arrays,Use object references as dependencies,"useEffect(() => { console.log(user.id) }, [user.id])","useEffect(() => { console.log(user.id) }, [user])",Low
|
||||||
|
21,Rerender,Derived State,derived boolean subscription,React/Next.js,Subscribe to derived booleans instead of continuous values,Use derived boolean state,Subscribe to continuous values,"const isMobile = useMediaQuery('(max-width: 767px)')","const width = useWindowWidth(); const isMobile = width < 768",Medium
|
||||||
|
22,Rerender,Functional setState,functional setstate callback,React/Next.js,Use functional setState updates for stable callbacks and no stale closures,Use functional form: setState(curr => ...),Reference state directly in setState,"setItems(curr => [...curr, newItem])","setItems([...items, newItem]) // items in deps",Medium
|
||||||
|
23,Rerender,Lazy State Init,usestate lazy initialization,React/Next.js,Pass function to useState for expensive initial values,Use function form for expensive init,Compute expensive value directly,"useState(() => buildSearchIndex(items))","useState(buildSearchIndex(items)) // runs every render",Medium
|
||||||
|
24,Rerender,Transitions,starttransition non-urgent,React/Next.js,Mark frequent non-urgent state updates as transitions,Use startTransition for non-urgent updates,Block UI on every state change,"startTransition(() => setScrollY(window.scrollY))","setScrollY(window.scrollY) // blocks on every scroll",Medium
|
||||||
|
25,Rendering,SVG Animation Wrapper,svg animation wrapper div,React/Next.js,Wrap SVG in div and animate wrapper for hardware acceleration,Animate div wrapper around SVG,Animate SVG element directly,"<div class='animate-spin'><svg>...</svg></div>","<svg class='animate-spin'>...</svg>",Low
|
||||||
|
26,Rendering,Content Visibility,content-visibility auto,React/Next.js,Apply content-visibility: auto to defer off-screen rendering,Use content-visibility for long lists,Render all list items immediately,".item { content-visibility: auto; contain-intrinsic-size: 0 80px }","Render 1000 items without optimization",High
|
||||||
|
27,Rendering,Hoist Static JSX,hoist static jsx element,React/Next.js,Extract static JSX outside components to avoid re-creation,Hoist static elements to module scope,Create static elements inside components,"const skeleton = <div class='animate-pulse' />; function C() { return skeleton }","function C() { return <div class='animate-pulse' /> }",Low
|
||||||
|
28,Rendering,Hydration No Flicker,hydration mismatch flicker,React/Next.js,Use inline script to set client-only data before hydration,Inject sync script for client-only values,Use useEffect causing flash,"<script dangerouslySetInnerHTML={{ __html: 'el.className = localStorage.theme' }} />","useEffect(() => setTheme(localStorage.theme), []) // flickers",Medium
|
||||||
|
29,Rendering,Conditional Render,conditional render ternary,React/Next.js,Use ternary instead of && when condition can be 0 or NaN,Use explicit ternary for conditionals,Use && with potentially falsy numbers,"{count > 0 ? <Badge>{count}</Badge> : null}","{count && <Badge>{count}</Badge>} // renders '0'",Low
|
||||||
|
30,Rendering,Activity Component,activity show hide preserve,React/Next.js,Use Activity component to preserve state/DOM for toggled components,Use Activity for expensive toggle components,Unmount/remount on visibility toggle,"<Activity mode={isOpen ? 'visible' : 'hidden'}><Menu /></Activity>","{isOpen && <Menu />} // loses state",Medium
|
||||||
|
31,JS Perf,Batch DOM CSS,batch dom css reflow,React/Next.js,Group CSS changes via classes or cssText to minimize reflows,Use class toggle or cssText,Change styles one property at a time,"element.classList.add('highlighted')","el.style.width='100px'; el.style.height='200px'",Medium
|
||||||
|
32,JS Perf,Index Map Lookup,map index lookup find,React/Next.js,Build Map for repeated lookups instead of multiple .find() calls,Build index Map for O(1) lookups,Use .find() in loops,"const byId = new Map(users.map(u => [u.id, u])); byId.get(id)","users.find(u => u.id === order.userId) // O(n) each time",Low-Medium
|
||||||
|
33,JS Perf,Cache Property Access,cache property loop,React/Next.js,Cache object property lookups in hot paths,Cache values before loops,Access nested properties in loops,"const val = obj.config.settings.value; for (...) process(val)","for (...) process(obj.config.settings.value)",Low-Medium
|
||||||
|
34,JS Perf,Cache Function Results,memoize cache function,React/Next.js,Use module-level Map to cache repeated function results,Use Map cache for repeated calls,Recompute same values repeatedly,"const cache = new Map(); if (cache.has(x)) return cache.get(x)","slugify(name) // called 100 times same input",Medium
|
||||||
|
35,JS Perf,Cache Storage API,localstorage cache read,React/Next.js,Cache localStorage/sessionStorage reads in memory,Cache storage reads in Map,Read storage on every call,"if (!cache.has(key)) cache.set(key, localStorage.getItem(key))","localStorage.getItem('theme') // every call",Low-Medium
|
||||||
|
36,JS Perf,Combine Iterations,combine filter map loop,React/Next.js,Combine multiple filter/map into single loop,Single loop for multiple categorizations,Chain multiple filter() calls,"for (u of users) { if (u.isAdmin) admins.push(u); if (u.isTester) testers.push(u) }","users.filter(admin); users.filter(tester); users.filter(inactive)",Low-Medium
|
||||||
|
37,JS Perf,Length Check First,length check array compare,React/Next.js,Check array lengths before expensive comparisons,Early return if lengths differ,Always run expensive comparison,"if (a.length !== b.length) return true; // then compare","a.sort().join() !== b.sort().join() // even when lengths differ",Medium-High
|
||||||
|
38,JS Perf,Early Return,early return exit function,React/Next.js,Return early when result is determined to skip processing,Return immediately on first error,Process all items then check errors,"for (u of users) { if (!u.email) return { error: 'Email required' } }","let hasError; for (...) { if (!email) hasError=true }; if (hasError)...",Low-Medium
|
||||||
|
39,JS Perf,Hoist RegExp,regexp hoist module,React/Next.js,Don't create RegExp inside render - hoist or memoize,Hoist RegExp to module scope,Create RegExp every render,"const EMAIL_RE = /^[^@]+@[^@]+$/; function validate() { EMAIL_RE.test(x) }","function C() { const re = new RegExp(pattern); re.test(x) }",Low-Medium
|
||||||
|
40,JS Perf,Loop Min Max,loop min max sort,React/Next.js,Use loop for min/max instead of sort - O(n) vs O(n log n),Single pass loop for min/max,Sort array to find min/max,"let max = arr[0]; for (x of arr) if (x > max) max = x","arr.sort((a,b) => b-a)[0] // O(n log n)",Low
|
||||||
|
41,JS Perf,Set Map Lookups,set map includes has,React/Next.js,Use Set/Map for O(1) lookups instead of array.includes(),Convert to Set for membership checks,Use .includes() for repeated checks,"const allowed = new Set(['a','b']); allowed.has(id)","const allowed = ['a','b']; allowed.includes(id)",Low-Medium
|
||||||
|
42,JS Perf,toSorted Immutable,tosorted sort immutable,React/Next.js,Use toSorted() instead of sort() to avoid mutating arrays,Use toSorted() for immutability,Mutate arrays with sort(),"users.toSorted((a,b) => a.name.localeCompare(b.name))","users.sort((a,b) => a.name.localeCompare(b.name)) // mutates",Medium-High
|
||||||
|
43,Advanced,Event Handler Refs,useeffectevent ref handler,React/Next.js,Store callbacks in refs for stable effect subscriptions,Use useEffectEvent for stable handlers,Re-subscribe on every callback change,"const onEvent = useEffectEvent(handler); useEffect(() => { listen(onEvent) }, [])","useEffect(() => { listen(handler) }, [handler]) // re-subscribes",Low
|
||||||
|
44,Advanced,useLatest Hook,uselatest ref callback,React/Next.js,Access latest values in callbacks without adding to dependency arrays,Use useLatest for fresh values in stable callbacks,Add callback to effect dependencies,"const cbRef = useLatest(cb); useEffect(() => { setTimeout(() => cbRef.current()) }, [])","useEffect(() => { setTimeout(() => cb()) }, [cb]) // re-runs",Low
|
||||||
|
61
skills/ui-ux-pro-max/data/stacks/shadcn.csv
Normal file
61
skills/ui-ux-pro-max/data/stacks/shadcn.csv
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Setup,Use CLI for installation,Install components via shadcn CLI for proper setup,npx shadcn@latest add component-name,Manual copy-paste from docs,npx shadcn@latest add button,Copy component code manually,High,https://ui.shadcn.com/docs/cli
|
||||||
|
2,Setup,Initialize project properly,Run init command to set up components.json and globals.css,npx shadcn@latest init before adding components,Skip init and add components directly,npx shadcn@latest init,npx shadcn@latest add button (without init),High,https://ui.shadcn.com/docs/installation
|
||||||
|
3,Setup,Configure path aliases,Set up proper import aliases in tsconfig and components.json,Use @/components/ui path aliases,Relative imports like ../../components,import { Button } from "@/components/ui/button",import { Button } from "../../components/ui/button",Medium,https://ui.shadcn.com/docs/installation
|
||||||
|
4,Theming,Use CSS variables for colors,Define colors as CSS variables in globals.css for theming,CSS variables in :root and .dark,Hardcoded color values in components,bg-primary text-primary-foreground,bg-blue-500 text-white,High,https://ui.shadcn.com/docs/theming
|
||||||
|
5,Theming,Follow naming convention,Use semantic color names with foreground pattern,primary/primary-foreground secondary/secondary-foreground,Generic color names,--primary --primary-foreground,--blue --light-blue,Medium,https://ui.shadcn.com/docs/theming
|
||||||
|
6,Theming,Support dark mode,Include .dark class styles for all custom CSS,Define both :root and .dark color schemes,Only light mode colors,.dark { --background: 240 10% 3.9%; },No .dark class styles,High,https://ui.shadcn.com/docs/dark-mode
|
||||||
|
7,Components,Use component variants,Leverage cva variants for consistent styling,Use variant prop for different styles,Inline conditional classes,<Button variant="destructive">,<Button className={isError ? "bg-red-500" : "bg-blue-500"}>,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
8,Components,Compose with className,Add custom classes via className prop for overrides,Extend with className for one-off customizations,Modify component source directly,<Button className="w-full">,Edit button.tsx to add w-full,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
9,Components,Use size variants consistently,Apply size prop for consistent sizing across components,size="sm" size="lg" for sizing,Mix size classes inconsistently,<Button size="lg">,<Button className="text-lg px-8 py-4">,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
10,Components,Prefer compound components,Use provided sub-components for complex UI,Card + CardHeader + CardContent pattern,Single component with many props,<Card><CardHeader><CardTitle>,<Card title="x" content="y" footer="z">,Medium,https://ui.shadcn.com/docs/components/card
|
||||||
|
11,Dialog,Use Dialog for modal content,Dialog component for overlay modal windows,Dialog for confirmations forms details,Alert for modal content,<Dialog><DialogContent>,<Alert> styled as modal,High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
12,Dialog,Handle dialog state properly,Use open and onOpenChange for controlled dialogs,Controlled state with useState,Uncontrolled with default open only,"<Dialog open={open} onOpenChange={setOpen}>","<Dialog defaultOpen={true}>",Medium,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
13,Dialog,Include proper dialog structure,Use DialogHeader DialogTitle DialogDescription,Complete semantic structure,Missing title or description,<DialogHeader><DialogTitle><DialogDescription>,<DialogContent><p>Content</p></DialogContent>,High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
14,Sheet,Use Sheet for side panels,Sheet component for slide-out panels and drawers,Sheet for navigation filters settings,Dialog for side content,<Sheet side="right">,<Dialog> with slide animation,Medium,https://ui.shadcn.com/docs/components/sheet
|
||||||
|
15,Sheet,Specify sheet side,Set side prop for sheet slide direction,Explicit side="left" or side="right",Default side without consideration,<Sheet><SheetContent side="left">,<Sheet><SheetContent>,Low,https://ui.shadcn.com/docs/components/sheet
|
||||||
|
16,Form,Use Form with react-hook-form,Integrate Form component with react-hook-form for validation,useForm + Form + FormField pattern,Custom form handling without Form,<Form {...form}><FormField control={form.control}>,<form onSubmit={handleSubmit}>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
17,Form,Use FormField for inputs,Wrap inputs in FormField for proper labeling and errors,FormField + FormItem + FormLabel + FormControl,Input without FormField wrapper,<FormField><FormItem><FormLabel><FormControl><Input>,<Input onChange={...}>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
18,Form,Display form messages,Use FormMessage for validation error display,FormMessage after FormControl,Custom error text without FormMessage,<FormControl><Input/></FormControl><FormMessage/>,<Input/>{error && <span>{error}</span>},Medium,https://ui.shadcn.com/docs/components/form
|
||||||
|
19,Form,Use Zod for validation,Define form schema with Zod for type-safe validation,zodResolver with form schema,Manual validation logic,zodResolver(formSchema),validate: (values) => { if (!values.email) },Medium,https://ui.shadcn.com/docs/components/form
|
||||||
|
20,Select,Use Select for dropdowns,Select component for option selection,Select for choosing from list,Native select element,<Select><SelectTrigger><SelectContent>,<select><option>,Medium,https://ui.shadcn.com/docs/components/select
|
||||||
|
21,Select,Structure Select properly,Include Trigger Value Content and Items,Complete Select structure,Missing SelectValue or SelectContent,<SelectTrigger><SelectValue/></SelectTrigger><SelectContent><SelectItem>,<Select><option>,High,https://ui.shadcn.com/docs/components/select
|
||||||
|
22,Command,Use Command for search,Command component for searchable lists and palettes,Command for command palette search,Input with custom dropdown,<Command><CommandInput><CommandList>,<Input><div className="dropdown">,Medium,https://ui.shadcn.com/docs/components/command
|
||||||
|
23,Command,Group command items,Use CommandGroup for categorized items,CommandGroup with heading for sections,Flat list without grouping,<CommandGroup heading="Suggestions"><CommandItem>,<CommandItem> without groups,Low,https://ui.shadcn.com/docs/components/command
|
||||||
|
24,Table,Use Table for data display,Table component for structured data,Table for tabular data display,Div grid for table-like layouts,<Table><TableHeader><TableBody><TableRow>,<div className="grid">,Medium,https://ui.shadcn.com/docs/components/table
|
||||||
|
25,Table,Include proper table structure,Use TableHeader TableBody TableRow TableCell,Semantic table structure,Missing thead or tbody,<TableHeader><TableRow><TableHead>,<Table><TableRow> without header,High,https://ui.shadcn.com/docs/components/table
|
||||||
|
26,DataTable,Use DataTable for complex tables,Combine Table with TanStack Table for features,DataTable pattern for sorting filtering pagination,Custom table implementation,useReactTable + Table components,Custom sort filter pagination logic,Medium,https://ui.shadcn.com/docs/components/data-table
|
||||||
|
27,Tabs,Use Tabs for content switching,Tabs component for tabbed interfaces,Tabs for related content sections,Custom tab implementation,<Tabs><TabsList><TabsTrigger><TabsContent>,<div onClick={() => setTab(...)},Medium,https://ui.shadcn.com/docs/components/tabs
|
||||||
|
28,Tabs,Set default tab value,Specify defaultValue for initial tab,defaultValue on Tabs component,No default leaving first tab,<Tabs defaultValue="account">,<Tabs> without defaultValue,Low,https://ui.shadcn.com/docs/components/tabs
|
||||||
|
29,Accordion,Use Accordion for collapsible,Accordion for expandable content sections,Accordion for FAQ settings panels,Custom collapse implementation,<Accordion><AccordionItem><AccordionTrigger>,<div onClick={() => setOpen(!open)}>,Medium,https://ui.shadcn.com/docs/components/accordion
|
||||||
|
30,Accordion,Choose accordion type,Use type="single" or type="multiple" appropriately,type="single" for one open type="multiple" for many,Default type without consideration,<Accordion type="single" collapsible>,<Accordion> without type,Low,https://ui.shadcn.com/docs/components/accordion
|
||||||
|
31,Toast,Use Sonner for toasts,Sonner integration for toast notifications,toast() from sonner for notifications,Custom toast implementation,toast("Event created"),setShowToast(true),Medium,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
32,Toast,Add Toaster to layout,Include Toaster component in root layout,<Toaster /> in app layout,Toaster in individual pages,app/layout.tsx: <Toaster />,page.tsx: <Toaster />,High,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
33,Toast,Use toast variants,Apply toast.success toast.error for context,Semantic toast methods,Generic toast for all messages,toast.success("Saved!") toast.error("Failed"),toast("Saved!") toast("Failed"),Medium,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
34,Popover,Use Popover for floating content,Popover for dropdown menus and floating panels,Popover for contextual actions,Absolute positioned divs,<Popover><PopoverTrigger><PopoverContent>,<div className="relative"><div className="absolute">,Medium,https://ui.shadcn.com/docs/components/popover
|
||||||
|
35,Popover,Handle popover alignment,Use align and side props for positioning,Explicit alignment configuration,Default alignment for all,<PopoverContent align="start" side="bottom">,<PopoverContent>,Low,https://ui.shadcn.com/docs/components/popover
|
||||||
|
36,DropdownMenu,Use DropdownMenu for actions,DropdownMenu for action lists and context menus,DropdownMenu for user menu actions,Popover for action lists,<DropdownMenu><DropdownMenuTrigger><DropdownMenuContent>,<Popover> for menu actions,Medium,https://ui.shadcn.com/docs/components/dropdown-menu
|
||||||
|
37,DropdownMenu,Group menu items,Use DropdownMenuGroup and DropdownMenuSeparator,Organized menu with separators,Flat list of items,<DropdownMenuGroup><DropdownMenuItem><DropdownMenuSeparator>,<DropdownMenuItem> without organization,Low,https://ui.shadcn.com/docs/components/dropdown-menu
|
||||||
|
38,Tooltip,Use Tooltip for hints,Tooltip for icon buttons and truncated text,Tooltip for additional context,Title attribute for tooltips,<Tooltip><TooltipTrigger><TooltipContent>,<button title="Delete">,Medium,https://ui.shadcn.com/docs/components/tooltip
|
||||||
|
39,Tooltip,Add TooltipProvider,Wrap app or section in TooltipProvider,TooltipProvider at app level,TooltipProvider per tooltip,<TooltipProvider><App/></TooltipProvider>,<Tooltip><TooltipProvider>,High,https://ui.shadcn.com/docs/components/tooltip
|
||||||
|
40,Skeleton,Use Skeleton for loading,Skeleton component for loading placeholders,Skeleton matching content layout,Spinner for content loading,<Skeleton className="h-4 w-[200px]"/>,<Spinner/> for card loading,Medium,https://ui.shadcn.com/docs/components/skeleton
|
||||||
|
41,Skeleton,Match skeleton dimensions,Size skeleton to match loaded content,Skeleton same size as expected content,Generic skeleton size,<Skeleton className="h-12 w-12 rounded-full"/>,<Skeleton/> without sizing,Medium,https://ui.shadcn.com/docs/components/skeleton
|
||||||
|
42,AlertDialog,Use AlertDialog for confirms,AlertDialog for destructive action confirmation,AlertDialog for delete confirmations,Dialog for confirmations,<AlertDialog><AlertDialogTrigger><AlertDialogContent>,<Dialog> for delete confirmation,High,https://ui.shadcn.com/docs/components/alert-dialog
|
||||||
|
43,AlertDialog,Include action buttons,Use AlertDialogAction and AlertDialogCancel,Standard confirm/cancel pattern,Custom buttons in AlertDialog,<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction>,<Button>Cancel</Button><Button>Confirm</Button>,Medium,https://ui.shadcn.com/docs/components/alert-dialog
|
||||||
|
44,Sidebar,Use Sidebar for navigation,Sidebar component for app navigation,Sidebar for main app navigation,Custom sidebar implementation,<SidebarProvider><Sidebar><SidebarContent>,<div className="w-64 fixed">,Medium,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
45,Sidebar,Wrap in SidebarProvider,Use SidebarProvider for sidebar state management,SidebarProvider at layout level,Sidebar without provider,<SidebarProvider><Sidebar></SidebarProvider>,<Sidebar> without provider,High,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
46,Sidebar,Use SidebarTrigger,Include SidebarTrigger for mobile toggle,SidebarTrigger for responsive toggle,Custom toggle button,<SidebarTrigger/>,<Button onClick={() => toggleSidebar()}>,Medium,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
47,Chart,Use Chart for data viz,Chart component with Recharts integration,Chart component for dashboards,Direct Recharts without wrapper,<ChartContainer config={chartConfig}>,<ResponsiveContainer><BarChart>,Medium,https://ui.shadcn.com/docs/components/chart
|
||||||
|
48,Chart,Define chart config,Create chartConfig for consistent theming,chartConfig with color definitions,Inline colors in charts,"{ desktop: { label: ""Desktop"", color: ""#2563eb"" } }",<Bar fill="#2563eb"/>,Medium,https://ui.shadcn.com/docs/components/chart
|
||||||
|
49,Chart,Use ChartTooltip,Apply ChartTooltip for interactive charts,ChartTooltip with ChartTooltipContent,Recharts Tooltip directly,<ChartTooltip content={<ChartTooltipContent/>}/>,<Tooltip/> from recharts,Low,https://ui.shadcn.com/docs/components/chart
|
||||||
|
50,Blocks,Use blocks for scaffolding,Start from shadcn blocks for common layouts,npx shadcn@latest add dashboard-01,Build dashboard from scratch,npx shadcn@latest add login-01,Custom login page from scratch,Medium,https://ui.shadcn.com/blocks
|
||||||
|
51,Blocks,Customize block components,Modify copied block code to fit needs,Edit block files after installation,Use blocks without modification,Customize dashboard-01 layout,Use dashboard-01 as-is,Low,https://ui.shadcn.com/blocks
|
||||||
|
52,A11y,Use semantic components,Shadcn components have built-in ARIA,Rely on component accessibility,Override ARIA attributes,<Button> has button role,<div role="button">,High,https://ui.shadcn.com/docs/components/button
|
||||||
|
53,A11y,Maintain focus management,Dialog Sheet handle focus automatically,Let components manage focus,Custom focus handling,<Dialog> traps focus,document.querySelector().focus(),High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
54,A11y,Provide labels,Use FormLabel and aria-label appropriately,FormLabel for form inputs,Placeholder as only label,<FormLabel>Email</FormLabel><Input/>,<Input placeholder="Email"/>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
55,Performance,Import components individually,Import only needed components,Named imports from component files,Import all from index,import { Button } from "@/components/ui/button",import { Button Card Dialog } from "@/components/ui",Medium,
|
||||||
|
56,Performance,Lazy load dialogs,Dynamic import for heavy dialog content,React.lazy for dialog content,Import all dialogs upfront,const HeavyContent = lazy(() => import('./Heavy')),import HeavyContent from './Heavy',Medium,
|
||||||
|
57,Customization,Extend variants with cva,Add new variants using class-variance-authority,Extend buttonVariants for new styles,Inline classes for variants,"variants: { size: { xl: ""h-14 px-8"" } }",className="h-14 px-8",Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
58,Customization,Create custom components,Build new components following shadcn patterns,Use cn() and cva for custom components,Different patterns for custom,const Custom = ({ className }) => <div className={cn("base" className)}>,const Custom = ({ style }) => <div style={style}>,Medium,
|
||||||
|
59,Patterns,Use asChild for composition,asChild prop for component composition,Slot pattern with asChild,Wrapper divs for composition,<Button asChild><Link href="/">,<Button><Link href="/"></Link></Button>,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
60,Patterns,Combine with React Hook Form,Form + useForm for complete forms,RHF Controller with shadcn inputs,Custom form state management,<FormField control={form.control} name="email">,<Input value={email} onChange={(e) => setEmail(e.target.value)},High,https://ui.shadcn.com/docs/components/form
|
||||||
|
Can't render this file because it contains an unexpected character in line 4 and column 188.
|
101
skills/ui-ux-pro-max/data/ui-reasoning.csv
Normal file
101
skills/ui-ux-pro-max/data/ui-reasoning.csv
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
No,UI_Category,Recommended_Pattern,Style_Priority,Color_Mood,Typography_Mood,Key_Effects,Decision_Rules,Anti_Patterns,Severity
|
||||||
|
1,SaaS (General),Hero + Features + CTA,Glassmorphism + Flat Design,Trust blue + Accent contrast,Professional + Hierarchy,Subtle hover (200-250ms) + Smooth transitions,"{""if_ux_focused"": ""prioritize-minimalism"", ""if_data_heavy"": ""add-glassmorphism""}",Excessive animation + Dark mode by default,HIGH
|
||||||
|
2,Micro SaaS,Minimal & Direct + Demo,Flat Design + Vibrant & Block,Vibrant primary + White space,Bold + Clean typography,Large CTA hover (300ms) + Scroll reveal,"{""if_quick_onboarding"": ""reduce-steps"", ""if_demo_available"": ""feature-interactive-demo""}",Complex onboarding flow + Cluttered layout,HIGH
|
||||||
|
3,E-commerce,Feature-Rich Showcase,Vibrant & Block-based,Brand primary + Success green,Engaging + Clear hierarchy,Card hover lift (200ms) + Scale effect,"{""if_luxury"": ""switch-to-liquid-glass"", ""if_conversion_focused"": ""add-urgency-colors""}",Flat design without depth + Text-heavy pages,HIGH
|
||||||
|
4,E-commerce Luxury,Feature-Rich Showcase,Liquid Glass + Glassmorphism,Premium colors + Minimal accent,Elegant + Refined typography,Chromatic aberration + Fluid animations (400-600ms),"{""if_checkout"": ""emphasize-trust"", ""if_hero_needed"": ""use-3d-hyperrealism""}",Vibrant & Block-based + Playful colors,HIGH
|
||||||
|
5,Healthcare App,Social Proof-Focused,Neumorphism + Accessible & Ethical,Calm blue + Health green,Readable + Large type (16px+),Soft box-shadow + Smooth press (150ms),"{""must_have"": ""wcag-aaa-compliance"", ""if_medication"": ""red-alert-colors""}",Bright neon colors + Motion-heavy animations + AI purple/pink gradients,HIGH
|
||||||
|
6,Fintech/Crypto,Conversion-Optimized,Glassmorphism + Dark Mode (OLED),Dark tech colors + Vibrant accents,Modern + Confident typography,Real-time chart animations + Alert pulse/glow,"{""must_have"": ""security-badges"", ""if_real_time"": ""add-streaming-data""}",Light backgrounds + No security indicators,HIGH
|
||||||
|
7,Education,Feature-Rich Showcase,Claymorphism + Micro-interactions,Playful colors + Clear hierarchy,Friendly + Engaging typography,Soft press (200ms) + Fluffy elements,"{""if_gamification"": ""add-progress-animation"", ""if_children"": ""increase-playfulness""}",Dark modes + Complex jargon,MEDIUM
|
||||||
|
8,Portfolio/Personal,Storytelling-Driven,Motion-Driven + Minimalism,Brand primary + Artistic,Expressive + Variable typography,Parallax (3-5 layers) + Scroll-triggered reveals,"{""if_creative_field"": ""add-brutalism"", ""if_minimal_portfolio"": ""reduce-motion""}",Corporate templates + Generic layouts,MEDIUM
|
||||||
|
9,Government/Public,Minimal & Direct,Accessible & Ethical + Minimalism,Professional blue + High contrast,Clear + Large typography,Clear focus rings (3-4px) + Skip links,"{""must_have"": ""wcag-aaa"", ""must_have"": ""keyboard-navigation""}",Ornate design + Low contrast + Motion effects + AI purple/pink gradients,HIGH
|
||||||
|
10,Fintech (Banking),Trust & Authority,Minimalism + Accessible & Ethical,Navy + Trust Blue + Gold,Professional + Trustworthy,Smooth state transitions + Number animations,"{""must_have"": ""security-first"", ""if_dashboard"": ""use-dark-mode""}",Playful design + Unclear fees + AI purple/pink gradients,HIGH
|
||||||
|
11,Social Media App,Feature-Rich Showcase,Vibrant & Block-based + Motion-Driven,Vibrant + Engagement colors,Modern + Bold typography,Large scroll animations + Icon animations,"{""if_engagement_metric"": ""add-motion"", ""if_content_focused"": ""minimize-chrome""}",Heavy skeuomorphism + Accessibility ignored,MEDIUM
|
||||||
|
12,Startup Landing,Hero-Centric + Trust,Motion-Driven + Vibrant & Block,Bold primaries + Accent contrast,Modern + Energetic typography,Scroll-triggered animations + Parallax,"{""if_pre_launch"": ""use-waitlist-pattern"", ""if_video_ready"": ""add-hero-video""}",Static design + No video + Poor mobile,HIGH
|
||||||
|
13,Gaming,Feature-Rich Showcase,3D & Hyperrealism + Retro-Futurism,Vibrant + Neon + Immersive,Bold + Impactful typography,WebGL 3D rendering + Glitch effects,"{""if_competitive"": ""add-real-time-stats"", ""if_casual"": ""increase-playfulness""}",Minimalist design + Static assets,HIGH
|
||||||
|
14,Creative Agency,Storytelling-Driven,Brutalism + Motion-Driven,Bold primaries + Artistic freedom,Bold + Expressive typography,CRT scanlines + Neon glow + Glitch effects,"{""must_have"": ""case-studies"", ""if_boutique"": ""increase-artistic-freedom""}",Corporate minimalism + Hidden portfolio,HIGH
|
||||||
|
15,Wellness/Mental Health,Social Proof-Focused,Neumorphism + Accessible & Ethical,Calm Pastels + Trust colors,Calming + Readable typography,Soft press + Breathing animations,"{""must_have"": ""privacy-first"", ""if_meditation"": ""add-breathing-animation""}",Bright neon + Motion overload,HIGH
|
||||||
|
16,Restaurant/Food,Hero-Centric + Conversion,Vibrant & Block-based + Motion-Driven,Warm colors (Orange Red Brown),Appetizing + Clear typography,Food image reveal + Menu hover effects,"{""must_have"": ""high_quality_images"", ""if_delivery"": ""emphasize-speed""}",Low-quality imagery + Outdated hours,HIGH
|
||||||
|
17,Real Estate,Hero-Centric + Feature-Rich,Glassmorphism + Minimalism,Trust Blue + Gold + White,Professional + Confident,3D property tour zoom + Map hover,"{""if_luxury"": ""add-3d-models"", ""must_have"": ""map-integration""}",Poor photos + No virtual tours,HIGH
|
||||||
|
18,Travel/Tourism,Storytelling-Driven + Hero,Aurora UI + Motion-Driven,Vibrant destination + Sky Blue,Inspirational + Engaging,Destination parallax + Itinerary animations,"{""if_experience_focused"": ""use-storytelling"", ""must_have"": ""mobile-booking""}",Generic photos + Complex booking,HIGH
|
||||||
|
19,SaaS Dashboard,Data-Dense Dashboard,Data-Dense + Heat Map,Cool to Hot gradients + Neutral grey,Clear + Readable typography,Hover tooltips + Chart zoom + Real-time pulse,"{""must_have"": ""real-time-updates"", ""if_large_dataset"": ""prioritize-performance""}",Ornate design + Slow rendering,HIGH
|
||||||
|
20,B2B SaaS Enterprise,Feature-Rich Showcase,Trust & Authority + Minimal,Professional blue + Neutral grey,Formal + Clear typography,Subtle section transitions + Feature reveals,"{""must_have"": ""case-studies"", ""must_have"": ""roi-messaging""}",Playful design + Hidden features + AI purple/pink gradients,HIGH
|
||||||
|
21,Music/Entertainment,Feature-Rich Showcase,Dark Mode (OLED) + Vibrant & Block-based,Dark (#121212) + Vibrant accents + Album art colors,Modern + Bold typography,Waveform visualization + Playlist animations,"{""must_have"": ""audio-player-ux"", ""if_discovery_focused"": ""add-playlist-recommendations""}",Cluttered layout + Poor audio player UX,HIGH
|
||||||
|
22,Video Streaming/OTT,Hero-Centric + Feature-Rich,Dark Mode (OLED) + Motion-Driven,Dark bg + Poster colors + Brand accent,Bold + Engaging typography,Video player animations + Content carousel (parallax),"{""must_have"": ""continue-watching"", ""if_personalized"": ""add-recommendations""}",Static layout + Slow video player,HIGH
|
||||||
|
23,Job Board/Recruitment,Conversion-Optimized + Feature-Rich,Flat Design + Minimalism,Professional Blue + Success Green + Neutral,Clear + Professional typography,Search/filter animations + Application flow,"{""must_have"": ""advanced-search"", ""if_salary_focused"": ""highlight-compensation""}",Outdated forms + Hidden filters,HIGH
|
||||||
|
24,Marketplace (P2P),Feature-Rich Showcase + Social Proof,Vibrant & Block-based + Flat Design,Trust colors + Category colors + Success green,Modern + Engaging typography,Review star animations + Listing hover effects,"{""must_have"": ""seller-profiles"", ""must_have"": ""secure-payment""}",Low trust signals + Confusing layout,HIGH
|
||||||
|
25,Logistics/Delivery,Feature-Rich Showcase + Real-Time,Minimalism + Flat Design,Blue (#2563EB) + Orange (tracking) + Green,Clear + Functional typography,Real-time tracking animation + Status pulse,"{""must_have"": ""tracking-map"", ""must_have"": ""delivery-updates""}",Static tracking + No map integration + AI purple/pink gradients,HIGH
|
||||||
|
26,Agriculture/Farm Tech,Feature-Rich Showcase,Organic Biophilic + Flat Design,Earth Green (#4A7C23) + Brown + Sky Blue,Clear + Informative typography,Data visualization + Weather animations,"{""must_have"": ""sensor-dashboard"", ""if_crop_focused"": ""add-health-indicators""}",Generic design + Ignored accessibility + AI purple/pink gradients,MEDIUM
|
||||||
|
27,Construction/Architecture,Hero-Centric + Feature-Rich,Minimalism + 3D & Hyperrealism,Grey (#4A4A4A) + Orange (safety) + Blueprint Blue,Professional + Bold typography,3D model viewer + Timeline animations,"{""must_have"": ""project-portfolio"", ""if_team_collaboration"": ""add-real-time-updates""}",2D-only layouts + Poor image quality + AI purple/pink gradients,HIGH
|
||||||
|
28,Automotive/Car Dealership,Hero-Centric + Feature-Rich,Motion-Driven + 3D & Hyperrealism,Brand colors + Metallic + Dark/Light,Bold + Confident typography,360 product view + Configurator animations,"{""must_have"": ""vehicle-comparison"", ""must_have"": ""financing-calculator""}",Static product pages + Poor UX,HIGH
|
||||||
|
29,Photography Studio,Storytelling-Driven + Hero-Centric,Motion-Driven + Minimalism,Black + White + Minimal accent,Elegant + Minimal typography,Full-bleed gallery + Before/after reveal,"{""must_have"": ""portfolio-showcase"", ""if_booking"": ""add-calendar-system""}",Heavy text + Poor image showcase,HIGH
|
||||||
|
30,Coworking Space,Hero-Centric + Feature-Rich,Vibrant & Block-based + Glassmorphism,Energetic colors + Wood tones + Brand,Modern + Engaging typography,Space tour video + Amenity reveal animations,"{""must_have"": ""virtual-tour"", ""must_have"": ""booking-system""}",Outdated photos + Confusing layout,MEDIUM
|
||||||
|
31,Cleaning Service,Conversion-Optimized + Trust,Soft UI Evolution + Flat Design,Fresh Blue (#00B4D8) + Clean White + Green,Friendly + Clear typography,Before/after gallery + Service package reveal,"{""must_have"": ""price-transparency"", ""must_have"": ""trust-badges""}",Poor before/after imagery + Hidden pricing,HIGH
|
||||||
|
32,Home Services,Conversion-Optimized + Trust,Flat Design + Trust & Authority,Trust Blue + Safety Orange + Grey,Professional + Clear typography,Emergency contact highlight + Service menu animations,"{""must_have"": ""emergency-contact"", ""must_have"": ""certifications-display""}",Hidden contact info + No certifications,HIGH
|
||||||
|
33,Childcare/Daycare,Social Proof-Focused + Trust,Claymorphism + Vibrant & Block-based,Playful pastels + Safe colors + Warm,Friendly + Playful typography,Parent portal animations + Activity gallery reveal,"{""must_have"": ""parent-communication"", ""must_have"": ""safety-certifications""}",Generic design + Hidden safety info,HIGH
|
||||||
|
34,Senior Care/Elderly,Trust & Authority + Accessible,Accessible & Ethical + Soft UI Evolution,Calm Blue + Warm neutrals + Large text,Large + Clear typography (18px+),Large touch targets + Clear navigation,"{""must_have"": ""wcag-aaa"", ""must_have"": ""family-portal""}",Small text + Complex navigation + AI purple/pink gradients,HIGH
|
||||||
|
35,Medical Clinic,Trust & Authority + Conversion,Accessible & Ethical + Minimalism,Medical Blue (#0077B6) + Trust White,Professional + Readable typography,Online booking flow + Doctor profile reveals,"{""must_have"": ""appointment-booking"", ""must_have"": ""insurance-info""}",Outdated interface + Confusing booking + AI purple/pink gradients,HIGH
|
||||||
|
36,Pharmacy/Drug Store,Conversion-Optimized + Trust,Flat Design + Accessible & Ethical,Pharmacy Green + Trust Blue + Clean White,Clear + Functional typography,Prescription upload flow + Refill reminders,"{""must_have"": ""prescription-management"", ""must_have"": ""drug-interaction-warnings""}",Confusing layout + Privacy concerns + AI purple/pink gradients,HIGH
|
||||||
|
37,Dental Practice,Social Proof-Focused + Conversion,Soft UI Evolution + Minimalism,Fresh Blue + White + Smile Yellow,Friendly + Professional typography,Before/after gallery + Patient testimonial carousel,"{""must_have"": ""before-after-gallery"", ""must_have"": ""appointment-system""}",Poor imagery + No testimonials,HIGH
|
||||||
|
38,Veterinary Clinic,Social Proof-Focused + Trust,Claymorphism + Accessible & Ethical,Caring Blue + Pet colors + Warm,Friendly + Welcoming typography,Pet profile management + Service animations,"{""must_have"": ""pet-portal"", ""must_have"": ""emergency-contact""}",Generic design + Hidden services,MEDIUM
|
||||||
|
39,News/Media Platform,Hero-Centric + Feature-Rich,Minimalism + Flat Design,Brand colors + High contrast,Clear + Readable typography,Breaking news badge + Article reveal animations,"{""must_have"": ""mobile-first-reading"", ""must_have"": ""category-navigation""}",Cluttered layout + Slow loading,HIGH
|
||||||
|
40,Legal Services,Trust & Authority + Minimal,Trust & Authority + Minimalism,Navy Blue (#1E3A5F) + Gold + White,Professional + Authoritative typography,Practice area reveal + Attorney profile animations,"{""must_have"": ""case-results"", ""must_have"": ""credential-display""}",Outdated design + Hidden credentials + AI purple/pink gradients,HIGH
|
||||||
|
41,Beauty/Spa/Wellness Service,Hero-Centric + Social Proof,Soft UI Evolution + Neumorphism,Soft pastels (Pink Sage Cream) + Gold accents,Elegant + Calming typography,Soft shadows + Smooth transitions (200-300ms) + Gentle hover,"{""must_have"": ""booking-system"", ""must_have"": ""before-after-gallery"", ""if_luxury"": ""add-gold-accents""}",Bright neon colors + Harsh animations + Dark mode,HIGH
|
||||||
|
42,Service Landing Page,Hero-Centric + Trust & Authority,Minimalism + Social Proof-Focused,Brand primary + Trust colors,Professional + Clear typography,Testimonial carousel + CTA hover (200ms),"{""must_have"": ""social-proof"", ""must_have"": ""clear-cta""}",Complex navigation + Hidden contact info,HIGH
|
||||||
|
43,B2B Service,Feature-Rich Showcase + Trust,Trust & Authority + Minimalism,Professional blue + Neutral grey,Formal + Clear typography,Section transitions + Feature reveals,"{""must_have"": ""case-studies"", ""must_have"": ""roi-messaging""}",Playful design + Hidden credentials + AI purple/pink gradients,HIGH
|
||||||
|
44,Financial Dashboard,Data-Dense Dashboard,Dark Mode (OLED) + Data-Dense,Dark bg + Red/Green alerts + Trust blue,Clear + Readable typography,Real-time number animations + Alert pulse,"{""must_have"": ""real-time-updates"", ""must_have"": ""high-contrast""}",Light mode default + Slow rendering,HIGH
|
||||||
|
45,Analytics Dashboard,Data-Dense + Drill-Down,Data-Dense + Heat Map,Cool→Hot gradients + Neutral grey,Clear + Functional typography,Hover tooltips + Chart zoom + Filter animations,"{""must_have"": ""data-export"", ""if_large_dataset"": ""virtualize-lists""}",Ornate design + No filtering,HIGH
|
||||||
|
46,Productivity Tool,Interactive Demo + Feature-Rich,Flat Design + Micro-interactions,Clear hierarchy + Functional colors,Clean + Efficient typography,Quick actions (150ms) + Task animations,"{""must_have"": ""keyboard-shortcuts"", ""if_collaboration"": ""add-real-time-cursors""}",Complex onboarding + Slow performance,HIGH
|
||||||
|
47,Design System/Component Library,Feature-Rich + Documentation,Minimalism + Accessible & Ethical,Clear hierarchy + Code-like structure,Monospace + Clear typography,Code copy animations + Component previews,"{""must_have"": ""search"", ""must_have"": ""code-examples""}",Poor documentation + No live preview,HIGH
|
||||||
|
48,AI/Chatbot Platform,Interactive Demo + Minimal,AI-Native UI + Minimalism,Neutral + AI Purple (#6366F1),Modern + Clear typography,Streaming text + Typing indicators + Fade-in,"{""must_have"": ""conversational-ui"", ""must_have"": ""context-awareness""}",Heavy chrome + Slow response feedback,HIGH
|
||||||
|
49,NFT/Web3 Platform,Feature-Rich Showcase,Cyberpunk UI + Glassmorphism,Dark + Neon + Gold (#FFD700),Bold + Modern typography,Wallet connect animations + Transaction feedback,"{""must_have"": ""wallet-integration"", ""must_have"": ""gas-fees-display""}",Light mode default + No transaction status,HIGH
|
||||||
|
50,Creator Economy Platform,Social Proof + Feature-Rich,Vibrant & Block-based + Bento Box Grid,Vibrant + Brand colors,Modern + Bold typography,Engagement counter animations + Profile reveals,"{""must_have"": ""creator-profiles"", ""must_have"": ""monetization-display""}",Generic layout + Hidden earnings,MEDIUM
|
||||||
|
51,Sustainability/ESG Platform,Trust & Authority + Data,Organic Biophilic + Minimalism,Green (#228B22) + Earth tones,Clear + Informative typography,Progress indicators + Impact animations,"{""must_have"": ""data-transparency"", ""must_have"": ""certification-badges""}",Greenwashing visuals + No data,HIGH
|
||||||
|
52,Remote Work/Collaboration,Feature-Rich + Real-Time,Soft UI Evolution + Minimalism,Calm Blue + Neutral grey,Clean + Readable typography,Real-time presence indicators + Notification badges,"{""must_have"": ""status-indicators"", ""must_have"": ""video-integration""}",Cluttered interface + No presence,HIGH
|
||||||
|
53,Pet Tech App,Storytelling + Feature-Rich,Claymorphism + Vibrant & Block-based,Playful + Warm colors,Friendly + Playful typography,Pet profile animations + Health tracking charts,"{""must_have"": ""pet-profiles"", ""if_health"": ""add-vet-integration""}",Generic design + No personality,MEDIUM
|
||||||
|
54,Smart Home/IoT Dashboard,Real-Time Monitoring,Glassmorphism + Dark Mode (OLED),Dark + Status indicator colors,Clear + Functional typography,Device status pulse + Quick action animations,"{""must_have"": ""real-time-controls"", ""must_have"": ""energy-monitoring""}",Slow updates + No automation,HIGH
|
||||||
|
55,EV/Charging Ecosystem,Hero-Centric + Feature-Rich,Minimalism + Aurora UI,Electric Blue (#009CD1) + Green,Modern + Clear typography,Range estimation animations + Map interactions,"{""must_have"": ""charging-map"", ""must_have"": ""range-calculator""}",Poor map UX + Hidden costs,HIGH
|
||||||
|
56,Subscription Box Service,Feature-Rich + Conversion,Vibrant & Block-based + Motion-Driven,Brand + Excitement colors,Engaging + Clear typography,Unboxing reveal animations + Product carousel,"{""must_have"": ""personalization-quiz"", ""must_have"": ""subscription-management""}",Confusing pricing + No unboxing preview,HIGH
|
||||||
|
57,Podcast Platform,Storytelling + Feature-Rich,Dark Mode (OLED) + Minimalism,Dark + Audio waveform accents,Modern + Clear typography,Waveform visualizations + Episode transitions,"{""must_have"": ""audio-player-ux"", ""must_have"": ""episode-discovery""}",Poor audio player + Cluttered layout,HIGH
|
||||||
|
58,Dating App,Social Proof + Feature-Rich,Vibrant & Block-based + Motion-Driven,Warm + Romantic (Pink/Red gradients),Modern + Friendly typography,Profile card swipe + Match animations,"{""must_have"": ""profile-cards"", ""must_have"": ""safety-features""}",Generic profiles + No safety,HIGH
|
||||||
|
59,Micro-Credentials/Badges,Trust & Authority + Feature,Minimalism + Flat Design,Trust Blue + Gold (#FFD700),Professional + Clear typography,Badge reveal animations + Progress tracking,"{""must_have"": ""credential-verification"", ""must_have"": ""progress-display""}",No verification + Hidden progress,MEDIUM
|
||||||
|
60,Knowledge Base/Documentation,FAQ + Minimal,Minimalism + Accessible & Ethical,Clean hierarchy + Minimal color,Clear + Readable typography,Search highlight + Smooth scrolling,"{""must_have"": ""search-first"", ""must_have"": ""version-switching""}",Poor navigation + No search,HIGH
|
||||||
|
61,Hyperlocal Services,Conversion + Feature-Rich,Minimalism + Vibrant & Block-based,Location markers + Trust colors,Clear + Functional typography,Map hover + Provider card reveals,"{""must_have"": ""map-integration"", ""must_have"": ""booking-system""}",No map + Hidden reviews,HIGH
|
||||||
|
62,Luxury/Premium Brand,Storytelling + Feature-Rich,Liquid Glass + Glassmorphism,Black + Gold (#FFD700) + White,Elegant + Refined typography,Slow parallax + Premium reveals (400-600ms),"{""must_have"": ""high-quality-imagery"", ""must_have"": ""storytelling""}",Cheap visuals + Fast animations,HIGH
|
||||||
|
63,Fitness/Gym App,Feature-Rich + Data,Vibrant & Block-based + Dark Mode (OLED),Energetic (Orange #FF6B35) + Dark bg,Bold + Motivational typography,Progress ring animations + Achievement unlocks,"{""must_have"": ""progress-tracking"", ""must_have"": ""workout-plans""}",Static design + No gamification,HIGH
|
||||||
|
64,Hotel/Hospitality,Hero-Centric + Social Proof,Liquid Glass + Minimalism,Warm neutrals + Gold (#D4AF37),Elegant + Welcoming typography,Room gallery + Amenity reveals,"{""must_have"": ""room-booking"", ""must_have"": ""virtual-tour""}",Poor photos + Complex booking,HIGH
|
||||||
|
65,Wedding/Event Planning,Storytelling + Social Proof,Soft UI Evolution + Aurora UI,Soft Pink (#FFD6E0) + Gold + Cream,Elegant + Romantic typography,Gallery reveals + Timeline animations,"{""must_have"": ""portfolio-gallery"", ""must_have"": ""planning-tools""}",Generic templates + No portfolio,HIGH
|
||||||
|
66,Insurance Platform,Conversion + Trust,Trust & Authority + Flat Design,Trust Blue (#0066CC) + Green + Neutral,Clear + Professional typography,Quote calculator animations + Policy comparison,"{""must_have"": ""quote-calculator"", ""must_have"": ""policy-comparison""}",Confusing pricing + No trust signals + AI purple/pink gradients,HIGH
|
||||||
|
67,Banking/Traditional Finance,Trust & Authority + Feature,Minimalism + Accessible & Ethical,Navy (#0A1628) + Trust Blue + Gold,Professional + Trustworthy typography,Smooth number animations + Security indicators,"{""must_have"": ""security-first"", ""must_have"": ""accessibility""}",Playful design + Poor security UX + AI purple/pink gradients,HIGH
|
||||||
|
68,Online Course/E-learning,Feature-Rich + Social Proof,Claymorphism + Vibrant & Block-based,Vibrant learning colors + Progress green,Friendly + Engaging typography,Progress bar animations + Certificate reveals,"{""must_have"": ""progress-tracking"", ""must_have"": ""video-player""}",Boring design + No gamification,HIGH
|
||||||
|
69,Non-profit/Charity,Storytelling + Trust,Accessible & Ethical + Organic Biophilic,Cause-related colors + Trust + Warm,Heartfelt + Readable typography,Impact counter animations + Story reveals,"{""must_have"": ""impact-stories"", ""must_have"": ""donation-transparency""}",No impact data + Hidden financials,HIGH
|
||||||
|
70,Florist/Plant Shop,Hero-Centric + Conversion,Organic Biophilic + Vibrant & Block-based,Natural Green + Floral pinks/purples,Elegant + Natural typography,Product reveal + Seasonal transitions,"{""must_have"": ""delivery-scheduling"", ""must_have"": ""care-guides""}",Poor imagery + No seasonal content,MEDIUM
|
||||||
|
71,Bakery/Cafe,Hero-Centric + Conversion,Vibrant & Block-based + Soft UI Evolution,Warm Brown + Cream + Appetizing accents,Warm + Inviting typography,Menu hover + Order animations,"{""must_have"": ""menu-display"", ""must_have"": ""online-ordering""}",Poor food photos + Hidden hours,HIGH
|
||||||
|
72,Coffee Shop,Hero-Centric + Minimal,Minimalism + Organic Biophilic,Coffee Brown (#6F4E37) + Cream + Warm,Cozy + Clean typography,Menu transitions + Loyalty animations,"{""must_have"": ""menu"", ""if_loyalty"": ""add-rewards-system""}",Generic design + No atmosphere,MEDIUM
|
||||||
|
73,Brewery/Winery,Storytelling + Hero-Centric,Motion-Driven + Storytelling-Driven,Deep amber/burgundy + Gold + Craft,Artisanal + Heritage typography,Tasting note reveals + Heritage timeline,"{""must_have"": ""product-showcase"", ""must_have"": ""story-heritage""}",Generic product pages + No story,HIGH
|
||||||
|
74,Airline,Conversion + Feature-Rich,Minimalism + Glassmorphism,Sky Blue + Brand colors + Trust,Clear + Professional typography,Flight search animations + Boarding pass reveals,"{""must_have"": ""flight-search"", ""must_have"": ""mobile-first""}",Complex booking + Poor mobile,HIGH
|
||||||
|
75,Magazine/Blog,Storytelling + Hero-Centric,Swiss Modernism 2.0 + Motion-Driven,Editorial colors + Brand + Clean white,Editorial + Elegant typography,Article transitions + Category reveals,"{""must_have"": ""article-showcase"", ""must_have"": ""newsletter-signup""}",Poor typography + Slow loading,HIGH
|
||||||
|
76,Freelancer Platform,Feature-Rich + Conversion,Flat Design + Minimalism,Professional Blue + Success Green,Clear + Professional typography,Skill match animations + Review reveals,"{""must_have"": ""portfolio-display"", ""must_have"": ""skill-matching""}",Poor profiles + No reviews,HIGH
|
||||||
|
77,Consulting Firm,Trust & Authority + Minimal,Trust & Authority + Minimalism,Navy + Gold + Professional grey,Authoritative + Clear typography,Case study reveals + Team profiles,"{""must_have"": ""case-studies"", ""must_have"": ""thought-leadership""}",Generic content + No credentials + AI purple/pink gradients,HIGH
|
||||||
|
78,Marketing Agency,Storytelling + Feature-Rich,Brutalism + Motion-Driven,Bold brand colors + Creative freedom,Bold + Expressive typography,Portfolio reveals + Results animations,"{""must_have"": ""portfolio"", ""must_have"": ""results-metrics""}",Boring design + Hidden work,HIGH
|
||||||
|
79,Event Management,Hero-Centric + Feature-Rich,Vibrant & Block-based + Motion-Driven,Event theme colors + Excitement accents,Bold + Engaging typography,Countdown timer + Registration flow,"{""must_have"": ""registration"", ""must_have"": ""agenda-display""}",Confusing registration + No countdown,HIGH
|
||||||
|
80,Conference/Webinar Platform,Feature-Rich + Conversion,Glassmorphism + Minimalism,Professional Blue + Video accent,Professional + Clear typography,Live stream integration + Agenda transitions,"{""must_have"": ""registration"", ""must_have"": ""speaker-profiles""}",Poor video UX + No networking,HIGH
|
||||||
|
81,Membership/Community,Social Proof + Conversion,Vibrant & Block-based + Soft UI Evolution,Community brand colors + Engagement,Friendly + Engaging typography,Member counter + Benefit reveals,"{""must_have"": ""member-benefits"", ""must_have"": ""pricing-tiers""}",Hidden benefits + No community proof,HIGH
|
||||||
|
82,Newsletter Platform,Minimal + Conversion,Minimalism + Flat Design,Brand primary + Clean white + CTA,Clean + Readable typography,Subscribe form + Archive reveals,"{""must_have"": ""subscribe-form"", ""must_have"": ""sample-content""}",Complex signup + No preview,MEDIUM
|
||||||
|
83,Digital Products/Downloads,Feature-Rich + Conversion,Vibrant & Block-based + Motion-Driven,Product colors + Brand + Success green,Modern + Clear typography,Product preview + Instant delivery animations,"{""must_have"": ""product-preview"", ""must_have"": ""instant-delivery""}",No preview + Slow delivery,HIGH
|
||||||
|
84,Church/Religious Organization,Hero-Centric + Social Proof,Accessible & Ethical + Soft UI Evolution,Warm Gold + Deep Purple/Blue + White,Welcoming + Clear typography,Service time highlights + Event calendar,"{""must_have"": ""service-times"", ""must_have"": ""community-events""}",Outdated design + Hidden info,MEDIUM
|
||||||
|
85,Sports Team/Club,Hero-Centric + Feature-Rich,Vibrant & Block-based + Motion-Driven,Team colors + Energetic accents,Bold + Impactful typography,Score animations + Schedule reveals,"{""must_have"": ""schedule"", ""must_have"": ""roster""}",Static content + Poor fan engagement,HIGH
|
||||||
|
86,Museum/Gallery,Storytelling + Feature-Rich,Minimalism + Motion-Driven,Art-appropriate neutrals + Exhibition accents,Elegant + Minimal typography,Virtual tour + Collection reveals,"{""must_have"": ""virtual-tour"", ""must_have"": ""exhibition-info""}",Cluttered layout + No online access,HIGH
|
||||||
|
87,Theater/Cinema,Hero-Centric + Conversion,Dark Mode (OLED) + Motion-Driven,Dark + Spotlight accents + Gold,Dramatic + Bold typography,Seat selection + Trailer reveals,"{""must_have"": ""showtimes"", ""must_have"": ""seat-selection""}",Poor booking UX + No trailers,HIGH
|
||||||
|
88,Language Learning App,Feature-Rich + Social Proof,Claymorphism + Vibrant & Block-based,Playful colors + Progress indicators,Friendly + Clear typography,Progress animations + Achievement unlocks,"{""must_have"": ""progress-tracking"", ""must_have"": ""gamification""}",Boring design + No motivation,HIGH
|
||||||
|
89,Coding Bootcamp,Feature-Rich + Social Proof,Dark Mode (OLED) + Minimalism,Code editor colors + Brand + Success,Technical + Clear typography,Terminal animations + Career outcome reveals,"{""must_have"": ""curriculum"", ""must_have"": ""career-outcomes""}",Light mode only + Hidden results,HIGH
|
||||||
|
90,Cybersecurity Platform,Trust & Authority + Real-Time,Cyberpunk UI + Dark Mode (OLED),Matrix Green (#00FF00) + Deep Black,Technical + Clear typography,Threat visualization + Alert animations,"{""must_have"": ""real-time-monitoring"", ""must_have"": ""threat-display""}",Light mode + Poor data viz,HIGH
|
||||||
|
91,Developer Tool/IDE,Minimal + Documentation,Dark Mode (OLED) + Minimalism,Dark syntax theme + Blue focus,Monospace + Functional typography,Syntax highlighting + Command palette,"{""must_have"": ""keyboard-shortcuts"", ""must_have"": ""documentation""}",Light mode default + Slow performance,HIGH
|
||||||
|
92,Biotech/Life Sciences,Storytelling + Data,Glassmorphism + Clean Science,Sterile White + DNA Blue + Life Green,Scientific + Clear typography,Data visualization + Research reveals,"{""must_have"": ""data-accuracy"", ""must_have"": ""clean-aesthetic""}",Cluttered data + Poor credibility,HIGH
|
||||||
|
93,Space Tech/Aerospace,Immersive + Feature-Rich,Holographic/HUD + Dark Mode,Deep Space Black + Star White + Metallic,Futuristic + Precise typography,Telemetry animations + 3D renders,"{""must_have"": ""high-tech-feel"", ""must_have"": ""precision-data""}",Generic design + No immersion,HIGH
|
||||||
|
94,Architecture/Interior,Portfolio + Hero-Centric,Exaggerated Minimalism + High Imagery,Monochrome + Gold Accent + High Imagery,Architectural + Elegant typography,Project gallery + Blueprint reveals,"{""must_have"": ""high-res-images"", ""must_have"": ""project-portfolio""}",Poor imagery + Cluttered layout,HIGH
|
||||||
|
95,Quantum Computing,Immersive + Interactive,Holographic/HUD + Dark Mode,Quantum Blue (#00FFFF) + Deep Black,Futuristic + Scientific typography,Probability visualizations + Qubit state animations,"{""must_have"": ""complexity-visualization"", ""must_have"": ""scientific-credibility""}",Generic tech design + No viz,HIGH
|
||||||
|
96,Biohacking/Longevity App,Data-Dense + Storytelling,Biomimetic/Organic 2.0 + Minimalism,Cellular Pink/Red + DNA Blue + White,Scientific + Clear typography,Biological data viz + Progress animations,"{""must_have"": ""data-privacy"", ""must_have"": ""scientific-credibility""}",Generic health app + No privacy,HIGH
|
||||||
|
97,Autonomous Drone Fleet,Real-Time + Feature-Rich,HUD/Sci-Fi FUI + Real-Time,Tactical Green + Alert Red + Map Dark,Technical + Functional typography,Telemetry animations + 3D spatial awareness,"{""must_have"": ""real-time-telemetry"", ""must_have"": ""safety-alerts""}",Slow updates + Poor spatial viz,HIGH
|
||||||
|
98,Generative Art Platform,Showcase + Feature-Rich,Minimalism + Gen Z Chaos,Neutral (#F5F5F5) + User Content,Minimal + Content-focused typography,Gallery masonry + Minting animations,"{""must_have"": ""fast-loading"", ""must_have"": ""creator-attribution""}",Heavy chrome + Slow loading,HIGH
|
||||||
|
99,Spatial Computing OS,Immersive + Interactive,Spatial UI (VisionOS) + Glassmorphism,Frosted Glass + System Colors + Depth,Spatial + Readable typography,Depth hierarchy + Gaze interactions,"{""must_have"": ""depth-hierarchy"", ""must_have"": ""environment-awareness""}",2D design + No spatial depth,HIGH
|
||||||
|
100,Sustainable Energy/Climate,Data + Trust,Organic Biophilic + E-Ink/Paper,Earth Green + Sky Blue + Solar Yellow,Clear + Informative typography,Impact viz + Progress animations,"{""must_have"": ""data-transparency"", ""must_have"": ""impact-visualization""}",Greenwashing + No real data,HIGH
|
||||||
|
31
skills/ui-ux-pro-max/data/web-interface.csv
Normal file
31
skills/ui-ux-pro-max/data/web-interface.csv
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
No,Category,Issue,Keywords,Platform,Description,Do,Don't,Code Example Good,Code Example Bad,Severity
|
||||||
|
1,Accessibility,Icon Button Labels,icon button aria-label,Web,Icon-only buttons must have accessible names,Add aria-label to icon buttons,Icon button without label,"<button aria-label='Close'><XIcon /></button>","<button><XIcon /></button>",Critical
|
||||||
|
2,Accessibility,Form Control Labels,form input label aria,Web,All form controls need labels or aria-label,Use label element or aria-label,Input without accessible name,"<label for='email'>Email</label><input id='email' />","<input placeholder='Email' />",Critical
|
||||||
|
3,Accessibility,Keyboard Handlers,keyboard onclick onkeydown,Web,Interactive elements must support keyboard interaction,Add onKeyDown alongside onClick,Click-only interaction,"<div onClick={fn} onKeyDown={fn} tabIndex={0}>","<div onClick={fn}>",High
|
||||||
|
4,Accessibility,Semantic HTML,semantic button a label,Web,Use semantic HTML before ARIA attributes,Use button/a/label elements,Div with role attribute,"<button onClick={fn}>Submit</button>","<div role='button' onClick={fn}>Submit</div>",High
|
||||||
|
5,Accessibility,Aria Live,aria-live polite async,Web,Async updates need aria-live for screen readers,Add aria-live='polite' for dynamic content,Silent async updates,"<div aria-live='polite'>{status}</div>","<div>{status}</div> // no announcement",Medium
|
||||||
|
6,Accessibility,Decorative Icons,aria-hidden decorative icon,Web,Decorative icons should be hidden from screen readers,Add aria-hidden='true' to decorative icons,Decorative icon announced,"<Icon aria-hidden='true' />","<Icon /> // announced as 'image'",Medium
|
||||||
|
7,Focus,Visible Focus States,focus-visible outline ring,Web,All interactive elements need visible focus states,Use :focus-visible with ring/outline,No focus indication,"focus-visible:ring-2 focus-visible:ring-blue-500","outline-none // no replacement",Critical
|
||||||
|
8,Focus,Never Remove Outline,outline-none focus replacement,Web,Never remove outline without providing replacement,Replace outline with visible alternative,Remove outline completely,"focus:outline-none focus:ring-2","focus:outline-none // nothing else",Critical
|
||||||
|
9,Focus,Checkbox Radio Hit Target,checkbox radio label target,Web,Checkbox/radio must share hit target with label,Wrap input and label together,Separate tiny checkbox,"<label class='flex gap-2'><input type='checkbox' /><span>Option</span></label>","<input type='checkbox' id='x' /><label for='x'>Option</label>",Medium
|
||||||
|
10,Forms,Autocomplete Attribute,autocomplete input form,Web,Inputs need autocomplete attribute for autofill,Add appropriate autocomplete value,Missing autocomplete,"<input autocomplete='email' type='email' />","<input type='email' />",High
|
||||||
|
11,Forms,Semantic Input Types,input type email tel url,Web,Use semantic input type attributes,Use email/tel/url/number types,text type for everything,"<input type='email' />","<input type='text' /> // for email",Medium
|
||||||
|
12,Forms,Never Block Paste,paste onpaste password,Web,Never prevent paste functionality,Allow paste on all inputs,Block paste on password/code,"<input type='password' />","<input onPaste={e => e.preventDefault()} />",High
|
||||||
|
13,Forms,Spellcheck Disable,spellcheck email code,Web,Disable spellcheck on emails and codes,Set spellcheck='false' on codes,Spellcheck on technical input,"<input spellCheck='false' type='email' />","<input type='email' /> // red squiggles",Low
|
||||||
|
14,Forms,Submit Button Enabled,submit button disabled loading,Web,Keep submit enabled and show spinner during requests,Show loading spinner keep enabled,Disable button during submit,"<button>{loading ? <Spinner /> : 'Submit'}</button>","<button disabled={loading}>Submit</button>",Medium
|
||||||
|
15,Forms,Inline Errors,error message inline focus,Web,Show error messages inline near the problem field,Inline error with focus on first error,Single error at top,"<input /><span class='text-red-500'>{error}</span>","<div class='error'>{allErrors}</div> // at top",High
|
||||||
|
16,Performance,Virtualize Lists,virtualize list 50 items,Web,Virtualize lists exceeding 50 items,Use virtual list for large datasets,Render all items,"<VirtualList items={items} />","items.map(item => <Item />)",High
|
||||||
|
17,Performance,Avoid Layout Reads,layout read render getboundingclientrect,Web,Avoid layout reads during render phase,Read layout in effects or callbacks,getBoundingClientRect in render,"useEffect(() => { el.getBoundingClientRect() })","const rect = el.getBoundingClientRect() // in render",Medium
|
||||||
|
18,Performance,Batch DOM Operations,batch dom write read,Web,Group DOM operations to minimize reflows,Batch writes then reads,Interleave reads and writes,"writes.forEach(w => w()); reads.forEach(r => r())","write(); read(); write(); read(); // thrashing",Medium
|
||||||
|
19,Performance,Preconnect CDN,preconnect link cdn,Web,Add preconnect links for CDN domains,Preconnect to known domains,"<link rel='preconnect' href='https://cdn.example.com' />","// no preconnect hint",Low
|
||||||
|
20,Performance,Lazy Load Images,lazy loading image below-fold,Web,Lazy-load images below the fold,Use loading='lazy' for below-fold images,Load all images eagerly,"<img loading='lazy' src='...' />","<img src='...' /> // above fold only",Medium
|
||||||
|
21,State,URL Reflects State,url state query params,Web,URL should reflect current UI state,Sync filters/tabs/pagination to URL,State only in memory,"?tab=settings&page=2","useState only // lost on refresh",High
|
||||||
|
22,State,Deep Linking,deep link stateful component,Web,Stateful components should support deep-linking,Enable sharing current view via URL,No shareable state,"router.push({ query: { ...filters } })","setFilters(f) // not in URL",Medium
|
||||||
|
23,State,Confirm Destructive Actions,confirm destructive delete modal,Web,Destructive actions require confirmation,Show confirmation dialog before delete,Delete without confirmation,"if (confirm('Delete?')) delete()","onClick={delete} // no confirmation",High
|
||||||
|
24,Typography,Proper Unicode,unicode ellipsis quotes,Web,Use proper Unicode characters,Use ... curly quotes proper dashes,ASCII approximations,"'Hello...' with proper ellipsis","'Hello...' with three dots",Low
|
||||||
|
25,Typography,Text Overflow,truncate line-clamp overflow,Web,Handle text overflow properly,Use truncate/line-clamp/break-words,Text overflows container,"<p class='truncate'>Long text...</p>","<p>Long text...</p> // overflows",Medium
|
||||||
|
26,Typography,Non-Breaking Spaces,nbsp unit brand,Web,Use non-breaking spaces for units and brand names,Use between number and unit,"10 kg or Next.js 14","10 kg // may wrap",Low
|
||||||
|
27,Anti-Pattern,No Zoom Disable,viewport zoom disable,Web,Never disable zoom in viewport meta,Allow user zoom,"<meta name='viewport' content='width=device-width'>","<meta name='viewport' content='maximum-scale=1'>",Critical
|
||||||
|
28,Anti-Pattern,No Transition All,transition all specific,Web,Avoid transition: all - specify properties,Transition specific properties,transition: all,"transition-colors duration-200","transition-all duration-200",Medium
|
||||||
|
29,Anti-Pattern,Outline Replacement,outline-none ring focus,Web,Never use outline-none without replacement,Provide visible focus replacement,Remove outline with nothing,"focus:outline-none focus:ring-2 focus:ring-blue-500","focus:outline-none // alone",Critical
|
||||||
|
30,Anti-Pattern,No Hardcoded Dates,date format intl locale,Web,Use Intl for date/number formatting,Use Intl.DateTimeFormat,Hardcoded date format,"new Intl.DateTimeFormat('en').format(date)","date.toLocaleDateString() // or manual format",Medium
|
||||||
|
BIN
skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-314.pyc
Normal file
BIN
skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-314.pyc
Normal file
Binary file not shown.
Binary file not shown.
@@ -54,6 +54,21 @@ CSV_CONFIG = {
|
|||||||
"file": "typography.csv",
|
"file": "typography.csv",
|
||||||
"search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"],
|
"search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"],
|
||||||
"output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"]
|
"output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"]
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"file": "icons.csv",
|
||||||
|
"search_cols": ["Category", "Icon Name", "Keywords", "Best For"],
|
||||||
|
"output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"]
|
||||||
|
},
|
||||||
|
"react": {
|
||||||
|
"file": "react-performance.csv",
|
||||||
|
"search_cols": ["Category", "Issue", "Keywords", "Description"],
|
||||||
|
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
|
||||||
|
},
|
||||||
|
"web": {
|
||||||
|
"file": "web-interface.csv",
|
||||||
|
"search_cols": ["Category", "Issue", "Keywords", "Description"],
|
||||||
|
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,7 +82,8 @@ STACK_CONFIG = {
|
|||||||
"svelte": {"file": "stacks/svelte.csv"},
|
"svelte": {"file": "stacks/svelte.csv"},
|
||||||
"swiftui": {"file": "stacks/swiftui.csv"},
|
"swiftui": {"file": "stacks/swiftui.csv"},
|
||||||
"react-native": {"file": "stacks/react-native.csv"},
|
"react-native": {"file": "stacks/react-native.csv"},
|
||||||
"flutter": {"file": "stacks/flutter.csv"}
|
"flutter": {"file": "stacks/flutter.csv"},
|
||||||
|
"shadcn": {"file": "stacks/shadcn.csv"}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Common columns for all stacks
|
# Common columns for all stacks
|
||||||
@@ -186,7 +202,10 @@ def detect_domain(query):
|
|||||||
"prompt": ["prompt", "css", "implementation", "variable", "checklist", "tailwind"],
|
"prompt": ["prompt", "css", "implementation", "variable", "checklist", "tailwind"],
|
||||||
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora"],
|
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora"],
|
||||||
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
|
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
|
||||||
"typography": ["font", "typography", "heading", "serif", "sans"]
|
"typography": ["font", "typography", "heading", "serif", "sans"],
|
||||||
|
"icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"],
|
||||||
|
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
|
||||||
|
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
|
||||||
}
|
}
|
||||||
|
|
||||||
scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
|
scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
|
||||||
|
|||||||
487
skills/ui-ux-pro-max/scripts/design_system.py
Normal file
487
skills/ui-ux-pro-max/scripts/design_system.py
Normal file
@@ -0,0 +1,487 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Design System Generator - Aggregates search results and applies reasoning
|
||||||
|
to generate comprehensive design system recommendations.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from design_system import generate_design_system
|
||||||
|
result = generate_design_system("SaaS dashboard", "My Project")
|
||||||
|
"""
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from core import search, DATA_DIR
|
||||||
|
|
||||||
|
|
||||||
|
# ============ CONFIGURATION ============
|
||||||
|
REASONING_FILE = "ui-reasoning.csv"
|
||||||
|
|
||||||
|
SEARCH_CONFIG = {
|
||||||
|
"product": {"max_results": 1},
|
||||||
|
"style": {"max_results": 3},
|
||||||
|
"color": {"max_results": 2},
|
||||||
|
"landing": {"max_results": 2},
|
||||||
|
"typography": {"max_results": 2}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ DESIGN SYSTEM GENERATOR ============
|
||||||
|
class DesignSystemGenerator:
|
||||||
|
"""Generates design system recommendations from aggregated searches."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.reasoning_data = self._load_reasoning()
|
||||||
|
|
||||||
|
def _load_reasoning(self) -> list:
|
||||||
|
"""Load reasoning rules from CSV."""
|
||||||
|
filepath = DATA_DIR / REASONING_FILE
|
||||||
|
if not filepath.exists():
|
||||||
|
return []
|
||||||
|
with open(filepath, 'r', encoding='utf-8') as f:
|
||||||
|
return list(csv.DictReader(f))
|
||||||
|
|
||||||
|
def _multi_domain_search(self, query: str, style_priority: list = None) -> dict:
|
||||||
|
"""Execute searches across multiple domains."""
|
||||||
|
results = {}
|
||||||
|
for domain, config in SEARCH_CONFIG.items():
|
||||||
|
if domain == "style" and style_priority:
|
||||||
|
# For style, also search with priority keywords
|
||||||
|
priority_query = " ".join(style_priority[:2]) if style_priority else query
|
||||||
|
combined_query = f"{query} {priority_query}"
|
||||||
|
results[domain] = search(combined_query, domain, config["max_results"])
|
||||||
|
else:
|
||||||
|
results[domain] = search(query, domain, config["max_results"])
|
||||||
|
return results
|
||||||
|
|
||||||
|
def _find_reasoning_rule(self, category: str) -> dict:
|
||||||
|
"""Find matching reasoning rule for a category."""
|
||||||
|
category_lower = category.lower()
|
||||||
|
|
||||||
|
# Try exact match first
|
||||||
|
for rule in self.reasoning_data:
|
||||||
|
if rule.get("UI_Category", "").lower() == category_lower:
|
||||||
|
return rule
|
||||||
|
|
||||||
|
# Try partial match
|
||||||
|
for rule in self.reasoning_data:
|
||||||
|
ui_cat = rule.get("UI_Category", "").lower()
|
||||||
|
if ui_cat in category_lower or category_lower in ui_cat:
|
||||||
|
return rule
|
||||||
|
|
||||||
|
# Try keyword match
|
||||||
|
for rule in self.reasoning_data:
|
||||||
|
ui_cat = rule.get("UI_Category", "").lower()
|
||||||
|
keywords = ui_cat.replace("/", " ").replace("-", " ").split()
|
||||||
|
if any(kw in category_lower for kw in keywords):
|
||||||
|
return rule
|
||||||
|
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def _apply_reasoning(self, category: str, search_results: dict) -> dict:
|
||||||
|
"""Apply reasoning rules to search results."""
|
||||||
|
rule = self._find_reasoning_rule(category)
|
||||||
|
|
||||||
|
if not rule:
|
||||||
|
return {
|
||||||
|
"pattern": "Hero + Features + CTA",
|
||||||
|
"style_priority": ["Minimalism", "Flat Design"],
|
||||||
|
"color_mood": "Professional",
|
||||||
|
"typography_mood": "Clean",
|
||||||
|
"key_effects": "Subtle hover transitions",
|
||||||
|
"anti_patterns": "",
|
||||||
|
"decision_rules": {},
|
||||||
|
"severity": "MEDIUM"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Parse decision rules JSON
|
||||||
|
decision_rules = {}
|
||||||
|
try:
|
||||||
|
decision_rules = json.loads(rule.get("Decision_Rules", "{}"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
return {
|
||||||
|
"pattern": rule.get("Recommended_Pattern", ""),
|
||||||
|
"style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")],
|
||||||
|
"color_mood": rule.get("Color_Mood", ""),
|
||||||
|
"typography_mood": rule.get("Typography_Mood", ""),
|
||||||
|
"key_effects": rule.get("Key_Effects", ""),
|
||||||
|
"anti_patterns": rule.get("Anti_Patterns", ""),
|
||||||
|
"decision_rules": decision_rules,
|
||||||
|
"severity": rule.get("Severity", "MEDIUM")
|
||||||
|
}
|
||||||
|
|
||||||
|
def _select_best_match(self, results: list, priority_keywords: list) -> dict:
|
||||||
|
"""Select best matching result based on priority keywords."""
|
||||||
|
if not results:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if not priority_keywords:
|
||||||
|
return results[0]
|
||||||
|
|
||||||
|
# First: try exact style name match
|
||||||
|
for priority in priority_keywords:
|
||||||
|
priority_lower = priority.lower().strip()
|
||||||
|
for result in results:
|
||||||
|
style_name = result.get("Style Category", "").lower()
|
||||||
|
if priority_lower in style_name or style_name in priority_lower:
|
||||||
|
return result
|
||||||
|
|
||||||
|
# Second: score by keyword match in all fields
|
||||||
|
scored = []
|
||||||
|
for result in results:
|
||||||
|
result_str = str(result).lower()
|
||||||
|
score = 0
|
||||||
|
for kw in priority_keywords:
|
||||||
|
kw_lower = kw.lower().strip()
|
||||||
|
# Higher score for style name match
|
||||||
|
if kw_lower in result.get("Style Category", "").lower():
|
||||||
|
score += 10
|
||||||
|
# Lower score for keyword field match
|
||||||
|
elif kw_lower in result.get("Keywords", "").lower():
|
||||||
|
score += 3
|
||||||
|
# Even lower for other field matches
|
||||||
|
elif kw_lower in result_str:
|
||||||
|
score += 1
|
||||||
|
scored.append((score, result))
|
||||||
|
|
||||||
|
scored.sort(key=lambda x: x[0], reverse=True)
|
||||||
|
return scored[0][1] if scored and scored[0][0] > 0 else results[0]
|
||||||
|
|
||||||
|
def _extract_results(self, search_result: dict) -> list:
|
||||||
|
"""Extract results list from search result dict."""
|
||||||
|
return search_result.get("results", [])
|
||||||
|
|
||||||
|
def generate(self, query: str, project_name: str = None) -> dict:
|
||||||
|
"""Generate complete design system recommendation."""
|
||||||
|
# Step 1: First search product to get category
|
||||||
|
product_result = search(query, "product", 1)
|
||||||
|
product_results = product_result.get("results", [])
|
||||||
|
category = "General"
|
||||||
|
if product_results:
|
||||||
|
category = product_results[0].get("Product Type", "General")
|
||||||
|
|
||||||
|
# Step 2: Get reasoning rules for this category
|
||||||
|
reasoning = self._apply_reasoning(category, {})
|
||||||
|
style_priority = reasoning.get("style_priority", [])
|
||||||
|
|
||||||
|
# Step 3: Multi-domain search with style priority hints
|
||||||
|
search_results = self._multi_domain_search(query, style_priority)
|
||||||
|
search_results["product"] = product_result # Reuse product search
|
||||||
|
|
||||||
|
# Step 4: Select best matches from each domain using priority
|
||||||
|
style_results = self._extract_results(search_results.get("style", {}))
|
||||||
|
color_results = self._extract_results(search_results.get("color", {}))
|
||||||
|
typography_results = self._extract_results(search_results.get("typography", {}))
|
||||||
|
landing_results = self._extract_results(search_results.get("landing", {}))
|
||||||
|
|
||||||
|
best_style = self._select_best_match(style_results, reasoning.get("style_priority", []))
|
||||||
|
best_color = color_results[0] if color_results else {}
|
||||||
|
best_typography = typography_results[0] if typography_results else {}
|
||||||
|
best_landing = landing_results[0] if landing_results else {}
|
||||||
|
|
||||||
|
# Step 5: Build final recommendation
|
||||||
|
# Combine effects from both reasoning and style search
|
||||||
|
style_effects = best_style.get("Effects & Animation", "")
|
||||||
|
reasoning_effects = reasoning.get("key_effects", "")
|
||||||
|
combined_effects = style_effects if style_effects else reasoning_effects
|
||||||
|
|
||||||
|
return {
|
||||||
|
"project_name": project_name or query.upper(),
|
||||||
|
"category": category,
|
||||||
|
"pattern": {
|
||||||
|
"name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
|
||||||
|
"sections": best_landing.get("Section Order", "Hero > Features > CTA"),
|
||||||
|
"cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),
|
||||||
|
"color_strategy": best_landing.get("Color Strategy", ""),
|
||||||
|
"conversion": best_landing.get("Conversion Optimization", "")
|
||||||
|
},
|
||||||
|
"style": {
|
||||||
|
"name": best_style.get("Style Category", "Minimalism"),
|
||||||
|
"type": best_style.get("Type", "General"),
|
||||||
|
"effects": style_effects,
|
||||||
|
"keywords": best_style.get("Keywords", ""),
|
||||||
|
"best_for": best_style.get("Best For", ""),
|
||||||
|
"performance": best_style.get("Performance", ""),
|
||||||
|
"accessibility": best_style.get("Accessibility", "")
|
||||||
|
},
|
||||||
|
"colors": {
|
||||||
|
"primary": best_color.get("Primary (Hex)", "#2563EB"),
|
||||||
|
"secondary": best_color.get("Secondary (Hex)", "#3B82F6"),
|
||||||
|
"cta": best_color.get("CTA (Hex)", "#F97316"),
|
||||||
|
"background": best_color.get("Background (Hex)", "#F8FAFC"),
|
||||||
|
"text": best_color.get("Text (Hex)", "#1E293B"),
|
||||||
|
"notes": best_color.get("Notes", "")
|
||||||
|
},
|
||||||
|
"typography": {
|
||||||
|
"heading": best_typography.get("Heading Font", "Inter"),
|
||||||
|
"body": best_typography.get("Body Font", "Inter"),
|
||||||
|
"mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
|
||||||
|
"best_for": best_typography.get("Best For", ""),
|
||||||
|
"google_fonts_url": best_typography.get("Google Fonts URL", ""),
|
||||||
|
"css_import": best_typography.get("CSS Import", "")
|
||||||
|
},
|
||||||
|
"key_effects": combined_effects,
|
||||||
|
"anti_patterns": reasoning.get("anti_patterns", ""),
|
||||||
|
"decision_rules": reasoning.get("decision_rules", {}),
|
||||||
|
"severity": reasoning.get("severity", "MEDIUM")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ OUTPUT FORMATTERS ============
|
||||||
|
BOX_WIDTH = 90 # Wider box for more content
|
||||||
|
|
||||||
|
def format_ascii_box(design_system: dict) -> str:
|
||||||
|
"""Format design system as ASCII box with emojis (MCP-style)."""
|
||||||
|
project = design_system.get("project_name", "PROJECT")
|
||||||
|
pattern = design_system.get("pattern", {})
|
||||||
|
style = design_system.get("style", {})
|
||||||
|
colors = design_system.get("colors", {})
|
||||||
|
typography = design_system.get("typography", {})
|
||||||
|
effects = design_system.get("key_effects", "")
|
||||||
|
anti_patterns = design_system.get("anti_patterns", "")
|
||||||
|
|
||||||
|
def wrap_text(text: str, prefix: str, width: int) -> list:
|
||||||
|
"""Wrap long text into multiple lines."""
|
||||||
|
if not text:
|
||||||
|
return []
|
||||||
|
words = text.split()
|
||||||
|
lines = []
|
||||||
|
current_line = prefix
|
||||||
|
for word in words:
|
||||||
|
if len(current_line) + len(word) + 1 <= width - 2:
|
||||||
|
current_line += (" " if current_line != prefix else "") + word
|
||||||
|
else:
|
||||||
|
if current_line != prefix:
|
||||||
|
lines.append(current_line)
|
||||||
|
current_line = prefix + word
|
||||||
|
if current_line != prefix:
|
||||||
|
lines.append(current_line)
|
||||||
|
return lines
|
||||||
|
|
||||||
|
# Build sections from pattern
|
||||||
|
sections = pattern.get("sections", "").split(">")
|
||||||
|
sections = [s.strip() for s in sections if s.strip()]
|
||||||
|
|
||||||
|
# Build output lines
|
||||||
|
lines = []
|
||||||
|
w = BOX_WIDTH - 1
|
||||||
|
|
||||||
|
lines.append("+" + "-" * w + "+")
|
||||||
|
lines.append(f"| TARGET: {project} - RECOMMENDED DESIGN SYSTEM".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("+" + "-" * w + "+")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Pattern section
|
||||||
|
lines.append(f"| PATTERN: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if pattern.get('conversion'):
|
||||||
|
lines.append(f"| Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if pattern.get('cta_placement'):
|
||||||
|
lines.append(f"| CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("| Sections:".ljust(BOX_WIDTH) + "|")
|
||||||
|
for i, section in enumerate(sections, 1):
|
||||||
|
lines.append(f"| {i}. {section}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Style section
|
||||||
|
lines.append(f"| STYLE: {style.get('name', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if style.get("keywords"):
|
||||||
|
for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
if style.get("best_for"):
|
||||||
|
for line in wrap_text(f"Best For: {style.get('best_for', '')}", "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
if style.get("performance") or style.get("accessibility"):
|
||||||
|
perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}"
|
||||||
|
lines.append(f"| {perf_a11y}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Colors section
|
||||||
|
lines.append("| COLORS:".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append(f"| Primary: {colors.get('primary', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append(f"| Secondary: {colors.get('secondary', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append(f"| CTA: {colors.get('cta', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append(f"| Background: {colors.get('background', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append(f"| Text: {colors.get('text', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if colors.get("notes"):
|
||||||
|
for line in wrap_text(f"Notes: {colors.get('notes', '')}", "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Typography section
|
||||||
|
lines.append(f"| TYPOGRAPHY: {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if typography.get("mood"):
|
||||||
|
for line in wrap_text(f"Mood: {typography.get('mood', '')}", "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
if typography.get("best_for"):
|
||||||
|
for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
if typography.get("google_fonts_url"):
|
||||||
|
lines.append(f"| Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "|")
|
||||||
|
if typography.get("css_import"):
|
||||||
|
lines.append(f"| CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Key Effects section
|
||||||
|
if effects:
|
||||||
|
lines.append("| KEY EFFECTS:".ljust(BOX_WIDTH) + "|")
|
||||||
|
for line in wrap_text(effects, "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Anti-patterns section
|
||||||
|
if anti_patterns:
|
||||||
|
lines.append("| AVOID (Anti-patterns):".ljust(BOX_WIDTH) + "|")
|
||||||
|
for line in wrap_text(anti_patterns, "| ", BOX_WIDTH):
|
||||||
|
lines.append(line.ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
# Pre-Delivery Checklist section
|
||||||
|
lines.append("| PRE-DELIVERY CHECKLIST:".ljust(BOX_WIDTH) + "|")
|
||||||
|
checklist_items = [
|
||||||
|
"[ ] No emojis as icons (use SVG: Heroicons/Lucide)",
|
||||||
|
"[ ] cursor-pointer on all clickable elements",
|
||||||
|
"[ ] Hover states with smooth transitions (150-300ms)",
|
||||||
|
"[ ] Light mode: text contrast 4.5:1 minimum",
|
||||||
|
"[ ] Focus states visible for keyboard nav",
|
||||||
|
"[ ] prefers-reduced-motion respected",
|
||||||
|
"[ ] Responsive: 375px, 768px, 1024px, 1440px"
|
||||||
|
]
|
||||||
|
for item in checklist_items:
|
||||||
|
lines.append(f"| {item}".ljust(BOX_WIDTH) + "|")
|
||||||
|
lines.append("|" + " " * BOX_WIDTH + "|")
|
||||||
|
|
||||||
|
lines.append("+" + "-" * w + "+")
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def format_markdown(design_system: dict) -> str:
|
||||||
|
"""Format design system as markdown."""
|
||||||
|
project = design_system.get("project_name", "PROJECT")
|
||||||
|
pattern = design_system.get("pattern", {})
|
||||||
|
style = design_system.get("style", {})
|
||||||
|
colors = design_system.get("colors", {})
|
||||||
|
typography = design_system.get("typography", {})
|
||||||
|
effects = design_system.get("key_effects", "")
|
||||||
|
anti_patterns = design_system.get("anti_patterns", "")
|
||||||
|
|
||||||
|
lines = []
|
||||||
|
lines.append(f"## Design System: {project}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Pattern section
|
||||||
|
lines.append("### Pattern")
|
||||||
|
lines.append(f"- **Name:** {pattern.get('name', '')}")
|
||||||
|
if pattern.get('conversion'):
|
||||||
|
lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}")
|
||||||
|
if pattern.get('cta_placement'):
|
||||||
|
lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
|
||||||
|
if pattern.get('color_strategy'):
|
||||||
|
lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}")
|
||||||
|
lines.append(f"- **Sections:** {pattern.get('sections', '')}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Style section
|
||||||
|
lines.append("### Style")
|
||||||
|
lines.append(f"- **Name:** {style.get('name', '')}")
|
||||||
|
if style.get('keywords'):
|
||||||
|
lines.append(f"- **Keywords:** {style.get('keywords', '')}")
|
||||||
|
if style.get('best_for'):
|
||||||
|
lines.append(f"- **Best For:** {style.get('best_for', '')}")
|
||||||
|
if style.get('performance') or style.get('accessibility'):
|
||||||
|
lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Colors section
|
||||||
|
lines.append("### Colors")
|
||||||
|
lines.append(f"| Role | Hex |")
|
||||||
|
lines.append(f"|------|-----|")
|
||||||
|
lines.append(f"| Primary | {colors.get('primary', '')} |")
|
||||||
|
lines.append(f"| Secondary | {colors.get('secondary', '')} |")
|
||||||
|
lines.append(f"| CTA | {colors.get('cta', '')} |")
|
||||||
|
lines.append(f"| Background | {colors.get('background', '')} |")
|
||||||
|
lines.append(f"| Text | {colors.get('text', '')} |")
|
||||||
|
if colors.get("notes"):
|
||||||
|
lines.append(f"\n*Notes: {colors.get('notes', '')}*")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Typography section
|
||||||
|
lines.append("### Typography")
|
||||||
|
lines.append(f"- **Heading:** {typography.get('heading', '')}")
|
||||||
|
lines.append(f"- **Body:** {typography.get('body', '')}")
|
||||||
|
if typography.get("mood"):
|
||||||
|
lines.append(f"- **Mood:** {typography.get('mood', '')}")
|
||||||
|
if typography.get("best_for"):
|
||||||
|
lines.append(f"- **Best For:** {typography.get('best_for', '')}")
|
||||||
|
if typography.get("google_fonts_url"):
|
||||||
|
lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}")
|
||||||
|
if typography.get("css_import"):
|
||||||
|
lines.append(f"- **CSS Import:**")
|
||||||
|
lines.append(f"```css")
|
||||||
|
lines.append(f"{typography.get('css_import', '')}")
|
||||||
|
lines.append(f"```")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Key Effects section
|
||||||
|
if effects:
|
||||||
|
lines.append("### Key Effects")
|
||||||
|
lines.append(f"{effects}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Anti-patterns section
|
||||||
|
if anti_patterns:
|
||||||
|
lines.append("### Avoid (Anti-patterns)")
|
||||||
|
lines.append(f"- {anti_patterns.replace(' + ', '\n- ')}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
# Pre-Delivery Checklist section
|
||||||
|
lines.append("### Pre-Delivery Checklist")
|
||||||
|
lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)")
|
||||||
|
lines.append("- [ ] cursor-pointer on all clickable elements")
|
||||||
|
lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
|
||||||
|
lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
|
||||||
|
lines.append("- [ ] Focus states visible for keyboard nav")
|
||||||
|
lines.append("- [ ] prefers-reduced-motion respected")
|
||||||
|
lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
# ============ MAIN ENTRY POINT ============
|
||||||
|
def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii") -> str:
|
||||||
|
"""
|
||||||
|
Main entry point for design system generation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query: Search query (e.g., "SaaS dashboard", "e-commerce luxury")
|
||||||
|
project_name: Optional project name for output header
|
||||||
|
output_format: "ascii" (default) or "markdown"
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Formatted design system string
|
||||||
|
"""
|
||||||
|
generator = DesignSystemGenerator()
|
||||||
|
design_system = generator.generate(query, project_name)
|
||||||
|
|
||||||
|
if output_format == "markdown":
|
||||||
|
return format_markdown(design_system)
|
||||||
|
return format_ascii_box(design_system)
|
||||||
|
|
||||||
|
|
||||||
|
# ============ CLI SUPPORT ============
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Generate Design System")
|
||||||
|
parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')")
|
||||||
|
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name")
|
||||||
|
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
result = generate_design_system(args.query, args.project_name, args.format)
|
||||||
|
print(result)
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
"""
|
"""
|
||||||
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
||||||
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
||||||
|
python search.py "<query>" --design-system [-p "Project Name"]
|
||||||
|
|
||||||
Domains: style, prompt, color, chart, landing, product, ux, typography
|
Domains: style, prompt, color, chart, landing, product, ux, typography
|
||||||
Stacks: html-tailwind, react, nextjs
|
Stacks: html-tailwind, react, nextjs
|
||||||
@@ -10,6 +11,7 @@ Stacks: html-tailwind, react, nextjs
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
|
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
|
||||||
|
from design_system import generate_design_system
|
||||||
|
|
||||||
|
|
||||||
def format_output(result):
|
def format_output(result):
|
||||||
@@ -45,17 +47,30 @@ if __name__ == "__main__":
|
|||||||
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)")
|
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)")
|
||||||
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
|
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
|
||||||
parser.add_argument("--json", action="store_true", help="Output as JSON")
|
parser.add_argument("--json", action="store_true", help="Output as JSON")
|
||||||
|
# Design system generation
|
||||||
|
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
|
||||||
|
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
|
||||||
|
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# Stack search takes priority
|
# Design system takes priority
|
||||||
if args.stack:
|
if args.design_system:
|
||||||
|
result = generate_design_system(args.query, args.project_name, args.format)
|
||||||
|
print(result)
|
||||||
|
# Stack search
|
||||||
|
elif args.stack:
|
||||||
result = search_stack(args.query, args.stack, args.max_results)
|
result = search_stack(args.query, args.stack, args.max_results)
|
||||||
|
if args.json:
|
||||||
|
import json
|
||||||
|
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
print(format_output(result))
|
||||||
|
# Domain search
|
||||||
else:
|
else:
|
||||||
result = search(args.query, args.domain, args.max_results)
|
result = search(args.query, args.domain, args.max_results)
|
||||||
|
if args.json:
|
||||||
if args.json:
|
import json
|
||||||
import json
|
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
else:
|
||||||
else:
|
print(format_output(result))
|
||||||
print(format_output(result))
|
|
||||||
|
|||||||
705
skills/workflow-automation/SKILL.md
Normal file
705
skills/workflow-automation/SKILL.md
Normal file
@@ -0,0 +1,705 @@
|
|||||||
|
---
|
||||||
|
name: workflow-automation
|
||||||
|
description: "Design and implement automated workflows combining visual logic with custom code. Create multi-step automations, integrate APIs, and build AI-native pipelines. Use when designing automation flows, integrating APIs, building event-driven systems, or creating LangChain-style AI workflows."
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🔄 Workflow Automation
|
||||||
|
|
||||||
|
> Patterns for building robust automated workflows, inspired by [n8n](https://github.com/n8n-io/n8n) and modern automation platforms.
|
||||||
|
|
||||||
|
## When to Use This Skill
|
||||||
|
|
||||||
|
Use this skill when:
|
||||||
|
|
||||||
|
- Designing multi-step automation workflows
|
||||||
|
- Integrating multiple APIs and services
|
||||||
|
- Building event-driven systems
|
||||||
|
- Creating AI-augmented pipelines
|
||||||
|
- Handling errors in complex flows
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Workflow Design Principles
|
||||||
|
|
||||||
|
### 1.1 Core Concepts
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ WORKFLOW │
|
||||||
|
│ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ │
|
||||||
|
│ │Trigger │───▶│ Node │───▶│ Node │───▶│ Action │ │
|
||||||
|
│ └────────┘ └────────┘ └────────┘ └────────┘ │
|
||||||
|
│ │ │ │ │ │
|
||||||
|
│ ▼ ▼ ▼ ▼ │
|
||||||
|
│ [Webhook] [Transform] [Condition] [Send Email] │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Components**:
|
||||||
|
|
||||||
|
- **Trigger**: What starts the workflow
|
||||||
|
- **Node**: Individual processing step
|
||||||
|
- **Edge**: Connection between nodes
|
||||||
|
- **Action**: External effect (API call, email, etc.)
|
||||||
|
|
||||||
|
### 1.2 Trigger Types
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const TRIGGER_TYPES = {
|
||||||
|
// Event-based
|
||||||
|
webhook: {
|
||||||
|
description: "HTTP request triggers workflow",
|
||||||
|
use_case: "External integrations, form submissions",
|
||||||
|
example: "POST /webhook/order-created",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Time-based
|
||||||
|
cron: {
|
||||||
|
description: "Scheduled execution",
|
||||||
|
use_case: "Reports, cleanup, sync jobs",
|
||||||
|
example: "0 9 * * *", // Daily at 9 AM
|
||||||
|
},
|
||||||
|
|
||||||
|
// Change-based
|
||||||
|
polling: {
|
||||||
|
description: "Check for changes periodically",
|
||||||
|
use_case: "Monitor RSS, check file changes",
|
||||||
|
example: "Every 5 minutes check for new items",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Message-based
|
||||||
|
queue: {
|
||||||
|
description: "Process from message queue",
|
||||||
|
use_case: "Async processing, decoupling",
|
||||||
|
example: "SQS, RabbitMQ, Redis Streams",
|
||||||
|
},
|
||||||
|
|
||||||
|
// Manual
|
||||||
|
manual: {
|
||||||
|
description: "User-initiated execution",
|
||||||
|
use_case: "Testing, on-demand tasks",
|
||||||
|
example: "Run workflow button",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 Node Types
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const NODE_TYPES = {
|
||||||
|
// Data transformation
|
||||||
|
transform: {
|
||||||
|
description: "Modify data shape or values",
|
||||||
|
operations: ["map", "filter", "merge", "split"],
|
||||||
|
},
|
||||||
|
|
||||||
|
// Flow control
|
||||||
|
condition: {
|
||||||
|
description: "Branch based on logic",
|
||||||
|
operations: ["if/else", "switch", "filter"],
|
||||||
|
},
|
||||||
|
|
||||||
|
// External actions
|
||||||
|
action: {
|
||||||
|
description: "Interact with external services",
|
||||||
|
operations: ["HTTP request", "database", "email", "API"],
|
||||||
|
},
|
||||||
|
|
||||||
|
// Sub-workflows
|
||||||
|
subworkflow: {
|
||||||
|
description: "Call another workflow",
|
||||||
|
operations: ["invoke", "wait", "parallel"],
|
||||||
|
},
|
||||||
|
|
||||||
|
// Error handling
|
||||||
|
errorHandler: {
|
||||||
|
description: "Handle failures gracefully",
|
||||||
|
operations: ["retry", "fallback", "notify"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Common Workflow Patterns
|
||||||
|
|
||||||
|
### 2.1 Sequential Pipeline
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Simple A → B → C flow
|
||||||
|
const sequentialWorkflow = {
|
||||||
|
trigger: { type: "webhook", path: "/process" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "fetch",
|
||||||
|
type: "http",
|
||||||
|
config: {
|
||||||
|
method: "GET",
|
||||||
|
url: "{{trigger.data.api_url}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "transform",
|
||||||
|
type: "code",
|
||||||
|
config: {
|
||||||
|
code: `
|
||||||
|
return items.map(item => ({
|
||||||
|
id: item.id,
|
||||||
|
name: item.name.toUpperCase(),
|
||||||
|
processed: true
|
||||||
|
}));
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "save",
|
||||||
|
type: "database",
|
||||||
|
config: {
|
||||||
|
operation: "insert",
|
||||||
|
table: "processed_items",
|
||||||
|
data: "{{transform.output}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Parallel Execution
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Fan-out: Execute multiple nodes in parallel
|
||||||
|
const parallelWorkflow = {
|
||||||
|
trigger: { type: "cron", schedule: "0 * * * *" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "parallel_group",
|
||||||
|
type: "parallel",
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "fetch_users",
|
||||||
|
type: "http",
|
||||||
|
config: { url: "/api/users" },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "fetch_orders",
|
||||||
|
type: "http",
|
||||||
|
config: { url: "/api/orders" },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "fetch_products",
|
||||||
|
type: "http",
|
||||||
|
config: { url: "/api/products" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "merge",
|
||||||
|
type: "merge",
|
||||||
|
config: {
|
||||||
|
method: "append", // or "combine", "zip"
|
||||||
|
inputs: ["fetch_users", "fetch_orders", "fetch_products"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Conditional Branching
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const conditionalWorkflow = {
|
||||||
|
trigger: { type: "webhook", path: "/order" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "check_value",
|
||||||
|
type: "switch",
|
||||||
|
config: {
|
||||||
|
property: "{{trigger.data.total}}",
|
||||||
|
rules: [
|
||||||
|
{ operator: "gte", value: 1000, output: "high_value" },
|
||||||
|
{ operator: "gte", value: 100, output: "medium_value" },
|
||||||
|
{ operator: "lt", value: 100, output: "low_value" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "high_value",
|
||||||
|
type: "action",
|
||||||
|
onlyIf: "{{check_value.output}} === 'high_value'",
|
||||||
|
config: {
|
||||||
|
action: "notify_sales_team",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "medium_value",
|
||||||
|
type: "action",
|
||||||
|
onlyIf: "{{check_value.output}} === 'medium_value'",
|
||||||
|
config: {
|
||||||
|
action: "send_thank_you_email",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "low_value",
|
||||||
|
type: "action",
|
||||||
|
onlyIf: "{{check_value.output}} === 'low_value'",
|
||||||
|
config: {
|
||||||
|
action: "add_to_newsletter",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 Loop/Iterator Pattern
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const loopWorkflow = {
|
||||||
|
trigger: { type: "manual" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "fetch_items",
|
||||||
|
type: "http",
|
||||||
|
config: { url: "/api/items" },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "process_each",
|
||||||
|
type: "loop",
|
||||||
|
config: {
|
||||||
|
items: "{{fetch_items.data}}",
|
||||||
|
batchSize: 10, // Process 10 at a time
|
||||||
|
continueOnError: true,
|
||||||
|
},
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "enrich",
|
||||||
|
type: "http",
|
||||||
|
config: {
|
||||||
|
url: "/api/enrich/{{item.id}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "save",
|
||||||
|
type: "database",
|
||||||
|
config: {
|
||||||
|
operation: "update",
|
||||||
|
id: "{{item.id}}",
|
||||||
|
data: "{{enrich.output}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.5 Wait/Delay Pattern
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const waitWorkflow = {
|
||||||
|
trigger: { type: "webhook", path: "/signup" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "send_welcome",
|
||||||
|
type: "email",
|
||||||
|
config: {
|
||||||
|
to: "{{trigger.data.email}}",
|
||||||
|
template: "welcome",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "wait_24h",
|
||||||
|
type: "wait",
|
||||||
|
config: {
|
||||||
|
duration: "24h",
|
||||||
|
// Or: resumeAt: "{{trigger.data.preferred_time}}"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "send_onboarding",
|
||||||
|
type: "email",
|
||||||
|
config: {
|
||||||
|
to: "{{trigger.data.email}}",
|
||||||
|
template: "onboarding_tips",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Error Handling Patterns
|
||||||
|
|
||||||
|
### 3.1 Retry with Backoff
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const retryConfig = {
|
||||||
|
retries: 3,
|
||||||
|
backoff: "exponential", // linear, exponential, fixed
|
||||||
|
initialDelay: 1000, // ms
|
||||||
|
maxDelay: 30000, // ms
|
||||||
|
retryOn: ["ECONNRESET", "ETIMEDOUT", "HTTP_5XX"],
|
||||||
|
};
|
||||||
|
|
||||||
|
const nodeWithRetry = {
|
||||||
|
id: "api_call",
|
||||||
|
type: "http",
|
||||||
|
config: { url: "/api/external" },
|
||||||
|
errorHandling: {
|
||||||
|
retry: retryConfig,
|
||||||
|
onMaxRetries: {
|
||||||
|
action: "continue", // or "fail", "branch"
|
||||||
|
fallbackValue: { data: [] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Dead Letter Queue
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const workflowWithDLQ = {
|
||||||
|
config: {
|
||||||
|
onError: {
|
||||||
|
action: "send_to_dlq",
|
||||||
|
queue: "failed_workflows",
|
||||||
|
includeContext: true, // Include full workflow state
|
||||||
|
},
|
||||||
|
},
|
||||||
|
nodes: [
|
||||||
|
/* ... */
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Separate workflow to process failed items
|
||||||
|
const dlqProcessor = {
|
||||||
|
trigger: {
|
||||||
|
type: "queue",
|
||||||
|
queue: "failed_workflows",
|
||||||
|
},
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "analyze",
|
||||||
|
type: "code",
|
||||||
|
config: {
|
||||||
|
code: `
|
||||||
|
const error = $input.error;
|
||||||
|
const context = $input.context;
|
||||||
|
|
||||||
|
// Classify error
|
||||||
|
if (error.type === 'VALIDATION') {
|
||||||
|
return { action: 'discard', reason: 'Bad data' };
|
||||||
|
}
|
||||||
|
if (error.type === 'RATE_LIMIT') {
|
||||||
|
return { action: 'retry', delay: '1h' };
|
||||||
|
}
|
||||||
|
return { action: 'manual_review' };
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Compensation/Rollback
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const sagaWorkflow = {
|
||||||
|
name: "order_saga",
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "reserve_inventory",
|
||||||
|
type: "api",
|
||||||
|
compensate: {
|
||||||
|
id: "release_inventory",
|
||||||
|
type: "api",
|
||||||
|
config: { method: "POST", url: "/inventory/release" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "charge_payment",
|
||||||
|
type: "api",
|
||||||
|
compensate: {
|
||||||
|
id: "refund_payment",
|
||||||
|
type: "api",
|
||||||
|
config: { method: "POST", url: "/payments/refund" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "create_shipment",
|
||||||
|
type: "api",
|
||||||
|
compensate: {
|
||||||
|
id: "cancel_shipment",
|
||||||
|
type: "api",
|
||||||
|
config: { method: "POST", url: "/shipments/cancel" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
onError: {
|
||||||
|
strategy: "compensate_all", // Run all compensations in reverse order
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Integration Patterns
|
||||||
|
|
||||||
|
### 4.1 API Integration Template
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const apiIntegration = {
|
||||||
|
name: "github_integration",
|
||||||
|
baseUrl: "https://api.github.com",
|
||||||
|
auth: {
|
||||||
|
type: "bearer",
|
||||||
|
token: "{{secrets.GITHUB_TOKEN}}",
|
||||||
|
},
|
||||||
|
operations: {
|
||||||
|
listRepos: {
|
||||||
|
method: "GET",
|
||||||
|
path: "/user/repos",
|
||||||
|
params: {
|
||||||
|
per_page: 100,
|
||||||
|
sort: "updated",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
createIssue: {
|
||||||
|
method: "POST",
|
||||||
|
path: "/repos/{{owner}}/{{repo}}/issues",
|
||||||
|
body: {
|
||||||
|
title: "{{title}}",
|
||||||
|
body: "{{body}}",
|
||||||
|
labels: "{{labels}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rateLimiting: {
|
||||||
|
requests: 5000,
|
||||||
|
period: "1h",
|
||||||
|
strategy: "queue", // queue, reject, throttle
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Webhook Handler
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const webhookHandler = {
|
||||||
|
trigger: {
|
||||||
|
type: "webhook",
|
||||||
|
path: "/webhooks/stripe",
|
||||||
|
method: "POST",
|
||||||
|
authentication: {
|
||||||
|
type: "signature",
|
||||||
|
header: "stripe-signature",
|
||||||
|
secret: "{{secrets.STRIPE_WEBHOOK_SECRET}}",
|
||||||
|
algorithm: "sha256",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "validate",
|
||||||
|
type: "code",
|
||||||
|
config: {
|
||||||
|
code: `
|
||||||
|
const event = $input.body;
|
||||||
|
if (!['checkout.session.completed',
|
||||||
|
'payment_intent.succeeded'].includes(event.type)) {
|
||||||
|
return { skip: true };
|
||||||
|
}
|
||||||
|
return event;
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "route",
|
||||||
|
type: "switch",
|
||||||
|
config: {
|
||||||
|
property: "{{validate.type}}",
|
||||||
|
routes: {
|
||||||
|
"checkout.session.completed": "handle_checkout",
|
||||||
|
"payment_intent.succeeded": "handle_payment",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. AI-Native Workflows
|
||||||
|
|
||||||
|
### 5.1 LLM in Pipeline
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const aiWorkflow = {
|
||||||
|
trigger: { type: "webhook", path: "/analyze" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "extract_text",
|
||||||
|
type: "code",
|
||||||
|
config: {
|
||||||
|
code: "return { text: $input.document.content }",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "analyze_sentiment",
|
||||||
|
type: "llm",
|
||||||
|
config: {
|
||||||
|
model: "gpt-4",
|
||||||
|
prompt: `
|
||||||
|
Analyze the sentiment of the following text.
|
||||||
|
Return JSON: {"sentiment": "positive|negative|neutral", "confidence": 0-1}
|
||||||
|
|
||||||
|
Text: {{extract_text.text}}
|
||||||
|
`,
|
||||||
|
responseFormat: "json",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "route_by_sentiment",
|
||||||
|
type: "switch",
|
||||||
|
config: {
|
||||||
|
property: "{{analyze_sentiment.sentiment}}",
|
||||||
|
routes: {
|
||||||
|
negative: "escalate_to_support",
|
||||||
|
positive: "send_thank_you",
|
||||||
|
neutral: "archive",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Agent Workflow
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const agentWorkflow = {
|
||||||
|
trigger: { type: "webhook", path: "/research" },
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "research_agent",
|
||||||
|
type: "agent",
|
||||||
|
config: {
|
||||||
|
model: "gpt-4",
|
||||||
|
tools: ["web_search", "calculator", "code_interpreter"],
|
||||||
|
maxIterations: 10,
|
||||||
|
prompt: `
|
||||||
|
Research the following topic and provide a comprehensive summary:
|
||||||
|
{{trigger.topic}}
|
||||||
|
|
||||||
|
Use the tools available to gather accurate, up-to-date information.
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "format_report",
|
||||||
|
type: "llm",
|
||||||
|
config: {
|
||||||
|
model: "gpt-4",
|
||||||
|
prompt: `
|
||||||
|
Format this research into a professional report with sections:
|
||||||
|
- Executive Summary
|
||||||
|
- Key Findings
|
||||||
|
- Recommendations
|
||||||
|
|
||||||
|
Research: {{research_agent.output}}
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "send_report",
|
||||||
|
type: "email",
|
||||||
|
config: {
|
||||||
|
to: "{{trigger.email}}",
|
||||||
|
subject: "Research Report: {{trigger.topic}}",
|
||||||
|
body: "{{format_report.output}}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Workflow Best Practices
|
||||||
|
|
||||||
|
### 6.1 Design Checklist
|
||||||
|
|
||||||
|
- [ ] **Idempotency**: Can workflow run multiple times safely?
|
||||||
|
- [ ] **Error handling**: What happens when nodes fail?
|
||||||
|
- [ ] **Timeouts**: Are there appropriate timeouts?
|
||||||
|
- [ ] **Logging**: Is there enough observability?
|
||||||
|
- [ ] **Rate limits**: Are external APIs rate-limited?
|
||||||
|
- [ ] **Secrets**: Are credentials stored securely?
|
||||||
|
- [ ] **Testing**: Can workflow be tested in isolation?
|
||||||
|
|
||||||
|
### 6.2 Naming Conventions
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Workflows: verb_noun or noun_verb
|
||||||
|
"sync_customers";
|
||||||
|
"process_orders";
|
||||||
|
"daily_report_generator";
|
||||||
|
|
||||||
|
// Nodes: action_target
|
||||||
|
"fetch_user_data";
|
||||||
|
"transform_to_csv";
|
||||||
|
"send_notification_email";
|
||||||
|
|
||||||
|
// Variables: lowercase_snake_case
|
||||||
|
"order_total";
|
||||||
|
"customer_email";
|
||||||
|
"processing_date";
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 Testing Workflows
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const workflowTest = {
|
||||||
|
name: "order_processing_test",
|
||||||
|
workflow: "process_order",
|
||||||
|
testCases: [
|
||||||
|
{
|
||||||
|
name: "valid_order",
|
||||||
|
input: {
|
||||||
|
order_id: "test-123",
|
||||||
|
items: [{ sku: "A1", qty: 2 }],
|
||||||
|
},
|
||||||
|
expectedOutput: {
|
||||||
|
status: "processed",
|
||||||
|
},
|
||||||
|
mocks: {
|
||||||
|
inventory_check: { available: true },
|
||||||
|
payment_process: { success: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "out_of_stock",
|
||||||
|
input: {
|
||||||
|
order_id: "test-456",
|
||||||
|
items: [{ sku: "B2", qty: 100 }],
|
||||||
|
},
|
||||||
|
expectedOutput: {
|
||||||
|
status: "failed",
|
||||||
|
reason: "insufficient_inventory",
|
||||||
|
},
|
||||||
|
mocks: {
|
||||||
|
inventory_check: { available: false },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Resource Links
|
||||||
|
|
||||||
|
- [n8n Documentation](https://docs.n8n.io/)
|
||||||
|
- [Temporal Workflows](https://temporal.io/)
|
||||||
|
- [Apache Airflow](https://airflow.apache.org/)
|
||||||
|
- [Zapier Automation Patterns](https://zapier.com/blog/automation-patterns/)
|
||||||
@@ -29,30 +29,32 @@ A **skill** is a reference guide for proven techniques, patterns, or tools. Skil
|
|||||||
|
|
||||||
## TDD Mapping for Skills
|
## TDD Mapping for Skills
|
||||||
|
|
||||||
| TDD Concept | Skill Creation |
|
| TDD Concept | Skill Creation |
|
||||||
|-------------|----------------|
|
| ----------------------- | ------------------------------------------------ |
|
||||||
| **Test case** | Pressure scenario with subagent |
|
| **Test case** | Pressure scenario with subagent |
|
||||||
| **Production code** | Skill document (SKILL.md) |
|
| **Production code** | Skill document (SKILL.md) |
|
||||||
| **Test fails (RED)** | Agent violates rule without skill (baseline) |
|
| **Test fails (RED)** | Agent violates rule without skill (baseline) |
|
||||||
| **Test passes (GREEN)** | Agent complies with skill present |
|
| **Test passes (GREEN)** | Agent complies with skill present |
|
||||||
| **Refactor** | Close loopholes while maintaining compliance |
|
| **Refactor** | Close loopholes while maintaining compliance |
|
||||||
| **Write test first** | Run baseline scenario BEFORE writing skill |
|
| **Write test first** | Run baseline scenario BEFORE writing skill |
|
||||||
| **Watch it fail** | Document exact rationalizations agent uses |
|
| **Watch it fail** | Document exact rationalizations agent uses |
|
||||||
| **Minimal code** | Write skill addressing those specific violations |
|
| **Minimal code** | Write skill addressing those specific violations |
|
||||||
| **Watch it pass** | Verify agent now complies |
|
| **Watch it pass** | Verify agent now complies |
|
||||||
| **Refactor cycle** | Find new rationalizations → plug → re-verify |
|
| **Refactor cycle** | Find new rationalizations → plug → re-verify |
|
||||||
|
|
||||||
The entire skill creation process follows RED-GREEN-REFACTOR.
|
The entire skill creation process follows RED-GREEN-REFACTOR.
|
||||||
|
|
||||||
## When to Create a Skill
|
## When to Create a Skill
|
||||||
|
|
||||||
**Create when:**
|
**Create when:**
|
||||||
|
|
||||||
- Technique wasn't intuitively obvious to you
|
- Technique wasn't intuitively obvious to you
|
||||||
- You'd reference this again across projects
|
- You'd reference this again across projects
|
||||||
- Pattern applies broadly (not project-specific)
|
- Pattern applies broadly (not project-specific)
|
||||||
- Others would benefit
|
- Others would benefit
|
||||||
|
|
||||||
**Don't create for:**
|
**Don't create for:**
|
||||||
|
|
||||||
- One-off solutions
|
- One-off solutions
|
||||||
- Standard practices well-documented elsewhere
|
- Standard practices well-documented elsewhere
|
||||||
- Project-specific conventions (put in CLAUDE.md)
|
- Project-specific conventions (put in CLAUDE.md)
|
||||||
@@ -61,17 +63,19 @@ The entire skill creation process follows RED-GREEN-REFACTOR.
|
|||||||
## Skill Types
|
## Skill Types
|
||||||
|
|
||||||
### Technique
|
### Technique
|
||||||
|
|
||||||
Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
|
Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
|
||||||
|
|
||||||
### Pattern
|
### Pattern
|
||||||
|
|
||||||
Way of thinking about problems (flatten-with-flags, test-invariants)
|
Way of thinking about problems (flatten-with-flags, test-invariants)
|
||||||
|
|
||||||
### Reference
|
### Reference
|
||||||
|
|
||||||
API docs, syntax guides, tool documentation (office docs)
|
API docs, syntax guides, tool documentation (office docs)
|
||||||
|
|
||||||
## Directory Structure
|
## Directory Structure
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
skills/
|
skills/
|
||||||
skill-name/
|
skill-name/
|
||||||
@@ -82,17 +86,41 @@ skills/
|
|||||||
**Flat namespace** - all skills in one searchable namespace
|
**Flat namespace** - all skills in one searchable namespace
|
||||||
|
|
||||||
**Separate files for:**
|
**Separate files for:**
|
||||||
|
|
||||||
1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
|
1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
|
||||||
2. **Reusable tools** - Scripts, utilities, templates
|
2. **Reusable tools** - Scripts, utilities, templates
|
||||||
|
|
||||||
**Keep inline:**
|
**Keep inline:**
|
||||||
|
|
||||||
- Principles and concepts
|
- Principles and concepts
|
||||||
- Code patterns (< 50 lines)
|
- Code patterns (< 50 lines)
|
||||||
- Everything else
|
- Everything else
|
||||||
|
|
||||||
|
## Set Appropriate Degrees of Freedom
|
||||||
|
|
||||||
|
Match the level of specificity to the task's fragility and variability:
|
||||||
|
|
||||||
|
- **High freedom (text-based instructions)**: Use when multiple approaches are valid or decisions depend on context.
|
||||||
|
- **Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists but some variation is acceptable.
|
||||||
|
- **Low freedom (specific scripts, no-context instructions)**: Use when operations are fragile, error-prone, or consistency is critical.
|
||||||
|
|
||||||
|
## Progressive Disclosure
|
||||||
|
|
||||||
|
Manage context efficiently by splitting detailed information into separate files:
|
||||||
|
|
||||||
|
1. **Metadata (name + description)**: Always loaded for discovery.
|
||||||
|
2. **SKILL.md body**: Core workflow and high-level guidance. Keep under 500 lines.
|
||||||
|
3. **Bundled resources**:
|
||||||
|
- `scripts/`: Deterministic code/logic.
|
||||||
|
- `references/`: Detailed schemas, API docs, or domain knowledge.
|
||||||
|
- `assets/`: Templates, images, or static files.
|
||||||
|
|
||||||
|
**Pattern**: Link to advanced content or variant-specific details (e.g., `aws.md` vs `gcp.md`) from the main `SKILL.md`.
|
||||||
|
|
||||||
## SKILL.md Structure
|
## SKILL.md Structure
|
||||||
|
|
||||||
**Frontmatter (YAML):**
|
**Frontmatter (YAML):**
|
||||||
|
|
||||||
- Only two fields supported: `name` and `description`
|
- Only two fields supported: `name` and `description`
|
||||||
- Max 1024 characters total
|
- Max 1024 characters total
|
||||||
- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
|
- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
|
||||||
@@ -111,32 +139,38 @@ description: Use when [specific triggering conditions and symptoms]
|
|||||||
# Skill Name
|
# Skill Name
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
What is this? Core principle in 1-2 sentences.
|
What is this? Core principle in 1-2 sentences.
|
||||||
|
|
||||||
## When to Use
|
## When to Use
|
||||||
|
|
||||||
[Small inline flowchart IF decision non-obvious]
|
[Small inline flowchart IF decision non-obvious]
|
||||||
|
|
||||||
Bullet list with SYMPTOMS and use cases
|
Bullet list with SYMPTOMS and use cases
|
||||||
When NOT to use
|
When NOT to use
|
||||||
|
|
||||||
## Core Pattern (for techniques/patterns)
|
## Core Pattern (for techniques/patterns)
|
||||||
|
|
||||||
Before/after code comparison
|
Before/after code comparison
|
||||||
|
|
||||||
## Quick Reference
|
## Quick Reference
|
||||||
|
|
||||||
Table or bullets for scanning common operations
|
Table or bullets for scanning common operations
|
||||||
|
|
||||||
## Implementation
|
## Implementation
|
||||||
|
|
||||||
Inline code for simple patterns
|
Inline code for simple patterns
|
||||||
Link to file for heavy reference or reusable tools
|
Link to file for heavy reference or reusable tools
|
||||||
|
|
||||||
## Common Mistakes
|
## Common Mistakes
|
||||||
|
|
||||||
What goes wrong + fixes
|
What goes wrong + fixes
|
||||||
|
|
||||||
## Real-World Impact (optional)
|
## Real-World Impact (optional)
|
||||||
|
|
||||||
Concrete results
|
Concrete results
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Claude Search Optimization (CSO)
|
## Claude Search Optimization (CSO)
|
||||||
|
|
||||||
**Critical for discovery:** Future Claude needs to FIND your skill
|
**Critical for discovery:** Future Claude needs to FIND your skill
|
||||||
@@ -172,8 +206,9 @@ description: Use when implementing any feature or bugfix, before writing impleme
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Content:**
|
**Content:**
|
||||||
|
|
||||||
- Use concrete triggers, symptoms, and situations that signal this skill applies
|
- Use concrete triggers, symptoms, and situations that signal this skill applies
|
||||||
- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)
|
- Describe the _problem_ (race conditions, inconsistent behavior) not _language-specific symptoms_ (setTimeout, sleep)
|
||||||
- Keep triggers technology-agnostic unless the skill itself is technology-specific
|
- Keep triggers technology-agnostic unless the skill itself is technology-specific
|
||||||
- If skill is technology-specific, make that explicit in the trigger
|
- If skill is technology-specific, make that explicit in the trigger
|
||||||
- Write in third person (injected into system prompt)
|
- Write in third person (injected into system prompt)
|
||||||
@@ -199,6 +234,7 @@ description: Use when using React Router and handling authentication redirects
|
|||||||
### 2. Keyword Coverage
|
### 2. Keyword Coverage
|
||||||
|
|
||||||
Use words Claude would search for:
|
Use words Claude would search for:
|
||||||
|
|
||||||
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
|
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
|
||||||
- Symptoms: "flaky", "hanging", "zombie", "pollution"
|
- Symptoms: "flaky", "hanging", "zombie", "pollution"
|
||||||
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
|
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
|
||||||
@@ -207,6 +243,7 @@ Use words Claude would search for:
|
|||||||
### 3. Descriptive Naming
|
### 3. Descriptive Naming
|
||||||
|
|
||||||
**Use active voice, verb-first:**
|
**Use active voice, verb-first:**
|
||||||
|
|
||||||
- ✅ `creating-skills` not `skill-creation`
|
- ✅ `creating-skills` not `skill-creation`
|
||||||
- ✅ `condition-based-waiting` not `async-test-helpers`
|
- ✅ `condition-based-waiting` not `async-test-helpers`
|
||||||
|
|
||||||
@@ -215,6 +252,7 @@ Use words Claude would search for:
|
|||||||
**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
|
**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
|
||||||
|
|
||||||
**Target word counts:**
|
**Target word counts:**
|
||||||
|
|
||||||
- getting-started workflows: <150 words each
|
- getting-started workflows: <150 words each
|
||||||
- Frequently-loaded skills: <200 words total
|
- Frequently-loaded skills: <200 words total
|
||||||
- Other skills: <500 words (still be concise)
|
- Other skills: <500 words (still be concise)
|
||||||
@@ -222,6 +260,7 @@ Use words Claude would search for:
|
|||||||
**Techniques:**
|
**Techniques:**
|
||||||
|
|
||||||
**Move details to tool help:**
|
**Move details to tool help:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# ❌ BAD: Document all flags in SKILL.md
|
# ❌ BAD: Document all flags in SKILL.md
|
||||||
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
|
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
|
||||||
@@ -231,34 +270,42 @@ search-conversations supports multiple modes and filters. Run --help for details
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use cross-references:**
|
**Use cross-references:**
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# ❌ BAD: Repeat workflow details
|
# ❌ BAD: Repeat workflow details
|
||||||
|
|
||||||
When searching, dispatch subagent with template...
|
When searching, dispatch subagent with template...
|
||||||
[20 lines of repeated instructions]
|
[20 lines of repeated instructions]
|
||||||
|
|
||||||
# ✅ GOOD: Reference other skill
|
# ✅ GOOD: Reference other skill
|
||||||
|
|
||||||
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
|
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
|
||||||
```
|
```
|
||||||
|
|
||||||
**Compress examples:**
|
**Compress examples:**
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
# ❌ BAD: Verbose example (42 words)
|
# ❌ BAD: Verbose example (42 words)
|
||||||
|
|
||||||
your human partner: "How did we handle authentication errors in React Router before?"
|
your human partner: "How did we handle authentication errors in React Router before?"
|
||||||
You: I'll search past conversations for React Router authentication patterns.
|
You: I'll search past conversations for React Router authentication patterns.
|
||||||
[Dispatch subagent with search query: "React Router authentication error handling 401"]
|
[Dispatch subagent with search query: "React Router authentication error handling 401"]
|
||||||
|
|
||||||
# ✅ GOOD: Minimal example (20 words)
|
# ✅ GOOD: Minimal example (20 words)
|
||||||
|
|
||||||
Partner: "How did we handle auth errors in React Router?"
|
Partner: "How did we handle auth errors in React Router?"
|
||||||
You: Searching...
|
You: Searching...
|
||||||
[Dispatch subagent → synthesis]
|
[Dispatch subagent → synthesis]
|
||||||
```
|
```
|
||||||
|
|
||||||
**Eliminate redundancy:**
|
**Eliminate redundancy:**
|
||||||
|
|
||||||
- Don't repeat what's in cross-referenced skills
|
- Don't repeat what's in cross-referenced skills
|
||||||
- Don't explain what's obvious from command
|
- Don't explain what's obvious from command
|
||||||
- Don't include multiple examples of same pattern
|
- Don't include multiple examples of same pattern
|
||||||
|
|
||||||
**Verification:**
|
**Verification:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
wc -w skills/path/SKILL.md
|
wc -w skills/path/SKILL.md
|
||||||
# getting-started workflows: aim for <150 each
|
# getting-started workflows: aim for <150 each
|
||||||
@@ -266,12 +313,14 @@ wc -w skills/path/SKILL.md
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Name by what you DO or core insight:**
|
**Name by what you DO or core insight:**
|
||||||
|
|
||||||
- ✅ `condition-based-waiting` > `async-test-helpers`
|
- ✅ `condition-based-waiting` > `async-test-helpers`
|
||||||
- ✅ `using-skills` not `skill-usage`
|
- ✅ `using-skills` not `skill-usage`
|
||||||
- ✅ `flatten-with-flags` > `data-structure-refactoring`
|
- ✅ `flatten-with-flags` > `data-structure-refactoring`
|
||||||
- ✅ `root-cause-tracing` > `debugging-techniques`
|
- ✅ `root-cause-tracing` > `debugging-techniques`
|
||||||
|
|
||||||
**Gerunds (-ing) work well for processes:**
|
**Gerunds (-ing) work well for processes:**
|
||||||
|
|
||||||
- `creating-skills`, `testing-skills`, `debugging-with-logs`
|
- `creating-skills`, `testing-skills`, `debugging-with-logs`
|
||||||
- Active, describes the action you're taking
|
- Active, describes the action you're taking
|
||||||
|
|
||||||
@@ -280,6 +329,7 @@ wc -w skills/path/SKILL.md
|
|||||||
**When writing documentation that references other skills:**
|
**When writing documentation that references other skills:**
|
||||||
|
|
||||||
Use skill name only, with explicit requirement markers:
|
Use skill name only, with explicit requirement markers:
|
||||||
|
|
||||||
- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
|
- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
|
||||||
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
|
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
|
||||||
- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
|
- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
|
||||||
@@ -303,11 +353,13 @@ digraph when_flowchart {
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use flowcharts ONLY for:**
|
**Use flowcharts ONLY for:**
|
||||||
|
|
||||||
- Non-obvious decision points
|
- Non-obvious decision points
|
||||||
- Process loops where you might stop too early
|
- Process loops where you might stop too early
|
||||||
- "When to use A vs B" decisions
|
- "When to use A vs B" decisions
|
||||||
|
|
||||||
**Never use flowcharts for:**
|
**Never use flowcharts for:**
|
||||||
|
|
||||||
- Reference material → Tables, lists
|
- Reference material → Tables, lists
|
||||||
- Code examples → Markdown blocks
|
- Code examples → Markdown blocks
|
||||||
- Linear instructions → Numbered lists
|
- Linear instructions → Numbered lists
|
||||||
@@ -316,6 +368,7 @@ digraph when_flowchart {
|
|||||||
See @graphviz-conventions.dot for graphviz style rules.
|
See @graphviz-conventions.dot for graphviz style rules.
|
||||||
|
|
||||||
**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
|
**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./render-graphs.js ../some-skill # Each diagram separately
|
./render-graphs.js ../some-skill # Each diagram separately
|
||||||
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
|
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
|
||||||
@@ -326,11 +379,13 @@ See @graphviz-conventions.dot for graphviz style rules.
|
|||||||
**One excellent example beats many mediocre ones**
|
**One excellent example beats many mediocre ones**
|
||||||
|
|
||||||
Choose most relevant language:
|
Choose most relevant language:
|
||||||
|
|
||||||
- Testing techniques → TypeScript/JavaScript
|
- Testing techniques → TypeScript/JavaScript
|
||||||
- System debugging → Shell/Python
|
- System debugging → Shell/Python
|
||||||
- Data processing → Python
|
- Data processing → Python
|
||||||
|
|
||||||
**Good example:**
|
**Good example:**
|
||||||
|
|
||||||
- Complete and runnable
|
- Complete and runnable
|
||||||
- Well-commented explaining WHY
|
- Well-commented explaining WHY
|
||||||
- From real scenario
|
- From real scenario
|
||||||
@@ -338,6 +393,7 @@ Choose most relevant language:
|
|||||||
- Ready to adapt (not generic template)
|
- Ready to adapt (not generic template)
|
||||||
|
|
||||||
**Don't:**
|
**Don't:**
|
||||||
|
|
||||||
- Implement in 5+ languages
|
- Implement in 5+ languages
|
||||||
- Create fill-in-the-blank templates
|
- Create fill-in-the-blank templates
|
||||||
- Write contrived examples
|
- Write contrived examples
|
||||||
@@ -347,21 +403,26 @@ You're good at porting - one great example is enough.
|
|||||||
## File Organization
|
## File Organization
|
||||||
|
|
||||||
### Self-Contained Skill
|
### Self-Contained Skill
|
||||||
|
|
||||||
```
|
```
|
||||||
defense-in-depth/
|
defense-in-depth/
|
||||||
SKILL.md # Everything inline
|
SKILL.md # Everything inline
|
||||||
```
|
```
|
||||||
|
|
||||||
When: All content fits, no heavy reference needed
|
When: All content fits, no heavy reference needed
|
||||||
|
|
||||||
### Skill with Reusable Tool
|
### Skill with Reusable Tool
|
||||||
|
|
||||||
```
|
```
|
||||||
condition-based-waiting/
|
condition-based-waiting/
|
||||||
SKILL.md # Overview + patterns
|
SKILL.md # Overview + patterns
|
||||||
example.ts # Working helpers to adapt
|
example.ts # Working helpers to adapt
|
||||||
```
|
```
|
||||||
|
|
||||||
When: Tool is reusable code, not just narrative
|
When: Tool is reusable code, not just narrative
|
||||||
|
|
||||||
### Skill with Heavy Reference
|
### Skill with Heavy Reference
|
||||||
|
|
||||||
```
|
```
|
||||||
pptx/
|
pptx/
|
||||||
SKILL.md # Overview + workflows
|
SKILL.md # Overview + workflows
|
||||||
@@ -369,6 +430,7 @@ pptx/
|
|||||||
ooxml.md # 500 lines XML structure
|
ooxml.md # 500 lines XML structure
|
||||||
scripts/ # Executable tools
|
scripts/ # Executable tools
|
||||||
```
|
```
|
||||||
|
|
||||||
When: Reference material too large for inline
|
When: Reference material too large for inline
|
||||||
|
|
||||||
## The Iron Law (Same as TDD)
|
## The Iron Law (Same as TDD)
|
||||||
@@ -383,6 +445,7 @@ Write skill before testing? Delete it. Start over.
|
|||||||
Edit skill without testing? Same violation.
|
Edit skill without testing? Same violation.
|
||||||
|
|
||||||
**No exceptions:**
|
**No exceptions:**
|
||||||
|
|
||||||
- Not for "simple additions"
|
- Not for "simple additions"
|
||||||
- Not for "just adding a section"
|
- Not for "just adding a section"
|
||||||
- Not for "documentation updates"
|
- Not for "documentation updates"
|
||||||
@@ -401,6 +464,7 @@ Different skill types need different test approaches:
|
|||||||
**Examples:** TDD, verification-before-completion, designing-before-coding
|
**Examples:** TDD, verification-before-completion, designing-before-coding
|
||||||
|
|
||||||
**Test with:**
|
**Test with:**
|
||||||
|
|
||||||
- Academic questions: Do they understand the rules?
|
- Academic questions: Do they understand the rules?
|
||||||
- Pressure scenarios: Do they comply under stress?
|
- Pressure scenarios: Do they comply under stress?
|
||||||
- Multiple pressures combined: time + sunk cost + exhaustion
|
- Multiple pressures combined: time + sunk cost + exhaustion
|
||||||
@@ -413,6 +477,7 @@ Different skill types need different test approaches:
|
|||||||
**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
|
**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
|
||||||
|
|
||||||
**Test with:**
|
**Test with:**
|
||||||
|
|
||||||
- Application scenarios: Can they apply the technique correctly?
|
- Application scenarios: Can they apply the technique correctly?
|
||||||
- Variation scenarios: Do they handle edge cases?
|
- Variation scenarios: Do they handle edge cases?
|
||||||
- Missing information tests: Do instructions have gaps?
|
- Missing information tests: Do instructions have gaps?
|
||||||
@@ -424,6 +489,7 @@ Different skill types need different test approaches:
|
|||||||
**Examples:** reducing-complexity, information-hiding concepts
|
**Examples:** reducing-complexity, information-hiding concepts
|
||||||
|
|
||||||
**Test with:**
|
**Test with:**
|
||||||
|
|
||||||
- Recognition scenarios: Do they recognize when pattern applies?
|
- Recognition scenarios: Do they recognize when pattern applies?
|
||||||
- Application scenarios: Can they use the mental model?
|
- Application scenarios: Can they use the mental model?
|
||||||
- Counter-examples: Do they know when NOT to apply?
|
- Counter-examples: Do they know when NOT to apply?
|
||||||
@@ -435,6 +501,7 @@ Different skill types need different test approaches:
|
|||||||
**Examples:** API documentation, command references, library guides
|
**Examples:** API documentation, command references, library guides
|
||||||
|
|
||||||
**Test with:**
|
**Test with:**
|
||||||
|
|
||||||
- Retrieval scenarios: Can they find the right information?
|
- Retrieval scenarios: Can they find the right information?
|
||||||
- Application scenarios: Can they use what they found correctly?
|
- Application scenarios: Can they use what they found correctly?
|
||||||
- Gap testing: Are common use cases covered?
|
- Gap testing: Are common use cases covered?
|
||||||
@@ -443,16 +510,16 @@ Different skill types need different test approaches:
|
|||||||
|
|
||||||
## Common Rationalizations for Skipping Testing
|
## Common Rationalizations for Skipping Testing
|
||||||
|
|
||||||
| Excuse | Reality |
|
| Excuse | Reality |
|
||||||
|--------|---------|
|
| ------------------------------ | ---------------------------------------------------------------- |
|
||||||
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
|
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
|
||||||
| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
|
| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
|
||||||
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
|
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
|
||||||
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
|
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
|
||||||
| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
|
| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
|
||||||
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
|
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
|
||||||
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
|
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
|
||||||
| "No time to test" | Deploying untested skill wastes more time fixing it later. |
|
| "No time to test" | Deploying untested skill wastes more time fixing it later. |
|
||||||
|
|
||||||
**All of these mean: Test before deploying. No exceptions.**
|
**All of these mean: Test before deploying. No exceptions.**
|
||||||
|
|
||||||
@@ -477,11 +544,13 @@ Write code before test? Delete it.
|
|||||||
Write code before test? Delete it. Start over.
|
Write code before test? Delete it. Start over.
|
||||||
|
|
||||||
**No exceptions:**
|
**No exceptions:**
|
||||||
|
|
||||||
- Don't keep it as "reference"
|
- Don't keep it as "reference"
|
||||||
- Don't "adapt" it while writing tests
|
- Don't "adapt" it while writing tests
|
||||||
- Don't look at it
|
- Don't look at it
|
||||||
- Delete means delete
|
- Delete means delete
|
||||||
```
|
|
||||||
|
````
|
||||||
</Good>
|
</Good>
|
||||||
|
|
||||||
### Address "Spirit vs Letter" Arguments
|
### Address "Spirit vs Letter" Arguments
|
||||||
@@ -490,7 +559,7 @@ Add foundational principle early:
|
|||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
**Violating the letter of the rules is violating the spirit of the rules.**
|
**Violating the letter of the rules is violating the spirit of the rules.**
|
||||||
```
|
````
|
||||||
|
|
||||||
This cuts off entire class of "I'm following the spirit" rationalizations.
|
This cuts off entire class of "I'm following the spirit" rationalizations.
|
||||||
|
|
||||||
@@ -499,10 +568,10 @@ This cuts off entire class of "I'm following the spirit" rationalizations.
|
|||||||
Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
|
Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
|
||||||
|
|
||||||
```markdown
|
```markdown
|
||||||
| Excuse | Reality |
|
| Excuse | Reality |
|
||||||
|--------|---------|
|
| -------------------------------- | ----------------------------------------------------------------------- |
|
||||||
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
|
||||||
| "I'll test after" | Tests passing immediately prove nothing. |
|
| "I'll test after" | Tests passing immediately prove nothing. |
|
||||||
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
|
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -537,6 +606,7 @@ Follow the TDD cycle:
|
|||||||
### RED: Write Failing Test (Baseline)
|
### RED: Write Failing Test (Baseline)
|
||||||
|
|
||||||
Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
|
Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
|
||||||
|
|
||||||
- What choices did they make?
|
- What choices did they make?
|
||||||
- What rationalizations did they use (verbatim)?
|
- What rationalizations did they use (verbatim)?
|
||||||
- Which pressures triggered violations?
|
- Which pressures triggered violations?
|
||||||
@@ -554,6 +624,7 @@ Run same scenarios WITH skill. Agent should now comply.
|
|||||||
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
|
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
|
||||||
|
|
||||||
**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
|
**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
|
||||||
|
|
||||||
- How to write pressure scenarios
|
- How to write pressure scenarios
|
||||||
- Pressure types (time, sunk cost, authority, exhaustion)
|
- Pressure types (time, sunk cost, authority, exhaustion)
|
||||||
- Plugging holes systematically
|
- Plugging holes systematically
|
||||||
@@ -562,21 +633,26 @@ Agent found new rationalization? Add explicit counter. Re-test until bulletproof
|
|||||||
## Anti-Patterns
|
## Anti-Patterns
|
||||||
|
|
||||||
### ❌ Narrative Example
|
### ❌ Narrative Example
|
||||||
|
|
||||||
"In session 2025-10-03, we found empty projectDir caused..."
|
"In session 2025-10-03, we found empty projectDir caused..."
|
||||||
**Why bad:** Too specific, not reusable
|
**Why bad:** Too specific, not reusable
|
||||||
|
|
||||||
### ❌ Multi-Language Dilution
|
### ❌ Multi-Language Dilution
|
||||||
|
|
||||||
example-js.js, example-py.py, example-go.go
|
example-js.js, example-py.py, example-go.go
|
||||||
**Why bad:** Mediocre quality, maintenance burden
|
**Why bad:** Mediocre quality, maintenance burden
|
||||||
|
|
||||||
### ❌ Code in Flowcharts
|
### ❌ Code in Flowcharts
|
||||||
|
|
||||||
```dot
|
```dot
|
||||||
step1 [label="import fs"];
|
step1 [label="import fs"];
|
||||||
step2 [label="read file"];
|
step2 [label="read file"];
|
||||||
```
|
```
|
||||||
|
|
||||||
**Why bad:** Can't copy-paste, hard to read
|
**Why bad:** Can't copy-paste, hard to read
|
||||||
|
|
||||||
### ❌ Generic Labels
|
### ❌ Generic Labels
|
||||||
|
|
||||||
helper1, helper2, step3, pattern4
|
helper1, helper2, step3, pattern4
|
||||||
**Why bad:** Labels should have semantic meaning
|
**Why bad:** Labels should have semantic meaning
|
||||||
|
|
||||||
@@ -585,6 +661,7 @@ helper1, helper2, step3, pattern4
|
|||||||
**After writing ANY skill, you MUST STOP and complete the deployment process.**
|
**After writing ANY skill, you MUST STOP and complete the deployment process.**
|
||||||
|
|
||||||
**Do NOT:**
|
**Do NOT:**
|
||||||
|
|
||||||
- Create multiple skills in batch without testing each
|
- Create multiple skills in batch without testing each
|
||||||
- Move to next skill before current one is verified
|
- Move to next skill before current one is verified
|
||||||
- Skip testing because "batching is more efficient"
|
- Skip testing because "batching is more efficient"
|
||||||
@@ -598,11 +675,13 @@ Deploying untested skills = deploying untested code. It's a violation of quality
|
|||||||
**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**
|
**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**
|
||||||
|
|
||||||
**RED Phase - Write Failing Test:**
|
**RED Phase - Write Failing Test:**
|
||||||
|
|
||||||
- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
|
- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
|
||||||
- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
|
- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
|
||||||
- [ ] Identify patterns in rationalizations/failures
|
- [ ] Identify patterns in rationalizations/failures
|
||||||
|
|
||||||
**GREEN Phase - Write Minimal Skill:**
|
**GREEN Phase - Write Minimal Skill:**
|
||||||
|
|
||||||
- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
|
- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
|
||||||
- [ ] YAML frontmatter with only name and description (max 1024 chars)
|
- [ ] YAML frontmatter with only name and description (max 1024 chars)
|
||||||
- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
|
- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
|
||||||
@@ -615,6 +694,7 @@ Deploying untested skills = deploying untested code. It's a violation of quality
|
|||||||
- [ ] Run scenarios WITH skill - verify agents now comply
|
- [ ] Run scenarios WITH skill - verify agents now comply
|
||||||
|
|
||||||
**REFACTOR Phase - Close Loopholes:**
|
**REFACTOR Phase - Close Loopholes:**
|
||||||
|
|
||||||
- [ ] Identify NEW rationalizations from testing
|
- [ ] Identify NEW rationalizations from testing
|
||||||
- [ ] Add explicit counters (if discipline skill)
|
- [ ] Add explicit counters (if discipline skill)
|
||||||
- [ ] Build rationalization table from all test iterations
|
- [ ] Build rationalization table from all test iterations
|
||||||
@@ -622,6 +702,7 @@ Deploying untested skills = deploying untested code. It's a violation of quality
|
|||||||
- [ ] Re-test until bulletproof
|
- [ ] Re-test until bulletproof
|
||||||
|
|
||||||
**Quality Checks:**
|
**Quality Checks:**
|
||||||
|
|
||||||
- [ ] Small flowchart only if decision non-obvious
|
- [ ] Small flowchart only if decision non-obvious
|
||||||
- [ ] Quick reference table
|
- [ ] Quick reference table
|
||||||
- [ ] Common mistakes section
|
- [ ] Common mistakes section
|
||||||
@@ -629,6 +710,7 @@ Deploying untested skills = deploying untested code. It's a violation of quality
|
|||||||
- [ ] Supporting files only for tools or heavy reference
|
- [ ] Supporting files only for tools or heavy reference
|
||||||
|
|
||||||
**Deployment:**
|
**Deployment:**
|
||||||
|
|
||||||
- [ ] Commit skill to git and push to your fork (if configured)
|
- [ ] Commit skill to git and push to your fork (if configured)
|
||||||
- [ ] Consider contributing back via PR (if broadly useful)
|
- [ ] Consider contributing back via PR (if broadly useful)
|
||||||
|
|
||||||
@@ -637,10 +719,10 @@ Deploying untested skills = deploying untested code. It's a violation of quality
|
|||||||
How future Claude finds your skill:
|
How future Claude finds your skill:
|
||||||
|
|
||||||
1. **Encounters problem** ("tests are flaky")
|
1. **Encounters problem** ("tests are flaky")
|
||||||
3. **Finds SKILL** (description matches)
|
2. **Finds SKILL** (description matches)
|
||||||
4. **Scans overview** (is this relevant?)
|
3. **Scans overview** (is this relevant?)
|
||||||
5. **Reads patterns** (quick reference table)
|
4. **Reads patterns** (quick reference table)
|
||||||
6. **Loads example** (only when implementing)
|
5. **Loads example** (only when implementing)
|
||||||
|
|
||||||
**Optimize for this flow** - put searchable terms early and often.
|
**Optimize for this flow** - put searchable terms early and often.
|
||||||
|
|
||||||
|
|||||||
@@ -309,7 +309,7 @@
|
|||||||
"id": "ui-ux-pro-max",
|
"id": "ui-ux-pro-max",
|
||||||
"path": "skills/ui-ux-pro-max",
|
"path": "skills/ui-ux-pro-max",
|
||||||
"name": "ui-ux-pro-max",
|
"name": "ui-ux-pro-max",
|
||||||
"description": "\"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient.\""
|
"description": "UI/UX design intelligence with v2.0 Design System Generator. 57 UI styles, 97 color palettes, 57 font pairings, 25 chart types, 100 industry-specific reasoning rules across 11 tech stacks (React, Next.js, Vue, Nuxt.js, Nuxt UI, Svelte, SwiftUI, React Native, Flutter, Tailwind, shadcn/ui). NEW: --design-system flag generates complete design systems with pattern + style + colors + typography + effects + anti-patterns. Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code, generate design system. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, soft UI, AI-native. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, design system generation."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "using-git-worktrees",
|
"id": "using-git-worktrees",
|
||||||
@@ -370,5 +370,59 @@
|
|||||||
"path": "skills/xlsx-official",
|
"path": "skills/xlsx-official",
|
||||||
"name": "xlsx",
|
"name": "xlsx",
|
||||||
"description": "\"Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas\""
|
"description": "\"Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas\""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "prompt-library",
|
||||||
|
"path": "skills/prompt-library",
|
||||||
|
"name": "prompt-library",
|
||||||
|
"description": "Curated collection of high-quality prompts for various use cases. Includes role-based prompts, task-specific templates, and prompt refinement techniques. Use when user needs prompt templates, role-play prompts, or ready-to-use prompt examples for coding, writing, analysis, or creative tasks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "javascript-mastery",
|
||||||
|
"path": "skills/javascript-mastery",
|
||||||
|
"name": "javascript-mastery",
|
||||||
|
"description": "Comprehensive JavaScript reference covering 33+ essential concepts every developer should know. From fundamentals like primitives and closures to advanced patterns like async/await and functional programming. Use when explaining JS concepts, debugging JavaScript issues, or teaching JavaScript fundamentals."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "llm-app-patterns",
|
||||||
|
"path": "skills/llm-app-patterns",
|
||||||
|
"name": "llm-app-patterns",
|
||||||
|
"description": "Production-ready patterns for building LLM applications. Covers RAG pipelines, agent architectures, prompt IDEs, and LLMOps monitoring. Use when designing AI applications, implementing RAG, building agents, or setting up LLM observability."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "workflow-automation",
|
||||||
|
"path": "skills/workflow-automation",
|
||||||
|
"name": "workflow-automation",
|
||||||
|
"description": "Design and implement automated workflows combining visual logic with custom code. Create multi-step automations, integrate APIs, and build AI-native pipelines. Use when designing automation flows, integrating APIs, building event-driven systems, or creating LangChain-style AI workflows."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "autonomous-agent-patterns",
|
||||||
|
"path": "skills/autonomous-agent-patterns",
|
||||||
|
"name": "autonomous-agent-patterns",
|
||||||
|
"description": "Design patterns for building autonomous coding agents. Covers tool integration, permission systems, browser automation, and human-in-the-loop workflows. Use when building AI agents, designing tool APIs, implementing permission systems, or creating autonomous coding assistants."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bun-development",
|
||||||
|
"path": "skills/bun-development",
|
||||||
|
"name": "bun-development",
|
||||||
|
"description": "Modern JavaScript/TypeScript development with Bun runtime. Covers package management, bundling, testing, and migration from Node.js. Use when working with Bun, optimizing JS/TS development speed, or migrating from Node.js to Bun."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "github-workflow-automation",
|
||||||
|
"path": "skills/github-workflow-automation",
|
||||||
|
"name": "github-workflow-automation",
|
||||||
|
"description": "Automate GitHub workflows with AI assistance. Includes PR reviews, issue triage, CI/CD integration, and Git operations. Use when automating GitHub workflows, setting up PR review automation, creating GitHub Actions, or triaging issues."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "address-github-comments",
|
||||||
|
"path": "skills/address-github-comments",
|
||||||
|
"name": "address-github-comments",
|
||||||
|
"description": "Use when you need to address review or issue comments on an open GitHub Pull Request using the gh CLI."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "concise-planning",
|
||||||
|
"path": "skills/concise-planning",
|
||||||
|
"name": "concise-planning",
|
||||||
|
"description": "Use when a user asks for a plan for a coding task, to generate a clear, actionable, and atomic checklist."
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
Reference in New Issue
Block a user