
example-skills
Collection of example skills demonstrating various capabilities including skill creation, MCP building, visual design, algorithmic art, internal communications, web testing, artifact building, Slack GIFs, and theme styling
- GitHub stars
- 50
Install
/plugin install example-skills@anthropic-agent-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add qodex-ai/ai-agent-skills.
Contents
Discovered from sourceSkills 80
Landing Page Redesign
Instructions
When requested to redesign a landing page based on a reference:
1. User Interview
- If not provided in the initial request, ask the user for:
- Reference URL or Image: The landing page or design to replicate (can be a live website URL or an image URL)
- Target Page: Which file in the codebase should receive the design (e.g.,
app/(tabs)/index.tsx,app/landing.tsx)
- If details are provided in the initial request, skip to step 2
2. Capture Reference Design
- Use Playwright MCP to open the reference URL:
- Navigate to the page
- Take a full-page screenshot to understand structure
- Interact with the website, mouse hover, click around
- Analyze the page deeply
- Analyze the landing page/image for:
- Layout structure (header, hero, sections, footer)
- Interactive elements
- Color palette
- Typography (fonts, sizes, weights)
- Spacing and padding patterns
- UI components (buttons, cards, forms, etc.)
- Responsive design patterns
3. Implement the Design
- Read the target page file to understand current structure
- Implement the design following these principles:
- Match the layout: Replicate section structure, grid layouts, flex patterns
- Match the intractions: Replicate mouse and button interactions, whether clicks or hovers - on key elements
- Match colors: Extract and use exact hex values from the reference
- Match typography: Use similar fonts (adjust to available system fonts or suggest font imports)
- Match spacing: Replicate padding, margins, and gaps
- Match components: Build equivalent React Native components for buttons, cards, inputs, etc.
- Follow project patterns: Use StyleSheet.create() as per CLAUDE.md guidelines
- Mobile-first: Ensure the design works on mobile (Expo/React Native)
- Write the implementation to the target file
4. Compare Implementations
- If the reference is a live website:
- Take a screenshot of the implemented page
- Use Playwright to view your implementation
- Visually compare:
- Layout alignment and proportions
- Color accuracy
- Typography consistency
- Spacing and padding
- Component styling details
- Document differences found
5. Iterate and Refine
- Based on comparison, identify specific gaps:
- Layout issues (alignment, sizing, positioning)
- Color mismatches
- Typography differences
- Missing components or details
- Spacing inconsistencies
- Make targeted refinements to address each gap
- Repeat steps 4-5 until:
- The design matches as closely as technically possible
- All major visual elements are replicated
- User confirms satisfaction
- Aim for 3-5 iterations minimum to achieve high fidelity
6. Final Review
- Present the final implementation to the user
- Summarize what was matched and any intentional differences
- Suggest any follow-up improvements (e.g., animations, hover states, responsive tweaks)
Best Practices
- Be detail-oriented: Small differences in spacing, colors, or typography can break the visual consistency
- Extract exact values: Use color pickers and measurement tools to get precise values from screenshots
- Component reusability: Extract repeated patterns into reusable components
- Maintain project standards: Follow the StyleSheet.create() pattern and existing architecture
- Document trade-offs: If React Native limitations prevent exact replication, document why
Example Flow
User request: "Make our landing page look like https://stripe.com/payments"
- Interview: Ask "Which file should receive this design?" → User: "app/(tabs)/index.tsx"
- Capture:
- Navigate to stripe.com/payments
- Take full-page screenshot
- Analyze deeply: Dark theme, gradient hero, feature grid, clean typography, button changes color upon hover/click
- Implement:
- Read app/(tabs)/index.tsx
- Build based on reference
- Compare:
- Screenshot shows hero gradient is lighter than reference
- Button border-radius is too sharp
- Font weights don't match
- Button doesn't change upon hover
- Iterate:
- Adjust gradient colors to match
- Reduce border-radius on buttons
- Increase font weights
- button changes upon hover/click
- Re-compare
- Iterate again:
- Fine-tune spacing between sections
- Adjust icon sizes
- Match exact color values
- Final review: Present to user with summary of matched elements
Technical Notes
-
React Native considerations:
- Web fonts may need to be loaded via expo-font or google fonts
- Some web-specific effects (box-shadow) have React Native equivalents (shadowColor, shadowOffset)
- Use Dimensions API for responsive layouts
-
Iteration targets:
- First iteration: Overall layout and structure
- Second iteration: Colors and typography
- Third iteration: Spacing and sizing refinement
- Fourth+ iterations: Fine details and polish
References
Slack GIF Creator
A toolkit providing utilities and knowledge for creating animated GIFs optimized for Slack.
Slack Requirements
Emoji GIFs (Slack emoji uploads):
- Max size: 64 KB
- Dimensions: 128x128 recommended (square)
- FPS: 10-12
- Colors: 32-48
- Duration: 1-2s
Message GIFs:
- Max size: ~2 MB
- Dimensions: 480x480 typical
- FPS: 15-20
- Colors: 128-256
- Duration: 2-5s
Core Workflow
from core.gif_builder import GIFBuilder
from PIL import Image, ImageDraw
# 1. Create builder
builder = GIFBuilder(width=128, height=128, fps=10)
# 2. Generate frames
for i in range(12):
frame = Image.new('RGB', (128, 128), (240, 248, 255))
draw = ImageDraw.Draw(frame)
# Draw your animation using PIL primitives
# (circles, polygons, lines, etc.)
builder.add_frame(frame)
# 3. Save with optimization
builder.save('output.gif', num_colors=48, optimize_for_emoji=True)
Optional shortcut: use animation templates in templates/ to generate frames quickly:
from templates.shake import create_shake_animation
frames = create_shake_animation(
object_type='circle',
object_data={'radius': 30, 'color': (100, 150, 255)},
num_frames=20,
direction='both'
)
builder.add_frames(frames)
Drawing Graphics
Working with User-Uploaded Images
If a user uploads an image, consider whether they want to:
- Use it directly (e.g., "animate this", "split this into frames")
- Use it as inspiration (e.g., "make something like this")
Load and work with images using PIL:
from PIL import Image
uploaded = Image.open('file.png')
# Use directly, or just as reference for colors/style
Drawing from Scratch
When drawing graphics from scratch, use PIL ImageDraw primitives:
from PIL import ImageDraw
draw = ImageDraw.Draw(frame)
# Circles/ovals
draw.ellipse([x1, y1, x2, y2], fill=(r, g, b), outline=(r, g, b), width=3)
# Stars, triangles, any polygon
points = [(x1, y1), (x2, y2), (x3, y3), ...]
draw.polygon(points, fill=(r, g, b), outline=(r, g, b), width=3)
# Lines
draw.line([(x1, y1), (x2, y2)], fill=(r, g, b), width=5)
# Rectangles
draw.rectangle([x1, y1, x2, y2], fill=(r, g, b), outline=(r, g, b), width=3)
Avoid relying solely on emoji fonts: they are platform-specific. If you use draw_emoji or draw_emoji_enhanced, expect rendering differences and be ready to adjust with shapes or text.
Making Graphics Look Good
Graphics should look polished and creative, not basic. Here's how:
Use thicker lines - Always set width=2 or higher for outlines and lines. Thin lines (width=1) look choppy and amateurish.
Add visual depth:
- Use gradients for backgrounds (
create_gradient_background) - Layer multiple shapes for complexity (e.g., a star with a smaller star inside)
Make shapes more interesting:
- Don't just draw a plain circle - add highlights, rings, or patterns
- Stars can have glows (draw larger, semi-transparent versions behind)
- Combine multiple shapes (stars + sparkles, circles + rings)
Pay attention to colors:
- Use vibrant, complementary colors
- Add contrast (dark outlines on light shapes, light outlines on dark shapes)
- Consider the overall composition
For complex shapes (hearts, snowflakes, etc.):
- Use combinations of polygons and ellipses
- Calculate points carefully for symmetry
- Add details (a heart can have a highlight curve, snowflakes have intricate branches)
Be creative and detailed! A good Slack GIF should look polished, not like placeholder graphics.
Available Utilities
GIFBuilder (core.gif_builder)
Assembles frames and optimizes for Slack:
builder = GIFBuilder(width=128, height=128, fps=10)
builder.add_frame(frame) # Add PIL Image
builder.add_frames(frames) # Add list of frames
builder.save('out.gif', num_colors=48, optimize_for_emoji=True, remove_duplicates=True)
Validators (core.validators)
Check if GIF meets Slack requirements:
from core.validators import (
validate_gif,
is_slack_ready,
check_slack_size,
validate_dimensions
)
# Detailed validation
passes, info = validate_gif('my.gif', is_emoji=True, verbose=True)
# Quick check
if is_slack_ready('my.gif'):
print("Ready!")
# Focused checks
passes, info = check_slack_size('my.gif', is_emoji=True)
passes, info = validate_dimensions(128, 128, is_emoji=True)
Easing Functions (core.easing)
Smooth motion instead of linear:
from core.easing import interpolate
# Progress from 0.0 to 1.0
t = i / (num_frames - 1)
# Apply easing
y = interpolate(start=0, end=400, t=t, easing='ease_out')
# Available: linear, ease_in, ease_out, ease_in_out,
# bounce_out, elastic_out, back_out
Frame Helpers (core.frame_composer)
Convenience functions for common needs:
from core.frame_composer import (
create_blank_frame, # Solid color background
create_gradient_background, # Vertical gradient
draw_circle, # Helper for circles
draw_rectangle, # Helper for rectangles
draw_line, # Helper for lines
draw_text, # Simple text rendering
draw_emoji, # Emoji rendering (platform-dependent)
draw_star # 5-pointed star
)
Other helpers include draw_emoji_enhanced, draw_circle_with_shadow, draw_rounded_rectangle, and add_vignette.
Color Palettes (core.color_palettes)
Hand-picked palettes and helpers for readable colors:
from core.color_palettes import get_palette, get_text_color_for_background
palette = get_palette('vibrant')
text_color = get_text_color_for_background(palette['background'])
Typography (core.typography)
High-quality outlined or shadowed text:
from core.typography import draw_text_with_outline
draw_text_with_outline(frame, "SALE!", position=(240, 240), font_size=48, centered=True)
Visual Effects (core.visual_effects)
Particles, blur, impacts, and motion effects:
from core.visual_effects import ParticleSystem
particles = ParticleSystem()
particles.emit(240, 240, count=20)
Animation Templates (templates/)
Ready-made animations (shake, bounce, spin, zoom, slide, fade, flip, explode, etc.).
Use them to generate frames and then pass to GIFBuilder.
Animation Concepts
Shake/Vibrate
Offset object position with oscillation:
- Use
math.sin()ormath.cos()with frame index - Add small random variations for natural feel
- Apply to x and/or y position
Pulse/Heartbeat
Scale object size rhythmically:
- Use
math.sin(t * frequency * 2 * math.pi)for smooth pulse - For heartbeat: two quick pulses then pause (adjust sine wave)
- Scale between 0.8 and 1.2 of base size
Bounce
Object falls and bounces:
- Use
interpolate()witheasing='bounce_out'for landing - Use
easing='ease_in'for falling (accelerating) - Apply gravity by increasing y velocity each frame
Spin/Rotate
Rotate object around center:
- PIL:
image.rotate(angle, resample=Image.BICUBIC) - For wobble: use sine wave for angle instead of linear
Fade In/Out
Gradually appear or disappear:
- Create RGBA image, adjust alpha channel
- Or use
Image.blend(image1, image2, alpha) - Fade in: alpha from 0 to 1
- Fade out: alpha from 1 to 0
Slide
Move object from off-screen to position:
- Start position: outside frame bounds
- End position: target location
- Use
interpolate()witheasing='ease_out'for smooth stop - For overshoot: use
easing='back_out'
Zoom
Scale and position for zoom effect:
- Zoom in: scale from 0.1 to 2.0, crop center
- Zoom out: scale from 2.0 to 1.0
- Can add motion blur for drama (PIL filter)
Explode/Particle Burst
Create particles radiating outward:
- Generate particles with random angles and velocities
- Update each particle:
x += vx,y += vy - Add gravity:
vy += gravity_constant - Fade out particles over time (reduce alpha)
Optimization Strategies
Only when asked to make the file size smaller, implement a few of the following methods:
- Fewer frames - Lower FPS (10 instead of 20) or shorter duration
- Fewer colors -
num_colors=48instead of 128 - Smaller dimensions - 128x128 instead of 480x480
- Remove duplicates -
remove_duplicates=Truein save() - Emoji mode -
optimize_for_emoji=Trueauto-optimizes
# Maximum optimization for emoji
builder.save(
'emoji.gif',
num_colors=48,
optimize_for_emoji=True,
remove_duplicates=True
)
Philosophy
This skill provides:
- Knowledge: Slack's requirements and animation concepts
- Utilities: GIFBuilder, validators, easing functions
- Flexibility: Create the animation logic using PIL primitives
It does NOT provide:
- Rigid animation templates or pre-made functions
- Emoji font rendering (unreliable across platforms)
- A library of pre-packaged graphics built into the skill
Note on user uploads: This skill doesn't include pre-built graphics, but if a user uploads an image, use PIL to load and work with it - interpret based on their request whether they want it used directly or just as inspiration.
Be creative! Combine concepts (bouncing + rotating, pulsing + sliding, etc.) and use PIL's full capabilities.
Dependencies
pip install pillow imageio numpy
Web Application Testing
To test local web applications, write native Python Playwright scripts.
Helper Scripts Available:
scripts/with_server.py- Manages server lifecycle (supports multiple servers)
Always run scripts with --help first to see usage. DO NOT read the source until you try running the script first and find that a customized solution is abslutely necessary. These scripts can be very large and thus pollute your context window. They exist to be called directly as black-box scripts rather than ingested into your context window.
Decision Tree: Choosing Your Approach
User task → Is it static HTML?
├─ Yes → Read HTML file directly to identify selectors
│ ├─ Success → Write Playwright script using selectors
│ └─ Fails/Incomplete → Treat as dynamic (below)
│
└─ No (dynamic webapp) → Is the server already running?
├─ No → Run: python scripts/with_server.py --help
│ Then use the helper + write simplified Playwright script
│
└─ Yes → Reconnaissance-then-action:
1. Navigate and wait for networkidle
2. Take screenshot or inspect DOM
3. Identify selectors from rendered state
4. Execute actions with discovered selectors
Example: Using with_server.py
To start a server, run --help first, then use the helper:
Single server:
python scripts/with_server.py --server "npm run dev" --port 5173 -- python your_automation.py
Multiple servers (e.g., backend + frontend):
python scripts/with_server.py \
--server "cd backend && python server.py" --port 3000 \
--server "cd frontend && npm run dev" --port 5173 \
-- python your_automation.py
To create an automation script, include only Playwright logic (servers are managed automatically):
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True) # Always launch chromium in headless mode
page = browser.new_page()
page.goto('http://localhost:5173') # Server already running and ready
page.wait_for_load_state('networkidle') # CRITICAL: Wait for JS to execute
# ... your automation logic
browser.close()
Reconnaissance-Then-Action Pattern
-
Inspect rendered DOM:
page.screenshot(path='/tmp/inspect.png', full_page=True) content = page.content() page.locator('button').all() -
Identify selectors from inspection results
-
Execute actions using discovered selectors
Common Pitfall
❌ Don't inspect the DOM before waiting for networkidle on dynamic apps
✅ Do wait for page.wait_for_load_state('networkidle') before inspection
Best Practices
- Use bundled scripts as black boxes - To accomplish a task, consider whether one of the scripts available in
scripts/can help. These scripts handle common, complex workflows reliably without cluttering the context window. Use--helpto see usage, then invoke directly. - Use
sync_playwright()for synchronous scripts - Always close the browser when done
- Use descriptive selectors:
text=,role=, CSS selectors, or IDs - Add appropriate waits:
page.wait_for_selector()orpage.wait_for_timeout()
Reference Files
- examples/ - Examples showing common patterns:
element_discovery.py- Discovering buttons, links, and inputs on a pagestatic_html_automation.py- Using file:// URLs for local HTMLconsole_logging.py- Capturing console logs during automation
Autonomous Agent Gaming
Build sophisticated game-playing agents that learn strategies, adapt to opponents, and master complex games through AI and reinforcement learning.
Overview
Autonomous game agents combine:
- Game Environment Interface: Connect to game rules and state
- Decision-Making Systems: Choose optimal actions
- Learning Mechanisms: Improve through experience
- Strategy Development: Long-term planning and adaptation
Applications
- Chess and board game masters
- Real-time strategy (RTS) game bots
- Video game autonomous players
- Game theory research
- AI testing and benchmarking
- Entertainment and challenge systems
Quick Start
Run example agents with:
# Rule-based agent
python examples/rule_based_agent.py
# Minimax with alpha-beta pruning
python examples/minimax_agent.py
# Monte Carlo Tree Search
python examples/mcts_agent.py
# Q-Learning agent
python examples/qlearning_agent.py
# Chess engine
python examples/chess_engine.py
# Game theory analysis
python scripts/game_theory_analyzer.py
# Benchmark agents
python scripts/agent_benchmark.py
Game Agent Architectures
1. Rule-Based Agents
Use predefined rules and heuristics. See full implementation in examples/rule_based_agent.py.
Key Concepts:
- Difficulty levels control strategy depth
- Evaluation combines material, position, and control factors
- Fast decision-making suitable for real-time games
- Easy to customize and understand
Usage Example:
from examples.rule_based_agent import RuleBasedGameAgent
agent = RuleBasedGameAgent(difficulty="hard")
best_move = agent.decide_action(game_state)
2. Minimax with Alpha-Beta Pruning
Optimal decision-making for turn-based games. See examples/minimax_agent.py.
Key Concepts:
- Exhaustive tree search up to fixed depth
- Alpha-beta pruning eliminates impossible branches
- Guarantees optimal play within search depth
- Evaluation function determines move quality
Performance Characteristics:
- Time complexity: O(b^(d/2)) with pruning vs O(b^d) without
- Space complexity: O(b*d)
- Adjustable depth for speed/quality tradeoff
Usage Example:
from examples.minimax_agent import MinimaxGameAgent
agent = MinimaxGameAgent(max_depth=6)
best_move = agent.get_best_move(game_state)
3. Monte Carlo Tree Search (MCTS)
Probabilistic game tree exploration. Full implementation in examples/mcts_agent.py.
Key Concepts:
- Four-phase algorithm: Selection, Expansion, Simulation, Backpropagation
- UCT (Upper Confidence bounds applied to Trees) balances exploration/exploitation
- Effective for games with high branching factors
- Anytime algorithm: more iterations = better decisions
The UCT Formula: UCT = (child_value / child_visits) + c * sqrt(ln(parent_visits) / child_visits)
Usage Example:
from examples.mcts_agent import MCTSAgent
agent = MCTSAgent(iterations=1000, exploration_constant=1.414)
best_move = agent.get_best_move(game_state)
4. Reinforcement Learning Agents
Learn through interaction with environment. See examples/qlearning_agent.py.
Key Concepts:
- Q-learning: model-free, off-policy learning
- Epsilon-greedy: balance exploration vs exploitation
- Update rule: Q(s,a) += α[r + γ*max_a'Q(s',a') - Q(s,a)]
- Q-table stores state-action value estimates
Hyperparameters:
- α (learning_rate): How quickly to adapt to new information
- γ (discount_factor): Importance of future rewards
- ε (epsilon): Exploration probability
Usage Example:
from examples.qlearning_agent import QLearningAgent
agent = QLearningAgent(learning_rate=0.1, discount_factor=0.99, epsilon=0.1)
action = agent.get_action(state)
agent.update_q_value(state, action, reward, next_state)
agent.decay_epsilon() # Reduce exploration over time
Game Environments
Standard Interfaces
Create game environments compatible with agents. See examples/game_environment.py for base classes.
Key Methods:
reset(): Initialize game statestep(action): Execute action, return (next_state, reward, done)get_legal_actions(state): List valid movesis_terminal(state): Check if game is overrender(): Display game state
OpenAI Gym Integration
Standard interface for game environments:
import gym
# Create environment
env = gym.make('CartPole-v1')
# Initialize
state = env.reset()
# Run episode
done = False
while not done:
action = agent.get_action(state)
next_state, reward, done, info = env.step(action)
agent.update(state, action, reward, next_state)
state = next_state
env.close()
Chess with python-chess
Full chess implementation in examples/chess_engine.py. Requires: pip install python-chess
Features:
- Full game rules and move validation
- Position evaluation based on material count
- Move history and undo functionality
- FEN notation support
Quick Example:
from examples.chess_engine import ChessAgent
agent = ChessAgent()
result, moves = agent.play_game()
print(f"Game result: {result} in {moves} moves")
Custom Game with Pygame
Extend examples/game_environment.py with pygame rendering:
from examples.game_environment import PygameGameEnvironment
class MyGame(PygameGameEnvironment):
def get_initial_state(self):
# Return initial game state
pass
def apply_action(self, state, action):
# Execute action, return new state
pass
def calculate_reward(self, state, action, next_state):
# Return reward value
pass
def is_terminal(self, state):
# Check if game is over
pass
def draw_state(self, state):
# Render using pygame
pass
game = MyGame()
game.render()
Strategy Development
All strategy implementations are in examples/strategy_modules.py.
1. Opening Theory
Pre-computed best moves for game openings. Load from PGN files or opening databases.
OpeningBook Features:
- Fast lookup using position hashing
- Load from PGN, opening databases, or create custom books
- Fallback to other strategies when out of book
Usage:
from examples.strategy_modules import OpeningBook
book = OpeningBook()
if book.in_opening(game_state):
move = book.get_opening_move(game_state)
2. Endgame Tablebases
Pre-computed endgame solutions with optimal moves and distance-to-mate.
Features:
- Guaranteed optimal moves in endgame positions
- Distance-to-mate calculation
- Lookup by position hash
Usage:
from examples.strategy_modules import EndgameTablebase
tablebase = EndgameTablebase()
if tablebase.in_tablebase(game_state):
move = tablebase.get_best_endgame_move(game_state)
dtm = tablebase.get_endgame_distance(game_state)
3. Multi-Stage Strategy
Combine different agents for different game phases using AdaptiveGameAgent.
Strategy Selection:
- Opening (Material > 30): Use opening book or memorized lines
- Middlegame (10-30): Use search-based engine (Minimax, MCTS)
- Endgame (Material < 10): Use tablebase for optimal play
Usage:
from examples.strategy_modules import AdaptiveGameAgent
from examples.minimax_agent import MinimaxGameAgent
agent = AdaptiveGameAgent(
opening_book=book,
middlegame_engine=MinimaxGameAgent(max_depth=6),
endgame_tablebase=tablebase
)
move = agent.decide_action(game_state)
phase_info = agent.get_phase_info(game_state)
4. Composite Strategies
Combine multiple strategies with priority ordering using CompositeStrategy.
Usage:
from examples.strategy_modules import CompositeStrategy
composite = CompositeStrategy([
opening_strategy,
endgame_strategy,
default_search_strategy
])
move = composite.get_move(game_state)
active = composite.get_active_strategy(game_state)
Performance Optimization
All optimization utilities are in scripts/performance_optimizer.py.
1. Transposition Tables
Cache evaluated positions to avoid re-computation. Especially effective with alpha-beta pruning.
How it works:
- Stores evaluation (score + depth + bound type)
- Hashes positions for fast lookup
- Only overwrites if new evaluation is deeper
- Thread-safe for parallel search
Bound Types:
- exact: Exact evaluation
- lower: Evaluation is at least this value
- upper: Evaluation is at most this value
Usage:
from scripts.performance_optimizer import TranspositionTable
tt = TranspositionTable(max_size=1000000)
# Store evaluation
tt.store(position_hash, depth=6, score=150, flag='exact')
# Lookup
score = tt.lookup(position_hash, depth=6)
hit_rate = tt.hit_rate()
2. Killer Heuristic
Track moves that cause cutoffs at similar depths for move ordering improvement.
Concept:
- Killer moves are non-capture moves that caused beta cutoffs
- Likely to be good moves at other nodes of same depth
- Improves alpha-beta pruning efficiency
Usage:
from scripts.performance_optimizer import KillerHeuristic
killers = KillerHeuristic(max_depth=20)
# When a cutoff occurs
killers.record_killer(move, depth=5)
# When ordering moves
killer_list = killers.get_killers(depth=5)
is_killer = killers.is_killer(move, depth=5)
3. Parallel Search
Parallelize game tree search across multiple threads.
Usage:
from scripts.performance_optimizer import ParallelSearchCoordinator
coordinator = ParallelSearchCoordinator(num_threads=4)
# Parallel move evaluation
scores = coordinator.parallel_evaluate_moves(moves, evaluate_func)
# Parallel minimax
best_move, score = coordinator.parallel_minimax(root_moves, minimax_func)
coordinator.shutdown()
4. Search Statistics
Track and analyze search performance with SearchStatistics.
Metrics:
- Nodes evaluated / pruned
- Branching factor
- Pruning efficiency
- Cache hit rate
Usage:
from scripts.performance_optimizer import SearchStatistics
stats = SearchStatistics()
# During search
stats.record_node()
stats.record_cutoff()
stats.record_cache_hit()
# Analysis
print(stats.summary())
print(f"Pruning efficiency: {stats.pruning_efficiency():.1f}%")
Game Theory Applications
Full implementation in scripts/game_theory_analyzer.py.
1. Nash Equilibrium Calculation
Find optimal mixed strategy solutions for 2-player games.
Pure Strategy Nash Equilibria: A cell is a Nash equilibrium if it's a best response for both players.
Mixed Strategy Nash Equilibria: Players randomize over actions. For 2x2 games, use indifference conditions.
Usage:
from scripts.game_theory_analyzer import GameTheoryAnalyzer, PayoffMatrix
import numpy as np
# Create payoff matrix
p1_payoffs = np.array([[3, 0], [5, 1]])
p2_payoffs = np.array([[3, 5], [0, 1]])
matrix = PayoffMatrix(
player1_payoffs=p1_payoffs,
player2_payoffs=p2_payoffs,
row_labels=['Strategy A', 'Strategy B'],
column_labels=['Strategy X', 'Strategy Y']
)
analyzer = GameTheoryAnalyzer()
# Find pure Nash equilibria
equilibria = analyzer.find_pure_strategy_nash_equilibria(matrix)
# Find mixed Nash equilibrium (2x2 only)
p1_mixed, p2_mixed = analyzer.calculate_mixed_strategy_2x2(matrix)
# Expected payoff
payoff = analyzer.calculate_expected_payoff(p1_mixed, p2_mixed, matrix, player=1)
# Zero-sum analysis
if matrix.is_zero_sum():
minimax = analyzer.minimax_value(matrix)
maximin = analyzer.maximin_value(matrix)
2. Cooperative Game Analysis
Analyze coalitional games where players can coordinate.
Shapley Value:
- Fair allocation of total payoff based on marginal contributions
- Each player receives expected marginal contribution across all coalition orderings
Core:
- Set of allocations where no coalition wants to deviate
- Stable outcomes that satisfy coalitional rationality
Usage:
from scripts.game_theory_analyzer import CooperativeGameAnalyzer
coop = CooperativeGameAnalyzer()
# Define payoff function for coalitions
def payoff_func(coalition):
# Return total value of coalition
return sum(player_values[p] for p in coalition)
players = ['Alice', 'Bob', 'Charlie']
# Calculate Shapley values
shapley = coop.calculate_shapley_value(payoff_func, players)
print(f"Alice's fair share: {shapley['Alice']}")
# Find core allocation
core = coop.calculate_core(payoff_func, players)
is_stable = coop.is_core_allocation(core, payoff_func, players)
Best Practices
Agent Development
- ✓ Start with rule-based baseline
- ✓ Measure performance metrics consistently
- ✓ Test against multiple opponents
- ✓ Use version control for agent versions
- ✓ Document strategy changes
Game Environment
- ✓ Validate game rules implementation
- ✓ Test edge cases
- ✓ Provide easy reset/replay
- ✓ Log game states for analysis
- ✓ Support deterministic seeds
Optimization
- ✓ Profile before optimizing
- ✓ Use transposition tables
- ✓ Implement proper time management
- ✓ Monitor memory usage
- ✓ Benchmark against baselines
Testing and Benchmarking
Complete benchmarking toolkit in scripts/agent_benchmark.py.
Tournament Evaluation
Run round-robin or elimination tournaments between agents.
Usage:
from scripts.agent_benchmark import GameAgentBenchmark
benchmark = GameAgentBenchmark()
# Run tournament
results = benchmark.run_tournament(agents, num_games=100)
# Compare two agents
comparison = benchmark.head_to_head_comparison(agent1, agent2, num_games=50)
print(f"Win rate: {comparison['agent1_win_rate']:.1%}")
Rating Systems
Calculate agent strength using standard rating systems.
Elo Rating:
- Based on strength differential
- K-factor of 32 for normal games
- Used in chess and many games
Glicko-2 Rating:
- Accounts for rating uncertainty (deviation)
- Better for irregular play schedules
Usage:
# Elo ratings
elo_ratings = benchmark.evaluate_elo_rating(agents, num_games=100)
# Glicko-2 ratings
glicko_ratings = benchmark.glicko2_rating(agents, num_games=100)
# Strength relative to baseline
strength = benchmark.rate_agent_strength(agent, baseline_agents, num_games=20)
Performance Profiling
Evaluate agent quality on test positions.
Usage:
# Get performance profile
profile = benchmark.performance_profile(agent, test_positions, time_limit=1.0)
print(f"Accuracy: {profile['accuracy']:.1%}")
print(f"Avg move quality: {profile['avg_move_quality']:.2f}")
Implementation Checklist
- Choose game environment (Gym, Chess, Custom)
- Design agent architecture (Rule-based, Minimax, MCTS, RL)
- Implement game state representation
- Create evaluation function
- Implement agent decision-making
- Set up training/learning loop
- Create benchmarking system
- Test against multiple opponents
- Optimize performance (search depth, eval speed)
- Document strategy and results
- Deploy and monitor performance
Resources
Frameworks
- OpenAI Gym: https://gym.openai.com/
- python-chess: https://python-chess.readthedocs.io/
- Pygame: https://www.pygame.org/
Research
- AlphaGo papers: https://deepmind.com/
- Stockfish: https://stockfishchess.org/
- Game Theory: Introduction to Game Theory (Osborne & Rubinstein)
AWS Bedrock AgentCore
AWS Bedrock AgentCore provides a complete platform for deploying and scaling AI agents with seven core services. This skill guides you through service selection, deployment patterns, and integration workflows using AWS CLI.
AWS Documentation Requirement
CRITICAL: This skill requires AWS MCP tools for accurate, up-to-date AWS information.
Before Answering AWS Questions
-
Always verify using AWS MCP tools (if available):
mcp__aws-mcp__aws___search_documentationormcp__*awsdocs*__aws___search_documentation- Search AWS docsmcp__aws-mcp__aws___read_documentationormcp__*awsdocs*__aws___read_documentation- Read specific pagesmcp__aws-mcp__aws___get_regional_availability- Check service availability
-
If AWS MCP tools are unavailable:
- Guide user to configure AWS MCP: See AWS MCP Setup Guide
- Help determine which option fits their environment:
- Has uvx + AWS credentials → Full AWS MCP Server
- No Python/credentials → AWS Documentation MCP (no auth)
- If cannot determine → Ask user which option to use
When to Use This Skill
Use this skill when you need to:
- Deploy REST APIs as MCP tools for AI agents (Gateway)
- Execute agents in serverless runtime (Runtime)
- Add conversation memory to agents (Memory)
- Manage API credentials and authentication (Identity)
- Enable agents to execute code securely (Code Interpreter)
- Allow agents to interact with websites (Browser)
- Monitor and trace agent performance (Observability)
Available Services
| Service | Use For | Documentation |
|---|---|---|
| Gateway | Converting REST APIs to MCP tools | services/gateway/README.md |
| Runtime | Deploying and scaling agents | services/runtime/README.md |
| Memory | Managing conversation state | services/memory/README.md |
| Identity | Credential and access management | services/identity/README.md |
| Code Interpreter | Secure code execution in sandboxes | services/code-interpreter/README.md |
| Browser | Web automation and scraping | services/browser/README.md |
| Observability | Tracing and monitoring | services/observability/README.md |
Common Workflows
Deploying a Gateway Target
MANDATORY - READ DETAILED DOCUMENTATION: See services/gateway/README.md for complete Gateway setup guide including deployment strategies, troubleshooting, and IAM configuration.
Quick Workflow:
- Upload OpenAPI schema to S3
- (API Key auth only) Create credential provider and store API key
- Create gateway target linking schema (and credentials if using API key)
- Verify target status and test connectivity
Note: Credential provider is only needed for API key authentication. Lambda targets use IAM roles, and MCP servers use OAuth.
Managing Credentials
MANDATORY - READ DETAILED DOCUMENTATION: See cross-service/credential-management.md for unified credential management patterns across all services.
Quick Workflow:
- Use Identity service credential providers for all API keys
- Link providers to gateway targets via ARN references
- Rotate credentials quarterly through credential provider updates
- Monitor usage with CloudWatch metrics
Monitoring Agents
MANDATORY - READ DETAILED DOCUMENTATION: See services/observability/README.md for comprehensive monitoring setup.
Quick Workflow:
- Enable observability for agents
- Configure CloudWatch dashboards for metrics
- Set up alarms for error rates and latency
- Use X-Ray for distributed tracing
Service-Specific Documentation
For detailed documentation on each AgentCore service, see the following resources:
Gateway Service
- Overview:
services/gateway/README.md - Deployment Strategies:
services/gateway/deployment-strategies.md - Troubleshooting:
services/gateway/troubleshooting-guide.md
Runtime, Memory, Identity, Code Interpreter, Browser, Observability
Each service has comprehensive documentation in its respective directory:
services/runtime/README.mdservices/memory/README.mdservices/identity/README.mdservices/code-interpreter/README.mdservices/browser/README.mdservices/observability/README.md
Cross-Service Resources
For patterns and best practices that span multiple AgentCore services:
- Credential Management:
cross-service/credential-management.md- Unified credential patterns, security practices, rotation procedures
Additional Resources
- AWS Documentation: Amazon Bedrock AgentCore
- API Reference: Bedrock AgentCore Control Plane API
- AWS CLI Reference: bedrock-agentcore-control commands
Supabase Integration Expert
Purpose
Provide comprehensive, accurate guidance for building applications with Supabase based on 2,616+ official documentation files. Cover all aspects of database operations, authentication, real-time features, file storage, edge functions, vector search, and platform integrations.
Documentation Coverage
Full access to official Supabase documentation (when available):
- Location:
docs/supabase_com/ - Files: 2,616 markdown files
- Coverage: Complete guides, API references, client libraries, and platform docs
Note: Documentation must be pulled separately:
pipx install docpull
docpull https://supabase.com/docs -o .claude/skills/supabase/docs
Major Areas:
- Database: PostgreSQL, Row Level Security (RLS), migrations, functions, triggers
- Authentication: Email/password, OAuth, magic links, SSO, MFA, phone auth
- Real-time: Database changes, broadcast, presence, channels
- Storage: File uploads, image transformations, CDN, buckets
- Edge Functions: Deno runtime, serverless, global deployment
- Vector/AI: pgvector, embeddings, semantic search, RAG
- Client Libraries: JavaScript, Python, Dart (Flutter), Swift, Kotlin
- Platform: CLI, local development, branching, observability
- Integrations: Next.js, React, Vue, Svelte, React Native, Expo
When to Use
Invoke when user mentions:
- Database: PostgreSQL, Postgres, SQL, database, tables, queries, migrations
- Auth: authentication, login, signup, OAuth, SSO, multi-factor, magic links
- Real-time: real-time, subscriptions, websocket, live data, presence, broadcast
- Storage: file upload, file storage, images, S3, CDN, buckets
- Functions: edge functions, serverless, API, Deno, cloud functions
- Security: Row Level Security, RLS, policies, permissions, access control
- AI/ML: vector search, embeddings, pgvector, semantic search, AI, RAG
- Framework Integration: Next.js, React, Supabase client, hooks
How to Use Documentation
When answering questions:
-
Search for specific topics:
# Use Grep to find relevant docs grep -r "row level security" docs/supabase_com/ --include="*.md" -
Find guides:
# Guides are organized by feature ls docs/supabase_com/guides_* -
Check reference docs:
# Reference docs for client libraries ls docs/supabase_com/reference_*
Quick Start
Installation
npm install @supabase/supabase-js
Initialize Client
import { createClient } from '@supabase/supabase-js';
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
Environment Variables:
NEXT_PUBLIC_SUPABASE_URL- Your project URL (safe for client)NEXT_PUBLIC_SUPABASE_ANON_KEY- Anonymous/public key (safe for client)SUPABASE_SERVICE_ROLE_KEY- Admin key (server-side only, bypasses RLS)
Database Operations
CRUD Operations
// Insert
const { data, error } = await supabase
.from('posts')
.insert({
title: 'Hello World',
content: 'My first post',
user_id: user.id,
})
.select()
.single();
// Read (with filters)
const { data: posts } = await supabase
.from('posts')
.select('*')
.eq('published', true)
.order('created_at', { ascending: false })
.limit(10);
// Update
const { data, error } = await supabase
.from('posts')
.update({ published: true })
.eq('id', postId)
.select()
.single();
// Delete
const { error } = await supabase
.from('posts')
.delete()
.eq('id', postId);
// Upsert (insert or update)
const { data, error } = await supabase
.from('profiles')
.upsert({
id: user.id,
name: 'John Doe',
updated_at: new Date().toISOString(),
})
.select();
Advanced Queries
// Joins
const { data } = await supabase
.from('posts')
.select(`
*,
author:profiles(name, avatar),
comments(count)
`)
.eq('published', true);
// Full-text search
const { data } = await supabase
.from('posts')
.select('*')
.textSearch('title', `'nextjs' & 'supabase'`);
// Range queries
const { data } = await supabase
.from('posts')
.select('*')
.gte('created_at', '2024-01-01')
.lt('created_at', '2024-12-31');
// JSON queries
const { data } = await supabase
.from('posts')
.select('*')
.contains('metadata', { tags: ['tutorial'] });
Database Functions
// Call stored procedure
const { data, error } = await supabase
.rpc('get_user_stats', {
user_id: userId,
});
// Call with filters
const { data } = await supabase
.rpc('search_posts', { search_term: 'supabase' })
.limit(10);
Authentication
Sign Up / Sign In
// Email/password signup
const { data, error } = await supabase.auth.signUp({
email: 'user@example.com',
password: 'secure-password',
options: {
data: {
first_name: 'John',
last_name: 'Doe',
},
},
});
// Email/password sign in
const { data, error } = await supabase.auth.signInWithPassword({
email: 'user@example.com',
password: 'secure-password',
});
// Magic link (passwordless)
const { data, error } = await supabase.auth.signInWithOtp({
email: 'user@example.com',
options: {
emailRedirectTo: 'https://example.com/auth/callback',
},
});
// Phone/SMS
const { data, error } = await supabase.auth.signInWithOtp({
phone: '+1234567890',
});
OAuth Providers
// Google sign in
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: 'http://localhost:3000/auth/callback',
scopes: 'profile email',
},
});
Supported providers:
- Google, GitHub, GitLab, Bitbucket
- Azure, Apple, Discord, Facebook
- Slack, Spotify, Twitch, Twitter/X
- Linear, Notion, Figma, and more
User Session Management
// Get current user
const { data: { user } } = await supabase.auth.getUser();
// Get session
const { data: { session } } = await supabase.auth.getSession();
// Sign out
const { error } = await supabase.auth.signOut();
// Listen to auth changes
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') {
console.log('User signed in:', session.user);
}
if (event === 'SIGNED_OUT') {
console.log('User signed out');
}
if (event === 'TOKEN_REFRESHED') {
console.log('Token refreshed');
}
});
Multi-Factor Authentication (MFA)
// Enroll MFA
const { data, error } = await supabase.auth.mfa.enroll({
factorType: 'totp',
friendlyName: 'My Authenticator App',
});
// Verify MFA
const { data, error } = await supabase.auth.mfa.challengeAndVerify({
factorId: data.id,
code: '123456',
});
// List factors
const { data: factors } = await supabase.auth.mfa.listFactors();
Row Level Security (RLS)
Enable RLS
-- Enable RLS on table
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
Create Policies
-- Public read access
CREATE POLICY "Posts are viewable by everyone"
ON posts FOR SELECT
USING (true);
-- Users can insert their own posts
CREATE POLICY "Users can create posts"
ON posts FOR INSERT
WITH CHECK (auth.uid() = user_id);
-- Users can update only their posts
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = user_id);
-- Users can delete only their posts
CREATE POLICY "Users can delete own posts"
ON posts FOR DELETE
USING (auth.uid() = user_id);
-- Conditional access (e.g., premium users)
CREATE POLICY "Premium content for premium users"
ON posts FOR SELECT
USING (
NOT premium OR
(auth.uid() IN (
SELECT user_id FROM subscriptions
WHERE status = 'active'
))
);
Helper Functions
-- Get current user ID
auth.uid()
-- Get current JWT
auth.jwt()
-- Access JWT claims
(auth.jwt()->>'role')::text
(auth.jwt()->>'email')::text
Real-time Subscriptions
Listen to Database Changes
const channel = supabase
.channel('posts-changes')
.on(
'postgres_changes',
{
event: '*', // or 'INSERT', 'UPDATE', 'DELETE'
schema: 'public',
table: 'posts',
},
(payload) => {
console.log('Change received:', payload);
}
)
.subscribe();
// Cleanup
channel.unsubscribe();
Filter Real-time Events
// Only listen to specific user's posts
const channel = supabase
.channel('my-posts')
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
table: 'posts',
filter: `user_id=eq.${userId}`,
},
(payload) => {
console.log('New post:', payload.new);
}
)
.subscribe();
Broadcast (Ephemeral Messages)
const channel = supabase.channel('chat-room');
// Send message
await channel.send({
type: 'broadcast',
event: 'message',
payload: { text: 'Hello!', user: 'John' },
});
// Receive messages
channel.on('broadcast', { event: 'message' }, (payload) => {
console.log('Message:', payload.payload);
});
await channel.subscribe();
Presence Tracking
const channel = supabase.channel('room-1');
// Track presence
channel
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState();
console.log('Online users:', Object.keys(state).length);
})
.on('presence', { event: 'join' }, ({ key, newPresences }) => {
console.log('User joined:', newPresences);
})
.on('presence', { event: 'leave' }, ({ key, leftPresences }) => {
console.log('User left:', leftPresences);
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({
user_id: userId,
online_at: new Date().toISOString(),
});
}
});
Storage
Upload Files
const file = event.target.files[0];
const { data, error } = await supabase.storage
.from('avatars')
.upload(`public/${userId}/avatar.png`, file, {
cacheControl: '3600',
upsert: true,
});
// Upload from base64
const { data, error } = await supabase.storage
.from('avatars')
.upload('file.png', decode(base64String), {
contentType: 'image/png',
});
Download Files
// Download as blob
const { data, error } = await supabase.storage
.from('avatars')
.download('public/avatar.png');
const url = URL.createObjectURL(data);
Public URLs
// Get public URL (for public buckets)
const { data } = supabase.storage
.from('avatars')
.getPublicUrl('public/avatar.png');
console.log(data.publicUrl);
Signed URLs (Private Files)
// Create temporary access URL
const { data, error } = await supabase.storage
.from('private-files')
.createSignedUrl('document.pdf', 3600); // 1 hour
console.log(data.signedUrl);
Image Transformations
const { data } = supabase.storage
.from('avatars')
.getPublicUrl('avatar.png', {
transform: {
width: 400,
height: 400,
resize: 'cover', // 'contain', 'cover', 'fill'
quality: 80,
},
});
List Files
const { data, error } = await supabase.storage
.from('avatars')
.list('public', {
limit: 100,
offset: 0,
sortBy: { column: 'created_at', order: 'desc' },
});
Edge Functions
Create Function
# Install Supabase CLI
npm install -g supabase
# Initialize project
supabase init
# Create function
supabase functions new my-function
Function Example
// supabase/functions/my-function/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
serve(async (req) => {
try {
// Initialize Supabase client
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_ANON_KEY')!,
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
},
}
);
// Get authenticated user
const { data: { user }, error: authError } = await supabase.auth.getUser();
if (authError || !user) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
// Query database
const { data: posts, error } = await supabase
.from('posts')
.select('*')
.eq('user_id', user.id);
if (error) throw error;
return new Response(JSON.stringify({ posts }), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
});
Deploy Function
# Deploy single function
supabase functions deploy my-function
# Deploy all functions
supabase functions deploy
Invoke Function
const { data, error } = await supabase.functions.invoke('my-function', {
body: { name: 'World' },
});
console.log(data);
Vector Search (AI/ML)
Enable pgvector
-- Enable extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create table with vector column
CREATE TABLE documents (
id BIGSERIAL PRIMARY KEY,
content TEXT,
embedding VECTOR(1536) -- OpenAI ada-002 dimensions
);
-- Create HNSW index for fast similarity search
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
Store Embeddings
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Generate embedding
const response = await openai.embeddings.create({
model: 'text-embedding-ada-002',
input: 'Supabase is awesome',
});
const embedding = response.data[0].embedding;
// Store in database
const { data, error } = await supabase
.from('documents')
.insert({
content: 'Supabase is awesome',
embedding,
});
Similarity Search
// Find similar documents
const { data, error } = await supabase.rpc('match_documents', {
query_embedding: embedding,
match_threshold: 0.78,
match_count: 10,
});
Similarity search function:
CREATE FUNCTION match_documents (
query_embedding VECTOR(1536),
match_threshold FLOAT,
match_count INT
)
RETURNS TABLE (
id BIGINT,
content TEXT,
similarity FLOAT
)
LANGUAGE plpgsql
AS $$
BEGIN
RETURN QUERY
SELECT
documents.id,
documents.content,
1 - (documents.embedding <=> query_embedding) AS similarity
FROM documents
WHERE 1 - (documents.embedding <=> query_embedding) > match_threshold
ORDER BY documents.embedding <=> query_embedding
LIMIT match_count;
END;
$$;
Next.js Integration
Server Components
// app/posts/page.tsx
import { createServerComponentClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
export default async function PostsPage() {
const supabase = createServerComponentClient({ cookies });
const { data: posts } = await supabase
.from('posts')
.select('*')
.order('created_at', { ascending: false });
return (
<div>
{posts?.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
}
Client Components
// app/new-post/page.tsx
'use client';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { useState } from 'react';
export default function NewPostPage() {
const supabase = createClientComponentClient();
const [title, setTitle] = useState('');
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
const { error } = await supabase
.from('posts')
.insert({ title });
if (error) console.error(error);
};
return <form onSubmit={handleSubmit}>...</form>;
}
Middleware (Auth Protection)
// middleware.ts
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const supabase = createMiddlewareClient({ req, res });
const { data: { session } } = await supabase.auth.getSession();
// Redirect to login if not authenticated
if (!session && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url));
}
return res;
}
export const config = {
matcher: ['/dashboard/:path*'],
};
Route Handlers
// app/api/posts/route.ts
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
export async function GET() {
const supabase = createRouteHandlerClient({ cookies });
const { data: posts } = await supabase
.from('posts')
.select('*');
return NextResponse.json({ posts });
}
export async function POST(request: Request) {
const supabase = createRouteHandlerClient({ cookies });
const body = await request.json();
const { data, error } = await supabase
.from('posts')
.insert(body)
.select()
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
return NextResponse.json({ post: data });
}
Database Migrations
Create Migration
supabase migration new create_posts_table
Migration File Example
-- supabase/migrations/20241116000000_create_posts_table.sql
-- Create table
CREATE TABLE posts (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
user_id UUID REFERENCES auth.users NOT NULL,
title TEXT NOT NULL,
content TEXT,
published BOOLEAN DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL
);
-- Enable RLS
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
-- Create policies
CREATE POLICY "Public posts are viewable by everyone"
ON posts FOR SELECT
USING (published = true);
CREATE POLICY "Users can view their own posts"
ON posts FOR SELECT
USING (auth.uid() = user_id);
CREATE POLICY "Users can create posts"
ON posts FOR INSERT
WITH CHECK (auth.uid() = user_id);
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = user_id);
-- Create indexes
CREATE INDEX posts_user_id_idx ON posts(user_id);
CREATE INDEX posts_created_at_idx ON posts(created_at DESC);
CREATE INDEX posts_published_idx ON posts(published) WHERE published = true;
-- Create updated_at trigger
CREATE OR REPLACE FUNCTION handle_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION handle_updated_at();
Run Migrations
# Apply migrations locally
supabase db reset
# Push to remote (production)
supabase db push
TypeScript Integration
Database Type Generation
# Generate types from your database schema
supabase gen types typescript --project-id YOUR_PROJECT_ID > types/supabase.ts
# Or from local development
supabase gen types typescript --local > types/supabase.ts
Type-Safe Client
// lib/supabase/types.ts
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json | undefined }
| Json[]
export interface Database {
public: {
Tables: {
posts: {
Row: {
id: string
created_at: string
title: string
content: string | null
user_id: string
published: boolean
}
Insert: {
id?: string
created_at?: string
title: string
content?: string | null
user_id: string
published?: boolean
}
Update: {
id?: string
created_at?: string
title?: string
content?: string | null
user_id?: string
published?: boolean
}
}
profiles: {
Row: {
id: string
name: string | null
avatar_url: string | null
created_at: string
}
Insert: {
id: string
name?: string | null
avatar_url?: string | null
created_at?: string
}
Update: {
id?: string
name?: string | null
avatar_url?: string | null
created_at?: string
}
}
}
Views: {
[_ in never]: never
}
Functions: {
[_ in never]: never
}
Enums: {
[_ in never]: never
}
}
}
// lib/supabase/client.ts
import { createClient } from '@supabase/supabase-js'
import { Database } from './types'
export const supabase = createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
// Now you get full type safety!
const { data } = await supabase
.from('posts') // ✅ TypeScript knows this table exists
.select('title, content, profiles(name)') // ✅ TypeScript validates columns
.eq('published', true) // ✅ TypeScript validates types
// data is typed as:
// Array<{ title: string; content: string | null; profiles: { name: string | null } }>
Server vs Client Supabase
// lib/supabase/client.ts - Client-side (respects RLS)
import { createBrowserClient } from '@supabase/ssr'
import { Database } from './types'
export function createClient() {
return createBrowserClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
}
// lib/supabase/server.ts - Server-side (Next.js App Router)
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { cookies } from 'next/headers'
import { Database } from './types'
export function createClient() {
const cookieStore = cookies()
return createServerClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value
},
set(name: string, value: string, options: CookieOptions) {
try {
cookieStore.set({ name, value, ...options })
} catch (error) {
// Called from Server Component - ignore
}
},
remove(name: string, options: CookieOptions) {
try {
cookieStore.set({ name, value: '', ...options })
} catch (error) {
// Called from Server Component - ignore
}
},
},
}
)
}
// lib/supabase/admin.ts - Admin client (bypasses RLS)
import { createClient } from '@supabase/supabase-js'
import { Database } from './types'
export const supabaseAdmin = createClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!, // ⚠️ Server-side only!
{
auth: {
autoRefreshToken: false,
persistSession: false
}
}
)
Next.js App Router Patterns
Server Components (Recommended)
// app/posts/page.tsx
import { createClient } from '@/lib/supabase/server'
export default async function PostsPage() {
const supabase = createClient()
// Fetch data on server (no loading state needed!)
const { data: posts } = await supabase
.from('posts')
.select('*, profiles(*)')
.eq('published', true)
.order('created_at', { ascending: false })
return (
<div>
{posts?.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>By {post.profiles?.name}</p>
<div>{post.content}</div>
</article>
))}
</div>
)
}
Server Actions for Mutations
// app/actions/posts.ts
'use server'
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
const title = formData.get('title') as string
const content = formData.get('content') as string
const { error } = await supabase
.from('posts')
.insert({
title,
content,
user_id: user.id,
})
if (error) {
throw new Error(error.message)
}
revalidatePath('/posts')
redirect('/posts')
}
export async function updatePost(id: string, formData: FormData) {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) throw new Error('Unauthorized')
const { error } = await supabase
.from('posts')
.update({
title: formData.get('title') as string,
content: formData.get('content') as string,
})
.eq('id', id)
.eq('user_id', user.id) // Ensure user owns the post
if (error) throw new Error(error.message)
revalidatePath('/posts')
}
export async function deletePost(id: string) {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) throw new Error('Unauthorized')
const { error } = await supabase
.from('posts')
.delete()
.eq('id', id)
.eq('user_id', user.id)
if (error) throw new Error(error.message)
revalidatePath('/posts')
}
Client Component with Real-time
// app/components/PostsList.tsx
'use client'
import { useEffect, useState } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Database } from '@/lib/supabase/types'
type Post = Database['public']['Tables']['posts']['Row']
export function PostsList({ initialPosts }: { initialPosts: Post[] }) {
const [posts, setPosts] = useState(initialPosts)
const supabase = createClient()
useEffect(() => {
const channel = supabase
.channel('posts-changes')
.on(
'postgres_changes',
{
event: '*',
schema: 'public',
table: 'posts',
filter: 'published=eq.true',
},
(payload) => {
if (payload.eventType === 'INSERT') {
setPosts(prev => [payload.new as Post, ...prev])
} else if (payload.eventType === 'UPDATE') {
setPosts(prev =>
prev.map(post =>
post.id === payload.new.id ? (payload.new as Post) : post
)
)
} else if (payload.eventType === 'DELETE') {
setPosts(prev => prev.filter(post => post.id !== payload.old.id))
}
}
)
.subscribe()
return () => {
supabase.removeChannel(channel)
}
}, [supabase])
return (
<div>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
))}
</div>
)
}
Route Handlers
// app/api/posts/route.ts
import { createClient } from '@/lib/supabase/server'
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
const supabase = createClient()
const { searchParams } = new URL(request.url)
const limit = parseInt(searchParams.get('limit') || '10')
const { data, error } = await supabase
.from('posts')
.select('*')
.eq('published', true)
.order('created_at', { ascending: false })
.limit(limit)
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json(data)
}
export async function POST(request: NextRequest) {
const supabase = createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await request.json()
const { data, error } = await supabase
.from('posts')
.insert({
...body,
user_id: user.id,
})
.select()
.single()
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json(data)
}
Advanced Authentication
Email/Password with Email Confirmation
// app/actions/auth.ts
'use server'
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
export async function signUp(formData: FormData) {
const supabase = createClient()
const email = formData.get('email') as string
const password = formData.get('password') as string
const name = formData.get('name') as string
const { error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
name, // Stored in auth.users.raw_user_meta_data
},
emailRedirectTo: `${process.env.NEXT_PUBLIC_URL}/auth/callback`,
},
})
if (error) {
return { error: error.message }
}
return { success: true, message: 'Check your email to confirm your account' }
}
export async function signIn(formData: FormData) {
const supabase = createClient()
const email = formData.get('email') as string
const password = formData.get('password') as string
const { error } = await supabase.auth.signInWithPassword({
email,
password,
})
if (error) {
return { error: error.message }
}
redirect('/dashboard')
}
export async function signOut() {
const supabase = createClient()
await supabase.auth.signOut()
redirect('/')
}
OAuth (Google, GitHub, etc.)
// app/actions/auth.ts
export async function signInWithGoogle() {
const supabase = createClient()
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: `${process.env.NEXT_PUBLIC_URL}/auth/callback`,
queryParams: {
access_type: 'offline',
prompt: 'consent',
},
},
})
if (data?.url) {
redirect(data.url)
}
}
export async function signInWithGitHub() {
const supabase = createClient()
const { data } = await supabase.auth.signInWithOAuth({
provider: 'github',
options: {
redirectTo: `${process.env.NEXT_PUBLIC_URL}/auth/callback`,
scopes: 'read:user user:email',
},
})
if (data?.url) {
redirect(data.url)
}
}
Magic Links
export async function sendMagicLink(email: string) {
const supabase = createClient()
const { error } = await supabase.auth.signInWithOtp({
email,
options: {
emailRedirectTo: `${process.env.NEXT_PUBLIC_URL}/auth/callback`,
},
})
if (error) {
return { error: error.message }
}
return { success: true, message: 'Check your email for the login link' }
}
Phone Auth (SMS)
export async function sendPhoneOTP(phone: string) {
const supabase = createClient()
const { error } = await supabase.auth.signInWithOtp({
phone,
})
if (error) {
return { error: error.message }
}
return { success: true }
}
export async function verifyPhoneOTP(phone: string, token: string) {
const supabase = createClient()
const { error } = await supabase.auth.verifyOtp({
phone,
token,
type: 'sms',
})
if (error) {
return { error: error.message }
}
redirect('/dashboard')
}
Multi-Factor Authentication (MFA)
// Enable MFA for user
export async function enableMFA() {
const supabase = createClient()
const { data, error } = await supabase.auth.mfa.enroll({
factorType: 'totp',
friendlyName: 'Authenticator App',
})
if (error) throw error
// data.totp.qr_code - QR code to scan
// data.totp.secret - Secret to enter manually
return data
}
// Verify MFA
export async function verifyMFA(factorId: string, code: string) {
const supabase = createClient()
const { data, error } = await supabase.auth.mfa.challengeAndVerify({
factorId,
code,
})
if (error) throw error
return data
}
Auth Callback Handler
// app/auth/callback/route.ts
import { createClient } from '@/lib/supabase/server'
import { NextRequest, NextResponse } from 'next/server'
export async function GET(request: NextRequest) {
const requestUrl = new URL(request.url)
const code = requestUrl.searchParams.get('code')
if (code) {
const supabase = createClient()
await supabase.auth.exchangeCodeForSession(code)
}
// Redirect to dashboard or wherever
return NextResponse.redirect(new URL('/dashboard', request.url))
}
Protected Routes
// middleware.ts
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
let response = NextResponse.next({
request: {
headers: request.headers,
},
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return request.cookies.get(name)?.value
},
set(name: string, value: string, options: CookieOptions) {
request.cookies.set({
name,
value,
...options,
})
response = NextResponse.next({
request: {
headers: request.headers,
},
})
response.cookies.set({
name,
value,
...options,
})
},
remove(name: string, options: CookieOptions) {
request.cookies.set({
name,
value: '',
...options,
})
response = NextResponse.next({
request: {
headers: request.headers,
},
})
response.cookies.set({
name,
value: '',
...options,
})
},
},
}
)
const { data: { user } } = await supabase.auth.getUser()
// Protect dashboard routes
if (request.nextUrl.pathname.startsWith('/dashboard') && !user) {
return NextResponse.redirect(new URL('/login', request.url))
}
// Redirect authenticated users away from auth pages
if (request.nextUrl.pathname.startsWith('/login') && user) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
return response
}
export const config = {
matcher: ['/dashboard/:path*', '/login', '/signup'],
}
Advanced Row Level Security
Complex RLS Policies
-- Users can only see published posts or their own drafts
CREATE POLICY "Users can read appropriate posts"
ON posts FOR SELECT
USING (
published = true
OR
auth.uid() = user_id
);
-- Users can update only their own posts
CREATE POLICY "Users can update own posts"
ON posts FOR UPDATE
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);
-- Team-based access
CREATE TABLE teams (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name TEXT NOT NULL
);
CREATE TABLE team_members (
team_id UUID REFERENCES teams,
user_id UUID REFERENCES auth.users,
role TEXT CHECK (role IN ('owner', 'admin', 'member')),
PRIMARY KEY (team_id, user_id)
);
CREATE TABLE team_documents (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
team_id UUID REFERENCES teams,
title TEXT,
content TEXT
);
-- Only team members can see team documents
CREATE POLICY "Team members can view documents"
ON team_documents FOR SELECT
USING (
team_id IN (
SELECT team_id
FROM team_members
WHERE user_id = auth.uid()
)
);
-- Only team owners/admins can delete
CREATE POLICY "Team admins can delete documents"
ON team_documents FOR DELETE
USING (
team_id IN (
SELECT team_id
FROM team_members
WHERE user_id = auth.uid()
AND role IN ('owner', 'admin')
)
);
Function-Based RLS
-- Create helper function
CREATE OR REPLACE FUNCTION is_team_admin(team_id UUID)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1
FROM team_members
WHERE team_members.team_id = is_team_admin.team_id
AND team_members.user_id = auth.uid()
AND team_members.role IN ('owner', 'admin')
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Use in policy
CREATE POLICY "Admins can update team settings"
ON teams FOR UPDATE
USING (is_team_admin(id))
WITH CHECK (is_team_admin(id));
RLS with JWT Claims
-- Access custom JWT claims
CREATE POLICY "Premium users can view premium content"
ON premium_content FOR SELECT
USING (
(auth.jwt() -> 'user_metadata' ->> 'subscription_tier') = 'premium'
);
-- Role-based access
CREATE POLICY "Admins have full access"
ON sensitive_data FOR ALL
USING (
(auth.jwt() -> 'user_metadata' ->> 'role') = 'admin'
);
Advanced Real-time Features
Presence (Who's Online)
'use client'
import { useEffect, useState } from 'react'
import { createClient } from '@/lib/supabase/client'
export function OnlineUsers() {
const [onlineUsers, setOnlineUsers] = useState<any[]>([])
const supabase = createClient()
useEffect(() => {
const channel = supabase.channel('online-users')
channel
.on('presence', { event: 'sync' }, () => {
const state = channel.presenceState()
const users = Object.values(state).flat()
setOnlineUsers(users)
})
.on('presence', { event: 'join' }, ({ newPresences }) => {
console.log('Users joined:', newPresences)
})
.on('presence', { event: 'leave' }, ({ leftPresences }) => {
console.log('Users left:', leftPresences)
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
// Track this user
const { data: { user } } = await supabase.auth.getUser()
if (user) {
await channel.track({
user_id: user.id,
email: user.email,
online_at: new Date().toISOString(),
})
}
}
})
return () => {
supabase.removeChannel(channel)
}
}, [])
return (
<div>
<h3>{onlineUsers.length} users online</h3>
<ul>
{onlineUsers.map((user, i) => (
<li key={i}>{user.email}</li>
))}
</ul>
</div>
)
}
Broadcast (Send Messages)
// Cursor tracking
export function CollaborativeCanvas() {
const supabase = createClient()
useEffect(() => {
const channel = supabase.channel('canvas')
channel
.on('broadcast', { event: 'cursor' }, (payload) => {
// Update cursor position
updateCursor(payload.payload)
})
.subscribe()
// Send cursor position
const handleMouseMove = (e: MouseEvent) => {
channel.send({
type: 'broadcast',
event: 'cursor',
payload: { x: e.clientX, y: e.clientY },
})
}
window.addEventListener('mousemove', handleMouseMove)
return () => {
window.removeEventListener('mousemove', handleMouseMove)
supabase.removeChannel(channel)
}
}, [])
return <canvas />
}
Postgres Changes (Database Events)
// Listen to specific columns
const channel = supabase
.channel('post-changes')
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'posts',
filter: 'id=eq.123', // Specific row
},
(payload) => {
console.log('Post updated:', payload)
}
)
.subscribe()
// Listen to multiple tables
const channel = supabase
.channel('changes')
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'posts' },
handlePostChange
)
.on(
'postgres_changes',
{ event: '*', schema: 'public', table: 'comments' },
handleCommentChange
)
.subscribe()
Advanced Storage
Image Transformations
// Upload with transformation
export async function uploadAvatar(file: File, userId: string) {
const supabase = createClient()
const fileExt = file.name.split('.').pop()
const fileName = `${userId}-${Date.now()}.${fileExt}`
const filePath = `avatars/${fileName}`
const { error: uploadError } = await supabase.storage
.from('avatars')
.upload(filePath, file, {
cacheControl: '3600',
upsert: false,
})
if (uploadError) throw uploadError
// Get transformed image URL
const { data } = supabase.storage
.from('avatars')
.getPublicUrl(filePath, {
transform: {
width: 200,
height: 200,
resize: 'cover',
quality: 80,
},
})
return data.publicUrl
}
Signed URLs (Private Files)
// Generate signed URL (expires after 1 hour)
export async function getPrivateFileUrl(path: string) {
const supabase = createClient()
const { data, error } = await supabase.storage
.from('private-files')
.createSignedUrl(path, 3600) // 1 hour
if (error) throw error
return data.signedUrl
}
// Upload to private bucket
export async function uploadPrivateFile(file: File, userId: string) {
const supabase = createClient()
const filePath = `${userId}/${file.name}`
const { error } = await supabase.storage
.from('private-files')
.upload(filePath, file)
if (error) throw error
return filePath
}
Storage RLS
-- Enable RLS on storage.objects
CREATE POLICY "Users can upload to their own folder"
ON storage.objects FOR INSERT
WITH CHECK (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Users can view their own files"
ON storage.objects FOR SELECT
USING (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Users can update their own files"
ON storage.objects FOR UPDATE
USING (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
CREATE POLICY "Users can delete their own files"
ON storage.objects FOR DELETE
USING (
bucket_id = 'avatars' AND
(storage.foldername(name))[1] = auth.uid()::text
);
Edge Functions
Basic Edge Function
// supabase/functions/hello/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
serve(async (req) => {
const { name } = await req.json()
return new Response(
JSON.stringify({ message: `Hello ${name}!` }),
{
headers: { 'Content-Type': 'application/json' },
},
)
})
Edge Function with Supabase Client
// supabase/functions/create-post/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
serve(async (req) => {
try {
const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
{
global: {
headers: { Authorization: req.headers.get('Authorization')! },
},
}
)
// Get authenticated user
const { data: { user }, error: userError } = await supabaseClient.auth.getUser()
if (userError || !user) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
})
}
const { title, content } = await req.json()
const { data, error } = await supabaseClient
.from('posts')
.insert({
title,
content,
user_id: user.id,
})
.select()
.single()
if (error) throw error
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
})
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
})
}
})
Scheduled Edge Function (Cron)
// supabase/functions/cleanup-old-data/index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
serve(async (req) => {
// Verify request is from Supabase Cron
const authHeader = req.headers.get('Authorization')
if (authHeader !== `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`) {
return new Response('Unauthorized', { status: 401 })
}
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
)
// Delete old data
const thirtyDaysAgo = new Date()
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
const { error } = await supabase
.from('temporary_data')
.delete()
.lt('created_at', thirtyDaysAgo.toISOString())
if (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
})
}
return new Response(JSON.stringify({ success: true }))
})
// Configure in Dashboard: Database > Cron Jobs
// Schedule: 0 2 * * * (2am daily)
// HTTP Request: https://your-project.supabase.co/functions/v1/cleanup-old-data
Invoke Edge Function from Client
// Client-side
const { data, error } = await supabase.functions.invoke('hello', {
body: { name: 'World' },
})
// With auth headers automatically included
const { data: { session } } = await supabase.auth.getSession()
const { data, error } = await supabase.functions.invoke('create-post', {
body: {
title: 'My Post',
content: 'Content here',
},
headers: {
Authorization: `Bearer ${session?.access_token}`,
},
})
Vector Search (AI/RAG)
Enable pgvector
-- Enable vector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create table with embedding column
CREATE TABLE documents (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
content TEXT NOT NULL,
metadata JSONB,
embedding vector(1536), -- For OpenAI ada-002 (1536 dimensions)
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Create index for fast similarity search
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
-- Or use HNSW for better performance (Postgres 15+)
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
Generate and Store Embeddings
// lib/embeddings.ts
import { OpenAI } from 'openai'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY!,
})
export async function generateEmbedding(text: string): Promise<number[]> {
const response = await openai.embeddings.create({
model: 'text-embedding-ada-002',
input: text,
})
return response.data[0].embedding
}
// Store document with embedding
export async function storeDocument(content: string, metadata: any) {
const supabase = createClient()
const embedding = await generateEmbedding(content)
const { data, error } = await supabase
.from('documents')
.insert({
content,
metadata,
embedding,
})
.select()
.single()
if (error) throw error
return data
}
Semantic Search
// Search similar documents
export async function searchSimilarDocuments(query: string, limit = 5) {
const supabase = createClient()
// Generate embedding for query
const queryEmbedding = await generateEmbedding(query)
// Search with RPC function
const { data, error } = await supabase.rpc('match_documents', {
query_embedding: queryEmbedding,
match_threshold: 0.78, // Minimum similarity
match_count: limit,
})
if (error) throw error
return data
}
// Create the RPC function
CREATE OR REPLACE FUNCTION match_documents (
query_embedding vector(1536),
match_threshold float,
match_count int
)
RETURNS TABLE (
id UUID,
content TEXT,
metadata JSONB,
similarity float
)
LANGUAGE SQL STABLE
AS $$
SELECT
documents.id,
documents.content,
documents.metadata,
1 - (documents.embedding <=> query_embedding) AS similarity
FROM documents
WHERE 1 - (documents.embedding <=> query_embedding) > match_threshold
ORDER BY documents.embedding <=> query_embedding
LIMIT match_count;
$$;
RAG (Retrieval Augmented Generation)
export async function ragQuery(question: string) {
// 1. Search for relevant documents
const relevantDocs = await searchSimilarDocuments(question, 5)
// 2. Build context from relevant documents
const context = relevantDocs
.map(doc => doc.content)
.join('\n\n')
// 3. Generate answer with GPT
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'system',
content: 'You are a helpful assistant. Answer questions based on the provided context.',
},
{
role: 'user',
content: `Context:\n${context}\n\nQuestion: ${question}`,
},
],
})
return {
answer: completion.choices[0].message.content,
sources: relevantDocs,
}
}
Database Functions & Triggers
Custom Functions
-- Get user's post count
CREATE OR REPLACE FUNCTION get_user_post_count(user_id UUID)
RETURNS INTEGER AS $$
SELECT COUNT(*)::INTEGER
FROM posts
WHERE posts.user_id = get_user_post_count.user_id;
$$ LANGUAGE SQL STABLE;
-- Call from TypeScript
const { data, error } = await supabase.rpc('get_user_post_count', {
user_id: userId,
})
Triggers
-- Auto-update updated_at column
CREATE OR REPLACE FUNCTION handle_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION handle_updated_at();
-- Update post count when post is created/deleted
CREATE OR REPLACE FUNCTION update_post_count()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
UPDATE profiles
SET post_count = post_count + 1
WHERE id = NEW.user_id;
RETURN NEW;
ELSIF TG_OP = 'DELETE' THEN
UPDATE profiles
SET post_count = post_count - 1
WHERE id = OLD.user_id;
RETURN OLD;
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_post_count_trigger
AFTER INSERT OR DELETE ON posts
FOR EACH ROW
EXECUTE FUNCTION update_post_count();
Performance Optimization
Query Optimization
// Bad: N+1 query problem
const { data: posts } = await supabase.from('posts').select('*')
for (const post of posts) {
const { data: author } = await supabase
.from('profiles')
.select('*')
.eq('id', post.user_id)
.single()
}
// Good: Join in single query
const { data: posts } = await supabase
.from('posts')
.select(`
*,
profiles (
id,
name,
avatar_url
)
`)
// Good: Use specific columns
const { data: posts } = await supabase
.from('posts')
.select('id, title, created_at, profiles(name)') // Only what you need
.eq('published', true)
.order('created_at', { ascending: false })
.limit(20)
Indexes
-- Index on frequently filtered columns
CREATE INDEX posts_user_id_idx ON posts(user_id);
CREATE INDEX posts_created_at_idx ON posts(created_at DESC);
-- Partial index (filtered)
CREATE INDEX posts_published_idx ON posts(published)
WHERE published = true;
-- Composite index
CREATE INDEX posts_user_published_idx ON posts(user_id, published, created_at DESC);
-- Full-text search index
CREATE INDEX posts_content_idx ON posts
USING GIN (to_tsvector('english', content));
Connection Pooling
// Use connection pooler for serverless (Supavisor)
// Connection string: postgresql://postgres.[project-ref]:[password]@aws-0-us-east-1.pooler.supabase.com:6543/postgres
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!,
{
db: {
schema: 'public',
},
global: {
headers: { 'x-my-custom-header': 'my-app-name' },
},
}
)
Caching
// Next.js cache with revalidation
import { unstable_cache } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
export const getCachedPosts = unstable_cache(
async () => {
const supabase = createClient()
const { data } = await supabase
.from('posts')
.select('*')
.eq('published', true)
return data
},
['posts'],
{
revalidate: 300, // 5 minutes
tags: ['posts'],
}
)
// Revalidate on mutation
import { revalidateTag } from 'next/cache'
export async function createPost(data: any) {
const supabase = createClient()
await supabase.from('posts').insert(data)
revalidateTag('posts')
}
Local Development
Setup Local Supabase
# Install Supabase CLI
brew install supabase/tap/supabase
# Initialize project
supabase init
# Start local Supabase (Docker required)
supabase start
# This starts:
# - PostgreSQL
# - GoTrue (Auth)
# - Realtime
# - Storage
# - Kong (API Gateway)
# - Studio (Dashboard)
Local Development URLs
# After supabase start:
API URL: http://localhost:54321
Studio URL: http://localhost:54323
Inbucket URL: http://localhost:54324 # Email testing
Migration Workflow
# Create migration
supabase migration new add_posts_table
# Edit migration file in supabase/migrations/
# Apply migration locally
supabase db reset
# Push to production
supabase db push
# Pull remote schema
supabase db pull
Generate Types from Local DB
# Generate TypeScript types
supabase gen types typescript --local > types/database.ts
Testing
Testing RLS Policies
-- Test as specific user
SET LOCAL ROLE authenticated;
SET LOCAL "request.jwt.claims" TO '{"sub": "user-uuid-here"}';
-- Test query
SELECT * FROM posts;
-- Reset
RESET ROLE;
Testing with Supabase Test Helpers
// tests/posts.test.ts
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY! // For testing
)
describe('Posts', () => {
beforeEach(async () => {
// Clean up
await supabase.from('posts').delete().neq('id', '00000000-0000-0000-0000-000000000000')
})
it('should create post', async () => {
const { data, error } = await supabase
.from('posts')
.insert({ title: 'Test', content: 'Test' })
.select()
.single()
expect(error).toBeNull()
expect(data.title).toBe('Test')
})
})
Error Handling
Comprehensive Error Handler
import { PostgrestError } from '@supabase/supabase-js'
export function handleSupabaseError(error: PostgrestError | null) {
if (!error) return null
// Common error codes
const errorMessages: Record<string, string> = {
'23505': 'This record already exists', // Unique violation
'23503': 'Related record not found', // Foreign key violation
'42P01': 'Table does not exist',
'42501': 'Permission denied',
'PGRST116': 'No rows found',
}
const userMessage = errorMessages[error.code] || error.message
console.error('Supabase error:', {
code: error.code,
message: error.message,
details: error.details,
hint: error.hint,
})
return userMessage
}
// Usage
const { data, error } = await supabase.from('posts').insert(postData)
if (error) {
const message = handleSupabaseError(error)
toast.error(message)
return
}
Best Practices
-
Row Level Security:
- Enable RLS on ALL tables
- Never rely on client-side checks alone
- Test policies thoroughly
- Use service role key sparingly (server-side only)
-
Query Optimization:
- Use
.select()to specify needed columns - Add database indexes for filtered/sorted columns
- Use
.limit()to cap results - Consider pagination for large datasets
- Use
-
Real-time Subscriptions:
- Always unsubscribe when component unmounts
- Use RLS policies to filter events
- Use broadcast for ephemeral data
- Limit number of simultaneous subscriptions
-
Authentication:
- Store JWT in httpOnly cookies when possible
- Refresh tokens before expiry
- Handle auth state changes
- Validate user on server-side
-
Storage:
- Set appropriate bucket policies
- Use image transformations for optimization
- Consider storage limits
- Clean up unused files
-
Error Handling:
- Always check
errorobject - Provide user-friendly error messages
- Log errors for debugging
- Handle network failures gracefully
- Always check
Common Patterns
Auto-create Profile on Signup
-- Create profiles table
CREATE TABLE profiles (
id UUID REFERENCES auth.users PRIMARY KEY,
name TEXT,
avatar_url TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Trigger function
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.profiles (id, name, avatar_url)
VALUES (
NEW.id,
NEW.raw_user_meta_data->>'name',
NEW.raw_user_meta_data->>'avatar_url'
);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- Trigger
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
Documentation Quick Reference
Need to find something specific?
Search the 2,616 documentation files:
# Search all docs
grep -r "search term" docs/supabase_com/
# Find guides
ls docs/supabase_com/guides_*
# Find API reference
ls docs/supabase_com/reference_*
Common doc locations:
- Guides:
docs/supabase_com/guides_* - JavaScript Reference:
docs/supabase_com/reference_javascript_* - Database:
docs/supabase_com/guides_database_* - Auth:
docs/supabase_com/guides_auth_* - Storage:
docs/supabase_com/guides_storage_*
Resources
- Dashboard: https://supabase.com/dashboard
- Docs: https://supabase.com/docs
- Status: https://status.supabase.com
- CLI Docs: https://supabase.com/docs/guides/cli
Implementation Checklist
- Create Supabase project
- Install:
npm install @supabase/supabase-js - Set environment variables
- Design database schema
- Create migrations
- Enable RLS and create policies
- Set up authentication
- Implement auth state management
- Create CRUD operations
- Add real-time subscriptions (if needed)
- Configure storage buckets (if needed)
- Test RLS policies
- Add database indexes
- Deploy edge functions (if needed)
- Test in production
Finishing a Development Branch
Overview
Guide completion of development work by presenting clear options and handling chosen workflow.
Core principle: Verify tests → Present options → Execute choice → Clean up.
Announce at start: "I'm using the finishing-a-development-branch skill to complete this work."
The Process
Step 1: Verify Tests
Before presenting options, verify tests pass:
# Run project's test suite
npm test / cargo test / pytest / go test ./...
If tests fail:
Tests failing (<N> failures). Must fix before completing:
[Show failures]
Cannot proceed with merge/PR until tests pass.
Stop. Don't proceed to Step 2.
If tests pass: Continue to Step 2.
Step 2: Determine Base Branch
# Try common base branches
git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
Or ask: "This branch split from main - is that correct?"
Step 3: Present Options
Present exactly these 4 options:
Implementation complete. What would you like to do?
1. Merge back to <base-branch> locally
2. Push and create a Pull Request
3. Keep the branch as-is (I'll handle it later)
4. Discard this work
Which option?
Don't add explanation - keep options concise.
Step 4: Execute Choice
Option 1: Merge Locally
# Switch to base branch
git checkout <base-branch>
# Pull latest
git pull
# Merge feature branch
git merge <feature-branch>
# Verify tests on merged result
<test command>
# If tests pass
git branch -d <feature-branch>
Then: Cleanup worktree (Step 5)
Option 2: Push and Create PR
# Push branch
git push -u origin <feature-branch>
# Create PR
gh pr create --title "<title>" --body "$(cat <<'EOF'
## Summary
<2-3 bullets of what changed>
## Test Plan
- [ ] <verification steps>
EOF
)"
Then: Cleanup worktree (Step 5)
Option 3: Keep As-Is
Report: "Keeping branch . Worktree preserved at ."
Don't cleanup worktree.
Option 4: Discard
Confirm first:
This will permanently delete:
- Branch <name>
- All commits: <commit-list>
- Worktree at <path>
Type 'discard' to confirm.
Wait for exact confirmation.
If confirmed:
git checkout <base-branch>
git branch -D <feature-branch>
Then: Cleanup worktree (Step 5)
Step 5: Cleanup Worktree
For Options 1, 2, 4:
Check if in worktree:
git worktree list | grep $(git branch --show-current)
If yes:
git worktree remove <worktree-path>
For Option 3: Keep worktree.
Quick Reference
| Option | Merge | Push | Keep Worktree | Cleanup Branch |
|---|---|---|---|---|
| 1. Merge locally | ✓ | - | - | ✓ |
| 2. Create PR | - | ✓ | ✓ | - |
| 3. Keep as-is | - | - | ✓ | - |
| 4. Discard | - | - | - | ✓ (force) |
Common Mistakes
Skipping test verification
- Problem: Merge broken code, create failing PR
- Fix: Always verify tests before offering options
Open-ended questions
- Problem: "What should I do next?" → ambiguous
- Fix: Present exactly 4 structured options
Automatic worktree cleanup
- Problem: Remove worktree when might need it (Option 2, 3)
- Fix: Only cleanup for Options 1 and 4
No confirmation for discard
- Problem: Accidentally delete work
- Fix: Require typed "discard" confirmation
Red Flags
Never:
- Proceed with failing tests
- Merge without verifying tests on result
- Delete work without confirmation
- Force-push without explicit request
Always:
- Verify tests before offering options
- Present exactly 4 options
- Get typed confirmation for Option 4
- Clean up worktree for Options 1 & 4 only
Integration
Called by:
- subagent-driven-development (Step 7) - After all tasks complete
- executing-plans (Step 5) - After all batches complete
Pairs with:
- using-git-worktrees - Cleans up worktree created by that skill
IMPORTANT - Path Resolution:
This skill can be installed in different locations (plugin system, manual installation, global, or project-specific). Before executing any commands, determine the skill directory based on where you loaded this SKILL.md file, and use that path in all commands below. Replace $SKILL_DIR with the actual discovered path.
Common installation paths:
- Plugin system:
~/.claude/plugins/marketplaces/playwright-skill/skills/playwright-skill - Manual global:
~/.claude/skills/playwright-skill - Project-specific:
<project>/.claude/skills/playwright-skill
Playwright Browser Automation
General-purpose browser automation skill. I'll write custom Playwright code for any automation task you request and execute it via the universal executor.
CRITICAL WORKFLOW - Follow these steps in order:
-
Auto-detect dev servers - For localhost testing, ALWAYS run server detection FIRST:
cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(servers => console.log(JSON.stringify(servers)))"- If 1 server found: Use it automatically, inform user
- If multiple servers found: Ask user which one to test
- If no servers found: Ask for URL or offer to help start dev server
-
Write scripts to /tmp - NEVER write test files to skill directory; always use
/tmp/playwright-test-*.js -
Use visible browser by default - Always use
headless: falseunless user specifically requests headless mode -
Parameterize URLs - Always make URLs configurable via environment variable or constant at top of script
How It Works
- You describe what you want to test/automate
- I auto-detect running dev servers (or ask for URL if testing external site)
- I write custom Playwright code in
/tmp/playwright-test-*.js(won't clutter your project) - I execute it via:
cd $SKILL_DIR && node run.js /tmp/playwright-test-*.js - Results displayed in real-time, browser window visible for debugging
- Test files auto-cleaned from /tmp by your OS
Setup (First Time)
cd $SKILL_DIR
npm run setup
This installs Playwright and Chromium browser. Only needed once.
Execution Pattern
Step 1: Detect dev servers (for localhost testing)
cd $SKILL_DIR && node -e "require('./lib/helpers').detectDevServers().then(s => console.log(JSON.stringify(s)))"
Step 2: Write test script to /tmp with URL parameter
// /tmp/playwright-test-page.js
const { chromium } = require('playwright');
// Parameterized URL (detected or user-provided)
const TARGET_URL = 'http://localhost:3001'; // <-- Auto-detected or from user
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto(TARGET_URL);
console.log('Page loaded:', await page.title());
await page.screenshot({ path: '/tmp/screenshot.png', fullPage: true });
console.log('📸 Screenshot saved to /tmp/screenshot.png');
await browser.close();
})();
Step 3: Execute from skill directory
cd $SKILL_DIR && node run.js /tmp/playwright-test-page.js
Common Patterns
Test a Page (Multiple Viewports)
// /tmp/playwright-test-responsive.js
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3001'; // Auto-detected
(async () => {
const browser = await chromium.launch({ headless: false, slowMo: 100 });
const page = await browser.newPage();
// Desktop test
await page.setViewportSize({ width: 1920, height: 1080 });
await page.goto(TARGET_URL);
console.log('Desktop - Title:', await page.title());
await page.screenshot({ path: '/tmp/desktop.png', fullPage: true });
// Mobile test
await page.setViewportSize({ width: 375, height: 667 });
await page.screenshot({ path: '/tmp/mobile.png', fullPage: true });
await browser.close();
})();
Test Login Flow
// /tmp/playwright-test-login.js
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3001'; // Auto-detected
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto(`${TARGET_URL}/login`);
await page.fill('input[name="email"]', 'test@example.com');
await page.fill('input[name="password"]', 'password123');
await page.click('button[type="submit"]');
// Wait for redirect
await page.waitForURL('**/dashboard');
console.log('✅ Login successful, redirected to dashboard');
await browser.close();
})();
Fill and Submit Form
// /tmp/playwright-test-form.js
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3001'; // Auto-detected
(async () => {
const browser = await chromium.launch({ headless: false, slowMo: 50 });
const page = await browser.newPage();
await page.goto(`${TARGET_URL}/contact`);
await page.fill('input[name="name"]', 'John Doe');
await page.fill('input[name="email"]', 'john@example.com');
await page.fill('textarea[name="message"]', 'Test message');
await page.click('button[type="submit"]');
// Verify submission
await page.waitForSelector('.success-message');
console.log('✅ Form submitted successfully');
await browser.close();
})();
Check for Broken Links
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('http://localhost:3000');
const links = await page.locator('a[href^="http"]').all();
const results = { working: 0, broken: [] };
for (const link of links) {
const href = await link.getAttribute('href');
try {
const response = await page.request.head(href);
if (response.ok()) {
results.working++;
} else {
results.broken.push({ url: href, status: response.status() });
}
} catch (e) {
results.broken.push({ url: href, error: e.message });
}
}
console.log(`✅ Working links: ${results.working}`);
console.log(`❌ Broken links:`, results.broken);
await browser.close();
})();
Take Screenshot with Error Handling
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
try {
await page.goto('http://localhost:3000', {
waitUntil: 'networkidle',
timeout: 10000
});
await page.screenshot({
path: '/tmp/screenshot.png',
fullPage: true
});
console.log('📸 Screenshot saved to /tmp/screenshot.png');
} catch (error) {
console.error('❌ Error:', error.message);
} finally {
await browser.close();
}
})();
Test Responsive Design
// /tmp/playwright-test-responsive-full.js
const { chromium } = require('playwright');
const TARGET_URL = 'http://localhost:3001'; // Auto-detected
(async () => {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
const viewports = [
{ name: 'Desktop', width: 1920, height: 1080 },
{ name: 'Tablet', width: 768, height: 1024 },
{ name: 'Mobile', width: 375, height: 667 }
];
for (const viewport of viewports) {
console.log(`Testing ${viewport.name} (${viewport.width}x${viewport.height})`);
await page.setViewportSize({
width: viewport.width,
height: viewport.height
});
await page.goto(TARGET_URL);
await page.waitForTimeout(1000);
await page.screenshot({
path: `/tmp/${viewport.name.toLowerCase()}.png`,
fullPage: true
});
}
console.log('✅ All viewports tested');
await browser.close();
})();
Inline Execution (Simple Tasks)
For quick one-off tasks, you can execute code inline without creating files:
# Take a quick screenshot
cd $SKILL_DIR && node run.js "
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
await page.goto('http://localhost:3001');
await page.screenshot({ path: '/tmp/quick-screenshot.png', fullPage: true });
console.log('Screenshot saved');
await browser.close();
"
When to use inline vs files:
- Inline: Quick one-off tasks (screenshot, check if element exists, get page title)
- Files: Complex tests, responsive design checks, anything user might want to re-run
Available Helpers
Optional utility functions in lib/helpers.js:
const helpers = require('./lib/helpers');
// Detect running dev servers (CRITICAL - use this first!)
const servers = await helpers.detectDevServers();
console.log('Found servers:', servers);
// Safe click with retry
await helpers.safeClick(page, 'button.submit', { retries: 3 });
// Safe type with clear
await helpers.safeType(page, '#username', 'testuser');
// Take timestamped screenshot
await helpers.takeScreenshot(page, 'test-result');
// Handle cookie banners
await helpers.handleCookieBanner(page);
// Extract table data
const data = await helpers.extractTableData(page, 'table.results');
See lib/helpers.js for full list.
Custom HTTP Headers
Configure custom headers for all HTTP requests via environment variables. Useful for:
- Identifying automated traffic to your backend
- Getting LLM-optimized responses (e.g., plain text errors instead of styled HTML)
- Adding authentication tokens globally
Configuration
Single header (common case):
PW_HEADER_NAME=X-Automated-By PW_HEADER_VALUE=playwright-skill \
cd $SKILL_DIR && node run.js /tmp/my-script.js
Multiple headers (JSON format):
PW_EXTRA_HEADERS='{"X-Automated-By":"playwright-skill","X-Debug":"true"}' \
cd $SKILL_DIR && node run.js /tmp/my-script.js
How It Works
Headers are automatically applied when using helpers.createContext():
const context = await helpers.createContext(browser);
const page = await context.newPage();
// All requests from this page include your custom headers
For scripts using raw Playwright API, use the injected getContextOptionsWithHeaders():
const context = await browser.newContext(
getContextOptionsWithHeaders({ viewport: { width: 1920, height: 1080 } })
);
Advanced Usage
For comprehensive Playwright API documentation, see API_REFERENCE.md:
- Selectors & Locators best practices
- Network interception & API mocking
- Authentication & session management
- Visual regression testing
- Mobile device emulation
- Performance testing
- Debugging techniques
- CI/CD integration
Tips
- CRITICAL: Detect servers FIRST - Always run
detectDevServers()before writing test code for localhost testing - Custom headers - Use
PW_HEADER_NAME/PW_HEADER_VALUEenv vars to identify automated traffic to your backend - Use /tmp for test files - Write to
/tmp/playwright-test-*.js, never to skill directory or user's project - Parameterize URLs - Put detected/provided URL in a
TARGET_URLconstant at the top of every script - DEFAULT: Visible browser - Always use
headless: falseunless user explicitly asks for headless mode - Headless mode - Only use
headless: truewhen user specifically requests "headless" or "background" execution - Slow down: Use
slowMo: 100to make actions visible and easier to follow - Wait strategies: Use
waitForURL,waitForSelector,waitForLoadStateinstead of fixed timeouts - Error handling: Always use try-catch for robust automation
- Console output: Use
console.log()to track progress and show what's happening
Troubleshooting
Playwright not installed:
cd $SKILL_DIR && npm run setup
Module not found:
Ensure running from skill directory via run.js wrapper
Browser doesn't open:
Check headless: false and ensure display available
Element not found:
Add wait: await page.waitForSelector('.element', { timeout: 10000 })
Example Usage
User: "Test if the marketing page looks good"
Claude: I'll test the marketing page across multiple viewports. Let me first detect running servers...
[Runs: detectDevServers()]
[Output: Found server on port 3001]
I found your dev server running on http://localhost:3001
[Writes custom automation script to /tmp/playwright-test-marketing.js with URL parameterized]
[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-marketing.js]
[Shows results with screenshots from /tmp/]
User: "Check if login redirects correctly"
Claude: I'll test the login flow. First, let me check for running servers...
[Runs: detectDevServers()]
[Output: Found servers on ports 3000 and 3001]
I found 2 dev servers. Which one should I test?
- http://localhost:3000
- http://localhost:3001
User: "Use 3001"
[Writes login automation to /tmp/playwright-test-login.js]
[Runs: cd $SKILL_DIR && node run.js /tmp/playwright-test-login.js]
[Reports: ✅ Login successful, redirected to /dashboard]
Notes
- Each automation is custom-written for your specific request
- Not limited to pre-built scripts - any browser task possible
- Auto-detects running dev servers to eliminate hardcoded URLs
- Test scripts written to
/tmpfor automatic cleanup (no clutter) - Code executes reliably with proper module resolution via
run.js - Progressive disclosure - API_REFERENCE.md loaded only when advanced features needed
IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.
This is not negotiable. This is not optional. You cannot rationalize your way out of this.
How to Access Skills
In Claude Code: Use the Skill tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.
In other environments: Check your platform's documentation for how skills are loaded.
Using Skills
The Rule
Check for skills BEFORE ANY RESPONSE. This includes clarifying questions. Even 1% chance means invoke the Skill tool first.
digraph skill_flow {
"User message received" [shape=doublecircle];
"Might any skill apply?" [shape=diamond];
"Invoke Skill tool" [shape=box];
"Announce: 'Using [skill] to [purpose]'" [shape=box];
"Has checklist?" [shape=diamond];
"Create TodoWrite todo per item" [shape=box];
"Follow skill exactly" [shape=box];
"Respond (including clarifications)" [shape=doublecircle];
"User message received" -> "Might any skill apply?";
"Might any skill apply?" -> "Invoke Skill tool" [label="yes, even 1%"];
"Might any skill apply?" -> "Respond (including clarifications)" [label="definitely not"];
"Invoke Skill tool" -> "Announce: 'Using [skill] to [purpose]'";
"Announce: 'Using [skill] to [purpose]'" -> "Has checklist?";
"Has checklist?" -> "Create TodoWrite todo per item" [label="yes"];
"Has checklist?" -> "Follow skill exactly" [label="no"];
"Create TodoWrite todo per item" -> "Follow skill exactly";
}
Red Flags
These thoughts mean STOP—you're rationalizing:
| Thought | Reality |
|---|---|
| "This is just a simple question" | Questions are tasks. Check for skills. |
| "I need more context first" | Skill check comes BEFORE clarifying questions. |
| "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. |
| "I can check git/files quickly" | Files lack conversation context. Check for skills. |
| "Let me gather information first" | Skills tell you HOW to gather information. |
| "This doesn't need a formal skill" | If a skill exists, use it. |
| "I remember this skill" | Skills evolve. Read current version. |
| "This doesn't count as a task" | Action = task. Check for skills. |
| "The skill is overkill" | Simple things become complex. Use it. |
| "I'll just do this one thing first" | Check BEFORE doing anything. |
| "This feels productive" | Undisciplined action wastes time. Skills prevent this. |
Skill Priority
When multiple skills could apply, use this order:
- Process skills first (brainstorming, debugging) - these determine HOW to approach the task
- Implementation skills second (frontend-design, mcp-builder) - these guide execution
"Let's build X" → brainstorming first, then implementation skills. "Fix this bug" → debugging first, then domain-specific skills.
Skill Types
Rigid (TDD, debugging): Follow exactly. Don't adapt away discipline.
Flexible (patterns): Adapt principles to context.
The skill itself tells you which.
User Instructions
Instructions say WHAT, not HOW. "Add X" or "Fix Y" doesn't mean skip workflows.
Skill Creator
This skill provides guidance for creating effective skills.
About Skills
Skills are modular, self-contained packages that extend Claude's capabilities by providing specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains or tasks—they transform Claude from a general-purpose agent into a specialized agent equipped with procedural knowledge that no model can fully possess.
What Skills Provide
- Specialized workflows - Multi-step procedures for specific domains
- Tool integrations - Instructions for working with specific file formats or APIs
- Domain expertise - Company-specific knowledge, schemas, business logic
- Bundled resources - Scripts, references, and assets for complex and repetitive tasks
Core Principles
Concise is Key
The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user 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?" and "Does this paragraph justify its token cost?"
Prefer concise examples over verbose explanations.
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, or heuristics guide the approach.
Medium freedom (pseudocode or scripts with parameters): Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
Low freedom (specific scripts, few parameters): Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
Anatomy of a Skill
Every skill consists of a required SKILL.md file and optional bundled resources:
skill-name/
├── SKILL.md (required)
│ ├── YAML frontmatter metadata (required)
│ │ ├── name: (required)
│ │ └── description: (required)
│ └── Markdown instructions (required)
└── Bundled Resources (optional)
├── scripts/ - Executable code (Python/Bash/etc.)
├── references/ - Documentation intended to be loaded into context as needed
└── assets/ - Files used in output (templates, icons, fonts, etc.)
SKILL.md (required)
Every SKILL.md consists of:
- Frontmatter (YAML): Contains
nameanddescriptionfields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used. Prefer third-person descriptions (e.g., "This skill should be used when..."). - Body (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
Bundled Resources (optional)
Scripts (scripts/)
Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
- When to include: When the same code is being rewritten repeatedly or deterministic reliability is needed
- Example:
scripts/rotate_pdf.pyfor PDF rotation tasks - Benefits: Token efficient, deterministic, may be executed without loading into context
- Note: Scripts may still need to be read by Claude for patching or environment-specific adjustments
References (references/)
Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
- When to include: For documentation that Claude should reference while working
- Examples:
references/finance.mdfor financial schemas,references/mnda.mdfor company NDA template,references/policies.mdfor company policies,references/api_docs.mdfor API specifications - Use cases: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
- Benefits: Keeps SKILL.md lean, loaded only when Claude determines it's needed
- Best practice: If files are large (>10k words), include grep search patterns in SKILL.md
- Avoid duplication: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
Assets (assets/)
Files not intended to be loaded into context, but rather used within the output Claude produces.
- When to include: When the skill needs files that will be used in the final output
- Examples:
assets/logo.pngfor brand assets,assets/slides.pptxfor PowerPoint templates,assets/frontend-template/for HTML/React boilerplate,assets/font.ttffor typography - Use cases: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
- Benefits: Separates output resources from documentation, enables Claude to use files without loading them into context
What to Not Include in a Skill
A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
- README.md
- INSTALLATION_GUIDE.md
- QUICK_REFERENCE.md
- CHANGELOG.md
- etc.
The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxilary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
Progressive Disclosure Design Principle
Skills use a three-level loading system to manage context efficiently:
- Metadata (name + description) - Always in context (~100 words)
- SKILL.md body - When skill triggers (<5k words)
- Bundled resources - As needed by Claude (Unlimited because scripts can be executed without reading into context window)
Progressive Disclosure Patterns
Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
Key principle: When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
Pattern 1: High-level guide with references
# PDF Processing
## Quick start
Extract text with pdfplumber:
[code example]
## Advanced features
- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
Pattern 2: Domain-specific organization
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)
When a user asks about sales metrics, Claude only reads sales.md.
Similarly, for skills supporting multiple frameworks or variants, organize by variant:
cloud-deploy/
├── SKILL.md (workflow + provider selection)
└── references/
├── aws.md (AWS deployment patterns)
├── gcp.md (GCP deployment patterns)
└── azure.md (Azure deployment patterns)
When the user chooses AWS, Claude only reads aws.md.
Pattern 3: Conditional details
Show basic content, link to advanced content:
# DOCX Processing
## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
## Editing documents
For simple edits, modify the XML directly.
**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)
Claude reads REDLINING.md or OOXML.md only when the user needs those features.
Important guidelines:
- Avoid deeply nested references - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
- Structure longer reference files - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing.
Skill Creation Process
Skill creation involves these steps:
- Understand the skill with concrete examples
- Plan reusable skill contents (scripts, references, assets)
- Initialize the skill (run init_skill.py)
- Edit the skill (implement resources and write SKILL.md)
- Package the skill (run package_skill.py)
- Iterate based on real usage
Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
Step 1: Understanding the Skill with Concrete Examples
Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
For example, when building an image-editor skill, relevant questions include:
- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
- "Can you give some examples of how this skill would be used?"
- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
- "What would a user say that should trigger this skill?"
To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
Conclude this step when there is a clear sense of the functionality the skill should support.
Step 2: Planning the Reusable Skill Contents
To turn concrete examples into an effective skill, analyze each example by:
- Considering how to execute on the example from scratch
- Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
Example: When building a pdf-editor skill to handle queries like "Help me rotate this PDF," the analysis shows:
- Rotating a PDF requires re-writing the same code each time
- A
scripts/rotate_pdf.pyscript would be helpful to store in the skill
Example: When designing a frontend-webapp-builder skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
- Writing a frontend webapp requires the same boilerplate HTML/React each time
- An
assets/hello-world/template containing the boilerplate HTML/React project files would be helpful to store in the skill
Example: When building a big-query skill to handle queries like "How many users have logged in today?" the analysis shows:
- Querying BigQuery requires re-discovering the table schemas and relationships each time
- A
references/schema.mdfile documenting the table schemas would be helpful to store in the skill
To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
Step 3: Initializing the Skill
At this point, it is time to actually create the skill.
Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
When creating a new skill from scratch, always run the init_skill.py script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
Usage:
scripts/init_skill.py <skill-name> --path <output-directory>
The script:
- Creates the skill directory at the specified path
- Generates a SKILL.md template with proper frontmatter and TODO placeholders
- Creates example resource directories:
scripts/,references/, andassets/ - Adds example files in each directory that can be customized or deleted
After initialization, customize or remove the generated SKILL.md and example files as needed.
Step 4: Edit the Skill
When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Include information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
Learn Proven Design Patterns
Consult these helpful guides based on your skill's needs:
- Multi-step processes: See references/workflows.md for sequential workflows and conditional logic
- Specific output formats or quality standards: See references/output-patterns.md for template and example patterns
These files contain established best practices for effective skill design.
Start with Reusable Skill Contents
To begin implementation, start with the reusable resources identified above: scripts/, references/, and assets/ files. Note that this step may require user input. For example, when implementing a brand-guidelines skill, the user may need to provide brand assets or templates to store in assets/, or documentation to store in references/.
Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
Any example files and directories not needed for the skill should be deleted. The initialization script creates example files in scripts/, references/, and assets/ to demonstrate structure, but most skills won't need all of them.
Update SKILL.md
Writing Guidelines: Always use imperative/infinitive form.
Frontmatter
Write the YAML frontmatter with name and description:
name: The skill namedescription: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill.- Include both what the Skill does and specific triggers/contexts for when to use it.
- Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude.
- Example description for a
docxskill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
Do not include any other fields in YAML frontmatter.
Body
Write instructions for using the skill and its bundled resources.
Step 5: Packaging a Skill
Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
scripts/package_skill.py <path/to/skill-folder>
Optional output directory specification:
scripts/package_skill.py <path/to/skill-folder> ./dist
The packaging script will:
-
Validate the skill automatically, checking:
- YAML frontmatter format and required fields
- Skill naming conventions and directory structure
- Description completeness and quality
- File organization and resource references
-
Package the skill if validation passes, creating a .skill file named after the skill (e.g.,
my-skill.skill) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
Step 6: Iterate
After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
Iteration workflow:
- Use the skill on real tasks
- Notice struggles or inefficiencies
- Identify how SKILL.md or bundled resources should be updated
- Implement changes and test again
Developer Growth Analysis
This skill provides personalized feedback on your recent coding work by analyzing your Claude Code chat interactions and identifying patterns that reveal strengths and areas for growth.
When to Use This Skill
Use this skill when you want to:
- Understand your development patterns and habits from recent work
- Identify specific technical gaps or recurring challenges
- Discover which topics would benefit from deeper study
- Get curated learning resources tailored to your actual work patterns
- Track improvement areas across your recent projects
- Find high-quality articles that directly address the skills you're developing
This skill is ideal for developers who want structured feedback on their growth without waiting for code reviews, and who prefer data-driven insights from their own work history.
What This Skill Does
This skill performs a six-step analysis of your development work:
-
Reads Your Chat History: Accesses your local Claude Code chat history from the past 24-48 hours to understand what you've been working on.
-
Identifies Development Patterns: Analyzes the types of problems you're solving, technologies you're using, challenges you encounter, and how you approach different kinds of tasks.
-
Detects Improvement Areas: Recognizes patterns that suggest skill gaps, repeated struggles, inefficient approaches, or areas where you might benefit from deeper knowledge.
-
Generates a Personalized Report: Creates a comprehensive report showing your work summary, identified improvement areas, and specific recommendations for growth.
-
Finds Learning Resources: Uses HackerNews to curate high-quality articles and discussions directly relevant to your improvement areas, providing you with a reading list tailored to your actual development work.
-
Sends to Your Slack DMs: Automatically delivers the complete report to your own Slack direct messages so you can reference it anytime, anywhere.
How to Use
Ask Claude to analyze your recent coding work:
Analyze my developer growth from my recent chats
Or be more specific about which time period:
Analyze my work from today and suggest areas for improvement
The skill will generate a formatted report with:
- Overview of your recent work
- Key improvement areas identified
- Specific recommendations for each area
- Curated learning resources from HackerNews
- Action items you can focus on
Instructions
When a user requests analysis of their developer growth or coding patterns from recent work:
-
Access Chat History
Read the chat history from
~/.claude/history.jsonl. This file is a JSONL format where each line contains:display: The user's message/requestproject: The project being worked ontimestamp: Unix timestamp (in milliseconds)pastedContents: Any code or content pasted
Filter for entries from the past 24-48 hours based on the current timestamp.
-
Analyze Work Patterns
Extract and analyze the following from the filtered chats:
- Projects and Domains: What types of projects was the user working on? (e.g., backend, frontend, DevOps, data, etc.)
- Technologies Used: What languages, frameworks, and tools appear in the conversations?
- Problem Types: What categories of problems are being solved? (e.g., performance optimization, debugging, feature implementation, refactoring, setup/configuration)
- Challenges Encountered: What problems did the user struggle with? Look for:
- Repeated questions about similar topics
- Problems that took multiple attempts to solve
- Questions indicating knowledge gaps
- Complex architectural decisions
- Approach Patterns: How does the user solve problems? (e.g., methodical, exploratory, experimental)
-
Identify Improvement Areas
Based on the analysis, identify 3-5 specific areas where the user could improve. These should be:
- Specific (not vague like "improve coding skills")
- Evidence-based (grounded in actual chat history)
- Actionable (practical improvements that can be made)
- Prioritized (most impactful first)
Examples of good improvement areas:
- "Advanced TypeScript patterns (generics, utility types, type guards) - you struggled with type safety in [specific project]"
- "Error handling and validation - I noticed you patched several bugs related to missing null checks"
- "Async/await patterns - your recent work shows some race conditions and timing issues"
- "Database query optimization - you rewrote the same query multiple times"
-
Generate Report
Create a comprehensive report with this structure:
# Your Developer Growth Report **Report Period**: [Yesterday / Today / [Custom Date Range]] **Last Updated**: [Current Date and Time] ## Work Summary [2-3 paragraphs summarizing what the user worked on, projects touched, technologies used, and overall focus areas] Example: "Over the past 24 hours, you focused primarily on backend development with three distinct projects. Your work involved TypeScript, React, and deployment infrastructure. You tackled a mix of feature implementation, debugging, and architectural decisions, with a particular focus on API design and database optimization." ## Improvement Areas (Prioritized) ### 1. [Area Name] **Why This Matters**: [Explanation of why this skill is important for the user's work] **What I Observed**: [Specific evidence from chat history showing this gap] **Recommendation**: [Concrete step(s) to improve in this area] **Time to Skill Up**: [Brief estimate of effort required] --- [Repeat for 2-4 additional areas] ## Strengths Observed [2-3 bullet points highlighting things you're doing well - things to continue doing] ## Action Items Priority order: 1. [Action item derived from highest priority improvement area] 2. [Action item from next area] 3. [Action item from next area] ## Learning Resources [Will be populated in next step] -
Search for Learning Resources
Use Rube MCP to search HackerNews for articles related to each improvement area:
- For each improvement area, construct a search query targeting high-quality resources
- Search HackerNews using RUBE_SEARCH_TOOLS with queries like:
- "Learn [Technology/Pattern] best practices"
- "[Technology] advanced patterns and techniques"
- "Debugging [specific problem type] in [language]"
- Prioritize posts with high engagement (comments, upvotes)
- For each area, include 2-3 most relevant articles with:
- Article title
- Publication date
- Brief description of why it's relevant
- Link to the article
Add this section to the report:
## Curated Learning Resources ### For: [Improvement Area] 1. **[Article Title]** - [Date] [Description of what it covers and why it's relevant to your improvement area] [Link] 2. **[Article Title]** - [Date] [Description] [Link] [Repeat for other improvement areas] -
Present the Complete Report
Deliver the report in a clean, readable format that the user can:
- Quickly scan for key takeaways
- Use for focused learning planning
- Reference over the next week as they work on improvements
- Share with mentors if they want external feedback
-
Send Report to Slack DMs
Use Rube MCP to send the complete report to the user's own Slack DMs:
- Check if Slack connection is active via RUBE_SEARCH_TOOLS
- If not connected, use RUBE_MANAGE_CONNECTIONS to initiate Slack auth
- Use RUBE_MULTI_EXECUTE_TOOL to send the report as a formatted message:
- Send the report title and period as the first message
- Break the report into logical sections (Summary, Improvements, Strengths, Actions, Resources)
- Format each section as a well-structured Slack message with proper markdown
- Include clickable links for the learning resources
- Confirm delivery in the CLI output
This ensures the user has the report in a place they check regularly and can reference it throughout the week.
Example Usage
Input
Analyze my developer growth from my recent chats
Output
# Your Developer Growth Report
**Report Period**: November 9-10, 2024
**Last Updated**: November 10, 2024, 9:15 PM UTC
## Work Summary
Over the past two days, you focused on backend infrastructure and API development. Your primary project was an open-source showcase application, where you made significant progress on connections management, UI improvements, and deployment configuration. You worked with TypeScript, React, and Node.js, tackling challenges ranging from data security to responsive design. Your work shows a balance between implementing features and addressing technical debt.
## Improvement Areas (Prioritized)
### 1. Advanced TypeScript Patterns and Type Safety
**Why This Matters**: TypeScript is central to your work, but leveraging its advanced features (generics, utility types, conditional types, type guards) can significantly improve code reliability and reduce runtime errors. Better type safety catches bugs at compile time rather than in production.
**What I Observed**: In your recent chats, you were working with connection data structures and struggled a few times with typing auth configurations properly. You also had to iterate on union types for different connection states. There's an opportunity to use discriminated unions and type guards more effectively.
**Recommendation**: Study TypeScript's advanced type system, particularly utility types (Omit, Pick, Record), conditional types, and discriminated unions. Apply these patterns to your connection configuration handling and auth state management.
**Time to Skill Up**: 5-8 hours of focused learning and practice
### 2. Secure Data Handling and Information Hiding in UI
**Why This Matters**: You identified and fixed a security concern where sensitive connection data was being displayed in your console. Preventing information leakage is critical for applications handling user credentials and API keys. Good practices here prevent security incidents and user trust violations.
**What I Observed**: You caught that your "Your Apps" page was showing full connection data including auth configs. This shows good security instincts, and the next step is building this into your default thinking when handling sensitive information.
**Recommendation**: Review security best practices for handling sensitive data in frontend applications. Create reusable patterns for filtering/masking sensitive information before displaying it. Consider implementing a secure data layer that explicitly whitelist what can be shown in the UI.
**Time to Skill Up**: 3-4 hours
### 3. Component Architecture and Responsive UI Patterns
**Why This Matters**: You're designing UIs that need to work across different screen sizes and user interactions. Strong component architecture makes it easier to build complex UIs without bugs and improves maintainability.
**What I Observed**: You worked on the "Marketplace" UI (formerly Browse Tools), recreating it from a design image. You also identified and fixed scrolling issues where content was overflowing containers. There's an opportunity to strengthen your understanding of layout containment and responsive design patterns.
**Recommendation**: Study React component composition patterns and CSS layout best practices (especially flexbox and grid). Focus on container queries and responsive patterns that prevent overflow issues. Look into component composition libraries and design system approaches.
**Time to Skill Up**: 6-10 hours (depending on depth)
## Strengths Observed
- **Security Awareness**: You proactively identified data leakage issues before they became problems
- **Iterative Refinement**: You worked through UI requirements methodically, asking clarifying questions and improving designs
- **Full-Stack Capability**: You comfortably work across backend APIs, frontend UI, and deployment concerns
- **Problem-Solving Approach**: You break down complex tasks into manageable steps
## Action Items
Priority order:
1. Spend 1-2 hours learning TypeScript utility types and discriminated unions; apply to your connection data structures
2. Document security patterns for your project (what data is safe to display, filtering/masking functions)
3. Study one article on advanced React patterns and apply one pattern to your current UI work
4. Set up a code review checklist focused on type safety and data security for future PRs
## Curated Learning Resources
### For: Advanced TypeScript Patterns
1. **TypeScript's Advanced Types: Generics, Utility Types, and Conditional Types** - HackerNews, October 2024
Deep dive into TypeScript's type system with practical examples and real-world applications. Covers discriminated unions, type guards, and patterns for ensuring compile-time safety in complex applications.
[Link to discussion]
2. **Building Type-Safe APIs in TypeScript** - HackerNews, September 2024
Practical guide to designing APIs with TypeScript that catch errors early. Particularly relevant for your connection configuration work.
[Link to discussion]
### For: Secure Data Handling in Frontend
1. **Preventing Information Leakage in Web Applications** - HackerNews, August 2024
Comprehensive guide to data security in frontend applications, including filtering sensitive information, secure logging, and audit trails.
[Link to discussion]
2. **OAuth and API Key Management Best Practices** - HackerNews, July 2024
How to safely handle authentication tokens and API keys in applications, with examples for different frameworks.
[Link to discussion]
### For: Component Architecture and Responsive Design
1. **Advanced React Patterns: Composition Over Configuration** - HackerNews
Explores component composition strategies that scale, with examples using modern React patterns.
[Link to discussion]
2. **CSS Layout Mastery: Flexbox, Grid, and Container Queries** - HackerNews, October 2024
Learn responsive design patterns that prevent overflow issues and work across all screen sizes.
[Link to discussion]
Tips and Best Practices
- Run this analysis once a week to track your improvement trajectory over time
- Pick one improvement area at a time and focus on it for a few days before moving to the next
- Use the learning resources as a study guide; work through the recommended materials and practice applying the patterns
- Revisit this report after focusing on an area for a week to see how your work patterns change
- The learning resources are intentionally curated for your actual work, not generic topics, so they'll be highly relevant to what you're building
How Accuracy and Quality Are Maintained
This skill:
- Analyzes your actual work patterns from timestamped chat history
- Generates evidence-based recommendations grounded in real projects
- Curates learning resources that directly address your identified gaps
- Focuses on actionable improvements, not vague feedback
- Provides specific time estimates based on complexity
- Prioritizes areas that will have the most impact on your development velocity
Writing Skills
Overview
Writing skills IS Test-Driven Development applied to process documentation.
Personal skills live in agent-specific directories (~/.claude/skills for Claude Code, ~/.codex/skills for Codex)
You write test cases (pressure scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).
Core principle: If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
REQUIRED BACKGROUND: You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
Official guidance: For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.
What is a Skill?
A skill is a reference guide for proven techniques, patterns, or tools. Skills help future Claude instances find and apply effective approaches.
Skills are: Reusable techniques, patterns, tools, reference guides
Skills are NOT: Narratives about how you solved a problem once
TDD Mapping for Skills
| TDD Concept | Skill Creation |
|---|---|
| Test case | Pressure scenario with subagent |
| Production code | Skill document (SKILL.md) |
| Test fails (RED) | Agent violates rule without skill (baseline) |
| Test passes (GREEN) | Agent complies with skill present |
| Refactor | Close loopholes while maintaining compliance |
| Write test first | Run baseline scenario BEFORE writing skill |
| Watch it fail | Document exact rationalizations agent uses |
| Minimal code | Write skill addressing those specific violations |
| Watch it pass | Verify agent now complies |
| Refactor cycle | Find new rationalizations → plug → re-verify |
The entire skill creation process follows RED-GREEN-REFACTOR.
When to Create a Skill
Create when:
- Technique wasn't intuitively obvious to you
- You'd reference this again across projects
- Pattern applies broadly (not project-specific)
- Others would benefit
Don't create for:
- One-off solutions
- Standard practices well-documented elsewhere
- Project-specific conventions (put in CLAUDE.md)
Skill Types
Technique
Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
Pattern
Way of thinking about problems (flatten-with-flags, test-invariants)
Reference
API docs, syntax guides, tool documentation (office docs)
Directory Structure
skills/
skill-name/
SKILL.md # Main reference (required)
supporting-file.* # Only if needed
Flat namespace - all skills in one searchable namespace
Separate files for:
- Heavy reference (100+ lines) - API docs, comprehensive syntax
- Reusable tools - Scripts, utilities, templates
Keep inline:
- Principles and concepts
- Code patterns (< 50 lines)
- Everything else
SKILL.md Structure
Frontmatter (YAML):
- Only two fields supported:
nameanddescription - Max 1024 characters total
name: Use letters, numbers, and hyphens only (no parentheses, special chars)description: Third-person, describes ONLY when to use (NOT what it does)- Start with "Use when..." to focus on triggering conditions
- Include specific symptoms, situations, and contexts
- NEVER summarize the skill's process or workflow (see CSO section for why)
- Keep under 500 characters if possible
---
name: Skill-Name-With-Hyphens
description: Use when [specific triggering conditions and symptoms]
---
# Skill Name
## Overview
What is this? Core principle in 1-2 sentences.
## When to Use
[Small inline flowchart IF decision non-obvious]
Bullet list with SYMPTOMS and use cases
When NOT to use
## Core Pattern (for techniques/patterns)
Before/after code comparison
## Quick Reference
Table or bullets for scanning common operations
## Implementation
Inline code for simple patterns
Link to file for heavy reference or reusable tools
## Common Mistakes
What goes wrong + fixes
## Real-World Impact (optional)
Concrete results
Claude Search Optimization (CSO)
Critical for discovery: Future Claude needs to FIND your skill
1. Rich Description Field
Purpose: Claude reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
Format: Start with "Use when..." to focus on triggering conditions
CRITICAL: Description = When to Use, NOT What the Skill Does
The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
Why this matters: Testing revealed that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused Claude to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).
When the description was changed to just "Use when executing implementation plans with independent tasks" (no workflow summary), Claude correctly read the flowchart and followed the two-stage review process.
The trap: Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.
# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
description: Use when executing plans - dispatches subagent per task with code review between tasks
# ❌ BAD: Too much process detail
description: Use for TDD - write test first, watch it fail, write minimal code, refactor
# ✅ GOOD: Just triggering conditions, no workflow summary
description: Use when executing implementation plans with independent tasks in the current session
# ✅ GOOD: Triggering conditions only
description: Use when implementing any feature or bugfix, before writing implementation code
Content:
- Use concrete triggers, symptoms, and situations that signal this skill applies
- Describe the problem (race conditions, inconsistent behavior) not language-specific symptoms (setTimeout, sleep)
- Keep triggers technology-agnostic unless the skill itself is technology-specific
- If skill is technology-specific, make that explicit in the trigger
- Write in third person (injected into system prompt)
- NEVER summarize the skill's process or workflow
# ❌ BAD: Too abstract, vague, doesn't include when to use
description: For async testing
# ❌ BAD: First person
description: I can help you with async tests when they're flaky
# ❌ BAD: Mentions technology but skill isn't specific to it
description: Use when tests use setTimeout/sleep and are flaky
# ✅ GOOD: Starts with "Use when", describes problem, no workflow
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
# ✅ GOOD: Technology-specific skill with explicit trigger
description: Use when using React Router and handling authentication redirects
2. Keyword Coverage
Use words Claude would search for:
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
- Symptoms: "flaky", "hanging", "zombie", "pollution"
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
- Tools: Actual commands, library names, file types
3. Descriptive Naming
Use active voice, verb-first:
- ✅
creating-skillsnotskill-creation - ✅
condition-based-waitingnotasync-test-helpers
4. Token Efficiency (Critical)
Problem: getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
Target word counts:
- getting-started workflows: <150 words each
- Frequently-loaded skills: <200 words total
- Other skills: <500 words (still be concise)
Techniques:
Move details to tool help:
# ❌ BAD: Document all flags in SKILL.md
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
# ✅ GOOD: Reference --help
search-conversations supports multiple modes and filters. Run --help for details.
Use cross-references:
# ❌ BAD: Repeat workflow details
When searching, dispatch subagent with template...
[20 lines of repeated instructions]
# ✅ GOOD: Reference other skill
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
Compress examples:
# ❌ BAD: Verbose example (42 words)
your human partner: "How did we handle authentication errors in React Router before?"
You: I'll search past conversations for React Router authentication patterns.
[Dispatch subagent with search query: "React Router authentication error handling 401"]
# ✅ GOOD: Minimal example (20 words)
Partner: "How did we handle auth errors in React Router?"
You: Searching...
[Dispatch subagent → synthesis]
Eliminate redundancy:
- Don't repeat what's in cross-referenced skills
- Don't explain what's obvious from command
- Don't include multiple examples of same pattern
Verification:
wc -w skills/path/SKILL.md
# getting-started workflows: aim for <150 each
# Other frequently-loaded: aim for <200 total
Name by what you DO or core insight:
- ✅
condition-based-waiting>async-test-helpers - ✅
using-skillsnotskill-usage - ✅
flatten-with-flags>data-structure-refactoring - ✅
root-cause-tracing>debugging-techniques
Gerunds (-ing) work well for processes:
creating-skills,testing-skills,debugging-with-logs- Active, describes the action you're taking
4. Cross-Referencing Other Skills
When writing documentation that references other skills:
Use skill name only, with explicit requirement markers:
- ✅ Good:
**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development - ✅ Good:
**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging - ❌ Bad:
See skills/testing/test-driven-development(unclear if required) - ❌ Bad:
@skills/testing/test-driven-development/SKILL.md(force-loads, burns context)
Why no @ links: @ syntax force-loads files immediately, consuming 200k+ context before you need them.
Flowchart Usage
digraph when_flowchart {
"Need to show information?" [shape=diamond];
"Decision where I might go wrong?" [shape=diamond];
"Use markdown" [shape=box];
"Small inline flowchart" [shape=box];
"Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
"Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
"Decision where I might go wrong?" -> "Use markdown" [label="no"];
}
Use flowcharts ONLY for:
- Non-obvious decision points
- Process loops where you might stop too early
- "When to use A vs B" decisions
Never use flowcharts for:
- Reference material → Tables, lists
- Code examples → Markdown blocks
- Linear instructions → Numbered lists
- Labels without semantic meaning (step1, helper2)
See @graphviz-conventions.dot for graphviz style rules.
Visualizing for your human partner: Use render-graphs.js in this directory to render a skill's flowcharts to SVG:
./render-graphs.js ../some-skill # Each diagram separately
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
Code Examples
One excellent example beats many mediocre ones
Choose most relevant language:
- Testing techniques → TypeScript/JavaScript
- System debugging → Shell/Python
- Data processing → Python
Good example:
- Complete and runnable
- Well-commented explaining WHY
- From real scenario
- Shows pattern clearly
- Ready to adapt (not generic template)
Don't:
- Implement in 5+ languages
- Create fill-in-the-blank templates
- Write contrived examples
You're good at porting - one great example is enough.
File Organization
Self-Contained Skill
defense-in-depth/
SKILL.md # Everything inline
When: All content fits, no heavy reference needed
Skill with Reusable Tool
condition-based-waiting/
SKILL.md # Overview + patterns
example.ts # Working helpers to adapt
When: Tool is reusable code, not just narrative
Skill with Heavy Reference
pptx/
SKILL.md # Overview + workflows
pptxgenjs.md # 600 lines API reference
ooxml.md # 500 lines XML structure
scripts/ # Executable tools
When: Reference material too large for inline
The Iron Law (Same as TDD)
NO SKILL WITHOUT A FAILING TEST FIRST
This applies to NEW skills AND EDITS to existing skills.
Write skill before testing? Delete it. Start over. Edit skill without testing? Same violation.
No exceptions:
- Not for "simple additions"
- Not for "just adding a section"
- Not for "documentation updates"
- Don't keep untested changes as "reference"
- Don't "adapt" while running tests
- Delete means delete
REQUIRED BACKGROUND: The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.
Testing All Skill Types
Different skill types need different test approaches:
Discipline-Enforcing Skills (rules/requirements)
Examples: TDD, verification-before-completion, designing-before-coding
Test with:
- Academic questions: Do they understand the rules?
- Pressure scenarios: Do they comply under stress?
- Multiple pressures combined: time + sunk cost + exhaustion
- Identify rationalizations and add explicit counters
Success criteria: Agent follows rule under maximum pressure
Technique Skills (how-to guides)
Examples: condition-based-waiting, root-cause-tracing, defensive-programming
Test with:
- Application scenarios: Can they apply the technique correctly?
- Variation scenarios: Do they handle edge cases?
- Missing information tests: Do instructions have gaps?
Success criteria: Agent successfully applies technique to new scenario
Pattern Skills (mental models)
Examples: reducing-complexity, information-hiding concepts
Test with:
- Recognition scenarios: Do they recognize when pattern applies?
- Application scenarios: Can they use the mental model?
- Counter-examples: Do they know when NOT to apply?
Success criteria: Agent correctly identifies when/how to apply pattern
Reference Skills (documentation/APIs)
Examples: API documentation, command references, library guides
Test with:
- Retrieval scenarios: Can they find the right information?
- Application scenarios: Can they use what they found correctly?
- Gap testing: Are common use cases covered?
Success criteria: Agent finds and correctly applies reference information
Common Rationalizations for Skipping Testing
| Excuse | Reality |
|---|---|
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
| "No time to test" | Deploying untested skill wastes more time fixing it later. |
All of these mean: Test before deploying. No exceptions.
Bulletproofing Skills Against Rationalization
Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.
Psychology note: Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.
Close Every Loophole Explicitly
Don't just state the rule - forbid specific workarounds:
```markdown Write code before test? Delete it. ``` ```markdown Write code before 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
</Good>
### Address "Spirit vs Letter" Arguments
Add foundational principle early:
```markdown
**Violating the letter of the rules is violating the spirit of the rules.**
This cuts off entire class of "I'm following the spirit" rationalizations.
Build Rationalization Table
Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
| 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?" |
Create Red Flags List
Make it easy for agents to self-check when rationalizing:
## Red Flags - STOP and Start Over
- Code before test
- "I already manually tested it"
- "Tests after achieve the same purpose"
- "It's about spirit not ritual"
- "This is different because..."
**All of these mean: Delete code. Start over with TDD.**
Update CSO for Violation Symptoms
Add to description: symptoms of when you're ABOUT to violate the rule:
description: use when implementing any feature or bugfix, before writing implementation code
RED-GREEN-REFACTOR for Skills
Follow the TDD cycle:
RED: Write Failing Test (Baseline)
Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
- What choices did they make?
- What rationalizations did they use (verbatim)?
- Which pressures triggered violations?
This is "watch the test fail" - you must see what agents naturally do before writing the skill.
GREEN: Write Minimal Skill
Write skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.
Run same scenarios WITH skill. Agent should now comply.
REFACTOR: Close Loopholes
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
Testing methodology: See @testing-skills-with-subagents.md for the complete testing methodology:
- How to write pressure scenarios
- Pressure types (time, sunk cost, authority, exhaustion)
- Plugging holes systematically
- Meta-testing techniques
Anti-Patterns
❌ Narrative Example
"In session 2025-10-03, we found empty projectDir caused..." Why bad: Too specific, not reusable
❌ Multi-Language Dilution
example-js.js, example-py.py, example-go.go Why bad: Mediocre quality, maintenance burden
❌ Code in Flowcharts
step1 [label="import fs"];
step2 [label="read file"];
Why bad: Can't copy-paste, hard to read
❌ Generic Labels
helper1, helper2, step3, pattern4 Why bad: Labels should have semantic meaning
STOP: Before Moving to Next Skill
After writing ANY skill, you MUST STOP and complete the deployment process.
Do NOT:
- Create multiple skills in batch without testing each
- Move to next skill before current one is verified
- Skip testing because "batching is more efficient"
The deployment checklist below is MANDATORY for EACH skill.
Deploying untested skills = deploying untested code. It's a violation of quality standards.
Skill Creation Checklist (TDD Adapted)
IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.
RED Phase - Write Failing Test:
- Create pressure scenarios (3+ combined pressures for discipline skills)
- Run scenarios WITHOUT skill - document baseline behavior verbatim
- Identify patterns in rationalizations/failures
GREEN Phase - Write Minimal Skill:
- Name uses only letters, numbers, hyphens (no parentheses/special chars)
- YAML frontmatter with only name and description (max 1024 chars)
- Description starts with "Use when..." and includes specific triggers/symptoms
- Description written in third person
- Keywords throughout for search (errors, symptoms, tools)
- Clear overview with core principle
- Address specific baseline failures identified in RED
- Code inline OR link to separate file
- One excellent example (not multi-language)
- Run scenarios WITH skill - verify agents now comply
REFACTOR Phase - Close Loopholes:
- Identify NEW rationalizations from testing
- Add explicit counters (if discipline skill)
- Build rationalization table from all test iterations
- Create red flags list
- Re-test until bulletproof
Quality Checks:
- Small flowchart only if decision non-obvious
- Quick reference table
- Common mistakes section
- No narrative storytelling
- Supporting files only for tools or heavy reference
Deployment:
- Commit skill to git and push to your fork (if configured)
- Consider contributing back via PR (if broadly useful)
Discovery Workflow
How future Claude finds your skill:
- Encounters problem ("tests are flaky")
- Finds SKILL (description matches)
- Scans overview (is this relevant?)
- Reads patterns (quick reference table)
- Loads example (only when implementing)
Optimize for this flow - put searchable terms early and often.
The Bottom Line
Creating skills IS TDD for process documentation.
Same Iron Law: No skill without failing test first. Same cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes). Same benefits: Better quality, fewer surprises, bulletproof results.
If you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.
Chat with ArXiv
Build intelligent agents that understand, discuss, and synthesize academic research papers from ArXiv, enabling conversational exploration of scientific literature.
Overview
ArXiv chat agents combine:
- Paper Discovery: Search and retrieve relevant research
- Content Processing: Extract and understand paper content
- Question Answering: Answer questions about papers
- Research Synthesis: Identify connections between papers
- Conversational Interface: Natural discussion about research
Applications
- Research assistant for literature review
- Paper summarization and explanation
- Topic exploration across multiple papers
- Citation analysis and connection finding
- Trend identification in research areas
- Thesis and dissertation support
Architecture
User Query
↓
Query Classifier (Paper Search vs Q&A)
├→ Paper Search
│ ├ Query ArXiv API
│ ├ Retrieve papers
│ └ Process metadata
│
├→ Question Answering
│ ├ Retrieve relevant papers
│ ├ Extract relevant sections
│ ├ Generate answer with LLM
│ └ Cite sources
│
└→ Conversational Analysis
├ Analyze paper relationships
├ Identify themes
└ Synthesize findings
↓
Response with Citations
Paper Discovery and Retrieval
1. ArXiv API Integration
See examples/arxiv_paper_retriever.py for ArXivPaperRetriever:
- Search papers by query with relevance ranking
- Search by category, author, or title keywords
- Retrieve trending papers by category and date range
- Find similar papers to a given paper
- Extract key terms from paper abstracts
2. Paper Content Processing
See examples/paper_content_processor.py for PaperContentProcessor:
- Download and extract PDF content
- Parse paper structure (abstract, introduction, methodology, results, conclusion, references)
- Extract citations from papers
- Cache processed papers for performance
- Chunk papers for RAG integration
Question Answering System
1. RAG-Based QA
See examples/paper_question_answerer.py for PaperQuestionAnswerer:
- Search for relevant papers from ArXiv
- Download and process papers
- Chunk papers for RAG retrieval
- Retrieve most relevant chunks using embeddings
- Generate answers with proper citations
2. Multi-Paper Synthesis
Build synthesis capabilities to:
- Analyze multiple papers on a topic
- Extract key findings and conclusions
- Identify common research themes
- Generate comprehensive synthesis of research area
Conversational Interface
1. Multi-Turn Conversation
See examples/arxiv_chatbot.py for ArXivChatbot:
- Maintain conversation history
- Classify query types (single paper Q&A, multi-paper synthesis, trends, general)
- Handle single paper questions with citations
- Handle synthesis queries across multiple papers
- Detect and retrieve research trends
- Generate contextual responses
2. Context Management
Build context management to:
- Track current discussion topic
- Remember discussed papers
- Find related papers in conversation
- Summarize discussion progress
Best Practices
Paper Retrieval
- ✓ Use specific queries for better results
- ✓ Limit results to relevant papers (max 50-100)
- ✓ Cache downloaded papers locally
- ✓ Handle API rate limits
- ✓ Validate PDF extraction
Question Answering
- ✓ Always cite sources with ArXiv IDs
- ✓ Use multiple paper perspectives
- ✓ Acknowledge uncertainties
- ✓ Highlight conflicting findings
- ✓ Suggest related papers
Conversation Management
- ✓ Maintain conversation history
- ✓ Track discussed papers
- ✓ Clarify ambiguous queries
- ✓ Suggest follow-up questions
- ✓ Provide paper recommendations
Implementation Checklist
- Set up ArXiv API client
- Implement paper retrieval
- Create PDF processing pipeline
- Build RAG system for QA
- Implement multi-paper synthesis
- Create conversational interface
- Add search filtering
- Set up caching system
- Implement citation formatting
- Add error handling and logging
- Test across research areas
Resources
ArXiv API
- ArXiv Official API: https://arxiv.org/help/api
- arxiv Python Client: https://github.com/lukasschwab/arxiv.py
Paper Processing
- PyPDF2: https://github.com/py-pdf/PyPDF2
- pdfplumber: https://github.com/jsvine/pdfplumber
RAG and QA
- LangChain: https://python.langchain.com/
- Hugging Face Transformers: https://huggingface.co/transformers/
Citation Management
- CrossRef API: https://www.crossref.org/services/metadata-retrieval/
- Semantic Scholar API: https://www.semanticscholar.org/product/api
AWS Cost & Operations
This skill provides comprehensive guidance for AWS cost optimization, monitoring, observability, and operational excellence with integrated MCP servers.
AWS Documentation Requirement
CRITICAL: This skill requires AWS MCP tools for accurate, up-to-date AWS information.
Before Answering AWS Questions
-
Always verify using AWS MCP tools (if available):
mcp__aws-mcp__aws___search_documentationormcp__*awsdocs*__aws___search_documentation- Search AWS docsmcp__aws-mcp__aws___read_documentationormcp__*awsdocs*__aws___read_documentation- Read specific pagesmcp__aws-mcp__aws___get_regional_availability- Check service availability
-
If AWS MCP tools are unavailable:
- Guide user to configure AWS MCP: See AWS MCP Setup Guide
- Help determine which option fits their environment:
- Has uvx + AWS credentials → Full AWS MCP Server
- No Python/credentials → AWS Documentation MCP (no auth)
- If cannot determine → Ask user which option to use
Integrated MCP Servers
This skill includes 8 MCP servers automatically configured with the plugin:
Cost Management Servers
1. AWS Billing and Cost Management MCP Server
Purpose: Real-time billing and cost management
- View current AWS spending and trends
- Analyze billing details across services
- Track budget utilization
- Monitor cost allocation tags
- Review consolidated billing for organizations
2. AWS Pricing MCP Server
Purpose: Pre-deployment cost estimation and optimization
- Estimate costs before deploying resources
- Compare pricing across regions
- Calculate Total Cost of Ownership (TCO)
- Evaluate different service options for cost efficiency
- Get current pricing information for AWS services
3. AWS Cost Explorer MCP Server
Purpose: Detailed cost analysis and reporting
- Analyze historical spending patterns
- Create custom cost reports
- Identify cost anomalies and trends
- Forecast future costs
- Analyze cost by service, region, or tag
- Generate cost optimization recommendations
Monitoring & Observability Servers
4. Amazon CloudWatch MCP Server
Purpose: Metrics, alarms, and logs analysis
- Query CloudWatch metrics and logs
- Create and manage CloudWatch alarms
- Analyze application performance metrics
- Troubleshoot operational issues
- Set up custom dashboards
- Monitor resource utilization
5. Amazon CloudWatch Application Signals MCP Server
Purpose: Application monitoring and performance insights
- Monitor application health and performance
- Analyze service-level objectives (SLOs)
- Track application dependencies
- Identify performance bottlenecks
- Monitor service map and traces
6. AWS Managed Prometheus MCP Server
Purpose: Prometheus-compatible monitoring
- Query Prometheus metrics
- Monitor containerized applications
- Analyze Kubernetes workload metrics
- Create PromQL queries
- Track custom application metrics
Audit & Security Servers
7. AWS CloudTrail MCP Server
Purpose: AWS API activity and audit analysis
- Analyze AWS API calls and user activity
- Track resource changes and modifications
- Investigate security incidents
- Audit compliance requirements
- Identify unusual access patterns
- Review who made what changes when
8. AWS Well-Architected Security Assessment Tool MCP Server
Purpose: Security assessment against Well-Architected Framework
- Assess security posture against AWS best practices
- Identify security gaps and vulnerabilities
- Get security improvement recommendations
- Review security pillar compliance
- Generate security assessment reports
When to Use This Skill
Use this skill when:
- Optimizing AWS costs and reducing spending
- Estimating costs before deployment
- Monitoring application and infrastructure performance
- Setting up observability and alerting
- Analyzing spending patterns and trends
- Investigating operational issues
- Auditing AWS activity and changes
- Assessing security posture
- Implementing operational excellence
Cost Optimization Best Practices
Pre-Deployment Cost Estimation
Always estimate costs before deploying:
- Use AWS Pricing MCP to estimate resource costs
- Compare pricing across different regions
- Evaluate alternative service options
- Calculate expected monthly costs
- Plan for scaling and growth
Example workflow:
"Estimate the monthly cost of running a Lambda function with
1 million invocations, 512MB memory, 3-second duration in us-east-1"
Cost Analysis and Optimization
Regular cost reviews:
- Use Cost Explorer MCP to analyze spending trends
- Identify cost anomalies and unexpected charges
- Review costs by service, region, and environment
- Compare actual vs. budgeted costs
- Generate cost optimization recommendations
Cost optimization strategies:
- Right-size over-provisioned resources
- Use appropriate storage classes (S3, EBS)
- Implement auto-scaling for dynamic workloads
- Leverage Savings Plans and Reserved Instances
- Delete unused resources and snapshots
- Use cost allocation tags effectively
Budget Monitoring
Track spending against budgets:
- Use Billing and Cost Management MCP to monitor budgets
- Set up budget alerts for threshold breaches
- Review budget utilization regularly
- Adjust budgets based on trends
- Implement cost controls and governance
Monitoring and Observability Best Practices
CloudWatch Metrics and Alarms
Implement comprehensive monitoring:
- Use CloudWatch MCP to query metrics and logs
- Set up alarms for critical metrics:
- CPU and memory utilization
- Error rates and latency
- Queue depths and processing times
- API gateway throttling
- Lambda errors and timeouts
- Create CloudWatch dashboards for visualization
- Use log insights for troubleshooting
Example alarm scenarios:
- Lambda error rate > 1%
- EC2 CPU utilization > 80%
- API Gateway 4xx/5xx error spike
- DynamoDB throttled requests
- ECS task failures
Application Performance Monitoring
Monitor application health:
- Use CloudWatch Application Signals MCP for APM
- Track service-level objectives (SLOs)
- Monitor application dependencies
- Identify performance bottlenecks
- Set up distributed tracing
Container and Kubernetes Monitoring
For containerized workloads:
- Use AWS Managed Prometheus MCP for metrics
- Monitor container resource utilization
- Track pod and node health
- Create PromQL queries for custom metrics
- Set up alerts for container anomalies
Audit and Security Best Practices
CloudTrail Activity Analysis
Audit AWS activity:
- Use CloudTrail MCP to analyze API activity
- Track who made changes to resources
- Investigate security incidents
- Monitor for suspicious activity patterns
- Audit compliance with policies
Common audit scenarios:
- "Who deleted this S3 bucket?"
- "Show all IAM role changes in the last 24 hours"
- "List failed login attempts"
- "Find all actions by a specific user"
- "Track modifications to security groups"
Security Assessment
Regular security reviews:
- Use Well-Architected Security Assessment MCP
- Assess security posture against best practices
- Identify security gaps and vulnerabilities
- Implement recommended security improvements
- Document security compliance
Security assessment areas:
- Identity and Access Management (IAM)
- Detective controls and monitoring
- Infrastructure protection
- Data protection and encryption
- Incident response preparedness
Using MCP Servers Effectively
Cost Analysis Workflow
- Pre-deployment: Use Pricing MCP to estimate costs
- Post-deployment: Use Billing MCP to track actual spending
- Analysis: Use Cost Explorer MCP for detailed cost analysis
- Optimization: Implement recommendations from Cost Explorer
Monitoring Workflow
- Setup: Configure CloudWatch metrics and alarms
- Monitor: Use CloudWatch MCP to track key metrics
- Analyze: Use Application Signals for APM insights
- Troubleshoot: Query CloudWatch Logs for issue resolution
Security Workflow
- Audit: Use CloudTrail MCP to review activity
- Assess: Use Well-Architected Security Assessment
- Remediate: Implement security recommendations
- Monitor: Track security events via CloudWatch
MCP Usage Best Practices
- Cost Awareness: Check pricing before deploying resources
- Proactive Monitoring: Set up alarms for critical metrics
- Regular Reviews: Analyze costs and performance weekly
- Audit Trails: Review CloudTrail logs for compliance
- Security First: Run security assessments regularly
- Optimize Continuously: Act on cost and performance recommendations
Operational Excellence Guidelines
Cost Optimization
- Tag Everything: Use consistent cost allocation tags
- Review Monthly: Analyze spending trends and anomalies
- Right-size: Match resources to actual usage
- Automate: Use auto-scaling and scheduling
- Monitor Budgets: Set alerts for cost overruns
Monitoring and Alerting
- Critical Metrics: Alert on business-critical metrics
- Noise Reduction: Fine-tune thresholds to reduce false positives
- Actionable Alerts: Ensure alerts have clear remediation steps
- Dashboard Visibility: Create dashboards for key stakeholders
- Log Retention: Balance cost and compliance needs
Security and Compliance
- Least Privilege: Grant minimum required permissions
- Audit Regularly: Review CloudTrail logs for anomalies
- Encrypt Data: Use encryption at rest and in transit
- Assess Continuously: Run security assessments frequently
- Incident Response: Have procedures for security events
Additional Resources
For detailed operational patterns and best practices, refer to the comprehensive reference:
File: references/operations-patterns.md
This reference includes:
- Cost optimization strategies
- Monitoring and alerting patterns
- Observability best practices
- Security and compliance guidelines
- Troubleshooting workflows
CloudWatch Alarms Reference
File: references/cloudwatch-alarms.md
Common alarm configurations for:
- Lambda functions
- EC2 instances
- RDS databases
- DynamoDB tables
- API Gateway
- ECS services
- Application Load Balancers
Doc Co-Authoring Workflow
This skill provides a structured workflow for guiding users through collaborative document creation. Act as an active guide, walking users through three stages: Context Gathering, Refinement & Structure, and Reader Testing.
When to Offer This Workflow
Trigger conditions:
- User mentions writing documentation: "write a doc", "draft a proposal", "create a spec", "write up"
- User mentions specific doc types: "PRD", "design doc", "decision doc", "RFC"
- User seems to be starting a substantial writing task
Initial offer: Offer the user a structured workflow for co-authoring the document. Explain the three stages:
- Context Gathering: User provides all relevant context while Claude asks clarifying questions
- Refinement & Structure: Iteratively build each section through brainstorming and editing
- Reader Testing: Test the doc with a fresh Claude (no context) to catch blind spots before others read it
Explain that this approach helps ensure the doc works well when others read it (including when they paste it into Claude). Ask if they want to try this workflow or prefer to work freeform.
If user declines, work freeform. If user accepts, proceed to Stage 1.
Stage 1: Context Gathering
Goal: Close the gap between what the user knows and what Claude knows, enabling smart guidance later.
Initial Questions
Start by asking the user for meta-context about the document:
- What type of document is this? (e.g., technical spec, decision doc, proposal)
- Who's the primary audience?
- What's the desired impact when someone reads this?
- Is there a template or specific format to follow?
- Any other constraints or context to know?
Inform them they can answer in shorthand or dump information however works best for them.
If user provides a template or mentions a doc type:
- Ask if they have a template document to share
- If they provide a link to a shared document, use the appropriate integration to fetch it
- If they provide a file, read it
If user mentions editing an existing shared document:
- Use the appropriate integration to read the current state
- Check for images without alt-text
- If images exist without alt-text, explain that when others use Claude to understand the doc, Claude won't be able to see them. Ask if they want alt-text generated. If so, request they paste each image into chat for descriptive alt-text generation.
Info Dumping
Once initial questions are answered, encourage the user to dump all the context they have. Request information such as:
- Background on the project/problem
- Related team discussions or shared documents
- Why alternative solutions aren't being used
- Organizational context (team dynamics, past incidents, politics)
- Timeline pressures or constraints
- Technical architecture or dependencies
- Stakeholder concerns
Advise them not to worry about organizing it - just get it all out. Offer multiple ways to provide context:
- Info dump stream-of-consciousness
- Point to team channels or threads to read
- Link to shared documents
If integrations are available (e.g., Slack, Teams, Google Drive, SharePoint, or other MCP servers), mention that these can be used to pull in context directly.
If no integrations are detected and in Claude.ai or Claude app: Suggest they can enable connectors in their Claude settings to allow pulling context from messaging apps and document storage directly.
Inform them clarifying questions will be asked once they've done their initial dump.
During context gathering:
-
If user mentions team channels or shared documents:
- If integrations available: Inform them the content will be read now, then use the appropriate integration
- If integrations not available: Explain lack of access. Suggest they enable connectors in Claude settings, or paste the relevant content directly.
-
If user mentions entities/projects that are unknown:
- Ask if connected tools should be searched to learn more
- Wait for user confirmation before searching
-
As user provides context, track what's being learned and what's still unclear
Asking clarifying questions:
When user signals they've done their initial dump (or after substantial context provided), ask clarifying questions to ensure understanding:
Generate 5-10 numbered questions based on gaps in the context.
Inform them they can use shorthand to answer (e.g., "1: yes, 2: see #channel, 3: no because backwards compat"), link to more docs, point to channels to read, or just keep info-dumping. Whatever's most efficient for them.
Exit condition: Sufficient context has been gathered when questions show understanding - when edge cases and trade-offs can be asked about without needing basics explained.
Transition: Ask if there's any more context they want to provide at this stage, or if it's time to move on to drafting the document.
If user wants to add more, let them. When ready, proceed to Stage 2.
Stage 2: Refinement & Structure
Goal: Build the document section by section through brainstorming, curation, and iterative refinement.
Instructions to user: Explain that the document will be built section by section. For each section:
- Clarifying questions will be asked about what to include
- 5-20 options will be brainstormed
- User will indicate what to keep/remove/combine
- The section will be drafted
- It will be refined through surgical edits
Start with whichever section has the most unknowns (usually the core decision/proposal), then work through the rest.
Section ordering:
If the document structure is clear: Ask which section they'd like to start with.
Suggest starting with whichever section has the most unknowns. For decision docs, that's usually the core proposal. For specs, it's typically the technical approach. Summary sections are best left for last.
If user doesn't know what sections they need: Based on the type of document and template, suggest 3-5 sections appropriate for the doc type.
Ask if this structure works, or if they want to adjust it.
Once structure is agreed:
Create the initial document structure with placeholder text for all sections.
If access to artifacts is available:
Use create_file to create an artifact. This gives both Claude and the user a scaffold to work from.
Inform them that the initial structure with placeholders for all sections will be created.
Create artifact with all section headers and brief placeholder text like "[To be written]" or "[Content here]".
Provide the scaffold link and indicate it's time to fill in each section.
If no access to artifacts:
Create a markdown file in the working directory. Name it appropriately (e.g., decision-doc.md, technical-spec.md).
Inform them that the initial structure with placeholders for all sections will be created.
Create file with all section headers and placeholder text.
Confirm the filename has been created and indicate it's time to fill in each section.
For each section:
Step 1: Clarifying Questions
Announce work will begin on the [SECTION NAME] section. Ask 5-10 clarifying questions about what should be included:
Generate 5-10 specific questions based on context and section purpose.
Inform them they can answer in shorthand or just indicate what's important to cover.
Step 2: Brainstorming
For the [SECTION NAME] section, brainstorm [5-20] things that might be included, depending on the section's complexity. Look for:
- Context shared that might have been forgotten
- Angles or considerations not yet mentioned
Generate 5-20 numbered options based on section complexity. At the end, offer to brainstorm more if they want additional options.
Step 3: Curation
Ask which points should be kept, removed, or combined. Request brief justifications to help learn priorities for the next sections.
Provide examples:
- "Keep 1,4,7,9"
- "Remove 3 (duplicates 1)"
- "Remove 6 (audience already knows this)"
- "Combine 11 and 12"
If user gives freeform feedback (e.g., "looks good" or "I like most of it but...") instead of numbered selections, extract their preferences and proceed. Parse what they want kept/removed/changed and apply it.
Step 4: Gap Check
Based on what they've selected, ask if there's anything important missing for the [SECTION NAME] section.
Step 5: Drafting
Use str_replace to replace the placeholder text for this section with the actual drafted content.
Announce the [SECTION NAME] section will be drafted now based on what they've selected.
If using artifacts: After drafting, provide a link to the artifact.
Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
If using a file (no artifacts): After drafting, confirm completion.
Inform them the [SECTION NAME] section has been drafted in [filename]. Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
Key instruction for user (include when drafting the first section): Provide a note: Instead of editing the doc directly, ask them to indicate what to change. This helps learning of their style for future sections. For example: "Remove the X bullet - already covered by Y" or "Make the third paragraph more concise".
Step 6: Iterative Refinement
As user provides feedback:
- Use
str_replaceto make edits (never reprint the whole doc) - If using artifacts: Provide link to artifact after each edit
- If using files: Just confirm edits are complete
- If user edits doc directly and asks to read it: mentally note the changes they made and keep them in mind for future sections (this shows their preferences)
Continue iterating until user is satisfied with the section.
Quality Checking
After 3 consecutive iterations with no substantial changes, ask if anything can be removed without losing important information.
When section is done, confirm [SECTION NAME] is complete. Ask if ready to move to the next section.
Repeat for all sections.
Near Completion
As approaching completion (80%+ of sections done), announce intention to re-read the entire document and check for:
- Flow and consistency across sections
- Redundancy or contradictions
- Anything that feels like "slop" or generic filler
- Whether every sentence carries weight
Read entire document and provide feedback.
When all sections are drafted and refined: Announce all sections are drafted. Indicate intention to review the complete document one more time.
Review for overall coherence, flow, completeness.
Provide any final suggestions.
Ask if ready to move to Reader Testing, or if they want to refine anything else.
Stage 3: Reader Testing
Goal: Test the document with a fresh Claude (no context bleed) to verify it works for readers.
Instructions to user: Explain that testing will now occur to see if the document actually works for readers. This catches blind spots - things that make sense to the authors but might confuse others.
Testing Approach
If access to sub-agents is available (e.g., in Claude Code):
Perform the testing directly without user involvement.
Step 1: Predict Reader Questions
Announce intention to predict what questions readers might ask when trying to discover this document.
Generate 5-10 questions that readers would realistically ask.
Step 2: Test with Sub-Agent
Announce that these questions will be tested with a fresh Claude instance (no context from this conversation).
For each question, invoke a sub-agent with just the document content and the question.
Summarize what Reader Claude got right/wrong for each question.
Step 3: Run Additional Checks
Announce additional checks will be performed.
Invoke sub-agent to check for ambiguity, false assumptions, contradictions.
Summarize any issues found.
Step 4: Report and Fix
If issues found: Report that Reader Claude struggled with specific issues.
List the specific issues.
Indicate intention to fix these gaps.
Loop back to refinement for problematic sections.
If no access to sub-agents (e.g., claude.ai web interface):
The user will need to do the testing manually.
Step 1: Predict Reader Questions
Ask what questions people might ask when trying to discover this document. What would they type into Claude.ai?
Generate 5-10 questions that readers would realistically ask.
Step 2: Setup Testing
Provide testing instructions:
- Open a fresh Claude conversation: https://claude.ai
- Paste or share the document content (if using a shared doc platform with connectors enabled, provide the link)
- Ask Reader Claude the generated questions
For each question, instruct Reader Claude to provide:
- The answer
- Whether anything was ambiguous or unclear
- What knowledge/context the doc assumes is already known
Check if Reader Claude gives correct answers or misinterprets anything.
Step 3: Additional Checks
Also ask Reader Claude:
- "What in this doc might be ambiguous or unclear to readers?"
- "What knowledge or context does this doc assume readers already have?"
- "Are there any internal contradictions or inconsistencies?"
Step 4: Iterate Based on Results
Ask what Reader Claude got wrong or struggled with. Indicate intention to fix those gaps.
Loop back to refinement for any problematic sections.
Exit Condition (Both Approaches)
When Reader Claude consistently answers questions correctly and doesn't surface new gaps or ambiguities, the doc is ready.
Final Review
When Reader Testing passes: Announce the doc has passed Reader Claude testing. Before completion:
- Recommend they do a final read-through themselves - they own this document and are responsible for its quality
- Suggest double-checking any facts, links, or technical details
- Ask them to verify it achieves the impact they wanted
Ask if they want one more review, or if the work is done.
If user wants final review, provide it. Otherwise: Announce document completion. Provide a few final tips:
- Consider linking this conversation in an appendix so readers can see how the doc was developed
- Use appendices to provide depth without bloating the main doc
- Update the doc as feedback is received from real readers
Tips for Effective Guidance
Tone:
- Be direct and procedural
- Explain rationale briefly when it affects user behavior
- Don't try to "sell" the approach - just execute it
Handling Deviations:
- If user wants to skip a stage: Ask if they want to skip this and write freeform
- If user seems frustrated: Acknowledge this is taking longer than expected. Suggest ways to move faster
- Always give user agency to adjust the process
Context Management:
- Throughout, if context is missing on something mentioned, proactively ask
- Don't let gaps accumulate - address them as they come up
Artifact Management:
- Use
create_filefor drafting full sections - Use
str_replacefor all edits - Provide artifact link after every change
- Never use artifacts for brainstorming lists - that's just conversation
Quality over Speed:
- Don't rush through stages
- Each iteration should make meaningful improvements
- The goal is a document that actually works for readers
Brainstorming Ideas Into Designs
Overview
Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design in small sections (200-300 words), checking after each section whether it looks right so far.
The Process
Understanding the idea:
- Check out the current project state first (files, docs, recent commits)
- Ask questions one at a time to refine the idea
- Prefer multiple choice questions when possible, but open-ended is fine too
- Only one question per message - if a topic needs more exploration, break it into multiple questions
- Focus on understanding: purpose, constraints, success criteria
Exploring approaches:
- Propose 2-3 different approaches with trade-offs
- Present options conversationally with your recommendation and reasoning
- Lead with your recommended option and explain why
Presenting the design:
- Once you believe you understand what you're building, present the design
- Break it into sections of 200-300 words
- Ask after each section whether it looks right so far
- Cover: architecture, components, data flow, error handling, testing
- Be ready to go back and clarify if something doesn't make sense
After the Design
Documentation:
- Write the validated design to
docs/plans/YYYY-MM-DD-<topic>-design.md - Use elements-of-style:writing-clearly-and-concisely skill if available
- Commit the design document to git
Implementation (if continuing):
- Ask: "Ready to set up for implementation?"
- Use superpowers:using-git-worktrees to create isolated workspace
- Use superpowers:writing-plans to create detailed implementation plan
Key Principles
- One question at a time - Don't overwhelm with multiple questions
- Multiple choice preferred - Easier to answer than open-ended when possible
- YAGNI ruthlessly - Remove unnecessary features from all designs
- Explore alternatives - Always propose 2-3 approaches before settling
- Incremental validation - Present design in sections, validate each
- Be flexible - Go back and clarify when something doesn't make sense
Shadcn UI Designer
Core Design Prompt
When designing any UI, apply this philosophy:
"Design a modern, clean UI following Shadcn principles: apply minimalism with ample white space and simple sans-serif typography; use strategic, subtle shadows for depth and hierarchy; ensure accessibility with high-contrast neutrals and scalable elements; provide beautiful defaults for buttons, cards, and forms that compose modularly; incorporate fluid, non-intrusive animations; maintain a professional palette of soft grays, whites, and minimal accents like purple; output as responsive, customizable React code with Tailwind CSS."
Design Rules
1. Typography Rule
- Limit to 2-3 font weights and sizes per screen
- Use Inter or system fonts for consistency
<h1 className="text-2xl font-semibold">Title</h1>
<p className="text-sm text-muted-foreground">Description</p>
2. Spacing Rule
- 4px-based scale: 4px, 8px, 16px, 24px, 32px
- Tailwind utilities:
p-1,p-2,p-4,p-6,p-8
<div className="p-6 space-y-4">
<div className="mb-8">...</div>
</div>
3. Color Rule
- Base on OKLCH for perceptual uniformity
- Use 50-950 scale grays (background, foreground, muted)
- Subtle accents at 10% opacity to avoid visual noise
<Card className="bg-card text-card-foreground border-border">
<Button className="bg-primary text-primary-foreground">Action</Button>
<div className="bg-primary/10">Subtle accent</div>
</Card>
4. Shadow Rule
- 3 levels only:
shadow-sm: Subtle lift (0 1px 2px) - for cardsshadow-md: Medium depth (0 4px 6px) - for dropdownsshadow-lg: High elevation (0 10px 15px) - for modals
<Card className="shadow-sm hover:shadow-md transition-shadow">
5. Animation Rule
- 200-300ms durations
- ease-in-out curves for transitions
- Subtle feedback only (hovers, state changes) - no decorative flourishes
<Button className="transition-colors duration-200 hover:bg-primary/90">
<Card className="transition-transform duration-200 hover:scale-105">
6. Accessibility Rule
- ARIA labels on all interactive elements
- WCAG 2.1 AA contrast ratios (4.5:1 minimum)
- Keyboard-focus styles matching hover states
- Semantic HTML structure
<button
aria-label="Submit form"
className="focus:ring-2 focus:ring-primary focus:outline-none"
>
Submit
</button>
Workflow
1. Interview User (if details not provided)
- Scope: Full page, section, or specific component?
- Type: Dashboard, form, card, modal, table?
- Target file: Where should this be implemented?
- Requirements: Features, interactions, data to display?
2. Design & Implement
- Match existing design - align with current UI patterns in the app
- Build UI first - complete visual interface before adding logic
- Modular components - break large pages into focused, reusable pieces
- Apply all 6 rules above strictly
- Verify accessibility - keyboard navigation, contrast, ARIA labels
- Test responsiveness - mobile, tablet, desktop
3. Component Structure Pattern
import { Button } from "@/components/ui/button"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
export function MyComponent() {
return (
<div className="container mx-auto p-6 space-y-6">
<header>
<h1 className="text-2xl font-semibold">Page Title</h1>
</header>
<main className="grid gap-4">
<Card className="shadow-sm">
<CardHeader>
<CardTitle>Section</CardTitle>
</CardHeader>
<CardContent>
{/* Content */}
</CardContent>
</Card>
</main>
</div>
)
}
4. Quality Checklist
Before completing, verify:
- Uses shadcn/ui components where applicable
- 2-3 font weights/sizes max per screen
- 4px-based spacing throughout
- Theme color variables (no hardcoded colors)
- 3 shadow levels max, strategically applied
- Animations 200-300ms with ease-in-out
- ARIA labels on interactive elements
- WCAG AA contrast ratios (4.5:1 min)
- Keyboard focus styles implemented
- Mobile-first responsive design
- Modular, reusable code structure
Common Patterns
Dashboard Page
<div className="container mx-auto p-6 space-y-6">
<header className="space-y-2">
<h1 className="text-2xl font-semibold">Dashboard</h1>
<p className="text-sm text-muted-foreground">Overview of metrics</p>
</header>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
{stats.map(stat => (
<Card key={stat.id} className="shadow-sm">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
{stat.title}
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-semibold">{stat.value}</div>
</CardContent>
</Card>
))}
</div>
</div>
Form Pattern
<form className="space-y-6">
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="name">Full Name</Label>
<Input id="name" placeholder="John Doe" />
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input id="email" type="email" placeholder="john@example.com" />
</div>
</div>
<Button type="submit" className="w-full transition-colors duration-200">
Submit
</Button>
</form>
Data Table Pattern
<Card className="shadow-sm">
<CardHeader>
<CardTitle className="text-xl font-semibold">Recent Orders</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Order ID</TableHead>
<TableHead>Customer</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{orders.map(order => (
<TableRow key={order.id} className="hover:bg-muted/50 transition-colors">
<TableCell className="font-medium">{order.id}</TableCell>
<TableCell>{order.customer}</TableCell>
<TableCell>
<Badge variant="default">{order.status}</Badge>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
Best Practices
- Match existing design - new designs align with current UI screens and components
- UI-first approach - complete visual interface before adding business logic
- Modular code - small, focused, reusable components (avoid monolithic pages)
- Token efficiency - concise, well-structured code
- Consistency - follow existing color, spacing, and typography patterns
- Composability - build with shadcn's philosophy of small components that work together
Common Shadcn Components
- Layout: Card, Tabs, Sheet, Dialog, Popover
- Forms: Input, Textarea, Select, Checkbox, Radio, Switch, Label
- Buttons: Button, Toggle, ToggleGroup
- Display: Badge, Avatar, Separator, Skeleton, Table
- Feedback: Alert, Toast, Progress
- Navigation: NavigationMenu, Dropdown, Command
References
Article Extractor
This skill extracts the main content from web articles and blog posts, removing navigation, ads, newsletter signups, and other clutter. Saves clean, readable text.
When to Use This Skill
Activate when the user:
- Provides an article/blog URL and wants the text content
- Asks to "download this article"
- Wants to "extract the content from [URL]"
- Asks to "save this blog post as text"
- Needs clean article text without distractions
How It Works
Priority Order:
- Check if tools are installed (reader or trafilatura)
- Download and extract article using best available tool
- Clean up the content (remove extra whitespace, format properly)
- Save to file with article title as filename
- Confirm location and show preview
Installation Check
Check for article extraction tools in this order:
Option 1: reader (Recommended - Mozilla's Readability)
command -v reader
If not installed:
npm install -g @mozilla/readability-cli
# or
npm install -g reader-cli
Option 2: trafilatura (Python-based, very good)
command -v trafilatura
If not installed:
pip3 install trafilatura
Option 3: Fallback (curl + simple parsing)
If no tools available, use basic curl + text extraction (less reliable but works)
Extraction Methods
Method 1: Using reader (Best for most articles)
# Extract article
reader "URL" > article.txt
Pros:
- Based on Mozilla's Readability algorithm
- Excellent at removing clutter
- Preserves article structure
Method 2: Using trafilatura (Best for blogs/news)
# Extract article
trafilatura --URL "URL" --output-format txt > article.txt
# Or with more options
trafilatura --URL "URL" --output-format txt --no-comments --no-tables > article.txt
Pros:
- Very accurate extraction
- Good with various site structures
- Handles multiple languages
Options:
--no-comments: Skip comment sections--no-tables: Skip data tables--precision: Favor precision over recall--recall: Extract more content (may include some noise)
Method 3: Fallback (curl + basic parsing)
# Download and extract basic content
curl -s "URL" | python3 -c "
from html.parser import HTMLParser
import sys
class ArticleExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.in_content = False
self.content = []
self.skip_tags = {'script', 'style', 'nav', 'header', 'footer', 'aside'}
self.current_tag = None
def handle_starttag(self, tag, attrs):
if tag not in self.skip_tags:
if tag in {'p', 'article', 'main', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'}:
self.in_content = True
self.current_tag = tag
def handle_data(self, data):
if self.in_content and data.strip():
self.content.append(data.strip())
def get_content(self):
return '\n\n'.join(self.content)
parser = ArticleExtractor()
parser.feed(sys.stdin.read())
print(parser.get_content())
" > article.txt
Note: This is less reliable but works without dependencies.
Getting Article Title
Extract title for filename:
Using reader:
# reader outputs markdown with title at top
TITLE=$(reader "URL" | head -n 1 | sed 's/^# //')
Using trafilatura:
# Get metadata including title
TITLE=$(trafilatura --URL "URL" --json | python3 -c "import json, sys; print(json.load(sys.stdin)['title'])")
Using curl (fallback):
TITLE=$(curl -s "URL" | grep -oP '<title>\K[^<]+' | sed 's/ - .*//' | sed 's/ | .*//')
Filename Creation
Clean title for filesystem:
# Get title
TITLE="Article Title from Website"
# Clean for filesystem (remove special chars, limit length)
FILENAME=$(echo "$TITLE" | tr '/' '-' | tr ':' '-' | tr '?' '' | tr '"' '' | tr '<' '' | tr '>' '' | tr '|' '-' | cut -c 1-100 | sed 's/ *$//')
# Add extension
FILENAME="${FILENAME}.txt"
Complete Workflow
ARTICLE_URL="https://example.com/article"
# Check for tools
if command -v reader &> /dev/null; then
TOOL="reader"
echo "Using reader (Mozilla Readability)"
elif command -v trafilatura &> /dev/null; then
TOOL="trafilatura"
echo "Using trafilatura"
else
TOOL="fallback"
echo "Using fallback method (may be less accurate)"
fi
# Extract article
case $TOOL in
reader)
# Get content
reader "$ARTICLE_URL" > temp_article.txt
# Get title (first line after # in markdown)
TITLE=$(head -n 1 temp_article.txt | sed 's/^# //')
;;
trafilatura)
# Get title from metadata
METADATA=$(trafilatura --URL "$ARTICLE_URL" --json)
TITLE=$(echo "$METADATA" | python3 -c "import json, sys; print(json.load(sys.stdin).get('title', 'Article'))")
# Get clean content
trafilatura --URL "$ARTICLE_URL" --output-format txt --no-comments > temp_article.txt
;;
fallback)
# Get title
TITLE=$(curl -s "$ARTICLE_URL" | grep -oP '<title>\K[^<]+' | head -n 1)
TITLE=${TITLE%% - *} # Remove site name
TITLE=${TITLE%% | *} # Remove site name (alternate)
# Get content (basic extraction)
curl -s "$ARTICLE_URL" | python3 -c "
from html.parser import HTMLParser
import sys
class ArticleExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.in_content = False
self.content = []
self.skip_tags = {'script', 'style', 'nav', 'header', 'footer', 'aside', 'form'}
def handle_starttag(self, tag, attrs):
if tag not in self.skip_tags:
if tag in {'p', 'article', 'main'}:
self.in_content = True
if tag in {'h1', 'h2', 'h3'}:
self.content.append('\n')
def handle_data(self, data):
if self.in_content and data.strip():
self.content.append(data.strip())
def get_content(self):
return '\n\n'.join(self.content)
parser = ArticleExtractor()
parser.feed(sys.stdin.read())
print(parser.get_content())
" > temp_article.txt
;;
esac
# Clean filename
FILENAME=$(echo "$TITLE" | tr '/' '-' | tr ':' '-' | tr '?' '' | tr '"' '' | tr '<>' '' | tr '|' '-' | cut -c 1-80 | sed 's/ *$//' | sed 's/^ *//')
FILENAME="${FILENAME}.txt"
# Move to final filename
mv temp_article.txt "$FILENAME"
# Show result
echo "✓ Extracted article: $TITLE"
echo "✓ Saved to: $FILENAME"
echo ""
echo "Preview (first 10 lines):"
head -n 10 "$FILENAME"
Error Handling
Common Issues
1. Tool not installed
- Try alternate tool (reader → trafilatura → fallback)
- Offer to install: "Install reader with: npm install -g reader-cli"
2. Paywall or login required
- Extraction tools may fail
- Inform user: "This article requires authentication. Cannot extract."
3. Invalid URL
- Check URL format
- Try with and without redirects
4. No content extracted
- Site may use heavy JavaScript
- Try fallback method
- Inform user if extraction fails
5. Special characters in title
- Clean title for filesystem
- Remove:
/,:,?,",<,>,| - Replace with
-or remove
Output Format
Saved File Contains:
- Article title (if available)
- Author (if available from tool)
- Main article text
- Section headings
- No navigation, ads, or clutter
What Gets Removed:
- Navigation menus
- Ads and promotional content
- Newsletter signup forms
- Related articles sidebars
- Comment sections (optional)
- Social media buttons
- Cookie notices
Tips for Best Results
1. Use reader for most articles
- Best all-around tool
- Based on Firefox Reader View
- Works on most news sites and blogs
2. Use trafilatura for:
- Academic articles
- News sites
- Blogs with complex layouts
- Non-English content
3. Fallback method limitations:
- May include some noise
- Less accurate paragraph detection
- Better than nothing for simple sites
4. Check extraction quality:
- Always show preview to user
- Ask if it looks correct
- Offer to try different tool if needed
Example Usage
Simple extraction:
# User: "Extract https://example.com/article"
reader "https://example.com/article" > temp.txt
TITLE=$(head -n 1 temp.txt | sed 's/^# //')
FILENAME="$(echo "$TITLE" | tr '/' '-').txt"
mv temp.txt "$FILENAME"
echo "✓ Saved to: $FILENAME"
With error handling:
if ! reader "$URL" > temp.txt 2>/dev/null; then
if command -v trafilatura &> /dev/null; then
trafilatura --URL "$URL" --output-format txt > temp.txt
else
echo "Error: Could not extract article. Install reader or trafilatura."
exit 1
fi
fi
Best Practices
- ✅ Always show preview after extraction (first 10 lines)
- ✅ Verify extraction succeeded before saving
- ✅ Clean filename for filesystem compatibility
- ✅ Try fallback method if primary fails
- ✅ Inform user which tool was used
- ✅ Keep filename length reasonable (< 100 chars)
After Extraction
Display to user:
- "✓ Extracted: [Article Title]"
- "✓ Saved to: [filename]"
- Show preview (first 10-15 lines)
- File size and location
Ask if needed:
- "Would you like me to also create a Ship-Learn-Next plan from this?" (if using ship-learn-next skill)
- "Should I extract another article?"
Creative Generation Agent
Build intelligent agents that generate original creative content across multiple modalities including text, music, images, memes, and podcasts.
Overview
Creative generation combines:
- Content Models: Diffusion models, transformers, GANs
- Prompt Engineering: Guide creative output
- Style Control: Maintain artistic consistency
- Quality Assessment: Evaluate creative output
- Iteration & Refinement: Improve results
Applications
- AI music composition and arrangement
- Automated meme generation
- Podcast script and audio generation
- Creative writing assistance
- Art and image generation
- Video content creation
- Game asset generation
Quick Start
Extract the code examples and utilities from the directories:
-
Examples: See
examples/directory for complete implementations:music_generation.py- Music generation and audio synthesismeme_generator.py- Image and text-based meme generationpodcast_producer.py- Podcast script and audio productionimage_generation.py- Diffusion-based image generationstyle_transfer.py- Neural style transfer
-
Utilities: See
scripts/directory for helper modules:creative_quality_assessment.py- Quality evaluationaudio_effects.py- Audio effect processingcontent_moderation.py- Safety and compliance filtering
Music Generation
1. Symbolic Music Generation
Generate music as MIDI/musical notation. See examples/music_generation.py.
Key Classes:
MusicGenerationAgent- Generates melodies and full compositions- Methods:
generate_melody(),generate_full_composition(),generate_harmony()
Usage:
from examples.music_generation import MusicGenerationAgent
agent = MusicGenerationAgent()
melody = agent.generate_melody(
seed_notes=[("C4", 1), ("E4", 1), ("G4", 1)],
length=32,
temperature=0.8
)
composition = agent.generate_full_composition(style="classical", duration_bars=32)
2. Audio Synthesis
Generate audio waveforms directly. See examples/music_generation.py.
Key Classes:
AudioSynthesisAgent- Synthesizes audio from MIDI and applies effects
Usage:
from examples.music_generation import AudioSynthesisAgent
synth = AudioSynthesisAgent(sample_rate=44100)
audio = synth.synthesize_from_midi(midi_data, duration_seconds=60)
audio = synth.add_effects(audio, effect_type="reverb")
synth.save_audio(audio, "output.wav")
Meme Generation
See examples/meme_generator.py for complete implementations.
1. Image-Based Meme Generator
Generate memes by applying captions to templates.
Key Classes:
MemeGenerationAgent- Generates image-based memes with captions- Methods:
generate_meme(),generate_caption(),apply_caption_to_template()
Usage:
from examples.meme_generator import MemeGenerationAgent
agent = MemeGenerationAgent()
meme = agent.generate_meme(topic="AI agents", meme_template="drake")
meme.save("output_meme.png")
2. Text-Based Meme Generator
Generate text-only memes in various formats.
Key Classes:
TextMemeGenerator- Generates text-based memes- Methods:
generate_text_meme(),generate_joke_meme(),generate_deep_meme()
Usage:
from examples.meme_generator import TextMemeGenerator
generator = TextMemeGenerator()
joke_meme = generator.generate_text_meme(topic="Python programming", format_type="joke")
deep_meme = generator.generate_text_meme(topic="AI", format_type="deep")
Podcast Generation
See examples/podcast_producer.py for complete implementations.
1. Script Generation
Generate podcast scripts with structure and natural conversation flow.
Key Classes:
PodcastScriptGenerator- Creates scripts from topics- Methods:
generate_episode(),generate_script(),generate_content_segments(),generate_intro(),generate_outro()
Usage:
from examples.podcast_producer import PodcastScriptGenerator
generator = PodcastScriptGenerator()
episode = generator.generate_episode(
topic="Future of AI",
duration_minutes=30,
num_hosts=2
)
print(episode["script"])
2. Audio Production
Convert scripts to audio with text-to-speech and effects.
Key Classes:
PodcastAudioProducer- Produces audio from podcast scripts- Methods:
produce_podcast(),text_to_speech(),add_background_music(),add_transitions()
Usage:
from examples.podcast_producer import PodcastAudioProducer
producer = PodcastAudioProducer()
audio = producer.produce_podcast(script_text)
Image and Art Generation
See examples/image_generation.py and examples/style_transfer.py.
1. Diffusion Model Integration
Generate images from text prompts using Stable Diffusion or similar models.
Key Classes:
ImageGenerationAgent- Generates images from text prompts- Methods:
generate_image(),enhance_prompt(),generate_variations()
Usage:
from examples.image_generation import ImageGenerationAgent
agent = ImageGenerationAgent()
image = agent.generate_image(
prompt="A futuristic city with neon lights",
style="cyberpunk",
num_inference_steps=50
)
image.save("generated_image.png")
variations = agent.generate_variations(image, num_variations=4)
2. Style Transfer
Transfer artistic style from one image to another.
Key Classes:
StyleTransferAgent- Applies style transfer between images- Methods:
transfer_style(),preprocess_image(),postprocess_image()
Usage:
from examples.style_transfer import StyleTransferAgent
agent = StyleTransferAgent()
stylized = agent.transfer_style(
content_image="photo.jpg",
style_image="monet_painting.jpg"
)
Quality Assessment
See scripts/creative_quality_assessment.py for complete implementations.
1. Creative Quality Metrics
Evaluate generated content across multiple quality dimensions.
Key Classes:
CreativeQualityAssessor- Assesses quality of all content types- Methods:
assess_content_quality(),assess_music_quality(),assess_meme_quality(),assess_image_quality()
Usage:
from scripts.creative_quality_assessment import CreativeQualityAssessor
assessor = CreativeQualityAssessor()
# Assess music quality
music_assessment = assessor.assess_content_quality(audio, content_type="music")
print(f"Overall score: {music_assessment['overall_score']}")
print(f"Metrics: {music_assessment['metrics']}")
# Assess meme quality
meme_assessment = assessor.assess_content_quality(meme, content_type="meme")
# Assess image quality
image_assessment = assessor.assess_content_quality(image, content_type="image")
Best Practices
Content Generation
- ✓ Start with clear style/mood specifications
- ✓ Use temperature wisely (0.7-0.9 for creativity, 0.3-0.5 for consistency)
- ✓ Implement iterative refinement
- ✓ Maintain seed values for reproducibility
- ✓ Test with diverse prompts
Quality Control
- ✓ Assess generated content systematically (see
creative_quality_assessment.py) - ✓ Implement human review loops
- ✓ Track quality metrics over time
- ✓ Use feedback to refine models
- ✓ Version different creative styles
Audio Processing
- ✓ Use audio effects wisely (see
audio_effects.py)- Reverb for spatial depth
- Compression for dynamic control
- EQ for frequency balance
- Fade in/out for smooth transitions
- ✓ Monitor audio levels to prevent clipping
- ✓ Mix multiple tracks appropriately
Content Moderation
- ✓ Filter inappropriate content (see
content_moderation.py) - ✓ Ensure copyright compliance
- ✓ Validate factual accuracy
- ✓ Check for bias in generation
- ✓ Implement safety guidelines
- ✓ Use strict mode for sensitive applications
Implementation Checklist
- Choose content modality (music, images, text, etc.)
- Select generation model/framework
- Implement prompt engineering
- Set up quality assessment metrics
- Create iterative refinement loop
- Build content moderation system
- Test generation across diverse inputs
- Optimize for speed/quality tradeoff
- Implement version control for outputs
- Document prompting strategies
Resources
Music Generation
- Music Transformer: https://magenta.tensorflow.org/
- MuseNet: https://openai.com/blog/musenet/
- music21: https://web.mit.edu/music21/
Image Generation
- Stable Diffusion: https://huggingface.co/runwayml/stable-diffusion-v1-5
- DALL-E: https://openai.com/dall-e/
- Midjourney: https://www.midjourney.com/
Audio Synthesis
- Jukebox: https://openai.com/research/jukebox
- Chirp: https://deepmind.google/discover/blog/chirp-universal-speech-model/
Video Generation
- Runway: https://runwayml.com/
- Pika: https://pika.art/
File Organizer
This skill acts as your personal organization assistant, helping you maintain a clean, logical file structure across your computer without the mental overhead of constant manual organization.
When to Use This Skill
- Your Downloads folder is a chaotic mess
- You can't find files because they're scattered everywhere
- You have duplicate files taking up space
- Your folder structure doesn't make sense anymore
- You want to establish better organization habits
- You're starting a new project and need a good structure
- You're cleaning up before archiving old projects
What This Skill Does
- Analyzes Current Structure: Reviews your folders and files to understand what you have
- Finds Duplicates: Identifies duplicate files across your system
- Suggests Organization: Proposes logical folder structures based on your content
- Automates Cleanup: Moves, renames, and organizes files with your approval
- Maintains Context: Makes smart decisions based on file types, dates, and content
- Reduces Clutter: Identifies old files you probably don't need anymore
How to Use
From Your Home Directory
cd ~
Then run Claude Code and ask for help:
Help me organize my Downloads folder
Find duplicate files in my Documents folder
Review my project directories and suggest improvements
Specific Organization Tasks
Organize these downloads into proper folders based on what they are
Find duplicate files and help me decide which to keep
Clean up old files I haven't touched in 6+ months
Create a better folder structure for my [work/projects/photos/etc]
Instructions
When a user requests file organization help:
-
Understand the Scope
Ask clarifying questions:
- Which directory needs organization? (Downloads, Documents, entire home folder?)
- What's the main problem? (Can't find things, duplicates, too messy, no structure?)
- Any files or folders to avoid? (Current projects, sensitive data?)
- How aggressively to organize? (Conservative vs. comprehensive cleanup)
-
Analyze Current State
Review the target directory:
# Get overview of current structure ls -la [target_directory] # Check file types and sizes find [target_directory] -type f -exec file {} \; | head -20 # Identify largest files du -sh [target_directory]/* | sort -rh | head -20 # Count file types find [target_directory] -type f | sed 's/.*\.//' | sort | uniq -c | sort -rnSummarize findings:
- Total files and folders
- File type breakdown
- Size distribution
- Date ranges
- Obvious organization issues
-
Identify Organization Patterns
Based on the files, determine logical groupings:
By Type:
- Documents (PDFs, DOCX, TXT)
- Images (JPG, PNG, SVG)
- Videos (MP4, MOV)
- Archives (ZIP, TAR, DMG)
- Code/Projects (directories with code)
- Spreadsheets (XLSX, CSV)
- Presentations (PPTX, KEY)
By Purpose:
- Work vs. Personal
- Active vs. Archive
- Project-specific
- Reference materials
- Temporary/scratch files
By Date:
- Current year/month
- Previous years
- Very old (archive candidates)
-
Find Duplicates
When requested, search for duplicates:
# Find exact duplicates by hash find [directory] -type f -exec md5 {} \; | sort | uniq -d # Find files with same name find [directory] -type f -printf '%f\n' | sort | uniq -d # Find similar-sized files find [directory] -type f -printf '%s %p\n' | sort -nFor each set of duplicates:
- Show all file paths
- Display sizes and modification dates
- Recommend which to keep (usually newest or best-named)
- Important: Always ask for confirmation before deleting
-
Propose Organization Plan
Present a clear plan before making changes:
# Organization Plan for [Directory] ## Current State - X files across Y folders - [Size] total - File types: [breakdown] - Issues: [list problems] ## Proposed Structure[Directory]/ ├── Work/ │ ├── Projects/ │ ├── Documents/ │ └── Archive/ ├── Personal/ │ ├── Photos/ │ ├── Documents/ │ └── Media/ └── Downloads/ ├── To-Sort/ └── Archive/
## Changes I'll Make 1. **Create new folders**: [list] 2. **Move files**: - X PDFs → Work/Documents/ - Y images → Personal/Photos/ - Z old files → Archive/ 3. **Rename files**: [any renaming patterns] 4. **Delete**: [duplicates or trash files] ## Files Needing Your Decision - [List any files you're unsure about] Ready to proceed? (yes/no/modify) -
Execute Organization
After approval, organize systematically:
# Create folder structure mkdir -p "path/to/new/folders" # Move files with clear logging mv "old/path/file.pdf" "new/path/file.pdf" # Rename files with consistent patterns # Example: "YYYY-MM-DD - Description.ext"Important Rules:
- Always confirm before deleting anything
- Log all moves for potential undo
- Preserve original modification dates
- Handle filename conflicts gracefully
- Stop and ask if you encounter unexpected situations
-
Provide Summary and Maintenance Tips
After organizing:
# Organization Complete! ✨ ## What Changed - Created [X] new folders - Organized [Y] files - Freed [Z] GB by removing duplicates - Archived [W] old files ## New Structure [Show the new folder tree] ## Maintenance Tips To keep this organized: 1. **Weekly**: Sort new downloads 2. **Monthly**: Review and archive completed projects 3. **Quarterly**: Check for new duplicates 4. **Yearly**: Archive old files ## Quick Commands for You ```bash # Find files modified this week find . -type f -mtime -7 # Sort downloads by type [custom command for their setup] # Find duplicates [custom command]Want to organize another folder?
Examples
Example 1: Organizing Downloads (From Justin Dielmann)
User: "My Downloads folder is a mess with 500+ files. Help me organize it."
Process:
- Analyzes Downloads folder
- Finds patterns: work docs, personal photos, installers, random PDFs
- Proposes structure:
- Downloads/
- Work/
- Personal/
- Installers/ (DMG, PKG files)
- Archive/
- ToSort/ (things needing decisions)
- Downloads/
- Asks for confirmation
- Moves files intelligently based on content and names
- Results: 500 files → 5 organized folders
Example 2: Finding and Removing Duplicates
User: "Find duplicate files in my Documents and help me decide which to keep."
Output:
# Found 23 Sets of Duplicates (156 MB total)
## Duplicate Set 1: "proposal.pdf"
- `/Documents/proposal.pdf` (2.3 MB, modified: 2024-03-15)
- `/Documents/old/proposal.pdf` (2.3 MB, modified: 2024-03-15)
- `/Desktop/proposal.pdf` (2.3 MB, modified: 2024-03-10)
**Recommendation**: Keep `/Documents/proposal.pdf` (most recent in correct location)
Delete the other 2 copies?
[Continue for all duplicates...]
Example 3: Restructuring Projects Folder
User: "Review my ~/Projects directory and suggest improvements."
Output:
# Analysis of ~/Projects
## Current Structure Issues
- Mix of active and archived projects (3+ years old)
- No consistent naming convention
- Some projects at root, others in random subfolders
- Duplicate folders (project-name, project-name-old, project-name-v2)
## Proposed Structure
Projects/ ├── Active/ │ ├── client-work/ │ ├── side-projects/ │ └── learning/ ├── Archive/ │ ├── 2022/ │ ├── 2023/ │ └── 2024/ └── Templates/
## Specific Changes
1. Move 12 projects not touched since 2022 → Archive/
2. Consolidate 4 duplicate project folders
3. Rename projects to consistent format: "client-name-project-name"
4. Create Archive for old work
Want me to implement this?
Example 4: Organizing Photos by Date
User: "Organize my photo folders by year and month."
Output: Creates structure like:
Photos/
├── 2023/
│ ├── 01-January/
│ ├── 02-February/
│ └── ...
├── 2024/
│ ├── 01-January/
│ └── ...
└── Unsorted/
Then moves photos based on EXIF data or file modification dates.
Common Organization Tasks
Downloads Cleanup
Organize my Downloads folder - move documents to Documents,
images to Pictures, keep installers separate, and archive files
older than 3 months.
Project Organization
Review my Projects folder structure and help me separate active
projects from old ones I should archive.
Duplicate Removal
Find all duplicate files in my Documents folder and help me
decide which ones to keep.
Desktop Cleanup
My Desktop is covered in files. Help me organize everything into
my Documents folder properly.
Photo Organization
Organize all photos in this folder by date (year/month) based
on when they were taken.
Work/Personal Separation
Help me separate my work files from personal files across my
Documents folder.
Pro Tips
- Start Small: Begin with one messy folder (like Downloads) to build trust
- Regular Maintenance: Run weekly cleanup on Downloads
- Consistent Naming: Use "YYYY-MM-DD - Description" format for important files
- Archive Aggressively: Move old projects to Archive instead of deleting
- Keep Active Separate: Maintain clear boundaries between active and archived work
- Trust the Process: Let Claude handle the cognitive load of where things go
Best Practices
Folder Naming
- Use clear, descriptive names
- Avoid spaces (use hyphens or underscores)
- Be specific: "client-proposals" not "docs"
- Use prefixes for ordering: "01-current", "02-archive"
File Naming
- Include dates: "2024-10-17-meeting-notes.md"
- Be descriptive: "q3-financial-report.xlsx"
- Avoid version numbers in names (use version control instead)
- Remove download artifacts: "document-final-v2 (1).pdf" → "document.pdf"
When to Archive
- Projects not touched in 6+ months
- Completed work that might be referenced later
- Old versions after migration to new systems
- Files you're hesitant to delete (archive first)
Related Use Cases
- Setting up organization for a new computer
- Preparing files for backup/archiving
- Cleaning up before storage cleanup
- Organizing shared team folders
- Structuring new project directories
Deep Research Agent
Build intelligent autonomous research agents that systematically investigate topics, evaluate sources, synthesize findings, and produce comprehensive reports.
Research Workflow
Stage 1: Research Planning
See examples/research_planner.py for ResearchPlanner:
- Define research questions
- Identify key research areas
- Plan information sources and evaluation criteria
- Create research timeline
Stage 2: Source Gathering
Gather sources from multiple channels:
- Academic databases (Google Scholar, PubMed, JSTOR)
- News sources and publications
- Industry reports and whitepapers
- Web and social media searches
- Expert interviews
Stage 3: Source Evaluation
See examples/source_evaluator.py for SourceEvaluator:
- Evaluate author expertise
- Assess publisher credibility
- Check information recency
- Identify potential biases
Stage 4: Information Extraction
Extract structured data from sources:
- Key findings and main points
- Statistics and quantitative data
- Expert opinions and perspectives
- Emerging trends
- Research gaps
Stage 5: Synthesis & Analysis
See examples/research_synthesizer.py for ResearchSynthesizer:
- Identify main conclusions
- Organize supporting evidence
- Identify conflicting viewpoints
- Detect research gaps
- Suggest future research directions
Stage 6: Report Generation
See examples/research_report_generator.py for ResearchReportGenerator:
- Generate executive summaries
- Format findings with evidence
- Present conflicting views
- Identify gaps and opportunities
- Create comprehensive reports with citations
Research Agent Implementation
Build a comprehensive research agent by:
- Creating research plans with
ResearchPlanner - Gathering sources from multiple channels
- Evaluating sources with
SourceEvaluator - Extracting structured information
- Synthesizing findings with
ResearchSynthesizer - Generating reports with
ResearchReportGenerator
Specialized Research Types
Market Research
Build market research capabilities:
- Estimate market size and growth rates
- Identify key competitors and market players
- Analyze market segments and entry barriers
- Identify opportunities and threats
- Track industry trends
Competitive Intelligence
Build competitive intelligence analysis:
- Identify direct and indirect competitors
- Analyze competitor products and pricing
- Estimate market share and positioning
- Assess strengths and weaknesses
- Track competitive strategies and moves
Literature Review
Build literature review automation:
- Search academic databases systematically
- Extract paper metadata and abstracts
- Analyze contributions and methodologies
- Identify key themes and connections
- Generate literature review synthesis
Best Practices
Research Quality
- ✓ Use multiple reliable sources
- ✓ Cross-reference findings
- ✓ Evaluate source credibility
- ✓ Identify and acknowledge biases
- ✓ Document all sources
Depth & Scope
- ✓ Define clear research questions
- ✓ Set appropriate scope
- ✓ Balance breadth and depth
- ✓ Identify research gaps
- ✓ Suggest future directions
Synthesis & Analysis
- ✓ Organize findings logically
- ✓ Present supporting evidence
- ✓ Address conflicting views
- ✓ Draw evidence-based conclusions
- ✓ Avoid unsupported claims
Tools & Technologies
Academic Search
- Google Scholar
- PubMed
- JSTOR
- ArXiv
- PapersWithCode
News & Web Search
- NewsAPI
- Bing News
- Google News
- RSS Feeds
- Social Media APIs
Data Analysis
- Pandas
- NumPy
- scikit-learn
- Statistical tools
Getting Started
- Define research question
- Create research plan
- Gather sources
- Evaluate credibility
- Extract key information
- Identify patterns
- Synthesize findings
- Generate comprehensive report
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
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
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
Vercel Production Deploy Loop
Instructions
When requested to deploy to Vercel production with automatic error fixing:
-
Initial Deployment Attempt
- Run
vercel --prodto start production deployment - Wait for deployment to complete
- Run
-
Error Detection & Analysis
- CRITICAL: Use Vercel MCP tool to fetch detailed logs:
- The MCP logs provide much more detail than CLI output
- Analyze the build logs to identify root cause:
- Build errors (TypeScript, ESLint, compilation)
- Runtime errors
- Environment variable issues
- Dependency problems
- Configuration issues
- Extract specific error messages
- CRITICAL: Use Vercel MCP tool to fetch detailed logs:
-
Error Fixing
- Make minimal, targeted fixes to resolve the specific error
-
Retry Deployment
- Run
vercel --prodagain with the fixes applied - Repeat steps until deployment succeeds
- Run
-
Success Confirmation
- Once deployment succeeds, report:
- Deployment URL
- All errors that were fixed
- Summary of changes made
- Ask if user wants to commit/push the fixes
- Once deployment succeeds, report:
Loop Exit Conditions
- ✅ Deployment succeeds
- ❌ SAME error occurs 5+ times (suggest manual intervention)
- ❌ User requests to stop
Best Practices
- Make incremental fixes rather than large refactors
- Preserve user's code style and patterns when fixing
Example Flow
User: "Deploy to production and fix any errors"
- Vercel MCP build logs are the PRIMARY source of error information
- CLI output alone is insufficient for proper error diagnosis
- Always wait for deployment to complete before fetching logs
- If errors require user input (like API keys), prompt user immediately
Theme Factory Skill
This skill provides a curated collection of professional font and color themes themes, each with carefully selected color palettes and font pairings. Once a theme is chosen, it can be applied to any artifact.
Purpose
To apply consistent, professional styling to presentation slide decks, use this skill. Each theme includes:
- A cohesive color palette with hex codes
- Complementary font pairings for headers and body text
- A distinct visual identity suitable for different contexts and audiences
Usage Instructions
To apply styling to a slide deck or other artifact:
- Show the theme showcase: Display the
theme-showcase.pdffile to allow users to see all available themes visually. Do not make any modifications to it; simply show the file for viewing. - Ask for their choice: Ask which theme to apply to the deck
- Wait for selection: Get explicit confirmation about the chosen theme
- Apply the theme: Once a theme has been chosen, apply the selected theme's colors and fonts to the deck/artifact
Themes Available
The following 10 themes are available, each showcased in theme-showcase.pdf:
- Ocean Depths - Professional and calming maritime theme
- Sunset Boulevard - Warm and vibrant sunset colors
- Forest Canopy - Natural and grounded earth tones
- Modern Minimalist - Clean and contemporary grayscale
- Golden Hour - Rich and warm autumnal palette
- Arctic Frost - Cool and crisp winter-inspired theme
- Desert Rose - Soft and sophisticated dusty tones
- Tech Innovation - Bold and modern tech aesthetic
- Botanical Garden - Fresh and organic garden colors
- Midnight Galaxy - Dramatic and cosmic deep tones
Theme Details
Each theme is defined in the themes/ directory with complete specifications including:
- Cohesive color palette with hex codes
- Complementary font pairings for headers and body text
- Distinct visual identity suitable for different contexts and audiences
Application Process
After a preferred theme is selected:
- Read the corresponding theme file from the
themes/directory - Apply the specified colors and fonts consistently throughout the deck
- Ensure proper contrast and readability
- Maintain the theme's visual identity across all slides
Create your Own Theme
To handle cases where none of the existing themes work for an artifact, create a custom theme. Based on provided inputs, generate a new theme similar to the ones above. Give the theme a similar name describing what the font/color combinations represent. Use any basic description provided to choose appropriate colors/fonts. After generating the theme, show it for review and verification. Following that, apply the theme as described above.
Systematic Debugging
Overview
Random fixes waste time and create new bugs. Quick patches mask underlying issues.
Core principle: ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
Violating the letter of this process is violating the spirit of debugging.
The Iron Law
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
If you haven't completed Phase 1, you cannot propose fixes.
When to Use
Use for ANY technical issue:
- Test failures
- Bugs in production
- Unexpected behavior
- Performance problems
- Build failures
- Integration issues
Use this ESPECIALLY when:
- Under time pressure (emergencies make guessing tempting)
- "Just one quick fix" seems obvious
- You've already tried multiple fixes
- Previous fix didn't work
- You don't fully understand the issue
Don't skip when:
- Issue seems simple (simple bugs have root causes too)
- You're in a hurry (rushing guarantees rework)
- Manager wants it fixed NOW (systematic is faster than thrashing)
The Four Phases
You MUST complete each phase before proceeding to the next.
Phase 1: Root Cause Investigation
BEFORE attempting ANY fix:
-
Read Error Messages Carefully
- Don't skip past errors or warnings
- They often contain the exact solution
- Read stack traces completely
- Note line numbers, file paths, error codes
-
Reproduce Consistently
- Can you trigger it reliably?
- What are the exact steps?
- Does it happen every time?
- If not reproducible → gather more data, don't guess
-
Check Recent Changes
- What changed that could cause this?
- Git diff, recent commits
- New dependencies, config changes
- Environmental differences
-
Gather Evidence in Multi-Component Systems
WHEN system has multiple components (CI → build → signing, API → service → database):
BEFORE proposing fixes, add diagnostic instrumentation:
For EACH component boundary: - Log what data enters component - Log what data exits component - Verify environment/config propagation - Check state at each layer Run once to gather evidence showing WHERE it breaks THEN analyze evidence to identify failing component THEN investigate that specific componentExample (multi-layer system):
# Layer 1: Workflow echo "=== Secrets available in workflow: ===" echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}" # Layer 2: Build script echo "=== Env vars in build script: ===" env | grep IDENTITY || echo "IDENTITY not in environment" # Layer 3: Signing script echo "=== Keychain state: ===" security list-keychains security find-identity -v # Layer 4: Actual signing codesign --sign "$IDENTITY" --verbose=4 "$APP"This reveals: Which layer fails (secrets → workflow ✓, workflow → build ✗)
-
Trace Data Flow
WHEN error is deep in call stack:
See
root-cause-tracing.mdin this directory for the complete backward tracing technique.Quick version:
- Where does bad value originate?
- What called this with bad value?
- Keep tracing up until you find the source
- Fix at source, not at symptom
Phase 2: Pattern Analysis
Find the pattern before fixing:
-
Find Working Examples
- Locate similar working code in same codebase
- What works that's similar to what's broken?
-
Compare Against References
- If implementing pattern, read reference implementation COMPLETELY
- Don't skim - read every line
- Understand the pattern fully before applying
-
Identify Differences
- What's different between working and broken?
- List every difference, however small
- Don't assume "that can't matter"
-
Understand Dependencies
- What other components does this need?
- What settings, config, environment?
- What assumptions does it make?
Phase 3: Hypothesis and Testing
Scientific method:
-
Form Single Hypothesis
- State clearly: "I think X is the root cause because Y"
- Write it down
- Be specific, not vague
-
Test Minimally
- Make the SMALLEST possible change to test hypothesis
- One variable at a time
- Don't fix multiple things at once
-
Verify Before Continuing
- Did it work? Yes → Phase 4
- Didn't work? Form NEW hypothesis
- DON'T add more fixes on top
-
When You Don't Know
- Say "I don't understand X"
- Don't pretend to know
- Ask for help
- Research more
Phase 4: Implementation
Fix the root cause, not the symptom:
-
Create Failing Test Case
- Simplest possible reproduction
- Automated test if possible
- One-off test script if no framework
- MUST have before fixing
- Use the
superpowers:test-driven-developmentskill for writing proper failing tests
-
Implement Single Fix
- Address the root cause identified
- ONE change at a time
- No "while I'm here" improvements
- No bundled refactoring
-
Verify Fix
- Test passes now?
- No other tests broken?
- Issue actually resolved?
-
If Fix Doesn't Work
- STOP
- Count: How many fixes have you tried?
- If < 3: Return to Phase 1, re-analyze with new information
- If ≥ 3: STOP and question the architecture (step 5 below)
- DON'T attempt Fix #4 without architectural discussion
-
If 3+ Fixes Failed: Question Architecture
Pattern indicating architectural problem:
- Each fix reveals new shared state/coupling/problem in different place
- Fixes require "massive refactoring" to implement
- Each fix creates new symptoms elsewhere
STOP and question fundamentals:
- Is this pattern fundamentally sound?
- Are we "sticking with it through sheer inertia"?
- Should we refactor architecture vs. continue fixing symptoms?
Discuss with your human partner before attempting more fixes
This is NOT a failed hypothesis - this is a wrong architecture.
Red Flags - STOP and Follow Process
If you catch yourself thinking:
- "Quick fix for now, investigate later"
- "Just try changing X and see if it works"
- "Add multiple changes, run tests"
- "Skip the test, I'll manually verify"
- "It's probably X, let me fix that"
- "I don't fully understand but this might work"
- "Pattern says X but I'll adapt it differently"
- "Here are the main problems: [lists fixes without investigation]"
- Proposing solutions before tracing data flow
- "One more fix attempt" (when already tried 2+)
- Each fix reveals new problem in different place
ALL of these mean: STOP. Return to Phase 1.
If 3+ fixes failed: Question the architecture (see Phase 4.5)
your human partner's Signals You're Doing It Wrong
Watch for these redirections:
- "Is that not happening?" - You assumed without verifying
- "Will it show us...?" - You should have added evidence gathering
- "Stop guessing" - You're proposing fixes without understanding
- "Ultrathink this" - Question fundamentals, not just symptoms
- "We're stuck?" (frustrated) - Your approach isn't working
When you see these: STOP. Return to Phase 1.
Common Rationalizations
| Excuse | Reality |
|---|---|
| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
Quick Reference
| Phase | Key Activities | Success Criteria |
|---|---|---|
| 1. Root Cause | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
| 2. Pattern | Find working examples, compare | Identify differences |
| 3. Hypothesis | Form theory, test minimally | Confirmed or new hypothesis |
| 4. Implementation | Create test, fix, verify | Bug resolved, tests pass |
When Process Reveals "No Root Cause"
If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
- You've completed the process
- Document what you investigated
- Implement appropriate handling (retry, timeout, error message)
- Add monitoring/logging for future investigation
But: 95% of "no root cause" cases are incomplete investigation.
Supporting Techniques
These techniques are part of systematic debugging and available in this directory:
root-cause-tracing.md- Trace bugs backward through call stack to find original triggerdefense-in-depth.md- Add validation at multiple layers after finding root causecondition-based-waiting.md- Replace arbitrary timeouts with condition polling
Related skills:
- superpowers:test-driven-development - For creating failing test case (Phase 4, Step 1)
- superpowers:verification-before-completion - Verify fix worked before claiming success
Real-World Impact
From debugging sessions:
- Systematic approach: 15-30 minutes to fix
- Random fixes approach: 2-3 hours of thrashing
- First-time fix rate: 95% vs 40%
- New bugs introduced: Near zero vs common
Claude Code Command Builder
Purpose
Guide users through creating effective Claude Code slash commands with proper structure, argument handling, and workflow design. Auto-invokes when users want to create or modify custom commands.
When to Use
Auto-invoke when users mention:
- Creating commands - "create command", "make command", "new slash command"
- Command structure - "command template", "command format", "command frontmatter"
- Arguments - "$ARGUMENTS", "$1", "$2", "command parameters", "positional args"
- Workflows - "command workflow", "command steps", "command process"
- Bash execution - "!
command", "execute bash in command", "command with bash"
Knowledge Base
- Official docs:
.claude/skills/ai/claude-code/docs/code_claude_com/docs_en_slash-commands.md - Project guide:
.claude/docs/creating-components.md - Examples in repository:
.claude/commands/
Process
1. Gather Requirements
Ask the user:
Let me help you create a Claude Code slash command! I need a few details:
1. **Command name** (lowercase-with-hyphens):
Example: deploy, review-pr, commit, analyze-tokens
This will be invoked as: /your-command-name
2. **What does this command do?**
Describe the workflow in 1-2 sentences.
3. **Does it need arguments?**
- None (simple prompt)
- All arguments: $ARGUMENTS
- Positional: $1, $2, $3, etc.
4. **Does it need bash execution?**
Commands that run before the slash command (e.g., !`git status`)
5. **Scope:**
- Personal (`~/.claude/commands/`) - just for you
- Project (`.claude/commands/`) - shared with team
6. **Namespace/subdirectory?**
Example: git/, deploy/, testing/
Helps organize related commands
2. Validate Input
Check the command name:
- Must be valid filename (no spaces, special chars except hyphen)
- Descriptive and memorable
- Won't conflict with built-in commands
- Use hyphens (not underscores)
Validate arguments:
- Define expected arguments
- Provide defaults if needed
- Document argument order
3. Determine Command Type
Simple Prompt (no frontmatter):
Analyze this code for performance issues and suggest optimizations.
With Arguments:
---
argument-hint: [file-path]
description: Analyze file for performance issues
---
Analyze the file at $1 for performance issues and suggest optimizations.
With Bash Execution:
---
allowed-tools: Bash(git status:*), Bash(git diff:*)
description: Create a git commit
---
## Current State
- Git status: !`git status`
- Staged changes: !`git diff --staged`
- Recent commits: !`git log --oneline -5`
## Your Task
Based on the above changes, create a git commit with a clear, conventional commit message.
Full-Featured:
---
allowed-tools: Bash(npm run:*), Bash(git add:*), Bash(git commit:*)
argument-hint: [component-name]
description: Create a new React component with tests
model: sonnet
---
# Create React Component
Component name: $1
Execute the following workflow:
1. **Validate Input**
!`test -n "$1" && echo "Creating component: $1" || echo "Error: Component name required"`
2. **Check Existing Files**
!`ls src/components/$1.tsx 2>/dev/null || echo "Component does not exist"`
3. **Create Files**
Create the following files:
- `src/components/$1.tsx`
- `src/components/$1.test.tsx`
- `src/components/$1.module.css`
4. **Run Tests**
After creation, run: !`npm run test -- $1`
4. Generate Command File
Create command structure based on complexity:
Template for Simple Command:
Brief description of what the command does.
[Prompt instructions for Claude]
Template for Command with Frontmatter:
---
argument-hint: [arg1] [arg2]
description: Brief description shown in /help
allowed-tools: Bash(command:*), Read, Write
model: sonnet
disable-model-invocation: false
---
# Command Name
Usage: /command-name [args]
[Detailed instructions]
5. Build Command Workflow
Structure the workflow with clear steps:
Execute the following workflow:
1. **Step Name**
```bash
# Bash command (if needed)
command arg1 arg2
- What this step does
- Validation checks
- Error handling
-
Next Step [Instructions for Claude]
- What to check
- How to proceed
- What to output
-
Final Step
- Summary of results
- Next actions for user
- Success criteria
### 6. Add Argument Handling
**All Arguments ($ARGUMENTS):**
```markdown
Fix issue #$ARGUMENTS following our coding standards.
User runs: /fix-issue 123 high-priority
Becomes: "Fix issue #123 high-priority following our coding standards."
Positional Arguments ($1, $2, $3):
Review PR #$1 with priority $2 and assign to $3.
Focus on: $4
User runs: /review-pr 456 high alice security
Becomes individual parameters you can reference separately.
With Defaults:
---
argument-hint: [environment] [branch]
---
Deploy to environment: ${1:-staging}
From branch: ${2:-main}
7. Add Bash Execution (if needed)
Use ! prefix to execute commands before processing:
---
allowed-tools: Bash(git:*)
---
## Context
- Current branch: !`git branch --show-current`
- Status: !`git status --short`
- Recent commits: !`git log --oneline -5`
## Your Task
[Instructions based on the above context]
Important:
- Must specify
allowed-toolswith specific Bash permissions - Output is included in command context
- Commands run before Claude processes the prompt
8. Add File References
Use @ prefix to reference files:
Review the implementation in @src/utils/helpers.js
Compare @src/old-version.js with @src/new-version.js
Analyze all files in @src/components/
9. Configure Thinking Mode (if needed)
For complex problems, trigger extended thinking:
Carefully analyze the following code and think through...
Let's approach this step by step...
Consider all edge cases before implementing...
These keywords can trigger extended thinking mode.
10. Create the File
Save to correct location:
Personal command:
~/.claude/commands/command-name.md
~/.claude/commands/category/command-name.md # With namespace
Project command:
.claude/commands/command-name.md
.claude/commands/category/command-name.md # With namespace
11. Test the Command
Provide testing instructions:
To test your command:
1. Restart Claude Code or start a new session
2. Type: /help
3. Find your command in the list
4. Try: /your-command-name [args]
5. Verify it behaves as expected
Test cases:
# No arguments
/your-command
# With arguments
/your-command arg1
/your-command arg1 arg2
# Edge cases
/your-command ""
/your-command "with spaces"
Frontmatter Reference
| Field | Purpose | Example |
|---|---|---|
argument-hint | Show expected arguments in autocomplete | [pr-number] [priority] |
description | Brief description for /help menu | Review pull request |
allowed-tools | Tools command can use | Bash(git:*), Read, Write |
model | Specific model to use | claude-sonnet-4-5-20250929 |
disable-model-invocation | Prevent SlashCommand tool from calling this | true |
Bash Tool Permissions
When using ! prefix or needing bash execution:
---
allowed-tools: Bash(git add:*), Bash(git commit:*), Bash(git push:*)
---
Permission patterns:
Bash(git:*)- All git commandsBash(npm run:*)- All npm run scriptsBash(git add:*), Bash(git commit:*)- Specific git commands
Argument Patterns
Pattern 1: All Arguments
Run tests for: $ARGUMENTS
Usage: /test users api database
Becomes: "Run tests for: users api database"
Pattern 2: Positional
Deploy $1 to $2 environment with tag $3
Usage: /deploy my-app staging v1.2.3
Becomes: "Deploy my-app to staging environment with tag v1.2.3"
Pattern 3: Mixed
---
argument-hint: <file> [rest of args]
---
Analyze file $1 for: $ARGUMENTS
Usage: /analyze src/app.js performance security
Becomes: "Analyze file src/app.js for: src/app.js performance security"
Note: $ARGUMENTS includes all args, so $1 is duplicated
Better approach:
Analyze file $1 for: ${2:+${@:2}}
This uses $1 separately and remaining args starting from $2
Pattern 4: With Defaults
Environment: ${1:-production}
Verbose: ${2:-false}
Command Size Guidelines
- ✅ Good: < 100 lines
- ⚠️ Warning: 100-150 lines
- ❌ Too large: > 250 lines (must refactor)
If too large:
- Extract to external script
- Split into multiple commands
- Use sub-commands pattern
Common Command Types
1. Git Workflow
---
allowed-tools: Bash(git:*)
description: Create conventional commit
---
## Context
- Status: !`git status --short`
- Diff: !`git diff HEAD`
Create a conventional commit message.
2. Code Generator
---
argument-hint: [component-name]
description: Generate React component
---
Create a new React component named $1:
- Component file
- Test file
- Storybook story
3. Analysis Tool
---
argument-hint: [file-path]
description: Analyze code complexity
---
Analyze @$1 for:
- Cyclomatic complexity
- Code smells
- Improvement suggestions
4. Deployment Helper
---
allowed-tools: Bash(npm:*), Bash(git:*)
argument-hint: [environment]
description: Deploy to environment
---
Deploy to ${1:-staging}:
1. Run tests: !`npm test`
2. Build: !`npm run build`
3. Deploy: !`npm run deploy:$1`
5. Documentation Generator
---
argument-hint: [file-pattern]
description: Generate API documentation
---
Generate documentation for: $1
Include:
- Function signatures
- Parameters
- Return types
- Examples
Examples from TOON Formatter
Simple version:
# Convert to TOON
Convert the specified JSON file to TOON v2.0 format with automatic optimization and show token savings.
Usage: /convert-to-toon <file>
Advanced version with bash:
---
allowed-tools: Bash(jq:*), Bash(.claude/utils/toon/zig-out/bin/toon:*)
argument-hint: <file> [--delimiter comma|tab|pipe]
description: Convert JSON to TOON format
---
# Convert to TOON
File: $1
Delimiter: ${2:-comma}
1. **Validate**: !`test -f "$1" && jq empty "$1" 2>&1`
2. **Analyze**: !`jq 'if type == "array" then length else 0 end' "$1"`
3. **Convert**: !`.claude/utils/toon/zig-out/bin/toon encode "$1"`
4. Show savings comparison
Troubleshooting
Command Not Found
Check:
# List all commands
ls ~/.claude/commands/*.md
ls .claude/commands/*.md
# Verify filename
ls .claude/commands/your-command.md
Remember:
- Filename (without
.md) becomes command name - Hyphens in filename become hyphens in command
- Case-sensitive on Linux/Mac
Arguments Not Working
Debug:
Debug: $ARGUMENTS
Debug $1: "$1"
Debug $2: "$2"
Run command and check output to see what's being passed.
Bash Commands Not Executing
Check:
allowed-toolsincludes correct Bash permissions- Using
!prefix:!command`` - Backticks are correct: `command` not 'command'
- Command is allowed by permissions
Command Not in /help
Possible reasons:
- File not in correct location
- File doesn't have
.mdextension - Syntax error in frontmatter
- Need to restart Claude Code
Best Practices
DO:
✅ Provide clear argument hints ✅ Include usage examples ✅ Handle errors gracefully ✅ Show progress for long operations ✅ Document expected behavior ✅ Test with various inputs ✅ Use descriptive command names
DON'T:
❌ Make commands too complex (>250 lines) ❌ Forget to specify allowed-tools for Bash ❌ Use unclear argument names ❌ Skip error handling ❌ Hardcode values (use arguments) ❌ Forget to test edge cases
Comparison: Commands vs Skills
Use Commands when:
- You want explicit control (manual invocation)
- Simple, repetitive prompts
- Specific workflow steps
- Frequently-used templates
Use Skills when:
- Claude should auto-detect need
- Complex, multi-file workflows
- Comprehensive domain knowledge
- Team needs standardized expertise
Can use both:
- Command invokes skill explicitly
- Skill activates automatically
- Command provides quick access
- Skill provides deep capability
Resources
- Official Command Docs:
.claude/skills/ai/claude-code/docs/code_claude_com/docs_en_slash-commands.md - Project Component Guide:
.claude/docs/creating-components.md - Command Examples:
.claude/commands/directory - Skills vs Commands: Section in slash-commands.md
Meeting Insights Analyzer
This skill transforms your meeting transcripts into actionable insights about your communication patterns, helping you become a more effective communicator and leader.
When to Use This Skill
- Analyzing your communication patterns across multiple meetings
- Getting feedback on your leadership and facilitation style
- Identifying when you avoid difficult conversations
- Understanding your speaking habits and filler words
- Tracking improvement in communication skills over time
- Preparing for performance reviews with concrete examples
- Coaching team members on their communication style
What This Skill Does
-
Pattern Recognition: Identifies recurring behaviors across meetings like:
- Conflict avoidance or indirect communication
- Speaking ratios and turn-taking
- Question-asking vs. statement-making patterns
- Active listening indicators
- Decision-making approaches
-
Communication Analysis: Evaluates communication effectiveness:
- Clarity and directness
- Use of filler words and hedging language
- Tone and sentiment patterns
- Meeting control and facilitation
-
Actionable Feedback: Provides specific, timestamped examples with:
- What happened
- Why it matters
- How to improve
-
Trend Tracking: Compares patterns over time when analyzing multiple meetings
How to Use
Basic Setup
- Download your meeting transcripts to a folder (e.g.,
~/meetings/) - Navigate to that folder in Claude Code
- Ask for the analysis you want
Quick Start Examples
Analyze all meetings in this folder and tell me when I avoided conflict.
Look at my meetings from the past month and identify my communication patterns.
Compare my facilitation style between these two meeting folders.
Advanced Analysis
Analyze all transcripts in this folder and:
1. Identify when I interrupted others
2. Calculate my speaking ratio
3. Find moments I avoided giving direct feedback
4. Track my use of filler words
5. Show examples of good active listening
Instructions
When a user requests meeting analysis:
-
Discover Available Data
- Scan the folder for transcript files (.txt, .md, .vtt, .srt, .docx)
- Check if files contain speaker labels and timestamps
- Confirm the date range of meetings
- Identify the user's name/identifier in transcripts
-
Clarify Analysis Goals
If not specified, ask what they want to learn:
- Specific behaviors (conflict avoidance, interruptions, filler words)
- Communication effectiveness (clarity, directness, listening)
- Meeting facilitation skills
- Speaking patterns and ratios
- Growth areas for improvement
-
Analyze Patterns
For each requested insight:
Conflict Avoidance:
- Look for hedging language ("maybe", "kind of", "I think")
- Indirect phrasing instead of direct requests
- Changing subject when tension arises
- Agreeing without commitment ("yeah, but...")
- Not addressing obvious problems
Speaking Ratios:
- Calculate percentage of meeting spent speaking
- Count interruptions (by and of the user)
- Measure average speaking turn length
- Track question vs. statement ratios
Filler Words:
- Count "um", "uh", "like", "you know", "actually", etc.
- Note frequency per minute or per speaking turn
- Identify situations where they increase (nervous, uncertain)
Active Listening:
- Questions that reference others' previous points
- Paraphrasing or summarizing others' ideas
- Building on others' contributions
- Asking clarifying questions
Leadership & Facilitation:
- Decision-making approach (directive vs. collaborative)
- How disagreements are handled
- Inclusion of quieter participants
- Time management and agenda control
- Follow-up and action item clarity
-
Provide Specific Examples
For each pattern found, include:
### [Pattern Name] **Finding**: [One-sentence summary of the pattern] **Frequency**: [X times across Y meetings] **Examples**: 1. **[Meeting Name/Date]** - [Timestamp] **What Happened**: > [Actual quote from transcript] **Why This Matters**: [Explanation of the impact or missed opportunity] **Better Approach**: [Specific alternative phrasing or behavior] [Repeat for 2-3 strongest examples] -
Synthesize Insights
After analyzing all patterns, provide:
# Meeting Insights Summary **Analysis Period**: [Date range] **Meetings Analyzed**: [X meetings] **Total Duration**: [X hours] ## Key Patterns Identified ### 1. [Primary Pattern] - **Observed**: [What you saw] - **Impact**: [Why it matters] - **Recommendation**: [How to improve] ### 2. [Second Pattern] [Same structure] ## Communication Strengths 1. [Strength 1 with example] 2. [Strength 2 with example] 3. [Strength 3 with example] ## Growth Opportunities 1. **[Area 1]**: [Specific, actionable advice] 2. **[Area 2]**: [Specific, actionable advice] 3. **[Area 3]**: [Specific, actionable advice] ## Speaking Statistics - Average speaking time: [X% of meeting] - Questions asked: [X per meeting average] - Filler words: [X per minute] - Interruptions: [X given / Y received per meeting] ## Next Steps [3-5 concrete actions to improve communication] -
Offer Follow-Up Options
- Track these same metrics in future meetings
- Deep dive into specific meetings or patterns
- Compare to industry benchmarks
- Create a personal communication development plan
- Generate a summary for performance reviews
Examples
Example 1: Conflict Avoidance Analysis (Inspired by Dan Shipper)
User: "I download all of my meeting recordings and put them in a folder. Tell me all the times I've subtly avoided conflict."
Output:
# Conflict Avoidance Patterns
Found 23 instances across 15 meetings where you used indirect
communication or avoided addressing tensions directly.
## Pattern: Hedging on Critical Feedback
**Frequency**: 8 times across 7 meetings
**Example 1: 1:1 with Sarah** - 00:14:32
**What Happened**:
> "So, I was thinking... maybe we could, like, potentially
> consider looking at the timeline again? I mean, if you
> think that makes sense. But whatever you think is best!"
**Why This Matters**:
You needed to address that Sarah's project was behind schedule,
but the hedging language ("maybe", "potentially", "if you think")
and the deflection at the end ("whatever you think") made it easy
for her to miss the urgency.
**Better Approach**:
"Sarah, the project is two weeks behind schedule. We need to
discuss what's blocking progress and create a new timeline
today."
[Additional examples...]
## Recommendations
1. **Name the issue directly** in the first sentence
2. **Remove hedging words** like "maybe," "kind of," "sort of"
3. **Ask specific questions** instead of hinting
4. **Schedule difficult conversations** instead of raising them casually
Example 2: Leadership Facilitation
User: "Analyze my team meetings and tell me about my facilitation style."
Output: Provides insights on:
- How much you speak vs. team members (60% vs. 40%)
- Whether you ask questions or make statements (3:1 ratio)
- How you handle disagreements (tendency to resolve too quickly)
- Who speaks least and whether you draw them in
- Examples of good and missed facilitation moments
Example 3: Personal Development Tracking
User: "Compare my meetings from Q1 vs. Q2 to see if I've improved my listening skills."
Output: Creates a comparative analysis showing:
- Decrease in interruptions (8 per meeting → 3 per meeting)
- Increase in clarifying questions (2 → 7 per meeting)
- Improvement in building on others' ideas
- Specific examples showing the difference
- Remaining areas for growth
Setup Tips
Getting Meeting Transcripts
From Granola (free with Lenny's newsletter subscription):
- Granola auto-transcribes your meetings
- Export transcripts to a folder: [Instructions on how]
- Point Claude Code to that folder
From Zoom:
- Enable cloud recording with transcription
- Download VTT or SRT files after meetings
- Store in a dedicated folder
From Google Meet:
- Use Google Docs auto-transcription
- Save transcript docs to a folder
- Download as .txt files or give Claude Code access
From Fireflies.ai, Otter.ai, etc.:
- Export transcripts in bulk
- Store in a local folder
- Run analysis on the folder
Best Practices
- Consistent naming: Use
YYYY-MM-DD - Meeting Name.txtformat - Regular analysis: Review monthly or quarterly for trends
- Specific queries: Ask about one behavior at a time for depth
- Privacy: Keep sensitive meeting data local
- Action-oriented: Focus on one improvement area at a time
Common Analysis Requests
- "When do I avoid difficult conversations?"
- "How often do I interrupt others?"
- "What's my speaking vs. listening ratio?"
- "Do I ask good questions?"
- "How do I handle disagreement?"
- "Am I inclusive of all voices?"
- "Do I use too many filler words?"
- "How clear are my action items?"
- "Do I stay on agenda or get sidetracked?"
- "How has my communication changed over time?"
Related Use Cases
- Creating a personal development plan from insights
- Preparing performance review materials with examples
- Coaching direct reports on their communication
- Analyzing customer calls for sales or support patterns
- Studying negotiation tactics and outcomes
Dispatching Parallel Agents
Overview
When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.
Core principle: Dispatch one agent per independent problem domain. Let them work concurrently.
When to Use
digraph when_to_use {
"Multiple failures?" [shape=diamond];
"Are they independent?" [shape=diamond];
"Single agent investigates all" [shape=box];
"One agent per problem domain" [shape=box];
"Can they work in parallel?" [shape=diamond];
"Sequential agents" [shape=box];
"Parallel dispatch" [shape=box];
"Multiple failures?" -> "Are they independent?" [label="yes"];
"Are they independent?" -> "Single agent investigates all" [label="no - related"];
"Are they independent?" -> "Can they work in parallel?" [label="yes"];
"Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
"Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
}
Use when:
- 3+ test files failing with different root causes
- Multiple subsystems broken independently
- Each problem can be understood without context from others
- No shared state between investigations
Don't use when:
- Failures are related (fix one might fix others)
- Need to understand full system state
- Agents would interfere with each other
The Pattern
1. Identify Independent Domains
Group failures by what's broken:
- File A tests: Tool approval flow
- File B tests: Batch completion behavior
- File C tests: Abort functionality
Each domain is independent - fixing tool approval doesn't affect abort tests.
2. Create Focused Agent Tasks
Each agent gets:
- Specific scope: One test file or subsystem
- Clear goal: Make these tests pass
- Constraints: Don't change other code
- Expected output: Summary of what you found and fixed
3. Dispatch in Parallel
// In Claude Code / AI environment
Task("Fix agent-tool-abort.test.ts failures")
Task("Fix batch-completion-behavior.test.ts failures")
Task("Fix tool-approval-race-conditions.test.ts failures")
// All three run concurrently
4. Review and Integrate
When agents return:
- Read each summary
- Verify fixes don't conflict
- Run full test suite
- Integrate all changes
Agent Prompt Structure
Good agent prompts are:
- Focused - One clear problem domain
- Self-contained - All context needed to understand the problem
- Specific about output - What should the agent return?
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:
1. "should abort tool with partial output capture" - expects 'interrupted at' in message
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
3. "should properly track pendingToolCount" - expects 3 results but gets 0
These are timing/race condition issues. Your task:
1. Read the test file and understand what each test verifies
2. Identify root cause - timing issues or actual bugs?
3. Fix by:
- Replacing arbitrary timeouts with event-based waiting
- Fixing bugs in abort implementation if found
- Adjusting test expectations if testing changed behavior
Do NOT just increase timeouts - find the real issue.
Return: Summary of what you found and what you fixed.
Common Mistakes
❌ Too broad: "Fix all the tests" - agent gets lost ✅ Specific: "Fix agent-tool-abort.test.ts" - focused scope
❌ No context: "Fix the race condition" - agent doesn't know where ✅ Context: Paste the error messages and test names
❌ No constraints: Agent might refactor everything ✅ Constraints: "Do NOT change production code" or "Fix tests only"
❌ Vague output: "Fix it" - you don't know what changed ✅ Specific: "Return summary of root cause and changes"
When NOT to Use
Related failures: Fixing one might fix others - investigate together first Need full context: Understanding requires seeing entire system Exploratory debugging: You don't know what's broken yet Shared state: Agents would interfere (editing same files, using same resources)
Real Example from Session
Scenario: 6 test failures across 3 files after major refactoring
Failures:
- agent-tool-abort.test.ts: 3 failures (timing issues)
- batch-completion-behavior.test.ts: 2 failures (tools not executing)
- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)
Decision: Independent domains - abort logic separate from batch completion separate from race conditions
Dispatch:
Agent 1 → Fix agent-tool-abort.test.ts
Agent 2 → Fix batch-completion-behavior.test.ts
Agent 3 → Fix tool-approval-race-conditions.test.ts
Results:
- Agent 1: Replaced timeouts with event-based waiting
- Agent 2: Fixed event structure bug (threadId in wrong place)
- Agent 3: Added wait for async tool execution to complete
Integration: All fixes independent, no conflicts, full suite green
Time saved: 3 problems solved in parallel vs sequentially
Key Benefits
- Parallelization - Multiple investigations happen simultaneously
- Focus - Each agent has narrow scope, less context to track
- Independence - Agents don't interfere with each other
- Speed - 3 problems solved in time of 1
Verification
After agents return:
- Review each summary - Understand what changed
- Check for conflicts - Did agents edit same code?
- Run full suite - Verify all fixes work together
- Spot check - Agents can make systematic errors
Real-World Impact
From debugging session (2025-10-03):
- 6 failures across 3 files
- 3 agents dispatched in parallel
- All investigations completed concurrently
- All fixes integrated successfully
- Zero conflicts between agent changes
Document Chat Interface
Build intelligent chat interfaces that allow users to query and interact with documents using natural language, transforming static documents into interactive knowledge sources.
Overview
A document chat interface combines three capabilities:
- Document Processing - Extract and prepare documents
- Semantic Understanding - Understand questions and find relevant content
- Conversational Interface - Maintain context and provide natural responses
Common Applications
- PDF Q&A: Answer questions about research papers, reports, books
- Email Search: Find information in email archives conversationally
- GitHub Explorer: Ask questions about code repositories
- Knowledge Base: Interactive access to company documentation
- Contract Review: Query legal documents with natural language
- Research Assistant: Explore academic papers interactively
Architecture
Document Source
↓
Document Processor
├→ Extract text
├→ Process content
└→ Generate embeddings
↓
Vector Database
↓
Chat Interface ← User Question
├→ Retrieve relevant content
├→ Maintain conversation history
└→ Generate response
Core Components
1. Document Sources
See examples/document_processors.py for implementations:
PDF Documents
- Extract text from PDF pages
- Preserve document structure and metadata
- Handle scanned PDFs with OCR (pytesseract)
- Extract tables (pdfplumber)
GitHub Repositories
- Extract code files from repositories
- Parse repository structure
- Process multiple file types
Email Archives
- Extract email metadata (from, to, subject, date)
- Parse email body content
- Handle multiple mailbox formats
Web Pages
- Extract page text and structure
- Preserve heading hierarchy
- Extract links and navigation
YouTube/Audio
- Get transcripts from YouTube videos
- Transcribe audio files
- Handle multiple formats
2. Document Processing
See examples/text_processor.py for implementations:
Text Extraction & Cleaning
- Remove extra whitespace and special characters
- Smart text chunking with overlap
- Intelligent sentence boundary detection
Metadata Extraction
- Extract title, author, date, language
- Calculate word count and document statistics
- Track document source and format
Structure Preservation
- Keep heading hierarchy in chunks
- Preserve section context
- Enable hierarchical retrieval
3. Chat Interface Design
See examples/conversation_manager.py for implementations:
Conversation Management
- Maintain conversation history with size limits
- Track message metadata (timestamps, roles)
- Provide context for LLM integration
- Clear history as needed
Question Refinement
- Expand implicit references in questions
- Handle pronouns and context references
- Improve question clarity with previous context
Response Generation
- Use document context for answering
- Maintain conversation history in prompts
- Provide source citations
- Handle out-of-scope questions
4. User Experience Features
Citation & Sources
def format_response_with_citations(response: str, sources: List[Dict]) -> str:
"""Add source citations to response"""
formatted = response + "\n\n**Sources:**\n"
for i, source in enumerate(sources, 1):
formatted += f"[{i}] Page {source['page']} of {source['source']}\n"
if 'excerpt' in source:
formatted += f" \"{source['excerpt'][:100]}...\"\n"
return formatted
Clarifying Questions
def generate_follow_up_questions(context: str, response: str) -> List[str]:
"""Suggest follow-up questions to user"""
prompt = f"""
Based on this Q&A, generate 3 relevant follow-up questions:
Context: {context[:500]}
Response: {response[:500]}
"""
follow_ups = llm.generate(prompt)
return follow_ups
Error Handling
def handle_query_failure(question: str, error: Exception) -> str:
"""Handle when no relevant documents found"""
if isinstance(error, NoRelevantDocuments):
return (
"I couldn't find information about that in the documents. "
"Try asking about different topics like: "
+ ", ".join(get_main_topics())
)
elif isinstance(error, ContextTooLarge):
return (
"The answer requires too much context. "
"Can you be more specific about what you'd like to know?"
)
else:
return f"I encountered an issue: {str(error)[:100]}"
Implementation Frameworks
Using LangChain
from langchain.document_loaders import PDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationalRetrievalChain
# Load document
loader = PDFLoader("document.pdf")
documents = loader.load()
# Split into chunks
splitter = CharacterTextSplitter(chunk_size=1000)
chunks = splitter.split_documents(documents)
# Create embeddings
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(chunks, embeddings)
# Create chat chain
llm = ChatOpenAI(model="gpt-4")
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
return_source_documents=True
)
# Chat interface
chat_history = []
while True:
question = input("You: ")
result = qa({"question": question, "chat_history": chat_history})
print(f"Assistant: {result['answer']}")
chat_history.append((question, result['answer']))
Using LlamaIndex
from llama_index import GPTVectorStoreIndex, SimpleDirectoryReader, ChatMemoryBuffer
from llama_index.llms import ChatMessage, MessageRole
# Load documents
documents = SimpleDirectoryReader("./docs").load_data()
# Create index
index = GPTVectorStoreIndex.from_documents(documents)
# Create chat engine with memory
chat_engine = index.as_chat_engine(
memory=ChatMemoryBuffer.from_defaults(token_limit=3900),
llm="gpt-4"
)
# Chat loop
while True:
question = input("You: ")
response = chat_engine.chat(question)
print(f"Assistant: {response}")
Using RAG-Based Approach
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
# Load and embed documents
model = SentenceTransformer('all-MiniLM-L6-v2')
documents = load_documents("document.pdf")
embeddings = model.encode(documents)
# Create FAISS index
dimension = embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(np.array(embeddings).astype('float32'))
# Chat function
def chat(question):
# Embed question
q_embedding = model.encode(question)
# Retrieve documents
k = 5
distances, indices = index.search(
np.array([q_embedding]).astype('float32'), k
)
# Get relevant documents
context = " ".join([documents[i] for i in indices[0]])
# Generate response
response = llm.generate(
f"Context: {context}\nQuestion: {question}\nAnswer:"
)
return response
Best Practices
Document Handling
- ✓ Support multiple formats (PDF, TXT, docx, etc.)
- ✓ Handle large documents efficiently
- ✓ Preserve document structure
- ✓ Extract metadata
- ✓ Handle multiple languages
- ✓ Implement OCR for scanned PDFs
Conversation Quality
- ✓ Maintain conversation context
- ✓ Ask clarifying questions
- ✓ Cite sources
- ✓ Handle ambiguity
- ✓ Suggest follow-up questions
- ✓ Handle out-of-scope questions
Performance
- ✓ Optimize retrieval speed
- ✓ Implement caching
- ✓ Handle large document sets
- ✓ Batch process documents
- ✓ Monitor latency
- ✓ Implement pagination
User Experience
- ✓ Clear response formatting
- ✓ Ability to cite sources
- ✓ Document browser/explorer
- ✓ Search suggestions
- ✓ Query history
- ✓ Export conversations
Common Challenges & Solutions
Challenge: Irrelevant Answers
Solutions:
- Improve retrieval (more context, better embeddings)
- Validate answer against context
- Ask clarifying questions
- Implement confidence scoring
- Use hybrid search
Challenge: Lost Context Across Turns
Solutions:
- Maintain conversation memory
- Update retrieval based on history
- Summarize long conversations
- Re-weight previous queries
Challenge: Handling Long Documents
Solutions:
- Hierarchical chunking
- Summarize first
- Question refinement
- Multi-hop retrieval
- Document navigation
Challenge: Limited Context Window
Solutions:
- Compress retrieved context
- Use document summarization
- Hierarchical retrieval
- Focus on most relevant sections
- Iterative refinement
Advanced Features
Multi-Document Analysis
def compare_documents(question: str, documents: List[str]):
"""Analyze and compare across multiple documents"""
results = []
for doc in documents:
response = query_document(doc, question)
results.append({
"document": doc.name,
"answer": response
})
# Compare and synthesize
comparison = llm.generate(
f"Compare these answers: {results}"
)
return comparison
Interactive Document Exploration
class DocumentExplorer:
def __init__(self, documents):
self.documents = documents
def browse_by_topic(self, topic):
"""Find documents by topic"""
pass
def get_related_documents(self, doc_id):
"""Find similar documents"""
pass
def get_key_terms(self, document):
"""Extract key terms and concepts"""
pass
Resources
Document Processing Libraries
- PyPDF: PDF handling
- python-docx: Word document handling
- BeautifulSoup: Web scraping
- youtube-transcript-api: YouTube transcripts
Chat Frameworks
- LangChain: Comprehensive framework
- LlamaIndex: Document-focused
- RAG libraries: Vector DB integration
Implementation Checklist
- Choose document source(s) to support
- Implement document loading and processing
- Set up vector database/embeddings
- Build chat interface
- Implement conversation management
- Add source citation
- Handle edge cases (large docs, OCR, etc.)
- Implement error handling
- Add performance monitoring
- Test with real documents
- Deploy and monitor
Getting Started
- Start Simple: Single PDF, basic chat
- Add Features: Multi-document, conversation history
- Improve Quality: Better chunking, retrieval
- Scale: Support more formats, larger documents
- Polish: UX improvements, error handling
Domain Name Brainstormer
This skill helps you find the perfect domain name for your project by generating creative options and checking what's actually available to register.
When to Use This Skill
- Starting a new project or company
- Launching a product or service
- Creating a personal brand or portfolio site
- Rebranding an existing project
- Registering a domain for a side project
- Finding available alternatives when your first choice is taken
What This Skill Does
- Understands Your Project: Analyzes what you're building and who it's for
- Generates Creative Names: Creates relevant, memorable domain options
- Checks Availability: Verifies which domains are actually available across multiple TLDs
- Multiple Extensions: Suggests .com, .io, .dev, .ai, .app, and more
- Provides Alternatives: Offers variations if top choices are taken
- Branding Insights: Explains why certain names work well
How to Use
Basic Brainstorming
I'm building a project management tool for remote teams.
Suggest domain names.
Help me brainstorm domain names for a personal finance app
Specific Preferences
I need a domain name for my AI writing assistant.
Prefer short names with .ai or .io extension.
With Keywords
Suggest domain names using the words "pixel" or "studio"
for my design agency
Example
User: "I'm building a tool for developers to share code snippets. Suggest creative domain names."
Output:
Analyzing your project...
Target audience: Developers
Key features: Code sharing, snippets, collaboration
🎯 Domain Name Suggestions
## Available (.com)
1. ✓ snippetbox.com - Clear, memorable, available!
Why: Directly describes the product, easy to remember
2. ✓ codeclip.com - Short and snappy
Why: Implies quick code sharing, only 8 characters
3. ✓ devpaste.com - Developer-focused
Why: Familiar to devs (like pastebin), clear purpose
## Available (Alternative TLDs)
4. ✓ snippet.dev - Perfect extension for developers
Why: .dev extension signals developer tool
5. ✓ codebox.io - Tech-forward
Why: .io popular with tech startups, clean name
6. ✓ sharecode.app - Descriptive
Why: .app extension, clearly states the action
## Premium/Taken (.com)
- codeshare.com (Taken, est. $2,500)
- snippets.com (Taken, premium domain)
## Recommendations
🏆 Top Pick: snippet.dev
- Perfect for developer audience
- Short and memorable
- .dev extension adds credibility
- Available now!
🥈 Runner-up: snippetbox.com
- .com is universally recognized
- Slightly longer but descriptive
- Great brandability
Next steps:
1. Register your favorite before someone else does!
2. Want me to check more variations?
3. Need help with logo ideas for these names?
Inspired by: Ben Aiad's use case from Lenny's Newsletter
Domain Naming Tips
What Makes a Good Domain
✓ Short: Under 15 characters ideal ✓ Memorable: Easy to recall and spell ✓ Pronounceable: Can be said in conversation ✓ Descriptive: Hints at what you do ✓ Brandable: Unique enough to stand out ✓ No hyphens: Easier to share verbally
TLD Guide
- .com: Universal, trusted, great for businesses
- .io: Tech startups, developer tools
- .dev: Developer-focused products
- .ai: AI/ML products
- .app: Mobile or web applications
- .co: Alternative to .com
- .xyz: Modern, creative projects
- .design: Creative/design agencies
- .tech: Technology companies
Advanced Features
Check Similar Variations
Check availability for "codebase" and similar variations
across .com, .io, .dev
Industry-Specific
Suggest domain names for a sustainable fashion brand,
checking .eco and .fashion TLDs
Multilingual Options
Brainstorm domain names in English and Spanish for
a language learning app
Competitor Analysis
Show me domain patterns used by successful project
management tools, then suggest similar available ones
Example Workflows
Startup Launch
- Describe your startup idea
- Get 10-15 domain suggestions across TLDs
- Review availability and pricing
- Pick top 3 favorites
- Register immediately
Personal Brand
- Share your name and profession
- Get variations (firstname.com, firstnamelastname.dev, etc.)
- Check social media handle availability too
- Register consistent brand across platforms
Product Naming
- Describe product and target market
- Get creative, brandable names
- Check trademark conflicts
- Verify domain and social availability
- Test names with target audience
Tips for Success
- Act Fast: Good domains get taken quickly
- Register Variations: Get .com and .io to protect brand
- Avoid Numbers: Hard to communicate verbally
- Check Social Media: Make sure @username is available too
- Say It Out Loud: Test if it's easy to pronounce
- Check Trademarks: Ensure no legal conflicts
- Think Long-term: Will it still make sense in 5 years?
Pricing Context
When suggesting domains, I'll note:
- Standard domains: ~$10-15/year
- Premium TLDs (.io, .ai): ~$30-50/year
- Taken domains: Market price if listed
- Premium domains: $hundreds to $thousands
Related Tools
After picking a domain:
- Check logo design options
- Verify social media handles
- Research trademark availability
- Plan brand identity colors/fonts
Shopify Development Expert
Purpose
Provide comprehensive, accurate guidance for building on Shopify's platform based on 24+ official documentation files. Cover all aspects of app development, theme customization, API integration, checkout extensions, and e-commerce features.
Documentation Coverage
Full access to official Shopify documentation (when available):
- Location:
docs/shopify/ - Files: 25 markdown files
- Coverage: Complete API reference, guides, best practices, and implementation patterns
Note: Documentation must be pulled separately:
pipx install docpull
docpull https://shopify.dev/docs -o .claude/skills/shopify/docs
Major Areas:
- GraphQL Admin API (products, orders, customers, inventory)
- Storefront API (cart, checkout, customer accounts)
- REST Admin API (legacy support)
- App development (authentication, webhooks, extensions)
- Theme development (Liquid, sections, blocks)
- Headless commerce (Hydrogen, Oxygen)
- Checkout customization (UI extensions, validation)
- Shopify Functions (discounts, delivery, payments)
- POS extensions (in-person sales)
- Subscriptions and selling plans
- Metafields and custom data
- Shopify Flow automation
- CLI and development tools
- Privacy and compliance
- Performance optimization
When to Use
Invoke when user mentions:
- Platform: Shopify, e-commerce, online store, merchant
- APIs: GraphQL, REST, Storefront API, Admin API
- Products: product management, collections, variants, inventory
- Orders: order processing, fulfillment, shipping
- Customers: customer data, accounts, authentication
- Checkout: checkout customization, payment methods, delivery options
- Themes: Liquid templates, theme development, sections, blocks
- Apps: app development, extensions, webhooks, OAuth
- Headless: Hydrogen, React, headless commerce, Oxygen
- Functions: Shopify Functions, custom logic, discounts
- Subscriptions: recurring billing, selling plans, subscriptions
- Tools: Shopify CLI, development workflow
- POS: point of sale, retail, in-person payments
How to Use Documentation
When answering questions:
-
Search for specific topics:
# Use Grep to find relevant docs grep -r "checkout" .claude/skills/shopify/docs/ --include="*.md" -
Read specific documentation:
# API docs cat .claude/skills/shopify/docs/shopify/api-admin-graphql.md cat .claude/skills/shopify/docs/shopify/api-storefront.md -
Find implementation guides:
# List all guides ls .claude/skills/shopify/docs/shopify/
Core Authentication
OAuth 2.0 Flow
// Redirect to Shopify OAuth
const authUrl = `https://${shop}/admin/oauth/authorize?` +
`client_id=${process.env.SHOPIFY_API_KEY}&` +
`scope=read_products,write_products&` +
`redirect_uri=${redirectUri}&` +
`state=${nonce}`;
// Exchange code for access token
const response = await fetch(
`https://${shop}/admin/oauth/access_token`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: process.env.SHOPIFY_API_KEY,
client_secret: process.env.SHOPIFY_API_SECRET,
code
})
}
);
const { access_token } = await response.json();
Session Tokens (Modern Embedded Apps)
import { shopifyApi } from '@shopify/shopify-api';
const shopify = shopifyApi({
apiKey: process.env.SHOPIFY_API_KEY,
apiSecretKey: process.env.SHOPIFY_API_SECRET,
scopes: ['read_products', 'write_products'],
hostName: process.env.HOST,
isEmbeddedApp: true,
});
GraphQL Admin API
Query Products
query {
products(first: 10) {
edges {
node {
id
title
handle
priceRange {
minVariantPrice {
amount
currencyCode
}
}
variants(first: 5) {
edges {
node {
id
sku
inventoryQuantity
}
}
}
}
}
}
}
Create Product
mutation {
productCreate(input: {
title: "New Product"
vendor: "My Store"
productType: "Apparel"
variants: [{
price: "29.99"
sku: "PROD-001"
}]
}) {
product {
id
title
}
userErrors {
field
message
}
}
}
Fetch Orders
query {
orders(first: 25, query: "fulfillment_status:unfulfilled") {
edges {
node {
id
name
createdAt
totalPriceSet {
shopMoney {
amount
currencyCode
}
}
customer {
email
}
lineItems(first: 10) {
edges {
node {
title
quantity
}
}
}
}
}
}
}
Storefront API
Create Cart
mutation {
cartCreate(input: {
lines: [{
merchandiseId: "gid://shopify/ProductVariant/123"
quantity: 1
}]
}) {
cart {
id
checkoutUrl
cost {
totalAmount {
amount
currencyCode
}
}
}
}
}
Update Cart
mutation {
cartLinesUpdate(
cartId: "gid://shopify/Cart/xyz"
lines: [{
id: "gid://shopify/CartLine/abc"
quantity: 2
}]
) {
cart {
id
lines(first: 10) {
edges {
node {
quantity
}
}
}
}
}
}
Webhooks
Setup Webhook
// Register webhook via API
const webhook = await shopify.webhooks.register({
topic: 'ORDERS_CREATE',
address: 'https://your-app.com/webhooks/orders-create',
format: 'json'
});
Verify Webhook
import crypto from 'crypto';
function verifyWebhook(body, hmacHeader, secret) {
const hash = crypto
.createHmac('sha256', secret)
.update(body, 'utf8')
.digest('base64');
return hash === hmacHeader;
}
// In webhook handler
app.post('/webhooks/orders-create', async (req, res) => {
const hmac = req.headers['x-shopify-hmac-sha256'];
const body = await req.text();
if (!verifyWebhook(body, hmac, process.env.SHOPIFY_API_SECRET)) {
return res.status(401).send('Invalid HMAC');
}
const order = JSON.parse(body);
// Process order...
res.status(200).send('OK');
});
Liquid Templates
Basic Liquid
<!-- Output product title -->
{{ product.title }}
<!-- Conditional logic -->
{% if product.available %}
<button>Add to Cart</button>
{% else %}
<span>Sold Out</span>
{% endif %}
<!-- Loop through variants -->
{% for variant in product.variants %}
<option value="{{ variant.id }}">
{{ variant.title }} - {{ variant.price | money }}
</option>
{% endfor %}
Custom Section
{% schema %}
{
"name": "Featured Product",
"settings": [
{
"type": "product",
"id": "product",
"label": "Product"
}
]
}
{% endschema %}
{% if section.settings.product %}
{% assign product = section.settings.product %}
<div class="featured-product">
<img src="{{ product.featured_image | img_url: '500x' }}" alt="{{ product.title }}">
<h2>{{ product.title }}</h2>
<p>{{ product.price | money }}</p>
</div>
{% endif %}
Shopify Functions
Discount Function
// Function to apply volume discount
export default (input) => {
const quantity = input.cart.lines.reduce((sum, line) => sum + line.quantity, 0);
let discountPercentage = 0;
if (quantity >= 10) discountPercentage = 20;
else if (quantity >= 5) discountPercentage = 10;
if (discountPercentage > 0) {
return {
discounts: [{
message: `${discountPercentage}% volume discount`,
targets: [{
orderSubtotal: {
excludedVariantIds: []
}
}],
value: {
percentage: {
value: discountPercentage.toString()
}
}
}]
};
}
return { discounts: [] };
};
Delivery Customization
// Hide specific delivery options
export default (input) => {
const operations = [];
// Hide express shipping for orders under $100
const cartTotal = parseFloat(input.cart.cost.subtotalAmount.amount);
if (cartTotal < 100) {
const expressOptions = input.cart.deliveryGroups[0].deliveryOptions
.filter(option => option.title.toLowerCase().includes('express'));
expressOptions.forEach(option => {
operations.push({
hide: {
deliveryOptionHandle: option.handle
}
});
});
}
return { operations };
};
Hydrogen (Headless Commerce)
Product Page
// app/routes/products.$handle.tsx
import {json, LoaderFunctionArgs} from '@shopify/remix-oxygen';
import {useLoaderData} from '@remix-run/react';
export async function loader({params, context}: LoaderFunctionArgs) {
const {product} = await context.storefront.query(PRODUCT_QUERY, {
variables: {handle: params.handle},
});
return json({product});
}
export default function Product() {
const {product} = useLoaderData<typeof loader>();
return (
<div>
<h1>{product.title}</h1>
<img src={product.featuredImage.url} alt={product.title} />
<p>{product.description}</p>
<AddToCartButton productId={product.id} />
</div>
);
}
const PRODUCT_QUERY = `#graphql
query Product($handle: String!) {
product(handle: $handle) {
id
title
description
featuredImage {
url
altText
}
variants(first: 10) {
nodes {
id
price {
amount
currencyCode
}
}
}
}
}
`;
Shopify CLI
Common Commands
# Create new app
shopify app init
# Start development server
shopify app dev
# Deploy app
shopify app deploy
# Create extension
shopify app generate extension
# Create theme
shopify theme init
# Serve theme locally
shopify theme dev --store=your-store.myshopify.com
# Push theme
shopify theme push
# Pull theme
shopify theme pull
Testing
Test Stores
- Create Partner account: https://partners.shopify.com
- Create development store
- Install your app
- Test features
Test Data
// Create test product
const product = await shopify.rest.Product.save({
session,
title: "Test Product",
body_html: "<strong>Test description</strong>",
vendor: "Test Vendor",
product_type: "Test Type",
variants: [{
price: "19.99",
sku: "TEST-001"
}]
});
// Create test order
const order = await shopify.rest.Order.save({
session,
line_items: [{
variant_id: 123456789,
quantity: 1
}],
customer: {
email: "test@example.com"
}
});
Security Best Practices
-
API Keys:
- Store in environment variables
- Never commit to version control
- Use separate keys per environment
- Rotate if compromised
-
Webhooks:
- ALWAYS verify HMAC signatures
- Use HTTPS endpoints only
- Return 200 immediately
- Process async
-
Access Scopes:
- Request minimal scopes
- Document why each scope is needed
- Review periodically
-
Rate Limits:
- Respect API rate limits
- Implement exponential backoff
- Monitor API usage
Common Errors
API Authentication
Invalid access token- Check token is valid and has correct scopesShop not found- Verify shop domain formatMissing access token- Include X-Shopify-Access-Token header
GraphQL Errors
User errors- CheckuserErrorsfield in responseThrottled- Reduce request rateField not found- Verify API version supports field
Webhook Issues
Invalid HMAC- Check webhook secret and verification logicDelivery failed- Ensure endpoint returns 200 within timeoutNot receiving webhooks- Check webhook registration and endpoint URL
Resources
- Dashboard: https://partners.shopify.com
- Documentation: https://shopify.dev
- GraphiQL Admin: https://shopify.dev/docs/apps/tools/graphiql-admin-api
- Community: https://community.shopify.com
- Status: https://www.shopifystatus.com
Documentation Quick Reference
Need to find something specific?
# Search all docs
grep -r "search term" .claude/skills/shopify/docs/
# Find specific topics
ls .claude/skills/shopify/docs/shopify/
# Read specific guide
cat .claude/skills/shopify/docs/shopify/webhooks.md
Common doc files:
api-admin-graphql.md- GraphQL Admin APIapi-storefront.md- Storefront APIauthentication.md- OAuth and auth flowswebhooks.md- Webhook handlingapps.md- App developmentthemes.md- Theme developmentliquid.md- Liquid referencehydrogen.md- Headless commercecheckout.md- Checkout customizationfunctions.md- Shopify Functionscli.md- CLI commands
AWS Serverless & Event-Driven Architecture
This skill provides comprehensive guidance for building serverless applications and event-driven architectures on AWS based on Well-Architected Framework principles.
AWS Documentation Requirement
CRITICAL: This skill requires AWS MCP tools for accurate, up-to-date AWS information.
Before Answering AWS Questions
-
Always verify using AWS MCP tools (if available):
mcp__aws-mcp__aws___search_documentationormcp__*awsdocs*__aws___search_documentation- Search AWS docsmcp__aws-mcp__aws___read_documentationormcp__*awsdocs*__aws___read_documentation- Read specific pagesmcp__aws-mcp__aws___get_regional_availability- Check service availability
-
If AWS MCP tools are unavailable:
- Guide user to configure AWS MCP: See AWS MCP Setup Guide
- Help determine which option fits their environment:
- Has uvx + AWS credentials → Full AWS MCP Server
- No Python/credentials → AWS Documentation MCP (no auth)
- If cannot determine → Ask user which option to use
Serverless MCP Servers
This skill can leverage serverless-specific MCP servers for enhanced development workflows:
AWS Serverless MCP Server
Purpose: Complete serverless application lifecycle with SAM CLI
- Initialize new serverless applications
- Deploy serverless applications
- Test Lambda functions locally
- Generate SAM templates
- Manage serverless application lifecycle
AWS Lambda Tool MCP Server
Purpose: Execute Lambda functions as tools
- Invoke Lambda functions directly
- Test Lambda integrations
- Execute workflows requiring private resource access
- Run Lambda-based automation
AWS Step Functions MCP Server
Purpose: Execute complex workflows and orchestration
- Create and manage state machines
- Execute workflow orchestrations
- Handle distributed transactions
- Implement saga patterns
- Coordinate microservices
Amazon SNS/SQS MCP Server
Purpose: Event-driven messaging and queue management
- Publish messages to SNS topics
- Send/receive messages from SQS queues
- Manage event-driven communication
- Implement pub/sub patterns
- Handle asynchronous processing
When to Use This Skill
Use this skill when:
- Building serverless applications with Lambda
- Designing event-driven architectures
- Implementing microservices patterns
- Creating asynchronous processing workflows
- Orchestrating multi-service transactions
- Building real-time data processing pipelines
- Implementing saga patterns for distributed transactions
- Designing for scale and resilience
AWS Well-Architected Serverless Design Principles
1. Speedy, Simple, Singular
Functions should be concise and single-purpose
// ✅ GOOD - Single purpose, focused function
export const processOrder = async (event: OrderEvent) => {
// Only handles order processing
const order = await validateOrder(event);
await saveOrder(order);
await publishOrderCreatedEvent(order);
return { statusCode: 200, body: JSON.stringify({ orderId: order.id }) };
};
// ❌ BAD - Function does too much
export const handleEverything = async (event: any) => {
// Handles orders, inventory, payments, shipping...
// Too many responsibilities
};
Keep functions environmentally efficient and cost-aware:
- Minimize cold start times
- Optimize memory allocation
- Use provisioned concurrency only when needed
- Leverage connection reuse
2. Think Concurrent Requests, Not Total Requests
Design for concurrency, not volume
Lambda scales horizontally - design considerations should focus on:
- Concurrent execution limits
- Downstream service throttling
- Shared resource contention
- Connection pool sizing
// Consider concurrent Lambda executions accessing DynamoDB
const table = new dynamodb.Table(this, 'Table', {
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // Auto-scales with load
});
// Or with provisioned capacity + auto-scaling
const table = new dynamodb.Table(this, 'Table', {
billingMode: dynamodb.BillingMode.PROVISIONED,
readCapacity: 5,
writeCapacity: 5,
});
// Enable auto-scaling for concurrent load
table.autoScaleReadCapacity({ minCapacity: 5, maxCapacity: 100 });
table.autoScaleWriteCapacity({ minCapacity: 5, maxCapacity: 100 });
3. Share Nothing
Function runtime environments are short-lived
// ❌ BAD - Relying on local file system
export const handler = async (event: any) => {
fs.writeFileSync('/tmp/data.json', JSON.stringify(data)); // Lost after execution
};
// ✅ GOOD - Use persistent storage
export const handler = async (event: any) => {
await s3.putObject({
Bucket: process.env.BUCKET_NAME,
Key: 'data.json',
Body: JSON.stringify(data),
});
};
State management:
- Use DynamoDB for persistent state
- Use Step Functions for workflow state
- Use ElastiCache for session state
- Use S3 for file storage
4. Assume No Hardware Affinity
Applications must be hardware-agnostic
Infrastructure can change without notice:
- Lambda functions can run on different hardware
- Container instances can be replaced
- No assumption about underlying infrastructure
Design for portability:
- Use environment variables for configuration
- Avoid hardware-specific optimizations
- Test across different environments
5. Orchestrate with State Machines, Not Function Chaining
Use Step Functions for orchestration
// ❌ BAD - Lambda function chaining
export const handler1 = async (event: any) => {
const result = await processStep1(event);
await lambda.invoke({
FunctionName: 'handler2',
Payload: JSON.stringify(result),
});
};
// ✅ GOOD - Step Functions orchestration
const stateMachine = new stepfunctions.StateMachine(this, 'OrderWorkflow', {
definition: stepfunctions.Chain
.start(validateOrder)
.next(processPayment)
.next(shipOrder)
.next(sendConfirmation),
});
Benefits of Step Functions:
- Visual workflow representation
- Built-in error handling and retries
- Execution history and debugging
- Parallel and sequential execution
- Service integrations without code
6. Use Events to Trigger Transactions
Event-driven over synchronous request/response
// Pattern: Event-driven processing
const bucket = new s3.Bucket(this, 'DataBucket');
bucket.addEventNotification(
s3.EventType.OBJECT_CREATED,
new s3n.LambdaDestination(processFunction),
{ prefix: 'uploads/' }
);
// Pattern: EventBridge integration
const rule = new events.Rule(this, 'OrderRule', {
eventPattern: {
source: ['orders'],
detailType: ['OrderPlaced'],
},
});
rule.addTarget(new targets.LambdaFunction(processOrderFunction));
Benefits:
- Loose coupling between services
- Asynchronous processing
- Better fault tolerance
- Independent scaling
7. Design for Failures and Duplicates
Operations must be idempotent
// ✅ GOOD - Idempotent operation
export const handler = async (event: SQSEvent) => {
for (const record of event.Records) {
const orderId = JSON.parse(record.body).orderId;
// Check if already processed (idempotency)
const existing = await dynamodb.getItem({
TableName: process.env.TABLE_NAME,
Key: { orderId },
});
if (existing.Item) {
console.log('Order already processed:', orderId);
continue; // Skip duplicate
}
// Process order
await processOrder(orderId);
// Mark as processed
await dynamodb.putItem({
TableName: process.env.TABLE_NAME,
Item: { orderId, processedAt: Date.now() },
});
}
};
Implement retry logic with exponential backoff:
async function withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
throw new Error('Max retries exceeded');
}
Event-Driven Architecture Patterns
Pattern 1: Event Router (EventBridge)
Use EventBridge for event routing and filtering:
// Create custom event bus
const eventBus = new events.EventBus(this, 'AppEventBus', {
eventBusName: 'application-events',
});
// Define event schema
const schema = new events.Schema(this, 'OrderSchema', {
schemaName: 'OrderPlaced',
definition: events.SchemaDefinition.fromInline({
openapi: '3.0.0',
info: { version: '1.0.0', title: 'Order Events' },
paths: {},
components: {
schemas: {
OrderPlaced: {
type: 'object',
properties: {
orderId: { type: 'string' },
customerId: { type: 'string' },
amount: { type: 'number' },
},
},
},
},
}),
});
// Create rules for different consumers
new events.Rule(this, 'ProcessOrderRule', {
eventBus,
eventPattern: {
source: ['orders'],
detailType: ['OrderPlaced'],
},
targets: [new targets.LambdaFunction(processOrderFunction)],
});
new events.Rule(this, 'NotifyCustomerRule', {
eventBus,
eventPattern: {
source: ['orders'],
detailType: ['OrderPlaced'],
},
targets: [new targets.LambdaFunction(notifyCustomerFunction)],
});
Pattern 2: Queue-Based Processing (SQS)
Use SQS for reliable asynchronous processing:
// Standard queue for at-least-once delivery
const queue = new sqs.Queue(this, 'ProcessingQueue', {
visibilityTimeout: Duration.seconds(300),
retentionPeriod: Duration.days(14),
deadLetterQueue: {
queue: dlq,
maxReceiveCount: 3,
},
});
// FIFO queue for ordered processing
const fifoQueue = new sqs.Queue(this, 'OrderedQueue', {
fifo: true,
contentBasedDeduplication: true,
deduplicationScope: sqs.DeduplicationScope.MESSAGE_GROUP,
});
// Lambda consumer
new lambda.EventSourceMapping(this, 'QueueConsumer', {
target: processingFunction,
eventSourceArn: queue.queueArn,
batchSize: 10,
maxBatchingWindow: Duration.seconds(5),
});
Pattern 3: Pub/Sub (SNS + SQS Fan-Out)
Implement fan-out pattern for multiple consumers:
// Create SNS topic
const topic = new sns.Topic(this, 'OrderTopic', {
displayName: 'Order Events',
});
// Multiple SQS queues subscribe to topic
const inventoryQueue = new sqs.Queue(this, 'InventoryQueue');
const shippingQueue = new sqs.Queue(this, 'ShippingQueue');
const analyticsQueue = new sqs.Queue(this, 'AnalyticsQueue');
topic.addSubscription(new subscriptions.SqsSubscription(inventoryQueue));
topic.addSubscription(new subscriptions.SqsSubscription(shippingQueue));
topic.addSubscription(new subscriptions.SqsSubscription(analyticsQueue));
// Each queue has its own Lambda consumer
new lambda.EventSourceMapping(this, 'InventoryConsumer', {
target: inventoryFunction,
eventSourceArn: inventoryQueue.queueArn,
});
Pattern 4: Saga Pattern with Step Functions
Implement distributed transactions:
const reserveFlight = new tasks.LambdaInvoke(this, 'ReserveFlight', {
lambdaFunction: reserveFlightFunction,
outputPath: '$.Payload',
});
const reserveHotel = new tasks.LambdaInvoke(this, 'ReserveHotel', {
lambdaFunction: reserveHotelFunction,
outputPath: '$.Payload',
});
const processPayment = new tasks.LambdaInvoke(this, 'ProcessPayment', {
lambdaFunction: processPaymentFunction,
outputPath: '$.Payload',
});
// Compensating transactions
const cancelFlight = new tasks.LambdaInvoke(this, 'CancelFlight', {
lambdaFunction: cancelFlightFunction,
});
const cancelHotel = new tasks.LambdaInvoke(this, 'CancelHotel', {
lambdaFunction: cancelHotelFunction,
});
// Define saga with compensation
const definition = reserveFlight
.next(reserveHotel)
.next(processPayment)
.addCatch(cancelHotel.next(cancelFlight), {
resultPath: '$.error',
});
new stepfunctions.StateMachine(this, 'BookingStateMachine', {
definition,
timeout: Duration.minutes(5),
});
Pattern 5: Event Sourcing
Store events as source of truth:
// Event store with DynamoDB
const eventStore = new dynamodb.Table(this, 'EventStore', {
partitionKey: { name: 'aggregateId', type: dynamodb.AttributeType.STRING },
sortKey: { name: 'version', type: dynamodb.AttributeType.NUMBER },
stream: dynamodb.StreamViewType.NEW_IMAGE,
});
// Lambda function stores events
export const handleCommand = async (event: any) => {
const { aggregateId, eventType, eventData } = event;
// Get current version
const items = await dynamodb.query({
TableName: process.env.EVENT_STORE,
KeyConditionExpression: 'aggregateId = :id',
ExpressionAttributeValues: { ':id': aggregateId },
ScanIndexForward: false,
Limit: 1,
});
const nextVersion = items.Items?.[0]?.version + 1 || 1;
// Append new event
await dynamodb.putItem({
TableName: process.env.EVENT_STORE,
Item: {
aggregateId,
version: nextVersion,
eventType,
eventData,
timestamp: Date.now(),
},
});
};
// Projections read from event stream
eventStore.grantStreamRead(projectionFunction);
Serverless Architecture Patterns
Pattern 1: API-Driven Microservices
REST APIs with Lambda backend:
const api = new apigateway.RestApi(this, 'Api', {
restApiName: 'microservices-api',
deployOptions: {
throttlingRateLimit: 1000,
throttlingBurstLimit: 2000,
tracingEnabled: true,
},
});
// User service
const users = api.root.addResource('users');
users.addMethod('GET', new apigateway.LambdaIntegration(getUsersFunction));
users.addMethod('POST', new apigateway.LambdaIntegration(createUserFunction));
// Order service
const orders = api.root.addResource('orders');
orders.addMethod('GET', new apigateway.LambdaIntegration(getOrdersFunction));
orders.addMethod('POST', new apigateway.LambdaIntegration(createOrderFunction));
Pattern 2: Stream Processing
Real-time data processing with Kinesis:
const stream = new kinesis.Stream(this, 'DataStream', {
shardCount: 2,
retentionPeriod: Duration.days(7),
});
// Lambda processes stream records
new lambda.EventSourceMapping(this, 'StreamProcessor', {
target: processFunction,
eventSourceArn: stream.streamArn,
batchSize: 100,
maxBatchingWindow: Duration.seconds(5),
parallelizationFactor: 10,
startingPosition: lambda.StartingPosition.LATEST,
retryAttempts: 3,
bisectBatchOnError: true,
onFailure: new lambdaDestinations.SqsDestination(dlq),
});
Pattern 3: Async Task Processing
Background job processing:
// SQS queue for tasks
const taskQueue = new sqs.Queue(this, 'TaskQueue', {
visibilityTimeout: Duration.minutes(5),
receiveMessageWaitTime: Duration.seconds(20), // Long polling
deadLetterQueue: {
queue: dlq,
maxReceiveCount: 3,
},
});
// Lambda worker processes tasks
const worker = new lambda.Function(this, 'TaskWorker', {
// ... configuration
reservedConcurrentExecutions: 10, // Control concurrency
});
new lambda.EventSourceMapping(this, 'TaskConsumer', {
target: worker,
eventSourceArn: taskQueue.queueArn,
batchSize: 10,
reportBatchItemFailures: true, // Partial batch failure handling
});
Pattern 4: Scheduled Jobs
Periodic processing with EventBridge:
// Daily cleanup job
new events.Rule(this, 'DailyCleanup', {
schedule: events.Schedule.cron({ hour: '2', minute: '0' }),
targets: [new targets.LambdaFunction(cleanupFunction)],
});
// Process every 5 minutes
new events.Rule(this, 'FrequentProcessing', {
schedule: events.Schedule.rate(Duration.minutes(5)),
targets: [new targets.LambdaFunction(processFunction)],
});
Pattern 5: Webhook Processing
Handle external webhooks:
// API Gateway endpoint for webhooks
const webhookApi = new apigateway.RestApi(this, 'WebhookApi', {
restApiName: 'webhooks',
});
const webhook = webhookApi.root.addResource('webhook');
webhook.addMethod('POST', new apigateway.LambdaIntegration(webhookFunction, {
proxy: true,
timeout: Duration.seconds(29), // API Gateway max
}));
// Lambda handler validates and queues webhook
export const handler = async (event: APIGatewayProxyEvent) => {
// Validate webhook signature
const isValid = validateSignature(event.headers, event.body);
if (!isValid) {
return { statusCode: 401, body: 'Invalid signature' };
}
// Queue for async processing
await sqs.sendMessage({
QueueUrl: process.env.QUEUE_URL,
MessageBody: event.body,
});
// Return immediately
return { statusCode: 202, body: 'Accepted' };
};
Best Practices
Error Handling
Implement comprehensive error handling:
export const handler = async (event: SQSEvent) => {
const failures: SQSBatchItemFailure[] = [];
for (const record of event.Records) {
try {
await processRecord(record);
} catch (error) {
console.error('Failed to process record:', record.messageId, error);
failures.push({ itemIdentifier: record.messageId });
}
}
// Return partial batch failures for retry
return { batchItemFailures: failures };
};
Dead Letter Queues
Always configure DLQs for error handling:
const dlq = new sqs.Queue(this, 'DLQ', {
retentionPeriod: Duration.days(14),
});
const queue = new sqs.Queue(this, 'Queue', {
deadLetterQueue: {
queue: dlq,
maxReceiveCount: 3,
},
});
// Monitor DLQ depth
new cloudwatch.Alarm(this, 'DLQAlarm', {
metric: dlq.metricApproximateNumberOfMessagesVisible(),
threshold: 1,
evaluationPeriods: 1,
alarmDescription: 'Messages in DLQ require attention',
});
Observability
Enable tracing and monitoring:
new NodejsFunction(this, 'Function', {
entry: 'src/handler.ts',
tracing: lambda.Tracing.ACTIVE, // X-Ray tracing
environment: {
POWERTOOLS_SERVICE_NAME: 'order-service',
POWERTOOLS_METRICS_NAMESPACE: 'MyApp',
LOG_LEVEL: 'INFO',
},
});
Using MCP Servers Effectively
AWS Serverless MCP Usage
Lifecycle management:
- Initialize new serverless projects
- Generate SAM templates
- Deploy applications
- Test locally before deployment
Lambda Tool MCP Usage
Function execution:
- Test Lambda functions directly
- Execute automation workflows
- Access private resources
- Validate integrations
Step Functions MCP Usage
Workflow orchestration:
- Create state machines for complex workflows
- Execute distributed transactions
- Implement saga patterns
- Coordinate microservices
SNS/SQS MCP Usage
Messaging operations:
- Test pub/sub patterns
- Send test messages to queues
- Validate event routing
- Debug message processing
Additional Resources
This skill includes comprehensive reference documentation based on AWS best practices:
-
Serverless Patterns:
references/serverless-patterns.md- Core serverless architectures and API patterns
- Data processing and integration patterns
- Orchestration with Step Functions
- Anti-patterns to avoid
-
Event-Driven Architecture Patterns:
references/eda-patterns.md- Event routing and processing patterns
- Event sourcing and saga patterns
- Idempotency and error handling
- Message ordering and deduplication
-
Security Best Practices:
references/security-best-practices.md- Shared responsibility model
- IAM least privilege patterns
- Data protection and encryption
- Network security with VPC
-
Observability Best Practices:
references/observability-best-practices.md- Three pillars: metrics, logs, traces
- Structured logging with Lambda Powertools
- X-Ray distributed tracing
- CloudWatch alarms and dashboards
-
Performance Optimization:
references/performance-optimization.md- Cold start optimization techniques
- Memory and CPU optimization
- Package size reduction
- Provisioned concurrency patterns
-
Deployment Best Practices:
references/deployment-best-practices.md- CI/CD pipeline design
- Testing strategies (unit, integration, load)
- Deployment strategies (canary, blue/green)
- Rollback and safety mechanisms
External Resources:
- AWS Well-Architected Serverless Lens: https://docs.aws.amazon.com/wellarchitected/latest/serverless-applications-lens/
- ServerlessLand.com: Pre-built serverless patterns
- AWS Serverless Workshops: https://serverlessland.com/learn?type=Workshops
For detailed implementation patterns, anti-patterns, and code examples, refer to the comprehensive references in the skill directory.
Review Feedback Implementation
Systematically process and implement changes based on code review feedback.
When to Use
- Provides reviewer comments or feedback
- Pastes PR review notes
- Mentions implementing review suggestions
- Says "address these comments" or "implement feedback"
- Shares list of changes requested by reviewers
Systematic Workflow
1. Parse Reviewer Notes
Identify individual feedback items:
- Split numbered lists (1., 2., etc.)
- Handle bullet points or unnumbered feedback
- Extract distinct change requests
- Clarify ambiguous items before starting
2. Create Todo List
Use TodoWrite tool to create actionable tasks:
- Each feedback item becomes one or more todos
- Break down complex feedback into smaller tasks
- Make tasks specific and measurable
- Mark first task as
in_progressbefore starting
Example:
- Add type hints to extract function
- Fix duplicate tag detection logic
- Update docstring in chain.py
- Add unit test for edge case
3. Implement Changes Systematically
For each todo item:
Locate relevant code:
- Use Grep to search for functions/classes
- Use Glob to find files by pattern
- Read current implementation
Make changes:
- Use Edit tool for modifications
- Follow project conventions (CLAUDE.md)
- Preserve existing functionality unless changing behavior
Verify changes:
- Check syntax correctness
- Run relevant tests if applicable
- Ensure changes address reviewer's intent
Update status:
- Mark todo as
completedimmediately after finishing - Move to next todo (only one
in_progressat a time)
4. Handle Different Feedback Types
Code changes:
- Use Edit tool for existing code
- Follow type hint conventions (PEP 604/585)
- Maintain consistent style
New features:
- Create new files with Write tool if needed
- Add corresponding tests
- Update documentation
Documentation:
- Update docstrings following project style
- Modify markdown files as needed
- Keep explanations concise
Tests:
- Write tests as functions, not classes
- Use descriptive names
- Follow pytest conventions
Refactoring:
- Preserve functionality
- Improve code structure
- Run tests to verify no regressions
5. Validation
After implementing changes:
- Run affected tests
- Check for linting errors:
uv run ruff check - Verify changes don't break existing functionality
6. Communication
Keep user informed:
- Update todo list in real-time
- Ask for clarification on ambiguous feedback
- Report blockers or challenges
- Summarize changes at completion
Edge Cases
Conflicting feedback:
- Ask user for guidance
- Explain conflict clearly
Breaking changes required:
- Notify user before implementing
- Discuss impact and alternatives
Tests fail after changes:
- Fix tests before marking todo complete
- Ensure all related tests pass
Referenced code doesn't exist:
- Ask user for clarification
- Verify understanding before proceeding
Important Guidelines
- Always use TodoWrite for tracking progress
- Mark todos completed immediately after each item
- Only one todo in_progress at any time
- Don't batch completions - update status in real-time
- Ask questions for unclear feedback
- Run tests if changes affect tested code
- Follow CLAUDE.md conventions for all code changes
- Use conventional commits if creating commits afterward
Financial Analysis Agent
Build intelligent financial analysis agents that evaluate investments, assess risks, and generate data-driven recommendations.
Financial Data Integration
See examples/financial_data_collector.py for the FinancialDataCollector class that:
- Integrates with yfinance for stock data
- Retrieves financial statements (income, balance sheet, cash flow)
- Fetches key metrics (market cap, PE ratio, dividend yield, etc.)
Financial Analysis Techniques
Technical Analysis
See examples/technical_analyzer.py for TechnicalAnalyzer:
- Moving averages calculation
- Relative Strength Index (RSI)
- Support and resistance level identification
Fundamental Analysis
See examples/fundamental_analyzer.py for FundamentalAnalyzer:
- Profitability ratios (gross margin, operating margin, net margin, ROA, ROE)
- Valuation ratios (PE, PB, PEG, price-to-sales)
- Liquidity ratios (current ratio, quick ratio, debt-to-equity)
Risk Assessment
See examples/risk_analyzer.py for RiskAnalyzer:
- Volatility calculation
- Value at Risk (VaR) assessment
- Sharpe Ratio calculation
- Company risk assessment
Investment Recommendations
See examples/investment_recommender.py for InvestmentRecommender:
- Generates recommendations (Strong Buy, Buy, Hold, Sell, Strong Sell)
- Calculates investment scores based on technical and fundamental signals
- Provides confidence levels and risk assessments
Portfolio Management
See examples/portfolio_manager.py for PortfolioManager:
- Calculate portfolio total value
- Rebalance portfolio based on target allocations
- Assess portfolio risk and volatility
Market Intelligence
Build market intelligence capabilities by:
- Analyzing overall market trends and sector performance
- Calculating market volatility indices
- Fetching economic indicators
- Identifying undervalued, growth, and dividend opportunities
Best Practices
Analysis Quality
- ✓ Use multiple data sources
- ✓ Cross-validate findings
- ✓ Document assumptions
- ✓ Consider time horizons
- ✓ Account for fees and taxes
Risk Management
- ✓ Assess downside risk
- ✓ Implement stop losses
- ✓ Diversify appropriately
- ✓ Position size accordingly
- ✓ Review regularly
Ethical Considerations
- ✓ Disclose conflicts of interest
- ✓ Avoid market manipulation
- ✓ Base recommendations on analysis
- ✓ Update recommendations regularly
- ✓ Acknowledge limitations
Tools & Data Sources
Data APIs
- yfinance
- Alpha Vantage
- IEX Cloud
- Polygon.io
- Yahoo Finance
Analysis Libraries
- pandas
- NumPy
- scikit-learn
- TA-Lib
- statsmodels
Getting Started
- Collect financial data
- Perform technical analysis
- Analyze fundamentals
- Assess risks
- Generate recommendations
- Monitor positions
- Rebalance periodically
Invoice Organizer
This skill transforms chaotic folders of invoices, receipts, and financial documents into a clean, tax-ready filing system without manual effort.
When to Use This Skill
- Preparing for tax season and need organized records
- Managing business expenses across multiple vendors
- Organizing receipts from a messy folder or email downloads
- Setting up automated invoice filing for ongoing bookkeeping
- Archiving financial records by year or category
- Reconciling expenses for reimbursement
- Preparing documentation for accountants
What This Skill Does
-
Reads Invoice Content: Extracts information from PDFs, images, and documents:
- Vendor/company name
- Invoice number
- Date
- Amount
- Product or service description
- Payment method
-
Renames Files Consistently: Creates standardized filenames:
- Format:
YYYY-MM-DD Vendor - Invoice - ProductOrService.pdf - Examples:
2024-03-15 Adobe - Invoice - Creative Cloud.pdf
- Format:
-
Organizes by Category: Sorts into logical folders:
- By vendor
- By expense category (software, office, travel, etc.)
- By time period (year, quarter, month)
- By tax category (deductible, personal, etc.)
-
Handles Multiple Formats: Works with:
- PDF invoices
- Scanned receipts (JPG, PNG)
- Email attachments
- Screenshots
- Bank statements
-
Maintains Originals: Preserves original files while organizing copies
How to Use
Basic Usage
Navigate to your messy invoice folder:
cd ~/Desktop/receipts-to-sort
Then ask Claude Code:
Organize these invoices for taxes
Or more specifically:
Read all invoices in this folder, rename them to
"YYYY-MM-DD Vendor - Invoice - Product.pdf" format,
and organize them by vendor
Advanced Organization
Organize these invoices:
1. Extract date, vendor, and description from each file
2. Rename to standard format
3. Sort into folders by expense category (Software, Office, Travel, etc.)
4. Create a CSV spreadsheet with all invoice details for my accountant
Instructions
When a user requests invoice organization:
-
Scan the Folder
Identify all invoice files:
# Find all invoice-related files find . -type f \( -name "*.pdf" -o -name "*.jpg" -o -name "*.png" \) -printReport findings:
- Total number of files
- File types
- Date range (if discernible from names)
- Current organization (or lack thereof)
-
Extract Information from Each File
For each invoice, extract:
From PDF invoices:
- Use text extraction to read invoice content
- Look for common patterns:
- "Invoice Date:", "Date:", "Issued:"
- "Invoice #:", "Invoice Number:"
- Company name (usually at top)
- "Amount Due:", "Total:", "Amount:"
- "Description:", "Service:", "Product:"
From image receipts:
- Read visible text from images
- Identify vendor name (often at top)
- Look for date (common formats)
- Find total amount
Fallback for unclear files:
- Use filename clues
- Check file creation/modification date
- Flag for manual review if critical info missing
-
Determine Organization Strategy
Ask user preference if not specified:
I found [X] invoices from [date range]. How would you like them organized? 1. **By Vendor** (Adobe/, Amazon/, Stripe/, etc.) 2. **By Category** (Software/, Office Supplies/, Travel/, etc.) 3. **By Date** (2024/Q1/, 2024/Q2/, etc.) 4. **By Tax Category** (Deductible/, Personal/, etc.) 5. **Custom** (describe your structure) Or I can use a default structure: Year/Category/Vendor -
Create Standardized Filename
For each invoice, create a filename following this pattern:
YYYY-MM-DD Vendor - Invoice - Description.extExamples:
2024-03-15 Adobe - Invoice - Creative Cloud.pdf2024-01-10 Amazon - Receipt - Office Supplies.pdf2023-12-01 Stripe - Invoice - Monthly Payment Processing.pdf
Filename Best Practices:
- Remove special characters except hyphens
- Capitalize vendor names properly
- Keep descriptions concise but meaningful
- Use consistent date format (YYYY-MM-DD) for sorting
- Preserve original file extension
-
Execute Organization
Before moving files, show the plan:
# Organization Plan ## Proposed StructureInvoices/ ├── 2023/ │ ├── Software/ │ │ ├── Adobe/ │ │ └── Microsoft/ │ ├── Services/ │ └── Office/ └── 2024/ ├── Software/ ├── Services/ └── Office/
## Sample Changes Before: `invoice_adobe_march.pdf` After: `2024-03-15 Adobe - Invoice - Creative Cloud.pdf` Location: `Invoices/2024/Software/Adobe/` Before: `IMG_2847.jpg` After: `2024-02-10 Staples - Receipt - Office Supplies.jpg` Location: `Invoices/2024/Office/Staples/` Process [X] files? (yes/no)After approval:
# Create folder structure mkdir -p "Invoices/2024/Software/Adobe" # Copy (don't move) to preserve originals cp "original.pdf" "Invoices/2024/Software/Adobe/2024-03-15 Adobe - Invoice - Creative Cloud.pdf" # Or move if user prefers mv "original.pdf" "new/path/standardized-name.pdf" -
Generate Summary Report
Create a CSV file with all invoice details:
Date,Vendor,Invoice Number,Description,Amount,Category,File Path 2024-03-15,Adobe,INV-12345,Creative Cloud,52.99,Software,Invoices/2024/Software/Adobe/2024-03-15 Adobe - Invoice - Creative Cloud.pdf 2024-03-10,Amazon,123-4567890-1234567,Office Supplies,127.45,Office,Invoices/2024/Office/Amazon/2024-03-10 Amazon - Receipt - Office Supplies.pdf ...This CSV is useful for:
- Importing into accounting software
- Sharing with accountants
- Expense tracking and reporting
- Tax preparation
-
Provide Completion Summary
# Organization Complete! 📊 ## Summary - **Processed**: [X] invoices - **Date range**: [earliest] to [latest] - **Total amount**: $[sum] (if amounts extracted) - **Vendors**: [Y] unique vendors ## New StructureInvoices/ ├── 2024/ (45 files) │ ├── Software/ (23 files) │ ├── Services/ (12 files) │ └── Office/ (10 files) └── 2023/ (12 files)
## Files Created - `/Invoices/` - Organized invoices - `/Invoices/invoice-summary.csv` - Spreadsheet for accounting - `/Invoices/originals/` - Original files (if copied) ## Files Needing Review [List any files where information couldn't be extracted completely] ## Next Steps 1. Review the `invoice-summary.csv` file 2. Check files in "Needs Review" folder 3. Import CSV into your accounting software 4. Set up auto-organization for future invoices Ready for tax season! 🎉
Examples
Example 1: Tax Preparation (From Martin Merschroth)
User: "I have a messy folder of invoices for taxes. Sort them and rename properly."
Process:
- Scans folder: finds 147 PDFs and images
- Reads each invoice to extract:
- Date
- Vendor name
- Invoice number
- Product/service description
- Renames all files:
YYYY-MM-DD Vendor - Invoice - Product.pdf - Organizes into:
2024/Software/,2024/Travel/, etc. - Creates
invoice-summary.csvfor accountant - Result: Tax-ready organized invoices in minutes
Example 2: Monthly Expense Reconciliation
User: "Organize my business receipts from last month by category."
Output:
# March 2024 Receipts Organized
## By Category
- Software & Tools: $847.32 (12 invoices)
- Office Supplies: $234.18 (8 receipts)
- Travel & Meals: $1,456.90 (15 receipts)
- Professional Services: $2,500.00 (3 invoices)
Total: $5,038.40
All receipts renamed and filed in:
`Business-Receipts/2024/03-March/[Category]/`
CSV export: `march-2024-expenses.csv`
Example 3: Multi-Year Archive
User: "I have 3 years of random invoices. Organize them by year, then by vendor."
Output: Creates structure:
Invoices/
├── 2022/
│ ├── Adobe/
│ ├── Amazon/
│ └── ...
├── 2023/
│ ├── Adobe/
│ ├── Amazon/
│ └── ...
└── 2024/
├── Adobe/
├── Amazon/
└── ...
Each file properly renamed with date and description.
Example 4: Email Downloads Cleanup
User: "I download invoices from Gmail. They're all named 'invoice.pdf', 'invoice(1).pdf', etc. Fix this mess."
Output:
Found 89 files all named "invoice*.pdf"
Reading each file to extract real information...
Renamed examples:
- invoice.pdf → 2024-03-15 Shopify - Invoice - Monthly Subscription.pdf
- invoice(1).pdf → 2024-03-14 Google - Invoice - Workspace.pdf
- invoice(2).pdf → 2024-03-10 Netlify - Invoice - Pro Plan.pdf
All files renamed and organized by vendor.
Common Organization Patterns
By Vendor (Simple)
Invoices/
├── Adobe/
├── Amazon/
├── Google/
└── Microsoft/
By Year and Category (Tax-Friendly)
Invoices/
├── 2023/
│ ├── Software/
│ ├── Hardware/
│ ├── Services/
│ └── Travel/
└── 2024/
└── ...
By Quarter (Detailed Tracking)
Invoices/
├── 2024/
│ ├── Q1/
│ │ ├── Software/
│ │ ├── Office/
│ │ └── Travel/
│ └── Q2/
│ └── ...
By Tax Category (Accountant-Ready)
Invoices/
├── Deductible/
│ ├── Software/
│ ├── Office/
│ └── Professional-Services/
├── Partially-Deductible/
│ └── Meals-Travel/
└── Personal/
Automation Setup
For ongoing organization:
Create a script that watches my ~/Downloads/invoices folder
and auto-organizes any new invoice files using our standard
naming and folder structure.
This creates a persistent solution that organizes invoices as they arrive.
Pro Tips
- Scan emails to PDF: Use Preview or similar to save email invoices as PDFs first
- Consistent downloads: Save all invoices to one folder for batch processing
- Monthly routine: Organize invoices monthly, not annually
- Backup originals: Keep original files before reorganizing
- Include amounts in CSV: Useful for budget tracking
- Tag by deductibility: Note which expenses are tax-deductible
- Keep receipts 7 years: Standard audit period
Handling Special Cases
Missing Information
If date/vendor can't be extracted:
- Flag file for manual review
- Use file modification date as fallback
- Create "Needs-Review/" folder
Duplicate Invoices
If same invoice appears multiple times:
- Compare file hashes
- Keep highest quality version
- Note duplicates in summary
Multi-Page Invoices
For invoices split across files:
- Merge PDFs if needed
- Use consistent naming for parts
- Note in CSV if invoice is split
Non-Standard Formats
For unusual receipt formats:
- Extract what's possible
- Standardize what you can
- Flag for review if critical info missing
Related Use Cases
- Creating expense reports for reimbursement
- Organizing bank statements
- Managing vendor contracts
- Archiving old financial records
- Preparing for audits
- Tracking subscription costs over time
Family History Research Planning Skill
Version: 1.0.6 Last Updated: November 6, 2025
CRITICAL: Always Plan Before Researching
ABSOLUTELY PROHIBITED: DO NOT perform unsolicited web searches or research.
When a user mentions an ancestor or asks for help researching, you MUST follow this sequence:
- Gather information from the user first - Ask what they already know about the ancestor
- Define the research objective - Work with the user to clarify their specific goals
- Create a research plan - Use the Research Planning Workflow below
- Present the plan to the user - Give them a structured plan with prioritized sources and search strategies
NEVER jump immediately to web searches when a user mentions an ancestor.
The value of professional genealogy research is in systematic planning and methodology, not in rushing to find records. Always build a proper foundation through planning first.
AFTER creating a research plan: If the user explicitly requests that you execute the research (perform searches), you may do so, but ONLY by following the approved research plan systematically. Document all searches, findings, and citations as you go.
When to Use This Skill
Trigger this skill when users:
- Ask for help researching an ancestor → START with research planning workflow, gather known info, CREATE a plan first (do NOT search immediately)
- Plan or organize genealogy research projects → Use research planning workflow
- Need to create proper genealogical citations → Use citation workflow
- Have conflicting information from multiple sources → Use evidence analysis workflow
- Want to analyze evidence quality and reliability
- Need to build proof arguments for genealogical conclusions
- Ask for help with census records, vital records, or other historical documents → Provide guidance and analysis
- Need guidance on research strategies or methodologies → Teach concepts, create plans
Remember: Always START with planning. Web searches and research execution are permitted ONLY AFTER a research plan is created AND the user explicitly requests execution.
Core Capabilities
1. Research Planning and Strategy
Guide researchers through creating structured research plans that incorporate professional standards.
Key Process:
- Define specific research questions (who, what, when, where)
- Identify target individuals and relationships
- List potential record sources and repositories
- Develop search strategy using FAN principle (Family, Associates, Neighbors)
- Create timeline with milestones
- Establish success criteria and proof requirements
Output: Create a research plan document using the template in assets/templates/research-plan-template.md (simplified for practical use). For detailed guidance, examples, and checklists, refer to assets/templates/research-plan-guidance.md
2. Citation Creation
Generate properly formatted genealogical citations following Evidence Explained standards.
Supported Source Types:
- Census records (federal, state, territorial)
- Vital records (birth, marriage, death)
- Church records (baptism, marriage, burial)
- Land records (deeds, grants, tax records)
- Probate records (wills, estate files)
- Military records (service, pensions)
- Immigration records (passenger lists, naturalizations)
- Newspapers (obituaries, notices)
- Court records, city directories
- Online databases (Ancestry, FamilySearch, etc.)
- Published books and manuscripts
Citation Process:
- Identify source type and access method
- Gather core information (who, what, when, where)
- Build full reference note citation using appropriate template from
references/citation-templates.md - Create short form for subsequent references
- Generate source list entry for bibliography
- Assess source quality (original vs. derivative, primary vs. secondary)
Output: Citation entry using template in assets/templates/citation-template.md
3. Evidence Analysis and Conflict Resolution
Systematically analyze and resolve conflicts between genealogical sources.
Analysis Framework:
Step 1: Inventory Sources
- List all sources providing information about the fact
- Categorize by evidence type (direct/indirect/negative)
Step 2: Evaluate Each Source
- Source classification (original/derivative/authored)
- Information type (primary/secondary/undetermined)
- Informant analysis (who, relationship, knowledge level)
- Reliability factors (timing, bias, consistency)
Step 3: Compare and Identify Conflicts
- Create evidence comparison matrix
- Document specific discrepancies
- Assess significance of conflicts
Step 4: Assess Reliability
- Rank sources from most to least reliable
- Weight sources by quality, not quantity
- Consider corroboration patterns
Step 5: Resolve Conflicts
- Explore possible explanations for conflicts
- Apply evidence weight to determine preponderance
- Resolve conflicts or acknowledge if unresolvable
Step 6: GPS Compliance Check Apply the five GPS elements:
- Reasonably exhaustive research
- Complete and accurate source citations
- Analysis and correlation of evidence
- Resolution of conflicting evidence
- Soundly reasoned, coherently written conclusion
Step 7: Build Proof Argument
- State conclusion clearly
- Assign appropriate proof level (proven/probable/possible/unproven/disproven)
- Write coherent proof argument explaining reasoning
Output: Evidence analysis report using template in assets/templates/evidence-analysis-template.md
4. Research Logging
Document research activities systematically to avoid duplication and track progress.
Essential Elements:
- Research session context (date, time, goal)
- Research questions addressed
- All sources searched (including negative results)
- Search strategies and variations used
- Positive findings with complete citations
- Negative results documented
- Evidence analysis and reliability notes
- Next steps and follow-up actions
Output: Research log entry using template in assets/templates/research-log-template.md
Default Workflow: Start Every Research Request This Way
When a user asks for help researching an ancestor:
STEP 1: Information Gathering (Always do this first)
- Ask what they already know (name, dates, locations)
- Ask what records they've already found
- Ask what specific questions they want answered
- Ask about any conflicting information they've encountered
STEP 2: Research Planning (Required before any searches)
- Work through the Research Planning Workflow (see below)
- Create a structured plan document
- Prioritize sources and strategies
- Present the plan to the user
STEP 3: Research Execution (ONLY if user explicitly requests it)
- Follow the approved research plan systematically
- Use appropriate tools (web_search, etc.) as directed by the plan
- Document all searches (including negative results)
- Create proper citations for all findings
- Log all research activities
- Report findings and analysis to the user
NEVER skip Steps 1 and 2 to jump directly to Step 3.
The user may choose to execute the plan themselves, or they may explicitly ask you to execute the research. Either approach is acceptable, but planning MUST come first.
Procedural Guidelines
Research Planning Workflow
To plan a new research project:
- Define the objective - What specific genealogical question needs answering?
- Formulate research questions - Break into 3-7 specific, answerable questions
- Identify individuals - List primary subjects and associated family members
- List record sources - Organize by category (vital, census, land, probate, military, etc.)
- Develop strategy - Prioritize sources, plan FAN approach, work chronologically
- Set timeline - Break into phases with milestones When executing steps 5-6 (Develop strategy & Set timeline):
- Provide links to research resources for the specific location
- Prioritize: FamilySearch Wiki and LDSgenealogy.com above all other resources
- Include links to relevant county/state pages
- Identify record repositories and their online availability
- Apply GPS framework - Ensure plan addresses all five GPS elements
- Define success criteria - What constitutes adequate proof?
- Create next actions - List 5-10 immediate concrete steps
Reference references/research-strategies.md for detailed methodologies.
Citation Generation Workflow
To create a proper citation:
- Identify source type - Census, vital record, land record, etc.
- Determine access method - Original, microfilm, digital image, database, transcription
- Gather information:
- Subject/individual name
- Record type and date
- Repository and collection
- Specific location (volume, page, entry)
- URL and access date (if online)
- Select appropriate template - See
references/citation-templates.md - Build full citation - Follow template for source type
- Create short form - Abbreviated version for subsequent references
- Generate source list entry - Formatted for bibliography
- Assess source quality:
- Original, derivative, or authored?
- Primary, secondary, or undetermined information?
- Direct, indirect, or negative evidence?
- Extract key information - Document what the source says
- Link to research context - How does this answer research questions?
Evidence Analysis Workflow
To analyze conflicting evidence:
- Define the research question - What specific fact is being analyzed?
- Create evidence inventory - List all relevant sources
- Evaluate each source individually:
- Apply source/information/evidence classification
- Analyze informant and reliability factors
- Assign reliability rating
- Build comparison matrix - Show what each source says
- Identify conflicts - Document specific discrepancies
- Rank source reliability:
- Information timing (primary > secondary)
- Source type (original > derivative)
- Informant quality (direct knowledge > hearsay)
- Consistency (corroborated > standalone)
- Identify agreements - Note corroborating evidence patterns
- Apply conflict resolution framework:
- Evaluate each side of conflict
- Consider explanations (error, informant mistake, both partially true)
- Apply evidence weight
- Determine preponderance
- GPS compliance assessment - Check all five elements
- Write proof argument:
- State conclusion
- Assign proof level
- Explain reasoning from evidence
- Document gaps and recommendations - What research remains?
Reference references/evidence-evaluation.md for detailed guidance.
Key Genealogical Concepts
Source Types
- Original Source - First recording in original form (courthouse deed book, original certificate)
- Derivative Source - Copy, transcription, or database entry
- Authored Work - Compiled or analyzed work (published genealogy)
Information Types
- Primary Information - Recorded at/near time of event by knowledgeable person
- Secondary Information - Recorded later from memory or hearsay
- Important: Original sources can contain secondary information! (e.g., death certificate shows birth date recorded 80 years later)
Evidence Types
- Direct Evidence - Explicitly states the fact needed
- Indirect Evidence - Implies fact when combined with other sources
- Negative Evidence - Expected information that's absent
Proof Levels
- Proven - Beyond reasonable doubt, no credible conflicts, GPS fully satisfied
- Probable - Preponderance of evidence supports, minor conflicts resolved
- Possible - Some evidence supports, significant gaps remain
- Unproven - Insufficient evidence
- Disproven - Evidence contradicts hypothesis
References
For detailed guidance on specific topics, load these reference files as needed:
references/citation-templates.md- Complete templates for 14+ source typesreferences/evidence-evaluation.md- Detailed frameworks for conflict resolutionreferences/research-strategies.md- Advanced research methodologiesreferences/gps-guidelines.md- Genealogical Proof Standard detailed requirementsresearch-log-guidance.md- Comprehensive guidance with examples and best practicesresearch-plan-guidance.md- Comprehensive guidance with examples and best practices
Templates
Output templates are available in assets/templates/:
research-plan-template.md- Simplified research project planning (practical, day-to-day use)citation-template.md- Citation library entryevidence-analysis-template.md- Evidence analysis reportresearch-log-template.md- Research session documentation
Best Practices
Creating Citations
- Cite what you actually consulted (if using database, cite both database and original)
- Include enough detail for others to find the same record
- Follow specific-to-general pattern (item → source → repository)
- Distinguish between original records and database transcriptions
Analyzing Evidence
- Quality matters more than quantity - one strong source beats three weak ones
- Always consider informant knowledge and proximity to event
- Look for independent corroboration, not derivative repetition
- Acknowledge conflicts honestly rather than ignoring them
Building Proof Arguments
- State conclusion clearly and precisely
- Choose appropriate proof level for evidence strength
- Explain reasoning transparently
- Address conflicts explicitly and show resolution process
- Acknowledge limitations and gaps
Research Strategy
- Apply FAN principle - research family, associates, and neighbors
- Document negative results - they're valuable research data
- Work chronologically or geographically in systematic way
- Consider collateral lines for clues about direct ancestors
Example Usage Patterns
User: "I found three census records that say my ancestor was born in Ohio, but his death certificate says Pennsylvania. How do I figure out which is right?"
Response: Load references/evidence-evaluation.md, apply conflict resolution framework. Evaluate each source for reliability (original vs. derivative, primary vs. secondary information, informant quality). Weight the three consistent earlier sources (John as likely informant) against single later source (unknown informant, secondary information). Analyze possible explanations. Determine preponderance of evidence. Create evidence analysis report documenting reasoning.
User: "Help me create a citation for a census record I found on Ancestry."
Response: Load references/citation-templates.md for census citation template. Gather: year, county, state, page number, household, database name, URL, access date, NARA microfilm info. Build full citation following Evidence Explained format. Create short form and source list entry. Assess source quality (derivative source with digital image of original, secondary information about birth, direct evidence of residence). Document key information extracted.
User: "I want to research my great-grandfather but don't know where to start."
Response: Guide through research planning workflow. Define objective (identify parents? determine birth location?). Formulate specific research questions. List known information and gaps. Identify potential sources (census, vital records, probate, military). Develop search strategy with priorities. Create timeline. Apply GPS framework. Generate research plan document with concrete next actions. Present the plan to the user. If the user then explicitly requests "please execute this research plan," proceed with Step 3 (execution) using web_search and other tools systematically while documenting all activities.
Writing Style
Follow genealogical professional standards:
- Use precise, objective language
- Cite sources consistently
- Acknowledge uncertainty appropriately
- Apply technical terms correctly (primary/secondary, original/derivative)
- Structure proof arguments logically
- Balance scholarly rigor with clarity
Always operate within the Genealogical Proof Standard framework, helping researchers build defensible, well-documented conclusions based on thorough evidence analysis.
Generate Swagger Documentation
Generate OpenAPI docs from your codebase in seconds with automatic API key setup.
How It Works
This skill automates the Swagger/OpenAPI documentation generation:
- API Key Setup - Accepts your OpenAI API key and sets it as an environment variable
- Initialization - Downloads and sets up the apimesh tool
- Automatic Processing - The tool analyzes your codebase and generates documentation
- Output - Outputs are saved to the apimesh/ directory
Setup Requirements
You need an OpenAI API key to use this skill. Get one from OpenAI's platform if you don't have one already.
Recommended: Quick Setup with API Key
The easiest way to use this skill is to pass your API key directly:
/Users/ankits/.claude/skills/generate-swagger-docs/generate-with-key.sh "sk-proj-your-api-key-here"
This will:
- Accept your OpenAI API key as an argument
- Create the
apimesh/directory and download the apimesh tool - Set up the environment variables correctly
- Generate your Swagger documentation automatically
- Display the output file locations
Automatic Flow
When you run this skill:
-
First Time: You'll be prompted for your OpenAI API key (starts with
sk-proj-)- The key is saved locally and used for subsequent runs
- The key is NOT committed to version control
-
Subsequent Runs: The skill uses the saved API key automatically
- No additional prompts for the key unless you clear the config
-
Framework Detection: Automatically detects your API framework
- Supports: Express, NestJS, FastAPI, Django, Rails, Go, and more
What It Does
- Scans your repository for API endpoints
- Detects the web framework (Django, Flask, FastAPI, Express, NestJS, Rails, Go)
- Generates OpenAPI 3.0 specification (
swagger.json) - Creates interactive HTML documentation (
apimesh-docs.html)
Output
apimesh/swagger.json- OpenAPI 3.0 specapimesh/apimesh-docs.html- Interactive Swagger UI (self-contained, shareable)apimesh/config.json- Saved configuration (includes your settings, gitignore this file)
Important Notes
- Your OpenAI API key is needed for the LLM analysis
- The generated
config.jsonshould be added to.gitignoreas it contains secrets - Framework detection is automatic but can be manually specified if needed
- The tool supports both public and private repositories
API Key Setup Methods
Method 1: Wrapper Script (Recommended) ✓
Use the provided wrapper script that properly handles environment variable propagation:
/Users/ankits/.claude/skills/generate-swagger-docs/generate-with-key.sh "sk-proj-your-api-key-here"
Why this works best:
- Properly passes the API key to the Python subprocess
- No interactive prompts in non-TTY environments
- Handles environment variable propagation correctly
- Provides clear success/error messages
Method 2: Using Saved Configuration
After the first run with Method 1, your key is saved in apimesh/config.json. On subsequent runs, you can omit the key (if you trust your local setup):
/Users/ankits/.claude/skills/generate-swagger-docs/generate-with-key.sh
Important: Never commit the config.json file to version control. Add it to .gitignore.
Method 3: Manual apimesh Setup
If you need more control, download and run apimesh directly:
export OPENAI_API_KEY="sk-proj-your-api-key-here"
mkdir -p apimesh && \
curl -sSL https://raw.githubusercontent.com/qodex-ai/apimesh/refs/heads/main/run.sh -o apimesh/run.sh && \
chmod +x apimesh/run.sh && \
cd apimesh && \
OPENAI_API_KEY="$OPENAI_API_KEY" ./run.sh
Note: The OPENAI_API_KEY must be explicitly passed to the subprocess as shown above.
Anthropic Brand Styling
Overview
To access Anthropic's official brand identity and style resources, use this skill.
Keywords: branding, corporate identity, visual identity, post-processing, styling, brand colors, typography, Anthropic brand, visual formatting, visual design
Brand Guidelines
Colors
Main Colors:
- Dark:
#141413- Primary text and dark backgrounds - Light:
#faf9f5- Light backgrounds and text on dark - Mid Gray:
#b0aea5- Secondary elements - Light Gray:
#e8e6dc- Subtle backgrounds
Accent Colors:
- Orange:
#d97757- Primary accent - Blue:
#6a9bcc- Secondary accent - Green:
#788c5d- Tertiary accent
Typography
- Headings: Poppins (with Arial fallback)
- Body Text: Lora (with Georgia fallback)
- Note: Fonts should be pre-installed in your environment for best results
Features
Smart Font Application
- Applies Poppins font to headings (24pt and larger)
- Applies Lora font to body text
- Automatically falls back to Arial/Georgia if custom fonts unavailable
- Preserves readability across all systems
Text Styling
- Headings (24pt+): Poppins font
- Body text: Lora font
- Smart color selection based on background
- Preserves text hierarchy and formatting
Shape and Accent Colors
- Non-text shapes use accent colors
- Cycles through orange, blue, and green accents
- Maintains visual interest while staying on-brand
Technical Details
Font Management
- Uses system-installed Poppins and Lora fonts when available
- Provides automatic fallback to Arial (headings) and Georgia (body)
- No font installation required - works with existing system fonts
- For best results, pre-install Poppins and Lora fonts in your environment
Color Application
- Uses RGB color values for precise brand matching
- Applied via python-pptx's RGBColor class
- Maintains color fidelity across different systems
AWS CDK Development
This skill provides comprehensive guidance for developing AWS infrastructure using the Cloud Development Kit (CDK), with integrated MCP servers for accessing latest AWS knowledge and CDK utilities.
AWS Documentation Requirement
CRITICAL: This skill requires AWS MCP tools for accurate, up-to-date AWS information.
Before Answering AWS Questions
-
Always verify using AWS MCP tools (if available):
mcp__aws-mcp__aws___search_documentationormcp__*awsdocs*__aws___search_documentation- Search AWS docsmcp__aws-mcp__aws___read_documentationormcp__*awsdocs*__aws___read_documentation- Read specific pagesmcp__aws-mcp__aws___get_regional_availability- Check service availability
-
If AWS MCP tools are unavailable:
- Guide user to configure AWS MCP: See AWS MCP Setup Guide
- Help determine which option fits their environment:
- Has uvx + AWS credentials → Full AWS MCP Server
- No Python/credentials → AWS Documentation MCP (no auth)
- If cannot determine → Ask user which option to use
Integrated MCP Servers
This skill includes the CDK MCP server automatically configured with the plugin:
AWS CDK MCP Server
When to use: For CDK-specific guidance and utilities
- Get CDK construct recommendations
- Retrieve CDK best practices
- Access CDK pattern suggestions
- Validate CDK configurations
- Get help with CDK-specific APIs
Important: Leverage this server for CDK construct guidance and advanced CDK operations.
When to Use This Skill
Use this skill when:
- Creating new CDK stacks or constructs
- Refactoring existing CDK infrastructure
- Implementing Lambda functions within CDK
- Following AWS CDK best practices
- Validating CDK stack configurations before deployment
- Verifying AWS service capabilities and regional availability
Core CDK Principles
Resource Naming
CRITICAL: Do NOT explicitly specify resource names when they are optional in CDK constructs.
Why: CDK-generated names enable:
- Reusable patterns: Deploy the same construct/pattern multiple times without conflicts
- Parallel deployments: Multiple stacks can deploy simultaneously in the same region
- Cleaner shared logic: Patterns and shared code can be initialized multiple times without name collision
- Stack isolation: Each stack gets uniquely identified resources automatically
Pattern: Let CDK generate unique names automatically using CloudFormation's naming mechanism.
// ❌ BAD - Explicit naming prevents reusability and parallel deployments
new lambda.Function(this, 'MyFunction', {
functionName: 'my-lambda', // Avoid this
// ...
});
// ✅ GOOD - Let CDK generate unique names
new lambda.Function(this, 'MyFunction', {
// No functionName specified - CDK generates: StackName-MyFunctionXXXXXX
// ...
});
Security Note: For different environments (dev, staging, prod), follow AWS Security Pillar best practices by using separate AWS accounts rather than relying on resource naming within a single account. Account-level isolation provides stronger security boundaries.
Lambda Function Development
Use the appropriate Lambda construct based on runtime:
TypeScript/JavaScript: Use @aws-cdk/aws-lambda-nodejs
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
new NodejsFunction(this, 'MyFunction', {
entry: 'lambda/handler.ts',
handler: 'handler',
// Automatically handles bundling, dependencies, and transpilation
});
Python: Use @aws-cdk/aws-lambda-python
import { PythonFunction } from '@aws-cdk/aws-lambda-python-alpha';
new PythonFunction(this, 'MyFunction', {
entry: 'lambda',
index: 'handler.py',
handler: 'handler',
// Automatically handles dependencies and packaging
});
Benefits:
- Automatic bundling and dependency management
- Transpilation handled automatically
- No manual packaging required
- Consistent deployment patterns
Pre-Deployment Validation
Use a multi-layer validation strategy for comprehensive CDK quality checks:
Layer 1: Real-Time IDE Feedback (Recommended)
For TypeScript/JavaScript projects:
Install cdk-nag for synthesis-time validation:
npm install --save-dev cdk-nag
Add to your CDK app:
import { Aspects } from 'aws-cdk-lib';
import { AwsSolutionsChecks } from 'cdk-nag';
const app = new App();
Aspects.of(app).add(new AwsSolutionsChecks());
Optional - VS Code users: Install CDK NAG Validator extension for faster feedback on file save.
For Python/Java/C#/Go projects: cdk-nag is available in all CDK languages and provides the same synthesis-time validation.
Layer 2: Synthesis-Time Validation (Required)
-
Synthesis with cdk-nag: Validate stack with comprehensive rules
cdk synth # cdk-nag runs automatically via Aspects -
Suppress legitimate exceptions with documented reasons:
import { NagSuppressions } from 'cdk-nag'; // Document WHY the exception is needed NagSuppressions.addResourceSuppressions(resource, [ { id: 'AwsSolutions-L1', reason: 'Lambda@Edge requires specific runtime for CloudFront compatibility' } ]);
Layer 3: Pre-Commit Safety Net
-
Build: Ensure compilation succeeds
npm run build # or language-specific build command -
Tests: Run unit and integration tests
npm test # or pytest, mvn test, etc. -
Validation Script: Meta-level checks
./scripts/validate-stack.sh
The validation script now focuses on:
- Language detection
- Template size and resource count analysis
- Synthesis success verification
- (Note: Detailed anti-pattern checks are handled by cdk-nag)
Workflow Guidelines
Development Workflow
- Design: Plan infrastructure resources and relationships
- Verify AWS Services: Use AWS Documentation MCP to confirm service availability and features
- Check regional availability for all required services
- Verify service limits and quotas
- Confirm latest API specifications
- Implement: Write CDK constructs following best practices
- Use CDK MCP server for construct recommendations
- Reference CDK best practices via MCP tools
- Validate: Run pre-deployment checks (see above)
- Synthesize: Generate CloudFormation templates
- Review: Examine synthesized templates for correctness
- Deploy: Deploy to target environment
- Verify: Confirm resources are created correctly
Stack Organization
- Use nested stacks for complex applications
- Separate concerns into logical construct boundaries
- Export values that other stacks may need
- Use CDK context for environment-specific configuration
Testing Strategy
- Unit test individual constructs
- Integration test stack synthesis
- Snapshot test CloudFormation templates
- Validate resource properties and relationships
Using MCP Servers Effectively
When to Use AWS Documentation MCP
Always verify before implementing:
- New AWS service features or configurations
- Service availability in target regions
- API parameter specifications
- Service limits and quotas
- Security best practices for AWS services
Example scenarios:
- "Check if Lambda supports Python 3.13 runtime"
- "Verify DynamoDB is available in eu-south-2"
- "What are the current Lambda timeout limits?"
- "Get latest S3 encryption options"
When to Use CDK MCP Server
Leverage for CDK-specific guidance:
- CDK construct selection and usage
- CDK API parameter options
- CDK best practice patterns
- Construct property configurations
- CDK-specific optimizations
Example scenarios:
- "What's the recommended CDK construct for API Gateway REST API?"
- "How to configure NodejsFunction bundling options?"
- "Best practices for CDK stack organization"
- "CDK construct for DynamoDB with auto-scaling"
MCP Usage Best Practices
- Verify First: Always check AWS Documentation MCP before implementing new features
- Regional Validation: Check service availability in target deployment regions
- CDK Guidance: Use CDK MCP for construct-specific recommendations
- Stay Current: MCP servers provide latest information beyond knowledge cutoff
- Combine Sources: Use both skill patterns and MCP servers for comprehensive guidance
CDK Patterns Reference
For detailed CDK patterns, anti-patterns, and architectural guidance, refer to the comprehensive reference:
File: references/cdk-patterns.md
This reference includes:
- Common CDK patterns and their use cases
- Anti-patterns to avoid
- Security best practices
- Cost optimization strategies
- Performance considerations
Additional Resources
- Validation Script:
scripts/validate-stack.sh- Pre-deployment validation - CDK Patterns:
references/cdk-patterns.md- Detailed pattern library - AWS Documentation MCP: Integrated for latest AWS information
- CDK MCP Server: Integrated for CDK-specific guidance
GitHub Actions Integration
When GitHub Actions workflow files exist in the repository, ensure all checks defined in .github/workflows/ pass before committing. This prevents CI/CD failures and maintains code quality standards.
Web Artifacts Builder
To build powerful frontend claude.ai artifacts, follow these steps:
- Initialize the frontend repo using
scripts/init-artifact.sh - Develop your artifact by editing the generated code
- Bundle all code into a single HTML file using
scripts/bundle-artifact.sh - Display artifact to user
- (Optional) Test the artifact
Stack: React 18 + TypeScript + Vite + Parcel (bundling) + Tailwind CSS + shadcn/ui
Design & Style Guidelines
VERY IMPORTANT: To avoid what is often referred to as "AI slop", avoid using excessive centered layouts, purple gradients, uniform rounded corners, and Inter font.
Quick Start
Step 1: Initialize Project
Run the initialization script to create a new React project:
bash scripts/init-artifact.sh <project-name>
cd <project-name>
This creates a fully configured project with:
- ✅ React + TypeScript (via Vite)
- ✅ Tailwind CSS 3.4.1 with shadcn/ui theming system
- ✅ Path aliases (
@/) configured - ✅ 40+ shadcn/ui components pre-installed
- ✅ All Radix UI dependencies included
- ✅ Parcel configured for bundling (via .parcelrc)
- ✅ Node 18+ compatibility (auto-detects and pins Vite version)
Step 2: Develop Your Artifact
To build the artifact, edit the generated files. See Common Development Tasks below for guidance.
Step 3: Bundle to Single HTML File
To bundle the React app into a single HTML artifact:
bash scripts/bundle-artifact.sh
This creates bundle.html - a self-contained artifact with all JavaScript, CSS, and dependencies inlined. This file can be directly shared in Claude conversations as an artifact.
Requirements: Your project must have an index.html in the root directory.
What the script does:
- Installs bundling dependencies (parcel, @parcel/config-default, parcel-resolver-tspaths, html-inline)
- Creates
.parcelrcconfig with path alias support - Builds with Parcel (no source maps)
- Inlines all assets into single HTML using html-inline
Step 4: Share Artifact with User
Finally, share the bundled HTML file in conversation with the user so they can view it as an artifact.
Step 5: Testing/Visualizing the Artifact (Optional)
Note: This is a completely optional step. Only perform if necessary or requested.
To test/visualize the artifact, use available tools (including other Skills or built-in tools like Playwright or Puppeteer). In general, avoid testing the artifact upfront as it adds latency between the request and when the finished artifact can be seen. Test later, after presenting the artifact, if requested or if issues arise.
Reference
- shadcn/ui components: https://ui.shadcn.com/docs/components
Sponsors
Details
- Marketplace
- qodex-ai/ai-agent-skills
- Category
- Community