From 5a28a0e85eeff28d164004368236845d61a15299 Mon Sep 17 00:00:00 2001 From: imeepos Date: Wed, 21 Jan 2026 11:15:08 +0800 Subject: [PATCH] fix: add agent and skill --- .claude/commands/coder.md | 69 + .claude/commands/fix-lint.md | 211 +++ .claude/commands/writing-plans.md | 1 + .claude/settings.local.json | 8 + .claude/skills/context-engineering/SKILL.md | 1261 +++++++++++++++++ .claude/skills/planning-with-files/SKILL.md | 211 +++ .../skills/planning-with-files/examples.md | 202 +++ .../skills/planning-with-files/reference.md | 218 +++ .../scripts/check-complete.sh | 44 + .../scripts/init-session.sh | 120 ++ .../planning-with-files/templates/findings.md | 95 ++ .../planning-with-files/templates/progress.md | 114 ++ .../templates/task_plan.md | 132 ++ .claude/skills/prompt-engineering/SKILL.md | 559 ++++++++ .../subagent-driven-development/SKILL.md | 240 ++++ .../code-quality-reviewer-prompt.md | 20 + .../implementer-prompt.md | 78 + .../spec-reviewer-prompt.md | 61 + .../skills/test-driven-development/SKILL.md | 371 +++++ .../testing-anti-patterns.md | 299 ++++ .claude/skills/ui-ux-pro-max/SKILL.md | 352 +++++ .claude/skills/ui-ux-pro-max/data/charts.csv | 26 + .claude/skills/ui-ux-pro-max/data/colors.csv | 97 ++ .claude/skills/ui-ux-pro-max/data/icons.csv | 101 ++ .claude/skills/ui-ux-pro-max/data/landing.csv | 31 + .../skills/ui-ux-pro-max/data/products.csv | 97 ++ .claude/skills/ui-ux-pro-max/data/prompts.csv | 24 + .../ui-ux-pro-max/data/react-performance.csv | 45 + .../ui-ux-pro-max/data/stacks/flutter.csv | 53 + .../data/stacks/html-tailwind.csv | 56 + .../data/stacks/jetpack-compose.csv | 53 + .../ui-ux-pro-max/data/stacks/nextjs.csv | 53 + .../ui-ux-pro-max/data/stacks/nuxt-ui.csv | 51 + .../ui-ux-pro-max/data/stacks/nuxtjs.csv | 59 + .../data/stacks/react-native.csv | 52 + .../ui-ux-pro-max/data/stacks/react.csv | 54 + .../ui-ux-pro-max/data/stacks/shadcn.csv | 61 + .../ui-ux-pro-max/data/stacks/svelte.csv | 54 + .../ui-ux-pro-max/data/stacks/swiftui.csv | 51 + .../skills/ui-ux-pro-max/data/stacks/vue.csv | 50 + .claude/skills/ui-ux-pro-max/data/styles.csv | 59 + .../skills/ui-ux-pro-max/data/typography.csv | 58 + .../ui-ux-pro-max/data/ui-reasoning.csv | 101 ++ .../ui-ux-pro-max/data/ux-guidelines.csv | 100 ++ .../ui-ux-pro-max/data/web-interface.csv | 31 + .claude/skills/ui-ux-pro-max/scripts/core.py | 258 ++++ .../ui-ux-pro-max/scripts/design_system.py | 487 +++++++ .../skills/ui-ux-pro-max/scripts/search.py | 76 + .claude/skills/using-git-worktrees/SKILL.md | 217 +++ .claude/skills/writing-plans/SKILL.md | 116 ++ 50 files changed, 7237 insertions(+) create mode 100644 .claude/commands/coder.md create mode 100644 .claude/commands/fix-lint.md create mode 100644 .claude/commands/writing-plans.md create mode 100644 .claude/settings.local.json create mode 100644 .claude/skills/context-engineering/SKILL.md create mode 100644 .claude/skills/planning-with-files/SKILL.md create mode 100644 .claude/skills/planning-with-files/examples.md create mode 100644 .claude/skills/planning-with-files/reference.md create mode 100644 .claude/skills/planning-with-files/scripts/check-complete.sh create mode 100644 .claude/skills/planning-with-files/scripts/init-session.sh create mode 100644 .claude/skills/planning-with-files/templates/findings.md create mode 100644 .claude/skills/planning-with-files/templates/progress.md create mode 100644 .claude/skills/planning-with-files/templates/task_plan.md create mode 100644 .claude/skills/prompt-engineering/SKILL.md create mode 100644 .claude/skills/subagent-driven-development/SKILL.md create mode 100644 .claude/skills/subagent-driven-development/code-quality-reviewer-prompt.md create mode 100644 .claude/skills/subagent-driven-development/implementer-prompt.md create mode 100644 .claude/skills/subagent-driven-development/spec-reviewer-prompt.md create mode 100644 .claude/skills/test-driven-development/SKILL.md create mode 100644 .claude/skills/test-driven-development/testing-anti-patterns.md create mode 100644 .claude/skills/ui-ux-pro-max/SKILL.md create mode 100644 .claude/skills/ui-ux-pro-max/data/charts.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/colors.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/icons.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/landing.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/products.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/prompts.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/react-performance.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/flutter.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/jetpack-compose.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/nextjs.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/react-native.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/react.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/shadcn.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/svelte.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/swiftui.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/stacks/vue.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/styles.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/typography.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/ui-reasoning.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/ux-guidelines.csv create mode 100644 .claude/skills/ui-ux-pro-max/data/web-interface.csv create mode 100644 .claude/skills/ui-ux-pro-max/scripts/core.py create mode 100644 .claude/skills/ui-ux-pro-max/scripts/design_system.py create mode 100644 .claude/skills/ui-ux-pro-max/scripts/search.py create mode 100644 .claude/skills/using-git-worktrees/SKILL.md create mode 100644 .claude/skills/writing-plans/SKILL.md diff --git a/.claude/commands/coder.md b/.claude/commands/coder.md new file mode 100644 index 0000000..076cb4e --- /dev/null +++ b/.claude/commands/coder.md @@ -0,0 +1,69 @@ + +## Core Philosophy + +**存在即合理 (Existence Implies Necessity)** +- Every class, property, method, function, and file must have an irreplaceable reason to exist +- Every line of code serves a unique, essential purpose +- Ruthlessly eliminate any meaningless or redundant code +- Before adding anything, ask: "Is this absolutely necessary? Does it serve an irreplaceable purpose?" +- If something can be removed without loss of functionality or clarity, it must be removed +- 注意:不要过度设计! + +**优雅即简约 (Elegance is Simplicity)** +- Never write meaningless comments—the code itself tells its story +- Code should be self-documenting through thoughtful structure and naming +- Reject redundant functionality—every design element is meticulously crafted +- Variable and function names are poetry: `useSession` is not just an identifier, it's the beginning of a narrative +- Names should reveal intent, tell stories, and guide readers through the code's journey +- Favor clarity and expressiveness over brevity when naming +- 注意:不要过度设计! + +**性能即艺术 (Performance is Art)** +- Optimize not just for speed, but for elegance in execution +- Performance improvements should enhance, not compromise, code beauty +- Seek algorithmic elegance—the most efficient solution is often the most beautiful +- Balance performance with maintainability and clarity +- 注意:不要过度设计! + +**错误处理如为人处世的哲学 (Error Handling as Life Philosophy)** +- Every error is an opportunity for refinement and growth +- Handle errors gracefully, with dignity and purpose +- Error messages should guide and educate, not merely report +- Use errors as signals for architectural improvement +- Design error handling that makes the system more resilient and elegant +- 注意:不要过度设计! + +**日志是思想的表达 (Logs Express Thought)** +- Logs should narrate the system's story, not clutter it +- Each log entry serves a purpose: debugging, monitoring, or understanding system behavior +- Log messages should be meaningful, contextual, and actionable +- Avoid verbose logging—only capture what matters +- 注意:不要过度设计! + +## Your Approach + +When writing code: +1. Begin with deep contemplation of the problem's essence +2. Design the minimal, most elegant solution +3. Choose names that tell stories and reveal intent +4. Write code that reads like prose—clear, purposeful, flowing +5. Eliminate every unnecessary element +6. Ensure every abstraction earns its place +7. Optimize for both human understanding and machine performance + +When reviewing code: +1. Identify redundancies and unnecessary complexity +2. Question the existence of every element: "Why does this exist?" +3. Suggest more elegant, minimal alternatives +4. Evaluate naming: Does it tell a story? Does it reveal intent? +5. Assess error handling: Is it philosophical and purposeful? +6. Review logs: Do they express meaningful thoughts? +7. Provide refactoring suggestions that elevate code to art + +## Quality Standards + +- **Necessity**: Can this be removed? If yes, remove it. +- **Clarity**: Does the code explain itself? If it needs comments to be understood, refactor it. +- **Elegance**: Is this the simplest, most beautiful solution? +- **Performance**: Is this efficient without sacrificing clarity? +- **Purpose**: Does every element serve an irreplaceable function? \ No newline at end of file diff --git a/.claude/commands/fix-lint.md b/.claude/commands/fix-lint.md new file mode 100644 index 0000000..1fd8dc2 --- /dev/null +++ b/.claude/commands/fix-lint.md @@ -0,0 +1,211 @@ +--- +description: Fix all ESLint errors by modifying code to comply with eslint.config.js rules +argument-hint: specific files or patterns to lint +--- + +# Lint Fix + +## User Arguments + +User can provide specific files or patterns to focus on: + +``` +$ARGUMENTS +``` + +If nothing is provided, lint all applicable files in the project. + +## Context + +ESLint helps maintain code quality and consistency by enforcing coding standards defined in `eslint.config.js`. This command systematically fixes all ESLint errors by modifying the code to comply with the configured rules. + +## Goal + +Fix all ESLint errors and warnings to achieve a clean linting result. + +## Important Constraints + +- **NEVER modify eslint.config.js** - the rules are fixed and must not be changed +- **Fix the code, not the rules** - modify code to comply with the linting rules +- **Analyze complexity of changes** - + - If there are 2 or more files with errors, or one file with complex/many errors, then **Do not fix yourself** - only orchestrate agents! + - If there is only one file with simple/minor errors, then you can fix it yourself. + +## Key ESLint Rules (from eslint.config.js) + +**Type Safety Rules:** +- `@typescript-eslint/no-explicit-any`: error - Ban `any` type +- `@typescript-eslint/no-non-null-assertion`: error - Ban ! non-null assertions +- `@typescript-eslint/no-unsafe-assignment`: error - Ban unsafe type assignments +- `@typescript-eslint/no-unsafe-call`: error - Ban unsafe function calls +- `@typescript-eslint/no-unsafe-member-access`: error - Ban unsafe property access +- `@typescript-eslint/no-unsafe-return`: error - Ban unsafe returns +- `@typescript-eslint/no-unsafe-argument`: error - Ban unsafe arguments + +**Code Quality Rules:** +- `@typescript-eslint/no-unused-vars`: error - Unused variables (prefix with `_` to ignore) +- `@typescript-eslint/no-floating-promises`: error - Unhandled promises +- `@typescript-eslint/no-misused-promises`: error - Misused async operations +- `@typescript-eslint/strict-boolean-expressions`: error - Strict boolean checks +- `@typescript-eslint/prefer-nullish-coalescing`: error - Use `??` instead of `||` +- `@typescript-eslint/prefer-optional-chain`: error - Use `?.` instead of `&&` checks + +## Workflow Steps + +### Preparation + +1. **Read sadd skill if available** + - If available, read the sadd skill to understand best practices for managing agents + +2. **Discover linting infrastructure** + - Read @README.md and package.json + - Identify the lint command (usually `npm run lint` or `pnpm lint`) + - Check if `eslint.config.js` exists (it should not be modified) + +3. **Run ESLint** + - Execute the lint command to see all errors + - If user provided arguments, run: `eslint $ARGUMENTS` + - Otherwise run the project's full lint command + +4. **Identify files with errors** + - Parse ESLint output to get list of files with errors + - Group by file for parallel agent execution + +### Analysis + +5. **Verify single file linting** + - Launch haiku agent to find proper command to lint a single file + - Test: `eslint path/to/file.ts` + - This ensures agents can lint files in isolation + +### Lint Fixing + +#### Simple Single File Flow + +If there is only one file with simple/minor errors, you can fix it yourself: + +1. Read the file with errors +2. Understand each ESLint error +3. Fix each error systematically: + - Replace any with proper types + - Remove ! assertions and use proper type guards + - Fix unsafe operations with proper type checking + - Remove unused variables or prefix with _ + - Use ?? instead of || for null checks + - Use ?. instead of && for optional chaining +4. Re-run the lint command +5. Iterate until all errors are fixed + +#### Multiple Files or Complex File Flow + +If there are multiple files with errors, or one file with many/complex errors, use specialized agents: + +6. **Launch developer agents (parallel)** (Sonnet or Opus models) + - Launch one agent per file with lint errors + - Provide each agent with: + * **Context**: ESLint errors for this file + * **Target**: Which specific file to fix + * **Rules**: Reference eslint.config.js for the rules (DO NOT modify it) + * **Constraint**: Fix code to comply with rules, never modify eslint.config.js + * **Goal**: Iterate until file has no ESLint errors + +7. **Verify all fixes** + - After all agents complete, run full lint command again + - Verify all files pass + +8. **Iterate if needed** + - If any files still have errors: Return to step 5 + - Launch new agents only for remaining errors + - Continue until 100% pass rate + +## Success Criteria + +- All ESLint errors fixed ✅ +- All ESLint warnings fixed (or justified) ✅ +- Code complies with eslint.config.js rules ✅ +- eslint.config.js remains unchanged ✅ + +## Agent Instructions Template + +When launching agents, use this template: + +``` +The file {FILE_PATH} has ESLint errors that need to be fixed. + +ESLint errors: +{ESLINT_OUTPUT} + +Your task: +1. Read the file {FILE_PATH} +2. Read eslint.config.js to understand the rules (DO NOT modify it) +3. Fix each ESLint error by modifying the code, not the rules: + - Replace `any` with proper types or `unknown` where appropriate + - Remove ! non-null assertions; use type guards or optional chaining + - Fix unsafe type operations with proper type checking + - Remove unused variables or prefix with _ + - Use ?? (nullish coalescing) instead of || + - Use ?. (optional chaining) instead of && checks + - Handle promises properly with await or .catch() + - Use strict boolean expressions (no loose truthy checks) +4. Run: eslint {FILE_PATH} +5. Iterate until all ESLint errors are fixed + +IMPORTANT: Never modify eslint.config.js - the rules are fixed. +``` + +## Common ESLint Error Fixes + +**@typescript-eslint/no-explicit-any** +```typescript +// Bad +function foo(x: any) { return x; } + +// Good +function foo(x: T): T { return x; } +// or +function foo(x: unknown) { /* validate and use */ } +``` + +**@typescript-eslint/no-non-null-assertion** +```typescript +// Bad +const value = maybeNull!.toString(); + +// Good +const value = maybeNull?.toString(); +// or +if (maybeNull !== null) { + const value = maybeNull.toString(); +} +``` + +**@typescript-eslint/prefer-nullish-coalescing** +```typescript +// Bad +const value = input || 'default'; + +// Good +const value = input ?? 'default'; +``` + +**@typescript-eslint/prefer-optional-chain** +```typescript +// Bad +if (obj && obj.nested && obj.nested.value) { } + +// Good +if (obj?.nested?.value) { } +``` + +**@typescript-eslint/no-unused-vars** +```typescript +// Bad +function foo(a: number, b: number) { + return a; +} + +// Good +function foo(a: number, _b: number) { + return a; +} +``` diff --git a/.claude/commands/writing-plans.md b/.claude/commands/writing-plans.md new file mode 100644 index 0000000..e774438 --- /dev/null +++ b/.claude/commands/writing-plans.md @@ -0,0 +1 @@ +use .claude\skills\writing-plans\SKILL.md skill \ No newline at end of file diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..afff9e2 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,8 @@ +{ + "permissions": { + "allow": [ + "mcp__acp__Bash", + "mcp__acp__Edit" + ] + } +} diff --git a/.claude/skills/context-engineering/SKILL.md b/.claude/skills/context-engineering/SKILL.md new file mode 100644 index 0000000..871763b --- /dev/null +++ b/.claude/skills/context-engineering/SKILL.md @@ -0,0 +1,1261 @@ +--- +name: context-engineering +description: Understand the components, mechanics, and constraints of context in agent systems. Use when writing, editing, or optimizing commands, skills, or sub-agents prompts. +--- + +# Context Engineering Fundamentals + +Context is the complete state available to a language model at inference time. It includes everything the model can attend to when generating responses: system instructions, tool definitions, retrieved documents, message history, and tool outputs. Understanding context fundamentals is prerequisite to effective context engineering. + +## Core Concepts + +Context comprises several distinct components, each with different characteristics and constraints. The attention mechanism creates a finite budget that constrains effective context usage. Progressive disclosure manages this constraint by loading information only as needed. The engineering discipline is curating the smallest high-signal token set that achieves desired outcomes. + +## Detailed Topics + +### The Anatomy of Context + +**System Prompts** +System prompts establish the agent's core identity, constraints, and behavioral guidelines. They are loaded once at session start and typically persist throughout the conversation. System prompts should be extremely clear and use simple, direct language at the right altitude for the agent. + +The right altitude balances two failure modes. At one extreme, engineers hardcode complex brittle logic that creates fragility and maintenance burden. At the other extreme, engineers provide vague high-level guidance that fails to give concrete signals for desired outputs or falsely assumes shared context. The optimal altitude strikes a balance: specific enough to guide behavior effectively, yet flexible enough to provide strong heuristics. + +Organize prompts into distinct sections using XML tagging or Markdown headers to delineate background information, instructions, tool guidance, and output description. The exact formatting matters less as models become more capable, but structural clarity remains valuable. + +**Tool Definitions** +Tool definitions specify the actions an agent can take. Each tool includes a name, description, parameters, and return format. Tool definitions live near the front of context after serialization, typically before or after the system prompt. + +Tool descriptions collectively steer agent behavior. Poor descriptions force agents to guess; optimized descriptions include usage context, examples, and defaults. The consolidation principle states that if a human engineer cannot definitively say which tool should be used in a given situation, an agent cannot be expected to do better. + +**Retrieved Documents** +Retrieved documents provide domain-specific knowledge, reference materials, or task-relevant information. Agents use retrieval augmented generation to pull relevant documents into context at runtime rather than pre-loading all possible information. + +The just-in-time approach maintains lightweight identifiers (file paths, stored queries, web links) and uses these references to load data into context dynamically. This mirrors human cognition: we generally do not memorize entire corpuses of information but rather use external organization and indexing systems to retrieve relevant information on demand. + +**Message History** +Message history contains the conversation between the user and agent, including previous queries, responses, and reasoning. For long-running tasks, message history can grow to dominate context usage. + +Message history serves as scratchpad memory where agents track progress, maintain task state, and preserve reasoning across turns. Effective management of message history is critical for long-horizon task completion. + +**Tool Outputs** +Tool outputs are the results of agent actions: file contents, search results, command execution output, API responses, and similar data. Tool outputs comprise the majority of tokens in typical agent trajectories, with research showing observations (tool outputs) can reach 83.9% of total context usage. + +Tool outputs consume context whether they are relevant to current decisions or not. This creates pressure for strategies like observation masking, compaction, and selective tool result retention. + +### Context Windows and Attention Mechanics + +**The Attention Budget Constraint** +Language models process tokens through attention mechanisms that create pairwise relationships between all tokens in context. For n tokens, this creates n^2 relationships that must be computed and stored. As context length increases, the model's ability to capture these relationships gets stretched thin. + +Models develop attention patterns from training data distributions where shorter sequences predominate. This means models have less experience with and fewer specialized parameters for context-wide dependencies. The result is an "attention budget" that depletes as context grows. + +**Position Encoding and Context Extension** +Position encoding interpolation allows models to handle longer sequences by adapting them to originally trained smaller contexts. However, this adaptation introduces degradation in token position understanding. Models remain highly capable at longer contexts but show reduced precision for information retrieval and long-range reasoning compared to performance on shorter contexts. + +**The Progressive Disclosure Principle** +Progressive disclosure manages context efficiently by loading information only as needed. At startup, agents load only skill names and descriptions--sufficient to know when a skill might be relevant. Full content loads only when a skill is activated for specific tasks. + +This approach keeps agents fast while giving them access to more context on demand. The principle applies at multiple levels: skill selection, document loading, and even tool result retrieval. + +### Context Quality Versus Context Quantity + +The assumption that larger context windows solve memory problems has been empirically debunked. Context engineering means finding the smallest possible set of high-signal tokens that maximize the likelihood of desired outcomes. + +Several factors create pressure for context efficiency. Processing cost grows disproportionately with context length--not just double the cost for double the tokens, but exponentially more in time and computing resources. Model performance degrades beyond certain context lengths even when the window technically supports more tokens. Long inputs remain expensive even with prefix caching. + +The guiding principle is informativity over exhaustiveness. Include what matters for the decision at hand, exclude what does not, and design systems that can access additional information on demand. + +### Context as Finite Resource + +Context must be treated as a finite resource with diminishing marginal returns. Like humans with limited working memory, language models have an attention budget drawn on when parsing large volumes of context. + +Every new token introduced depletes this budget by some amount. This creates the need for careful curation of available tokens. The engineering problem is optimizing utility against inherent constraints. + +Context engineering is iterative and the curation phase happens each time you decide what to pass to the model. It is not a one-time prompt writing exercise but an ongoing discipline of context management. + +## Practical Guidance + +### File-System-Based Access + +Agents with filesystem access can use progressive disclosure naturally. Store reference materials, documentation, and data externally. Load files only when needed using standard filesystem operations. This pattern avoids stuffing context with information that may not be relevant. + +The file system itself provides structure that agents can navigate. File sizes suggest complexity; naming conventions hint at purpose; timestamps serve as proxies for relevance. Metadata of file references provides a mechanism to efficiently refine behavior. + +### Hybrid Strategies + +The most effective agents employ hybrid strategies. Pre-load some context for speed (like CLAUDE.md files or project rules), but enable autonomous exploration for additional context as needed. The decision boundary depends on task characteristics and context dynamics. + +For contexts with less dynamic content, pre-loading more upfront makes sense. For rapidly changing or highly specific information, just-in-time loading avoids stale context. + +### Context Budgeting + +Design with explicit context budgets in mind. Know the effective context limit for your model and task. Monitor context usage during development. Implement compaction triggers at appropriate thresholds. Design systems assuming context will degrade rather than hoping it will not. + +Effective context budgeting requires understanding not just raw token counts but also attention distribution patterns. The middle of context receives less attention than the beginning and end. Place critical information at attention-favored positions. + +## Examples + +**Example 1: Organizing System Prompts** +```markdown + +You are a Python expert helping a development team. +Current project: Data processing pipeline in Python 3.9+ + + + +- Write clean, idiomatic Python code +- Include type hints for function signatures +- Add docstrings for public functions +- Follow PEP 8 style guidelines + + + +Use bash for shell operations, python for code tasks. +File operations should use pathlib for cross-platform compatibility. + + + +Provide actionable feedback with specific line references. +Explain the reasoning behind suggestions. + +``` + +**Example 2: Progressive Document Loading** +```markdown +# Instead of loading all documentation at once: + +# Step 1: Load summary +docs/architecture_overview.md # Lightweight overview + +# Step 2: Load specific section as needed +docs/api/endpoints.md # Only when API work needed +docs/database/schemas.md # Only when data layer work needed +``` + +**Example 3: Skill Description Design** +```markdown +# Bad: Vague description that loads into context but provides little signal +description: Helps with code things + +# Good: Specific description that helps model decide when to activate +description: Analyze code quality and suggest refactoring patterns. Use when reviewing pull requests or improving existing code structure. +``` + +## Guidelines + +1. Treat context as a finite resource with diminishing returns +2. Place critical information at attention-favored positions (beginning and end) +3. Use progressive disclosure to defer loading until needed +4. Organize system prompts with clear section boundaries +5. Monitor context usage during development +6. Implement compaction triggers at 70-80% utilization +7. Design for context degradation rather than hoping to avoid it +8. Prefer smaller high-signal context over larger low-signal context + +# Context Degradation Patterns + +Language models exhibit predictable degradation patterns as context length increases. Understanding these patterns is essential for diagnosing failures and designing resilient systems. Context degradation is not a binary state but a continuum of performance degradation that manifests in several distinct ways. + +## Core Concepts + +Context degradation manifests through several distinct patterns. The lost-in-middle phenomenon causes information in the center of context to receive less attention. Context poisoning occurs when errors compound through repeated reference. Context distraction happens when irrelevant information overwhelms relevant content. Context confusion arises when the model cannot determine which context applies. Context clash develops when accumulated information directly conflicts. + +These patterns are predictable and can be mitigated through architectural patterns like compaction, masking, partitioning, and isolation. + +## Detailed Topics + +### The Lost-in-Middle Phenomenon + +The most well-documented degradation pattern is the "lost-in-middle" effect, where models demonstrate U-shaped attention curves. Information at the beginning and end of context receives reliable attention, while information buried in the middle suffers from dramatically reduced recall accuracy. + +**Empirical Evidence** +Research demonstrates that relevant information placed in the middle of context experiences 10-40% lower recall accuracy compared to the same information at the beginning or end. This is not a failure of the model but a consequence of attention mechanics and training data distributions. + +Models allocate massive attention to the first token (often the BOS token) to stabilize internal states. This creates an "attention sink" that soaks up attention budget. As context grows, the limited budget is stretched thinner, and middle tokens fail to garner sufficient attention weight for reliable retrieval. + +**Practical Implications** +Design context placement with attention patterns in mind. Place critical information at the beginning or end of context. Consider whether information will be queried directly or needs to support reasoning--if the latter, placement matters less but overall signal quality matters more. + +For long documents or conversations, use summary structures that surface key information at attention-favored positions. Use explicit section headers and transitions to help models navigate structure. + +### Context Poisoning + +Context poisoning occurs when hallucinations, errors, or incorrect information enters context and compounds through repeated reference. Once poisoned, context creates feedback loops that reinforce incorrect beliefs. + +**How Poisoning Occurs** +Poisoning typically enters through three pathways. First, tool outputs may contain errors or unexpected formats that models accept as ground truth. Second, retrieved documents may contain incorrect or outdated information that models incorporate into reasoning. Third, model-generated summaries or intermediate outputs may introduce hallucinations that persist in context. + +The compounding effect is severe. If an agent's goals section becomes poisoned, it develops strategies that take substantial effort to undo. Each subsequent decision references the poisoned content, reinforcing incorrect assumptions. + +**Detection and Recovery** +Watch for symptoms including degraded output quality on tasks that previously succeeded, tool misalignment where agents call wrong tools or parameters, and hallucinations that persist despite correction attempts. When these symptoms appear, consider context poisoning. + +Recovery requires removing or replacing poisoned content. This may involve truncating context to before the poisoning point, explicitly noting the poisoning in context and asking for re-evaluation, or restarting with clean context and preserving only verified information. + +### Context Distraction + +Context distraction emerges when context grows so long that models over-focus on provided information at the expense of their training knowledge. The model attends to everything in context regardless of relevance, and this creates pressure to use provided information even when internal knowledge is more accurate. + +**The Distractor Effect** +Research shows that even a single irrelevant document in context reduces performance on tasks involving relevant documents. Multiple distractors compound degradation. The effect is not about noise in absolute terms but about attention allocation--irrelevant information competes with relevant information for limited attention budget. + +Models do not have a mechanism to "skip" irrelevant context. They must attend to everything provided, and this obligation creates distraction even when the irrelevant information is clearly not useful. + +**Mitigation Strategies** +Mitigate distraction through careful curation of what enters context. Apply relevance filtering before loading retrieved documents. Use namespacing and organization to make irrelevant sections easy to ignore structurally. Consider whether information truly needs to be in context or can be accessed through tool calls instead. + +### Context Confusion + +Context confusion arises when irrelevant information influences responses in ways that degrade quality. This is related to distraction but distinct--confusion concerns the influence of context on model behavior rather than attention allocation. + +If you put something in context, the model has to pay attention to it. The model may incorporate irrelevant information, use inappropriate tool definitions, or apply constraints that came from different contexts. Confusion is especially problematic when context contains multiple task types or when switching between tasks within a single session. + +**Signs of Confusion** +Watch for responses that address the wrong aspect of a query, tool calls that seem appropriate for a different task, or outputs that mix requirements from multiple sources. These indicate confusion about what context applies to the current situation. + +**Architectural Solutions** +Architectural solutions include explicit task segmentation where different tasks get different context windows, clear transitions between task contexts, and state management that isolates context for different objectives. + +### Context Clash + +Context clash develops when accumulated information directly conflicts, creating contradictory guidance that derails reasoning. This differs from poisoning where one piece of information is incorrect--in clash, multiple correct pieces of information contradict each other. + +**Sources of Clash** +Clash commonly arises from multi-source retrieval where different sources have contradictory information, version conflicts where outdated and current information both appear in context, and perspective conflicts where different viewpoints are valid but incompatible. + +**Resolution Approaches** +Resolution approaches include explicit conflict marking that identifies contradictions and requests clarification, priority rules that establish which source takes precedence, and version filtering that excludes outdated information from context. + +### Counterintuitive Findings + +Research reveals several counterintuitive patterns that challenge assumptions about context management. + +**Shuffled Haystacks Outperform Coherent Ones** +Studies found that shuffled (incoherent) haystacks produce better performance than logically coherent ones. This suggests that coherent context may create false associations that confuse retrieval, while incoherent context forces models to rely on exact matching. + +**Single Distractors Have Outsized Impact** +Even a single irrelevant document reduces performance significantly. The effect is not proportional to the amount of noise but follows a step function where the presence of any distractor triggers degradation. + +**Needle-Question Similarity Correlation** +Lower similarity between needle and question pairs shows faster degradation with context length. Tasks requiring inference across dissimilar content are particularly vulnerable. + +### When Larger Contexts Hurt + +Larger context windows do not uniformly improve performance. In many cases, larger contexts create new problems that outweigh benefits. + +**Performance Degradation Curves** +Models exhibit non-linear degradation with context length. Performance remains stable up to a threshold, then degrades rapidly. The threshold varies by model and task complexity. For many models, meaningful degradation begins around 8,000-16,000 tokens even when context windows support much larger sizes. + +**Cost Implications** +Processing cost grows disproportionately with context length. The cost to process a 400K token context is not double the cost of 200K--it increases exponentially in both time and computing resources. For many applications, this makes large-context processing economically impractical. + +**Cognitive Load Metaphor** +Even with an infinite context, asking a single model to maintain consistent quality across dozens of independent tasks creates a cognitive bottleneck. The model must constantly switch context between items, maintain a comparative framework, and ensure stylistic consistency. This is not a problem that more context solves. + +## Practical Guidance + +### The Four-Bucket Approach + +Four strategies address different aspects of context degradation: + +**Write**: Save context outside the window using scratchpads, file systems, or external storage. This keeps active context lean while preserving information access. + +**Select**: Pull relevant context into the window through retrieval, filtering, and prioritization. This addresses distraction by excluding irrelevant information. + +**Compress**: Reduce tokens while preserving information through summarization, abstraction, and observation masking. This extends effective context capacity. + +**Isolate**: Split context across sub-agents or sessions to prevent any single context from growing large enough to degrade. This is the most aggressive strategy but often the most effective. + +### Architectural Patterns + +Implement these strategies through specific architectural patterns. Use just-in-time context loading to retrieve information only when needed. Use observation masking to replace verbose tool outputs with compact references. Use sub-agent architectures to isolate context for different tasks. Use compaction to summarize growing context before it exceeds limits. + +## Examples + +**Example 1: Detecting Degradation in Prompt Design** +```markdown +# Signs your command/skill prompt may be too large: + +Early signs (context ~50-70% utilized): +- Agent occasionally misses instructions +- Responses become less focused +- Some guidelines ignored + +Warning signs (context ~70-85% utilized): +- Inconsistent behavior across runs +- Agent "forgets" earlier instructions +- Quality varies significantly + +Critical signs (context >85% utilized): +- Agent ignores key constraints +- Hallucinations increase +- Task completion fails +``` + +**Example 2: Mitigating Lost-in-Middle in Prompt Structure** +```markdown +# Organize prompts with critical info at edges + + # At start (high attention) +- Never modify production files directly +- Always run tests before committing +- Maximum file size: 500 lines + + + # Middle (lower attention) +- Code style preferences +- Documentation templates +- Review checklists +- Example patterns + + + # At end (high attention) +- Run tests: npm test +- Format code: npm run format +- Create PR with description + +``` + +**Example 3: Sub-Agent Context Isolation** +```markdown +# Instead of one agent handling everything: + +## Coordinator Agent (lean context) +- Understands task decomposition +- Delegates to specialized sub-agents +- Synthesizes results + +## Code Review Sub-Agent (isolated context) +- Loaded only with code review guidelines +- Focuses solely on review task +- Returns structured findings + +## Test Writer Sub-Agent (isolated context) +- Loaded only with testing patterns +- Focuses solely on test creation +- Returns test files +``` + +## Guidelines + +1. Monitor context length and performance correlation during development +2. Place critical information at beginning or end of context +3. Implement compaction triggers before degradation becomes severe +4. Validate retrieved documents for accuracy before adding to context +5. Use versioning to prevent outdated information from causing clash +6. Segment tasks to prevent context confusion across different objectives +7. Design for graceful degradation rather than assuming perfect conditions +8. Test with progressively larger contexts to find degradation thresholds + +# Context Degradation Patterns: Multi-Agent Workflows + +This section transforms context degradation detection and mitigation concepts into actionable multi-agent workflows for Claude Code. Use these patterns when building commands, skills, or complex agent pipelines to ensure quality and reliability. + +## Hallucination Detection Workflow + +Hallucinations in agent output can poison downstream context and propagate errors through multi-step workflows. This workflow detects hallucinations before they compound. + +### When to Use + +- After any agent completes a task that produces factual claims +- Before committing agent-generated code or documentation +- When output will be used as input for subsequent agents +- During review of long-running agent sessions + +### Multi-Agent Verification Pattern + +**Step 1: Generate Output** + +Have the primary agent complete its task normally. + +**Step 2: Extract Claims** + +Spawn a verification sub-agent with this prompt: + +```markdown + +Extract all factual claims from the following output. List each claim on a separate line. + + + +- File paths and their existence +- Function/class/method names referenced +- Code behavior assertions ("this function returns X") +- External facts about APIs, libraries, or specifications +- Numerical values and metrics + + + +{agent_output} + + + +One claim per line, prefixed with category: +[PATH] /src/auth/login.ts exists +[CODE] validateCredentials() returns a boolean +[FACT] JWT tokens expire after 24 hours by default +[METRIC] The function has O(n) complexity + +``` + +**Step 3: Verify Claims** + +For groups of extracted claimd, spawn a verification agent: + +```markdown + +Verify this claim by checking the actual codebase and context. + + + +{claim} + + + +- For file paths: Use file tools to check existence +- For code claims: Read the actual code and verify behavior +- For external facts: Cross-reference with documentation or web search +- For metrics: Analyze the code structure + + + +STATUS: [VERIFIED | FALSE | UNVERIFIABLE] +EVIDENCE: [What you found] +CONFIDENCE: [HIGH | MEDIUM | LOW] + +``` + +**Step 4: Calculate Poisoning Risk** + +Aggregate verification results: + +``` +total_claims = number of claims extracted +verified_count = claims marked VERIFIED +false_count = claims marked FALSE +unverifiable_count = claims marked UNVERIFIABLE + +poisoning_risk = (false_count * 2 + unverifiable_count) / total_claims +``` + +**Step 5: Decision Threshold** + +- **Risk < 0.1**: Output is reliable, proceed normally +- **Risk 0.1-0.3**: Review flagged claims manually before proceeding +- **Risk > 0.3**: Regenerate output with more explicit grounding instructions: + +```markdown + +Previous output contained {false_count} false claims and {unverifiable_count} unverifiable claims. + +Specific issues: +{list of FALSE and UNVERIFIABLE claims with evidence} + +Please regenerate your response. For each factual claim: +1. Explicitly verify it using tools before stating it +2. If you cannot verify, state "I cannot verify..." instead of asserting +3. Cite the specific file/line/source for verifiable facts + +``` + +## Lost-in-Middle Detection Workflow + +Critical information buried in the middle of long prompts receives less attention. This workflow detects which parts of your prompt are at risk of being ignored by running multiple agents and verifying their outputs against the original instructions. + +### When to Use + +- When designing new commands or skills with long prompts +- When agents inconsistently follow instructions across runs +- Before deploying prompts to production +- During prompt optimization + +### Multi-Run Verification Pattern + +**Step 1: Identify Critical Instructions** + +Extract all critical instructions from your prompt that the agent MUST follow: + +```markdown +Critical instructions to verify: +1. "Never modify files in /production" +2. "Always run tests before committing" +3. "Use TypeScript strict mode" +4. "Maximum function length: 50 lines" +5. "Include JSDoc for public APIs" +6. "Format output as JSON" +7. "Log all file modifications" +``` + +**Step 2: Run Multiple Agents with Same Prompt** + +Spawn 3-5 agents with the SAME prompt (the command/skill/agent being tested). Each agent runs independently with identical inputs: + +```markdown + +Number of runs: 5 +Prompt: {your_full_prompt_being_tested} +Task: {representative_task_that_exercises_all_instructions} + +For each run, save: +- run_id: unique identifier +- agent_output: complete response from agent +- timestamp: when run completed + +``` + +**Step 3: Verify Each Output Against Original Prompt** + +For each agent's output, spawn a NEW verification agent that checks compliance with every critical instruction: + +```markdown + + +You are a compliance verification agent. Analyze whether the agent output followed each instruction from the original prompt. + + + +{the_full_prompt_being_tested} + + + +{numbered_list_of_critical_instructions} + + + +{output_from_run_N} + + + +For each critical instruction: +1. Determine if the instruction was applicable to this task +2. If applicable, check whether the output complies +3. Look for both explicit violations and omissions +4. Note any partial compliance + + + +RUN_ID: {run_id} + +INSTRUCTION_COMPLIANCE: +- Instruction 1: "Never modify files in /production" + STATUS: [FOLLOWED | VIOLATED | NOT_APPLICABLE] + EVIDENCE: {quote from output or explanation} + +- Instruction 2: "Always run tests before committing" + STATUS: [FOLLOWED | VIOLATED | NOT_APPLICABLE] + EVIDENCE: {quote from output or explanation} + +[... continue for all instructions ...] + +SUMMARY: +- Instructions followed: {count} +- Instructions violated: {count} +- Not applicable: {count} + + +``` + +**Step 4: Aggregate Results and Identify At-Risk Parts** + +Collect verification results from all runs and identify instructions that were inconsistently followed: + +```markdown + +For each instruction: + followed_count = number of runs where STATUS == FOLLOWED + violated_count = number of runs where STATUS == VIOLATED + applicable_runs = total_runs - (runs where STATUS == NOT_APPLICABLE) + + compliance_rate = followed_count / applicable_runs + + Classification: + - compliance_rate == 1.0: RELIABLE (always followed) + - compliance_rate >= 0.8: MOSTLY_RELIABLE (minor inconsistency) + - compliance_rate >= 0.5: AT_RISK (inconsistent - likely lost-in-middle) + - compliance_rate < 0.5: FREQUENTLY_IGNORED (severe issue) + - compliance_rate == 0.0: ALWAYS_IGNORED (critical failure) + +AT_RISK instructions are the primary signal for lost-in-middle problems. +These are instructions that work sometimes but not consistently, indicating +they are in attention-weak positions. + + + +INSTRUCTION COMPLIANCE SUMMARY: + +| Instruction | Followed | Violated | Compliance Rate | Status | +|-------------|----------|----------|-----------------|--------| +| 1. Never modify /production | 5/5 | 0/5 | 100% | RELIABLE | +| 2. Run tests before commit | 3/5 | 2/5 | 60% | AT_RISK | +| 3. TypeScript strict mode | 4/5 | 1/5 | 80% | MOSTLY_RELIABLE | +| 4. Max function length 50 | 2/5 | 3/5 | 40% | FREQUENTLY_IGNORED | +| 5. Include JSDoc | 5/5 | 0/5 | 100% | RELIABLE | +| 6. Format as JSON | 1/5 | 4/5 | 20% | ALWAYS_IGNORED | +| 7. Log modifications | 3/5 | 2/5 | 60% | AT_RISK | + +AT-RISK INSTRUCTIONS (likely in lost-in-middle zone): +- Instruction 2: "Run tests before commit" (60% compliance) +- Instruction 4: "Max function length 50" (40% compliance) +- Instruction 6: "Format as JSON" (20% compliance) +- Instruction 7: "Log modifications" (60% compliance) + +``` + +**Step 5: Output Recommendations** + +Based on the at-risk parts identified, provide specific remediation guidance: + +```markdown + +LOST-IN-MIDDLE ANALYSIS COMPLETE + +At-Risk Instructions Detected: {count} +These instructions are inconsistently followed, indicating they likely +reside in attention-weak positions (middle of prompt). + +SPECIFIC RECOMMENDATIONS: + +1. MOVE CRITICAL INFORMATION TO ATTENTION-FAVORED POSITIONS + The following instructions should be relocated to the beginning or end of your prompt: + - "Run tests before commit" -> Move to at prompt START + - "Max function length 50" -> Move to at prompt END + - "Format as JSON" -> Move to at prompt END + - "Log modifications" -> Add to both START and END sections + +2. USE EXPLICIT MARKERS TO HIGHLIGHT CRITICAL INFORMATION + Restructure at-risk instructions with emphasis: + + Before: "Always run tests before committing" + After: "**CRITICAL:** You MUST run tests before committing. Never skip this step." + + Before: "Maximum function length: 50 lines" + After: "3. [REQUIRED] Maximum function length: 50 lines" + + Use numbered lists, bold markers, or explicit tags like [REQUIRED], [CRITICAL], [MUST]. + +3. CONSIDER SPLITTING CONTEXT TO REDUCE MIDDLE SECTION + If your prompt has many instructions, consider: + - Breaking into focused sub-prompts for different aspects + - Using sub-agents with specialized, shorter contexts + - Moving detailed guidance to on-demand sections loaded only when needed + + Current prompt structure creates a large middle section where + {count} instructions are being lost. Reduce middle section by: + - Moving 2-3 most critical items to edges + - Converting remaining middle items to a numbered checklist + - Adding explicit "verify these items" reminder at end + +``` + +### Complete Workflow Example + +```markdown +# Example: Testing a Code Review Command + +## Original Prompt Being Tested: +"Review the code for: security issues, performance problems, +code style, test coverage, documentation completeness, +error handling, and logging practices." + +## Run 5 Agents: +Each agent reviews the same code sample with this prompt. + +## Verification Results: +| Instruction | Run 1 | Run 2 | Run 3 | Run 4 | Run 5 | Rate | +|-------------|-------|-------|-------|-------|-------|------| +| Security | Y | Y | Y | Y | Y | 100% | +| Performance | Y | X | Y | X | Y | 60% | +| Code style | X | X | Y | X | X | 20% | +| Test coverage | X | Y | X | X | Y | 40% | +| Documentation | X | X | X | Y | X | 20% | +| Error handling | Y | Y | X | Y | Y | 80% | +| Logging | Y | Y | Y | Y | Y | 100% | + +## Analysis: +- RELIABLE: Security, Logging (at edges of list) +- AT_RISK: Performance, Error handling +- FREQUENTLY_IGNORED: Code style, Test coverage, Documentation (middle of list) + +## Remediation Applied: +"**CRITICAL REVIEW AREAS:** +1. Security vulnerabilities +2. Test coverage gaps +3. Documentation completeness + +Review also: performance, code style, error handling, logging. + +**BEFORE COMPLETING:** Verify you addressed items 1-3 above." +``` + +## Error Propagation Analysis Workflow + +In multi-agent chains, errors from early agents propagate and amplify through subsequent agents. This workflow traces errors to their source. + +### When to Use + +- When final output contains errors despite correct intermediate steps +- When debugging complex multi-agent workflows +- When establishing error boundaries in agent chains +- During post-mortem analysis of failed agent tasks + +### Error Trace Pattern + +**Step 1: Capture Agent Chain Outputs** + +Record the output of each agent in your chain: + +```markdown +Agent Chain Record: +- Agent 1 (Analyzer): {output_1} +- Agent 2 (Planner): {output_2} +- Agent 3 (Implementer): {output_3} +- Agent 4 (Reviewer): {output_4} +``` + +**Step 2: Identify Error Symptoms** + +Spawn an error identification agent: + +```markdown + +Analyze the final output and identify all errors, inconsistencies, or quality issues. + + + +{output_from_last_agent} + + + +ERROR_ID: E1 +DESCRIPTION: Function missing null check +LOCATION: src/utils/parser.ts:45 +SEVERITY: HIGH + +ERROR_ID: E2 +... + +``` + +**Step 3: Trace Each Error Backward** + +For each identified error, spawn a trace agent: + +```markdown + +Trace this error backward through the agent chain to find its origin. + + + +{error_description} + + + +Agent 1 Output: {output_1} +Agent 2 Output: {output_2} +Agent 3 Output: {output_3} +Agent 4 Output: {output_4} + + + +For each agent output (starting from the last): +1. Does this output contain the error? +2. If yes, was the error present in the input to this agent? +3. If error is in output but not input: This agent INTRODUCED the error +4. If error is in both: This agent PROPAGATED the error + + + +ERROR: {error_id} +ORIGIN_AGENT: Agent {N} +ORIGIN_TYPE: [INTRODUCED | PROPAGATED_FROM_CONTEXT | PROPAGATED_FROM_TOOL_OUTPUT] +ROOT_CAUSE: {explanation} +CONTEXT_THAT_CAUSED_IT: {relevant context snippet if applicable} + +``` + +**Step 4: Calculate Propagation Metrics** + +``` +For each agent in chain: + errors_introduced = count of errors this agent created + errors_propagated = count of errors this agent passed through + errors_caught = count of errors this agent fixed or flagged + +propagation_rate = errors_at_end / errors_introduced_total +amplification_factor = errors_at_end / errors_at_start +``` + +**Step 5: Establish Error Boundaries** + +Based on analysis, add verification checkpoints: + +```markdown + +After Agent {N} completes: + +1. Spawn verification agent to check for common error patterns: + - {error_pattern_1 that Agent N tends to introduce} + - {error_pattern_2 that Agent N tends to introduce} + +2. If errors detected: + - Log error for analysis + - Either: Fix inline and continue + - Or: Regenerate Agent N output with explicit guidance + +3. Only proceed to Agent {N+1} if verification passes + +``` + +## Context Relevance Scoring Workflow + +Not all parts of a prompt contribute equally to task completion. This workflow identifies distractor parts within a prompt that consume attention budget without adding value. + +### When to Use + +- When optimizing prompt length and content +- When deciding what to include in CLAUDE.md +- When a prompt feels bloated but you are unsure what to cut +- When debugging agents that ignore provided context +- Before deploying new commands, skills, or agent prompts + +### Distractor Identification Pattern + +**Step 1: Split Prompt into Parts** + +Divide the prompt (command/skill/agent) into logical sections. Each part should be a coherent unit: + +```markdown + +PART_1: + ID: background + CONTENT: | + You are a Python expert helping a development team. + Current project: Data processing pipeline in Python 3.9+ + +PART_2: + ID: code_style_rules + CONTENT: | + - Write clean, idiomatic Python code + - Include type hints for function signatures + - Add docstrings for public functions + - Follow PEP 8 style guidelines + +PART_3: + ID: historical_context + CONTENT: | + The project was migrated from Python 2.7 in 2019. + Original team used camelCase naming but we now use snake_case. + Legacy modules in /legacy folder are frozen. + +PART_4: + ID: output_format + CONTENT: | + Provide actionable feedback with specific line references. + Explain the reasoning behind suggestions. + +``` + +Splitting guidelines: +- Each XML section or Markdown header becomes a part +- Separate conceptually distinct instructions into their own parts +- Keep related instructions together (do not split mid-thought) +- Aim for 3-15 parts depending on prompt length + +**Step 2: Spawn Scoring Agents** + +Spawn multiple scoring agents in parallel: + +```markdown + +Score how relevant this prompt parts is for accomplishing the specified task. + + + +{description of what the agent should accomplish} +Example: "Review a pull request for code quality issues and suggest improvements" + + + +{contents of all the parts being evaluated} + + + +Score 0-10 based on these criteria: + +ESSENTIAL (8-10): +- Part directly enables task completion +- Removing this part would cause task failure +- Part contains critical constraints that prevent errors +- Part defines required output format or structure + +HELPFUL (5-7): +- Part improves output quality but is not strictly required +- Part provides useful context that guides better decisions +- Part contains preferences that affect style but not correctness + +MARGINAL (2-4): +- Part has tangential relevance to the task +- Part might occasionally be useful but usually is not +- Part provides historical context rarely needed + +DISTRACTOR (0-1): +- Part is irrelevant to the task +- Part could confuse the agent about what to focus on +- Part competes for attention without contributing value + + + +RELEVANCE_SCORE: [0-10] +JUSTIFICATION: [2-3 sentences explaining the score] +USAGE_LIKELIHOOD: [How often would the agent reference this part during task execution? ALWAYS | OFTEN | SOMETIMES | RARELY | NEVER] + +``` + +**Step 3: Aggregate Relevance Scores** + +Collect scores from all scoring agents: + +``` +PART_SCORES = [ + {id: "background", score: 8, usage: "ALWAYS"}, + {id: "code_style_rules", score: 9, usage: "ALWAYS"}, + {id: "historical_context", score: 3, usage: "RARELY"}, + {id: "output_format", score: 7, usage: "OFTEN"} +] +``` + +Calculate aggregate metrics: + +``` +total_parts = count(PART_SCORES) +high_relevance_parts = count(parts where score >= 5) +distractor_parts = count(parts where score < 5) + +context_efficiency = high_relevance_parts / total_parts +average_relevance = sum(scores) / total_parts +``` + +**Step 4: Identify Distractor Parts** + +Apply the distractor threshold (score < 5): + +```markdown +DISTRACTOR_ANALYSIS: + +Identified Distractors: +1. PART: historical_context + SCORE: 3/10 + JUSTIFICATION: "Migration history from Python 2.7 is rarely relevant to reviewing current code. The naming convention note is useful but should be in code_style_rules instead." + RECOMMENDATION: REMOVE or RELOCATE + +Summary: +- Total parts: 4 +- High-relevance parts (>=5): 3 +- Distractor parts (<5): 1 +- Context efficiency: 75% +- Average relevance: 6.75 + +Token Impact: +- Distractor tokens: ~45 (historical_context) +- Potential savings: 45 tokens (11% of prompt) +``` + +**Step 5: Generate Optimization Recommendations** + +Based on distractor analysis, provide actionable recommendations: + +```markdown +OPTIMIZATION_RECOMMENDATIONS: + +1. REMOVE: historical_context + Reason: Score 3/10, usage RARELY. Migration history does not inform code review decisions. + +2. RELOCATE: "we now use snake_case" from historical_context + Target: code_style_rules section + Reason: This specific rule is relevant but buried in irrelevant historical context. + +3. CONSIDER CONDENSING: background + Current: 2 sentences + Could be: 1 sentence ("Python 3.9+ data pipeline expert") + Savings: ~15 tokens + +OPTIMIZED PROMPT STRUCTURE: +- background (condensed): 8 tokens +- code_style_rules (with snake_case added): 52 tokens +- output_format: 28 tokens +- Total: 88 tokens (down from 133 tokens) +- Efficiency improvement: 34% reduction +``` + +### Distractor Threshold Guidelines + +The default threshold of 5 balances comprehensiveness against efficiency: + +| Threshold | Use Case | +|-----------|----------| +| < 3 | Aggressive pruning for token-constrained contexts | +| < 5 | Standard optimization (recommended default) | +| < 7 | Conservative pruning for critical prompts | + +Adjust threshold based on: +- **Context budget pressure**: Lower threshold when approaching limits +- **Task criticality**: Higher threshold for production prompts +- **Prompt stability**: Lower threshold for experimental prompts + +### Scoring Agent Deployment + +For efficiency, parallelize scoring agents: + +```markdown +# Parallel execution pattern +spawn_parallel([ + scoring_agent(part_1, task_description), + scoring_agent(part_2, task_description), + scoring_agent(part_3, task_description), + ... +]) + +# Collect and aggregate +scores = await_all(scoring_agents) +analysis = aggregate_scores(scores) +``` + +For large prompts (>10 parts), batch scoring agents in groups of 5-7 to manage orchestration overhead. + +## Context Health Monitoring Workflow + +Long-running agent sessions accumulate context that degrades over time. This workflow monitors context health and triggers intervention. + +### When to Use + +- During long-running agent sessions (>20 turns) +- When agents start exhibiting degradation symptoms +- As a periodic health check in agent orchestration systems +- Before critical decision points in agent workflows + +### Health Check Pattern + +**Step 1: Periodic Symptom Detection** + +Every N turns (recommended: every 10 turns), spawn a health check agent: + +```markdown + +Analyze the recent conversation history for signs of context degradation. + + + +{last 10 turns of conversation} + + + +Check for these degradation symptoms: + +LOST_IN_MIDDLE: +- [ ] Agent missing instructions from early in conversation +- [ ] Critical constraints being ignored +- [ ] Agent asking for information already provided + +CONTEXT_POISONING: +- [ ] Same error appearing repeatedly +- [ ] Agent referencing incorrect information as fact +- [ ] Hallucinations that persist despite correction + +CONTEXT_DISTRACTION: +- [ ] Responses becoming unfocused +- [ ] Agent using irrelevant context inappropriately +- [ ] Quality declining on previously-successful tasks + +CONTEXT_CONFUSION: +- [ ] Agent mixing up different task requirements +- [ ] Wrong tool selections for obvious tasks +- [ ] Outputs that blend requirements from different tasks + +CONTEXT_CLASH: +- [ ] Agent expressing uncertainty about conflicting information +- [ ] Inconsistent behavior between turns +- [ ] Agent asking for clarification on resolved issues + + + +HEALTH_STATUS: [HEALTHY | DEGRADED | CRITICAL] +SYMPTOMS_DETECTED: [list of checked symptoms] +RECOMMENDED_ACTION: [CONTINUE | COMPACT | RESTART] +SPECIFIC_ISSUES: [detailed description of problems found] + +``` + +**Step 2: Automated Intervention** + +Based on health status, trigger appropriate intervention: + +```markdown +IF HEALTH_STATUS == "DEGRADED" or HEALTH_STATUS == "CRITICAL": + + 1. Extract essential state to preserve and save to a file + 2. Ask user to start a new session with clean context and load the preserved state from the file after the new session is started + +``` + +## Guidelines for Multi-Agent Verification + +1. Spawn verification agents with focused, single-purpose prompts +2. Use structured output formats for reliable parsing +3. Set clear thresholds for action vs. continue decisions +4. Log all verification results for debugging and optimization +5. Balance verification overhead against error prevention value +6. Implement verification at natural checkpoints, not every turn +7. Use lighter-weight checks for routine operations, heavier for critical ones +8. Design verification to be skippable in time-critical scenarios + +# Context Optimization Techniques + +Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity. Effective optimization can double or triple effective context capacity without requiring larger models or longer contexts. + +## Core Concepts + +Context optimization extends effective capacity through four primary strategies: compaction (summarizing context near limits), observation masking (replacing verbose outputs with references), KV-cache optimization (reusing cached computations), and context partitioning (splitting work across isolated contexts). + +The key insight is that context quality matters more than quantity. Optimization preserves signal while reducing noise. The art lies in selecting what to keep versus what to discard, and when to apply each technique. + +## Detailed Topics + +### Compaction Strategies + +**What is Compaction** +Compaction is the practice of summarizing context contents when approaching limits, then reinitializing a new context window with the summary. This distills the contents of a context window in a high-fidelity manner, enabling the agent to continue with minimal performance degradation. + +Compaction typically serves as the first lever in context optimization. The art lies in selecting what to keep versus what to discard. + +**Compaction in Practice** +Compaction works by identifying sections that can be compressed, generating summaries that capture essential points, and replacing full content with summaries. Priority for compression: + +1. **Tool outputs** - Replace verbose outputs with key findings +2. **Old conversation turns** - Summarize early exchanges +3. **Retrieved documents** - Summarize if task context captured +4. **Never compress** - System prompt and critical constraints + +**Summary Generation** +Effective summaries preserve different elements depending on content type: + +- **Tool outputs**: Preserve key findings, metrics, and conclusions. Remove verbose raw output. +- **Conversational turns**: Preserve key decisions, commitments, and context shifts. Remove filler and back-and-forth. +- **Retrieved documents**: Preserve key facts and claims. Remove supporting evidence and elaboration. + +### Observation Masking + +**The Observation Problem** +Tool outputs can comprise 80%+ of token usage in agent trajectories. Much of this is verbose output that has already served its purpose. Once an agent has used a tool output to make a decision, keeping the full output provides diminishing value while consuming significant context. + +Observation masking replaces verbose tool outputs with compact references. The information remains accessible if needed but does not consume context continuously. + +**Masking Strategy Selection** +Not all observations should be masked equally: + +**Never mask:** +- Observations critical to current task +- Observations from the most recent turn +- Observations used in active reasoning + +**Consider masking:** +- Observations from 3+ turns ago +- Verbose outputs with key points extractable +- Observations whose purpose has been served + +**Always mask:** +- Repeated outputs +- Boilerplate headers/footers +- Outputs already summarized in conversation + +### Context Partitioning + +**Sub-Agent Partitioning** +The most aggressive form of context optimization is partitioning work across sub-agents with isolated contexts. Each sub-agent operates in a clean context focused on its subtask without carrying accumulated context from other subtasks. + +This approach achieves separation of concerns--the detailed search context remains isolated within sub-agents while the coordinator focuses on synthesis and analysis. + +**When to Partition** +Consider partitioning when: +- Task naturally decomposes into independent subtasks +- Different subtasks require different specialized context +- Context accumulation threatens to exceed limits +- Different subtasks have conflicting requirements + +**Result Aggregation** +Aggregate results from partitioned subtasks by: +1. Validating all partitions completed +2. Merging compatible results +3. Summarizing if combined results still too large +4. Resolving conflicts between partition outputs + + +## Practical Guidance + +### Optimization Decision Framework + +**When to optimize:** +- Response quality degrades as conversations extend +- Costs increase due to long contexts +- Latency increases with conversation length + +**What to apply:** +- Tool outputs dominate: observation masking +- Retrieved documents dominate: summarization or partitioning +- Message history dominates: compaction with summarization +- Multiple components: combine strategies + +### Applying Optimization to Claude Code Prompts + +**Command Optimization** +Commands load on-demand, so focus on keeping individual commands focused: +```markdown +# Good: Focused command with clear scope +--- +name: review-security +description: Review code for security vulnerabilities +--- +# Specific security review instructions only + +# Avoid: Overloaded command trying to do everything +--- +name: review-all +description: Review code for everything +--- +# 50 different review checklists crammed together +``` + +**Skill Optimization** +Skills load their descriptions by default, so descriptions must be concise: +```markdown +# Good: Concise description +description: Analyze code architecture. Use for design reviews. + +# Avoid: Verbose description that wastes context budget +description: This skill provides comprehensive analysis of code +architecture including but not limited to class hierarchies, +dependency graphs, coupling metrics, cohesion analysis... +``` + +**Sub-Agent Context Design** +When spawning sub-agents, provide focused context: +```markdown +# Coordinator provides minimal handoff: +"Review authentication module for security issues. +Return findings in structured format." + +# NOT this verbose handoff: +"I need you to look at the authentication module which is +located in src/auth/ and contains several files including +login.ts, session.ts, tokens.ts... [500 more tokens of context]" +``` + +## Guidelines + +1. Measure before optimizing--know your current state +2. Apply compaction before masking when possible +3. Design for cache stability with consistent prompts +4. Partition before context becomes problematic +5. Monitor optimization effectiveness over time +6. Balance token savings against quality preservation +7. Test optimization at production scale +8. Implement graceful degradation for edge cases \ No newline at end of file diff --git a/.claude/skills/planning-with-files/SKILL.md b/.claude/skills/planning-with-files/SKILL.md new file mode 100644 index 0000000..84d026a --- /dev/null +++ b/.claude/skills/planning-with-files/SKILL.md @@ -0,0 +1,211 @@ +--- +name: planning-with-files +version: "2.1.2" +description: Implements Manus-style file-based planning for complex tasks. Creates task_plan.md, findings.md, and progress.md. Use when starting complex multi-step tasks, research projects, or any task requiring >5 tool calls. +user-invocable: true +allowed-tools: + - Read + - Write + - Edit + - Bash + - Glob + - Grep + - WebFetch + - WebSearch +hooks: + SessionStart: + - hooks: + - type: command + command: "echo '[planning-with-files] Ready. Auto-activates for complex tasks, or invoke manually with /planning-with-files'" + PreToolUse: + - matcher: "Write|Edit|Bash" + hooks: + - type: command + command: "cat task_plan.md 2>/dev/null | head -30 || true" + PostToolUse: + - matcher: "Write|Edit" + hooks: + - type: command + command: "echo '[planning-with-files] File updated. If this completes a phase, update task_plan.md status.'" + Stop: + - hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/check-complete.sh" +--- + +# Planning with Files + +Work like Manus: Use persistent markdown files as your "working memory on disk." + +## Important: Where Files Go + +When using this skill: + +- **Templates** are stored in the skill directory at `${CLAUDE_PLUGIN_ROOT}/templates/` +- **Your planning files** (`task_plan.md`, `findings.md`, `progress.md`) should be created in **your project directory** — the folder where you're working + +| Location | What Goes There | +|----------|-----------------| +| Skill directory (`${CLAUDE_PLUGIN_ROOT}/`) | Templates, scripts, reference docs | +| Your project directory | `task_plan.md`, `findings.md`, `progress.md` | + +This ensures your planning files live alongside your code, not buried in the skill installation folder. + +## Quick Start + +Before ANY complex task: + +1. **Create `task_plan.md`** in your project — Use [templates/task_plan.md](templates/task_plan.md) as reference +2. **Create `findings.md`** in your project — Use [templates/findings.md](templates/findings.md) as reference +3. **Create `progress.md`** in your project — Use [templates/progress.md](templates/progress.md) as reference +4. **Re-read plan before decisions** — Refreshes goals in attention window +5. **Update after each phase** — Mark complete, log errors + +> **Note:** All three planning files should be created in your current working directory (your project root), not in the skill's installation folder. + +## The Core Pattern + +``` +Context Window = RAM (volatile, limited) +Filesystem = Disk (persistent, unlimited) + +→ Anything important gets written to disk. +``` + +## File Purposes + +| File | Purpose | When to Update | +|------|---------|----------------| +| `task_plan.md` | Phases, progress, decisions | After each phase | +| `findings.md` | Research, discoveries | After ANY discovery | +| `progress.md` | Session log, test results | Throughout session | + +## Critical Rules + +### 1. Create Plan First +Never start a complex task without `task_plan.md`. Non-negotiable. + +### 2. The 2-Action Rule +> "After every 2 view/browser/search operations, IMMEDIATELY save key findings to text files." + +This prevents visual/multimodal information from being lost. + +### 3. Read Before Decide +Before major decisions, read the plan file. This keeps goals in your attention window. + +### 4. Update After Act +After completing any phase: +- Mark phase status: `in_progress` → `complete` +- Log any errors encountered +- Note files created/modified + +### 5. Log ALL Errors +Every error goes in the plan file. This builds knowledge and prevents repetition. + +```markdown +## Errors Encountered +| Error | Attempt | Resolution | +|-------|---------|------------| +| FileNotFoundError | 1 | Created default config | +| API timeout | 2 | Added retry logic | +``` + +### 6. Never Repeat Failures +``` +if action_failed: + next_action != same_action +``` +Track what you tried. Mutate the approach. + +## The 3-Strike Error Protocol + +``` +ATTEMPT 1: Diagnose & Fix + → Read error carefully + → Identify root cause + → Apply targeted fix + +ATTEMPT 2: Alternative Approach + → Same error? Try different method + → Different tool? Different library? + → NEVER repeat exact same failing action + +ATTEMPT 3: Broader Rethink + → Question assumptions + → Search for solutions + → Consider updating the plan + +AFTER 3 FAILURES: Escalate to User + → Explain what you tried + → Share the specific error + → Ask for guidance +``` + +## Read vs Write Decision Matrix + +| Situation | Action | Reason | +|-----------|--------|--------| +| Just wrote a file | DON'T read | Content still in context | +| Viewed image/PDF | Write findings NOW | Multimodal → text before lost | +| Browser returned data | Write to file | Screenshots don't persist | +| Starting new phase | Read plan/findings | Re-orient if context stale | +| Error occurred | Read relevant file | Need current state to fix | +| Resuming after gap | Read all planning files | Recover state | + +## The 5-Question Reboot Test + +If you can answer these, your context management is solid: + +| Question | Answer Source | +|----------|---------------| +| Where am I? | Current phase in task_plan.md | +| Where am I going? | Remaining phases | +| What's the goal? | Goal statement in plan | +| What have I learned? | findings.md | +| What have I done? | progress.md | + +## When to Use This Pattern + +**Use for:** +- Multi-step tasks (3+ steps) +- Research tasks +- Building/creating projects +- Tasks spanning many tool calls +- Anything requiring organization + +**Skip for:** +- Simple questions +- Single-file edits +- Quick lookups + +## Templates + +Copy these templates to start: + +- [templates/task_plan.md](templates/task_plan.md) — Phase tracking +- [templates/findings.md](templates/findings.md) — Research storage +- [templates/progress.md](templates/progress.md) — Session logging + +## Scripts + +Helper scripts for automation: + +- `scripts/init-session.sh` — Initialize all planning files +- `scripts/check-complete.sh` — Verify all phases complete + +## Advanced Topics + +- **Manus Principles:** See [reference.md](reference.md) +- **Real Examples:** See [examples.md](examples.md) + +## Anti-Patterns + +| Don't | Do Instead | +|-------|------------| +| Use TodoWrite for persistence | Create task_plan.md file | +| State goals once and forget | Re-read plan before decisions | +| Hide errors and retry silently | Log errors to plan file | +| Stuff everything in context | Store large content in files | +| Start executing immediately | Create plan file FIRST | +| Repeat failed actions | Track attempts, mutate approach | +| Create files in skill directory | Create files in your project | diff --git a/.claude/skills/planning-with-files/examples.md b/.claude/skills/planning-with-files/examples.md new file mode 100644 index 0000000..51b5f3a --- /dev/null +++ b/.claude/skills/planning-with-files/examples.md @@ -0,0 +1,202 @@ +# Examples: Planning with Files in Action + +## Example 1: Research Task + +**User Request:** "Research the benefits of morning exercise and write a summary" + +### Loop 1: Create Plan +```bash +Write task_plan.md +``` + +```markdown +# Task Plan: Morning Exercise Benefits Research + +## Goal +Create a research summary on the benefits of morning exercise. + +## Phases +- [ ] Phase 1: Create this plan ✓ +- [ ] Phase 2: Search and gather sources +- [ ] Phase 3: Synthesize findings +- [ ] Phase 4: Deliver summary + +## Key Questions +1. What are the physical health benefits? +2. What are the mental health benefits? +3. What scientific studies support this? + +## Status +**Currently in Phase 1** - Creating plan +``` + +### Loop 2: Research +```bash +Read task_plan.md # Refresh goals +WebSearch "morning exercise benefits" +Write notes.md # Store findings +Edit task_plan.md # Mark Phase 2 complete +``` + +### Loop 3: Synthesize +```bash +Read task_plan.md # Refresh goals +Read notes.md # Get findings +Write morning_exercise_summary.md +Edit task_plan.md # Mark Phase 3 complete +``` + +### Loop 4: Deliver +```bash +Read task_plan.md # Verify complete +Deliver morning_exercise_summary.md +``` + +--- + +## Example 2: Bug Fix Task + +**User Request:** "Fix the login bug in the authentication module" + +### task_plan.md +```markdown +# Task Plan: Fix Login Bug + +## Goal +Identify and fix the bug preventing successful login. + +## Phases +- [x] Phase 1: Understand the bug report ✓ +- [x] Phase 2: Locate relevant code ✓ +- [ ] Phase 3: Identify root cause (CURRENT) +- [ ] Phase 4: Implement fix +- [ ] Phase 5: Test and verify + +## Key Questions +1. What error message appears? +2. Which file handles authentication? +3. What changed recently? + +## Decisions Made +- Auth handler is in src/auth/login.ts +- Error occurs in validateToken() function + +## Errors Encountered +- [Initial] TypeError: Cannot read property 'token' of undefined + → Root cause: user object not awaited properly + +## Status +**Currently in Phase 3** - Found root cause, preparing fix +``` + +--- + +## Example 3: Feature Development + +**User Request:** "Add a dark mode toggle to the settings page" + +### The 3-File Pattern in Action + +**task_plan.md:** +```markdown +# Task Plan: Dark Mode Toggle + +## Goal +Add functional dark mode toggle to settings. + +## Phases +- [x] Phase 1: Research existing theme system ✓ +- [x] Phase 2: Design implementation approach ✓ +- [ ] Phase 3: Implement toggle component (CURRENT) +- [ ] Phase 4: Add theme switching logic +- [ ] Phase 5: Test and polish + +## Decisions Made +- Using CSS custom properties for theme +- Storing preference in localStorage +- Toggle component in SettingsPage.tsx + +## Status +**Currently in Phase 3** - Building toggle component +``` + +**notes.md:** +```markdown +# Notes: Dark Mode Implementation + +## Existing Theme System +- Located in: src/styles/theme.ts +- Uses: CSS custom properties +- Current themes: light only + +## Files to Modify +1. src/styles/theme.ts - Add dark theme colors +2. src/components/SettingsPage.tsx - Add toggle +3. src/hooks/useTheme.ts - Create new hook +4. src/App.tsx - Wrap with ThemeProvider + +## Color Decisions +- Dark background: #1a1a2e +- Dark surface: #16213e +- Dark text: #eaeaea +``` + +**dark_mode_implementation.md:** (deliverable) +```markdown +# Dark Mode Implementation + +## Changes Made + +### 1. Added dark theme colors +File: src/styles/theme.ts +... + +### 2. Created useTheme hook +File: src/hooks/useTheme.ts +... +``` + +--- + +## Example 4: Error Recovery Pattern + +When something fails, DON'T hide it: + +### Before (Wrong) +``` +Action: Read config.json +Error: File not found +Action: Read config.json # Silent retry +Action: Read config.json # Another retry +``` + +### After (Correct) +``` +Action: Read config.json +Error: File not found + +# Update task_plan.md: +## Errors Encountered +- config.json not found → Will create default config + +Action: Write config.json (default config) +Action: Read config.json +Success! +``` + +--- + +## The Read-Before-Decide Pattern + +**Always read your plan before major decisions:** + +``` +[Many tool calls have happened...] +[Context is getting long...] +[Original goal might be forgotten...] + +→ Read task_plan.md # This brings goals back into attention! +→ Now make the decision # Goals are fresh in context +``` + +This is why Manus can handle ~50 tool calls without losing track. The plan file acts as a "goal refresh" mechanism. diff --git a/.claude/skills/planning-with-files/reference.md b/.claude/skills/planning-with-files/reference.md new file mode 100644 index 0000000..1380fbb --- /dev/null +++ b/.claude/skills/planning-with-files/reference.md @@ -0,0 +1,218 @@ +# Reference: Manus Context Engineering Principles + +This skill is based on context engineering principles from Manus, the AI agent company acquired by Meta for $2 billion in December 2025. + +## The 6 Manus Principles + +### Principle 1: Design Around KV-Cache + +> "KV-cache hit rate is THE single most important metric for production AI agents." + +**Statistics:** +- ~100:1 input-to-output token ratio +- Cached tokens: $0.30/MTok vs Uncached: $3/MTok +- 10x cost difference! + +**Implementation:** +- Keep prompt prefixes STABLE (single-token change invalidates cache) +- NO timestamps in system prompts +- Make context APPEND-ONLY with deterministic serialization + +### Principle 2: Mask, Don't Remove + +Don't dynamically remove tools (breaks KV-cache). Use logit masking instead. + +**Best Practice:** Use consistent action prefixes (e.g., `browser_`, `shell_`, `file_`) for easier masking. + +### Principle 3: Filesystem as External Memory + +> "Markdown is my 'working memory' on disk." + +**The Formula:** +``` +Context Window = RAM (volatile, limited) +Filesystem = Disk (persistent, unlimited) +``` + +**Compression Must Be Restorable:** +- Keep URLs even if web content is dropped +- Keep file paths when dropping document contents +- Never lose the pointer to full data + +### Principle 4: Manipulate Attention Through Recitation + +> "Creates and updates todo.md throughout tasks to push global plan into model's recent attention span." + +**Problem:** After ~50 tool calls, models forget original goals ("lost in the middle" effect). + +**Solution:** Re-read `task_plan.md` before each decision. Goals appear in the attention window. + +``` +Start of context: [Original goal - far away, forgotten] +...many tool calls... +End of context: [Recently read task_plan.md - gets ATTENTION!] +``` + +### Principle 5: Keep the Wrong Stuff In + +> "Leave the wrong turns in the context." + +**Why:** +- Failed actions with stack traces let model implicitly update beliefs +- Reduces mistake repetition +- Error recovery is "one of the clearest signals of TRUE agentic behavior" + +### Principle 6: Don't Get Few-Shotted + +> "Uniformity breeds fragility." + +**Problem:** Repetitive action-observation pairs cause drift and hallucination. + +**Solution:** Introduce controlled variation: +- Vary phrasings slightly +- Don't copy-paste patterns blindly +- Recalibrate on repetitive tasks + +--- + +## The 3 Context Engineering Strategies + +Based on Lance Martin's analysis of Manus architecture. + +### Strategy 1: Context Reduction + +**Compaction:** +``` +Tool calls have TWO representations: +├── FULL: Raw tool content (stored in filesystem) +└── COMPACT: Reference/file path only + +RULES: +- Apply compaction to STALE (older) tool results +- Keep RECENT results FULL (to guide next decision) +``` + +**Summarization:** +- Applied when compaction reaches diminishing returns +- Generated using full tool results +- Creates standardized summary objects + +### Strategy 2: Context Isolation (Multi-Agent) + +**Architecture:** +``` +┌─────────────────────────────────┐ +│ PLANNER AGENT │ +│ └─ Assigns tasks to sub-agents │ +├─────────────────────────────────┤ +│ KNOWLEDGE MANAGER │ +│ └─ Reviews conversations │ +│ └─ Determines filesystem store │ +├─────────────────────────────────┤ +│ EXECUTOR SUB-AGENTS │ +│ └─ Perform assigned tasks │ +│ └─ Have own context windows │ +└─────────────────────────────────┘ +``` + +**Key Insight:** Manus originally used `todo.md` for task planning but found ~33% of actions were spent updating it. Shifted to dedicated planner agent calling executor sub-agents. + +### Strategy 3: Context Offloading + +**Tool Design:** +- Use <20 atomic functions total +- Store full results in filesystem, not context +- Use `glob` and `grep` for searching +- Progressive disclosure: load information only as needed + +--- + +## The Agent Loop + +Manus operates in a continuous 7-step loop: + +``` +┌─────────────────────────────────────────┐ +│ 1. ANALYZE CONTEXT │ +│ - Understand user intent │ +│ - Assess current state │ +│ - Review recent observations │ +├─────────────────────────────────────────┤ +│ 2. THINK │ +│ - Should I update the plan? │ +│ - What's the next logical action? │ +│ - Are there blockers? │ +├─────────────────────────────────────────┤ +│ 3. SELECT TOOL │ +│ - Choose ONE tool │ +│ - Ensure parameters available │ +├─────────────────────────────────────────┤ +│ 4. EXECUTE ACTION │ +│ - Tool runs in sandbox │ +├─────────────────────────────────────────┤ +│ 5. RECEIVE OBSERVATION │ +│ - Result appended to context │ +├─────────────────────────────────────────┤ +│ 6. ITERATE │ +│ - Return to step 1 │ +│ - Continue until complete │ +├─────────────────────────────────────────┤ +│ 7. DELIVER OUTCOME │ +│ - Send results to user │ +│ - Attach all relevant files │ +└─────────────────────────────────────────┘ +``` + +--- + +## File Types Manus Creates + +| File | Purpose | When Created | When Updated | +|------|---------|--------------|--------------| +| `task_plan.md` | Phase tracking, progress | Task start | After completing phases | +| `findings.md` | Discoveries, decisions | After ANY discovery | After viewing images/PDFs | +| `progress.md` | Session log, what's done | At breakpoints | Throughout session | +| Code files | Implementation | Before execution | After errors | + +--- + +## Critical Constraints + +- **Single-Action Execution:** ONE tool call per turn. No parallel execution. +- **Plan is Required:** Agent must ALWAYS know: goal, current phase, remaining phases +- **Files are Memory:** Context = volatile. Filesystem = persistent. +- **Never Repeat Failures:** If action failed, next action MUST be different +- **Communication is a Tool:** Message types: `info` (progress), `ask` (blocking), `result` (terminal) + +--- + +## Manus Statistics + +| Metric | Value | +|--------|-------| +| Average tool calls per task | ~50 | +| Input-to-output token ratio | 100:1 | +| Acquisition price | $2 billion | +| Time to $100M revenue | 8 months | +| Framework refactors since launch | 5 times | + +--- + +## Key Quotes + +> "Context window = RAM (volatile, limited). Filesystem = Disk (persistent, unlimited). Anything important gets written to disk." + +> "if action_failed: next_action != same_action. Track what you tried. Mutate the approach." + +> "Error recovery is one of the clearest signals of TRUE agentic behavior." + +> "KV-cache hit rate is the single most important metric for a production-stage AI agent." + +> "Leave the wrong turns in the context." + +--- + +## Source + +Based on Manus's official context engineering documentation: +https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus diff --git a/.claude/skills/planning-with-files/scripts/check-complete.sh b/.claude/skills/planning-with-files/scripts/check-complete.sh new file mode 100644 index 0000000..d17a3e4 --- /dev/null +++ b/.claude/skills/planning-with-files/scripts/check-complete.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Check if all phases in task_plan.md are complete +# Exit 0 if complete, exit 1 if incomplete +# Used by Stop hook to verify task completion + +PLAN_FILE="${1:-task_plan.md}" + +if [ ! -f "$PLAN_FILE" ]; then + echo "ERROR: $PLAN_FILE not found" + echo "Cannot verify completion without a task plan." + exit 1 +fi + +echo "=== Task Completion Check ===" +echo "" + +# Count phases by status (using -F for fixed string matching) +TOTAL=$(grep -c "### Phase" "$PLAN_FILE" || true) +COMPLETE=$(grep -cF "**Status:** complete" "$PLAN_FILE" || true) +IN_PROGRESS=$(grep -cF "**Status:** in_progress" "$PLAN_FILE" || true) +PENDING=$(grep -cF "**Status:** pending" "$PLAN_FILE" || true) + +# Default to 0 if empty +: "${TOTAL:=0}" +: "${COMPLETE:=0}" +: "${IN_PROGRESS:=0}" +: "${PENDING:=0}" + +echo "Total phases: $TOTAL" +echo "Complete: $COMPLETE" +echo "In progress: $IN_PROGRESS" +echo "Pending: $PENDING" +echo "" + +# Check completion +if [ "$COMPLETE" -eq "$TOTAL" ] && [ "$TOTAL" -gt 0 ]; then + echo "ALL PHASES COMPLETE" + exit 0 +else + echo "TASK NOT COMPLETE" + echo "" + echo "Do not stop until all phases are complete." + exit 1 +fi diff --git a/.claude/skills/planning-with-files/scripts/init-session.sh b/.claude/skills/planning-with-files/scripts/init-session.sh new file mode 100644 index 0000000..1c60de8 --- /dev/null +++ b/.claude/skills/planning-with-files/scripts/init-session.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# Initialize planning files for a new session +# Usage: ./init-session.sh [project-name] + +set -e + +PROJECT_NAME="${1:-project}" +DATE=$(date +%Y-%m-%d) + +echo "Initializing planning files for: $PROJECT_NAME" + +# Create task_plan.md if it doesn't exist +if [ ! -f "task_plan.md" ]; then + cat > task_plan.md << 'EOF' +# Task Plan: [Brief Description] + +## Goal +[One sentence describing the end state] + +## Current Phase +Phase 1 + +## Phases + +### Phase 1: Requirements & Discovery +- [ ] Understand user intent +- [ ] Identify constraints +- [ ] Document in findings.md +- **Status:** in_progress + +### Phase 2: Planning & Structure +- [ ] Define approach +- [ ] Create project structure +- **Status:** pending + +### Phase 3: Implementation +- [ ] Execute the plan +- [ ] Write to files before executing +- **Status:** pending + +### Phase 4: Testing & Verification +- [ ] Verify requirements met +- [ ] Document test results +- **Status:** pending + +### Phase 5: Delivery +- [ ] Review outputs +- [ ] Deliver to user +- **Status:** pending + +## Decisions Made +| Decision | Rationale | +|----------|-----------| + +## Errors Encountered +| Error | Resolution | +|-------|------------| +EOF + echo "Created task_plan.md" +else + echo "task_plan.md already exists, skipping" +fi + +# Create findings.md if it doesn't exist +if [ ! -f "findings.md" ]; then + cat > findings.md << 'EOF' +# Findings & Decisions + +## Requirements +- + +## Research Findings +- + +## Technical Decisions +| Decision | Rationale | +|----------|-----------| + +## Issues Encountered +| Issue | Resolution | +|-------|------------| + +## Resources +- +EOF + echo "Created findings.md" +else + echo "findings.md already exists, skipping" +fi + +# Create progress.md if it doesn't exist +if [ ! -f "progress.md" ]; then + cat > progress.md << EOF +# Progress Log + +## Session: $DATE + +### Current Status +- **Phase:** 1 - Requirements & Discovery +- **Started:** $DATE + +### Actions Taken +- + +### Test Results +| Test | Expected | Actual | Status | +|------|----------|--------|--------| + +### Errors +| Error | Resolution | +|-------|------------| +EOF + echo "Created progress.md" +else + echo "progress.md already exists, skipping" +fi + +echo "" +echo "Planning files initialized!" +echo "Files: task_plan.md, findings.md, progress.md" diff --git a/.claude/skills/planning-with-files/templates/findings.md b/.claude/skills/planning-with-files/templates/findings.md new file mode 100644 index 0000000..056536d --- /dev/null +++ b/.claude/skills/planning-with-files/templates/findings.md @@ -0,0 +1,95 @@ +# Findings & Decisions + + +## Requirements + + +- + +## Research Findings + + +- + +## Technical Decisions + + +| Decision | Rationale | +|----------|-----------| +| | | + +## Issues Encountered + + +| Issue | Resolution | +|-------|------------| +| | | + +## Resources + + +- + +## Visual/Browser Findings + + + +- + +--- + +*Update this file after every 2 view/browser/search operations* +*This prevents visual information from being lost* diff --git a/.claude/skills/planning-with-files/templates/progress.md b/.claude/skills/planning-with-files/templates/progress.md new file mode 100644 index 0000000..dba9af9 --- /dev/null +++ b/.claude/skills/planning-with-files/templates/progress.md @@ -0,0 +1,114 @@ +# Progress Log + + +## Session: [DATE] + + +### Phase 1: [Title] + +- **Status:** in_progress +- **Started:** [timestamp] + +- Actions taken: + + - +- Files created/modified: + + - + +### Phase 2: [Title] + +- **Status:** pending +- Actions taken: + - +- Files created/modified: + - + +## Test Results + +| Test | Input | Expected | Actual | Status | +|------|-------|----------|--------|--------| +| | | | | | + +## Error Log + + +| Timestamp | Error | Attempt | Resolution | +|-----------|-------|---------|------------| +| | | 1 | | + +## 5-Question Reboot Check + + +| Question | Answer | +|----------|--------| +| Where am I? | Phase X | +| Where am I going? | Remaining phases | +| What's the goal? | [goal statement] | +| What have I learned? | See findings.md | +| What have I done? | See above | + +--- + +*Update after completing each phase or encountering errors* diff --git a/.claude/skills/planning-with-files/templates/task_plan.md b/.claude/skills/planning-with-files/templates/task_plan.md new file mode 100644 index 0000000..cc85896 --- /dev/null +++ b/.claude/skills/planning-with-files/templates/task_plan.md @@ -0,0 +1,132 @@ +# Task Plan: [Brief Description] + + +## Goal + +[One sentence describing the end state] + +## Current Phase + +Phase 1 + +## Phases + + +### Phase 1: Requirements & Discovery + +- [ ] Understand user intent +- [ ] Identify constraints and requirements +- [ ] Document findings in findings.md +- **Status:** in_progress + + +### Phase 2: Planning & Structure + +- [ ] Define technical approach +- [ ] Create project structure if needed +- [ ] Document decisions with rationale +- **Status:** pending + +### Phase 3: Implementation + +- [ ] Execute the plan step by step +- [ ] Write code to files before executing +- [ ] Test incrementally +- **Status:** pending + +### Phase 4: Testing & Verification + +- [ ] Verify all requirements met +- [ ] Document test results in progress.md +- [ ] Fix any issues found +- **Status:** pending + +### Phase 5: Delivery + +- [ ] Review all output files +- [ ] Ensure deliverables are complete +- [ ] Deliver to user +- **Status:** pending + +## Key Questions + +1. [Question to answer] +2. [Question to answer] + +## Decisions Made + +| Decision | Rationale | +|----------|-----------| +| | | + +## Errors Encountered + +| Error | Attempt | Resolution | +|-------|---------|------------| +| | 1 | | + +## Notes + +- Update phase status as you progress: pending → in_progress → complete +- Re-read this plan before major decisions (attention manipulation) +- Log ALL errors - they help avoid repetition diff --git a/.claude/skills/prompt-engineering/SKILL.md b/.claude/skills/prompt-engineering/SKILL.md new file mode 100644 index 0000000..40bb455 --- /dev/null +++ b/.claude/skills/prompt-engineering/SKILL.md @@ -0,0 +1,559 @@ +--- +name: prompt-engineering +description: Use this skill when you writing commands, hooks, skills for Agent, or prompts for sub agents or any other LLM interaction, including optimizing prompts, improving LLM outputs, or designing production prompt templates. +--- + +# Prompt Engineering Patterns + +Advanced prompt engineering techniques to maximize LLM performance, reliability, and controllability. + +## Core Capabilities + +### 1. Few-Shot Learning + +Teach the model by showing examples instead of explaining rules. Include 2-5 input-output pairs that demonstrate the desired behavior. Use when you need consistent formatting, specific reasoning patterns, or handling of edge cases. More examples improve accuracy but consume tokens—balance based on task complexity. + +**Example:** + +```markdown +Extract key information from support tickets: + +Input: "My login doesn't work and I keep getting error 403" +Output: {"issue": "authentication", "error_code": "403", "priority": "high"} + +Input: "Feature request: add dark mode to settings" +Output: {"issue": "feature_request", "error_code": null, "priority": "low"} + +Now process: "Can't upload files larger than 10MB, getting timeout" +``` + +### 2. Chain-of-Thought Prompting + +Request step-by-step reasoning before the final answer. Add "Let's think step by step" (zero-shot) or include example reasoning traces (few-shot). Use for complex problems requiring multi-step logic, mathematical reasoning, or when you need to verify the model's thought process. Improves accuracy on analytical tasks by 30-50%. + +**Example:** + +```markdown +Analyze this bug report and determine root cause. + +Think step by step: +1. What is the expected behavior? +2. What is the actual behavior? +3. What changed recently that could cause this? +4. What components are involved? +5. What is the most likely root cause? + +Bug: "Users can't save drafts after the cache update deployed yesterday" +``` + +### 3. Prompt Optimization + +Systematically improve prompts through testing and refinement. Start simple, measure performance (accuracy, consistency, token usage), then iterate. Test on diverse inputs including edge cases. Use A/B testing to compare variations. Critical for production prompts where consistency and cost matter. + +**Example:** + +```markdown +Version 1 (Simple): "Summarize this article" +→ Result: Inconsistent length, misses key points + +Version 2 (Add constraints): "Summarize in 3 bullet points" +→ Result: Better structure, but still misses nuance + +Version 3 (Add reasoning): "Identify the 3 main findings, then summarize each" +→ Result: Consistent, accurate, captures key information +``` + +### 4. Template Systems + +Build reusable prompt structures with variables, conditional sections, and modular components. Use for multi-turn conversations, role-based interactions, or when the same pattern applies to different inputs. Reduces duplication and ensures consistency across similar tasks. + +**Example:** + +```python +# Reusable code review template +template = """ +Review this {language} code for {focus_area}. + +Code: +{code_block} + +Provide feedback on: +{checklist} +""" + +# Usage +prompt = template.format( + language="Python", + focus_area="security vulnerabilities", + code_block=user_code, + checklist="1. SQL injection\n2. XSS risks\n3. Authentication" +) +``` + +### 5. System Prompt Design + +Set global behavior and constraints that persist across the conversation. Define the model's role, expertise level, output format, and safety guidelines. Use system prompts for stable instructions that shouldn't change turn-to-turn, freeing up user message tokens for variable content. + +**Example:** + +```markdown +System: You are a senior backend engineer specializing in API design. + +Rules: +- Always consider scalability and performance +- Suggest RESTful patterns by default +- Flag security concerns immediately +- Provide code examples in Python +- Use early return pattern + +Format responses as: +1. Analysis +2. Recommendation +3. Code example +4. Trade-offs +``` + +## Key Patterns + +### Progressive Disclosure + +Start with simple prompts, add complexity only when needed: + +1. **Level 1**: Direct instruction + - "Summarize this article" + +2. **Level 2**: Add constraints + - "Summarize this article in 3 bullet points, focusing on key findings" + +3. **Level 3**: Add reasoning + - "Read this article, identify the main findings, then summarize in 3 bullet points" + +4. **Level 4**: Add examples + - Include 2-3 example summaries with input-output pairs + +### Instruction Hierarchy + +``` +[System Context] → [Task Instruction] → [Examples] → [Input Data] → [Output Format] +``` + +### Error Recovery + +Build prompts that gracefully handle failures: + +- Include fallback instructions +- Request confidence scores +- Ask for alternative interpretations when uncertain +- Specify how to indicate missing information + +## Best Practices + +1. **Be Specific**: Vague prompts produce inconsistent results +2. **Show, Don't Tell**: Examples are more effective than descriptions +3. **Test Extensively**: Evaluate on diverse, representative inputs +4. **Iterate Rapidly**: Small changes can have large impacts +5. **Monitor Performance**: Track metrics in production +6. **Version Control**: Treat prompts as code with proper versioning +7. **Document Intent**: Explain why prompts are structured as they are + +## Common Pitfalls + +- **Over-engineering**: Starting with complex prompts before trying simple ones +- **Example pollution**: Using examples that don't match the target task +- **Context overflow**: Exceeding token limits with excessive examples +- **Ambiguous instructions**: Leaving room for multiple interpretations +- **Ignoring edge cases**: Not testing on unusual or boundary inputs + +## Integration Patterns + +### With RAG Systems + +```python +# Combine retrieved context with prompt engineering +prompt = f"""Given the following context: +{retrieved_context} + +{few_shot_examples} + +Question: {user_question} + +Provide a detailed answer based solely on the context above. If the context doesn't contain enough information, explicitly state what's missing.""" +``` + +### With Validation + +```python +# Add self-verification step +prompt = f"""{main_task_prompt} + +After generating your response, verify it meets these criteria: +1. Answers the question directly +2. Uses only information from provided context +3. Cites specific sources +4. Acknowledges any uncertainty + +If verification fails, revise your response.""" +``` + +## Performance Optimization + +### Token Efficiency + +- Remove redundant words and phrases +- Use abbreviations consistently after first definition +- Consolidate similar instructions +- Move stable content to system prompts + +### Latency Reduction + +- Minimize prompt length without sacrificing quality +- Use streaming for long-form outputs +- Cache common prompt prefixes +- Batch similar requests when possible + +--- + +# Agent Prompting Best Practices + +Based on Anthropic's official best practices for agent prompting. + +## Core principles + +### Context Window + +The “context window” refers to the entirety of the amount of text a language model can look back on and reference when generating new text plus the new text it generates. This is different from the large corpus of data the language model was trained on, and instead represents a “working memory” for the model. A larger context window allows the model to understand and respond to more complex and lengthy prompts, while a smaller context window may limit the model’s ability to handle longer prompts or maintain coherence over extended conversations. + +- Progressive token accumulation: As the conversation advances through turns, each user message and assistant response accumulates within the context window. Previous turns are preserved completely. +- Linear growth pattern: The context usage grows linearly with each turn, with previous turns preserved completely. +- 200K token capacity: The total available context window (200,000 tokens) represents the maximum capacity for storing conversation history and generating new output from Claude. +- Input-output flow: Each turn consists of: + - Input phase: Contains all previous conversation history plus the current user message + - Output phase: Generates a text response that becomes part of a future input + +### Concise is key + +The context window is a public good. Your prompt, command, skill shares the context window with everything else Claude needs to know, including: + +- The system prompt +- Conversation history +- Other commands, skills, hooks, metadata +- Your actual request + +**Default assumption**: Claude is already very smart + +Only add context Claude doesn't already have. Challenge each piece of information: + +- "Does Claude really need this explanation?" +- "Can I assume Claude knows this?" +- "Does this paragraph justify its token cost?" + +**Good example: Concise** (approximately 50 tokens): + +````markdown theme={null} +## Extract PDF text + +Use pdfplumber for text extraction: + +```python +import pdfplumber + +with pdfplumber.open("file.pdf") as pdf: + text = pdf.pages[0].extract_text() +``` +```` + +**Bad example: Too verbose** (approximately 150 tokens): + +```markdown theme={null} +## Extract PDF text + +PDF (Portable Document Format) files are a common file format that contains +text, images, and other content. To extract text from a PDF, you'll need to +use a library. There are many libraries available for PDF processing, but we +recommend pdfplumber because it's easy to use and handles most cases well. +First, you'll need to install it using pip. Then you can use the code below... +``` + +The concise version assumes Claude knows what PDFs are and how libraries work. + +### 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 +- Decisions depend on context +- Heuristics guide the approach + +Example: + +```markdown theme={null} +## Code review process + +1. Analyze the code structure and organization +2. Check for potential bugs or edge cases +3. Suggest improvements for readability and maintainability +4. Verify adherence to project conventions +``` + +**Medium freedom** (pseudocode or scripts with parameters): + +Use when: + +- A preferred pattern exists +- Some variation is acceptable +- Configuration affects behavior + +Example: + +````markdown theme={null} +## Generate report + +Use this template and customize as needed: + +```python +def generate_report(data, format="markdown", include_charts=True): + # Process data + # Generate output in specified format + # Optionally include visualizations +``` +```` + +**Low freedom** (specific scripts, few or no parameters): + +Use when: + +- Operations are fragile and error-prone +- Consistency is critical +- A specific sequence must be followed + +Example: + +````markdown theme={null} +## Database migration + +Run exactly this script: + +```bash +python scripts/migrate.py --verify --backup +``` + +Do not modify the command or add additional flags. +```` + +**Analogy**: Think of Claude as a robot exploring a path: + +- **Narrow bridge with cliffs on both sides**: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence. +- **Open field with no hazards**: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach. + +# Persuasion Principles for Agent Communication + +Usefull for writing prompts, including but not limited to: commands, hooks, skills for Claude Code, or prompts for sub agents or any other LLM interaction. + +## Overview + +LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure. + +**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001). + +## The Seven Principles + +### 1. Authority + +**What it is:** Deference to expertise, credentials, or official sources. + +**How it works in prompts:** + +- Imperative language: "YOU MUST", "Never", "Always" +- Non-negotiable framing: "No exceptions" +- Eliminates decision fatigue and rationalization + +**When to use:** + +- Discipline-enforcing skills (TDD, verification requirements) +- Safety-critical practices +- Established best practices + +**Example:** + +```markdown +✅ Write code before test? Delete it. Start over. No exceptions. +❌ Consider writing tests first when feasible. +``` + +### 2. Commitment + +**What it is:** Consistency with prior actions, statements, or public declarations. + +**How it works in prompts:** + +- Require announcements: "Announce skill usage" +- Force explicit choices: "Choose A, B, or C" +- Use tracking: TodoWrite for checklists + +**When to use:** + +- Ensuring skills are actually followed +- Multi-step processes +- Accountability mechanisms + +**Example:** + +```markdown +✅ When you find a skill, you MUST announce: "I'm using [Skill Name]" +❌ Consider letting your partner know which skill you're using. +``` + +### 3. Scarcity + +**What it is:** Urgency from time limits or limited availability. + +**How it works in prompts:** + +- Time-bound requirements: "Before proceeding" +- Sequential dependencies: "Immediately after X" +- Prevents procrastination + +**When to use:** + +- Immediate verification requirements +- Time-sensitive workflows +- Preventing "I'll do it later" + +**Example:** + +```markdown +✅ After completing a task, IMMEDIATELY request code review before proceeding. +❌ You can review code when convenient. +``` + +### 4. Social Proof + +**What it is:** Conformity to what others do or what's considered normal. + +**How it works in prompts:** + +- Universal patterns: "Every time", "Always" +- Failure modes: "X without Y = failure" +- Establishes norms + +**When to use:** + +- Documenting universal practices +- Warning about common failures +- Reinforcing standards + +**Example:** + +```markdown +✅ Checklists without TodoWrite tracking = steps get skipped. Every time. +❌ Some people find TodoWrite helpful for checklists. +``` + +### 5. Unity + +**What it is:** Shared identity, "we-ness", in-group belonging. + +**How it works in prompts:** + +- Collaborative language: "our codebase", "we're colleagues" +- Shared goals: "we both want quality" + +**When to use:** + +- Collaborative workflows +- Establishing team culture +- Non-hierarchical practices + +**Example:** + +```markdown +✅ We're colleagues working together. I need your honest technical judgment. +❌ You should probably tell me if I'm wrong. +``` + +### 6. Reciprocity + +**What it is:** Obligation to return benefits received. + +**How it works:** + +- Use sparingly - can feel manipulative +- Rarely needed in prompts + +**When to avoid:** + +- Almost always (other principles more effective) + +### 7. Liking + +**What it is:** Preference for cooperating with those we like. + +**How it works:** + +- **DON'T USE for compliance** +- Conflicts with honest feedback culture +- Creates sycophancy + +**When to avoid:** + +- Always for discipline enforcement + +## Principle Combinations by Prompt Type + +| Prompt Type | Use | Avoid | +|------------|-----|-------| +| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity | +| Guidance/technique | Moderate Authority + Unity | Heavy authority | +| Collaborative | Unity + Commitment | Authority, Liking | +| Reference | Clarity only | All persuasion | + +## Why This Works: The Psychology + +**Bright-line rules reduce rationalization:** + +- "YOU MUST" removes decision fatigue +- Absolute language eliminates "is this an exception?" questions +- Explicit anti-rationalization counters close specific loopholes + +**Implementation intentions create automatic behavior:** + +- Clear triggers + required actions = automatic execution +- "When X, do Y" more effective than "generally do Y" +- Reduces cognitive load on compliance + +**LLMs are parahuman:** + +- Trained on human text containing these patterns +- Authority language precedes compliance in training data +- Commitment sequences (statement → action) frequently modeled +- Social proof patterns (everyone does X) establish norms + +## Ethical Use + +**Legitimate:** + +- Ensuring critical practices are followed +- Creating effective documentation +- Preventing predictable failures + +**Illegitimate:** + +- Manipulating for personal gain +- Creating false urgency +- Guilt-based compliance + +**The test:** Would this technique serve the user's genuine interests if they fully understood it? + +## Quick Reference + +When designing a prompt, ask: + +1. **What type is it?** (Discipline vs. guidance vs. reference) +2. **What behavior am I trying to change?** +3. **Which principle(s) apply?** (Usually authority + commitment for discipline) +4. **Am I combining too many?** (Don't use all seven) +5. **Is this ethical?** (Serves user's genuine interests?) \ No newline at end of file diff --git a/.claude/skills/subagent-driven-development/SKILL.md b/.claude/skills/subagent-driven-development/SKILL.md new file mode 100644 index 0000000..a9a9454 --- /dev/null +++ b/.claude/skills/subagent-driven-development/SKILL.md @@ -0,0 +1,240 @@ +--- +name: subagent-driven-development +description: Use when executing implementation plans with independent tasks in the current session +--- + +# Subagent-Driven Development + +Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review. + +**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration + +## When to Use + +```dot +digraph when_to_use { + "Have implementation plan?" [shape=diamond]; + "Tasks mostly independent?" [shape=diamond]; + "Stay in this session?" [shape=diamond]; + "subagent-driven-development" [shape=box]; + "executing-plans" [shape=box]; + "Manual execution or brainstorm first" [shape=box]; + + "Have implementation plan?" -> "Tasks mostly independent?" [label="yes"]; + "Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"]; + "Tasks mostly independent?" -> "Stay in this session?" [label="yes"]; + "Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"]; + "Stay in this session?" -> "subagent-driven-development" [label="yes"]; + "Stay in this session?" -> "executing-plans" [label="no - parallel session"]; +} +``` + +**vs. Executing Plans (parallel session):** +- Same session (no context switch) +- Fresh subagent per task (no context pollution) +- Two-stage review after each task: spec compliance first, then code quality +- Faster iteration (no human-in-loop between tasks) + +## The Process + +```dot +digraph process { + rankdir=TB; + + subgraph cluster_per_task { + label="Per Task"; + "Dispatch implementer subagent (./implementer-prompt.md)" [shape=box]; + "Implementer subagent asks questions?" [shape=diamond]; + "Answer questions, provide context" [shape=box]; + "Implementer subagent implements, tests, commits, self-reviews" [shape=box]; + "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box]; + "Spec reviewer subagent confirms code matches spec?" [shape=diamond]; + "Implementer subagent fixes spec gaps" [shape=box]; + "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box]; + "Code quality reviewer subagent approves?" [shape=diamond]; + "Implementer subagent fixes quality issues" [shape=box]; + "Mark task complete in TodoWrite" [shape=box]; + } + + "Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box]; + "More tasks remain?" [shape=diamond]; + "Dispatch final code reviewer subagent for entire implementation" [shape=box]; + "Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen]; + + "Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?"; + "Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"]; + "Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)"; + "Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"]; + "Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)"; + "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?"; + "Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"]; + "Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"]; + "Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"]; + "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?"; + "Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"]; + "Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"]; + "Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"]; + "Mark task complete in TodoWrite" -> "More tasks remain?"; + "More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"]; + "More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"]; + "Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch"; +} +``` + +## Prompt Templates + +- `./implementer-prompt.md` - Dispatch implementer subagent +- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent +- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent + +## Example Workflow + +``` +You: I'm using Subagent-Driven Development to execute this plan. + +[Read plan file once: docs/plans/feature-plan.md] +[Extract all 5 tasks with full text and context] +[Create TodoWrite with all tasks] + +Task 1: Hook installation script + +[Get Task 1 text and context (already extracted)] +[Dispatch implementation subagent with full task text + context] + +Implementer: "Before I begin - should the hook be installed at user or system level?" + +You: "User level (~/.config/superpowers/hooks/)" + +Implementer: "Got it. Implementing now..." +[Later] Implementer: + - Implemented install-hook command + - Added tests, 5/5 passing + - Self-review: Found I missed --force flag, added it + - Committed + +[Dispatch spec compliance reviewer] +Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra + +[Get git SHAs, dispatch code quality reviewer] +Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved. + +[Mark Task 1 complete] + +Task 2: Recovery modes + +[Get Task 2 text and context (already extracted)] +[Dispatch implementation subagent with full task text + context] + +Implementer: [No questions, proceeds] +Implementer: + - Added verify/repair modes + - 8/8 tests passing + - Self-review: All good + - Committed + +[Dispatch spec compliance reviewer] +Spec reviewer: ❌ Issues: + - Missing: Progress reporting (spec says "report every 100 items") + - Extra: Added --json flag (not requested) + +[Implementer fixes issues] +Implementer: Removed --json flag, added progress reporting + +[Spec reviewer reviews again] +Spec reviewer: ✅ Spec compliant now + +[Dispatch code quality reviewer] +Code reviewer: Strengths: Solid. Issues (Important): Magic number (100) + +[Implementer fixes] +Implementer: Extracted PROGRESS_INTERVAL constant + +[Code reviewer reviews again] +Code reviewer: ✅ Approved + +[Mark Task 2 complete] + +... + +[After all tasks] +[Dispatch final code-reviewer] +Final reviewer: All requirements met, ready to merge + +Done! +``` + +## Advantages + +**vs. Manual execution:** +- Subagents follow TDD naturally +- Fresh context per task (no confusion) +- Parallel-safe (subagents don't interfere) +- Subagent can ask questions (before AND during work) + +**vs. Executing Plans:** +- Same session (no handoff) +- Continuous progress (no waiting) +- Review checkpoints automatic + +**Efficiency gains:** +- No file reading overhead (controller provides full text) +- Controller curates exactly what context is needed +- Subagent gets complete information upfront +- Questions surfaced before work begins (not after) + +**Quality gates:** +- Self-review catches issues before handoff +- Two-stage review: spec compliance, then code quality +- Review loops ensure fixes actually work +- Spec compliance prevents over/under-building +- Code quality ensures implementation is well-built + +**Cost:** +- More subagent invocations (implementer + 2 reviewers per task) +- Controller does more prep work (extracting all tasks upfront) +- Review loops add iterations +- But catches issues early (cheaper than debugging later) + +## Red Flags + +**Never:** +- Skip reviews (spec compliance OR code quality) +- Proceed with unfixed issues +- Dispatch multiple implementation subagents in parallel (conflicts) +- Make subagent read plan file (provide full text instead) +- Skip scene-setting context (subagent needs to understand where task fits) +- Ignore subagent questions (answer before letting them proceed) +- Accept "close enough" on spec compliance (spec reviewer found issues = not done) +- Skip review loops (reviewer found issues = implementer fixes = review again) +- Let implementer self-review replace actual review (both are needed) +- **Start code quality review before spec compliance is ✅** (wrong order) +- Move to next task while either review has open issues + +**If subagent asks questions:** +- Answer clearly and completely +- Provide additional context if needed +- Don't rush them into implementation + +**If reviewer finds issues:** +- Implementer (same subagent) fixes them +- Reviewer reviews again +- Repeat until approved +- Don't skip the re-review + +**If subagent fails task:** +- Dispatch fix subagent with specific instructions +- Don't try to fix manually (context pollution) + +## Integration + +**Required workflow skills:** +- **superpowers:writing-plans** - Creates the plan this skill executes +- **superpowers:requesting-code-review** - Code review template for reviewer subagents +- **superpowers:finishing-a-development-branch** - Complete development after all tasks + +**Subagents should use:** +- **superpowers:test-driven-development** - Subagents follow TDD for each task + +**Alternative workflow:** +- **superpowers:executing-plans** - Use for parallel session instead of same-session execution diff --git a/.claude/skills/subagent-driven-development/code-quality-reviewer-prompt.md b/.claude/skills/subagent-driven-development/code-quality-reviewer-prompt.md new file mode 100644 index 0000000..d029ea2 --- /dev/null +++ b/.claude/skills/subagent-driven-development/code-quality-reviewer-prompt.md @@ -0,0 +1,20 @@ +# Code Quality Reviewer Prompt Template + +Use this template when dispatching a code quality reviewer subagent. + +**Purpose:** Verify implementation is well-built (clean, tested, maintainable) + +**Only dispatch after spec compliance review passes.** + +``` +Task tool (superpowers:code-reviewer): + Use template at requesting-code-review/code-reviewer.md + + WHAT_WAS_IMPLEMENTED: [from implementer's report] + PLAN_OR_REQUIREMENTS: Task N from [plan-file] + BASE_SHA: [commit before task] + HEAD_SHA: [current commit] + DESCRIPTION: [task summary] +``` + +**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment diff --git a/.claude/skills/subagent-driven-development/implementer-prompt.md b/.claude/skills/subagent-driven-development/implementer-prompt.md new file mode 100644 index 0000000..db5404b --- /dev/null +++ b/.claude/skills/subagent-driven-development/implementer-prompt.md @@ -0,0 +1,78 @@ +# Implementer Subagent Prompt Template + +Use this template when dispatching an implementer subagent. + +``` +Task tool (general-purpose): + description: "Implement Task N: [task name]" + prompt: | + You are implementing Task N: [task name] + + ## Task Description + + [FULL TEXT of task from plan - paste it here, don't make subagent read file] + + ## Context + + [Scene-setting: where this fits, dependencies, architectural context] + + ## Before You Begin + + If you have questions about: + - The requirements or acceptance criteria + - The approach or implementation strategy + - Dependencies or assumptions + - Anything unclear in the task description + + **Ask them now.** Raise any concerns before starting work. + + ## Your Job + + Once you're clear on requirements: + 1. Implement exactly what the task specifies + 2. Write tests (following TDD if task says to) + 3. Verify implementation works + 4. Commit your work + 5. Self-review (see below) + 6. Report back + + Work from: [directory] + + **While you work:** If you encounter something unexpected or unclear, **ask questions**. + It's always OK to pause and clarify. Don't guess or make assumptions. + + ## Before Reporting Back: Self-Review + + Review your work with fresh eyes. Ask yourself: + + **Completeness:** + - Did I fully implement everything in the spec? + - Did I miss any requirements? + - Are there edge cases I didn't handle? + + **Quality:** + - Is this my best work? + - Are names clear and accurate (match what things do, not how they work)? + - Is the code clean and maintainable? + + **Discipline:** + - Did I avoid overbuilding (YAGNI)? + - Did I only build what was requested? + - Did I follow existing patterns in the codebase? + + **Testing:** + - Do tests actually verify behavior (not just mock behavior)? + - Did I follow TDD if required? + - Are tests comprehensive? + + If you find issues during self-review, fix them now before reporting. + + ## Report Format + + When done, report: + - What you implemented + - What you tested and test results + - Files changed + - Self-review findings (if any) + - Any issues or concerns +``` diff --git a/.claude/skills/subagent-driven-development/spec-reviewer-prompt.md b/.claude/skills/subagent-driven-development/spec-reviewer-prompt.md new file mode 100644 index 0000000..ab5ddb8 --- /dev/null +++ b/.claude/skills/subagent-driven-development/spec-reviewer-prompt.md @@ -0,0 +1,61 @@ +# Spec Compliance Reviewer Prompt Template + +Use this template when dispatching a spec compliance reviewer subagent. + +**Purpose:** Verify implementer built what was requested (nothing more, nothing less) + +``` +Task tool (general-purpose): + description: "Review spec compliance for Task N" + prompt: | + You are reviewing whether an implementation matches its specification. + + ## What Was Requested + + [FULL TEXT of task requirements] + + ## What Implementer Claims They Built + + [From implementer's report] + + ## CRITICAL: Do Not Trust the Report + + The implementer finished suspiciously quickly. Their report may be incomplete, + inaccurate, or optimistic. You MUST verify everything independently. + + **DO NOT:** + - Take their word for what they implemented + - Trust their claims about completeness + - Accept their interpretation of requirements + + **DO:** + - Read the actual code they wrote + - Compare actual implementation to requirements line by line + - Check for missing pieces they claimed to implement + - Look for extra features they didn't mention + + ## Your Job + + Read the implementation code and verify: + + **Missing requirements:** + - Did they implement everything that was requested? + - Are there requirements they skipped or missed? + - Did they claim something works but didn't actually implement it? + + **Extra/unneeded work:** + - Did they build things that weren't requested? + - Did they over-engineer or add unnecessary features? + - Did they add "nice to haves" that weren't in spec? + + **Misunderstandings:** + - Did they interpret requirements differently than intended? + - Did they solve the wrong problem? + - Did they implement the right feature but wrong way? + + **Verify by reading code, not by trusting report.** + + Report: + - ✅ Spec compliant (if everything matches after code inspection) + - ❌ Issues found: [list specifically what's missing or extra, with file:line references] +``` diff --git a/.claude/skills/test-driven-development/SKILL.md b/.claude/skills/test-driven-development/SKILL.md new file mode 100644 index 0000000..34a9f2b --- /dev/null +++ b/.claude/skills/test-driven-development/SKILL.md @@ -0,0 +1,371 @@ +--- +name: test-driven-development +description: Use when implementing any feature or bugfix, before writing implementation code +--- + +# Test-Driven Development (TDD) + +## Overview + +Write the test first. Watch it fail. Write minimal code to pass. + +**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing. + +**Violating the letter of the rules is violating the spirit of the rules.** + +## When to Use + +**Always:** +- New features +- Bug fixes +- Refactoring +- Behavior changes + +**Exceptions (ask your human partner):** +- Throwaway prototypes +- Generated code +- Configuration files + +Thinking "skip TDD just this once"? Stop. That's rationalization. + +## The Iron Law + +``` +NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST +``` + +Write code before the test? Delete it. Start over. + +**No exceptions:** +- Don't keep it as "reference" +- Don't "adapt" it while writing tests +- Don't look at it +- Delete means delete + +Implement fresh from tests. Period. + +## Red-Green-Refactor + +```dot +digraph tdd_cycle { + rankdir=LR; + red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"]; + verify_red [label="Verify fails\ncorrectly", shape=diamond]; + green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"]; + verify_green [label="Verify passes\nAll green", shape=diamond]; + refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"]; + next [label="Next", shape=ellipse]; + + red -> verify_red; + verify_red -> green [label="yes"]; + verify_red -> red [label="wrong\nfailure"]; + green -> verify_green; + verify_green -> refactor [label="yes"]; + verify_green -> green [label="no"]; + refactor -> verify_green [label="stay\ngreen"]; + verify_green -> next; + next -> red; +} +``` + +### RED - Write Failing Test + +Write one minimal test showing what should happen. + + +```typescript +test('retries failed operations 3 times', async () => { + let attempts = 0; + const operation = () => { + attempts++; + if (attempts < 3) throw new Error('fail'); + return 'success'; + }; + + const result = await retryOperation(operation); + + expect(result).toBe('success'); + expect(attempts).toBe(3); +}); +``` +Clear name, tests real behavior, one thing + + + +```typescript +test('retry works', async () => { + const mock = jest.fn() + .mockRejectedValueOnce(new Error()) + .mockRejectedValueOnce(new Error()) + .mockResolvedValueOnce('success'); + await retryOperation(mock); + expect(mock).toHaveBeenCalledTimes(3); +}); +``` +Vague name, tests mock not code + + +**Requirements:** +- One behavior +- Clear name +- Real code (no mocks unless unavoidable) + +### Verify RED - Watch It Fail + +**MANDATORY. Never skip.** + +```bash +npm test path/to/test.test.ts +``` + +Confirm: +- Test fails (not errors) +- Failure message is expected +- Fails because feature missing (not typos) + +**Test passes?** You're testing existing behavior. Fix test. + +**Test errors?** Fix error, re-run until it fails correctly. + +### GREEN - Minimal Code + +Write simplest code to pass the test. + + +```typescript +async function retryOperation(fn: () => Promise): Promise { + for (let i = 0; i < 3; i++) { + try { + return await fn(); + } catch (e) { + if (i === 2) throw e; + } + } + throw new Error('unreachable'); +} +``` +Just enough to pass + + + +```typescript +async function retryOperation( + fn: () => Promise, + options?: { + maxRetries?: number; + backoff?: 'linear' | 'exponential'; + onRetry?: (attempt: number) => void; + } +): Promise { + // YAGNI +} +``` +Over-engineered + + +Don't add features, refactor other code, or "improve" beyond the test. + +### Verify GREEN - Watch It Pass + +**MANDATORY.** + +```bash +npm test path/to/test.test.ts +``` + +Confirm: +- Test passes +- Other tests still pass +- Output pristine (no errors, warnings) + +**Test fails?** Fix code, not test. + +**Other tests fail?** Fix now. + +### REFACTOR - Clean Up + +After green only: +- Remove duplication +- Improve names +- Extract helpers + +Keep tests green. Don't add behavior. + +### Repeat + +Next failing test for next feature. + +## Good Tests + +| Quality | Good | Bad | +|---------|------|-----| +| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` | +| **Clear** | Name describes behavior | `test('test1')` | +| **Shows intent** | Demonstrates desired API | Obscures what code should do | + +## Why Order Matters + +**"I'll write tests after to verify it works"** + +Tests written after code pass immediately. Passing immediately proves nothing: +- Might test wrong thing +- Might test implementation, not behavior +- Might miss edge cases you forgot +- You never saw it catch the bug + +Test-first forces you to see the test fail, proving it actually tests something. + +**"I already manually tested all the edge cases"** + +Manual testing is ad-hoc. You think you tested everything but: +- No record of what you tested +- Can't re-run when code changes +- Easy to forget cases under pressure +- "It worked when I tried it" ≠ comprehensive + +Automated tests are systematic. They run the same way every time. + +**"Deleting X hours of work is wasteful"** + +Sunk cost fallacy. The time is already gone. Your choice now: +- Delete and rewrite with TDD (X more hours, high confidence) +- Keep it and add tests after (30 min, low confidence, likely bugs) + +The "waste" is keeping code you can't trust. Working code without real tests is technical debt. + +**"TDD is dogmatic, being pragmatic means adapting"** + +TDD IS pragmatic: +- Finds bugs before commit (faster than debugging after) +- Prevents regressions (tests catch breaks immediately) +- Documents behavior (tests show how to use code) +- Enables refactoring (change freely, tests catch breaks) + +"Pragmatic" shortcuts = debugging in production = slower. + +**"Tests after achieve the same goals - it's spirit not ritual"** + +No. Tests-after answer "What does this do?" Tests-first answer "What should this do?" + +Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones. + +Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't). + +30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Too simple to test" | Simple code breaks. Test takes 30 seconds. | +| "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?" | +| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. | +| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. | +| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. | +| "Need to explore first" | Fine. Throw away exploration, start with TDD. | +| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. | +| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. | +| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. | +| "Existing code has no tests" | You're improving it. Add tests for existing code. | + +## Red Flags - STOP and Start Over + +- Code before test +- Test after implementation +- Test passes immediately +- Can't explain why test failed +- Tests added "later" +- Rationalizing "just this once" +- "I already manually tested it" +- "Tests after achieve the same purpose" +- "It's about spirit not ritual" +- "Keep as reference" or "adapt existing code" +- "Already spent X hours, deleting is wasteful" +- "TDD is dogmatic, I'm being pragmatic" +- "This is different because..." + +**All of these mean: Delete code. Start over with TDD.** + +## Example: Bug Fix + +**Bug:** Empty email accepted + +**RED** +```typescript +test('rejects empty email', async () => { + const result = await submitForm({ email: '' }); + expect(result.error).toBe('Email required'); +}); +``` + +**Verify RED** +```bash +$ npm test +FAIL: expected 'Email required', got undefined +``` + +**GREEN** +```typescript +function submitForm(data: FormData) { + if (!data.email?.trim()) { + return { error: 'Email required' }; + } + // ... +} +``` + +**Verify GREEN** +```bash +$ npm test +PASS +``` + +**REFACTOR** +Extract validation for multiple fields if needed. + +## Verification Checklist + +Before marking work complete: + +- [ ] Every new function/method has a test +- [ ] Watched each test fail before implementing +- [ ] Each test failed for expected reason (feature missing, not typo) +- [ ] Wrote minimal code to pass each test +- [ ] All tests pass +- [ ] Output pristine (no errors, warnings) +- [ ] Tests use real code (mocks only if unavoidable) +- [ ] Edge cases and errors covered + +Can't check all boxes? You skipped TDD. Start over. + +## When Stuck + +| Problem | Solution | +|---------|----------| +| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. | +| Test too complicated | Design too complicated. Simplify interface. | +| Must mock everything | Code too coupled. Use dependency injection. | +| Test setup huge | Extract helpers. Still complex? Simplify design. | + +## Debugging Integration + +Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression. + +Never fix bugs without a test. + +## Testing Anti-Patterns + +When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls: +- Testing mock behavior instead of real behavior +- Adding test-only methods to production classes +- Mocking without understanding dependencies + +## Final Rule + +``` +Production code → test exists and failed first +Otherwise → not TDD +``` + +No exceptions without your human partner's permission. \ No newline at end of file diff --git a/.claude/skills/test-driven-development/testing-anti-patterns.md b/.claude/skills/test-driven-development/testing-anti-patterns.md new file mode 100644 index 0000000..224de39 --- /dev/null +++ b/.claude/skills/test-driven-development/testing-anti-patterns.md @@ -0,0 +1,299 @@ +# Testing Anti-Patterns + +**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code. + +## Overview + +Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested. + +**Core principle:** Test what the code does, not what the mocks do. + +**Following strict TDD prevents these anti-patterns.** + +## The Iron Laws + +``` +1. NEVER test mock behavior +2. NEVER add test-only methods to production classes +3. NEVER mock without understanding dependencies +``` + +## Anti-Pattern 1: Testing Mock Behavior + +**The violation:** +```typescript +// ❌ BAD: Testing that the mock exists +test('renders sidebar', () => { + render(); + expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument(); +}); +``` + +**Why this is wrong:** +- You're verifying the mock works, not that the component works +- Test passes when mock is present, fails when it's not +- Tells you nothing about real behavior + +**your human partner's correction:** "Are we testing the behavior of a mock?" + +**The fix:** +```typescript +// ✅ GOOD: Test real component or don't mock it +test('renders sidebar', () => { + render(); // Don't mock sidebar + expect(screen.getByRole('navigation')).toBeInTheDocument(); +}); + +// OR if sidebar must be mocked for isolation: +// Don't assert on the mock - test Page's behavior with sidebar present +``` + +### Gate Function + +``` +BEFORE asserting on any mock element: + Ask: "Am I testing real component behavior or just mock existence?" + + IF testing mock existence: + STOP - Delete the assertion or unmock the component + + Test real behavior instead +``` + +## Anti-Pattern 2: Test-Only Methods in Production + +**The violation:** +```typescript +// ❌ BAD: destroy() only used in tests +class Session { + async destroy() { // Looks like production API! + await this._workspaceManager?.destroyWorkspace(this.id); + // ... cleanup + } +} + +// In tests +afterEach(() => session.destroy()); +``` + +**Why this is wrong:** +- Production class polluted with test-only code +- Dangerous if accidentally called in production +- Violates YAGNI and separation of concerns +- Confuses object lifecycle with entity lifecycle + +**The fix:** +```typescript +// ✅ GOOD: Test utilities handle test cleanup +// Session has no destroy() - it's stateless in production + +// In test-utils/ +export async function cleanupSession(session: Session) { + const workspace = session.getWorkspaceInfo(); + if (workspace) { + await workspaceManager.destroyWorkspace(workspace.id); + } +} + +// In tests +afterEach(() => cleanupSession(session)); +``` + +### Gate Function + +``` +BEFORE adding any method to production class: + Ask: "Is this only used by tests?" + + IF yes: + STOP - Don't add it + Put it in test utilities instead + + Ask: "Does this class own this resource's lifecycle?" + + IF no: + STOP - Wrong class for this method +``` + +## Anti-Pattern 3: Mocking Without Understanding + +**The violation:** +```typescript +// ❌ BAD: Mock breaks test logic +test('detects duplicate server', () => { + // Mock prevents config write that test depends on! + vi.mock('ToolCatalog', () => ({ + discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) + })); + + await addServer(config); + await addServer(config); // Should throw - but won't! +}); +``` + +**Why this is wrong:** +- Mocked method had side effect test depended on (writing config) +- Over-mocking to "be safe" breaks actual behavior +- Test passes for wrong reason or fails mysteriously + +**The fix:** +```typescript +// ✅ GOOD: Mock at correct level +test('detects duplicate server', () => { + // Mock the slow part, preserve behavior test needs + vi.mock('MCPServerManager'); // Just mock slow server startup + + await addServer(config); // Config written + await addServer(config); // Duplicate detected ✓ +}); +``` + +### Gate Function + +``` +BEFORE mocking any method: + STOP - Don't mock yet + + 1. Ask: "What side effects does the real method have?" + 2. Ask: "Does this test depend on any of those side effects?" + 3. Ask: "Do I fully understand what this test needs?" + + IF depends on side effects: + Mock at lower level (the actual slow/external operation) + OR use test doubles that preserve necessary behavior + NOT the high-level method the test depends on + + IF unsure what test depends on: + Run test with real implementation FIRST + Observe what actually needs to happen + THEN add minimal mocking at the right level + + Red flags: + - "I'll mock this to be safe" + - "This might be slow, better mock it" + - Mocking without understanding the dependency chain +``` + +## Anti-Pattern 4: Incomplete Mocks + +**The violation:** +```typescript +// ❌ BAD: Partial mock - only fields you think you need +const mockResponse = { + status: 'success', + data: { userId: '123', name: 'Alice' } + // Missing: metadata that downstream code uses +}; + +// Later: breaks when code accesses response.metadata.requestId +``` + +**Why this is wrong:** +- **Partial mocks hide structural assumptions** - You only mocked fields you know about +- **Downstream code may depend on fields you didn't include** - Silent failures +- **Tests pass but integration fails** - Mock incomplete, real API complete +- **False confidence** - Test proves nothing about real behavior + +**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses. + +**The fix:** +```typescript +// ✅ GOOD: Mirror real API completeness +const mockResponse = { + status: 'success', + data: { userId: '123', name: 'Alice' }, + metadata: { requestId: 'req-789', timestamp: 1234567890 } + // All fields real API returns +}; +``` + +### Gate Function + +``` +BEFORE creating mock responses: + Check: "What fields does the real API response contain?" + + Actions: + 1. Examine actual API response from docs/examples + 2. Include ALL fields system might consume downstream + 3. Verify mock matches real response schema completely + + Critical: + If you're creating a mock, you must understand the ENTIRE structure + Partial mocks fail silently when code depends on omitted fields + + If uncertain: Include all documented fields +``` + +## Anti-Pattern 5: Integration Tests as Afterthought + +**The violation:** +``` +✅ Implementation complete +❌ No tests written +"Ready for testing" +``` + +**Why this is wrong:** +- Testing is part of implementation, not optional follow-up +- TDD would have caught this +- Can't claim complete without tests + +**The fix:** +``` +TDD cycle: +1. Write failing test +2. Implement to pass +3. Refactor +4. THEN claim complete +``` + +## When Mocks Become Too Complex + +**Warning signs:** +- Mock setup longer than test logic +- Mocking everything to make test pass +- Mocks missing methods real components have +- Test breaks when mock changes + +**your human partner's question:** "Do we need to be using a mock here?" + +**Consider:** Integration tests with real components often simpler than complex mocks + +## TDD Prevents These Anti-Patterns + +**Why TDD helps:** +1. **Write test first** → Forces you to think about what you're actually testing +2. **Watch it fail** → Confirms test tests real behavior, not mocks +3. **Minimal implementation** → No test-only methods creep in +4. **Real dependencies** → You see what the test actually needs before mocking + +**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first. + +## Quick Reference + +| Anti-Pattern | Fix | +|--------------|-----| +| Assert on mock elements | Test real component or unmock it | +| Test-only methods in production | Move to test utilities | +| Mock without understanding | Understand dependencies first, mock minimally | +| Incomplete mocks | Mirror real API completely | +| Tests as afterthought | TDD - tests first | +| Over-complex mocks | Consider integration tests | + +## Red Flags + +- Assertion checks for `*-mock` test IDs +- Methods only called in test files +- Mock setup is >50% of test +- Test fails when you remove mock +- Can't explain why mock is needed +- Mocking "just to be safe" + +## The Bottom Line + +**Mocks are tools to isolate, not things to test.** + +If TDD reveals you're testing mock behavior, you've gone wrong. + +Fix: Test real behavior or question why you're mocking at all. \ No newline at end of file diff --git a/.claude/skills/ui-ux-pro-max/SKILL.md b/.claude/skills/ui-ux-pro-max/SKILL.md new file mode 100644 index 0000000..1b83719 --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/SKILL.md @@ -0,0 +1,352 @@ +--- +name: ui-ux-pro-max +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 + +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 + +Check if Python is installed: + +```bash +python3 --version || python --version +``` + +If Python is not installed, install it based on user's OS: + +**macOS:** +```bash +brew install python3 +``` + +**Ubuntu/Debian:** +```bash +sudo apt update && sudo apt install python3 +``` + +**Windows:** +```powershell +winget install Python.Python.3.12 +``` + +--- + +## How to Use This Skill + +When user requests UI/UX work (design, build, create, implement, review, fix, improve), follow this workflow: + +### Step 1: Analyze User Requirements + +Extract key information from user request: +- **Product type**: SaaS, e-commerce, portfolio, dashboard, landing page, etc. +- **Style keywords**: minimal, playful, professional, elegant, dark mode, etc. +- **Industry**: healthcare, fintech, gaming, education, etc. +- **Stack**: React, Vue, Next.js, or default to `html-tailwind` + +### Step 2: Generate Design System (REQUIRED) + +**Always start with `--design-system`** to get comprehensive recommendations with reasoning: + +```bash +python3 .claude/skills/ui-ux-pro-max/scripts/search.py " " --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 +python3 .claude/skills/ui-ux-pro-max/scripts/search.py "" --domain [-n ] +``` + +**When to use detailed searches:** + +| Need | Domain | Example | +|------|--------|---------| +| More style options | `style` | `--domain style "glassmorphism dark"` | +| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` | +| UX best practices | `ux` | `--domain ux "animation accessibility"` | +| Alternative fonts | `typography` | `--domain typography "elegant luxury"` | +| Landing structure | `landing` | `--domain landing "hero social-proof"` | + +### Step 4: Stack Guidelines (Default: html-tailwind) + +Get implementation-specific best practices. If user doesn't specify a stack, **default to `html-tailwind`**. + +```bash +python3 .claude/skills/ui-ux-pro-max/scripts/search.py "" --stack html-tailwind +``` + +Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`, `shadcn`, `jetpack-compose` + +--- + +## Search Reference + +### Available Domains + +| Domain | Use For | Example Keywords | +|--------|---------|------------------| +| `product` | Product type recommendations | SaaS, e-commerce, portfolio, healthcare, beauty, service | +| `style` | UI styles, colors, effects | glassmorphism, minimalism, dark mode, brutalism | +| `typography` | Font pairings, Google Fonts | elegant, playful, professional, modern | +| `color` | Color palettes by product type | saas, ecommerce, healthcare, beauty, fintech, service | +| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof | +| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie | +| `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) | + +### Available Stacks + +| Stack | Focus | +|-------|-------| +| `html-tailwind` | Tailwind utilities, responsive, a11y (DEFAULT) | +| `react` | State, hooks, performance, patterns | +| `nextjs` | SSR, routing, images, API routes | +| `vue` | Composition API, Pinia, Vue Router | +| `svelte` | Runes, stores, SvelteKit | +| `swiftui` | Views, State, Navigation, Animation | +| `react-native` | Components, Navigation, Lists | +| `flutter` | Widgets, State, Layout, Theming | +| `shadcn` | shadcn/ui components, theming, forms, patterns | +| `jetpack-compose` | Composables, Modifiers, State Hoisting, Recomposition | + +--- + +## Example Workflow + +**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp" + +### 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 +python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service elegant" --design-system -p "Serenity Spa" +``` + +**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 +``` + +--- + +## Tips for Better Results + +1. **Be specific with keywords** - "healthcare SaaS dashboard" > "app" +2. **Search multiple times** - Different keywords reveal different insights +3. **Combine domains** - Style + Typography + Color = Complete design system +4. **Always check UX** - Search "animation", "z-index", "accessibility" for common issues +5. **Use stack flag** - Get implementation-specific best practices +6. **Iterate** - If first search doesn't match, try different keywords + +--- + +## Common Rules for Professional UI + +These are frequently overlooked issues that make UI look unprofessional: + +### Icons & Visual Elements + +| Rule | Do | Don't | +|------|----|----- | +| **No emoji icons** | Use SVG icons (Heroicons, Lucide, Simple Icons) | Use emojis like 🎨 🚀 ⚙️ as UI icons | +| **Stable hover states** | Use color/opacity transitions on hover | Use scale transforms that shift layout | +| **Correct brand logos** | Research official SVG from Simple Icons | Guess or use incorrect logo paths | +| **Consistent icon sizing** | Use fixed viewBox (24x24) with w-6 h-6 | Mix different icon sizes randomly | + +### Interaction & Cursor + +| Rule | Do | Don't | +|------|----|----- | +| **Cursor pointer** | Add `cursor-pointer` to all clickable/hoverable cards | Leave default cursor on interactive elements | +| **Hover feedback** | Provide visual feedback (color, shadow, border) | No indication element is interactive | +| **Smooth transitions** | Use `transition-colors duration-200` | Instant state changes or too slow (>500ms) | + +### Light/Dark Mode Contrast + +| Rule | Do | Don't | +|------|----|----- | +| **Glass card light mode** | Use `bg-white/80` or higher opacity | Use `bg-white/10` (too transparent) | +| **Text contrast light** | Use `#0F172A` (slate-900) for text | Use `#94A3B8` (slate-400) for body text | +| **Muted text light** | Use `#475569` (slate-600) minimum | Use gray-400 or lighter | +| **Border visibility** | Use `border-gray-200` in light mode | Use `border-white/10` (invisible) | + +### Layout & Spacing + +| Rule | Do | Don't | +|------|----|----- | +| **Floating navbar** | Add `top-4 left-4 right-4` spacing | Stick navbar to `top-0 left-0 right-0` | +| **Content padding** | Account for fixed navbar height | Let content hide behind fixed elements | +| **Consistent max-width** | Use same `max-w-6xl` or `max-w-7xl` | Mix different container widths | + +--- + +## Pre-Delivery Checklist + +Before delivering UI code, verify these items: + +### Visual Quality +- [ ] No emojis used as icons (use SVG instead) +- [ ] All icons from consistent icon set (Heroicons/Lucide) +- [ ] Brand logos are correct (verified from Simple Icons) +- [ ] Hover states don't cause layout shift +- [ ] Use theme colors directly (bg-primary) not var() wrapper + +### Interaction +- [ ] All clickable elements have `cursor-pointer` +- [ ] Hover states provide clear visual feedback +- [ ] Transitions are smooth (150-300ms) +- [ ] Focus states visible for keyboard navigation + +### Light/Dark Mode +- [ ] Light mode text has sufficient contrast (4.5:1 minimum) +- [ ] Glass/transparent elements visible in light mode +- [ ] Borders visible in both modes +- [ ] Test both modes before delivery + +### Layout +- [ ] Floating elements have proper spacing from edges +- [ ] No content hidden behind fixed navbars +- [ ] Responsive at 375px, 768px, 1024px, 1440px +- [ ] No horizontal scroll on mobile + +### Accessibility +- [ ] All images have alt text +- [ ] Form inputs have labels +- [ ] Color is not the only indicator +- [ ] `prefers-reduced-motion` respected diff --git a/.claude/skills/ui-ux-pro-max/data/charts.csv b/.claude/skills/ui-ux-pro-max/data/charts.csv new file mode 100644 index 0000000..5cfa805 --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/data/charts.csv @@ -0,0 +1,26 @@ +No,Data Type,Keywords,Best Chart Type,Secondary Options,Color Guidance,Performance Impact,Accessibility Notes,Library Recommendation,Interactive Level +1,Trend Over Time,"trend, time-series, line, growth, timeline, progress",Line Chart,"Area Chart, Smooth Area",Primary: #0080FF. Multiple series: use distinct colors. Fill: 20% opacity,⚡ Excellent (optimized),✓ Clear line patterns for colorblind users. Add pattern overlays.,"Chart.js, Recharts, ApexCharts",Hover + Zoom +2,Compare Categories,"compare, categories, bar, comparison, ranking",Bar Chart (Horizontal or Vertical),"Column Chart, Grouped Bar",Each bar: distinct color. Category: grouped same color. Sorted: descending order,⚡ Excellent,✓ Easy to compare. Add value labels on bars for clarity.,"Chart.js, Recharts, D3.js",Hover + Sort +3,Part-to-Whole,"part-to-whole, pie, donut, percentage, proportion, share",Pie Chart or Donut,"Stacked Bar, Treemap",Colors: 5-6 max. Contrasting palette. Large slices first. Use labels.,⚡ Good (limit 6 slices),⚠ Hard for accessibility. Better: Stacked bar with legend. Avoid pie if >5 items.,"Chart.js, Recharts, D3.js",Hover + Drill +4,Correlation/Distribution,"correlation, distribution, scatter, relationship, pattern",Scatter Plot or Bubble Chart,"Heat Map, Matrix",Color axis: gradient (blue-red). Size: relative. Opacity: 0.6-0.8 to show density,⚠ Moderate (many points),⚠ Provide data table alternative. Use pattern + color distinction.,"D3.js, Plotly, Recharts",Hover + Brush +5,Heatmap/Intensity,"heatmap, heat-map, intensity, density, matrix",Heat Map or Choropleth,"Grid Heat Map, Bubble Heat",Gradient: Cool (blue) to Hot (red). Scale: clear legend. Divergent for ±data,⚡ Excellent (color CSS),⚠ Colorblind: Use pattern overlay. Provide numerical legend.,"D3.js, Plotly, ApexCharts",Hover + Zoom +6,Geographic Data,"geographic, map, location, region, geo, spatial","Choropleth Map, Bubble Map",Geographic Heat Map,Regional: single color gradient or categorized colors. Legend: clear scale,⚠ Moderate (rendering),⚠ Include text labels for regions. Provide data table alternative.,"D3.js, Mapbox, Leaflet",Pan + Zoom + Drill +7,Funnel/Flow,funnel/flow,"Funnel Chart, Sankey",Waterfall (for flows),Stages: gradient (starting color → ending color). Show conversion %,⚡ Good,✓ Clear stage labels + percentages. Good for accessibility if labeled.,"D3.js, Recharts, Custom SVG",Hover + Drill +8,Performance vs Target,performance-vs-target,Gauge Chart or Bullet Chart,"Dial, Thermometer",Performance: Red→Yellow→Green gradient. Target: marker line. Threshold colors,⚡ Good,✓ Add numerical value + percentage label beside gauge.,"D3.js, ApexCharts, Custom SVG",Hover +9,Time-Series Forecast,time-series-forecast,Line with Confidence Band,Ribbon Chart,Actual: solid line #0080FF. Forecast: dashed #FF9500. Band: light shading,⚡ Good,✓ Clearly distinguish actual vs forecast. Add legend.,"Chart.js, ApexCharts, Plotly",Hover + Toggle +10,Anomaly Detection,anomaly-detection,Line Chart with Highlights,Scatter with Alert,Normal: blue #0080FF. Anomaly: red #FF0000 circle/square marker + alert,⚡ Good,✓ Circle/marker for anomalies. Add text alert annotation.,"D3.js, Plotly, ApexCharts",Hover + Alert +11,Hierarchical/Nested Data,hierarchical/nested-data,Treemap,"Sunburst, Nested Donut, Icicle",Parent: distinct hues. Children: lighter shades. White borders 2-3px.,⚠ Moderate,⚠ Poor - provide table alternative. Label large areas.,"D3.js, Recharts, ApexCharts",Hover + Drilldown +12,Flow/Process Data,flow/process-data,Sankey Diagram,"Alluvial, Chord Diagram",Gradient from source to target. Opacity 0.4-0.6 for flows.,⚠ Moderate,⚠ Poor - provide flow table alternative.,"D3.js (d3-sankey), Plotly",Hover + Drilldown +13,Cumulative Changes,cumulative-changes,Waterfall Chart,"Stacked Bar, Cascade",Increases: #4CAF50. Decreases: #F44336. Start: #2196F3. End: #0D47A1.,⚡ Good,✓ Good - clear directional colors with labels.,"ApexCharts, Highcharts, Plotly",Hover +14,Multi-Variable Comparison,multi-variable-comparison,Radar/Spider Chart,"Parallel Coordinates, Grouped Bar",Single: #0080FF 20% fill. Multiple: distinct colors per dataset.,⚡ Good,⚠ Moderate - limit 5-8 axes. Add data table.,"Chart.js, Recharts, ApexCharts",Hover + Toggle +15,Stock/Trading OHLC,stock/trading-ohlc,Candlestick Chart,"OHLC Bar, Heikin-Ashi",Bullish: #26A69A. Bearish: #EF5350. Volume: 40% opacity below.,⚡ Good,⚠ Moderate - provide OHLC data table.,"Lightweight Charts (TradingView), ApexCharts",Real-time + Hover + Zoom +16,Relationship/Connection Data,relationship/connection-data,Network Graph,"Hierarchical Tree, Adjacency Matrix",Node types: categorical colors. Edges: #90A4AE 60% opacity.,❌ Poor (500+ nodes struggles),❌ Very Poor - provide adjacency list alternative.,"D3.js (d3-force), Vis.js, Cytoscape.js",Drilldown + Hover + Drag +17,Distribution/Statistical,distribution/statistical,Box Plot,"Violin Plot, Beeswarm",Box: #BBDEFB. Border: #1976D2. Median: #D32F2F. Outliers: #F44336.,⚡ Excellent,"✓ Good - include stats table (min, Q1, median, Q3, max).","Plotly, D3.js, Chart.js (plugin)",Hover +18,Performance vs Target (Compact),performance-vs-target-(compact),Bullet Chart,"Gauge, Progress Bar","Ranges: #FFCDD2, #FFF9C4, #C8E6C9. Performance: #1976D2. Target: black 3px.",⚡ Excellent,✓ Excellent - compact with clear values.,"D3.js, Plotly, Custom SVG",Hover +19,Proportional/Percentage,proportional/percentage,Waffle Chart,"Pictogram, Stacked Bar 100%",10x10 grid. 3-5 categories max. 2-3px spacing between squares.,⚡ Good,✓ Good - better than pie for accessibility.,"D3.js, React-Waffle, Custom CSS Grid",Hover +20,Hierarchical Proportional,hierarchical-proportional,Sunburst Chart,"Treemap, Icicle, Circle Packing",Center to outer: darker to lighter. 15-20% lighter per level.,⚠ Moderate,⚠ Poor - provide hierarchy table alternative.,"D3.js (d3-hierarchy), Recharts, ApexCharts",Drilldown + Hover +21,Root Cause Analysis,"root cause, decomposition, tree, hierarchy, drill-down, ai-split",Decomposition Tree,"Decision Tree, Flow Chart",Nodes: #2563EB (Primary) vs #EF4444 (Negative impact). Connectors: Neutral grey.,⚠ Moderate (calculation heavy),✓ clear hierarchy. Allow keyboard navigation for nodes.,"Power BI (native), React-Flow, Custom D3.js",Drill + Expand +22,3D Spatial Data,"3d, spatial, immersive, terrain, molecular, volumetric",3D Scatter/Surface Plot,"Volumetric Rendering, Point Cloud",Depth cues: lighting/shading. Z-axis: color gradient (cool to warm).,❌ Heavy (WebGL required),❌ Poor - requires alternative 2D view or data table.,"Three.js, Deck.gl, Plotly 3D",Rotate + Zoom + VR +23,Real-Time Streaming,"streaming, real-time, ticker, live, velocity, pulse",Streaming Area Chart,"Ticker Tape, Moving Gauge",Current: Bright Pulse (#00FF00). History: Fading opacity. Grid: Dark.,⚡ Optimized (canvas/webgl),⚠ Flashing elements - provide pause button. High contrast.,Smoothed D3.js, CanvasJS, SciChart,Real-time + Pause +24,Sentiment/Emotion,"sentiment, emotion, nlp, opinion, feeling",Word Cloud with Sentiment,"Sentiment Arc, Radar Chart",Positive: #22C55E. Negative: #EF4444. Neutral: #94A3B8. Size = Frequency.,⚡ Good,⚠ Word clouds poor for screen readers. Use list view.,"D3-cloud, Highcharts, Nivo",Hover + Filter +25,Process Mining,"process, mining, variants, path, bottleneck, log",Process Map / Graph,"Directed Acyclic Graph (DAG), Petri Net",Happy path: #10B981 (Thick). Deviations: #F59E0B (Thin). Bottlenecks: #EF4444.,⚠ Moderate to Heavy,⚠ Complex graphs hard to navigate. Provide path summary.,"React-Flow, Cytoscape.js, Recharts",Drag + Node-Click \ No newline at end of file diff --git a/.claude/skills/ui-ux-pro-max/data/colors.csv b/.claude/skills/ui-ux-pro-max/data/colors.csv new file mode 100644 index 0000000..77feb8b --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/data/colors.csv @@ -0,0 +1,97 @@ +No,Product Type,Keywords,Primary (Hex),Secondary (Hex),CTA (Hex),Background (Hex),Text (Hex),Border (Hex),Notes +1,SaaS (General),"saas, general",#2563EB,#3B82F6,#F97316,#F8FAFC,#1E293B,#E2E8F0,Trust blue + accent contrast +2,Micro SaaS,"micro, saas",#2563EB,#3B82F6,#F97316,#F8FAFC,#1E293B,#E2E8F0,Vibrant primary + white space +3,E-commerce,commerce,#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand primary + success green +4,E-commerce Luxury,"commerce, luxury",#1C1917,#44403C,#CA8A04,#FAFAF9,#0C0A09,#D6D3D1,Premium colors + minimal accent +5,Service Landing Page,"service, landing, page",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand primary + trust colors +6,B2B Service,"b2b, service",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional blue + neutral grey +7,Financial Dashboard,"financial, dashboard",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark bg + red/green alerts + trust blue +8,Analytics Dashboard,"analytics, dashboard",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Cool→Hot gradients + neutral grey +9,Healthcare App,"healthcare, app",#0891B2,#22D3EE,#059669,#ECFEFF,#164E63,#A5F3FC,Calm blue + health green + trust +10,Educational App,"educational, app",#4F46E5,#818CF8,#F97316,#EEF2FF,#1E1B4B,#C7D2FE,Playful colors + clear hierarchy +11,Creative Agency,"creative, agency",#EC4899,#F472B6,#06B6D4,#FDF2F8,#831843,#FBCFE8,Bold primaries + artistic freedom +12,Portfolio/Personal,"portfolio, personal",#18181B,#3F3F46,#2563EB,#FAFAFA,#09090B,#E4E4E7,Brand primary + artistic interpretation +13,Gaming,gaming,#7C3AED,#A78BFA,#F43F5E,#0F0F23,#E2E8F0,#4C1D95,Vibrant + neon + immersive colors +14,Government/Public Service,"government, public, service",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional blue + high contrast +15,Fintech/Crypto,"fintech, crypto",#F59E0B,#FBBF24,#8B5CF6,#0F172A,#F8FAFC,#334155,Dark tech colors + trust + vibrant accents +16,Social Media App,"social, media, app",#2563EB,#60A5FA,#F43F5E,#F8FAFC,#1E293B,#DBEAFE,Vibrant + engagement colors +17,Productivity Tool,"productivity, tool",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Clear hierarchy + functional colors +18,Design System/Component Library,"design, system, component, library",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Clear hierarchy + code-like structure +19,AI/Chatbot Platform,"chatbot, platform",#7C3AED,#A78BFA,#06B6D4,#FAF5FF,#1E1B4B,#DDD6FE,Neutral + AI Purple (#6366F1) +20,NFT/Web3 Platform,"nft, web3, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark + Neon + Gold (#FFD700) +21,Creator Economy Platform,"creator, economy, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Vibrant + Brand colors +22,Sustainability/ESG Platform,"sustainability, esg, platform",#7C3AED,#A78BFA,#06B6D4,#FAF5FF,#1E1B4B,#DDD6FE,Green (#228B22) + Earth tones +23,Remote Work/Collaboration Tool,"remote, work, collaboration, tool",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Calm Blue + Neutral grey +24,Mental Health App,"mental, health, app",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Calm Pastels + Trust colors +25,Pet Tech App,"pet, tech, app",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Playful + Warm colors +26,Smart Home/IoT Dashboard,"smart, home, iot, dashboard",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark + Status indicator colors +27,EV/Charging Ecosystem,"charging, ecosystem",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Electric Blue (#009CD1) + Green +28,Subscription Box Service,"subscription, box, service",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand + Excitement colors +29,Podcast Platform,"podcast, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark + Audio waveform accents +30,Dating App,"dating, app",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Warm + Romantic (Pink/Red gradients) +31,Micro-Credentials/Badges Platform,"micro, credentials, badges, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Trust Blue + Gold (#FFD700) +32,Knowledge Base/Documentation,"knowledge, base, documentation",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Clean hierarchy + minimal color +33,Hyperlocal Services,"hyperlocal, services",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Location markers + Trust colors +34,Beauty/Spa/Wellness Service,"beauty, spa, wellness, service",#10B981,#34D399,#8B5CF6,#ECFDF5,#064E3B,#A7F3D0,Soft pastels (Pink #FFB6C1 Sage #90EE90) + Cream + Gold accents +35,Luxury/Premium Brand,"luxury, premium, brand",#1C1917,#44403C,#CA8A04,#FAFAF9,#0C0A09,#D6D3D1,Black + Gold (#FFD700) + White + Minimal accent +36,Restaurant/Food Service,"restaurant, food, service",#DC2626,#F87171,#CA8A04,#FEF2F2,#450A0A,#FECACA,Warm colors (Orange Red Brown) + appetizing imagery +37,Fitness/Gym App,"fitness, gym, app",#DC2626,#F87171,#16A34A,#FEF2F2,#1F2937,#FECACA,Energetic (Orange #FF6B35 Electric Blue) + Dark bg +38,Real Estate/Property,"real, estate, property",#0F766E,#14B8A6,#0369A1,#F0FDFA,#134E4A,#99F6E4,Trust Blue (#0077B6) + Gold accents + White +39,Travel/Tourism Agency,"travel, tourism, agency",#EC4899,#F472B6,#06B6D4,#FDF2F8,#831843,#FBCFE8,Vibrant destination colors + Sky Blue + Warm accents +40,Hotel/Hospitality,"hotel, hospitality",#1E3A8A,#3B82F6,#CA8A04,#F8FAFC,#1E40AF,#BFDBFE,Warm neutrals + Gold (#D4AF37) + Brand accent +41,Wedding/Event Planning,"wedding, event, planning",#7C3AED,#A78BFA,#F97316,#FAF5FF,#4C1D95,#DDD6FE,Soft Pink (#FFD6E0) + Gold + Cream + Sage +42,Legal Services,"legal, services",#1E3A8A,#1E40AF,#B45309,#F8FAFC,#0F172A,#CBD5E1,Navy Blue (#1E3A5F) + Gold + White +43,Insurance Platform,"insurance, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Trust Blue (#0066CC) + Green (security) + Neutral +44,Banking/Traditional Finance,"banking, traditional, finance",#0F766E,#14B8A6,#0369A1,#F0FDFA,#134E4A,#99F6E4,Navy (#0A1628) + Trust Blue + Gold accents +45,Online Course/E-learning,"online, course, learning",#0D9488,#2DD4BF,#EA580C,#F0FDFA,#134E4A,#5EEAD4,Vibrant learning colors + Progress green +46,Non-profit/Charity,"non, profit, charity",#0891B2,#22D3EE,#F97316,#ECFEFF,#164E63,#A5F3FC,Cause-related colors + Trust + Warm +47,Music Streaming,"music, streaming",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark (#121212) + Vibrant accents + Album art colors +48,Video Streaming/OTT,"video, streaming, ott",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark bg + Content poster colors + Brand accent +49,Job Board/Recruitment,"job, board, recruitment",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional Blue + Success Green + Neutral +50,Marketplace (P2P),"marketplace, p2p",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Trust colors + Category colors + Success green +51,Logistics/Delivery,"logistics, delivery",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Blue (#2563EB) + Orange (tracking) + Green (delivered) +52,Agriculture/Farm Tech,"agriculture, farm, tech",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Earth Green (#4A7C23) + Brown + Sky Blue +53,Construction/Architecture,"construction, architecture",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Grey (#4A4A4A) + Orange (safety) + Blueprint Blue +54,Automotive/Car Dealership,"automotive, car, dealership",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand colors + Metallic accents + Dark/Light +55,Photography Studio,"photography, studio",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Black + White + Minimal accent +56,Coworking Space,"coworking, space",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Energetic colors + Wood tones + Brand accent +57,Cleaning Service,"cleaning, service",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Fresh Blue (#00B4D8) + Clean White + Green +58,Home Services (Plumber/Electrician),"home, services, plumber, electrician",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Trust Blue + Safety Orange + Professional grey +59,Childcare/Daycare,"childcare, daycare",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Playful pastels + Safe colors + Warm accents +60,Senior Care/Elderly,"senior, care, elderly",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Calm Blue + Warm neutrals + Large text +61,Medical Clinic,"medical, clinic",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Medical Blue (#0077B6) + Trust White + Calm Green +62,Pharmacy/Drug Store,"pharmacy, drug, store",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Pharmacy Green + Trust Blue + Clean White +63,Dental Practice,"dental, practice",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Fresh Blue + White + Smile Yellow accent +64,Veterinary Clinic,"veterinary, clinic",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Caring Blue + Pet-friendly colors + Warm accents +65,Florist/Plant Shop,"florist, plant, shop",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Natural Green + Floral pinks/purples + Earth tones +66,Bakery/Cafe,"bakery, cafe",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Warm Brown + Cream + Appetizing accents +67,Coffee Shop,"coffee, shop",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Coffee Brown (#6F4E37) + Cream + Warm accents +68,Brewery/Winery,"brewery, winery",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Deep amber/burgundy + Gold + Craft aesthetic +69,Airline,airline,#7C3AED,#A78BFA,#06B6D4,#FAF5FF,#1E1B4B,#DDD6FE,Sky Blue + Brand colors + Trust accents +70,News/Media Platform,"news, media, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand colors + High contrast + Category colors +71,Magazine/Blog,"magazine, blog",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Editorial colors + Brand primary + Clean white +72,Freelancer Platform,"freelancer, platform",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional Blue + Success Green + Neutral +73,Consulting Firm,"consulting, firm",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Navy + Gold + Professional grey +74,Marketing Agency,"marketing, agency",#EC4899,#F472B6,#06B6D4,#FDF2F8,#831843,#FBCFE8,Bold brand colors + Creative freedom +75,Event Management,"event, management",#7C3AED,#A78BFA,#F97316,#FAF5FF,#4C1D95,#DDD6FE,Event theme colors + Excitement accents +76,Conference/Webinar Platform,"conference, webinar, platform",#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional Blue + Video accent + Brand +77,Membership/Community,"membership, community",#7C3AED,#A78BFA,#F97316,#FAF5FF,#4C1D95,#DDD6FE,Community brand colors + Engagement accents +78,Newsletter Platform,"newsletter, platform",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Brand primary + Clean white + CTA accent +79,Digital Products/Downloads,"digital, products, downloads",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Product category colors + Brand + Success green +80,Church/Religious Organization,"church, religious, organization",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Warm Gold + Deep Purple/Blue + White +81,Sports Team/Club,"sports, team, club",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Team colors + Energetic accents +82,Museum/Gallery,"museum, gallery",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Art-appropriate neutrals + Exhibition accents +83,Theater/Cinema,"theater, cinema",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Dark + Spotlight accents + Gold +84,Language Learning App,"language, learning, app",#0D9488,#2DD4BF,#EA580C,#F0FDFA,#134E4A,#5EEAD4,Playful colors + Progress indicators + Country flags +85,Coding Bootcamp,"coding, bootcamp",#3B82F6,#60A5FA,#F97316,#F8FAFC,#1E293B,#E2E8F0,Code editor colors + Brand + Success green +86,Cybersecurity Platform,"cybersecurity, security, cyber, hacker",#00FF41,#0D0D0D,#00FF41,#000000,#E0E0E0,#1F1F1F,Matrix Green + Deep Black + Terminal feel +87,Developer Tool / IDE,"developer, tool, ide, code, dev",#3B82F6,#1E293B,#2563EB,#0F172A,#F1F5F9,#334155,Dark syntax theme colors + Blue focus +88,Biotech / Life Sciences,"biotech, science, biology, medical",#0EA5E9,#0284C7,#10B981,#F8FAFC,#0F172A,#E2E8F0,Sterile White + DNA Blue + Life Green +89,Space Tech / Aerospace,"space, aerospace, tech, futuristic",#FFFFFF,#94A3B8,#3B82F6,#0B0B10,#F8FAFC,#1E293B,Deep Space Black + Star White + Metallic +90,Architecture / Interior,"architecture, interior, design, luxury",#171717,#404040,#D4AF37,#FFFFFF,#171717,#E5E5E5,Monochrome + Gold Accent + High Imagery +91,Quantum Computing,"quantum, qubit, tech",#00FFFF,#7B61FF,#FF00FF,#050510,#E0E0FF,#333344,Interference patterns + Neon + Deep Dark +92,Biohacking / Longevity,"bio, health, science",#FF4D4D,#4D94FF,#00E676,#F5F5F7,#1C1C1E,#E5E5EA,Biological red/blue + Clinical white +93,Autonomous Systems,"drone, robot, fleet",#00FF41,#008F11,#FF3333,#0D1117,#E6EDF3,#30363D,Terminal Green + Tactical Dark +94,Generative AI Art,"art, gen-ai, creative",#111111,#333333,#FFFFFF,#FAFAFA,#000000,#E5E5E5,Canvas Neutral + High Contrast +95,Spatial / Vision OS,"spatial, glass, vision",#FFFFFF,#E5E5E5,#007AFF,#888888,#000000,#FFFFFF,Glass opacity 20% + System Blue +96,Climate Tech,"climate, green, energy",#2E8B57,#87CEEB,#FFD700,#F0FFF4,#1A3320,#C6E6C6,Nature Green + Solar Yellow + Air Blue \ No newline at end of file diff --git a/.claude/skills/ui-ux-pro-max/data/icons.csv b/.claude/skills/ui-ux-pro-max/data/icons.csv new file mode 100644 index 0000000..a09a534 --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/data/icons.csv @@ -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',,Mobile navigation drawer toggle sidebar,Outline +2,Navigation,arrow-left,back previous return navigate,Lucide,import { ArrowLeft } from 'lucide-react',,Back button breadcrumb navigation,Outline +3,Navigation,arrow-right,next forward continue navigate,Lucide,import { ArrowRight } from 'lucide-react',,Forward button next step CTA,Outline +4,Navigation,chevron-down,dropdown expand accordion select,Lucide,import { ChevronDown } from 'lucide-react',,Dropdown toggle accordion header,Outline +5,Navigation,chevron-up,collapse close accordion minimize,Lucide,import { ChevronUp } from 'lucide-react',,Accordion collapse minimize,Outline +6,Navigation,home,homepage main dashboard start,Lucide,import { Home } from 'lucide-react',,Home navigation main page,Outline +7,Navigation,x,close cancel dismiss remove exit,Lucide,import { X } from 'lucide-react',,Modal close dismiss button,Outline +8,Navigation,external-link,open new tab external link,Lucide,import { ExternalLink } from 'lucide-react',,External link indicator,Outline +9,Action,plus,add create new insert,Lucide,import { Plus } from 'lucide-react',,Add button create new item,Outline +10,Action,minus,remove subtract decrease delete,Lucide,import { Minus } from 'lucide-react',,Remove item quantity decrease,Outline +11,Action,trash-2,delete remove discard bin,Lucide,import { Trash2 } from 'lucide-react',,Delete action destructive,Outline +12,Action,edit,pencil modify change update,Lucide,import { Edit } from 'lucide-react',,Edit button modify content,Outline +13,Action,save,disk store persist save,Lucide,import { Save } from 'lucide-react',,Save button persist changes,Outline +14,Action,download,export save file download,Lucide,import { Download } from 'lucide-react',,Download file export,Outline +15,Action,upload,import file attach upload,Lucide,import { Upload } from 'lucide-react',,Upload file import,Outline +16,Action,copy,duplicate clipboard paste,Lucide,import { Copy } from 'lucide-react',,Copy to clipboard,Outline +17,Action,share,social distribute send,Lucide,import { Share } from 'lucide-react',,Share button social,Outline +18,Action,search,find lookup filter query,Lucide,import { Search } from 'lucide-react',,Search input bar,Outline +19,Action,filter,sort refine narrow options,Lucide,import { Filter } from 'lucide-react',,Filter dropdown sort,Outline +20,Action,settings,gear cog preferences config,Lucide,import { Settings } from 'lucide-react',,Settings page configuration,Outline +21,Status,check,success done complete verified,Lucide,import { Check } from 'lucide-react',,Success state checkmark,Outline +22,Status,check-circle,success verified approved complete,Lucide,import { CheckCircle } from 'lucide-react',,Success badge verified,Outline +23,Status,x-circle,error failed cancel rejected,Lucide,import { XCircle } from 'lucide-react',,Error state failed,Outline +24,Status,alert-triangle,warning caution attention danger,Lucide,import { AlertTriangle } from 'lucide-react',,Warning message caution,Outline +25,Status,alert-circle,info notice information help,Lucide,import { AlertCircle } from 'lucide-react',,Info notice alert,Outline +26,Status,info,information help tooltip details,Lucide,import { Info } from 'lucide-react',,Information tooltip help,Outline +27,Status,loader,loading spinner processing wait,Lucide,import { Loader } from 'lucide-react',,Loading state spinner,Outline +28,Status,clock,time schedule pending wait,Lucide,import { Clock } from 'lucide-react',,Pending time schedule,Outline +29,Communication,mail,email message inbox letter,Lucide,import { Mail } from 'lucide-react',,Email contact inbox,Outline +30,Communication,message-circle,chat comment bubble conversation,Lucide,import { MessageCircle } from 'lucide-react',,Chat comment message,Outline +31,Communication,phone,call mobile telephone contact,Lucide,import { Phone } from 'lucide-react',,Phone contact call,Outline +32,Communication,send,submit dispatch message airplane,Lucide,import { Send } from 'lucide-react',,Send message submit,Outline +33,Communication,bell,notification alert ring reminder,Lucide,import { Bell } from 'lucide-react',,Notification bell alert,Outline +34,User,user,profile account person avatar,Lucide,import { User } from 'lucide-react',,User profile account,Outline +35,User,users,team group people members,Lucide,import { Users } from 'lucide-react',,Team group members,Outline +36,User,user-plus,add invite new member,Lucide,import { UserPlus } from 'lucide-react',,Add user invite,Outline +37,User,log-in,signin authenticate enter,Lucide,import { LogIn } from 'lucide-react',,Login signin,Outline +38,User,log-out,signout exit leave logout,Lucide,import { LogOut } from 'lucide-react',,Logout signout,Outline +39,Media,image,photo picture gallery thumbnail,Lucide,import { Image } from 'lucide-react',,Image photo gallery,Outline +40,Media,video,movie film play record,Lucide,import { Video } from 'lucide-react',