
memstack
131 battle-tested skills for Claude Code. Session memory, git workflows, database migrations, security scanning, deployments, and more.
- version
- 3.10.5
- GitHub stars
- 433
Install
/plugin install memstack@cwinvestments-memstackRun it inside Claude Code after adding the marketplace with /plugin marketplace add cwinvestments/memstack.
Contents
Discovered from sourceSkills 87
API Integration: Building system connector...
Develops system-to-system connectors with REST/GraphQL patterns, authentication flows, rate limit handling, data mapping, error recovery, and SDK wrapper generation.
Activation
When this skill activates, output:
API Integration: Building system connector...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "API integration", "connect APIs", "sync data" | ACTIVE |
| User says "data mapping" or "rate limiting" | ACTIVE |
| User needs to build a connector between two systems | ACTIVE |
| User wants a visual n8n workflow | DORMANT: use n8n Workflow Builder |
| User wants to receive webhooks | DORMANT: use Webhook Designer |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Ignore rate limits" | Getting blocked by the API wastes hours of debugging. Implement rate limiting from day one. |
| "No retry logic" | APIs have transient failures. Without retry + backoff, your sync silently drops data. |
| "Store tokens in code" | Use environment variables or a secrets manager. Tokens in code end up in git history. |
| "Map fields manually every time" | Build a reusable mapping layer. Manual field-by-field transforms are fragile and hard to update. |
| "No pagination handling" | Most APIs return paginated results. If you only read page 1, you're missing data. |
Protocol
Step 1: Gather Integration Requirements
If the user hasn't provided details, ask:
- Source system: where does the data come from? (API name, docs URL)
- Destination: where does it go? (your DB, another API, file)
- Data: what entities are synced? (users, orders, products, events)
- Direction: one-way, two-way, or event-driven?
- Auth: how does the API authenticate? (API key, OAuth 2.0, JWT, Basic)
- Volume: how much data? How often? (1K records/day vs 1M)
Step 2: Implement Authentication
| Auth Type | Implementation | Token Lifecycle |
|---|---|---|
| API Key | Header: X-API-Key: {key} or query param | Static: rotate manually |
| Bearer Token | Header: Authorization: Bearer {token} | Expires: refresh needed |
| OAuth 2.0 | Auth code flow → access + refresh tokens | Auto-refresh on 401 |
| JWT | Sign claims → Authorization: Bearer {jwt} | Short-lived: re-sign |
| Basic Auth | Header: Authorization: Basic {base64} | Static |
| HMAC | Sign request body → custom header | Per-request signing |
OAuth 2.0 token refresh pattern:
class ApiClient {
private accessToken: string;
private refreshToken: string;
private expiresAt: number;
async request(method: string, path: string, body?: any): Promise<any> {
if (Date.now() >= this.expiresAt - 60_000) { // Refresh 60s early
await this.refreshAccessToken();
}
const response = await fetch(`${this.baseUrl}${path}`, {
method,
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json',
},
body: body ? JSON.stringify(body) : undefined,
});
if (response.status === 401) {
await this.refreshAccessToken();
return this.request(method, path, body); // Retry once
}
return response.json();
}
}
Step 3: Handle Rate Limiting
Rate limit detection and backoff:
async function requestWithRateLimit(
fn: () => Promise<Response>,
maxRetries = 3
): Promise<Response> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const response = await fn();
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '0');
const waitMs = retryAfter > 0
? retryAfter * 1000
: Math.min(1000 * Math.pow(2, attempt), 30_000); // Exponential backoff, max 30s
console.log(`Rate limited. Waiting ${waitMs}ms (attempt ${attempt + 1})`);
await sleep(waitMs);
continue;
}
return response;
}
throw new Error('Rate limit exceeded after max retries');
}
Proactive rate limiting (token bucket):
class RateLimiter {
private tokens: number;
private lastRefill: number;
constructor(
private maxTokens: number, // e.g., 100
private refillRate: number, // tokens per second, e.g., 10
) {
this.tokens = maxTokens;
this.lastRefill = Date.now();
}
async acquire(): Promise<void> {
this.refill();
if (this.tokens <= 0) {
const waitMs = (1 / this.refillRate) * 1000;
await sleep(waitMs);
this.refill();
}
this.tokens--;
}
private refill(): void {
const now = Date.now();
const elapsed = (now - this.lastRefill) / 1000;
this.tokens = Math.min(this.maxTokens, this.tokens + elapsed * this.refillRate);
this.lastRefill = now;
}
}
Step 4: Build Data Mapper
Mapping layer pattern:
// Define field mappings declaratively
interface FieldMapping {
source: string; // Source field path (dot notation)
target: string; // Target field path
transform?: (val: any) => any; // Optional transformation
required?: boolean;
}
const orderMappings: FieldMapping[] = [
{ source: 'id', target: 'externalId', required: true },
{ source: 'customer.email', target: 'email', required: true },
{ source: 'total_price', target: 'amount', transform: (v) => parseFloat(v) * 100 }, // dollars to cents
{ source: 'created_at', target: 'createdAt', transform: (v) => new Date(v).toISOString() },
{ source: 'line_items', target: 'items', transform: mapLineItems },
];
function mapRecord(source: any, mappings: FieldMapping[]): any {
const target: any = {};
for (const m of mappings) {
const value = getNestedValue(source, m.source);
if (value === undefined && m.required) {
throw new Error(`Missing required field: ${m.source}`);
}
if (value !== undefined) {
setNestedValue(target, m.target, m.transform ? m.transform(value) : value);
}
}
return target;
}
Step 5: Handle Pagination
Common pagination patterns:
| Pattern | How to Detect | Implementation |
|---|---|---|
| Offset/limit | ?offset=0&limit=100 | Increment offset until empty results |
| Page number | ?page=1&per_page=100 | Increment page until last page |
| Cursor-based | next_cursor in response | Use cursor until null/empty |
| Link header | Link: <url>; rel="next" | Follow the next URL |
Generic paginator:
async function* paginate<T>(
fetchPage: (cursor?: string) => Promise<{ data: T[]; nextCursor?: string }>
): AsyncGenerator<T> {
let cursor: string | undefined;
do {
const page = await fetchPage(cursor);
for (const item of page.data) {
yield item;
}
cursor = page.nextCursor;
} while (cursor);
}
// Usage
for await (const order of paginate(fetchOrders)) {
await processOrder(order);
}
Step 6: Error Recovery & Sync State
Sync state tracking:
CREATE TABLE sync_state (
integration VARCHAR(100) PRIMARY KEY,
last_cursor VARCHAR(255),
last_sync_at TIMESTAMPTZ NOT NULL,
items_synced INTEGER NOT NULL DEFAULT 0,
status VARCHAR(20) NOT NULL DEFAULT 'idle', -- idle | running | failed
error TEXT
);
Incremental sync pattern:
async function incrementalSync(integration: string): Promise<void> {
const state = await getSyncState(integration);
let cursor = state.lastCursor;
let count = 0;
try {
await updateSyncState(integration, { status: 'running' });
for await (const item of paginate((c) => fetchItems(c || cursor))) {
await processItem(item);
cursor = item.id; // Track progress
count++;
// Checkpoint every 100 items (resume from here on failure)
if (count % 100 === 0) {
await updateSyncState(integration, { lastCursor: cursor, itemsSynced: count });
}
}
await updateSyncState(integration, {
status: 'idle', lastCursor: cursor,
lastSyncAt: new Date(), itemsSynced: count
});
} catch (error) {
await updateSyncState(integration, {
status: 'failed', lastCursor: cursor, error: error.message
});
throw error;
}
}
Step 7: Production Checklist
- Authentication handles token refresh (no manual token replacement)
- Rate limiter respects API's documented limits
- Retry logic with exponential backoff for 429 and 5xx responses
- Pagination handles all pages (not just page 1)
- Data mapper validates required fields before writing
- Sync state persisted, can resume from last checkpoint on failure
- Structured logging with correlation IDs
- Secrets in environment variables or secrets manager
- Error alerts configured (Slack, email, or PagerDuty)
- Integration tested with production-volume data
Output Format
# API Integration: [Source] → [Destination]
## Overview
- **Direction:** [One-way / Two-way / Event-driven]
- **Entities:** [What's being synced]
- **Auth:** [Auth method]
- **Rate limit:** [X requests/second]
- **Sync frequency:** [Real-time / Every X minutes / Daily]
## Authentication
[Implementation from Step 2]
## Rate Limiting
[Implementation from Step 3]
## Data Mapping
[Mapping definitions from Step 4]
## Pagination
[Pattern from Step 5]
## Sync State & Recovery
[Implementation from Step 6]
## Production Checklist
[From Step 7]
Completion
API Integration: Complete!
Integration: [Source] → [Destination]
Entities synced: [List]
Auth method: [Method]
Rate limit handling: [Strategy]
Pagination: [Pattern]
Sync state: [Checkpoint-based]
Next steps:
1. Implement using the code patterns above
2. Set up credentials in your secrets manager
3. Run an initial full sync with a small dataset
4. Verify data mapping accuracy in destination
5. Enable incremental sync on schedule
Level History
- Lv.1: Base: 6 auth patterns (API key, Bearer, OAuth 2.0 with refresh, JWT, Basic, HMAC), reactive + proactive rate limiting (token bucket), declarative data mapper with transformations, 4 pagination patterns with generic async generator, incremental sync with checkpoint-based recovery, sync state table, production checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Content Pipeline: Automating content workflow...
Automates end-to-end content workflows from ideation through draft, review, approval, cross-platform formatting, scheduling, and publishing with CMS integration and image optimization.
Activation
When this skill activates, output:
Content Pipeline: Automating content workflow...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "content pipeline", "content automation", "auto-publish" | ACTIVE |
| User says "repurpose content" or "multi-platform publishing" | ACTIVE |
| User wants to automate content creation through distribution | ACTIVE |
| User wants a single blog post | DORMANT: use Blog Post |
| User wants a single social media post | DORMANT, use Twitter Thread or TikTok Script |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Same content on every platform" | Each platform has its own format, tone, and audience expectations. Repurpose, don't copy-paste. |
| "Automate quality away" | Automation handles formatting and scheduling, not editorial judgment. Keep human review in the loop. |
| "No content calendar" | Publishing without a schedule leads to feast-or-famine posting. Consistency beats volume. |
| "Skip image optimization" | Unoptimized images slow page load and fail platform size requirements. Automate resizing. |
| "Publish and forget" | Monitor engagement within 24-48 hours. Boost winners, learn from underperformers. |
Protocol
Step 1: Gather Pipeline Requirements
If the user hasn't provided details, ask:
- Content types: what do you produce? (blog, newsletter, social, video, podcast)
- Platforms: where do you publish? (website, Twitter/X, LinkedIn, Instagram, YouTube, email)
- Frequency: how often? (daily, 3x/week, weekly)
- Team: who's involved? (writer, editor, designer, social manager)
- CMS: what do you use? (WordPress, Ghost, Notion, Webflow, headless CMS)
- Current process: what's manual today that should be automated?
Step 2: Design Pipeline Stages
[Ideation] → [Draft] → [Review] → [Approve] → [Format] → [Schedule] → [Publish] → [Monitor]
Stage definitions:
| Stage | Owner | Input | Output | Automation Level |
|---|---|---|---|---|
| Ideation | Content lead | Keyword research, trending topics, audience questions | Content brief | Semi-auto (AI-assisted topic generation) |
| Draft | Writer | Content brief | Raw draft (Markdown/Docs) | Manual (AI-assisted) |
| Review | Editor | Raw draft | Edited draft with feedback | Manual |
| Approve | Content lead | Edited draft | Approved for publishing | Manual (checklist-gated) |
| Format | Pipeline | Approved content | Platform-specific versions | Fully automated |
| Schedule | Pipeline | Formatted content | Queued posts with dates/times | Fully automated |
| Publish | Pipeline | Scheduled posts | Live content across platforms | Fully automated |
| Monitor | Marketing | Published content | Engagement metrics | Semi-auto (dashboard) |
Step 3: Content Repurposing Matrix
Define how one piece of content becomes many:
| Source | → Blog Post | → Twitter Thread | → Newsletter | ||
|---|---|---|---|---|---|
| Blog post | Original | Key points (5-10 tweets) | Summary + insights | Featured article | Quote card + carousel |
| Video | Transcript → post | Key quotes | Behind-the-scenes | Recap + link | Clips (15-60s) |
| Podcast | Show notes | Soundbite quotes | Episode summary | Weekly roundup | Audiogram |
| Newsletter | Expanded article | Thread from section | Cross-post | Original | Highlight card |
Repurposing rules:
- Each platform version should feel native (not like a cross-post)
- Adjust tone: Twitter (punchy, direct), LinkedIn (professional, storytelling), Instagram (visual, emotional)
- Adjust length: Twitter (280 chars/tweet), LinkedIn (1300 chars optimal), Instagram (2200 chars max)
- Add platform-specific elements: hashtags (Instagram), mentions (Twitter), links (LinkedIn)
Step 4: Image Optimization Pipeline
Platform image specs:
| Platform | Size | Aspect Ratio | Max File Size | Format |
|---|---|---|---|---|
| Blog (hero) | 1200×630 | 1.91:1 | 200KB | WebP (JPEG fallback) |
| 1200×675 | 16:9 | 5MB | PNG/JPEG | |
| 1200×627 | 1.91:1 | 5MB | PNG/JPEG | |
| Instagram (feed) | 1080×1080 | 1:1 | 8MB | JPEG |
| Instagram (story) | 1080×1920 | 9:16 | 8MB | JPEG |
| Newsletter | 600×300 | 2:1 | 100KB | PNG/JPEG |
| Open Graph | 1200×630 | 1.91:1 | 200KB | PNG/JPEG |
Automated image processing:
# Using sharp (Node.js) or ImageMagick
# From one source image, generate all platform variants:
sharp(sourceImage)
.resize(1200, 630, { fit: 'cover' })
.webp({ quality: 80 })
.toFile('blog-hero.webp');
sharp(sourceImage)
.resize(1080, 1080, { fit: 'cover' })
.jpeg({ quality: 85 })
.toFile('instagram-square.jpg');
sharp(sourceImage)
.resize(1080, 1920, { fit: 'cover' })
.jpeg({ quality: 85 })
.toFile('instagram-story.jpg');
Step 5: Scheduling Strategy
Optimal posting times (general: adjust to your analytics):
| Platform | Best Days | Best Times (ET) | Frequency |
|---|---|---|---|
| Blog | Tue-Thu | 10 AM | 1-3x/week |
| Twitter/X | Mon-Fri | 8 AM, 12 PM, 5 PM | 1-3x/day |
| Tue-Thu | 7-8 AM, 12 PM | 3-5x/week | |
| Mon, Wed, Fri | 11 AM, 1 PM | 3-5x/week | |
| Newsletter | Tue or Thu | 9-10 AM | 1x/week |
| YouTube | Thu-Sat | 2-4 PM | 1-2x/week |
Content calendar template:
## Week of [Date]
| Day | Blog | Twitter | LinkedIn | Newsletter | Instagram |
|-----|------|---------|----------|-----------|-----------|
| Mon | none | [Thread from Friday's blog] | none | none | [Quote card] |
| Tue | [New post: Topic] | [3 promo tweets] | [Post: summary] | [Weekly send] | none |
| Wed | none | [Engagement thread] | none | none | [Carousel] |
| Thu | none | [Tips thread] | [Article share] | none | [Behind-scenes] |
| Fri | [New post: Topic] | [3 promo tweets] | [Post: summary] | none | [Quote card] |
Step 6: CMS Integration Patterns
Headless CMS workflow (API-based):
// Publish to CMS via API
async function publishToCMS(content: {
title: string;
body: string;
slug: string;
featuredImage: string;
tags: string[];
publishAt?: Date;
}): Promise<string> {
const response = await cmsClient.post('/posts', {
title: content.title,
content: content.body,
slug: content.slug,
featured_image: content.featuredImage,
tags: content.tags,
status: content.publishAt ? 'scheduled' : 'published',
published_at: content.publishAt?.toISOString(),
});
return response.data.url;
}
Social media scheduling (via Buffer/Hootsuite API or native):
async function scheduleToSocial(posts: SocialPost[]): Promise<void> {
for (const post of posts) {
await bufferClient.post('/updates/create', {
profile_ids: [post.profileId],
text: post.content,
media: post.imageUrl ? { photo: post.imageUrl } : undefined,
scheduled_at: post.scheduledAt.toISOString(),
});
}
}
Step 7: Monitoring & Optimization
Engagement tracking (24-48 hours post-publish):
| Metric | Blog | Newsletter | ||
|---|---|---|---|---|
| Views/Impressions | Page views | Impressions | Impressions | Opens |
| Engagement | Time on page | Likes + replies | Reactions + comments | Click rate |
| Conversion | CTA clicks | Link clicks | Link clicks | Reply rate |
| Share/Viral | Social shares | Retweets | Reposts | Forwards |
Content scoring formula:
Score = (Engagement Rate × 40%) + (Conversion Rate × 40%) + (Shares × 20%)
- A-tier (top 20%): Repurpose aggressively, boost with ads, create sequel content
- B-tier (middle 60%): Standard distribution, note what worked
- C-tier (bottom 20%): Analyze why it underperformed, adjust future topics
Output Format
# Content Pipeline: [Brand/Product Name]
## Pipeline Stages
[Stage diagram and definitions from Step 2]
## Repurposing Matrix
[From Step 3: source → platform transformations]
## Image Specs
[Platform-specific sizes from Step 4]
## Content Calendar
[Weekly template from Step 5]
## CMS & Social Integration
[API patterns from Step 6]
## Monitoring Dashboard
[Metrics and scoring from Step 7]
Completion
Content Pipeline: Complete!
Platforms: [Count] ([list])
Content types: [Count]
Pipeline stages: 8 (ideation → monitor)
Publishing frequency: [X pieces/week across platforms]
Automation level: [X/8 stages automated]
Next steps:
1. Set up CMS API access and social scheduling tool
2. Create image templates for each platform
3. Build the first week's content calendar
4. Automate the Format → Schedule → Publish stages
5. Review engagement data weekly and adjust
Level History
- Lv.1: Base: 8-stage pipeline (ideation through monitoring), content repurposing matrix (blog/video/podcast → 5 platforms), platform image specs with automated processing, optimal posting times, content calendar template, CMS integration patterns (headless API, social scheduling), engagement monitoring with content scoring formula. (Origin: MemStack Pro v3.2, Mar 2026)
Cron Scheduler: Building scheduled job...
Builds production-grade scheduled jobs with cron syntax, timezone handling, overlap prevention, health checks, monitoring, alerting, and structured logging.
Activation
When this skill activates, output:
Cron Scheduler: Building scheduled job...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "cron job", "scheduled task", "run every" | ACTIVE |
| User says "cron expression" or "recurring job" | ACTIVE |
| User needs a time-based scheduled task with monitoring | ACTIVE |
| User wants a visual n8n workflow | DORMANT: use n8n Workflow Builder |
| User wants an event-driven webhook | DORMANT: use Webhook Designer |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "No overlap prevention" | If a job takes 10 min and runs every 5 min, you get concurrent executions corrupting data. |
| "Ignore timezones" | Cron defaults to server timezone. Midnight UTC ≠ midnight local. Always set TZ explicitly. |
| "No monitoring" | Silent job failures are invisible. You won't know it broke until users complain. |
| "Log to stdout only" | Stdout disappears on restart. Use structured logging with persistence. |
| "Run as root" | Principle of least privilege. Run jobs under a dedicated service account. |
Protocol
Step 1: Gather Job Requirements
If the user hasn't provided details, ask:
- Task: what does the job do? (sync data, send emails, clean up, generate reports)
- Schedule: how often? (every 5 min, hourly, daily at 2 AM, weekly)
- Duration: how long does a typical run take?
- Timezone: which timezone matters? (UTC, user's local, business hours)
- Platform: where does this run? (server crontab, cloud function, Docker, Kubernetes)
- Failure mode: what happens if it fails? (retry, alert, skip until next run)
Step 2: Write the Cron Expression
Cron syntax (5-field standard):
┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-7, 0 and 7 = Sunday)
│ │ │ │ │
* * * * *
Common schedule reference:
| Schedule | Expression | Notes |
|---|---|---|
| Every minute | * * * * * | Testing only: too aggressive for production |
| Every 5 minutes | */5 * * * * | Good for near-real-time sync |
| Every 15 minutes | */15 * * * * | Light polling |
| Every hour | 0 * * * * | At minute 0 of every hour |
| Every 6 hours | 0 */6 * * * | 4x daily |
| Daily at 2 AM UTC | 0 2 * * * | Maintenance window |
| Daily at 9 AM ET | 0 14 * * * | 14:00 UTC = 9:00 AM ET (EST, adjust for DST) |
| Weekdays at 8 AM | 0 8 * * 1-5 | Monday through Friday |
| Weekly (Sunday midnight) | 0 0 * * 0 | Weekly cleanup |
| Monthly (1st at midnight) | 0 0 1 * * | Monthly reports |
| Quarterly (Jan/Apr/Jul/Oct 1st) | 0 0 1 1,4,7,10 * | Quarterly processing |
Timezone handling:
# System crontab, set TZ per job
CRON_TZ=America/New_York
0 9 * * * /path/to/job.sh # Runs at 9 AM Eastern (handles DST)
# Or set in the crontab header
TZ=UTC
// Node.js (node-cron), explicit timezone
import cron from 'node-cron';
cron.schedule('0 9 * * *', () => {
runDailyReport();
}, {
timezone: 'America/New_York'
});
Step 3: Implement Overlap Prevention
Lock-based approach (recommended):
import { acquireLock, releaseLock } from './lockService';
async function runJob() {
const lockKey = 'job:daily-report';
const lockTTL = 3600; // seconds, must exceed max job duration
const acquired = await acquireLock(lockKey, lockTTL);
if (!acquired) {
console.log('Job already running: skipping this execution');
return;
}
try {
await executeJobLogic();
} finally {
await releaseLock(lockKey);
}
}
Lock implementations by platform:
| Platform | Lock Method | TTL Support |
|---|---|---|
| Redis | SET key value NX EX ttl | Yes |
| PostgreSQL | pg_advisory_lock(id) | Session-based |
| File system | flock or PID file | Manual cleanup |
| DynamoDB | Conditional put with TTL | Yes |
| Kubernetes | CronJob concurrencyPolicy: Forbid | Built-in |
PID file approach (simple servers):
#!/bin/bash
PIDFILE="/tmp/myjob.pid"
if [ -f "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") 2>/dev/null; then
echo "Job already running (PID $(cat $PIDFILE))"
exit 0
fi
echo $$ > "$PIDFILE"
trap "rm -f $PIDFILE" EXIT
# Job logic here
Step 4: Structured Logging
interface JobLog {
job: string;
runId: string; // Unique per execution
phase: 'start' | 'progress' | 'complete' | 'error';
timestamp: string;
durationMs?: number;
itemsProcessed?: number;
error?: string;
metadata?: Record<string, any>;
}
function logJob(entry: JobLog): void {
console.log(JSON.stringify(entry));
}
// Usage
const runId = crypto.randomUUID();
const start = Date.now();
logJob({ job: 'daily-report', runId, phase: 'start', timestamp: new Date().toISOString() });
try {
const result = await executeJobLogic();
logJob({
job: 'daily-report', runId, phase: 'complete',
timestamp: new Date().toISOString(),
durationMs: Date.now() - start,
itemsProcessed: result.count
});
} catch (error) {
logJob({
job: 'daily-report', runId, phase: 'error',
timestamp: new Date().toISOString(),
durationMs: Date.now() - start,
error: error.message
});
throw error;
}
Step 5: Monitoring & Alerting
Health check pattern: heartbeat:
// After successful job completion, ping a health check URL
async function pingHealthCheck(url: string): Promise<void> {
await fetch(url); // Services: Cronitor, Healthchecks.io, Better Uptime
}
// The monitoring service alerts if it doesn't receive a ping within the expected window
Alert conditions:
| Condition | Severity | Action |
|---|---|---|
| Job didn't run (missed heartbeat) | Critical | Page on-call |
| Job failed (error thrown) | High | Slack + email alert |
| Job duration > 2x normal | Warning | Slack notification |
| Job processed 0 items (expected >0) | Warning | Review logs |
| Job overlap detected (lock contention) | Info | Log, investigate if frequent |
Job history table (for dashboard):
CREATE TABLE job_runs (
id SERIAL PRIMARY KEY,
job_name VARCHAR(100) NOT NULL,
run_id UUID NOT NULL,
status VARCHAR(20) NOT NULL, -- 'success' | 'failure' | 'skipped'
started_at TIMESTAMPTZ NOT NULL,
completed_at TIMESTAMPTZ,
duration_ms INTEGER,
items_count INTEGER,
error TEXT,
metadata JSONB
);
CREATE INDEX idx_job_runs_name_started ON job_runs(job_name, started_at DESC);
Step 6: Production Checklist
Before deploying:
- Cron expression tested with crontab.guru
- Timezone explicitly set (never rely on server default)
- Overlap prevention implemented (lock or concurrency policy)
- Structured logging with run IDs
- Health check / heartbeat URL configured
- Alert rules set for: missed run, failure, slow run
- Graceful shutdown handling (finish current item, don't corrupt)
- Environment variables for all config (no hardcoded values)
- Job runs under dedicated service account (not root)
- Tested with realistic data volume
Maintenance:
- Review job duration trends monthly (creeping duration = scaling issue)
- Clean up job history older than 90 days
- Verify health check alerts with a test failure quarterly
Output Format
# Cron Job: [Job Name]
## Schedule
- **Expression:** [cron expression]
- **Timezone:** [TZ]
- **Frequency:** [Human-readable]
- **Expected duration:** [X minutes]
## Job Logic
[What the job does, step by step]
## Implementation
[Code with overlap prevention, logging, error handling]
## Monitoring
- **Health check:** [URL or service]
- **Alerts:** [Alert conditions]
- **Dashboard:** [Where to view job history]
## Production Checklist
[Completed checklist from Step 6]
Completion
Cron Scheduler: Complete!
Job: [Name]
Schedule: [Expression] ([timezone])
Overlap prevention: [Lock method]
Monitoring: [Health check service]
Alerts: [Count] conditions configured
Next steps:
1. Implement the job using the code templates above
2. Test the cron expression at crontab.guru
3. Deploy with overlap prevention and structured logging
4. Set up health check monitoring
5. Verify the first 3 runs succeed, then check weekly
Level History
- Lv.1: Base: Cron syntax guide with 12 common schedules, timezone handling (crontab + Node.js), overlap prevention (Redis lock, PID file, K8s ConcurrencyPolicy), structured logging with run IDs, heartbeat monitoring pattern, alert conditions (5 severities), job history table, production deployment checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Hosted MCP Catalog: Finding hosted MCP servers...
Reference guide for zero-setup hosted MCP servers that require no API keys, no local install, just point any MCP client at the URL.
Activation
| Trigger | Status |
|---|---|
| User says "what MCP servers" or "find an MCP for" | ACTIVE |
| User says "hosted MCP" or "MCP catalog" | ACTIVE |
| User says "available MCP tools" or "list MCP servers" | ACTIVE |
| User wants to BUILD an MCP server | NOT this skill: use mcp-builder |
| User wants to configure local MCP | NOT this skill: check .mcp.json docs |
Context Guard
- Do NOT use for building MCP servers (that's mcp-builder Pro skill)
- Do NOT use for local MCP server configuration
- Do NOT use for debugging MCP connection issues
- This skill ONLY helps discover and connect to hosted MCP endpoints
How Hosted MCP Works
Hosted MCP servers run remotely: no local install needed. Add the URL to your MCP client config and the tools are available immediately.
In Claude Code: add to .mcp.json:
{
"mcpServers": {
"server-name": {
"type": "url",
"url": "https://example.com/mcp"
}
}
}
In Claude Desktop: add to claude_desktop_config.json:
{
"mcpServers": {
"server-name": {
"url": "https://example.com/mcp"
}
}
}
Catalog: Official Platform MCP Servers
These are maintained by major platforms and generally stable:
| Server | URL | Tools | Use Case |
|---|---|---|---|
| Vercel | https://mcp.vercel.com | Deploy, logs, env vars, projects | Vercel deployment management |
| Supabase | https://mcp.supabase.com/mcp | DB queries, migrations, RLS | Database management |
| Sentry | https://mcp.sentry.dev/mcp | Issues, errors, performance | Error tracking |
| Stripe | https://mcp.stripe.com | Payments, customers, invoices | Payment processing |
| Linear | https://mcp.linear.app/mcp | Issues, projects, cycles | Project management |
| Slack | https://mcp.slack.com/mcp | Messages, channels, search | Team communication |
| Greptile | https://api.greptile.com/mcp | Codebase search, understanding | Code intelligence |
Note: Most official servers require OAuth authentication on first use. Claude Code handles this automatically, you'll get a browser prompt to authorize.
How to Choose
When the user needs an MCP server, help them find the right one:
Step 1: Identify the need
| User wants to... | Recommended MCP |
|---|---|
| Query a database | Supabase |
| Track errors/bugs | Sentry |
| Deploy code | Vercel |
| Process payments | Stripe |
| Manage issues/tickets | Linear |
| Send team messages | Slack |
| Search codebases | Greptile |
Step 2: Add to config
Generate the .mcp.json entry for the chosen server:
{
"mcpServers": {
"<server-name>": {
"type": "url",
"url": "<server-url>"
}
}
}
Step 3: Test the connection
After adding, restart Claude Code and verify:
- The server appears in the MCP tools list
- Authentication completes (if required)
- A simple tool call succeeds
Discovery Resources
When the catalog above doesn't cover the user's need:
| Resource | URL | Description |
|---|---|---|
| Anthropic MCP Registry | https://github.com/modelcontextprotocol/servers | Official MCP server list |
| Smithery | https://smithery.ai | MCP server marketplace |
| MCP.so | https://mcp.so | Community MCP directory |
| Glama | https://glama.ai/mcp/servers | Curated MCP catalog |
Output Template
MCP Server: [name]
URL: [endpoint]
Auth: [OAuth / API key / None]
Tools available: [list of key tools]
Config to add to .mcp.json:
{
"mcpServers": {
"[name]": {
"type": "url",
"url": "[endpoint]"
}
}
}
Restart Claude Code after adding.
Disambiguation
- "what MCP servers" / "find an MCP for" / "hosted MCP" = Hosted MCP Catalog
- "build an MCP server" / "create MCP tools" = mcp-builder (not this skill)
- "MCP not connecting" / "MCP error" = Debug directly (not this skill)
- "what tools do I have" = Check current MCP config (not this skill)
Level History
- Lv.1: Base: Hosted MCP server catalog with official platform endpoints, connection setup, discovery resources. (Origin: MemStack v3.5, Apr 2026)
n8n Workflow Builder: Designing automation workflow...
Designs visual n8n workflows with trigger selection, node mapping, data transformations, error handling, and webhook integration.
Activation
When this skill activates, output:
n8n Workflow Builder: Designing automation workflow...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "n8n workflow", "build a workflow", "automation workflow" | ACTIVE |
| User says "connect services" or wants visual automation | ACTIVE |
| User wants to automate a multi-step process with n8n | ACTIVE |
| User needs a standalone webhook endpoint | DORMANT: use Webhook Designer |
| User needs a cron/scheduled job without n8n | DORMANT: use Cron Scheduler |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "One giant workflow" | Workflows over 20 nodes become unmaintainable. Split into sub-workflows with triggers. |
| "No error handling" | Silent failures mean lost data. Every workflow needs an Error Trigger node. |
| "Hardcoded credentials" | Use n8n's credential store, never paste API keys into HTTP Request nodes. |
| "Skip testing with real data" | Test with production-like payloads. Dummy data hides type mismatches and missing fields. |
| "Poll when you can webhook" | Polling wastes resources. If the service supports webhooks, use the Webhook trigger instead. |
Protocol
Step 1: Gather Workflow Requirements
If the user hasn't provided details, ask:
- Trigger: what starts the workflow? (webhook, schedule, app event, manual)
- Input: what data comes in? (payload shape, source service)
- Actions: what should happen step-by-step?
- Output: where does the result go? (database, API, email, Slack, file)
- Error handling: what happens if a step fails?
- Frequency: how often does this run? (per event, hourly, daily)
Step 2: Select Trigger Node
| Trigger Type | n8n Node | When to Use |
|---|---|---|
| Incoming webhook | Webhook | External service sends data to you |
| Schedule | Schedule Trigger | Run at fixed intervals (cron) |
| App event | [App] Trigger | Slack message, GitHub PR, Stripe payment, etc. |
| Manual | Manual Trigger | Testing or on-demand execution |
| Email Trigger (IMAP) | React to incoming emails | |
| File change | Local File Trigger | Watch a directory for new files |
| Another workflow | Execute Workflow Trigger | Sub-workflow called by parent |
Trigger configuration template:
Trigger: [Node name]
Type: [Webhook / Schedule / App event]
Configuration:
- [Setting 1: e.g., HTTP Method: POST]
- [Setting 2: e.g., Path: /webhook/orders]
- [Setting 3: e.g., Authentication: Header Auth]
Output schema:
{
"field1": "type: description",
"field2": "type: description"
}
Step 3: Map the Workflow Nodes
Design the node sequence from trigger to output:
Workflow diagram template:
[Trigger] → [Transform/Filter] → [Action 1] → [Action 2] → [Output]
↓ (on error)
[Error Handler]
Common node patterns:
| Pattern | Nodes | Use Case |
|---|---|---|
| Filter & route | IF / Switch | Route data based on conditions |
| Transform | Set / Code / Item Lists | Reshape data between nodes |
| Batch process | SplitInBatches → Loop | Process large datasets without timeout |
| Merge streams | Merge | Combine data from parallel branches |
| Lookup & enrich | HTTP Request → Merge | Add data from external APIs |
| Deduplicate | Code (Set-based check) | Prevent processing the same item twice |
Node specification template (for each node):
Node [N]: [Name]
Type: [n8n node type]
Purpose: [What this node does]
Input: [What it receives from the previous node]
Configuration:
- [Key setting 1]
- [Key setting 2]
Output: [What it passes to the next node]
Step 4: Data Transformations
Accessing data between nodes:
// Reference previous node output
{{ $json.fieldName }}
// Reference a specific node by name
{{ $('Node Name').item.json.fieldName }}
// Access all items from a node
{{ $('Node Name').all() }}
// Current item index in a loop
{{ $itemIndex }}
// Environment variables
{{ $env.MY_VARIABLE }}
Common transformation patterns:
| Transformation | Node | Expression Example |
|---|---|---|
| Rename field | Set | newName: {{ $json.oldName }} |
| Format date | Set / Code | {{ DateTime.fromISO($json.date).toFormat('yyyy-MM-dd') }} |
| Filter items | IF | {{ $json.status === 'active' }} |
| Concatenate | Set | {{ $json.first + ' ' + $json.last }} |
| Parse JSON string | Code | JSON.parse($json.rawBody) |
| Map array | Code | items.map(i => ({ json: { id: i.json.id } })) |
| Aggregate | Code | [{ json: { total: items.reduce((s,i) => s + i.json.amount, 0) } }] |
Code node template (JavaScript):
// Process all items
const results = [];
for (const item of $input.all()) {
results.push({
json: {
id: item.json.id,
processed: true,
// Add transformed fields here
}
});
}
return results;
Step 5: Error Handling
Error handling strategy:
[Main Workflow]
├── [Error Trigger] → [Log to DB] → [Send Alert]
└── [Individual nodes with retry]
Three layers of error handling:
| Layer | Implementation | Purpose |
|---|---|---|
| Node retry | Settings → Retry on Fail (max 3, wait 1s) | Transient failures (network, rate limits) |
| Error Trigger | Error Trigger node → notification workflow | Catch any unhandled errors |
| Dead letter | On error → write to DB/queue for later replay | Don't lose failed items |
Error Trigger workflow template:
Node 1: Error Trigger
→ Receives: error message, workflow name, node name, execution ID
Node 2: Set (format error)
→ Builds: { workflow, node, error, timestamp, executionUrl }
Node 3: Send alert (Slack / Email / PagerDuty)
→ Message: "Workflow '[name]' failed at node '[node]': [error]"
Node 4: Log to database (optional)
→ Insert error record for tracking and replay
Step 6: Testing & Deployment
Testing checklist:
- Test with real-shaped data (not just
{ "test": true }) - Test the error path (disable a downstream service and verify error handling fires)
- Test with empty arrays and null values
- Test with maximum expected payload size
- Verify credentials are in n8n credential store (not hardcoded)
- Check timezone settings on Schedule triggers
Production deployment:
- Set workflow to Active
- Verify webhook URLs are registered in source services
- Enable execution logging (Settings → Save Execution Progress)
- Set execution timeout appropriate for workload
- Tag workflow with version number and description
- Document the workflow in your team's runbook
Output Format
# n8n Workflow: [Workflow Name]
## Overview
- **Trigger:** [Trigger type and config]
- **Purpose:** [What this workflow automates]
- **Frequency:** [How often it runs]
- **Services connected:** [List of external services]
## Workflow Diagram
[ASCII diagram of node flow]
## Node Specifications
### Node 1: [Trigger]
[Config template from Step 3]
### Node 2: [Transform/Action]
[Config template from Step 3]
[...all nodes...]
## Data Transformations
[Key expressions from Step 4]
## Error Handling
[Strategy from Step 5]
## Testing Checklist
[From Step 6]
Completion
n8n Workflow Builder: Complete!
Workflow: [Name]
Trigger: [Type]
Nodes: [Count]
Services connected: [List]
Error handling: [Strategy summary]
Next steps:
1. Create the workflow in n8n using the node specs above
2. Configure credentials in n8n's credential store
3. Test with sample data before activating
4. Activate and verify the first real execution
5. Set up the Error Trigger workflow for monitoring
Level History
- Lv.1: Base: Trigger selection (7 types), node mapping with specification templates, data transformation patterns (expressions + Code node), 3-layer error handling (retry, Error Trigger, dead letter), common workflow patterns (filter, batch, merge, deduplicate), testing checklist, production deployment checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Webhook Designer: Designing webhook handler...
Creates secure webhook handlers with endpoint design, payload validation, HMAC signature verification, retry logic, idempotency, logging, and dead letter queues.
Activation
When this skill activates, output:
Webhook Designer: Designing webhook handler...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "webhook", "webhook handler", "webhook endpoint" | ACTIVE |
| User says "receive events", "HMAC verification", "idempotency" | ACTIVE |
| User wants to build an endpoint that receives external events | ACTIVE |
| User wants a full n8n automation workflow | DORMANT: use n8n Workflow Builder |
| User wants a scheduled/cron job | DORMANT: use Cron Scheduler |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Skip signature verification" | Without HMAC, anyone can send fake events to your endpoint. Always verify. |
| "Process synchronously" | Long processing blocks the response. Return 200 immediately, process async. |
| "No idempotency" | Senders retry on timeout. Without idempotency keys, you'll process duplicates. |
| "Ignore retry headers" | Senders include retry count and delivery ID. Log them for debugging. |
| "Return detailed errors" | Never expose internals. Return 200 (accepted) or 400 (bad request), nothing more. |
Protocol
Step 1: Gather Webhook Requirements
If the user hasn't provided details, ask:
- Source: what service sends the webhook? (Stripe, GitHub, Shopify, custom)
- Events: which events do you need to handle? (e.g., payment.completed, push)
- Payload: what does the payload look like? (JSON schema or example)
- Auth: how does the source authenticate? (HMAC, bearer token, IP whitelist)
- Processing: what should happen when an event arrives?
- Framework: what's your stack? (Next.js, Express, FastAPI, etc.)
Step 2: Design Endpoint
Endpoint pattern:
POST /api/webhooks/{source}
Headers:
Content-Type: application/json
X-Webhook-Signature: {hmac_signature}
X-Webhook-ID: {delivery_id}
X-Webhook-Timestamp: {unix_timestamp}
Body: {event payload}
Response: 200 OK (within 5 seconds)
Handler flow:
Request received
├── 1. Read raw body (before JSON parsing)
├── 2. Verify signature (HMAC-SHA256)
│ └── Fail → 401 Unauthorized (log attempt)
├── 3. Parse JSON payload
│ └── Fail → 400 Bad Request
├── 4. Check idempotency (delivery ID seen before?)
│ └── Duplicate → 200 OK (skip processing)
├── 5. Validate event type (is it one we handle?)
│ └── Unknown → 200 OK (acknowledge but ignore)
├── 6. Return 200 OK immediately
└── 7. Process event asynchronously
└── Fail → Write to dead letter queue
Step 3: Implement Signature Verification
HMAC-SHA256 verification (most common):
// Next.js / Express example
import crypto from 'crypto';
function verifyWebhookSignature(
rawBody: string,
signature: string,
secret: string
): boolean {
const expected = crypto
.createHmac('sha256', secret)
.update(rawBody, 'utf8')
.digest('hex');
// Timing-safe comparison prevents timing attacks
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
Provider-specific patterns:
| Provider | Header | Algorithm | Prefix |
|---|---|---|---|
| Stripe | Stripe-Signature | HMAC-SHA256 | t=timestamp,v1=signature |
| GitHub | X-Hub-Signature-256 | HMAC-SHA256 | sha256= |
| Shopify | X-Shopify-Hmac-Sha256 | HMAC-SHA256 (base64) | None |
| Twilio | X-Twilio-Signature | HMAC-SHA1 (base64) | None |
| Slack | X-Slack-Signature | HMAC-SHA256 | v0= |
| Custom | X-Webhook-Signature | HMAC-SHA256 (hex) | None |
Timestamp validation (replay protection):
function verifyTimestamp(timestamp: number, toleranceSeconds = 300): boolean {
const now = Math.floor(Date.now() / 1000);
return Math.abs(now - timestamp) <= toleranceSeconds;
}
Step 4: Implement Idempotency
// Using a database table for idempotency
async function isProcessed(deliveryId: string): Promise<boolean> {
const existing = await db.webhookDeliveries.findUnique({
where: { deliveryId }
});
return !!existing;
}
async function markProcessed(deliveryId: string, event: string): Promise<void> {
await db.webhookDeliveries.create({
data: {
deliveryId,
event,
processedAt: new Date(),
// Auto-delete after 7 days to prevent unbounded growth
}
});
}
Idempotency table schema:
CREATE TABLE webhook_deliveries (
delivery_id VARCHAR(255) PRIMARY KEY,
event_type VARCHAR(100) NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
payload_hash VARCHAR(64), -- Optional: detect payload changes
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Auto-cleanup: delete records older than 7 days
CREATE INDEX idx_webhook_deliveries_created ON webhook_deliveries(created_at);
Step 5: Build Event Router
// Event handler registry
const handlers: Record<string, (payload: any) => Promise<void>> = {
'payment.completed': handlePaymentCompleted,
'payment.failed': handlePaymentFailed,
'customer.created': handleCustomerCreated,
// Add handlers as needed
};
async function routeEvent(eventType: string, payload: any): Promise<void> {
const handler = handlers[eventType];
if (!handler) {
console.log(`Unhandled event type: ${eventType}`);
return; // Acknowledge but don't process
}
await handler(payload);
}
Event handler template:
async function handlePaymentCompleted(payload: any): Promise<void> {
// 1. Extract relevant data
const { id, amount, customerId } = payload;
// 2. Validate required fields
if (!id || !amount || !customerId) {
throw new Error('Missing required fields in payment.completed');
}
// 3. Execute business logic
await updateOrderStatus(id, 'paid');
await sendReceiptEmail(customerId, amount);
// 4. Log success
console.log(`Processed payment ${id} for $${amount / 100}`);
}
Step 6: Dead Letter Queue
When async processing fails after retries, write to a dead letter queue:
async function processWithRetry(
deliveryId: string,
eventType: string,
payload: any,
maxRetries = 3
): Promise<void> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await routeEvent(eventType, payload);
return; // Success
} catch (error) {
if (attempt === maxRetries) {
await writeToDeadLetter(deliveryId, eventType, payload, error);
// Alert: send notification to ops team
}
await sleep(attempt * 1000); // Exponential backoff
}
}
}
Dead letter table:
CREATE TABLE webhook_dead_letters (
id SERIAL PRIMARY KEY,
delivery_id VARCHAR(255) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
error TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 3,
replayed BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Step 7: Logging & Monitoring
Structured logging for every webhook:
function logWebhook(phase: string, data: Record<string, any>): void {
console.log(JSON.stringify({
type: 'webhook',
phase, // 'received' | 'verified' | 'processed' | 'failed'
timestamp: new Date().toISOString(),
...data
}));
}
// Usage:
logWebhook('received', { deliveryId, eventType, source: 'stripe' });
logWebhook('verified', { deliveryId, signatureValid: true });
logWebhook('processed', { deliveryId, durationMs: 45 });
logWebhook('failed', { deliveryId, error: err.message, attempt: 3 });
Monitoring checklist:
- Alert on: >5% failure rate over 15 minutes
- Alert on: dead letter queue depth > 10
- Alert on: no events received in [expected window]
- Dashboard: events/minute by type, success rate, p95 latency
- Retention: keep webhook logs for 30 days minimum
Output Format
# Webhook Handler: [Source] Events
## Endpoint
- **URL:** POST /api/webhooks/[source]
- **Auth:** [HMAC-SHA256 / Bearer / IP whitelist]
- **Events handled:** [List]
## Handler Flow
[Flow diagram from Step 2]
## Signature Verification
[Code from Step 3]
## Idempotency
[Schema + code from Step 4]
## Event Handlers
[Router + handler templates from Step 5]
## Error Recovery
[Dead letter queue from Step 6]
## Monitoring
[Logging + alerts from Step 7]
Completion
Webhook Designer: Complete!
Source: [Service name]
Endpoint: POST /api/webhooks/[source]
Events handled: [Count]
Auth method: [HMAC-SHA256 / etc.]
Idempotency: Delivery ID based
Dead letter: Database-backed
Next steps:
1. Implement the handler using the code templates above
2. Store the webhook secret in environment variables
3. Register the webhook URL in the source service
4. Send a test event and verify end-to-end
5. Set up monitoring alerts
Level History
- Lv.1: Base: Endpoint design with handler flow, HMAC-SHA256 signature verification (6 provider patterns), timestamp replay protection, delivery-ID idempotency with DB schema, event router with handler registry, dead letter queue with retry/backoff, structured logging, monitoring checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Client Onboarding: Setting up new client...
Produces a complete client onboarding package with welcome email, intake questionnaire, kickoff meeting agenda, access provisioning checklist, expectations document, and 30/60/90-day check-in schedule.
Activation
When this skill activates, output:
Client Onboarding: Setting up new client...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "client onboarding", "new client", "onboard client" | ACTIVE |
| User says "kickoff meeting", "intake form", "welcome email" | ACTIVE |
| User just signed a new client and needs to set up the engagement | ACTIVE |
| User wants a contract or agreement | DORMANT: use Contract Template |
| User wants to send an invoice | DORMANT: use Invoice Generator |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Start working immediately" | Without intake and alignment, you'll waste the first 2 weeks on rework. |
| "Skip the expectations document" | Unclear expectations cause 80% of client conflicts. Document everything upfront. |
| "No single point of contact" | Multiple client contacts = conflicting feedback. Designate one decision-maker. |
| "Forget access provisioning" | Waiting for logins and credentials delays the project by days or weeks. |
| "No check-in schedule" | Without scheduled touchpoints, small issues become big surprises. |
Protocol
Step 1: Gather Client Information
If the user hasn't provided details, ask:
- Client: company name, primary contact, industry
- Project: what was sold? (service type, scope, deliverables)
- Timeline: start date, key milestones, end date
- Communication: preferred channel (email, Slack, calls)?
- Access needed: what systems, accounts, or assets do you need from them?
Step 2: Send Welcome Email
Welcome email template:
Subject: Welcome aboard! Here's what happens next: [Your Company]
Hi [Client Name],
Welcome to [Your Company]! We're excited to work with you on [Project Name].
Here's what to expect in the next few days:
1. **Intake questionnaire** (attached / linked below), please complete
by [date, 2-3 business days]. This helps us understand your goals,
preferences, and current setup.
2. **Access provisioning**: we'll need a few logins and assets from you
(details in the questionnaire). The sooner we have access, the sooner
we can start.
3. **Kickoff call**: I've sent a calendar invite for [date/time].
This is a [30/60]-minute call where we align on goals, timeline, and
communication cadence.
Your primary point of contact is [Name] ([email]). For anything urgent,
you can also reach us at [phone/Slack].
If you have any questions before the kickoff, just reply to this email.
Looking forward to getting started!
[Your Name]
[Title]
[Company]
[Phone]
Step 3: Intake Questionnaire
Standard intake questions:
## Client Intake Questionnaire
### About Your Business
1. What does your business do? (One paragraph)
2. Who is your target audience?
3. What makes you different from competitors?
4. What's your brand voice? (Professional, casual, technical, friendly)
### About This Project
5. What's the #1 goal for this project?
6. What does success look like? How will you measure it?
7. Are there specific deadlines we should know about?
8. What have you tried before? What worked and what didn't?
### Design & Brand
9. Do you have brand guidelines? (colors, fonts, logo files)
10. Share 3 examples of [websites/designs/content] you admire
11. Share 3 examples of what you DON'T want
### Technical
12. What platforms/tools do you currently use? (CMS, email, analytics, etc.)
13. Do you have Google Analytics / Search Console set up?
14. Who manages your domain and hosting?
### Access (we'll need these before kickoff)
15. [ ] Website admin login (URL + credentials)
16. [ ] Google Analytics / Search Console access (add [email] as editor)
17. [ ] Social media account access (or manager role)
18. [ ] Brand assets (logo files, brand guide, fonts)
19. [ ] Any existing content or copy documents
20. [ ] Current customer list or CRM access (if applicable)
### Communication Preferences
21. Preferred communication channel: Email / Slack / Phone / Other
22. Best time for meetings (timezone + availability)
23. Who is the primary decision-maker on your side?
24. Who else needs to approve deliverables?
Step 4: Kickoff Meeting Agenda
Kickoff meeting template (60 minutes):
## Kickoff Meeting, [Client Name] × [Your Company]
**Date:** [Date] | **Time:** [Time] | **Duration:** 60 min
### Attendees
- [Your team: names and roles]
- [Client team: names and roles]
### Agenda
**1. Introductions (5 min)**
- Who's on each team and their role in this project
**2. Project overview (10 min)**
- Recap: what we're building and why
- Confirm scope and deliverables (reference SOW/contract)
- Confirm timeline and key milestones
**3. Goals & success metrics (10 min)**
- Review client's #1 goal (from intake questionnaire)
- Agree on measurable success criteria
- Identify any risks or concerns early
**4. Communication & process (10 min)**
- Communication channel (email / Slack / project tool)
- Meeting cadence: [weekly / biweekly] check-ins on [day] at [time]
- How to submit feedback (one document, not scattered emails)
- Turnaround times: our deliverables [X days], your feedback [X days]
**5. Review intake questionnaire (10 min)**
- Walk through answers, clarify anything unclear
- Confirm access items are provided or in progress
**6. Immediate next steps (10 min)**
- [ ] [Action item 1], [Owner], by [Date]
- [ ] [Action item 2], [Owner], by [Date]
- [ ] [Action item 3], [Owner], by [Date]
**7. Questions & close (5 min)**
- Open floor for any questions
- Confirm next meeting date
Step 5: Access Provisioning Checklist
Access checklist (customize per project):
| # | Item | Status | Owner | Notes |
|---|---|---|---|---|
| 1 | Website CMS login | [ ] Pending | Client | [URL] |
| 2 | Google Analytics (Editor access) | [ ] Pending | Client | Add [email] |
| 3 | Google Search Console | [ ] Pending | Client | Add [email] |
| 4 | Social media accounts | [ ] Pending | Client | [Platforms] |
| 5 | Email marketing platform | [ ] Pending | Client | [Platform] |
| 6 | Brand assets (logo, fonts, guide) | [ ] Pending | Client | Shared drive link |
| 7 | Hosting / DNS access | [ ] Pending | Client | [Provider] |
| 8 | Payment processor (if applicable) | [ ] Pending | Client | [Stripe, etc.] |
| 9 | Project management tool invite | [ ] Pending | You | Add client to [tool] |
| 10 | Slack / Teams channel setup | [ ] Pending | You | Create shared channel |
Step 6: Expectations Document
## Working Agreement: [Client Name] × [Your Company]
### Communication
- **Primary channel:** [Email / Slack]
- **Response time:** We respond within [1 business day / 4 hours]
- **Meeting cadence:** [Weekly / Biweekly] on [Day] at [Time]
- **Urgent issues:** [Phone / text to [number]]
### Deliverable Process
1. We deliver [drafts/designs/builds] by the agreed date
2. You provide feedback within [3-5 business days]
3. Feedback should be consolidated (one person collects all feedback)
4. We incorporate feedback and deliver the revision
5. [2-3] revision rounds are included; additional rounds at $[X]/hour
### What We Need From You
- Timely responses to questions and feedback requests
- Access to all required systems (see provisioning checklist)
- One designated decision-maker for approvals
- Content and assets delivered by agreed deadlines
### What You Can Expect From Us
- Transparent progress updates at every check-in
- Proactive communication about any delays or blockers
- Professional, high-quality deliverables on schedule
- No scope changes without written agreement and revised estimate
### Revision Policy
- [2] rounds of revisions included per deliverable
- Revisions must be requested within [5 business days] of delivery
- Out-of-scope changes require a change order
### Escalation Path
If anything feels off, reach out early:
1. Contact your project lead: [Name, email]
2. If unresolved: Contact [Manager/Owner name, email]
Step 7: 30/60/90-Day Check-In Schedule
| Checkpoint | When | Focus | Format |
|---|---|---|---|
| Week 1 | Day 5 | Quick pulse: any blockers? Access complete? | 15-min call or Slack |
| 30 days | Day 30 | Progress review, milestone check, feedback loop | 30-min call |
| 60 days | Day 60 | Mid-project review, scope check, quality audit | 30-min call |
| 90 days | Day 90 | Results review, project wrap-up or renewal | 45-min call |
Check-in agenda (30/60/90):
- Progress update: what's been completed, what's next
- Metrics review: are we hitting the success criteria?
- Client satisfaction: what's working, what could improve?
- Scope check: any changes needed? (change order if yes)
- Action items for next period
Output Format
# Client Onboarding Package: [Client Name]
## Welcome Email
[From Step 2]
## Intake Questionnaire
[From Step 3]
## Kickoff Meeting Agenda
[From Step 4]
## Access Provisioning Checklist
[From Step 5]
## Working Agreement
[From Step 6]
## Check-In Schedule
[From Step 7]
Completion
Client Onboarding: Complete!
Client: [Name]
Project: [Project name]
Kickoff date: [Date]
Check-in cadence: [Weekly / Biweekly]
Documents prepared: 6 (welcome email, questionnaire, kickoff agenda,
access checklist, expectations doc, check-in schedule)
Next steps:
1. Send the welcome email today
2. Attach/link the intake questionnaire
3. Send kickoff meeting calendar invite
4. Follow up on access provisioning within 48 hours
5. Share the working agreement at the kickoff meeting
Level History
- Lv.1: Base: Welcome email template, 24-question intake questionnaire, 60-minute kickoff meeting agenda, 10-item access provisioning checklist, working agreement (communication, deliverables, revisions, escalation), 30/60/90-day check-in schedule with agendas. (Origin: MemStack Pro v3.2, Mar 2026)
Contract Template: Drafting service agreement...
Provides service agreement, NDA, and subcontractor templates with scope, payment, IP ownership, confidentiality, termination, and liability clauses.
Activation
When this skill activates, output:
Contract Template: Drafting service agreement...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "contract", "agreement", "service agreement", "NDA" | ACTIVE |
| User says "freelance contract" or "consulting agreement" | ACTIVE |
| User needs a written agreement for client or vendor work | ACTIVE |
| User wants an invoice | DORMANT: use Invoice Generator |
| User wants a project proposal | DORMANT: use Proposal Writer |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Handshake deal, no contract" | Verbal agreements are unenforceable. A simple contract protects both parties. |
| "Skip IP ownership clause" | Without explicit IP transfer, the creator often retains rights by default. Always specify. |
| "No termination clause" | Without exit terms, either party is trapped. Define how and when the contract can end. |
| "Copy a template without reading" | Every clause should match your actual arrangement. Mismatched terms create liability. |
| "No dispute resolution" | Without a specified method (mediation, arbitration, jurisdiction), disputes escalate to costly litigation. |
Disclaimer: These templates are starting points, not legal advice. Have an attorney review contracts before use, especially for high-value engagements.
Protocol
Step 1: Gather Contract Requirements
If the user hasn't provided details, ask:
- Contract type: service agreement, NDA, subcontractor agreement, or other?
- Parties: who is the provider and who is the client?
- Scope: what work is being performed?
- Payment: flat fee, hourly, retainer, milestone-based?
- Duration: start date, end date, or ongoing?
- Special terms: non-compete, exclusivity, IP considerations?
Step 2: Select Contract Type
| Type | Use When | Key Clauses |
|---|---|---|
| Service Agreement | Providing professional services to a client | Scope, payment, IP, liability, termination |
| NDA (Mutual) | Both parties share confidential information | Definition of confidential info, exclusions, duration, remedies |
| NDA (One-way) | Only one party shares confidential info | Same as mutual but obligations on one side |
| Subcontractor Agreement | Hiring someone to help deliver client work | Scope, payment, IP assignment, confidentiality, non-solicitation |
| Retainer Agreement | Ongoing monthly services at a fixed rate | Hours/month, rollover policy, scope boundaries, renewal |
Step 3: Draft Core Clauses
1. Parties & Effective Date:
This [Agreement Type] ("Agreement") is entered into as of [Date]
("Effective Date") by and between:
**[Provider Name]** ("[Provider/Contractor]")
[Address]
[Email]
and
**[Client Name]** ("Client")
[Address]
[Email]
2. Scope of Work:
Provider agrees to perform the following services ("Services"):
1. [Deliverable 1: specific description]
2. [Deliverable 2: specific description]
3. [Deliverable 3: specific description]
Out of scope (requires separate agreement or change order):
- [Excluded item 1]
- [Excluded item 2]
3. Payment Terms:
Compensation:
- [Flat fee: $X for completion of all Services]
OR
- [Hourly rate: $X/hour, billed [weekly/monthly], capped at [X] hours]
OR
- [Milestone: $X upon completion of each milestone per Schedule A]
OR
- [Retainer: $X/month for up to [X] hours, additional hours at $X/hour]
Payment schedule:
- [50% deposit due upon signing; 50% upon completion]
OR
- [Net 30 from invoice date]
Late payment:
- Invoices unpaid after [30] days will incur [1.5]% monthly interest.
- Provider may suspend Services after [15] days of non-payment.
4. Intellectual Property:
Option A, Full IP Transfer (most common for client work):
Upon full payment, all work product created under this Agreement
("Work Product") shall be the exclusive property of Client. Provider
assigns all rights, title, and interest in the Work Product to Client.
Option B: License (provider retains ownership):
Provider retains all rights to the Work Product and grants Client a
perpetual, non-exclusive, worldwide license to use, modify, and
distribute the Work Product for Client's business purposes.
Option C, Shared (split ownership):
Client owns the final deliverables. Provider retains the right to
reuse general techniques, methodologies, and non-client-specific
components ("Provider Tools") in future work.
Pre-existing IP:
Any pre-existing intellectual property brought to this engagement
remains the property of its original owner.
5. Confidentiality:
Each party agrees to keep confidential all non-public information
disclosed by the other party ("Confidential Information"), including
but not limited to: business plans, customer data, financial records,
technical specifications, and trade secrets.
Exclusions, Information is not confidential if it:
(a) is or becomes publicly available without breach;
(b) was known to the receiving party before disclosure;
(c) is independently developed without use of confidential information;
(d) is disclosed pursuant to legal requirement (with prior notice).
Duration: Confidentiality obligations survive for [2/3/5] years
after termination of this Agreement.
6. Termination:
Either party may terminate this Agreement:
(a) For convenience: with [30] days written notice;
(b) For cause: if the other party materially breaches and fails to
cure within [15] days of written notice;
(c) Immediately: if the other party becomes insolvent or bankrupt.
Upon termination:
- Client pays for all Services performed through the termination date.
- Provider delivers all completed and in-progress Work Product.
- Confidentiality and IP provisions survive termination.
7. Liability & Indemnification:
Limitation of Liability:
Provider's total liability under this Agreement shall not exceed
the total fees paid by Client in the [12] months preceding the claim.
Neither party shall be liable for indirect, incidental, consequential,
or punitive damages.
Indemnification:
Each party shall indemnify and hold harmless the other from claims
arising from their own negligence, willful misconduct, or breach
of this Agreement.
8. Dispute Resolution:
Any dispute arising from this Agreement shall be resolved as follows:
1. Good faith negotiation between the parties (30 days);
2. If unresolved, mediation in [City, State];
3. If mediation fails, binding arbitration under [AAA/JAMS] rules;
4. Governing law: State of [State].
Step 4: NDA Template (If Requested)
## NON-DISCLOSURE AGREEMENT
This NDA is entered into as of [Date] between:
**Disclosing Party:** [Name]
**Receiving Party:** [Name]
1. **Definition:** "Confidential Information" means all non-public
information disclosed in writing, orally, or by inspection,
marked as confidential or reasonably understood to be confidential.
2. **Obligations:** Receiving Party shall: (a) use Confidential
Information solely for [Purpose]; (b) not disclose to third
parties without written consent; (c) protect with reasonable care.
3. **Exclusions:** [Same as Section 5 above]
4. **Duration:** [2] years from date of disclosure.
5. **Return:** Upon request, Receiving Party shall return or destroy
all Confidential Information and certify destruction in writing.
6. **Remedies:** Unauthorized disclosure may cause irreparable harm.
Disclosing Party may seek injunctive relief in addition to damages.
7. **Governing Law:** State of [State].
Step 5: Signature Block
IN WITNESS WHEREOF, the parties have executed this Agreement
as of the Effective Date.
**[Provider Name]**
Signature: _________________________
Name: [Full name]
Title: [Title]
Date: [Date]
**[Client Name]**
Signature: _________________________
Name: [Full name]
Title: [Title]
Date: [Date]
Step 6: Contract Checklist
Before sending:
- All party names, addresses, and contact info are correct
- Scope of work matches the proposal or SOW exactly
- Payment terms, amounts, and schedule are specified
- IP ownership clause matches the agreed arrangement
- Confidentiality duration is specified
- Termination conditions are clear for both parties
- Liability cap is set at a reasonable amount
- Dispute resolution jurisdiction/method is specified
- Both parties have time to review before signing
- Sent for legal review (recommended for engagements >$10K)
Output Format
Deliver the contract as a complete document with all selected clauses assembled in order, ready for legal review and signing.
Completion
Contract Template: Complete!
Type: [Service Agreement / NDA / Subcontractor / Retainer]
Parties: [Provider] and [Client]
Duration: [Start] to [End / Ongoing]
Payment: [Terms summary]
IP: [Transfer / License / Shared]
Next steps:
1. Review all clauses to ensure they match your arrangement
2. Have an attorney review before sending (especially >$10K)
3. Send to client for review with reasonable response time
4. Both parties sign and date
5. Store executed copy securely (both parties keep a copy)
Level History
- Lv.1: Base: 5 contract types (service, NDA mutual/one-way, subcontractor, retainer), 8 core clauses (parties, scope, payment, IP with 3 options, confidentiality, termination, liability, dispute), standalone NDA template, signature block, pre-send checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Financial Model: Building financial projections...
Builds monthly revenue projections, expense forecasts, unit economics (CAC, LTV, payback), break-even analysis, cash flow tracking, and scenario modeling (best/base/worst).
Activation
When this skill activates, output:
Financial Model: Building financial projections...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "financial model", "projections", "revenue forecast" | ACTIVE |
| User mentions MRR, churn, CAC, LTV, runway, or break-even | ACTIVE |
| User wants to forecast revenue, expenses, or cash flow | ACTIVE |
| User wants to set pricing tiers | DORMANT: use Pricing Strategy |
| User wants to generate an invoice | DORMANT: use Invoice Generator |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Hockey stick revenue" | Realistic projections beat optimistic fantasies. Start conservative, model scenarios. |
| "Forget to model churn" | SaaS without churn modeling is fiction. Even 3% monthly churn compounds fast. |
| "Revenue only, no expenses" | Revenue without expenses is a dream. Model all costs to see actual profitability. |
| "One scenario only" | A single forecast is a guess. Model best/base/worst to understand the range. |
| "Skip unit economics" | If CAC > LTV, growth loses money. Unit economics tell you if the business model works. |
Protocol
Step 1: Gather Business Data
If the user hasn't provided details, ask:
- Business model: SaaS, e-commerce, service, marketplace, or other?
- Revenue streams: subscriptions, one-time sales, services, ads?
- Current numbers: existing revenue, customers, growth rate?
- Pricing: price points, tiers, average revenue per user?
- Costs: known fixed and variable costs?
- Funding: bootstrapped or funded? Current cash balance?
Step 2: Revenue Model
SaaS / Subscription revenue:
Month N Revenue = (Previous customers - Churned + New) × ARPU
Where:
- Previous customers: end of prior month
- Churned: Previous × monthly churn rate
- New: Acquired through marketing/sales
- ARPU: Average Revenue Per User (monthly)
| Month | Starting | New | Churned | Ending | MRR | ARR |
|---|---|---|---|---|---|---|
| 1 | 0 | [X] | 0 | [X] | $[X] | none |
| 2 | [X] | [X] | [X] | [X] | $[X] | none |
| 3 | [X] | [X] | [X] | [X] | $[X] | none |
| ... | ||||||
| 12 | [X] | [X] | [X] | [X] | $[X] | $[X] |
E-commerce / Transaction revenue:
Monthly Revenue = Visitors × Conversion Rate × Average Order Value
Where:
- Visitors: Monthly unique visitors (organic + paid)
- Conversion Rate: % of visitors who purchase (target: 1-3%)
- AOV: Average Order Value
Service revenue:
Monthly Revenue = Active Clients × Average Monthly Retainer
+ Project Revenue (one-time)
Step 3: Unit Economics
Key SaaS metrics:
CAC (Customer Acquisition Cost):
= Total Sales & Marketing Spend ÷ New Customers Acquired
Target: recover within 12 months
LTV (Customer Lifetime Value):
= ARPU × Gross Margin% × (1 ÷ Monthly Churn Rate)
Example: $50 × 80% × (1 ÷ 0.05) = $800
LTV:CAC Ratio:
= LTV ÷ CAC
Target: > 3:1 (every $1 spent acquires $3+ in lifetime value)
Payback Period:
= CAC ÷ (ARPU × Gross Margin%)
Example: $200 ÷ ($50 × 80%) = 5 months
Target: < 12 months
Unit economics table:
| Metric | Value | Target | Status |
|---|---|---|---|
| ARPU (monthly) | $[X] | none | none |
| Monthly churn rate | [X]% | <5% | [OK / At Risk] |
| CAC | $[X] | none | none |
| LTV | $[X] | >3× CAC | [OK / At Risk] |
| LTV:CAC ratio | [X]:1 | >3:1 | [OK / At Risk] |
| Payback period | [X] months | <12 months | [OK / At Risk] |
| Gross margin | [X]% | >70% (SaaS) | [OK / At Risk] |
Step 4: Expense Forecast
Fixed costs (monthly):
| Category | Monthly Cost | Annual Cost | Notes |
|---|---|---|---|
| Salaries & wages | $[X] | $[X] | [Headcount × avg salary ÷ 12] |
| Office / co-working | $[X] | $[X] | |
| Software & tools | $[X] | $[X] | [List: hosting, SaaS tools, etc.] |
| Insurance | $[X] | $[X] | |
| Legal & accounting | $[X] | $[X] | |
| Total fixed | $[X] | $[X] |
Variable costs (scales with revenue):
| Category | Cost Basis | Monthly Estimate | Notes |
|---|---|---|---|
| Hosting / infrastructure | [X]% of revenue | $[X] | Scales with users |
| Payment processing | 2.9% + $0.30/txn | $[X] | Stripe standard rate |
| Customer support | $[X] per 100 customers | $[X] | |
| Sales commissions | [X]% of new revenue | $[X] | |
| Marketing spend | $[X] fixed + [X]% of revenue | $[X] | |
| Total variable | $[X] |
Total monthly burn:
Burn Rate = Fixed Costs + Variable Costs - Revenue
Runway = Cash Balance ÷ Monthly Burn Rate
Step 5: Break-Even Analysis
Break-Even Point (customers):
= Fixed Costs ÷ (ARPU - Variable Cost per Customer)
Break-Even Point (revenue):
= Fixed Costs ÷ Gross Margin%
Example:
Fixed costs: $10,000/month
ARPU: $50/month
Variable cost per customer: $10/month
Break-even: $10,000 ÷ ($50 - $10) = 250 customers
Monthly P&L projection:
| Mo 1 | Mo 3 | Mo 6 | Mo 12 | |
|---|---|---|---|---|
| Revenue | $[X] | $[X] | $[X] | $[X] |
| COGS / variable costs | ($[X]) | ($[X]) | ($[X]) | ($[X]) |
| Gross profit | $[X] | $[X] | $[X] | $[X] |
| Gross margin % | [X]% | [X]% | [X]% | [X]% |
| Operating expenses | ($[X]) | ($[X]) | ($[X]) | ($[X]) |
| Net income | ($[X]) | ($[X]) | $[X] | $[X] |
| Cumulative cash | $[X] | $[X] | $[X] | $[X] |
Step 6: Scenario Modeling
Three scenarios:
| Assumption | Worst Case | Base Case | Best Case |
|---|---|---|---|
| Monthly new customers | [X] | [X] | [X] |
| Monthly churn rate | [X]% | [X]% | [X]% |
| ARPU | $[X] | $[X] | $[X] |
| Marketing spend | $[X] | $[X] | $[X] |
| Hiring timeline | Delayed | On time | Accelerated |
12-month outcome by scenario:
| Metric | Worst | Base | Best |
|---|---|---|---|
| Customers (Mo 12) | [X] | [X] | [X] |
| MRR (Mo 12) | $[X] | $[X] | $[X] |
| ARR (Mo 12) | $[X] | $[X] | $[X] |
| Monthly burn (avg) | $[X] | $[X] | $[X] |
| Break-even month | Mo [X] | Mo [X] | Mo [X] |
| Runway remaining | [X] months | [X] months | [X] months |
| Cash needed | $[X] | $[X] | $0 |
Step 7: Cash Flow Summary
Monthly cash flow:
| Month | Revenue | Expenses | Net | Cumulative |
|---|---|---|---|---|
| 1 | $[X] | $[X] | ($[X]) | $[X] |
| 2 | $[X] | $[X] | ($[X]) | $[X] |
| 3 | $[X] | $[X] | ($[X]) | $[X] |
| ... | ||||
| 12 | $[X] | $[X] | $[X] | $[X] |
Key dates:
- Cash-flow positive: Month [X] (when monthly net turns positive)
- Break-even (cumulative): Month [X] (when cumulative losses are recovered)
- Runway exhausted: Month [X] at current burn (worst case)
Output Format
# Financial Model: [Business Name]
## Revenue Model
[From Step 2: monthly revenue projections]
## Unit Economics
[From Step 3: CAC, LTV, payback, margins]
## Expense Forecast
[From Step 4: fixed + variable costs]
## Break-Even Analysis
[From Step 5, break-even point + P&L]
## Scenario Analysis
[From Step 6: worst/base/best]
## Cash Flow
[From Step 7, monthly cash flow + key dates]
## Key Assumptions
[List every assumption with the value used]
Completion
Financial Model: Complete!
Business model: [Type]
12-month ARR (base case): $[X]
Break-even: Month [X]
LTV:CAC ratio: [X]:1
Runway: [X] months
Scenarios modeled: 3 (worst/base/best)
Next steps:
1. Validate assumptions with real data (update monthly)
2. Track actual vs projected monthly
3. If LTV:CAC < 3:1, reduce CAC or increase ARPU before scaling
4. If runway < 6 months, raise capital or cut burn
5. Update the model quarterly with actuals
Level History
- Lv.1: Base: Revenue models (SaaS, e-commerce, service), unit economics (CAC, LTV, payback, LTV:CAC, gross margin), expense forecast (fixed + variable), break-even analysis with P&L projection, 3-scenario modeling (worst/base/best), cash flow timeline with key dates (cash-positive, break-even, runway). (Origin: MemStack Pro v3.2, Mar 2026)
Freelancer Toolkit: Setting up freelancer workflows...
Produces time tracking sheets, invoice calculations, and project analytics for freelancers managing multiple clients.
Activation
| Trigger | Status |
|---|---|
| User says "track my time" or "billable hours" | ACTIVE |
| User says "freelancer invoice" or "client billing" | ACTIVE |
| User says "freelance finances" or "project hours" | ACTIVE |
| User wants a formal proposal or SOW | NOT this skill, use Proposal Writer or Scope of Work |
| User wants a generic invoice template | NOT this skill: use Invoice Generator |
Context Guard
- Do NOT use for proposal writing (that's proposal-writer)
- Do NOT use for scope of work documents (that's scope-of-work)
- Do NOT use for generic invoice templates (that's invoice-generator)
- This skill covers the full freelancer workflow: tracking time → calculating billable → generating invoice → analyzing profitability
Steps
Step 1: Gather freelancer context
| Parameter | Default | Example |
|---|---|---|
| Hourly rate | Ask | $150/hr, $85/hr |
| Currency | USD | EUR, GBP, AUD |
| Billing cycle | Monthly | Weekly, per-project |
| Clients | Ask | Acme Corp, StartupX |
| Tax rate | 0% (user adds) | 20% VAT, 25% self-employment |
Step 2: Time tracking sheet
Create or update a tracking spreadsheet (CSV or markdown):
# Time Log: [Month Year]
## [Client Name]
| Date | Project | Task | Hours | Billable | Notes |
|------|---------|------|-------|----------|-------|
| 2026-04-01 | Website Redesign | Homepage wireframes | 3.5 | Yes | Completed v1 |
| 2026-04-01 | Website Redesign | Client feedback call | 0.5 | Yes | Revision notes |
| 2026-04-02 | API Integration | Auth endpoint | 4.0 | Yes | |
| 2026-04-02 | Internal | Admin/invoicing | 1.0 | No | Non-billable |
**Subtotal:** 8.0 billable hours / 9.0 total hours
Time tracking rules:
- Log daily, reconstructing from memory loses hours
- Separate billable from non-billable (admin, learning, invoicing)
- Round to nearest 15 minutes (0.25 hr increments)
- Include project and task for accurate per-project reporting
- Notes field captures context for invoice line items
Step 3: Invoice calculation
Compute totals from the time log:
# Invoice Calculation, [Client Name], [Period]
| Project | Hours | Rate | Subtotal |
|---------|-------|------|----------|
| Website Redesign | 24.5 | $150 | $3,675.00 |
| API Integration | 16.0 | $150 | $2,400.00 |
| | |
|---|---|
| Subtotal | $6,075.00 |
| Tax ([rate]%) | $[amount] |
| **Total Due** | **$[amount]** |
| Payment terms | Net 30 |
| Due date | [date] |
For fixed-price projects, track hours anyway for profitability analysis.
Step 4: Monthly analytics
Generate a freelancer dashboard:
# Freelance Analytics: [Month Year]
## Revenue Summary
| Client | Invoiced | Paid | Outstanding |
|--------|----------|------|-------------|
| Acme Corp | $6,075 | $6,075 | $0 |
| StartupX | $3,200 | $0 | $3,200 |
| **Total** | **$9,275** | **$6,075** | **$3,200** |
## Time Breakdown
- Total hours logged: 82.0
- Billable hours: 68.5 (83.5% utilization)
- Non-billable hours: 13.5
- Effective hourly rate: $135.40 (revenue / total hours)
## Client Concentration
- Acme Corp: 65.5% of revenue (risk: high dependency)
- StartupX: 34.5%
## Profitability by Project
| Project | Hours | Revenue | Effective Rate |
|---------|-------|---------|----------------|
| Website Redesign | 24.5 | $3,675 | $150/hr |
| API Integration | 16.0 | $2,400 | $150/hr |
| Maintenance | 28.0 | $3,200 | $114/hr |
Step 5: Alerts and recommendations
Flag issues automatically:
| Alert | Threshold | Action |
|---|---|---|
| Low utilization | < 70% billable | Review non-billable time, reduce admin overhead |
| Client concentration | > 50% one client | Diversify: pursue new leads |
| Outstanding invoices | > 30 days | Send payment reminder |
| Effective rate below target | < 80% of hourly rate | Review scope creep, renegotiate |
| Overwork | > 45 hrs/week sustained | Raise rates or reduce commitments |
Step 6: File organization
Recommended folder structure:
freelance/
clients/
acme-corp/
time-log-2026-04.md
invoices/
INV-2026-04-001.md
startupx/
time-log-2026-04.md
invoices/
analytics/
2026-04-monthly.md
templates/
invoice-template.md
time-log-template.md
Output Template
Freelancer Report: [Period]:
- Billable hours: [N] ([utilization]% utilization)
- Revenue: $[amount] ([N] invoices)
- Outstanding: $[amount]
- Effective rate: $[rate]/hr
- Alerts: [list any flags]
Files updated: [list]
Disambiguation
- "track my time" / "billable hours" / "freelancer invoice" = Freelancer Toolkit
- "write a proposal" / "project proposal" = Proposal Writer (not this skill)
- "scope of work" / "SOW" = Scope of Work (not this skill)
- "create invoice" / "invoice template" = Invoice Generator (not this skill)
- "financial model" / "projections" = Financial Model (not this skill)
Level History
- Lv.1: Base: Time tracking, invoice calculation, monthly analytics, profitability analysis, alerts. (Origin: MemStack v3.5, Apr 2026)
GDPR: Personal-data assessment from the repo...
Scans a repository for evidence of personal data collection, classifies sensitivity under GDPR, decides whether GDPR applies and how critical the obligations are, and reports the required roles, articles to satisfy, and remediation plan.
Activation
When this skill activates, output:
GDPR, Personal-data assessment from the repo...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "GDPR", "data protection", "privacy compliance" | ACTIVE |
| User asks "do I need GDPR", "does GDPR apply to this project" | ACTIVE |
| User says "DSAR", "right to be forgotten", "cookie consent", "DPA" | ACTIVE |
| User asks about CCPA, LGPD, PIPEDA, UK GDPR | ACTIVE |
| User wants a generic security audit | DORMANT: use owasp-top10 |
| User wants a service agreement or NDA | DORMANT: use contract-template |
| User wants RLS / database access policies | DORMANT: use rls-checker |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "We're a US company so GDPR doesn't apply" | GDPR follows the data subject, not the company. Any EU/UK resident's data triggers it. |
| "Hashed emails aren't personal data" | Hashes are still personal data if reversible or linkable. True anonymisation is irreversible. |
| "Cookie banner with only Accept" | Reject must be equally prominent. Pre-ticked = invalid consent. |
| "Legitimate interest covers everything" | Requires a documented balancing test. Cannot be used for special category data or marketing to children. |
| "We'll get the DPA later" | Article 28 requires a written DPA before processing begins. |
| "72-hour clock starts after we finish investigating" | The clock starts on awareness of a likely breach. |
Disclaimer: Produces a compliance assessment, not legal advice. Engage a qualified DPO or data-protection lawyer before relying on outputs for regulated processing.
Protocol
Step 1: Scan the repo for personal-data signals
Don't ask the user what they collect, find out from the code. Run discovery against every relevant surface:
Database schemas / migrations
find . \( -name "*.sql" -o -name "schema.prisma" -o -name "models.py" -o -name "*.dbml" \) -not -path "*/node_modules/*"
grep -rEin "email|phone|address|first_?name|last_?name|date_?of_?birth|dob|ssn|passport|tax_?id|national_?id|ip_?address|geo|lat|lng|location|gender|race|religion|health|medical|biometric|fingerprint|face|child|minor" --include="*.sql" --include="*.prisma" --include="*.py" --include="*.ts"
Form / UI input fields
grep -rEin "<input[^>]*name=|formField|FormControl|registerField" --include="*.tsx" --include="*.jsx" --include="*.vue" --include="*.svelte"
grep -rEin "type=[\"']email[\"']|type=[\"']tel[\"']|autoComplete=[\"'](name|email|tel|address|cc-|bday)" .
API request schemas / DTOs
grep -rEin "z\.object|class.*BaseModel|interface.*Request|Schema\(" --include="*.ts" --include="*.py"
Auth configuration
find . -iname "auth*" -o -iname "*supabase*" -o -iname "*clerk*" -o -iname "*next-auth*" -o -iname "*firebase*"
grep -rEin "providers:|GoogleProvider|GitHubProvider|EmailProvider|magicLink|phoneSignIn"
Analytics / tracking SDKs
grep -rEin "posthog|mixpanel|amplitude|segment|google-?analytics|gtag|fbq|hotjar|fullstory|datadog.*RUM|sentry" .
Cookies / sessions
grep -rEin "Set-Cookie|cookies\.set|res\.cookie|getServerSession|session\(" .
Logging that may capture PII
grep -rEin "console\.log.*req\.|logger\.(info|debug).*body|print\(.*request" .
Third-party data recipients
cat package.json requirements.txt pyproject.toml composer.json Gemfile 2>/dev/null | grep -Ei "stripe|paypal|sendgrid|mailgun|twilio|openai|anthropic|hubspot|intercom|zendesk|algolia"
Existing privacy artifacts (gap check)
find . \( -iname "privacy*" -o -iname "*dpa*" -o -iname "ropa*" -o -iname "cookie-policy*" -o -iname "data-processing*" \)
Record findings in a working table:
| Source | Field / Signal | Personal Data? | Sensitivity Class |
|--------|---------------|----------------|-------------------|
| db/schema.sql L42 | users.email | Yes | Identifier |
| db/schema.sql L43 | users.phone | Yes | Identifier |
| src/forms/Profile.tsx L18 | dob input | Yes | Identifier (age) |
| src/forms/Health.tsx L7 | medical_conditions | Yes | **Special category (Art 9)** |
| package.json | posthog-js | Yes: behavioral | Behavioral |
| src/api/users.ts L88 | logger.info(req.body) | Possible PII leak | Risk |
If no personal-data signals are found, jump to Step 3 with verdict NO and stop.
Step 2: Classify sensitivity
Bucket every confirmed finding into one or more of:
| Class | Examples | GDPR Treatment |
|---|---|---|
| Identifier | name, email, phone, address, account ID, IP | Standard personal data, Art 6 lawful basis required |
| Financial | card number, bank account, billing address | Standard personal data + PCI scope considerations |
| Location | precise GPS, geo, IP-derived city | Standard personal data; precise location may require explicit consent |
| Behavioral | clickstream, page views, session recording, fingerprint | Standard personal data; consent for non-essential cookies/tracking |
| Government ID | passport, SSN, national ID, driver's licence | Standard personal data but elevated risk; often national-law restricted |
| Special category (Art 9 | health, biometric, genetic, race, ethnicity, religion, political, sexual orientation, trade-union | Prohibited unless an Art 9(2) condition applies) almost always explicit consent |
| Children's data, Art 8 | any data from users under 16 (age varies 13 to 16 by member state) | Requires parental consent for information-society services |
| Criminal data, Art 10 | offences, convictions | Only under official authority or specific national law |
Step 3: Verdict: does GDPR apply, and how critical?
| Question | Answer |
|----------|--------|
| Is any personal data collected? | [Yes / No] |
| Are EU/UK data subjects in scope? | [Yes / Probably (global product) / No (closed user base)] |
| Any special category data (Art 9)? | [Yes / No] |
| Any children's data (Art 8)? | [Yes / No] |
| Large-scale or systematic monitoring? | [Yes / No] |
| Third parties / processors involved? | [Yes / No] |
| Cross-border transfers outside EU/UK? | [Yes / No / Unknown] |
Verdict matrix:
| Scenario | Verdict | Criticality |
|---|---|---|
| No personal data at all | GDPR does not apply | None |
| Personal data + EU/UK subjects unlikely (e.g. closed internal tool, non-EU user base) | GDPR applies if even one EU/UK subject; treat as best practice | 🟩 LOW |
| Standard identifiers + EU/UK subjects | GDPR applies | 🟨 MEDIUM |
| Identifiers + financial / location / behavioral tracking | GDPR applies, multiple obligations | 🟧 HIGH |
| Any Art 9 special category data | GDPR applies, strict | 🟥 CRITICAL |
| Any children's data | GDPR applies, strict + Art 8 parental consent | 🟥 CRITICAL |
| Large-scale systematic monitoring or profiling | GDPR applies, DPIA required | 🟥 CRITICAL |
Step 4: Map required roles
Based on the verdict, list which roles the project must staff:
| Role | Triggered When | Status |
|---|---|---|
| Controller (Art 4(7)) | Project decides purposes and means of processing: almost always you | Required |
| Joint controllers (Art 26) | Shared decisions with another org | Check |
| Processor (Art 4(8)) | You process data on behalf of another controller | Check |
| DPO (Art 37) | Public authority, OR core activities = large-scale systematic monitoring, OR core activities = large-scale special category | Required if any trigger |
| Art 27 EU representative | Controller/processor not established in EU but processes EU data, AND processing is not occasional | Required if any trigger |
| Internal owner | Every project, accountable for GDPR posture day-to-day | Required |
Step 5: Map required articles to fulfill
Only list the articles that actually trigger for this project, with a one-line "what to do" for each:
| Article | Obligation | Triggered? | Concrete action |
|---|---|---|---|
| Art 5: Principles | Lawfulness, fairness, transparency, purpose limitation, minimisation, accuracy, storage limitation, integrity, accountability | Always | Document each principle is met |
| Art 6, Lawful basis | Pick one of 6 bases per processing activity | Always | Add lawful basis column to ROPA |
| Art 7: Conditions for consent | If any basis is consent | If consent | Implement explicit, granular, withdrawable consent UI |
| Art 8, Children | If under-16 users | If children | Parental consent flow |
| Art 9, Special category | If health/biometric/etc. | If Art 9 data | Explicit consent + extra safeguards |
| Art 13/14, Transparency | Privacy notice at collection | Always | Publish privacy policy that mirrors actual processing |
| Art 15 to 22: Subject rights | Access, rectification, erasure, restriction, portability, objection, ADM | Always | Implement DSAR endpoint + 30-day SLA |
| Art 25, Privacy by design | Default settings minimise data | Always | Code review checklist |
| Art 28, Processors | Written DPA before processing | If any processor | Sign DPAs with every vendor |
| Art 30, ROPA | Record of Processing Activities | If 250+ employees OR not occasional OR Art 9 | Maintain ROPA |
| Art 32: Security | TIA-equivalent technical/organisational measures | Always | Document encryption, access control, backups |
| Art 33, Breach to authority | 72h notification | Always | Breach runbook |
| Art 34, Breach to subjects | Without undue delay if high risk | Always | Subject notification template |
| Art 35, DPIA | High-risk processing | If profiling/large scale/Art 9 | Run DPIA before launch |
| Art 37 to 39, DPO | If triggered (see Step 4) | If triggered | Appoint and publish |
| Chapter V, Transfers | International transfers | If any | SCCs / adequacy / BCRs + TIA |
Step 6: Gap analysis from the repo
For each triggered article in Step 5, check whether the repo already has evidence of the obligation:
| Obligation | Evidence in repo? | Gap |
|------------|-------------------|-----|
| Privacy policy (Art 13) | ❌ Not found | Draft from ROPA |
| Cookie banner (ePrivacy + Art 6) | ✅ src/components/CookieBanner.tsx | Verify reject is equally prominent |
| DSAR endpoint (Art 15 to 22) | ❌ Not found | Implement /api/account/export and /api/account/delete |
| DPA with Stripe (Art 28) | ❓ Unknown | Confirm signed, store reference |
| Breach runbook (Art 33) | ❌ Not found | Create docs/security/breach-runbook.md |
| ROPA (Art 30) | ❌ Not found | Draft from Step 1 inventory |
| DPIA (Art 35) | ❌ Required (Art 9 data present) | Run before any launch |
Step 7: Produce the assessment report
## GDPR Assessment: [Project Name]
**Date:** [YYYY-MM-DD]
**Verdict:** GDPR **[APPLIES / DOES NOT APPLY / APPLIES AS BEST PRACTICE]**
**Criticality:** [🟥 CRITICAL / 🟧 HIGH / 🟨 MEDIUM / 🟩 LOW / None]
### Why this verdict
[2 to 4 sentences referencing the specific data found in Step 1: e.g. "The repo collects user emails, phone numbers, dates of birth, and self-reported medical conditions through src/forms/Health.tsx. The medical_conditions field is special category data under Article 9, which elevates the project to CRITICAL regardless of user geography."]
### Personal data inventory
[Table from Step 1, filtered to confirmed personal data]
### Sensitivity classification
[Counts per class from Step 2]
### Required roles
[Table from Step 4]
### Required articles to satisfy
[Filtered table from Step 5 showing only triggered rows]
### Gaps found in the repo
[Table from Step 6]
### Remediation plan (priority order)
1. **🟥 [Critical fix]**: [what + which file/system + estimated effort]
2. **🟧 [High fix]**: ...
3. **🟨 [Medium fix]**: ...
4. **🟩 [Low / hardening]**: ...
### What to do if you ignore this
[1 to 3 sentences naming the concrete legal exposure: maximum fines under Art 83 are €20M or 4% of global annual turnover, whichever is higher; supervisory authority enforcement; reputational damage; civil claims under Art 82.]
### Recommended next steps
1. [Owner], [Action], [Due]
2. ...
Output Format
Deliver the Step 7 report as markdown. Save under docs/compliance/gdpr-assessment.md if a project layout is available. Include the exact discovery commands you ran in an appendix so the user can reproduce the scan.
Completion
GDPR: Assessment complete!
Verdict: [APPLIES / DOES NOT APPLY / BEST PRACTICE]
Criticality: [tier]
Personal data fields found: [N]
Special category fields: [N]
Triggered articles: [N]
Gaps to remediate: [N]
Next steps:
1. Address all 🟥 CRITICAL gaps before any further processing
2. Draft missing artifacts (privacy policy, ROPA, DPA, breach runbook)
3. Implement DSAR endpoints in the codebase
4. Run a DPIA if special-category or large-scale profiling is in scope
5. Have a qualified DPO or data-protection lawyer review before going live
Level History
- Lv.1: Base: repo-driven scan across schemas/forms/DTOs/auth/analytics/cookies/logging/third parties, sensitivity classification (identifier/financial/location/behavioral/Art 9/Art 8/Art 10), verdict matrix with 7 scenarios, role mapping (Controller/Processor/DPO/Art 27 rep), 16-article obligation map, repo gap analysis, full assessment report with criticality tier, why-this-verdict section, remediation priority list, and exposure summary. (Origin: MemStack Pro v3.6, Apr 2026)
Invoice Generator: Creating professional invoice...
Generates professional invoices with line items, tax calculations, payment terms, due dates, and payment instructions. Output as structured markdown ready for PDF conversion.
Activation
When this skill activates, output:
Invoice Generator: Creating professional invoice...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "invoice", "generate invoice", "create invoice", "bill client" | ACTIVE |
| User says "line items" or "payment terms" | ACTIVE |
| User needs a professional invoice for a client | ACTIVE |
| User wants a contract or service agreement | DORMANT: use Contract Template |
| User wants financial projections | DORMANT: use Financial Model |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "No invoice number" | Sequential invoice numbers are required for accounting and tax compliance. |
| "Vague line items" | "Consulting: $5,000" invites disputes. Itemize by deliverable, hours, or phase. |
| "No payment terms" | Without explicit terms (Net 30, due on receipt), clients have no obligation to pay on time. |
| "Skip tax line" | Even if tax is $0, show the tax line. It demonstrates professionalism and compliance. |
| "No late payment terms" | Without stated consequences, you have no leverage on overdue invoices. |
Protocol
Step 1: Gather Invoice Details
If the user hasn't provided details, ask:
- Client: company name, contact person, billing address
- Your business: business name, address, tax ID / EIN (if applicable)
- Line items: what are you billing for? (description, quantity, rate)
- Payment terms: Net 30, Net 15, due on receipt?
- Tax: applicable tax rate? (state sales tax, VAT, or exempt)
- Currency: USD, EUR, GBP, etc.?
Step 2: Generate Invoice Number
Invoice numbering convention:
[PREFIX]-[YEAR][MONTH]-[SEQUENCE]
Example: INV-202603-001
| Component | Rule |
|---|---|
| Prefix | INV (standard), PRO (proforma), CR (credit note) |
| Date | YYYYMM of invoice date |
| Sequence | 001, 002, 003... (reset yearly or continuous) |
Alternative formats:
- Client-based:
INV-ACME-001 - Project-based:
INV-PROJ042-001
Step 3: Build Line Items
Line item table:
| # | Description | Qty | Unit | Rate | Amount |
|---|---|---|---|---|---|
| 1 | [Detailed description of work/deliverable] | [X] | [hours/units/flat] | $[X.XX] | $[X.XX] |
| 2 | [Detailed description] | [X] | [unit] | $[X.XX] | $[X.XX] |
| 3 | [Detailed description] | [X] | [unit] | $[X.XX] | $[X.XX] |
Line item rules:
- Each line should describe a specific deliverable or time period
- Include enough detail to prevent client questions ("Website development" → "Homepage redesign, responsive layout, 3 revision rounds")
- For hourly work: include date range and total hours
- For project work: reference the SOW or contract phase
- For expenses: mark as "Reimbursable expense" with receipt reference
Totals calculation:
Subtotal: $[sum of line amounts]
Discount ([X]%): -$[discount amount]
Subtotal after discount: $[adjusted subtotal]
Tax ([X]% [tax name]): +$[tax amount]
──────────────────────────────────
Total Due: $[final total]
Step 4: Set Payment Terms
Standard payment terms:
| Term | Meaning | Best For |
|---|---|---|
| Due on receipt | Pay immediately | Small amounts, first-time clients |
| Net 15 | Due within 15 days | Freelance, small projects |
| Net 30 | Due within 30 days | Standard business term |
| Net 60 | Due within 60 days | Enterprise, government |
| 50/50 | 50% upfront, 50% on completion | Projects >$5,000 |
| Milestone | Payment at each project phase | Large projects |
Late payment clause:
Late Payment: Invoices not paid within [X] days of the due date will
incur a late fee of [1.5]% per month ([18]% annually) on the outstanding
balance. All collection costs, including attorney fees, will be the
responsibility of the client.
Early payment discount (optional):
2/10 Net 30: 2% discount if paid within 10 days; full amount due in 30 days.
Step 5: Add Payment Instructions
## Payment Methods
**Bank Transfer (preferred):**
Bank: [Bank name]
Account name: [Business name]
Routing number: [XXXXXXXXX]
Account number: [XXXXXXXXX]
Reference: [Invoice number]
**Online Payment:**
Pay online: [Payment link: Stripe, PayPal, or Square invoice URL]
**Check:**
Make payable to: [Business name]
Mail to: [Mailing address]
Memo: [Invoice number]
**Wire Transfer (international):**
SWIFT/BIC: [Code]
IBAN: [Number]
Bank address: [Address]
Step 6: Assemble the Invoice
Invoice template:
─────────────────────────────────────────────────────────
INVOICE
─────────────────────────────────────────────────────────
**From:** **Invoice #:** [INV-YYYYMM-NNN]
[Your Business Name] **Date:** [Invoice date]
[Your Address] **Due Date:** [Due date]
[City, State ZIP] **Terms:** [Net 30 / etc.]
[Email]
[Phone]
[Tax ID: XX-XXXXXXX]
**Bill To:**
[Client Company Name]
[Client Contact Name]
[Client Address]
[City, State ZIP]
[Client Email]
─────────────────────────────────────────────────────────
| # | Description | Qty | Rate | Amount |
|----|---------------------------------|------|-----------|-----------|
| 1 | [Line item description] | [X] | $[X.XX] | $[X.XX] |
| 2 | [Line item description] | [X] | $[X.XX] | $[X.XX] |
| 3 | [Line item description] | [X] | $[X.XX] | $[X.XX] |
─────────────────────────────────────────────────────────
Subtotal: $[X,XXX.XX]
Tax ([X]%): $[XXX.XX]
──────────────────────────
**TOTAL DUE: $[X,XXX.XX]**
─────────────────────────────────────────────────────────
## Payment Instructions
[From Step 5]
## Terms
- Payment is due within [X] days of invoice date.
- [Late payment clause from Step 4]
- [Early payment discount if applicable]
─────────────────────────────────────────────────────────
Thank you for your business.
─────────────────────────────────────────────────────────
Step 7: Recurring Invoice Setup
For ongoing retainer or subscription billing:
## Recurring Invoice Schedule
| Invoice # | Period | Amount | Due Date | Status |
|-----------|--------|--------|----------|--------|
| INV-202601-001 | Jan 2026 | $[X] | [Date] | Paid |
| INV-202602-001 | Feb 2026 | $[X] | [Date] | Paid |
| INV-202603-001 | Mar 2026 | $[X] | [Date] | Current |
| INV-202604-001 | Apr 2026 | $[X] | [Date] | Upcoming |
Automation tips:
- Use Stripe Invoicing, QuickBooks, or FreshBooks for recurring invoices
- Set automatic payment reminders: 3 days before due, on due date, 7 days overdue
- Auto-generate the next invoice on a fixed schedule (1st of month, etc.)
Output Format
Deliver the complete invoice in the template format from Step 6, ready to be:
- Converted to PDF (via Pandoc, browser print, or invoicing tool)
- Pasted into an invoicing platform
- Sent directly to the client
Completion
Invoice Generator: Complete!
Invoice #: [Number]
Client: [Name]
Line items: [Count]
Subtotal: $[Amount]
Tax: $[Amount]
Total due: $[Amount]
Payment terms: [Terms]
Due date: [Date]
Next steps:
1. Review all line items for accuracy
2. Convert to PDF or enter into your invoicing tool
3. Send to client with payment instructions
4. Set a calendar reminder for the due date
5. Follow up if not paid within 3 days of due date
Level History
- Lv.1: Base: Invoice numbering convention, detailed line items with totals/tax/discount, 6 payment term options, late payment clause, early payment discount, 4 payment method templates (bank, online, check, wire), complete invoice template, recurring invoice schedule, automation tips. (Origin: MemStack Pro v3.2, Mar 2026)
Licensing: Commercial-use license audit from the repo...
Scans a repository for every license that touches the product (deps, vendored code, fonts, assets), then produces a per-package verdict table marking each as Ready, Citation Required, Needs Info, or Not Allowed for commercial use.
Activation
When this skill activates, output:
Licensing, Commercial-use license audit from the repo...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "license audit", "licensing", "license check" | ACTIVE |
| User asks "can I use this commercially?" or "is this safe to ship?" | ACTIVE |
| User mentions GPL, AGPL, LGPL, MPL, MIT, BSD, Apache, copyleft | ACTIVE |
| User is preparing to ship, sell, or relicense a product | ACTIVE |
| User wants security vulnerability scanning | DORMANT: use dependency-audit |
| User wants a service contract or NDA | DORMANT: use contract-template |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "MIT and GPL are both open source so they're compatible" | Combining MIT into GPL is fine; the reverse forces your code under GPL. Direction matters. |
| "We don't distribute, so AGPL doesn't apply" | AGPL §13 triggers on network use. SaaS counts. |
| "It's on GitHub so it's free to use" | Public ≠ licensed. No LICENSE file = all rights reserved. |
| "Transitive dependencies don't matter" | Your bundle ships every dep in the tree. Copyleft transitives can taint the whole product. |
| "License from package.json metadata is authoritative" | The actual LICENSE file in upstream source is authoritative. Metadata is often wrong, missing, or outdated. |
| "BSL / SSPL / Elastic / Commons Clause are open source" | They are not OSI-approved and usually restrict commercial hosting or competition. Read the actual terms. |
Disclaimer: Produces a license inventory and risk assessment, not legal advice. License interpretation (especially copyleft scope, "linking", and SaaS triggers) is contested. Engage IP counsel before shipping high-stakes products.
Protocol
Step 1: Confirm the distribution model
Just one question, the verdict logic depends on it:
How is the product distributed?
- A. SaaS / hosted (users access over the network, no binary handed out)
- B. Distributed binary (desktop, mobile, on-prem install, downloadable executable)
- C. Open-source library you publish for others to consume
- D. Internal only (no users outside your organisation)
Default to A if the repo contains web framework code (Next.js, FastAPI, Rails, etc.) and no installer/build target.
Step 2: Scan the repo for every license source
Walk every manifest, lockfile, vendored directory, and asset folder. Never trust a single source: cross-check.
| Stack | Manifest | Discovery command |
|---|---|---|
| Node.js | package.json, package-lock.json, pnpm-lock.yaml, yarn.lock | npm ls --all --json then npx license-checker --json --production |
| Python | requirements*.txt, pyproject.toml, Pipfile.lock, poetry.lock | pip-licenses --format=json --with-license-file --with-urls |
| Rust | Cargo.toml, Cargo.lock | cargo license --json |
| Go | go.mod, go.sum | go-licenses report ./... --template '{{.Name}},{{.LicenseName}},{{.LicenseURL}}' |
| Java | pom.xml, build.gradle | mvn license:add-third-party or gradle-license-report |
| Ruby | Gemfile, Gemfile.lock | bundle exec license_finder report --format json |
| PHP | composer.json, composer.lock | composer licenses --format=json |
| .NET | *.csproj, packages.lock.json | dotnet list package --include-transitive + nuget-license |
| Container base images | Dockerfile | syft <image> -o spdx-json then read package licenses |
| Vendored / submodules | vendor/, third_party/, .gitmodules | walk directories: look for LICENSE, LICENSE.md, COPYING, NOTICE |
| Fonts / icons / media | assets/, public/, static/ | check each asset's source license: commonly missed |
| Snippets and copy-pasted code | comments, headers | `grep -rEin "Copyright |
For everything found, capture:
| Package | Version | Declared license (manifest) | License file present | Direct/transitive | Source URL |
|---------|---------|----------------------------|---------------------|-------------------|------------|
| react | 18.3.1 | MIT | Yes | direct | github.com/facebook/react |
| ... | ... | ... | ... | ... | ... |
Step 3: Resolve the actual license (don't trust metadata)
For every entry that is HIGH-impact (copyleft candidate, missing license, or version where licenses are known to change), open the upstream LICENSE file and confirm the SPDX identifier.
Watch for license changes between versions:
| Project | Version cut | Old → New |
|---|---|---|
| Elasticsearch | 7.10 → 7.11 | Apache-2.0 → SSPL/Elastic |
| Redis | 7.2 → 7.4 | BSD → SSPL/RSAL |
| Terraform | 1.5 → 1.6 | MPL-2.0 → BSL |
| MongoDB | 4.0 | AGPL → SSPL |
| HashiCorp tools | 2023 | MPL-2.0 → BSL |
| Sentry | 8.x | BSD → FSL |
Pin to the last compliant version or migrate.
Also check for:
- Dual licensing ("MIT OR Apache-2.0"), pick the option you'll comply with and record the choice
- Commons Clause layered on top of an OSI license: restricts "selling"
- Custom / vendor licenses: read the actual terms verbatim
Step 4: Classify each license
| Class | Examples | Commercial use allowed? | Reach |
|---|---|---|---|
| Public domain | CC0, Unlicense, WTFPL, 0BSD | Yes: no obligations | None |
| Permissive | MIT, BSD-2/3, ISC, Apache-2.0, Zlib | Yes: preserve notice | None |
| Weak copyleft | LGPL-2.1, LGPL-3.0, MPL-2.0, EPL-2.0 | Yes with obligations | File-level (MPL) or dynamic-linking carve-out (LGPL) |
| Strong copyleft | GPL-2.0, GPL-3.0 | Yes, but derivative works become GPL on distribution | Whole derivative work |
| Network copyleft | AGPL-3.0 | Yes, but SaaS triggers source disclosure | Whole derivative work + network use |
| Source-available (non-OSI) | BSL, SSPL, Elastic v2, Commons Clause, RSAL, FSL | Restricted: usually no competing hosted service | Per terms |
| Creative Commons | CC-BY, CC-BY-SA, CC-BY-NC, CC-BY-ND | NC = no commercial; SA = share-alike; ND = no derivatives | Per variant |
| Proprietary / commercial EULA | Vendor SDKs, paid libraries | Per contract | Per contract |
| Unknown / no license | No LICENSE file | No, all rights reserved by default | N/A |
Step 5: Apply the verdict per package
For every dependency, run it through the distribution model from Step 1 and assign exactly one verdict:
| Verdict | Symbol | Meaning |
|---|---|---|
| Ready for commercial use | ✅ | No obligations beyond preserving the existing notice file. Safe to ship. |
| Citation / attribution required | 📝 | Commercial use is allowed but the license requires the copyright notice and license text to be reproduced (typically in THIRD_PARTY_LICENSES.md, an About page, or alongside the binary). MIT, BSD, Apache-2.0, ISC, Zlib all fall here when shipped to users. |
| More information needed | ❓ | License is unknown, ambiguous, dual-licensed, or version-changed. Cannot ship until resolved. |
| Not allowed for commercial use | ❌ | License blocks the chosen distribution model. Must replace, remove, relicense, or buy a commercial exception. |
Verdict rules per distribution model:
| License class | A. SaaS | B. Binary | C. OSS library | D. Internal |
|---|---|---|---|---|
| Public domain | ✅ | ✅ | ✅ | ✅ |
| Permissive (MIT, BSD, Apache, ISC, Zlib) | 📝 | 📝 | 📝 | ✅ |
| LGPL | 📝 | 📝 (must allow relinking) | 📝 | ✅ |
| MPL-2.0 / EPL-2.0 | 📝 | 📝 (file-level disclosure) | 📝 | ✅ |
| GPL-2.0 / GPL-3.0 | 📝 (no distribution = no source disclosure) | ❌ (forces whole product GPL) | ❌ unless your lib is also GPL | ✅ |
| AGPL-3.0 | ❌ (network use triggers source disclosure) | ❌ | ❌ unless your lib is AGPL | ✅ |
| BSL | ❓ → usually ❌ for SaaS (read additional use grant) | ❓ | ❌ | ✅ |
| SSPL | ❌ for SaaS | ❌ | ❌ | ✅ |
| Elastic v2 / Commons Clause / RSAL / FSL | ❌ | ❌ | ❌ | ✅ |
| CC-BY | 📝 | 📝 | 📝 | ✅ |
| CC-BY-SA | 📝 (share-alike on derivatives) | 📝 | ❌ unless your work is also SA | ✅ |
| CC-BY-NC | ❌ | ❌ | ❌ | ✅ |
| CC-BY-ND | ❌ if modified | ❌ if modified | ❌ if modified | ✅ |
| Proprietary EULA | per contract | per contract | per contract | per contract |
| Unknown / no license | ❓ → ❌ until resolved | ❓ → ❌ | ❓ → ❌ | ❓ → ❌ |
Step 6: Build the verdict table
This is the primary deliverable. One row per dependency, sorted by verdict severity (❌ → ❓ → 📝 → ✅).
| Package | Version | License | Direct/Trans | Verdict | Required action |
|---------|---------|---------|--------------|---------|----------------|
| ❌ mongodb | 6.0.5 | SSPL-1.0 | direct | ❌ Not allowed for SaaS | Replace with PostgreSQL or buy commercial license |
| ❌ some-lib | 2.1.0 | AGPL-3.0 | direct | ❌ Not allowed for SaaS | Replace with permissive alternative |
| ❓ obscure-pkg | 0.4.2 | (no LICENSE file) | transitive | ❓ Unknown | Open upstream issue; pin or remove until resolved |
| ❓ dual-pkg | 1.2.0 | "MIT OR GPL-3.0" | direct | ❓ Choose | Document MIT election in NOTICE |
| 📝 react | 18.3.1 | MIT | direct | 📝 Citation required | Add to THIRD_PARTY_LICENSES.md |
| 📝 fastify | 4.26.0 | MIT | direct | 📝 Citation required | Add to THIRD_PARTY_LICENSES.md |
| 📝 lodash | 4.17.21 | MIT | transitive | 📝 Citation required | Add to THIRD_PARTY_LICENSES.md |
| 📝 protobufjs | 7.2.5 | BSD-3-Clause | transitive | 📝 Citation required | Add to THIRD_PARTY_LICENSES.md |
| 📝 fonts/inter | none | OFL-1.1 | asset | 📝 Citation required | Include OFL.txt in assets/fonts/ |
| ✅ classnames | 2.5.1 | MIT | transitive | ✅ Ready | (already in attribution bundle) |
| ✅ public-domain-pkg | 1.0.0 | CC0-1.0 | direct | ✅ Ready | None |
Step 7: Generate the attribution bundle
For every 📝 row, the user needs a THIRD_PARTY_LICENSES.md (or NOTICES.txt) shipped alongside the product. Offer to generate it:
# Third-Party Licenses
This product includes the following third-party software:
## react v18.3.1
**License:** MIT
**Source:** https://github.com/facebook/react
**Copyright:** Copyright (c) Meta Platforms, Inc. and affiliates.
[Full MIT license text verbatim]
---
## next-package vA.B.C
...
For Apache-2.0 deps, also preserve any upstream NOTICE file content.
Step 8: Produce the report
## License Audit: [Project Name]
**Date:** [YYYY-MM-DD]
**Distribution model:** [A. SaaS / B. Binary / C. Library / D. Internal]
**Project's own license:** [SPDX or "proprietary"]
**Total dependencies analysed:** [N direct + M transitive + K assets]
### Verdict summary
| Verdict | Count |
|---------|-------|
| ❌ Not allowed for commercial use | [N] |
| ❓ More information needed | [N] |
| 📝 Citation / attribution required | [N] |
| ✅ Ready for commercial use | [N] |
### Commercial-use verdict
**[CLEAR TO SHIP / CLEAR WITH CITATION OBLIGATIONS / BLOCKED]**
[2 to 3 sentences explaining the verdict and naming the specific blockers if any.]
### Full verdict table
[Table from Step 6]
### Required attribution bundle
[Either inline THIRD_PARTY_LICENSES.md content, or a list of packages that must appear in it]
### Remediation plan (priority order)
1. **❌ [Blocker]**: [package], [replace with X / remove feature Y / buy license / quarantine]
2. **❓ [Unknown]**: [package]: [investigation step]
3. **📝 [Attribution gap]**: [add to THIRD_PARTY_LICENSES.md]
### Recommended next steps
1. Resolve every ❌ before shipping
2. Resolve every ❓ before shipping
3. Generate / update `THIRD_PARTY_LICENSES.md` and ship with the product
4. Add an automated license check to CI to catch new dependencies
5. Re-run this audit before each release
6. Have IP counsel review if any BSL/SSPL/AGPL/unknown findings remain
Output Format
Deliver the Step 8 report as markdown. Save under docs/compliance/license-audit.md if a project layout is available. Save the generated attribution bundle as THIRD_PARTY_LICENSES.md at the repo root. Include the exact discovery commands you ran in an appendix so the user can reproduce.
Completion
Licensing: Audit complete!
Distribution model: [A / B / C / D]
Dependencies analysed: [N direct + M transitive + K assets]
❌ Blocked: [N]
❓ Unknown: [N]
📝 Citation required: [N]
✅ Ready: [N]
Verdict: [CLEAR / CLEAR WITH OBLIGATIONS / BLOCKED]
Next steps:
1. Resolve every ❌ before shipping
2. Resolve every ❓ before shipping
3. Ship THIRD_PARTY_LICENSES.md alongside the product
4. Add license check to CI
5. Have IP counsel review high-risk findings
Level History
- Lv.1: Base: distribution-model question, multi-language repo scan (Node/Python/Rust/Go/Java/Ruby/PHP/.NET/containers/vendored/assets), upstream LICENSE verification, version-change traps (Elastic/Mongo/Redis/Terraform/Sentry/HashiCorp), 9-class taxonomy, 4-verdict system (✅ Ready / 📝 Citation / ❓ Needs info / ❌ Not allowed), distribution-model verdict matrix, primary verdict table, attribution bundle generator, full report with summary counts and remediation plan. (Origin: MemStack Pro v3.6, Apr 2026)
📝 Proposal Writer: Drafting project proposal...
Generates a professional project proposal with executive summary, deliverables, tiered pricing, timeline, and terms, ready to send as PDF or email.
Activation
When this skill activates, output:
📝 Proposal Writer: Gathering project details...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "write proposal" or "create proposal" | ACTIVE |
| User says "pitch" or "bid on project" or "client proposal" | ACTIVE |
| Preparing a document to send to a prospective client | ACTIVE |
| Writing internal project plans (no client) | DORMANT: use scope-of-work |
| Discussing pricing strategy generally | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Just list what we'll build" | Proposals sell outcomes, not features. Lead with the problem you solve. |
| "One price, take it or leave it" | Tiered pricing lets clients choose their budget level. Always offer 2-3 options. |
| "We'll figure out scope later" | Vague scope creates disputes. Define deliverables AND exclusions explicitly. |
| "Terms can wait until contract" | Payment schedule, revision limits, and IP ownership prevent 80% of freelance conflicts. Include them. |
| "The longer the better" | Busy clients skim. Executive summary + pricing first. Details in appendix. |
Protocol
Step 1: Gather Project Requirements
If the user hasn't provided project details, ask:
I need a few details for the proposal:
- Client name and company
- Project type (web app, mobile app, marketing site, API, etc.)
- Core problem: what does the client need solved?
- Rough scope: key features or deliverables
- Timeline: any deadlines or target launch date?
- Budget range: if known (helps calibrate tier pricing)
If the user provides partial info, ask only for what's missing. Don't ask for information you can infer.
Step 2: Write Executive Summary
The executive summary is what the client reads first (and sometimes only). It must:
- Name the problem the client faces, in their language, not technical jargon
- Present the solution at a high level, what you'll build and why it works
- State the outcome: what the client gets (revenue, time saved, users served)
- Establish credibility: briefly mention relevant experience
Template:
## Executive Summary
[Client name] needs [problem statement: what's broken, missing, or inefficient].
We propose [solution summary, what you'll build] using [key technology/approach].
This will [primary outcome, measurable benefit to the client].
Based on our experience with [relevant past work], we estimate [timeline]
for full delivery, with [key milestone] available within [shorter timeframe].
Rules:
- Max 150 words, if you can't summarize in 150 words, you don't understand the project
- No technical jargon the client wouldn't use
- Lead with their problem, not your solution
- Include one specific number (timeline, cost savings, user capacity)
Step 3: Break Down Deliverables
List every deliverable with estimated hours per phase:
## Deliverables
### Phase 1: Foundation (Week 1-2)
| Deliverable | Description | Est. Hours |
|-------------|-------------|-----------|
| Project setup | Repository, CI/CD, staging environment | 8 |
| Authentication | User registration, login, password reset | 16 |
| Database design | Schema, migrations, seed data | 12 |
| **Phase subtotal** | | **36** |
### Phase 2: Core Features (Week 3-5)
| Deliverable | Description | Est. Hours |
|-------------|-------------|-----------|
| Dashboard | Admin dashboard with key metrics | 24 |
| User management | CRUD, roles, permissions | 20 |
| API integration | Connect to [external service] | 16 |
| **Phase subtotal** | | **60** |
### Phase 3: Polish & Launch (Week 6-7)
| Deliverable | Description | Est. Hours |
|-------------|-------------|-----------|
| Testing | Unit tests, integration tests, QA | 16 |
| Deployment | Production setup, domain, SSL | 8 |
| Documentation | User guide, API docs | 8 |
| **Phase subtotal** | | **32** |
**Total estimated hours: 128**
Rules:
- Group deliverables by phase (foundation, core, polish)
- Each deliverable is specific and verifiable (not "backend work")
- Hours are estimates, include a buffer note ("+/- 15%")
- Include testing, deployment, and documentation: clients forget these exist
Step 4: Tech Stack Recommendation
Justify the technology choices:
## Technical Approach
| Layer | Technology | Why |
|-------|-----------|-----|
| Frontend | Next.js 15 + React | Fast development, SEO-friendly, scales well |
| Styling | Tailwind CSS | Rapid UI development, consistent design system |
| Backend | Next.js API Routes | Unified codebase, simplifies deployment |
| Database | Supabase (Postgres) | Real-time capabilities, built-in auth, RLS |
| Hosting | Railway + Netlify | Reliable, auto-scaling, CI/CD built-in |
| Auth | Supabase Auth | Secure, supports OAuth, handles sessions |
This stack was chosen for [speed of development / scalability / client's existing infrastructure / cost-effectiveness].
Rules:
- Only include if the client cares about technical details (some don't)
- Justify each choice in client terms (fast, cheap, reliable: not "it's cool")
- Mention alternatives you considered and why you didn't pick them
- Flag any client-side constraints (existing systems, team expertise)
Step 5: Create Tiered Pricing
Always offer 2-3 options: never a single price:
## Investment
### Option A: Essential, $X,XXX
Core functionality to solve the primary problem.
- [Deliverable 1]
- [Deliverable 2]
- [Deliverable 3]
- 1 round of revisions
- 30 days post-launch support
### Option B: Standard, $XX,XXX ⭐ Recommended
Full solution with all planned features.
- Everything in Essential, plus:
- [Additional deliverable 4]
- [Additional deliverable 5]
- [Additional deliverable 6]
- 2 rounds of revisions
- 60 days post-launch support
### Option C: Premium, $XX,XXX
Complete solution with ongoing support and future-proofing.
- Everything in Standard, plus:
- [Premium deliverable 7]
- [Premium deliverable 8]
- Priority support and maintenance
- 3 rounds of revisions
- 90 days post-launch support + monthly check-ins
All prices exclude applicable taxes. See Payment Terms below.
Pricing rules:
- Standard tier should be the one you actually want them to pick
- Essential is 60-70% of Standard price: stripped to minimum viable
- Premium is 140-160% of Standard price: adds ongoing value
- Mark the recommended tier visually
- Include revision rounds and support period in each tier, these are the #1 source of scope creep
Step 6: Timeline with Milestones
## Timeline
| Milestone | Target Date | Deliverables |
|-----------|------------|-------------|
| Kickoff | [Date] | Requirements review, access handoff |
| Phase 1 Complete | [Date + 2 weeks] | Foundation: auth, database, staging |
| Phase 1 Review | [Date + 2.5 weeks] | Client review and feedback |
| Phase 2 Complete | [Date + 5 weeks] | Core features on staging |
| Phase 2 Review | [Date + 5.5 weeks] | Client review and feedback |
| Phase 3 Complete | [Date + 7 weeks] | Testing, deployment, docs |
| Launch | [Date + 7.5 weeks] | Production deployment |
| Support Period Begins | [Date + 8 weeks] | Post-launch monitoring |
**Notes:**
- Timeline assumes prompt feedback at review milestones (2 business days)
- Delays in feedback shift subsequent milestones by the same duration
- Timeline is for [Standard tier], Essential is shorter, Premium is longer
Rules:
- Include explicit review/feedback milestones (clients cause most delays)
- State feedback turnaround expectation
- Note that delayed feedback shifts the timeline
- Tie timeline to the recommended tier
Step 7: Terms and Conditions
## Terms
### Payment Schedule
| Milestone | Amount | Due |
|-----------|--------|-----|
| Project kickoff | 30% ($X,XXX) | Upon signing |
| Phase 2 complete | 40% ($X,XXX) | On delivery |
| Final delivery | 30% ($X,XXX) | On launch |
### Revision Policy
- Each tier includes [N] rounds of revisions per phase
- A "round" is a single set of consolidated feedback
- Additional revision rounds billed at $XXX/round
- Revisions must be submitted within 5 business days of delivery
### Intellectual Property
- All code and assets become client property upon final payment
- Third-party libraries remain under their original licenses
- We retain the right to use the project in our portfolio (unless client opts out)
### Cancellation
- Client may cancel with 7 days written notice
- Work completed to date is billed at hourly rate ($XXX/hr)
- Deposit is non-refundable after kickoff meeting
### Confidentiality
- Both parties agree to keep project details confidential
- NDA available upon request
Rules:
- Payment is milestone-based, never 100% upfront or 100% on completion
- Revision policy prevents infinite feedback loops
- IP transfers on final payment, protects you if they don't pay
- Cancellation terms protect both sides
Step 8: Assemble Final Document
Output the complete proposal in clean markdown:
# Project Proposal: [Project Name]
**Prepared for:** [Client Name], [Company]
**Prepared by:** [Your Name / Company]
**Date:** [YYYY-MM-DD]
**Valid until:** [Date + 30 days]
---
## Executive Summary
[Step 2 output]
## Deliverables
[Step 3 output]
## Technical Approach
[Step 4 output]
## Investment
[Step 5 output]
## Timeline
[Step 6 output]
## Terms
[Step 7 output]
---
## Next Steps
To proceed, please:
1. Select your preferred tier (Essential / Standard / Premium)
2. Sign this proposal (reply with written confirmation)
3. Submit the initial deposit
We'll schedule a kickoff meeting within 3 business days of receiving both.
Questions? Reply to this email or call [phone number].
---
*This proposal is valid for 30 days from the date above.*
Output summary:
📝 Proposal Writer: Complete
Client: [name]
Project: [project name]
Tiers: Essential ($X) / Standard ($XX) / Premium ($XXX)
Timeline: [N] weeks (Standard tier)
Phases: [N] with [N] review milestones
Document: [word count] words, ready for PDF conversion
Next steps:
1. Review and customize pricing figures
2. Add your company details and contact info
3. Export to PDF or paste into email
Level History
- Lv.1: Base: Requirements gathering, executive summary, phased deliverables with hours, tech stack justification, 3-tier pricing, milestone timeline, terms (payment, revisions, IP, cancellation), final document assembly. Based on Quill skill patterns and real client work (Soul Siren Somatics, freelance projects). (Origin: MemStack Pro v3.2, Mar 2026)
📐 Scope of Work: Defining project boundaries and deliverables...
Generates a formal Scope of Work document with objectives, deliverables, acceptance criteria, in/out scope definitions, work breakdown structure, milestones, and change request process.
Activation
When this skill activates, output:
📐 Scope of Work, Defining project scope and deliverables...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "scope of work" or "SOW" or "define scope" | ACTIVE |
| User says "write SOW" or "project scope" or "scope document" | ACTIVE |
| Defining formal project boundaries for a client engagement | ACTIVE |
| Writing internal task lists (no formal scope needed) | DORMANT: use Work skill |
| Writing a proposal (includes pricing/sales) | DORMANT: use proposal-writer |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "The scope is obvious from the proposal" | Proposals sell. SOWs define. Same project, different documents, different purpose. |
| "We don't need to list exclusions" | Every scope dispute starts with "I assumed it was included." List what's OUT explicitly. |
| "Acceptance criteria slow us down" | Acceptance criteria prevent "it's not what I wanted" after you've built it. They speed up delivery. |
| "We'll handle changes informally" | Informal changes create informal expectations. Formal change requests protect the timeline and budget. |
| "Dependencies don't matter yet" | Dependencies determine what blocks what. Discovering them mid-project causes delays. Map them upfront. |
Protocol
Step 1: Define Project Objectives
Establish what success looks like at the highest level:
## 1. Project Objectives
### Primary Objective
[One sentence: what this project delivers and why it matters]
Example: Build a multi-tenant SaaS dashboard that enables [Client]'s customers
to manage their accounts, view analytics, and configure integrations, replacing
the current manual process that requires 3 support staff.
### Success Criteria
| Criteria | Measurement | Target |
|----------|------------|--------|
| Core functionality | All deliverables pass acceptance criteria | 100% |
| Performance | Page load time under 3 seconds | p95 < 3s |
| Reliability | Uptime during business hours | 99.5% |
| User adoption | Active users within 30 days of launch | > 50% of target audience |
| Support reduction | Decrease in support tickets for covered workflows | > 40% reduction |
Success criteria must be **measurable**. "The client is happy" is not a success criterion.
"Support tickets decrease by 40%" is.
Rules:
- One primary objective, max 2 sentences
- 3-5 measurable success criteria with specific targets
- Criteria should be verifiable by both parties (no subjective measures)
Step 2: List Deliverables with Acceptance Criteria
Every deliverable needs a clear definition of "done":
## 2. Deliverables
### D1: User Authentication System
**Description:** Complete authentication flow including registration, login, password reset, and OAuth integration with Google.
**Acceptance criteria:**
- [ ] Users can register with email and password
- [ ] Users can log in with email/password and receive a session token
- [ ] Users can reset their password via email link
- [ ] Users can log in with Google OAuth
- [ ] Invalid credentials return appropriate error messages
- [ ] Session expires after 24 hours of inactivity
- [ ] All auth endpoints have rate limiting (5 attempts per 15 minutes)
**Depends on:** None (first deliverable)
**Estimated effort:** 20 hours
---
### D2: Admin Dashboard
**Description:** Administrative interface for managing users, viewing analytics, and configuring system settings.
**Acceptance criteria:**
- [ ] Dashboard loads within 3 seconds on standard broadband
- [ ] Displays active user count, revenue metrics, and system health
- [ ] User management: view, search, edit roles, deactivate accounts
- [ ] Data refreshes automatically every 60 seconds
- [ ] Responsive layout works on desktop (1024px+) and tablet (768px+)
- [ ] Role-based access: admin sees all, manager sees their org only
**Depends on:** D1 (Authentication)
**Estimated effort:** 32 hours
---
### D3: [Next Deliverable]
...
Acceptance criteria rules:
- Each criterion is a binary yes/no check: not subjective ("looks good")
- Include functional requirements (what it does)
- Include non-functional requirements (performance, responsiveness, accessibility)
- Include negative cases (error handling, invalid input)
- Number deliverables (D1, D2, D3) for easy reference in change requests
Step 3: Define In-Scope and Out-of-Scope
This section prevents scope disputes. Be exhaustive on exclusions:
## 3. Scope Definition
### In Scope
| Item | Details |
|------|---------|
| User authentication | Registration, login, password reset, Google OAuth |
| Admin dashboard | User management, analytics display, system settings |
| API development | RESTful endpoints for all dashboard operations |
| Database design | Schema, migrations, seed data, RLS policies |
| Deployment | Railway (backend) + Netlify (frontend), CI/CD pipeline |
| Testing | Unit tests for critical paths, integration tests for API |
| Documentation | API docs, deployment guide, user manual |
| Post-launch support | 30-day bug fix window (Standard tier) |
### Out of Scope
| Item | Rationale | If Needed Later |
|------|-----------|----------------|
| Mobile application | Not required for MVP; web app is responsive | Can be added via Change Request |
| Content creation | Client provides all copy, images, and branding | Content services available separately |
| Email marketing | No email campaigns or newsletter integration | Recommend Mailchimp integration post-launch |
| Payment processing | No billing or payment features in this phase | Phase 2 scope, separate SOW |
| Data migration | No import of existing data from legacy systems | Can be scoped as separate project |
| SEO optimization | Beyond basic meta tags and semantic HTML | SEO audit available as add-on |
| Accessibility audit | WCAG compliance testing by third party | Recommend post-launch audit |
| Browser support | IE11 or older browsers | Modern browsers only (Chrome, Firefox, Safari, Edge) |
| Load testing | Stress testing beyond normal usage patterns | Recommend before scaling |
### Assumptions
| # | Assumption | Impact if Wrong |
|---|-----------|----------------|
| A1 | Client provides branding assets (logo, colors, fonts) by kickoff | Delays Phase 2 by duration of delay |
| A2 | Client designates one decision-maker for feedback | Multiple reviewers slow approval cycles |
| A3 | Existing API documentation is accurate and current | Additional discovery time needed |
| A4 | Production hosting costs are paid by client directly | Hosting setup may differ |
| A5 | Feedback is provided within 2 business days of each review | Timeline shifts day-for-day |
Rules:
- Out-of-scope section must be at least as detailed as in-scope
- Every exclusion gets a rationale (why it's out) and a path back in (change request)
- List all assumptions that, if wrong, change the timeline or budget
- Number assumptions (A1, A2) for reference in change requests
Step 4: Create Work Breakdown Structure
Map tasks with dependencies:
## 4. Work Breakdown Structure
### Phase 1: Foundation (Week 1-2)
| Task | Deliverable | Depends On | Hours |
|------|------------|-----------|-------|
| 1.1 Project setup (repo, CI/CD, environments) | D1 | none | 6 |
| 1.2 Database schema design and migration | D1 | none | 8 |
| 1.3 Authentication: email/password flow | D1 | 1.1, 1.2 | 10 |
| 1.4 Authentication: Google OAuth | D1 | 1.3 | 6 |
| 1.5 Authentication: password reset | D1 | 1.3 | 4 |
| 1.6 Auth testing and hardening | D1 | 1.3, 1.4, 1.5 | 6 |
| **Phase 1 total** | | | **40** |
### Phase 2: Core Features (Week 3-5)
| Task | Deliverable | Depends On | Hours |
|------|------------|-----------|-------|
| 2.1 Dashboard layout and navigation | D2 | 1.3 | 8 |
| 2.2 User management CRUD | D2 | 2.1, 1.6 | 12 |
| 2.3 Analytics display components | D2 | 2.1 | 10 |
| 2.4 System settings interface | D2 | 2.1 | 8 |
| 2.5 Role-based access control | D2 | 2.2 | 8 |
| 2.6 Dashboard testing | D2 | 2.2, 2.3, 2.4, 2.5 | 10 |
| **Phase 2 total** | | | **56** |
### Phase 3: Polish & Launch (Week 6-7)
| Task | Deliverable | Depends On | Hours |
|------|------------|-----------|-------|
| 3.1 API documentation | D3 | 2.6 | 6 |
| 3.2 Deployment setup (production) | D3 | 2.6 | 8 |
| 3.3 User manual / guides | D3 | 2.6 | 6 |
| 3.4 Final QA and bug fixes | All | 3.1, 3.2, 3.3 | 12 |
| 3.5 Client UAT support | All | 3.4 | 4 |
| **Phase 3 total** | | | **36** |
**Total hours: 132** (+/- 15% contingency)
WBS rules:
- Every task maps to a deliverable (D1, D2, etc.)
- Dependencies are explicit, no hidden assumptions about ordering
- Tasks are small enough to estimate (max 12 hours per task)
- Include testing and documentation as explicit tasks, not afterthoughts
Step 5: Define Milestones
## 5. Milestones
| # | Milestone | Target Date | Go/No-Go Criteria | Deliverables |
|---|-----------|------------|-------------------|-------------|
| M1 | Kickoff | [Date] | Signed SOW, deposit received, access granted | none |
| M2 | Phase 1 Review | [Date + 2 wk] | All D1 acceptance criteria pass on staging | D1: Auth system |
| M3 | Phase 2 Review | [Date + 5 wk] | All D2 acceptance criteria pass on staging | D2: Dashboard |
| M4 | UAT Begin | [Date + 6.5 wk] | Client begins user acceptance testing | All deliverables on staging |
| M5 | Launch | [Date + 7.5 wk] | All acceptance criteria pass, client sign-off | Production deployment |
| M6 | Support Period End | [Date + 11.5 wk] | No critical bugs open | Support handoff |
### Go/No-Go Process
At each milestone review:
1. Vendor demonstrates completed deliverables against acceptance criteria
2. Client has **2 business days** to review and provide feedback
3. **Go:** Client confirms acceptance criteria are met → proceed to next phase
4. **No-Go:** Client provides specific items that fail acceptance criteria → vendor addresses within 3 business days → re-review
5. If no response within 2 business days, milestone is considered accepted
**Milestone acceptance is required before the next phase begins.** This protects both parties from building on unapproved work.
Step 6: Constraints and Dependencies
## 6. Constraints & Dependencies
### Constraints
| Constraint | Impact |
|-----------|--------|
| Budget ceiling of $XX,XXX | Scope adjustments if estimates exceed budget |
| Launch deadline of [date] | Feature prioritization required if timeline slips |
| Must integrate with [existing system] | API compatibility required, may limit tech choices |
| Data must remain in [region] | Hosting provider and database region restricted |
### External Dependencies
| Dependency | Owner | Required By | Risk if Delayed |
|-----------|-------|------------|----------------|
| Branding assets (logo, colors) | Client | M1 (Kickoff) | Delays Phase 2 UI work |
| API credentials for [service] | Client | Phase 2 start | Blocks integration tasks |
| DNS access for domain setup | Client | Phase 3 start | Blocks production deployment |
| Stakeholder availability for UAT | Client | M4 | Delays launch milestone |
| Code review approval | Vendor lead | Each phase end | Blocks milestone sign-off |
Step 7: Change Request Process
## 7. Change Management
### Change Request Process
Changes to scope, timeline, or budget follow this process:
1. **Request:** Either party submits a written change request describing:
- What changes (new feature, modified requirement, removed item)
- Why the change is needed
- Which deliverables are affected
2. **Impact Assessment:** Vendor provides within 3 business days:
- Hours impact (additional or reduced)
- Cost impact (additional or credit)
- Timeline impact (delay or no change)
- Risk assessment (what else might be affected)
3. **Approval:** Client reviews and provides written approval or rejection
- Approved changes update this SOW as an amendment
- Rejected changes are documented but not implemented
4. **Implementation:** Approved changes begin in the next phase or sprint
### Change Request Template
CHANGE REQUEST #[number] Date: YYYY-MM-DD Requested by: [Name]
Description: [What changes and why]
Affected deliverables: [D1, D2, etc.] Hours impact: [+/- N hours] Cost impact: [+/- $X,XXX] Timeline impact: [+/- N days/weeks]
Approved: [ ] Yes [ ] No Signature: _______________ Date: ___________
### Out-of-Process Changes
Work requested outside the change request process (verbal, chat, email without formal CR) is not included in this SOW and will not be implemented. This protects both parties from scope drift.
Step 8: Assemble Final Document
Output the complete SOW:
# Scope of Work: [Project Name]
| Field | Value |
|-------|-------|
| **Client** | [Client Name, Company] |
| **Vendor** | [Your Name / Company] |
| **Date** | YYYY-MM-DD |
| **Version** | 1.0 |
| **Valid until** | [Date + 30 days] |
---
## Table of Contents
1. Project Objectives
2. Deliverables
3. Scope Definition
4. Work Breakdown Structure
5. Milestones
6. Constraints & Dependencies
7. Change Management
---
[Section 1-7 content]
---
## Signatures
This Scope of Work is agreed to by both parties:
**Client:**
Name: ___________________________
Title: ___________________________
Signature: ___________________________
Date: ___________________________
**Vendor:**
Name: ___________________________
Title: ___________________________
Signature: ___________________________
Date: ___________________________
---
## Amendments
| # | Date | Description | Approved By |
|---|------|-------------|------------|
| none | none | Original SOW | none |
---
*This document, together with any approved amendments, constitutes the complete
agreement regarding the scope of work for this project.*
Output summary:
📐 Scope of Work: Complete
Project: [name]
Client: [client name]
Deliverables: [count] with [total] acceptance criteria
Phases: [count] across [weeks] weeks
Total hours: [count] (+/- 15%)
Milestones: [count] with go/no-go gates
Assumptions: [count]
Exclusions: [count] items explicitly out of scope
Document: [word count] words
Next steps:
1. Review with client, negotiate any changes
2. Both parties sign the document
3. File signed copy and begin kickoff preparations
4. Set up milestone calendar reminders
Level History
- Lv.1: Base: Project objectives with measurable success criteria, deliverables with acceptance criteria, explicit in/out scope, work breakdown structure with dependencies, milestones with go/no-go gates, constraints and external dependencies, formal change request process, signatures and amendments. (Origin: MemStack Pro v3.2, Mar 2026)
📋 SOP Builder: Documenting standard operating procedure...
Generates a structured Standard Operating Procedure with numbered steps, prerequisites, decision points, verification checkpoints, rollback steps, and time estimates.
Activation
When this skill activates, output:
📋 SOP Builder, Identifying process and building procedure...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "create SOP" or "write SOP" or "document process" | ACTIVE |
| User says "runbook" or "playbook" or "process documentation" | ACTIVE |
| Creating step-by-step instructions for a repeatable workflow | ACTIVE |
| Writing a one-time guide or tutorial | DORMANT |
| Discussing process improvement at a high level | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "The steps are obvious" | What's obvious to you is opaque to a new team member at 2 AM. Write every step. |
| "Just follow the README" | READMEs explain concepts. SOPs give exact actions in exact order. Different purpose. |
| "We'll remember the edge cases" | You won't. Decision points and rollback steps are the whole point of an SOP. |
| "This process never changes" | Every process changes. Version numbers and last-updated dates prevent stale docs from causing outages. |
| "Anyone can figure out if it worked" | Explicit verification checkpoints ("you should see X") catch failures before they cascade. |
Protocol
Step 1: Identify the Process
If the user hasn't specified the process, ask:
What process should this SOP document? For example:
- Deploying to production
- Onboarding a new developer
- Handling a customer bug report
- Running a database migration
- Publishing a release
- Setting up a new project
Then gather:
- Process name: clear, specific title
- Audience: who will follow this SOP? (developer, ops, new hire, non-technical)
- Trigger: what event kicks off this process? (PR merged, customer request, scheduled)
- Frequency: how often is this run? (daily, weekly, per release, ad-hoc)
- Critical?: does failure cause downtime, data loss, or revenue impact?
Step 2: Define Prerequisites
List everything needed before starting:
## Prerequisites
### Required Access
| System | Access Level | How to Request |
|--------|-------------|---------------|
| GitHub | Write access to repo | Ask team lead in #dev-access |
| Railway | Deploy permissions | Railway dashboard → Team → Invite |
| Supabase | Database admin | Supabase dashboard → Settings → Team |
| AWS S3 | Read/write to production bucket | IT ticket #aws-access |
### Required Tools
| Tool | Version | Install Command |
|------|---------|----------------|
| Node.js | 20+ | `nvm install 20` |
| Railway CLI | Latest | `npm install -g @railway/cli` |
| Git | 2.40+ | Pre-installed on most systems |
### Required Knowledge
- Familiarity with [relevant concept]
- Completed [training/onboarding step]
- Access to [documentation/wiki link]
### Before You Begin
- [ ] Verify you have all required access (test each login)
- [ ] Pull latest code from main branch
- [ ] Notify team in [channel] that you're starting this process
- [ ] Block [estimated time] on your calendar
Rules:
- Every tool, login, and permission is listed: no assumptions
- Include "how to get access" for each system (not just "you need access")
- Include a pre-flight checklist the operator runs before step 1
Step 3: Write Numbered Steps
Each step follows a strict format:
## Procedure
### Step 1: [Action verb] [specific thing]
**Time estimate:** ~5 minutes
**Can fail:** Yes
**Action:**
1. Navigate to [specific location]
2. Run the following command:
```bash
npm run build
- Wait for the build to complete (typically 1-3 minutes)
Verification:
- Build output shows "Build successful" with zero errors
-
dist/directory contains updated files - File count is similar to previous build (sanity check)
If it fails:
- Build error with dependency issue → Run
npm ciand retry - Build error with TypeScript type error → Fix the type error, commit, and restart from Step 1
- Build times out (> 10 minutes) → Check for infinite loops in recent changes
**Step writing rules:**
- Start every step title with an **action verb** (Run, Open, Navigate, Verify, Configure)
- No vague steps ("set up the environment"), every action is copy-pasteable or clickable
- Include the **exact command**, **exact URL**, or **exact menu path**
- Mark whether each step **can fail**: if yes, it needs verification and failure handling
- Time estimates help the operator know if something is taking too long
### Step 4: Add Decision Points
For steps with branching logic, use clear if/then formatting:
```markdown
### Step 4: Check migration status
**Time estimate:** ~2 minutes
**Can fail:** Yes
**Action:**
1. Run: `supabase migration list`
2. Review the output
**Decision point:**
| Situation | Action |
|-----------|--------|
| All migrations show `applied` | Continue to Step 5 |
| One migration shows `pending` | Run `supabase db push` then re-check |
| Migration shows `failed` | Stop. Go to Rollback Procedure below |
| Connection refused error | Verify VPN is connected, retry in 30 seconds |
| Unknown error | Screenshot the error, post in #dev-help, wait for response |
**Do NOT continue to Step 5 until all migrations show `applied`.**
Decision point rules:
- Every
can fail: Yesstep gets a decision table - Cover the 3-5 most common failure modes (not just happy path)
- Include "unknown error" row, operators need to know what to do when nothing matches
- Use bold warnings for steps where continuing on failure causes cascading damage
Step 5: Add Verification Checkpoints
Major milestones get dedicated verification steps:
### Checkpoint A: Pre-deployment verification
**Time estimate:** ~3 minutes
Before proceeding to deployment, verify ALL of the following:
| Check | How to Verify | Expected Result |
|-------|--------------|-----------------|
| Build passes | `npm run build` exits cleanly | Exit code 0, no errors |
| Tests pass | `npm test` exits cleanly | All tests green |
| Env vars set | Railway dashboard → Variables | All vars from .env.example present |
| Database ready | `supabase status` | Database is running, migrations applied |
| Branch is clean | `git status` | No uncommitted changes |
**All checks must pass.** If any check fails, resolve it before continuing.
Do not skip checks "because it worked last time."
Checkpoint rules:
- Place checkpoints before irreversible actions (deployment, data migration, public release)
- Every check has a specific command or action to run and an expected result
- Emphasize that ALL checks must pass: no skipping
Step 6: Include Rollback Steps
For any step that modifies state (deployment, data changes, config updates):
## Rollback Procedure
Use this procedure if deployment fails or causes issues in production.
### Rollback Step 1: Revert deployment
**Time estimate:** ~2 minutes
1. Open Railway dashboard → Deployments
2. Find the last successful deployment (green checkmark)
3. Click the three-dot menu → "Rollback to this deploy"
4. Wait for rollback to complete (typically 30-60 seconds)
**Verification:**
- [ ] Railway shows the previous deployment as active
- [ ] Health check endpoint returns 200: `curl https://[app].up.railway.app/health`
- [ ] Users can access the application
### Rollback Step 2: Revert database migration (if applicable)
**Time estimate:** ~5 minutes
1. Run the rollback migration:
```bash
supabase db execute --file supabase/migrations/[number]_rollback.sql
- Verify the schema matches the previous state
WARNING: Database rollbacks may cause data loss if the forward migration added columns that received data. Assess the risk before proceeding.
Rollback Step 3: Notify team
- Post in #incidents: "Rolled back [deployment name]. Investigating [brief issue]."
- Update status page if customer-facing
- Create incident ticket for post-mortem
**Rollback rules:**
- Every deployment/migration step needs a corresponding rollback
- Rollback steps are just as detailed as forward steps
- Include data loss warnings where applicable
- Always end rollback with team notification
### Step 7: Add Time Estimates
Summarize the total time at the top of the document:
```markdown
## Time Summary
| Phase | Estimated Time |
|-------|---------------|
| Prerequisites check | 5 minutes |
| Steps 1-3 (preparation) | 15 minutes |
| Steps 4-6 (execution) | 20 minutes |
| Steps 7-8 (verification) | 10 minutes |
| **Total (happy path)** | **~50 minutes** |
| **Total (with 1 failure + rollback)** | **~75 minutes** |
**Schedule buffer:** Block 1.5x the happy path time on your calendar.
Time estimate rules:
- Include happy path total AND failure path total
- Recommend 1.5x calendar buffer
- Individual step estimates help operators identify if a step is taking too long
Step 8: Assemble Final Document
Output the complete SOP:
# SOP: [Process Name]
| Field | Value |
|-------|-------|
| **Version** | 1.0 |
| **Last updated** | YYYY-MM-DD |
| **Author** | [Name] |
| **Audience** | [Who follows this SOP] |
| **Trigger** | [When to run this process] |
| **Frequency** | [How often] |
| **Estimated time** | [Happy path total] |
| **Critical** | [Yes/No: does failure cause downtime?] |
---
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Procedure](#procedure)
- Step 1: [title]
- Step 2: [title]
- ...
- Checkpoint A: [title]
- Step N: [title]
3. [Rollback Procedure](#rollback-procedure)
4. [Time Summary](#time-summary)
5. [Change Log](#change-log)
---
[Prerequisites section]
[Procedure section with steps, decision points, checkpoints]
[Rollback Procedure section]
[Time Summary section]
---
## Change Log
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | YYYY-MM-DD | [Name] | Initial version |
Output summary:
📋 SOP Builder: Complete
Process: [name]
Audience: [who]
Steps: [count] steps, [count] decision points, [count] checkpoints
Rollback: [count] rollback steps
Estimated time: [happy path] / [with failure]
Document: [word count] words
Next steps:
1. Review steps with someone who runs this process
2. Do a dry run following the SOP exactly
3. Store in team wiki/docs and link from relevant README
4. Schedule quarterly review to keep it current
Level History
- Lv.1: Base: Process identification, prerequisites with access/tools, numbered steps with action verbs, decision point tables, verification checkpoints, rollback procedures, time estimates, versioned final document with change log. (Origin: MemStack Pro v3.2, Mar 2026)
Compress - TokenStack Proxy Manager
Monitor and troubleshoot the built-in TokenStack compression proxy for CC sessions.
Activation
When this skill activates, output:
Compress - Checking TokenStack status...
Then execute the protocol below.
- Keywords: tokenstack, compression stats, token savings, proxy status, check proxy
- Contextual: When user asks about token usage, context window limits, or session cost
- Level: 2 (explicit trigger only)
Context Guard
| Context | Status |
|---|---|
| User says "tokenstack", "compression stats", "check proxy" | ACTIVE - run status check |
| User asks about token savings or context window | ACTIVE - point to dashboard report |
| Proxy errors or API connection failures appear | ACTIVE - run health diagnostics |
| General discussion about CC features | DORMANT - do not activate |
| User is actively coding (no proxy issues) | DORMANT - do not activate |
What It Does
TokenStack is a transparent proxy between Claude Code and the Anthropic API. It compresses tool output before it reaches the API, extending effective context and lowering token cost.
This skill checks that the proxy is running and routing, and troubleshoots connection issues. For the full feature overview, enable steps, and transform tables, use the Token Optimization skill.
Prerequisites
TokenStack ships inside the memstack-skill-loader package. There is no separate install.
- Start with the dashboard (recommended):
python -m memstack_skill_loader dashboard --with-proxy- Starts the proxy on
127.0.0.1:8787and setsANTHROPIC_BASE_URLautomatically.
- Starts the proxy on
- Run only the proxy:
python -m memstack_skill_loader proxy
Workflow
1. Health Check
curl http://127.0.0.1:8787/health
A healthy proxy responds on /health. If there is no response, the proxy is not running.
Note: the proxy has no /stats endpoint. Live savings are reported in the dashboard, not over curl. See "Reading Savings" below.
2. Confirm Routing
Open the dashboard and look at the proxy indicator. A live PRO or FREE badge means Claude Code traffic is routing through TokenStack. If the badge reads "not detected," the dashboard was started without --with-proxy; restart it with the flag.
3. Diagnose "not running"
Check the port:
netstat -ano | findstr 8787
If nothing is listening, start it:
python -m memstack_skill_loader dashboard --with-proxy
4. Reading Savings
Savings live in the dashboard (default http://localhost:3333):
- Proxy indicator: PRO or FREE badge with session and 30-day percentages
- Overview header: session and lifetime tokens saved
- Burn Report: per-transform breakdown, estimated cost, time filters (all-time, daily, weekly, monthly), and a per-agent split for the Manager, Builder, and Reviewer
Tier Behavior
| Tier | Transforms |
|---|---|
| Free | Six lossless text reductions, always applied |
| Pro | Adds seven transforms including AST truncation (license-gated) |
A valid Pro license switches the proxy to Pro tier automatically. The dashboard badge shows the active tier.
Troubleshooting
| Symptom | Fix |
|---|---|
No response on /health | Proxy not running. Start with python -m memstack_skill_loader dashboard --with-proxy. |
| Proxy indicator shows "not detected" | Dashboard was started without --with-proxy. Restart with the flag. |
| Badge shows FREE but you hold Pro | License cache may be stale. The proxy revalidates the license on next start. |
| Cost figures differ from Anthropic Console | Estimates use list token prices and do not model server-side prompt caching. For billed cost, check console.anthropic.com. |
Output Format
TokenStack Status
Proxy: Running on :8787
Tier: PRO
Savings: read in the dashboard (Overview header and Burn Report)
Integration
- Dashboard: proxy indicator, Overview header, and Burn Report
- CC sessions: auto-routed when the dashboard is started with
--with-proxy - Standalone proxy:
python -m memstack_skill_loader proxy
Relationship to Other Skills
| Skill | Scope | When to Use |
|---|---|---|
| Token Optimization | Full TokenStack overview, enable steps, transform tables | Understanding or turning on compression |
| Compress (this) | Health, routing, troubleshooting | Proxy not running or not routing |
Level History
- Lv.1 - Base: health check and stats reporting for the legacy Headroom proxy. (Origin: MemStack, Feb 2026)
- Lv.2 - Rewrite: retargeted to the built-in TokenStack proxy. Removed the external Headroom install and the
/statscurl; savings are now read from the dashboard. (Jun 2026)
✍️ Blog Post: Writing SEO-optimized blog post...
Produces a complete, publish-ready blog post with SEO metadata, structured sections, readability optimization, and internal linking suggestions.
Activation
When this skill activates, output:
✍️ Blog Post, Gathering topic and audience details...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "write blog post" or "blog post about" | ACTIVE |
| User says "write article" or "create blog" or "write post" | ACTIVE |
| Creating long-form content for a website or publication | ACTIVE |
| Writing landing page copy (short-form, conversion-focused) | DORMANT: use landing-page-copy |
| Writing email content | DORMANT: use email-sequence |
| Writing social media posts | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Write about everything related to the topic" | Focus on one angle. Broad posts rank for nothing. Narrow posts rank for one keyword. |
| "The intro should provide context" | The intro should hook. Context bores. Open with a bold claim, stat, or question. |
| "Longer is better for SEO" | Comprehensive beats long. 1,500 focused words outrank 3,000 padded words. |
| "Stuff the keyword everywhere" | Use the keyword naturally 3-5 times. Search engines penalize stuffing. Readers hate it. |
| "Anyone who finds it will read it" | You have 3 seconds. If the title and intro don't hook them, the rest doesn't matter. |
Protocol
Step 1: Gather Topic Details
If the user hasn't provided details, ask:
I need a few details for the blog post:
- Topic: what's this post about?
- Target audience: who are you writing for? (developers, business owners, beginners, etc.)
- Target keyword: what search term should this rank for?
- Tone: casual/conversational, professional, technical, inspirational?
- Desired length: short (800 words), standard (1,200-1,500), long-form (2,000+)?
If the user provides partial info, infer what you can and ask only for what's missing.
Step 2: Research and Outline
Before writing, build a structured outline:
- Identify 3-5 key points the post must cover
- Find supporting data: statistics, examples, or case studies that strengthen each point
- Note counterarguments: addressing objections builds credibility
- Determine the unique angle: what perspective makes this post different from the top 10 results?
Outline template:
## Outline
**Angle:** [What makes this post different]
**Target keyword:** [primary keyword]
**Secondary keywords:** [2-3 related terms]
1. Hook intro, [opening strategy: bold claim / stat / question / story]
2. [Section H2]: [key point + supporting evidence]
3. [Section H2]: [key point + supporting evidence]
4. [Section H2]: [key point + supporting evidence]
5. [Section H2]: [key point + counterargument addressed]
6. Actionable takeaways, [summary of what to do next]
7. CTA conclusion, [what you want the reader to do]
Present the outline for user approval before writing the full post.
Step 3: Write SEO Metadata
**Title:** [60 characters max: include target keyword, power word, specific benefit]
**Meta description:** [155 characters max: summarize the value, include keyword, end with implicit CTA]
**URL slug:** [target-keyword-in-slug: lowercase, hyphens, no filler words]
Title formula options:
- Number + Adjective + Keyword + Promise: "7 Proven Ways to [Keyword] Without [Pain Point]"
- How to + Keyword + Benefit: "How to [Keyword]: A Step-by-Step Guide for [Audience]"
- Question format: "Why Does [Keyword] Matter? [Provocative Answer]"
- Contrarian: "[Common Belief] Is Wrong. Here's What [Keyword] Actually Means"
Title rules:
- Include target keyword within the first 40 characters
- Use a power word (proven, essential, complete, ultimate, simple)
- Promise a specific outcome (not vague "improve")
- Max 60 characters to avoid Google truncation
Meta description rules:
- Include target keyword naturally
- Summarize the unique value of this post
- Create curiosity or promise a benefit
- Max 155 characters to avoid truncation
Step 4: Write the Post
Intro (100-150 words)
The intro must accomplish three things in three paragraphs (or fewer):
- Hook: bold claim, surprising stat, relatable pain point, or provocative question
- Relevance: why this matters to the reader right now
- Promise: what they'll know or be able to do after reading
[Hook sentence, bold claim or surprising stat]
[1-2 sentences connecting to reader's situation]
[Promise: "In this post, you'll learn..." or "Here's exactly how to..."]
Do NOT:
- Start with "In today's fast-paced world..." or any throat-clearing
- Define the obvious ("What is marketing?")
- Summarize the entire post upfront (that's what the outline is for)
Body Sections (3-5 H2 sections)
Each section follows this structure:
## [H2: Keyword-rich, benefit-oriented heading]
[Opening sentence that states the section's key point]
[Supporting evidence: stat, example, case study, or expert quote]
[Practical explanation, how this applies to the reader]
[Specific example or actionable step]
> [Optional: pull quote or callout box with key insight]
[Transition sentence leading to the next section]
Body writing rules:
- Paragraphs: max 3-4 sentences each (walls of text kill readability)
- Sentences: vary length, mix short punchy sentences with longer explanatory ones
- Use H3 subheadings to break up sections longer than 300 words
- Include the target keyword in at least 2 H2 headings (naturally, not forced)
- Use bullet points or numbered lists for any set of 3+ items
- Bold key phrases for scanners (most readers scan before deciding to read)
Readability Targets
| Metric | Target | Why |
|---|---|---|
| Flesch-Kincaid Grade | 8 or below | Accessible to 80% of readers |
| Sentence length | Average 15-20 words | Longer sentences lose readers |
| Paragraph length | Max 3-4 sentences | Short paragraphs feel faster |
| Passive voice | Below 10% | Active voice is direct and clear |
| Adverb usage | Minimal | "Ran quickly" loses to "sprinted" |
| Jargon | Define or avoid | Unless audience is technical |
Step 5: Write Conclusion and CTA
## [Takeaway heading: not "Conclusion"]
[Summarize the 3 most important points in 2-3 sentences]
[Restate the benefit: what the reader can now do]
**[CTA, what you want them to do next:]**
- Subscribe/newsletter: "Get [topic] tips weekly: subscribe below"
- Product: "Try [product] free: [link]"
- Share: "Found this useful? Share it with your team"
- Next post: "Read next: [related post title]"
- Comment: "What's your experience with [topic]? Drop a comment"
Step 6: Add Internal Linking Suggestions
## Internal Linking Opportunities
| Anchor Text | Link To | Location in Post |
|-------------|---------|-----------------|
| "[related concept]" | /blog/[related-post-slug] | Section 2, paragraph 3 |
| "[tool or feature mentioned]" | /features/[feature-page] | Section 4, paragraph 1 |
| "[previous post reference]" | /blog/[previous-post-slug] | Conclusion |
**External links (for credibility):**
| Anchor Text | Link To | Rationale |
|-------------|---------|-----------|
| "[stat source]" | [authoritative source URL] | Backs up claim in Section 1 |
| "[expert quote source]" | [source URL] | Attribution |
Linking rules:
- 2-4 internal links per 1,000 words (to existing site content)
- 1-2 external links to authoritative sources (studies, reports, official docs)
- Anchor text should be descriptive, not "click here"
- Open external links in new tab
Step 7: Add Image Suggestions
## Image Placements
| Position | Image Concept | Alt Text | Purpose |
|----------|--------------|----------|---------|
| After intro | [Relevant hero image or infographic] | "[Descriptive alt text with keyword]" | Visual hook |
| Section 2 | [Screenshot, diagram, or example] | "[Descriptive alt text]" | Illustrate concept |
| Section 4 | [Chart, comparison, or data visualization] | "[Descriptive alt text]" | Support data point |
| Before CTA | [Product shot or action image] | "[Descriptive alt text]" | Reinforce CTA |
Image rules:
- Alt text is descriptive (for accessibility), not keyword-stuffed
- Include target keyword in hero image alt text (once, naturally)
- Suggest image type (photo, screenshot, infographic, chart) not specific images
- One image per 300-500 words keeps readers engaged
Step 8: Assemble and Output
Output the complete blog post in clean markdown:
---
title: "[SEO title]"
description: "[Meta description]"
date: YYYY-MM-DD
author: "[Author]"
tags: ["keyword1", "keyword2", "keyword3"]
image: "/blog/[slug]/hero.jpg"
---
# [Post Title]
[Full post content with H2 sections, formatting, links]
Output summary:
✍️ Blog Post: Complete
Title: [title] ([character count] chars)
Meta description: [description] ([character count] chars)
Target keyword: [keyword]
Word count: [count]
Sections: [count] H2s, [count] H3s
Reading time: ~[count] minutes
Readability: Flesch-Kincaid Grade [score]
SEO checklist:
✅ Keyword in title (first 40 chars)
✅ Keyword in meta description
✅ Keyword in 2+ H2 headings
✅ Keyword in first 100 words
✅ Internal links: [count]
✅ External links: [count]
✅ Image alt text with keyword: [count]
Next steps:
1. Review and add personal voice/anecdotes
2. Source or create images for suggested placements
3. Add internal links to existing content
4. Publish and submit to Google Search Console
Level History
- Lv.1: Base: Topic gathering, research/outline, SEO metadata (title 60 chars, meta 155 chars), structured sections with H2s, readability targets (Flesch-Kincaid grade 8), internal/external linking, image suggestions with alt text, publish-ready markdown output. (Origin: MemStack Pro v3.2, Mar 2026)
📧 Email Sequence: Writing automated email campaign...
Produces a complete multi-email sequence with subject lines, preview text, body copy, CTAs, and A/B test suggestions, ready to load into any email platform.
Activation
When this skill activates, output:
📧 Email Sequence: Designing email campaign structure...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "write email sequence" or "email series" or "drip campaign" | ACTIVE |
| User says "nurture sequence" or "onboarding emails" or "launch emails" | ACTIVE |
| Creating a multi-email automated campaign | ACTIVE |
| Writing a single one-off email | DORMANT, just write the email directly |
| Writing newsletter content | DORMANT |
| Writing email for support or personal communication | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Pitch in the first email" | Email 1 is for trust, not selling. Premature pitching gets unsubscribes, not conversions. |
| "More emails = more sales" | Frequency breeds fatigue. 5 focused emails beat 12 filler emails. Quality per email matters more than quantity. |
| "Long subject lines explain more" | Subject lines are read on mobile. After 50 characters, they're truncated. Short + curious wins. |
| "The body copy needs to be short" | Length doesn't kill: boring does. A 500-word email that's engaging outperforms a 100-word email that's bland. |
| "Everyone gets the same sequence" | Segmentation doubles conversion. At minimum, separate new subscribers from existing customers. |
Protocol
Step 1: Gather Campaign Details
If the user hasn't provided details, ask:
I need a few details for the email sequence:
- Product/service: what are you promoting or onboarding for?
- Target audience: who receives these emails? (new signups, leads, customers, etc.)
- Sequence goal: what's the purpose?
- Nurture (build trust over time)
- Launch (build anticipation, sell on launch day)
- Onboarding (activate new users)
- Re-engagement (win back inactive users)
- Entry trigger: what puts someone into this sequence? (signup, purchase, abandoned cart, etc.)
- Existing relationship: do they already know you, or is this first contact?
Step 2: Design Sequence Structure
Plan the sequence length and cadence based on the goal:
| Goal | Emails | Cadence | Arc |
|---|---|---|---|
| Nurture | 5-7 | Every 2-3 days | Welcome → Story → Value → Value → Soft pitch → Hard pitch → Last chance |
| Launch | 4-6 | Daily during launch week | Announcement → Behind-the-scenes → Early access → Launch day → Reminder → Last chance |
| Onboarding | 3-5 | Day 0, 1, 3, 7, 14 | Welcome → Quick win → Key feature → Advanced tip → Check-in |
| Re-engagement | 3-4 | Every 3-5 days | Miss you → What's new → Special offer → Goodbye (unsubscribe) |
Sequence map:
Email 1 (Day 0) → [Welcome/Hook]: Set expectations, deliver value
↓ 2 days
Email 2 (Day 2) → [Story/Credibility]: Build trust, share journey
↓ 2 days
Email 3 (Day 4) → [Value/Teaching]: Prove expertise, give actionable tip
↓ 3 days
Email 4 (Day 7) → [Soft Pitch]: Introduce offer naturally
↓ 3 days
Email 5 (Day 10) → [Hard Pitch]: Urgency, scarcity, direct CTA
Present the sequence map for user approval before writing emails.
Step 3: Write Email 1: Welcome / Hook
The first email sets the tone for the entire relationship:
## Email 1: Welcome / Hook
**Send:** Immediately upon trigger (Day 0)
**Goal:** Set expectations, deliver promised value, make a first impression
**Tone:** Warm, personal, not salesy
---
**Subject line:** [50 chars max, deliver on signup promise]
**Preview text:** [90 chars max, extends subject line, visible in inbox]
---
Hey [First Name],
[Opening: Thank them for signing up / downloading / purchasing.
Be specific about what they signed up for.]
[Deliver the promised value immediately, if they signed up for a
guide, link it here. If they signed up for a tool, show them the
first step. Never make them wait for what was promised.]
Here's what to expect from me:
- [Frequency]: You'll hear from me [every X days / weekly / etc.]
- [Content type]: I'll share [tips, strategies, behind-the-scenes, etc.]
- [Value promise]: Every email will [teach you something / save you time / etc.]
[One quick win: give them something actionable they can do right now,
in under 5 minutes, that gets a result.]
Talk soon,
[Name]
P.S. [Curiosity hook for Email 2: "Tomorrow, I'll share the story of
how [interesting teaser]..."]
---
**CTA:** [Deliver the lead magnet / Start using the product / Reply to say hello]
Email 1 rules:
- Deliver what was promised (lead magnet, access, resource) immediately
- Set expectations for frequency and content type
- Include one quick win (builds trust through immediate value)
- P.S. line teases Email 2 (creates anticipation)
- No selling, this email is about trust
Step 4: Write Email 2: Story / Credibility
## Email 2: Story / Credibility
**Send:** Day 2
**Goal:** Build personal connection, establish credibility through narrative
**Tone:** Conversational, vulnerable, relatable
---
**Subject line:** [50 chars max, hint at a story or revelation]
**Preview text:** [90 chars max]
---
Hey [First Name],
[Opening: Bridge from Email 1: "Yesterday I shared [X].
Today I want to tell you why I built this / started this / care about this."]
[Story: Share your origin story, a failure that led to insight,
or a customer's transformation story. Structure:]
1. **Situation**: where you/they were before (relatable pain)
2. **Turning point**: what changed (discovery, decision, realization)
3. **Result**: where you/they are now (credibility proof)
[Connect the story to the reader's situation, "I share this because
you're probably in a similar spot. You're dealing with [their pain],
and I know what that feels like."]
[Transition to expertise, "That experience taught me [lesson], and
it's exactly why [product/approach] works the way it does."]
[Name]
P.S. [Tease Email 3: "In my next email, I'll share the exact
[strategy/framework/technique] that made the biggest difference..."]
---
**CTA:** [Soft, reply to share their story / follow on social / read a blog post]
Step 5: Write Email 3: Value / Teaching
## Email 3: Value / Teaching
**Send:** Day 4
**Goal:** Demonstrate expertise by teaching something immediately useful
**Tone:** Expert, generous, practical
---
**Subject line:** [50 chars max, promise a specific takeaway]
**Preview text:** [90 chars max]
---
Hey [First Name],
[Opening: Jump straight into the value: no lengthy preamble.]
Here's [the framework / the technique / the strategy] I promised:
**[Name the framework or technique]**
[Step-by-step breakdown, teach them something they can implement today:]
**Step 1: [Action]**
[1-2 sentences explaining how and why]
**Step 2: [Action]**
[1-2 sentences explaining how and why]
**Step 3: [Action]**
[1-2 sentences explaining how and why]
[Show the result: "When you do this, you'll see [specific outcome].
[Customer name] used this exact approach and [result with numbers]."]
[Bridge to product (subtle): "This is actually one of the core ideas
behind [product], we built [feature] specifically to make Step 2
automatic."]
[Name]
P.S. [Tease Email 4: "I have something special coming in a few days.
Stay tuned."]
---
**CTA:** [Try the technique / Read the full guide / Watch the tutorial]
Email 3 rules:
- Teach something genuinely useful, not a watered-down teaser
- Include specific steps, not abstract advice
- One subtle bridge to the product (not a pitch: a connection)
- This email should work as standalone content even without the sequence
Step 6: Write Email 4: Soft Pitch
## Email 4: Soft Pitch
**Send:** Day 7
**Goal:** Introduce the offer naturally, without pressure
**Tone:** Helpful, confident, low-pressure
---
**Subject line:** [50 chars max, curiosity or question format]
**Preview text:** [90 chars max]
---
Hey [First Name],
[Opening: Reference the value from Email 3, "Last week I shared
[technique]. Did you try it?"]
[Transition: "A lot of people who try [technique] hit a wall at
[common obstacle]. That's actually why I built [product]."]
Here's what [product] does differently:
- **[Benefit 1]**: [how it solves the obstacle from the teaching email]
- **[Benefit 2]**: [additional value they haven't heard yet]
- **[Benefit 3]**: [outcome with social proof: "[Customer] saw [result]"]
[Soft CTA: "If you're curious, you can [try it free / see it in action /
check out the details] here: [link]"]
[No-pressure close: "No rush, I just wanted you to know it exists.
Either way, I'll keep sharing [value type] with you."]
[Name]
P.S. [Social proof: "[Number] people are already using [product] to
[outcome]. Here's what [Name] said: '[short testimonial]'"]
---
**CTA:** [Check it out / Try free / See pricing: but positioned as optional]
Step 7: Write Email 5: Hard Pitch
## Email 5: Hard Pitch
**Send:** Day 10
**Goal:** Close the sale with urgency and a direct ask
**Tone:** Direct, confident, urgent (but not desperate)
---
**Subject line:** [50 chars max, urgency or FOMO element]
**Preview text:** [90 chars max]
---
Hey [First Name],
[Opening: Direct and honest, "I'll keep this short."]
Over the past [timeframe], I've shared:
- [Email 1 value recap: one line]
- [Email 2 story/lesson recap: one line]
- [Email 3 technique recap: one line]
[Product] is [one-sentence value proposition].
**Here's what you get:**
- [Key benefit 1]
- [Key benefit 2]
- [Key benefit 3]
- [Bonus or guarantee]
[Urgency element: must be genuine:]
- Price increase: "This price goes up to $XX on [date]"
- Limited availability: "Only [X] spots left at this rate"
- Bonus expiration: "The [bonus] is only available until [date]"
- Time-limited offer: "This link expires in 48 hours"
**[CTA button text]: [Link]**
[Risk reversal: "30-day money-back guarantee. If it's not for you,
email me and I'll refund you: no questions asked."]
[Name]
P.S. [Final nudge: "If you've been on the fence, this is the best
time. [Urgency element]. [Link]"]
---
**CTA:** [Buy now / Start now / Claim your spot: direct, urgent, single action]
Email 5 rules:
- Be direct, the reader has been warmed up over 4 emails
- Recap the value they've received (reciprocity principle)
- Urgency must be genuine, fake scarcity destroys trust permanently
- Include risk reversal (guarantee, free trial, cancel anytime)
- One clear CTA, don't offer alternatives here
Step 8: Write Subject Line Variants
For each email, provide A/B test options:
## A/B Test Suggestions
### Email 1: Welcome
- A: "[Lead magnet name]: your download is inside"
- B: "Welcome! Here's your [promise] + a quick win"
### Email 2: Story
- A: "I almost quit [thing], here's what saved me"
- B: "The mistake that changed everything"
### Email 3: Value
- A: "The [framework] that [specific result]"
- B: "[Number] steps to [outcome] (takes 10 min)"
### Email 4: Soft pitch
- A: "Quick question about [their pain point]"
- B: "This might help with [obstacle]"
### Email 5: Hard pitch
- A: "Last chance: [offer] ends [date]"
- B: "[First Name], I made you something"
A/B testing rules:
- Test ONE variable at a time (subject line OR send time, not both)
- Need 1,000+ recipients per variant for statistical significance
- Wait 24-48 hours before declaring a winner
- Winners become the control for the next test
Step 9: Output Complete Sequence
# Email Sequence: [Campaign Name]
**Product:** [name]
**Audience:** [segment]
**Goal:** [nurture / launch / onboarding / re-engagement]
**Entry trigger:** [what puts them in this sequence]
**Cadence:** [X] emails over [Y] days
---
[Email 1, complete]
[Email 2, complete]
[Email 3, complete]
[Email 4: complete]
[Email 5: complete]
---
## A/B Test Plan
[Subject line variants per email]
## Platform Setup Notes
- **SendGrid:** Create automation, set delays between emails
- **ConvertKit:** Create sequence, add emails with wait steps
- **Mailchimp:** Create customer journey, add email actions
- Tag subscribers who complete the sequence for next campaign
Output summary:
📧 Email Sequence: Complete
Campaign: [name]
Emails: [count] over [days] days
Goal: [type]
Trigger: [event]
Per-email summary:
1. Welcome (Day 0): [subject line]
2. Story (Day 2): [subject line]
3. Value (Day 4): [subject line]
4. Soft pitch (Day 7): [subject line]
5. Hard pitch (Day 10): [subject line]
A/B variants: [count] subject line alternatives
Total word count: ~[count] words
Next steps:
1. Customize with brand voice and personal anecdotes
2. Add real customer testimonials to Emails 4-5
3. Set up in your email platform with proper delays
4. Test all links before activating
5. Monitor open rates and click rates for first 2 weeks
Level History
- Lv.1: Base: Campaign planning (goal, cadence, arc), 5-email structure (welcome, story, value, soft pitch, hard pitch), subject lines (50 chars), preview text, P.S. lines, A/B test suggestions, platform setup notes, complete sequence output. (Origin: MemStack Pro v3.2, Mar 2026)
🎯 Landing Page Copy: Writing conversion-optimized page copy...
Produces structured landing page copy blocks (hero, problem, solution, features, social proof, FAQ, CTA) ready to drop into any template or design.
Activation
When this skill activates, output:
🎯 Landing Page Copy, Gathering product and audience details...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "write landing page" or "landing page copy" | ACTIVE |
| User says "sales page" or "hero section" or "conversion copy" | ACTIVE |
| Creating copy for a product, service, or signup page | ACTIVE |
| Writing blog content (long-form, educational) | DORMANT: use blog-post |
| Writing email copy | DORMANT: use email-sequence |
| Designing the page layout (not writing copy) | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Describe all the features" | Features tell. Benefits sell. Lead with what the customer gets, not what the product does. |
| "Make the headline clever" | Clever headlines confuse. Clear headlines convert. Clarity beats creativity every time. |
| "Everyone is our audience" | Speaking to everyone means connecting with no one. Pick one persona and write to them. |
| "Long copy won't be read" | Long copy outperforms short copy when every sentence earns the next. Cut filler, not length. |
| "We don't need social proof yet" | No testimonials? Use stats, logos, case study snippets, or "built by" credibility. Something is always better than nothing. |
Protocol
Step 1: Gather Product Details
If the user hasn't provided details, ask:
I need a few details for the landing page:
- Product/service name: what are we selling?
- Target audience: who is the ideal customer? (role, pain point, situation)
- Key benefit: what's the #1 thing they get? (in their words, not yours)
- Price point: free, freemium, one-time, subscription? (affects urgency strategy)
- CTA goal: what's the primary action? (sign up, buy, book a call, download)
- Existing copy or brand voice: any tone/style to match?
Step 2: Write Hero Section
The hero section determines whether visitors stay or leave. Every word earns its place.
## Hero Section
### Headline (10 words max)
[Clear statement of the primary benefit: what they get]
### Subheadline (20 words max)
[Specificity: who it's for, how it works, what makes it different]
### Primary CTA Button
[Action verb + outcome: "Start Free Trial" / "Get Your Report" / "Book a Demo"]
### Supporting text (optional, below CTA)
[Reduce friction: "No credit card required" / "Free for 14 days" / "Setup in 2 minutes"]
Headline formulas:
| Formula | Example |
|---|---|
| [Outcome] Without [Pain] | "Ship Faster Without Breaking Production" |
| [Outcome] for [Audience] | "Beautiful Dashboards for Data Teams" |
| The [Category] That [Difference] | "The CRM That Writes Itself" |
| Stop [Pain]. Start [Benefit]. | "Stop Guessing. Start Knowing." |
| [Number] [Outcome] in [Timeframe] | "10x Revenue in 90 Days" |
Headline rules:
- No jargon the visitor wouldn't say out loud
- Specific beats vague ("Save 10 hours/week" beats "Save time")
- One benefit only, trying to say everything says nothing
- If you can add "so what?" and it still makes sense, the headline is too vague
CTA button rules:
- Action verb first ("Start," "Get," "Try," "Download", never "Submit" or "Click Here")
- 2-5 words max
- State the outcome, not the action ("Get My Free Report" not "Download PDF")
- One primary CTA per section: don't split attention
Step 3: Problem / Agitation Section
Make the reader feel their problem before presenting the solution:
## Problem Section
### Section headline
[Name the pain directly: "Tired of [problem]?" / "You know the feeling..."]
### Pain points (3-4 bullet points)
- [Specific frustration they experience daily]
- [Consequence of not solving this problem]
- [The thing they've tried that didn't work]
- [The emotional cost: stress, wasted time, missed opportunities]
### Agitation paragraph
[1-2 sentences amplifying the stakes: what happens if they do nothing?
Paint the future they don't want.]
Problem section rules:
- Use the reader's own language (words from reviews, support tickets, forums)
- Be specific, "You spend 3 hours every Monday compiling reports" not "Reports take too long"
- Don't insult the reader or their current tools: empathize with their situation
- The problem section ends with the reader thinking "Yes, that's exactly my problem"
Step 4: Solution Section
Transition from pain to relief. This is where your product enters:
## Solution Section
### Transition line
[Bridge from problem to solution: "What if you could..." / "That's why we built..." / "Imagine instead..."]
### Product introduction (2-3 sentences)
[Product name] [does what] for [whom]. [How it solves the problem stated above].
[One sentence about the approach or key differentiator.]
### How it works (3 steps)
1. **[Action verb]**: [Simple first step the user takes]
2. **[Action verb]**: [What happens next / the product's magic moment]
3. **[Action verb]**: [The outcome they get]
### Visual suggestion
[Screenshot, demo GIF, or product illustration showing the solution in action]
Solution section rules:
- The "how it works" should be 3 steps max: complexity kills conversion
- Each step starts with an action verb
- Show, don't tell, include a visual of the product
- Connect back to the problem: the solution should directly address the pain points listed above
Step 5: Features with Benefit-Oriented Copy
List features, but lead with the benefit each feature provides:
## Features Section
### Section headline
["Everything you need to [outcome]" / "Built for [audience] who [goal]"]
| Benefit (what they get) | Feature (how it works) |
|------------------------|----------------------|
| Never miss a deadline | Automated reminders and milestone tracking |
| See your data clearly | Real-time dashboard with custom views |
| Work from anywhere | Cloud-based with mobile-responsive design |
| Stay secure | End-to-end encryption and SSO |
| Scale without pain | Auto-scaling infrastructure, no DevOps needed |
| Save 10 hours/week | AI-powered automation for repetitive tasks |
Alternative layout (for 3-6 features):
### [Benefit headline]
[1-2 sentences explaining the feature in terms of what the user gains.
Not what it does, what it means for them.]
### [Benefit headline]
[1-2 sentences...]
Feature copy rules:
- Lead column is the benefit (what they get), second column is the feature (how)
- Write benefits as outcomes: "Never miss a deadline" not "Has reminders"
- Include specific numbers when possible: "Save 10 hours/week" not "Save time"
- 4-6 features is the sweet spot, more than 8 overwhelms, fewer than 3 feels thin
- The most important feature goes first (or at the top-left if using a grid)
Step 6: Social Proof Section
Build trust with evidence that others have succeeded:
## Social Proof Section
### Testimonial template (if real testimonials aren't available yet)
> "[Specific result they achieved] since switching to [Product].
> [What they were doing before and what changed.]
> I'd recommend it to any [target audience descriptor]."
>
>: **[Name]**, [Title] at [Company]
### Stat-based proof (if available)
- **[Number]** [users/companies/projects] trust [Product]
- **[Percentage]%** [improvement metric] on average
- **[Timeframe]** average time to see results
### Trust badges
[Logos of notable customers, media mentions, or certifications]
"Trusted by teams at [Company 1], [Company 2], [Company 3]"
### Case study snippet (if available)
**[Company] increased [metric] by [X]% in [timeframe]**
[2-3 sentences about their situation, what they did, and the result]
[Link: "Read the full case study →"]
Social proof rules:
- Specific results beat generic praise ("Saved us 15 hours/week" beats "Great product!")
- Include name, title, and company for credibility (anonymous quotes are weak)
- If you don't have testimonials yet, use stats, founding story, or "built by" credibility
- 3 testimonials is the sweet spot, 1 feels cherry-picked, 5+ feels desperate
- Place social proof after features (they've seen what it does, now they need validation)
Step 7: FAQ Section
Address the top objections that prevent conversion:
## FAQ Section
### Section headline
"Questions? We've got answers." / "Common questions"
**Q: [Price objection, "How much does it cost?" / "Is there a free trial?"]**
A: [Direct answer. If there's a free tier, lead with it. Include pricing page link.]
**Q: [Trust objection, "Is my data secure?" / "Who else uses this?"]**
A: [Specific security measures. Customer logos or numbers. Certifications.]
**Q: [Effort objection, "How long does setup take?" / "Do I need technical skills?"]**
A: [Minimize perceived effort. "Setup takes 5 minutes" / "No coding required."]
**Q: [Switching objection, "Can I import my existing data?" / "What about my current tool?"]**
A: [Migration path. Import tools. Compatibility assurances.]
**Q: [Commitment objection, "What if it doesn't work for me?" / "Can I cancel anytime?"]**
A: [Money-back guarantee. No lock-in. Cancel anytime policy.]
FAQ rules:
- 4-6 questions max on the landing page
- Phrase questions the way a customer would (not formal, not marketing-speak)
- Every answer ends with confidence, not hedging
- The FAQ is really an objection-handling section: structure it that way
- If the same question keeps coming up in sales calls, it belongs here
Step 8: Final CTA Section
The bottom CTA converts readers who've scrolled the entire page:
## Final CTA Section
### Headline
[Restate the primary benefit with urgency: "Ready to [outcome]?"]
### Supporting copy (1-2 sentences)
[Summarize value + reduce risk: "Join [X] teams already [achieving outcome].
Start free: no credit card required."]
### CTA Button
[Same as hero CTA, or stronger: "Start Free Trial" → "Start Your Free Trial Now"]
### Urgency element (use only if genuine)
- Time-limited: "Launch pricing ends [date]"
- Scarcity: "[X] spots remaining this month"
- Social: "[X] teams signed up this week"
### Secondary CTA (optional)
"Not ready yet? [Book a demo / Watch a 2-minute walkthrough / Read our blog]"
Final CTA rules:
- Don't introduce new information here: reinforce the hero message
- Urgency must be real, fake countdown timers destroy trust
- Always include a secondary/softer CTA for people who aren't ready to commit
- This CTA should be the most visually prominent element below the fold
Step 9: Output Copy Blocks
Output all sections as clean, structured copy:
# Landing Page Copy: [Product Name]
**Target audience:** [persona]
**Primary CTA:** [action]
**Tone:** [casual / professional / bold / etc.]
---
[Hero Section]
[Problem Section]
[Solution Section]
[Features Section]
[Social Proof Section]
[FAQ Section]
[Final CTA Section]
---
Output summary:
🎯 Landing Page Copy: Complete
Product: [name]
Audience: [target persona]
Sections: 7 (Hero, Problem, Solution, Features, Social Proof, FAQ, CTA)
Primary CTA: [button text]
Urgency element: [type or "none"]
Word count: ~[count] words across all sections
Headline: [headline] ([word count] words)
Conversion checklist:
✅ Clear headline (under 10 words)
✅ Benefit-oriented feature copy
✅ Problem/agitation section
✅ Social proof (testimonials/stats)
✅ Objection handling (FAQ)
✅ Single primary CTA throughout
✅ Friction reducer (free trial/no CC/guarantee)
Next steps:
1. Review and customize with brand voice
2. Add real testimonials and customer logos
3. Drop copy blocks into your page template
4. A/B test headline variations
Level History
- Lv.1: Base: Product detail gathering, hero section (10-word headline, subheadline, CTA), problem/agitation, solution with 3-step process, benefit-oriented features, social proof templates, FAQ objection handling, final CTA with urgency, structured copy blocks. Based on adminstack.pro, ImageStack, and memstack.pro landing pages. (Origin: MemStack Pro v3.2, Mar 2026)
Newsletter: Writing email newsletter edition...
Produces an email newsletter edition with subject line formulas, section structure, personalization, link placement strategy, growth tactics, and engagement optimization.
Activation
When this skill activates, output:
Newsletter: Writing email newsletter edition...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "newsletter", "email newsletter", "weekly digest" | ACTIVE |
| User says "subscriber growth" or "open rates" | ACTIVE |
| User wants to write a newsletter edition or start a newsletter | ACTIVE |
| User wants a lead magnet with email capture | DORMANT: use Lead Magnet |
| User wants a full content automation pipeline | DORMANT: use Content Pipeline |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Newsletter = company updates" | Nobody cares about your company news. Deliver value: insights, tips, curated content. |
| "Generic subject line" | "[Company] Monthly Newsletter" gets 10% opens. Curiosity-driven subjects get 35%+. |
| "No consistent format" | Readers want predictable value. A consistent structure builds habit and trust. |
| "Too many links" | More than 3-5 links per section dilutes clicks. Feature one primary link prominently. |
| "No growth strategy" | "Build it and they will come" doesn't work. Actively promote every issue. |
Protocol
Step 1: Gather Newsletter Requirements
If the user hasn't provided details, ask:
- Topic/niche: what's the newsletter about?
- Audience: who reads it? (role, industry, experience level)
- Frequency: weekly, biweekly, or monthly?
- Type: curated links, original essays, tips, industry news, or mixed?
- Current state: new or existing? (subscriber count, open rates)
- Monetization: free, paid, or sponsored?
Step 2: Write the Subject Line
Subject line formulas:
| Formula | Template | Example |
|---|---|---|
| Curiosity gap | [Topic]: The [thing] nobody talks about | "Pricing: The metric nobody tracks" |
| Numbered value | [X] [things] to [outcome] this week | "5 tools to ship faster this week" |
| Question | Why [common practice] [doesn't work / is wrong]? | "Why your landing page isn't converting?" |
| Personal | I [did thing], here's what happened | "I quit meetings for a month" |
| Direct value | How to [outcome] (in [constraint]) | "How to write copy that converts (in 20 min)" |
| Current event | [Event/trend]: What it means for [audience] | "GPT-5: What it means for developers" |
Subject line rules:
- 6-10 words (40-50 characters) for mobile display
- No ALL CAPS, no spam triggers ("FREE", "ACT NOW", "!!!")
- Preview text (first 90 characters of email) should complement, not repeat the subject
- A/B test 2 subjects per send (most platforms support this)
- Track open rates by subject formula, double down on what works
Step 3: Design Section Structure
Newsletter format template:
# [Newsletter Name]: [Edition Title or Number]
## Intro (2-3 sentences)
[Personal note, context for this edition, or a hook that frames the content]
---
## [Section 1: Primary Content] (60% of newsletter)
[Your main value: original insight, deep dive, or featured piece]
[Include one primary CTA link]
---
## [Section 2: Quick Hits / Curated] (25% of newsletter)
### [Item 1 title]
[1-2 sentence summary + link]
### [Item 2 title]
[1-2 sentence summary + link]
### [Item 3 title]
[1-2 sentence summary + link]
---
## [Section 3: Closer] (15% of newsletter)
[Personal sign-off, question for readers, or community highlight]
---
[Footer: Unsubscribe | Forward to a friend | [Social links]]
Section type options (pick 2-4 per edition):
| Section | Content | Purpose |
|---|---|---|
| Deep Dive | Original essay or analysis (500-800 words) | Demonstrate expertise |
| Quick Hits | 3-5 curated links with one-line summaries | Deliver breadth of value |
| Tool/Resource | Featured tool with your take on it | Practical value |
| Tip of the Week | One actionable tactic they can use today | Quick win |
| Community Spotlight | Reader question, testimonial, or submission | Build community |
| Sponsor Section | Sponsored content (clearly labeled) | Monetization |
| Poll/Question | Ask readers something: drives replies | Engagement signal |
Step 4: Write the Edition
Intro paragraph rules:
- 2-3 sentences maximum
- Personal and conversational (not corporate)
- Frames why THIS edition matters
- Optional: reference a current event or reader feedback
Body content rules:
- Write at an 8th-grade reading level (clear, accessible)
- Use headers, bold, and bullet points for scannability
- One idea per paragraph (3 sentences max)
- Link text should describe the destination ("Read the full case study" not "Click here")
- Primary CTA should appear within the first scroll (above 300 words)
Personalization techniques:
| Technique | Implementation | Impact |
|---|---|---|
| First name in subject | "Hey {first_name}, [subject]" | +10-15% open rate |
| Segment by interest | Tag subscribers → send relevant content | +20-30% click rate |
| Reference past behavior | "Since you read about [topic]..." | Higher engagement |
| Reader-submitted content | Feature reader questions or wins | Community loyalty |
Step 5: Link Placement Strategy
Link placement hierarchy:
| Position | Purpose | Click Priority |
|---|---|---|
| Above the fold (first 100 words) | Primary CTA or featured link | Highest |
| End of main section | Deeper reading link | High |
| Quick hits section | Curated resource links | Medium |
| Closer | Social follow or referral link | Low |
Rules:
- 1 primary link per edition (the ONE thing you want them to click)
- 3-5 secondary links maximum (curated content, resources)
- No more than 8 total links (including footer): too many dilutes clicks
- Use descriptive anchor text, not raw URLs
- Track clicks with UTM parameters:
?utm_source=newsletter&utm_medium=email&utm_campaign=edition-[N]
Step 6: Growth Tactics
Subscriber acquisition channels:
| Channel | Tactic | Expected Growth |
|---|---|---|
| Website | Email capture in header, footer, and exit-intent popup | Steady baseline |
| Social media | Share a highlight from each edition with subscribe link | 5-15 subs/post |
| Twitter/X threads | End threads with "I go deeper in my newsletter: [link]" | 10-50 subs/thread |
| Cross-promotion | Swap recommendations with similar-sized newsletters | 50-200 per swap |
| Referral program | "Refer 3 friends → get [bonus]" | 10-20% of new subs |
| Gated content | Best content behind email signup (lead magnet) | High conversion |
| Guest posts | Write for others, link to newsletter in bio | 20-100 per post |
Retention metrics to track:
| Metric | Target | Red Flag |
|---|---|---|
| Open rate | >35% | <20% |
| Click rate | >3% | <1% |
| Unsubscribe rate | <0.5% per send | >1% |
| Reply rate | >0.5% | 0% (no engagement) |
| Growth rate (net) | >5% monthly | Negative (losing subs) |
Step 7: Scheduling & Send Optimization
Optimal send times:
| Audience | Best Day | Best Time | Why |
|---|---|---|---|
| Business / B2B | Tuesday-Thursday | 9-10 AM local | Morning inbox check |
| Creators / Solo | Tuesday or Saturday | 8-9 AM local | Before the day fills up |
| Developers | Wednesday | 10 AM local | Mid-week engagement peak |
| General / Consumer | Sunday or Tuesday | 9-10 AM local | Weekend reading or fresh week |
Pre-send checklist:
- Subject line is 6-10 words, creates curiosity
- Preview text complements the subject (not a repeat)
- All links work (click-test every one)
- UTM parameters on all links
- Images have alt text
- Mobile preview looks good (60%+ open on mobile)
- Unsubscribe link is visible
- Spell check passed
- Send a test email to yourself first
Output Format
# [Newsletter Name]: Edition [#]
**Subject:** [Subject line]
**Preview text:** [90 characters]
**Send date:** [Date, Time, Timezone]
---
[Full newsletter content following the structure from Step 3]
---
## Metrics to Track
- Open rate target: [X]%
- Click rate target: [X]%
- Primary CTA link: [URL]
Completion
Newsletter: Complete!
Edition: [#/Title]
Subject line: "[Subject]"
Sections: [Count]
Links: [Count] ([1] primary, [X] secondary)
Word count: [X]
Next steps:
1. Load into your email platform
2. Preview on mobile (most opens are mobile)
3. A/B test the subject line (send 2 variants to 20% each, winner to 60%)
4. Schedule for [optimal time]
5. After sending: share a highlight on social media with subscribe CTA
Level History
- Lv.1: Base: 6 subject line formulas, section structure template (intro, deep dive, quick hits, closer), body writing rules with personalization techniques, link placement hierarchy (primary + secondary), 7 growth channels with expected results, retention metrics with red flags, send time optimization, pre-send checklist. (Origin: MemStack Pro v3.2, Mar 2026)
Product Description: Writing product copy...
Creates conversion-optimized product descriptions with feature-to-benefit conversion, sensory language, SEO keywords, A/B variants, and platform-specific formats for Amazon, Shopify, and Etsy.
Activation
When this skill activates, output:
Product Description: Writing product copy...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "product description", "product listing", "product copy" | ACTIVE |
| User says "Amazon listing", "Shopify listing", "e-commerce copy" | ACTIVE |
| User wants to write or improve copy for a product listing | ACTIVE |
| User wants to set pricing | DORMANT: use Pricing Strategy |
| User wants a full sales funnel | DORMANT: use Sales Funnel |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "List features, not benefits" | "500mAh battery" means nothing. "Lasts 12 hours so you never run out mid-day" sells. |
| "Generic descriptions" | "High quality product" could describe anything. Be specific about WHAT makes it quality. |
| "Ignore the platform" | Amazon, Shopify, and Etsy have different algorithms, formats, and buyer expectations. |
| "No keywords" | E-commerce search is keyword-driven. No keywords = invisible in search results. |
| "One version only" | A/B testing descriptions is easy and can improve conversion 10-30%. Write variants. |
Protocol
Step 1: Gather Product Details
If the user hasn't provided details, ask:
- Product: what is it? (name, category, physical/digital)
- Features: what are its key specs and features? (list 5-10)
- Audience: who buys this? (demographics, use case, pain point)
- Platform: where is it listed? (Amazon, Shopify, Etsy, other)
- Price point: what does it cost? (affects copy tone and positioning)
- Competitors: what are the top 3 alternatives? (for differentiation)
Step 2: Feature-to-Benefit Conversion
Transform every feature into a customer benefit:
| Feature (What It Is) | Benefit (Why They Care) | Emotional Trigger |
|---|---|---|
| [Technical spec] | [Practical outcome] | [Feeling it creates] |
Examples:
| Feature | → Benefit | → Emotional |
|---|---|---|
| "Made from organic cotton" | "Gentle on sensitive skin" | "Safe for your baby" |
| "5000mAh battery" | "Lasts 2 full days on one charge" | "Never stress about dying battery" |
| "Adjustable height: 28-36 inches" | "Fits any desk setup, standing or sitting" | "Work comfortably, your way" |
| "Ships in recyclable packaging" | "Zero waste delivery to your door" | "Feel good about your purchase" |
Conversion formula:
[Feature] → so you can → [Benefit] → which means → [Emotional outcome]
Step 3: Write the Product Description
Universal structure:
## [Product Title: Keyword-Rich, Benefit-Driven]
### Opening Hook (1-2 sentences)
[Address the pain point or desire. Create an "I need that" reaction.]
### Key Benefits (bullet points)
• [Benefit 1], [supporting detail]
• [Benefit 2], [supporting detail]
• [Benefit 3], [supporting detail]
• [Benefit 4], [supporting detail]
• [Benefit 5]: [supporting detail]
### Body Description (2-3 short paragraphs)
[Paint a picture of using the product. Use sensory language.
Address the top objection. Include social proof if available.]
### Specifications
[Technical details for comparison shoppers]
### Call to Action
[Urgency or reassurance: "Order now" + guarantee or shipping info]
Sensory language guide:
| Sense | Words | Use For |
|---|---|---|
| Touch | Silky, rugged, lightweight, cushioned, velvety | Clothing, furniture, tools |
| Sight | Vibrant, sleek, crystal-clear, polished, matte | Electronics, decor, fashion |
| Sound | Whisper-quiet, crisp, deep bass, silent | Electronics, appliances |
| Taste | Rich, smooth, zesty, creamy, bold | Food, beverages |
| Smell | Fresh, earthy, aromatic, clean, invigorating | Candles, skincare, food |
Step 4: Platform-Specific Formatting
Amazon listing format:
## Product Title (200 characters max)
[Brand] [Product Name] ([Key Benefit] [Key Feature] [Size/Variant]) [Use Case]
Example: "EcoBottle Premium Insulated Water Bottle, Keeps Drinks Cold 24 Hours, BPA-Free Stainless Steel, 32oz: Perfect for Hiking & Gym"
## Bullet Points (5 bullets, 200 chars each)
• [BENEFIT IN CAPS]: [Explanation]. [Spec detail].
• [BENEFIT IN CAPS]: [Explanation]. [Spec detail].
• [BENEFIT IN CAPS]: [Explanation]. [Spec detail].
• [BENEFIT IN CAPS]: [Explanation]. [Spec detail].
• [BENEFIT IN CAPS]: [Explanation]. [Spec detail].
## Product Description (2000 chars max)
[Rich HTML-formatted description with headers, paragraphs, and bold text]
## Backend Keywords (250 bytes)
[Hidden keywords separated by spaces: no commas, no repeats, no brand names]
Shopify product page:
## Product Title
[Concise, descriptive, SEO-friendly: 60-70 characters]
## Price + Compare-at Price (if on sale)
## Short Description (visible above the fold)
[2-3 sentences: hook + primary benefit + social proof snippet]
## Full Description (tabbed or expandable)
### Why You'll Love It
[3-5 benefit bullets]
### How It Works
[Use case description or instructions]
### What's Included
[List of everything in the box/package]
### Specifications
[Technical details table]
## SEO
- Meta title: [Product]: [Benefit] | [Brand] (60 chars)
- Meta description: [Compelling summary with CTA] (155 chars)
- URL handle: /products/[keyword-slug]
Etsy listing:
## Title (140 characters)
[Keywords first: "Handmade [Product] for [Occasion]: [Key Feature] [Material] [Size]"]
## Description (first 160 chars appear in search)
[Hook sentence first: this shows in search preview]
[Full description with story element: why you made this, materials used, care instructions]
[Size guide / dimensions]
[Shipping information]
[Care instructions]
[Customization options]
## Tags (13 tags, 20 chars each)
[Long-tail keywords that match buyer search behavior]
[Focus on: material, use case, recipient, occasion, style]
## Attributes
[Fill ALL available attributes: material, color, occasion, style]
Step 5: SEO Keyword Integration
Keyword research for product listings:
| Keyword Type | Where to Use | Example |
|---|---|---|
| Primary keyword | Title, first sentence of description | "insulated water bottle" |
| Secondary keywords | Bullet points, body description | "BPA-free", "stainless steel", "cold 24 hours" |
| Long-tail keywords | Backend/tags, lower in description | "best water bottle for hiking 2026" |
| Competitor keywords | Backend/tags | "hydroflask alternative", "yeti competitor" |
Keyword placement rules:
- Primary keyword appears in: title, first bullet/sentence, one subheading
- Don't keyword-stuff, read it aloud; if it sounds robotic, rewrite
- Backend keywords (Amazon) or tags (Etsy) are invisible, use them for synonyms and misspellings
- Use natural language, "water bottle that keeps drinks cold" beats "cold water bottle insulated"
Step 6: Write A/B Variants
Write 2 description variants to test:
## Variant A: Benefit-Led
[Opens with the primary benefit and emotional outcome]
"Never worry about your drink going warm again. The [Product] keeps
beverages ice-cold for 24 hours..."
## Variant B: Problem-Led
[Opens with the pain point the product solves]
"Tired of lukewarm water halfway through your hike? [Product] uses
double-wall vacuum insulation to keep your drinks cold all day..."
What to A/B test:
- Headline approach (benefit-led vs. problem-led)
- Bullet point order (most popular benefit first vs. most unique)
- Description length (short punchy vs. detailed comprehensive)
- CTA text ("Add to Cart" vs. "Get Yours Now" vs. "Buy Now: Free Shipping")
Step 7: Pre-Publish Checklist
- Primary keyword in title and first sentence
- All features converted to benefits (no naked specs)
- Sensory language used where appropriate
- Platform-specific format followed (Amazon bullets, Shopify tabs, Etsy story)
- Backend keywords / tags filled in
- Images referenced match description claims
- Price and shipping info are accurate
- Social proof included if available (reviews, awards, "bestseller")
- Scannability: bullets, bold, short paragraphs
- Read aloud, does it sound natural and persuasive?
- Mobile preview checked (most shopping is mobile)
Output Format
# Product Description: [Product Name]
## Platform: [Amazon / Shopify / Etsy]
## Primary Keyword: [Keyword]
### Title
[Platform-optimized title]
### Description
[Full description following platform format from Step 4]
### SEO
[Keywords, meta tags, backend keywords]
### A/B Variant
[Second version for testing]
Completion
Product Description: Complete!
Product: [Name]
Platform: [Platform]
Primary keyword: [Keyword]
Benefits highlighted: [Count]
A/B variants: 2
SEO elements: Title, description, backend keywords
Next steps:
1. Upload to your platform using the formatted copy
2. Add high-quality images that match the description claims
3. Set up A/B test between Variant A and Variant B
4. Monitor conversion rate for 2 weeks before picking a winner
5. Update quarterly based on new reviews and competitor changes
Level History
- Lv.1: Base: Feature-to-benefit conversion formula, sensory language guide (5 senses), universal product description structure, platform-specific formats (Amazon, Shopify, Etsy), SEO keyword integration with placement rules, A/B testing variants (benefit-led vs. problem-led), pre-publish checklist. (Origin: MemStack Pro v3.2, Mar 2026)
TikTok Script: Writing short-form video script...
Creates timestamped scripts for TikTok, Reels, and Shorts (15-60 seconds) with hook-in-first-2-seconds, visual cues, caption text, trending audio strategy, and hashtag research.
Activation
When this skill activates, output:
TikTok Script, Writing short-form video script...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "TikTok script", "TikTok video", "Reels script", "Shorts script" | ACTIVE |
| User says "short-form video" and wants a scripted 15-60 second video | ACTIVE |
| User wants to create content for TikTok, Instagram Reels, or YouTube Shorts | ACTIVE |
| User wants a Twitter/X thread | DORMANT: use Twitter Thread |
| User wants a long-form video (YouTube) | DORMANT: use YouTube Script |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Slow intro" | You have 1-2 seconds to hook. The algorithm judges retention in the first 3 seconds. |
| "Read from a teleprompter" | Stiff delivery kills engagement. Use bullet points, not word-for-word scripts. |
| "Ignore trending audio" | Trending sounds get algorithmic boost. Use them even if you're talking over them at low volume. |
| "No text on screen" | 80%+ watch without sound. On-screen captions and text hooks are essential. |
| "One take, one angle" | Visual variety (cuts, zooms, angle changes) every 2-3 seconds keeps retention high. |
Protocol
Step 1: Gather Video Requirements
If the user hasn't provided details, ask:
- Topic: what's the video about?
- Format: talking head, tutorial, storytime, POV, or visual showcase?
- Platform: TikTok, Instagram Reels, YouTube Shorts, or all three?
- Length: 15s, 30s, or 60s?
- Goal: views, followers, website traffic, or product sales?
- Audience: who's watching? (age, interests, awareness level)
Step 2: Choose Video Format
| Format | Best For | Hook Style |
|---|---|---|
| Talking head | Tips, hot takes, storytelling | Direct eye contact + bold statement |
| Tutorial/how-to | Teaching a skill, showing a process | "Here's how to [outcome] in [X] seconds" |
| Storytime | Personal experience, relatable content | "The time I [dramatic event]..." |
| POV | Relatable situations, humor | Text overlay: "POV: [situation]" |
| Before/After | Transformations, results | Show the "after" first (pattern interrupt) |
| Duet/Stitch | Reacting to trends, adding commentary | Response to existing content |
| Visual showcase | Products, travel, food | Satisfying visuals + trending audio |
Step 3: Write the Hook (First 2 Seconds)
The 2-second rule: If they don't stop scrolling in 2 seconds, the video fails.
Hook formulas:
| Formula | Example | On-Screen Text |
|---|---|---|
| Bold claim | "This one trick doubled my revenue" | "DOUBLED my revenue" |
| Question | "Why does nobody talk about this?" | "WHY??" |
| Challenge | "I bet you didn't know this" | "BET you didn't know" |
| Pattern interrupt | Start mid-action, unexpected visual | [Eye-catching visual] |
| Controversy | "Unpopular opinion: [take]" | "UNPOPULAR OPINION" |
| Result first | Show the end result immediately | "Here's the result" |
| Direct address | "Stop scrolling if you [situation]" | "STOP SCROLLING" |
Hook delivery tips:
- Start talking IMMEDIATELY (no "hey guys" or "so today")
- Movement in frame from second 0 (lean in, gesture, reveal)
- On-screen text appears in first 0.5 seconds
- Confident energy, uncertainty is a scroll trigger
Step 4: Write the Script
15-second script template:
[0:00-0:02] HOOK
Visual: [What's on screen]
Audio: "[Hook line, bold, concise]"
Text overlay: "[Key phrase in large text]"
[0:02-0:10] BODY
Visual: [Action / demonstration / explanation]
Audio: "[Core content, 2-3 key sentences]"
Text overlay: "[Supporting text or steps]"
[0:10-0:15] CTA
Visual: [Face to camera / point at text]
Audio: "[CTA: follow for more / link in bio / comment below]"
Text overlay: "[CTA text]"
30-second script template:
[0:00-0:02] HOOK
Visual: [Pattern interrupt or result]
Audio: "[Hook line]"
Text overlay: "[Hook text: large, bold]"
[0:02-0:08] CONTEXT
Visual: [Set up the problem or situation]
Audio: "[Why this matters, 2 sentences]"
Text overlay: "[Key phrase]"
[0:08-0:22] BODY (3 points)
Visual: [Demonstration, steps, or story beats]
Audio: "[Point 1] → [Point 2] → [Point 3]"
Text overlay: "[Step 1] [Step 2] [Step 3]" (change with each point)
Cut/zoom every 3-4 seconds
[0:22-0:30] CTA
Visual: [Face to camera, energy up]
Audio: "[Wrap-up + CTA]"
Text overlay: "[CTA: Follow + Save]"
60-second script template:
[0:00-0:03] HOOK
[0:03-0:10] CONTEXT (why this matters)
[0:10-0:45] BODY (5-7 points with visual cuts every 3-5 seconds)
[0:45-0:55] SUMMARY (key takeaway)
[0:55-1:00] CTA
Step 5: Visual Direction
Shot list template:
| Timestamp | Shot Type | Description | Text Overlay |
|---|---|---|---|
| 0:00 | Close-up | Face, direct eye contact | Hook text (bold) |
| 0:02 | Medium | Upper body, gesturing | none |
| 0:05 | B-roll / screen | Demo or visual | Step 1 text |
| 0:10 | Close-up | Back to face, different angle | Step 2 text |
| 0:15 | B-roll / screen | Second demo | Step 3 text |
| 0:20 | Medium | Wrap-up, high energy | CTA text |
Visual retention techniques:
- Cut or zoom every 2-4 seconds (never hold one shot >5 seconds)
- Use jump cuts to remove dead air and "um"s
- Text on screen should appear 0.5s before the speaker says it
- Use pointing gestures to direct attention to on-screen text
- Match visual transitions to beat drops in the audio
Step 6: Audio & Trending Sound Strategy
Audio approach by format:
| Format | Audio Strategy |
|---|---|
| Talking head | Your voice only, OR voice over trending sound at 10% volume |
| Tutorial | Voiceover narration + trending sound at low volume |
| Storytime | Your voice with ambient/emotional background music |
| POV | Trending sound at full volume (lip sync or background) |
| Visual showcase | Trending sound at full volume |
Finding trending sounds:
- Check TikTok's Discover page for trending sounds
- Use sounds with an upward arrow (↑) indicating growth
- Filter by sounds used in 10K-500K videos (sweet spot for riding the trend)
- Save sounds to a "favorites" library for quick access
Step 7: Hashtag & Caption Strategy
Caption formula:
[Hook/question that drives comments] + [1-2 sentences of context]
Example:
"This changed how I work forever. Save this for later. #[niche] #[topic]"
Hashtag strategy (3-5 per post):
| Type | Example | Purpose |
|---|---|---|
| Niche-specific | #saastips #ecommercetips | Reach your target audience |
| Trending | #fyp #viral #trending | Algorithmic boost |
| Content-type | #learnontiktok #tutorial | Platform-promoted categories |
Caption rules:
- Keep under 150 characters (most users don't expand)
- Front-load the hook, first line must create curiosity
- Ask a question to drive comments (comments boost distribution)
- Use 3-5 hashtags (more than 5 looks spammy)
Output Format
# Short-Form Video Script: [Topic]
## Overview
- **Platform:** [TikTok / Reels / Shorts]
- **Length:** [15s / 30s / 60s]
- **Format:** [Talking head / Tutorial / etc.]
- **Audio:** [Original voice / Trending sound]
## Script
### [0:00-0:02] Hook
**Visual:** [Shot description]
**Audio:** "[Spoken text]"
**Text overlay:** "[On-screen text]"
### [0:02-0:XX] Body
[Timestamped sections with visual/audio/text]
### [0:XX-End] CTA
**Visual:** [Shot description]
**Audio:** "[CTA text]"
**Text overlay:** "[CTA text]"
## Production Notes
- **Trending sound:** [Sound name / link]
- **Hashtags:** [3-5 hashtags]
- **Caption:** "[Caption text]"
- **Best posting time:** [Day, Time]
Completion
TikTok Script: Complete!
Topic: [Topic]
Length: [X] seconds
Format: [Type]
Visual cuts: [Count]
Audio: [Strategy]
Next steps:
1. Practice the script 2-3 times (aim for natural, not memorized)
2. Film in good lighting (natural light or ring light)
3. Record 3-5 takes and pick the best energy
4. Edit with cuts every 2-4 seconds
5. Add text overlays and captions
6. Post at peak time with trending sound
Level History
- Lv.1: Base: 7 video formats with hook styles, 7 hook formulas with on-screen text, timestamped script templates (15s/30s/60s), shot list with visual retention techniques, audio strategy by format, trending sound discovery, hashtag strategy (3-type approach), caption formula. (Origin: MemStack Pro v3.2, Mar 2026)
Twitter Thread: Writing viral thread...
Creates multi-tweet threads (5-15 posts) with hook formulas, narrative arc, engagement tactics, data points, CTA placement, and scheduling strategy.
Activation
When this skill activates, output:
Twitter Thread: Writing viral thread...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "twitter thread", "tweet thread", "X thread" | ACTIVE |
| User says "viral thread" or wants multi-tweet content | ACTIVE |
| User wants to share insights, stories, or frameworks on Twitter/X | ACTIVE |
| User wants a TikTok or Reels script | DORMANT: use TikTok Script |
| User wants a newsletter | DORMANT: use Newsletter |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Weak first tweet" | Tweet 1 is your headline. If it doesn't stop the scroll, no one reads tweets 2-15. |
| "Wall of text per tweet" | White space matters. Short lines, line breaks, and punchy sentences get read. |
| "No thread structure" | Random thoughts don't thread well. Use a framework: story, list, or lesson arc. |
| "Forget the CTA" | Every thread should end with a clear ask: follow, retweet, reply, or click. |
| "Post at random times" | Twitter engagement peaks at specific hours. Schedule for your audience's timezone. |
Protocol
Step 1: Gather Thread Requirements
If the user hasn't provided details, ask:
- Topic: what's the thread about?
- Angle: personal story, tactical how-to, hot take, data breakdown, or curated list?
- Goal: followers, engagement, traffic to a link, or brand awareness?
- Length: short (5-7 tweets), medium (8-12), or long (13-15)?
- Key points: what are the 3-5 main takeaways?
Step 2: Choose Thread Structure
| Structure | Best For | Pattern |
|---|---|---|
| Story arc | Personal experience, case study | Setup → Conflict → Turning point → Resolution → Lesson |
| Listicle | Tips, tools, resources | Hook → Item 1 → Item 2 → ... → Summary → CTA |
| Framework | Teaching a method | Hook → Context → Step 1 → Step 2 → Step 3 → Recap → CTA |
| Contrarian | Hot takes, challenging norms | Bold claim → Evidence 1 → Evidence 2 → Nuance → Reframe → CTA |
| Before/After | Transformations, results | Old way → Problems → Discovery → New way → Results → CTA |
Step 3: Write the Hook (Tweet 1)
The hook tweet determines 90% of thread performance.
Hook formulas:
| Formula | Template | Example |
|---|---|---|
| Bold claim | "[Counter-intuitive statement]:" | "Most marketing advice is wrong:" |
| Numbered list | "[X] [things] that [outcome]:" | "7 pricing mistakes that cost me $50K:" |
| Story opener | "In [year], I [dramatic situation]." | "In 2023, I almost shut down my startup." |
| Question | "Why do [group] always [action]?" | "Why do most SaaS founders underprice?" |
| Data hook | "I analyzed [X] and found [surprising result]." | "I analyzed 500 landing pages. Here's what converts:" |
| Time-based | "[Time period] ago, I [situation]. Today, [result]." | "6 months ago I had 200 followers. Today: 50K." |
Hook rules:
- Maximum 2 lines visible without expanding (keep under 180 characters)
- Create a curiosity gap, make them need to read tweet 2
- End with a colon
:or "Here's what I learned:" to signal more is coming - No links in tweet 1 (links reduce reach by 50%+)
Step 4: Write Body Tweets (2 through N-1)
Body tweet rules:
- One idea per tweet (never two concepts in one tweet)
- Use line breaks for readability
- Short sentences. Punchy paragraphs.
- Include a mini-hook every 3-4 tweets to retain scrollers
- Use numbered tweets (
1/,2/) OR natural flow (no numbers): don't mix
Formatting patterns:
[Concept tweet]
This is the key insight.
Most people think [common belief].
But the reality is [contrarian truth].
Here's why:
[Tactical tweet]
Step 3: [Action]
→ Do [specific thing]
→ Then [specific thing]
→ Result: [outcome]
This alone [impressive result].
[Data tweet]
I tested this on [X samples].
Results:
• [Finding 1]: [XX]%
• [Finding 2]: [XX]%
• [Finding 3]: [XX]%
The winner? [Finding].
Engagement re-hooks (insert at tweets 4, 7, 10):
- "But here's where it gets interesting:"
- "This next one changed everything:"
- "Most people miss this part:"
- "(save this one)"
Step 5: Write the Closing CTA (Final Tweet)
CTA formulas:
| Goal | CTA Template |
|---|---|
| Followers | "Follow me @[handle] for more [topic]. I share [value] every [frequency]." |
| Retweet | "If this was helpful, retweet the first tweet so others can find it." |
| Reply | "What would you add? Drop your best [topic] tip below." |
| Link click | "I wrote a full breakdown here: [link]" |
| Newsletter | "I go deeper on this in my newsletter. Subscribe: [link]" |
| Engagement | "Which of these was most surprising? Reply with the number." |
CTA rules:
- ONE primary CTA only (multiple CTAs dilute action)
- If driving to a link, put it in the last tweet (not tweet 1)
- Add the self-retweet ask: "Retweet tweet 1 to help others find this"
- Reply to your own thread with the link (keeps link out of main thread)
Step 6: Final Polish
Thread checklist:
- Tweet 1 creates a curiosity gap (would YOU click to read more?)
- Each tweet can stand alone (make sense without surrounding context)
- No tweet exceeds 280 characters
- Line breaks and white space make each tweet scannable
- Engagement re-hooks at tweets 4, 7, and 10
- CTA in the final tweet is clear and specific
- No links in tweet 1 (put links in last tweet or reply)
- Thread length matches content depth (don't pad, don't rush)
- Read the full thread aloud: does it flow naturally?
Scheduling strategy:
- Best times: Weekdays 8-10 AM or 12-1 PM (audience's timezone)
- Best days: Tuesday through Thursday
- Post tweet 1, then unroll the rest within 1-2 minutes
- Self-retweet the thread 6-8 hours later for a second wave
Output Format
# Twitter/X Thread: [Topic]
**Structure:** [Story / Listicle / Framework / etc.]
**Length:** [X] tweets
**Goal:** [Followers / Engagement / Traffic]
**Best posting time:** [Day, Time, Timezone]
## Thread
**Tweet 1 (Hook):**
[Hook tweet: under 180 chars]
**Tweet 2:**
[Body tweet]
**Tweet 3:**
[Body tweet]
[...all tweets...]
**Tweet [N] (CTA):**
[Closing CTA tweet]
**Reply to thread:**
[Link or bonus content, posted as a reply to tweet 1]
Completion
Twitter Thread: Complete!
Topic: [Topic]
Structure: [Type]
Length: [X] tweets
Hook type: [Formula used]
CTA: [Primary action]
Next steps:
1. Read the full thread aloud, trim anything that doesn't flow
2. Schedule for [optimal time] using a scheduling tool
3. Self-retweet 6-8 hours after posting
4. Engage with every reply in the first 2 hours (boosts algorithm)
5. Track impressions and engagement rate to learn what works
Level History
- Lv.1: Base: 5 thread structures (story, listicle, framework, contrarian, before/after), 6 hook formulas with examples, body tweet formatting patterns, engagement re-hooks, CTA formulas by goal (6 types), scheduling strategy, full thread checklist. (Origin: MemStack Pro v3.2, Mar 2026)
🎬 YouTube Script: Writing retention-optimized video script...
Produces a timestamped video script with hook, retention techniques, visual directions, SEO metadata, and thumbnail concept, optimized for YouTube's algorithm.
Activation
When this skill activates, output:
🎬 YouTube Script, Gathering topic and audience details...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "write youtube script" or "youtube script" | ACTIVE |
| User says "video script" or "write script for video" | ACTIVE |
| Creating a scripted video for YouTube or video platform | ACTIVE |
| Writing a blog post (not video) | DORMANT: use blog-post |
| Writing a podcast outline | DORMANT |
| Discussing YouTube strategy at a high level | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Start with an intro about who I am" | Viewers don't care who you are until you've hooked them. Identity comes after value. |
| "Cover everything about the topic" | YouTube rewards depth on one angle, not breadth across many. Pick one promise and deliver it fully. |
| "The content speaks for itself" | Retention techniques (open loops, pattern breaks) keep viewers watching. Great content with poor pacing loses to good content with great pacing. |
| "I'll figure out the visuals during editing" | Script the visuals alongside the words. B-roll and graphics are planned, not improvised. |
| "Thumbnails are just screenshots" | The thumbnail is 50% of click-through rate. Design it before filming, it shapes the video's angle. |
Protocol
Step 1: Gather Video Details
If the user hasn't provided details, ask:
I need a few details for the script:
- Topic: what's this video about?
- Target viewer: who is watching? (beginner dev, business owner, tech enthusiast, etc.)
- Video length goal: short (5-8 min), standard (10-15 min), long-form (20+ min)?
- CTA goal: what should viewers do? (subscribe, click a link, watch next video, buy)
- Channel context: is this part of a series? What's the channel about?
- Presentation style: talking head, screencast, voiceover with visuals, mixed?
Step 2: Write the Hook (First 30 Seconds)
The hook determines whether viewers watch or leave. Structure it as three beats:
## HOOK [0:00 - 0:30]
### Beat 1: Pattern Interrupt [0:00 - 0:05]
**[VISUAL: [Eye-catching opening shot / bold text on screen / unexpected image]]**
[Speaker:]
"[Bold opening: a surprising stat, contrarian claim, or provocative question]"
Examples:
- Stat: "90% of startups fail because of one mistake. And you're probably making it right now."
- Contrarian: "Everything you've been taught about [topic] is wrong."
- Question: "What if I told you that [common approach] is actually hurting your [outcome]?"
- Demo: "Watch this." [Show the end result before explaining how]
### Beat 2: Promise [0:05 - 0:15]
[Speaker:]
"In this video, I'm going to show you [specific outcome].
By the end, you'll know exactly how to [tangible result]."
### Beat 3: Credibility [0:15 - 0:30]
[Speaker:]
"[Brief credibility: I've [done X] / helped [N] people / spent [time] researching this].
And I'm going to break down [the framework / the exact steps / what actually works]."
**[VISUAL: Quick montage of proof: screenshots, results, credentials]]**
Hook rules:
- Pattern interrupt first, break expectations within 5 seconds
- Promise must be specific, "how to grow your channel" is vague; "how to get your first 1,000 subscribers in 30 days" is specific
- Credibility is 1-2 sentences max, prove you're worth listening to, then move on
- Never start with "Hey guys, welcome back to my channel": earn the intro first
- Total hook: under 30 seconds
Step 3: Structure with Retention Techniques
Build the body using techniques that maintain watch time:
Open Loops
Plant unanswered questions that pay off later:
[Speaker:]
"Now, there are three strategies that work, but the third one is the one that
changed everything for me. I'll get to that in a minute. First, let's talk about..."
Open loop placement:
- Drop an open loop at the end of the hook (tease something coming later)
- Plant 1-2 mid-video loops before major sections
- Always close loops before the video ends: broken promises kill trust
Pattern Breaks
Change the visual or audio rhythm every 60-90 seconds to reset attention:
| Break Type | When to Use | Example |
|---|---|---|
| B-roll cut | Every 30-60 seconds of talking head | Show the thing being discussed |
| On-screen text | Key stats, definitions, lists | Bold text highlighting the main point |
| Camera angle change | Every 2-3 minutes | Switch between close-up and medium shot |
| Music shift | Section transitions | Background music changes mood |
| Direct address | When making a key point | Look directly at camera, pause, then speak |
| Screen recording | Tutorial/demo sections | Switch from talking head to screen |
Visual Cues
Script what appears on screen alongside dialogue:
[Speaker:] "There are three types of content that perform on YouTube."
**[ON SCREEN: "3 Content Types" in bold text]**
[Speaker:] "Number one: tutorials."
**[ON SCREEN: "1. Tutorials" with icon]**
**[B-ROLL: Quick clips of tutorial-style content]**
Step 4: Write Body Sections
Each section follows a retention-optimized structure:
## SECTION 1: [Topic] [1:00 - 4:00]
### Transition In
[Speaker:]
"[Bridge from previous section, use a question or callback]
So now that you understand [previous concept], let's talk about [this section]."
**[VISUAL: Section title card or transition graphic]**
### Content
[Speaker:]
"[Key point, state it directly in one sentence]
[Explanation, break down why this matters, 2-3 sentences]
[Example: specific, concrete illustration]
**[ON SCREEN: [Visual that supports the example: screenshot, diagram, code]]**
[Actionable step, what the viewer should do with this information]"
### Open Loop / Transition Out
[Speaker:]
"[Tease next section or callback to open loop]
But here's where it gets interesting, in the next section,
I'll show you [what makes this 10x more effective]."
**[VISUAL: Quick preview of next section's visual]**
Body section writing rules:
- State the key point first, then explain, don't build up to it
- One idea per section, don't combine multiple concepts
- Include a specific example for every abstract concept
- Script visual cues inline, don't leave visuals to post-production guesswork
- End every section with a transition that pulls viewers into the next
Pacing by video length:
| Video Length | Sections | Time per Section | Pattern Breaks |
|---|---|---|---|
| 5-8 minutes | 3 | 1.5-2 min each | Every 45-60 sec |
| 10-15 minutes | 4-5 | 2-3 min each | Every 60-90 sec |
| 20+ minutes | 6-8 | 2.5-3.5 min each | Every 60-90 sec |
Step 5: Write Section Transitions
Transitions keep viewers watching through section boundaries (where most drop-off happens):
Transition formulas:
| Type | Template | When to Use |
|---|---|---|
| Question bridge | "So [recap], but you might be wondering, [question]?" | After explaining a concept |
| Contrast bridge | "That was [method A]. But [method B] takes it further." | Between two related ideas |
| Stakes bridge | "If you skip this next part, [negative consequence]." | Before the most important section |
| Curiosity bridge | "This next technique is the one most people get wrong." | Before a counterintuitive point |
| Progress bridge | "We've covered [X and Y]. Now for the final piece: [Z]." | After the midpoint of the video |
Transition rules:
- Never use "Moving on..." or "Next, let's talk about...", these signal a stopping point
- Every transition should create a reason to keep watching (question, promise, stakes)
- Transitions are 1-2 sentences max: long transitions lose momentum
Step 6: Write CTA and Outro
## CTA + OUTRO [final 30-60 seconds]
### Payoff / Summary
[Speaker:]
"[Close any remaining open loops: deliver what was promised]
So to recap: [3 bullet points summarizing the actionable takeaways]"
**[ON SCREEN: Summary graphic with 3 key points]**
### Call to Action
[Speaker:]
"[Primary CTA: one specific action:]"
- Subscribe: "If this helped you, hit subscribe. I post [frequency] about [topic]."
- Link: "I put together a [resource], the link is in the description below."
- Next video: "If you want to go deeper on [topic], watch this video next."
**[ON SCREEN: End screen card pointing to next video]**
"[Secondary CTA: lower commitment:]"
- "Drop a comment below: what's your biggest challenge with [topic]?"
- "Like this video if you learned something, it helps more people find it."
### Outro
[Speaker:]
"Thanks for watching. See you in the next one."
**[VISUAL: End screen with subscribe button and recommended video, 15-20 seconds]**
CTA rules:
- One primary CTA, don't ask for subscribe AND like AND comment AND click the link
- Place CTA after delivering value, not before (reciprocity)
- The "next video" CTA feeds YouTube's session watch time metric: use it
- End screens must be planned in the script, they require 20 seconds of screen time
Step 7: Write SEO Metadata
## SEO Metadata
### Title (60 characters max)
[Primary keyword + promise + hook element]
Title formulas:
- "How to [Outcome] in [Timeframe] ([Year])"
- "[Number] [Topic] Mistakes You're Making Right Now"
- "I Tried [Thing] for [Duration]: Here's What Happened"
- "[Topic] Explained in [Time] Minutes"
### Description (first 2 lines visible without expand)
Line 1: [Restate the video promise, what they'll learn]
Line 2: [CTA, link to resource, timestamps below]
[Line break]
Timestamps:
0:00, Intro
0:30, [Section 1 title]
[X:XX], [Section 2 title]
[X:XX], [Section 3 title]
[X:XX]: [Final section / CTA]
[Line break]
[Links to resources mentioned in the video]
[Social media links]
[Related videos]
### Tags (10-15)
[Primary keyword], [variation 1], [variation 2], [related topic 1],
[related topic 2], [channel name], [series name if applicable]
SEO rules:
- Title: include primary keyword in first 40 characters
- Description: first 2 lines are visible in search: front-load the value
- Timestamps create chapters in YouTube, use them for videos over 5 minutes
- Tags help YouTube understand the topic, use your primary keyword and variations
Step 8: Thumbnail Concept
## Thumbnail Concept
**Layout:** [Describe the visual composition]
**Text:** [3-5 words max on the thumbnail: large, readable at mobile size]
**Emotion:** [What expression/mood: surprise, curiosity, excitement, concern]
**Colors:** [High contrast, avoid YouTube's red/white/black to stand out]
**Thumbnail rules:**
- Must be readable at 120x68 pixels (mobile size)
- Max 3-5 words of text, if you need more, the concept isn't clear enough
- Face with emotion outperforms no-face by 30%+ CTR
- High contrast between background, text, and subject
- Avoid red/white/black (YouTube's brand colors): use complementary colors
- The thumbnail should tell a different story than the title (complement, don't repeat)
**Example concept:**
[Face showing surprise/curiosity] + [Bold text: "STOP DOING THIS"] + [Relevant object/screenshot]
Step 9: Output Complete Script
# YouTube Script: [Video Title]
**Topic:** [topic]
**Target viewer:** [audience]
**Video length:** ~[minutes] minutes
**Style:** [talking head / screencast / mixed]
---
## HOOK [0:00 - 0:30]
[Hook content]
## SECTION 1: [Title] [0:30 - X:XX]
[Section content with visual directions]
## SECTION 2: [Title] [X:XX - X:XX]
[Section content with visual directions]
## SECTION 3: [Title] [X:XX - X:XX]
[Section content with visual directions]
## CTA + OUTRO [X:XX - X:XX]
[CTA and outro content]
---
## SEO Metadata
[Title, description with timestamps, tags]
## Thumbnail Concept
[Visual description]
---
Output summary:
🎬 YouTube Script: Complete
Title: [title] ([character count] chars)
Length: ~[minutes] minutes ([word count] words at 150 wpm)
Sections: [count] + hook + outro
Open loops: [count] planted, [count] closed
Pattern breaks: [count] scripted
B-roll suggestions: [count]
SEO:
✅ Title under 60 chars with keyword
✅ Description with timestamps
✅ Tags: [count]
✅ Thumbnail concept defined
Retention techniques used:
✅ Pattern interrupt hook (first 5 sec)
✅ Open loops across sections
✅ Pattern breaks every 60-90 sec
✅ Transition bridges between sections
✅ End screen CTA with next video
Next steps:
1. Rehearse the hook, nail the first 30 seconds
2. Design the thumbnail before filming
3. Prepare B-roll and screen recordings
4. Film, edit, upload with metadata
5. Publish at peak time for your audience
Level History
- Lv.1: Base: Topic gathering, 30-second hook (pattern interrupt / promise / credibility), retention techniques (open loops, pattern breaks, visual cues), section transitions, CTA with end screen, SEO metadata (60 char title, timestamps, tags), thumbnail concept. Based on YouTube Growth Guide N.I.C.E.R. framework. (Origin: MemStack Pro v3.2, Mar 2026)
🔄 CI/CD Pipeline: Continuous Integration & Deployment
Detect project type and generate a complete CI/CD pipeline with lint, test, build, deploy stages, rollback strategy, and environment management.
Activation
When this skill activates, output:
🔄 CI/CD Pipeline: Designing your pipeline...
| Context | Status |
|---|---|
| User says "CI/CD", "pipeline", "GitHub Actions" | ACTIVE |
| User wants automated testing and deployment | ACTIVE |
| User mentions branch strategy, deploy gates, or rollbacks | ACTIVE |
| User wants Docker setup (CI/CD is secondary) | DORMANT: see docker-setup |
| User wants server provisioning (not pipeline) | DORMANT: see hetzner-setup |
| User wants to deploy to a specific platform only | DORMANT, see railway-deploy or netlify-deploy |
Protocol
Step 1: Gather Inputs
Ask the user for:
- Project type: Node.js, Python, Go, Rust, monorepo?
- Testing framework: Jest, Vitest, Pytest, Go test?
- Deployment target: Vercel, Railway, Netlify, Hetzner VPS, AWS, Docker registry?
- Current CI/CD: Any existing pipeline, or starting from scratch?
- Branch strategy: Trunk-based, GitFlow, or custom?
- Team size: Solo dev, small team, or large team?
Step 2: Detect Project & Recommend Platform
Auto-detect from project files and recommend CI/CD platform:
| Project Signal | Platform Recommendation | Reason |
|---|---|---|
.github/ exists | GitHub Actions | Already on GitHub, native integration |
vercel.json or Next.js | Vercel (auto-deploy) + GitHub Actions (CI) | Vercel handles deploy, GHA handles testing |
railway.json | Railway (auto-deploy) + GitHub Actions (CI) | Railway handles deploy, GHA handles testing |
netlify.toml | Netlify (auto-deploy) + GitHub Actions (CI) | Netlify handles deploy, GHA handles testing |
| Dockerfile present | GitHub Actions → Docker registry → deploy | Full control pipeline |
Monorepo (packages/) | GitHub Actions with matrix/path filters | Need per-package CI |
| Self-hosted server | GitHub Actions → SSH deploy | Push-based deployment |
Default recommendation: GitHub Actions: free for public repos, 2,000 min/month for private.
Step 3: Design Pipeline Stages
Define the stage sequence:
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ LINT │──→│ TEST │──→│ BUILD │──→│ DEPLOY │──→│ VERIFY │
│ │ │ │ │ │ │ │ │ │
│ ESLint │ │ Unit │ │ Compile │ │ Push to │ │ Health │
│ Prettier│ │ Integ. │ │ Bundle │ │ target │ │ Smoke │
│ Types │ │ E2E │ │ Docker │ │ env │ │ Rollback│
└─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘
│ │ │ │ │
Fail fast Gate: block Artifacts Env-specific Auto-rollback
< 1 min if < 80% cached secrets on failure
Stage details:
| Stage | Trigger | Failure Action | Duration Target |
|---|---|---|---|
| Lint | Every push, every PR | Block merge | < 1 min |
| Test | Every push, every PR | Block merge | < 5 min |
| Build | PR merge to main/develop | Block deploy | < 3 min |
| Deploy | Build passes on target branch | Alert + rollback | < 2 min |
| Verify | After deploy completes | Auto-rollback | < 1 min |
Step 4: Branch Strategy
Recommended: Simplified GitFlow
main (production)
├── develop (staging)
│ ├── feature/add-auth
│ ├── feature/dashboard
│ └── fix/login-bug
└── hotfix/critical-fix (→ main + develop)
| Branch | Deploys To | CI Runs | Auto-Deploy? |
|---|---|---|---|
feature/* | none | Lint + Test | No |
develop | Staging | Lint + Test + Build + Deploy | Yes |
main | Production | Lint + Test + Build + Deploy | Yes (or manual gate) |
hotfix/* | none | Lint + Test | No (merge to main to deploy) |
Branch protection rules:
main:
- Require PR review (1+ approvals)
- Require status checks (lint, test, build)
- No force push
- No direct push
develop:
- Require status checks (lint, test)
- Allow direct push (for solo devs)
- No force push
Step 5: Environment Variable Management
── ENVIRONMENT VARIABLES ──────────────────
Three environments with escalating secrets:
LOCAL (.env.local, never committed):
DATABASE_URL=postgresql://localhost:5432/app_dev
API_KEY=dev_test_key
NODE_ENV=development
STAGING (GitHub Secrets / platform env):
DATABASE_URL=[staging DB connection string]
API_KEY=[staging API key]
NODE_ENV=staging
PRODUCTION (GitHub Secrets / platform env):
DATABASE_URL=[production DB connection string]
API_KEY=[production API key]
NODE_ENV=production
Secret management rules:
- Never hardcode secrets in pipeline config
- Use GitHub Environments for per-branch secrets
- Use
GITHUB_TOKENfor GitHub operations (auto-provided) - Rotate secrets quarterly
- Audit secret access in GitHub Settings → Secrets → Audit log
GitHub Environments setup:
Repository → Settings → Environments:
staging:
Secrets: DATABASE_URL, API_KEY
Deployment branches: develop
production:
Secrets: DATABASE_URL, API_KEY
Deployment branches: main
Required reviewers: [team member] (optional gate)
Step 6: Generate Pipeline Config
GitHub Actions: Node.js project:
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm run typecheck # If TypeScript
test:
name: Test
runs-on: ubuntu-latest
needs: lint
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- uses: actions/upload-artifact@v4
if: always()
with:
name: coverage-report
path: coverage/
build:
name: Build
runs-on: ubuntu-latest
needs: test
if: github.event_name == 'push'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: build-output
path: dist/
deploy-staging:
name: Deploy to Staging
runs-on: ubuntu-latest
needs: build
if: github.ref == 'refs/heads/develop'
environment: staging
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: build-output
path: dist/
# Platform-specific deploy step here
# Option A: Railway
# - uses: bervProject/railway-deploy@main
# with:
# railway_token: ${{ secrets.RAILWAY_TOKEN }}
# Option B: SSH deploy to VPS
# - uses: appleboy/ssh-action@v1
# with:
# host: ${{ secrets.SERVER_HOST }}
# username: deploy
# key: ${{ secrets.SSH_PRIVATE_KEY }}
# port: 2222
# script: |
# cd /opt/app && git pull && npm ci --production && pm2 restart all
deploy-production:
name: Deploy to Production
runs-on: ubuntu-latest
needs: build
if: github.ref == 'refs/heads/main'
environment: production
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: build-output
path: dist/
# Same deploy pattern as staging but with production env
verify:
name: Verify Deployment
runs-on: ubuntu-latest
needs: [deploy-staging, deploy-production]
if: always() && (needs.deploy-staging.result == 'success' || needs.deploy-production.result == 'success')
steps:
- name: Health check
run: |
URL="${{ github.ref == 'refs/heads/main' && secrets.PRODUCTION_URL || secrets.STAGING_URL }}"
for i in 1 2 3 4 5; do
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL/health")
if [ "$STATUS" = "200" ]; then
echo "Health check passed"
exit 0
fi
echo "Attempt $i: HTTP $STATUS, retrying in 10s..."
sleep 10
done
echo "Health check failed after 5 attempts"
exit 1
GitHub Actions: Python project:
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install ruff mypy
- run: ruff check .
- run: mypy .
test:
runs-on: ubuntu-latest
needs: lint
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
ports: ['5432:5432']
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
cache: 'pip'
- run: pip install -r requirements.txt
- run: pytest --cov --cov-report=xml
env:
DATABASE_URL: postgresql://test:test@localhost:5432/testdb
build-and-deploy:
runs-on: ubuntu-latest
needs: test
if: github.event_name == 'push'
steps:
- uses: actions/checkout@v4
# Docker build + push or direct deploy
Step 7: Deployment Rollback Strategy
Automated rollback on failed health check:
rollback:
name: Rollback on Failure
runs-on: ubuntu-latest
needs: verify
if: failure()
steps:
- name: Rollback deployment
run: |
echo "Deployment verification failed: rolling back"
# Option A: Revert to previous Docker image
# docker pull $REGISTRY/app:previous && docker tag $REGISTRY/app:previous $REGISTRY/app:latest
# Option B: Railway rollback
# railway rollback
# Option C: Git revert + redeploy
# git revert HEAD --no-edit && git push
- name: Notify team
run: |
curl -X POST "${{ secrets.SLACK_WEBHOOK }}" \
-H 'Content-Type: application/json' \
-d '{"text":"🔴 Deployment rolled back, health check failed on ${{ github.ref }}"}'
Rollback strategies by deployment target:
| Target | Rollback Method | Speed | Data Safety |
|---|---|---|---|
| Vercel | Instant rollback in dashboard or CLI | Instant | Safe: immutable deploys |
| Railway | railway rollback or dashboard | Instant | Safe: previous deploy preserved |
| Netlify | Deploy previous build in dashboard | Instant | Safe: immutable deploys |
| Docker | Tag previous image as latest, restart | Seconds | Safe: images preserved |
| VPS/PM2 | git revert + pm2 restart | Minutes | Check DB migrations first |
| Kubernetes | kubectl rollout undo | Seconds | Check DB migrations first |
Database migration caution:
- If the deploy includes DB migrations, rollback is complex
- Always write reversible migrations (
up+down) - Test
downmigration before deployingup - Consider: deploy DB migration separately from code deploy
Step 8: Notifications
Slack notification on deploy:
notify:
name: Notify
runs-on: ubuntu-latest
needs: [deploy-staging, deploy-production, verify]
if: always()
steps:
- name: Send Slack notification
env:
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
run: |
if [ "${{ needs.verify.result }}" = "success" ]; then
EMOJI="✅"
STATUS="succeeded"
else
EMOJI="🔴"
STATUS="failed"
fi
curl -X POST "$SLACK_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{
\"text\": \"${EMOJI} Deploy ${STATUS}\",
\"blocks\": [
{
\"type\": \"section\",
\"text\": {
\"type\": \"mrkdwn\",
\"text\": \"${EMOJI} *Deploy ${STATUS}*\nBranch: \`${{ github.ref_name }}\`\nCommit: \`${{ github.sha }}\`\nBy: ${{ github.actor }}\"
}
}
]
}"
Alternative notification channels:
- GitHub Actions built-in: Email on failure (Settings → Notifications)
- Discord webhook: Same curl pattern, different payload format
- PagerDuty: For production failures that need on-call response
Step 9: Output
Present the complete CI/CD configuration:
━━━ CI/CD PIPELINE ━━━━━━━━━━━━━━━━━━━━━━━
Project: [name]
Platform: GitHub Actions
Deploy target: [platform]
Branch strategy: [strategy]
── PIPELINE STAGES ────────────────────────
Lint → Test → Build → Deploy → Verify
[stage diagram with timing]
── BRANCH STRATEGY ────────────────────────
[branch → environment mapping]
[protection rules]
── ENVIRONMENT VARIABLES ──────────────────
[per-environment secret setup]
── PIPELINE CONFIG ────────────────────────
[complete .github/workflows/ci-cd.yml]
── ROLLBACK STRATEGY ──────────────────────
[per-target rollback method]
[database migration caution]
── NOTIFICATIONS ──────────────────────────
[Slack/Discord/email setup]
── SETUP CHECKLIST ────────────────────────
[ ] Create .github/workflows/ directory
[ ] Add pipeline YAML file
[ ] Configure GitHub Environments (staging, production)
[ ] Add secrets to each environment
[ ] Set branch protection rules
[ ] Configure notification webhook
[ ] Test pipeline with a feature branch PR
[ ] Verify staging deploy on develop merge
[ ] Verify production deploy on main merge
Inputs
- Project type and language
- Testing framework
- Deployment target
- Branch strategy preference
- Team size
- Existing CI/CD (if any)
Outputs
- Pipeline stage design with timing targets
- Branch strategy with protection rules
- Environment variable management per stage
- Complete CI/CD config file (GitHub Actions YAML)
- Deployment rollback strategy per target
- Notification setup (Slack, Discord, email)
- Setup checklist for first-time configuration
Level History
- Lv.1: Base: Auto-detect project type, 5-stage pipeline (lint/test/build/deploy/verify), GitHub Actions configs for Node.js and Python, simplified GitFlow branch strategy, environment variable management with GitHub Environments, automated rollback on health check failure, Slack notifications, setup checklist. (Origin: MemStack v3.2, Mar 2026)
🐳 Docker Setup: Container Configuration Generator
Analyze a project and generate optimized Dockerfiles, docker-compose configs, and deployment-ready container setups with health checks and volume management.
Activation
When this skill activates, output:
🐳 Docker Setup: Containerizing your project...
| Context | Status |
|---|---|
| User says "Docker", "Dockerfile", "docker-compose" | ACTIVE |
| User wants to containerize their application | ACTIVE |
| User mentions multi-stage builds, Docker optimization, or .dockerignore | ACTIVE |
| User wants CI/CD with Docker (pipeline focus) | DORMANT: see ci-cd-pipeline |
| User wants server provisioning with Docker installed | DORMANT: see hetzner-setup |
| User wants Kubernetes orchestration | DORMANT: beyond current scope |
Protocol
Step 1: Gather Inputs
Ask the user for:
- Project type: Node.js, Python, Go, Rust, static site?
- Purpose: Local development, production deployment, or both?
- Services needed: Database (PostgreSQL, MySQL), cache (Redis), queue (RabbitMQ)?
- Build artifacts: Does the project compile to a binary or run interpreted?
- Environment: Where will containers run? (local, VPS, cloud container service)
Step 2: Analyze Project & Generate Dockerfile
Detect project type from files and generate an optimized multi-stage Dockerfile:
Node.js (multi-stage):
# Stage 1: Install dependencies
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --ignore-scripts
# Stage 2: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Stage 3: Production
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Security: run as non-root
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 appuser
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/package.json ./
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]
Python (multi-stage):
# Stage 1: Build
FROM python:3.12-slim AS builder
WORKDIR /app
RUN pip install --no-cache-dir --upgrade pip
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
# Stage 2: Production
FROM python:3.12-slim AS runner
WORKDIR /app
# Security: run as non-root
RUN groupadd --gid 1001 appgroup && \
useradd --uid 1001 --gid appgroup --shell /bin/false appuser
COPY --from=builder /install /usr/local
COPY --chown=appuser:appgroup . .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Go (minimal final image):
# Stage 1: Build
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server .
# Stage 2: Production (scratch, smallest possible image)
FROM scratch AS runner
COPY --from=builder /app/server /server
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD ["/server", "healthcheck"]
ENTRYPOINT ["/server"]
Next.js (standalone output):
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 appuser
COPY --from=builder --chown=appuser:appgroup /app/.next/standalone ./
COPY --from=builder --chown=appuser:appgroup /app/.next/static ./.next/static
COPY --from=builder --chown=appuser:appgroup /app/public ./public
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=15s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/ || exit 1
CMD ["node", "server.js"]
Step 3: Generate .dockerignore
# Dependencies
node_modules/
.pnp
.pnp.js
# Build output (built inside container)
dist/
build/
.next/
out/
# Environment files (secrets)
.env
.env.local
.env.*.local
# Version control
.git
.gitignore
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS files
.DS_Store
Thumbs.db
# Docker (prevent recursive copy)
Dockerfile
docker-compose*.yml
.dockerignore
# Testing & development
coverage/
*.test.js
*.spec.js
__tests__/
.nyc_output/
# Documentation
README.md
CHANGELOG.md
docs/
# CI/CD
.github/
.gitlab-ci.yml
Step 4: Generate docker-compose.yml
Development compose (app + database + cache):
# docker-compose.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
target: builder # Use builder stage for dev (with dev dependencies)
ports:
- '3000:3000'
environment:
- NODE_ENV=development
- DATABASE_URL=postgresql://postgres:postgres@db:5432/app_dev
- REDIS_URL=redis://redis:6379
volumes:
- .:/app
- /app/node_modules # Prevent overwriting container node_modules
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
restart: unless-stopped
db:
image: postgres:16-alpine
ports:
- '5432:5432'
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_dev
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- '6379:6379'
volumes:
- redis_data:/data
healthcheck:
test: ['CMD', 'redis-cli', 'ping']
interval: 10s
timeout: 5s
retries: 5
command: redis-server --appendonly yes
volumes:
postgres_data:
redis_data:
Production compose:
# docker-compose.prod.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile
target: runner # Production stage
ports:
- '3000:3000'
env_file:
- .env.production
depends_on:
db:
condition: service_healthy
restart: always
deploy:
resources:
limits:
memory: 512M
cpus: '1.0'
reservations:
memory: 256M
cpus: '0.5'
db:
image: postgres:16-alpine
env_file:
- .env.production
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U $${POSTGRES_USER}']
interval: 10s
timeout: 5s
retries: 5
restart: always
deploy:
resources:
limits:
memory: 1G
volumes:
postgres_data:
driver: local
Step 5: Environment Variable Handling
── ENVIRONMENT STRATEGY ───────────────────
Development (.env, local only, gitignored):
DATABASE_URL=postgresql://postgres:postgres@db:5432/app_dev
REDIS_URL=redis://redis:6379
API_KEY=dev_key_not_real
NODE_ENV=development
Production (.env.production, on server, never in repo):
DATABASE_URL=postgresql://user:STRONG_PASS@db:5432/app_prod
REDIS_URL=redis://:STRONG_PASS@redis:6379
API_KEY=prod_real_key
NODE_ENV=production
Docker env var priority (highest to lowest):
docker run -e VAR=value(command line)environment:in docker-compose.ymlenv_file:in docker-compose.ymlENVin Dockerfile (build-time defaults only)
Secrets handling:
- Never put secrets in Dockerfile
ENV(visible in image layers) - Use
env_filefor production (file on server, not in repo) - For CI/CD: inject via
docker run -efrom pipeline secrets - Consider Docker Secrets for Swarm/production deployments
Step 6: Health Check Configuration
Design health checks for each service:
── HEALTH CHECKS ──────────────────────────
App:
Endpoint: GET /health
Response: { "status": "ok", "db": "connected", "redis": "connected" }
Interval: 30s
Timeout: 3s
Start period: 10s (allow app to boot)
Retries: 3
PostgreSQL:
Command: pg_isready -U postgres
Interval: 10s
Timeout: 5s
Retries: 5
Redis:
Command: redis-cli ping
Interval: 10s
Timeout: 5s
Retries: 5
Application health endpoint implementation:
// GET /health
app.get('/health', async (req, res) => {
const checks = {
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
};
try {
await db.query('SELECT 1');
checks.db = 'connected';
} catch {
checks.db = 'disconnected';
checks.status = 'degraded';
}
try {
await redis.ping();
checks.redis = 'connected';
} catch {
checks.redis = 'disconnected';
checks.status = 'degraded';
}
const statusCode = checks.status === 'ok' ? 200 : 503;
res.status(statusCode).json(checks);
});
Step 7: Image Optimization
Optimization techniques applied:
| Technique | Impact | Applied In |
|---|---|---|
| Multi-stage build | 50-80% smaller image | Separate build/run stages |
| Alpine base | ~5MB vs ~100MB base | node:20-alpine vs node:20 |
| Non-root user | Security hardening | USER appuser in final stage |
| Layer caching | Faster rebuilds | Copy package.json before source |
| .dockerignore | Smaller build context | Exclude node_modules, .git, docs |
| Minimal final stage | Only runtime files | No dev deps, no source in prod |
| Combined RUN | Fewer layers | Chain apt commands with && |
Image size comparison:
| Approach | Typical Size | Notes |
|---|---|---|
node:20 (no optimization) | ~1 GB | Full Debian + dev tools |
node:20-slim | ~200 MB | Slim Debian |
node:20-alpine (multi-stage) | ~80-150 MB | Alpine + app only |
Go with scratch | ~5-20 MB | Binary only, no OS |
Python slim (multi-stage) | ~100-200 MB | Slim + deps only |
Check image size:
docker images | grep app
# Or detailed layer analysis:
docker history app:latest
Step 8: Networking
Development networking:
# docker-compose.yml, services on same default network
# Access between services by service name:
# app → db:5432, app → redis:6379
Production networking:
# Explicit network for isolation
networks:
frontend:
driver: bridge
backend:
driver: bridge
services:
app:
networks: [frontend, backend] # Talks to proxy AND database
db:
networks: [backend] # Only accessible from app
redis:
networks: [backend] # Only accessible from app
nginx:
networks: [frontend] # Only talks to app
ports: ['80:80', '443:443'] # Exposed to internet
Port exposure rules:
- Development: Expose DB/Redis ports for local tools (DBeaver, RedisInsight)
- Production: Only expose HTTP/HTTPS through reverse proxy
- Never expose database ports in production compose
- Use
127.0.0.1:5432:5432instead of5432:5432to restrict to localhost
Step 9: Volume Management
── VOLUMES ────────────────────────────────
Persistent data (named volumes):
postgres_data → /var/lib/postgresql/data (DB files)
redis_data → /data (Redis AOF/RDB)
uploads → /app/uploads (User uploads)
Development bind mounts:
.:/app → Live code reloading
/app/node_modules → Prevent host overwriting container deps
Backup volumes:
docker run --rm -v postgres_data:/data -v $(pwd):/backup \
alpine tar czf /backup/postgres_backup.tar.gz /data
Volume backup script:
#!/bin/bash
# Backup all named volumes
DATE=$(date +%F)
BACKUP_DIR="/opt/backups/docker"
mkdir -p "$BACKUP_DIR"
for VOLUME in $(docker volume ls -q); do
docker run --rm \
-v "$VOLUME":/source:ro \
-v "$BACKUP_DIR":/backup \
alpine tar czf "/backup/${VOLUME}_${DATE}.tar.gz" -C /source .
done
# Cleanup backups older than 14 days
find "$BACKUP_DIR" -type f -mtime +14 -delete
Step 10: Output
Present the complete Docker setup:
━━━ DOCKER SETUP ━━━━━━━━━━━━━━━━━━━━━━━━━
Project: [name]
Type: [language/framework]
Services: [app, db, redis, etc.]
── DOCKERFILE ─────────────────────────────
[complete multi-stage Dockerfile]
Final image size: ~[X] MB
── .DOCKERIGNORE ──────────────────────────
[complete .dockerignore]
── DOCKER-COMPOSE (Development) ───────────
[docker-compose.yml with dev services]
Start: docker compose up -d
Logs: docker compose logs -f app
Stop: docker compose down
── DOCKER-COMPOSE (Production) ────────────
[docker-compose.prod.yml]
Start: docker compose -f docker-compose.prod.yml up -d
── ENVIRONMENT ────────────────────────────
[env var strategy per environment]
── HEALTH CHECKS ──────────────────────────
[per-service health check config]
── NETWORKING ─────────────────────────────
[network topology for dev and prod]
── VOLUMES ────────────────────────────────
[persistent data + backup strategy]
── USEFUL COMMANDS ────────────────────────
Build: docker compose build
Start: docker compose up -d
Logs: docker compose logs -f
Shell: docker compose exec app sh
Rebuild: docker compose up -d --build
Clean: docker system prune -f
Inputs
- Project type and language
- Required services (database, cache, queue)
- Development vs production needs
- Deployment target
- Existing Dockerfile (if any)
Outputs
- Optimized multi-stage Dockerfile (Node.js, Python, Go, or Next.js)
- .dockerignore with comprehensive exclusions
- docker-compose.yml for development (app + services)
- docker-compose.prod.yml for production (with resource limits)
- Environment variable strategy per environment
- Health check configuration for all services
- Image optimization summary with size comparison
- Network topology (dev: open, prod: isolated)
- Volume management with backup script
- Quick-reference command cheat sheet
Level History
- Lv.1: Base: Multi-stage Dockerfiles (Node.js, Python, Go, Next.js), docker-compose for dev and prod, .dockerignore, environment variable strategy, health checks, image optimization (Alpine, layer caching, non-root user), network isolation, volume management with backups. (Origin: MemStack v3.2, Mar 2026)
🔒 Domain & SSL: Verifying domain, DNS, and certificate configuration...
Validates DNS records, SSL certificates, redirects, HSTS, and domain health across all managed properties.
Activation
When this skill activates, output:
🔒 Domain & SSL: Running domain health checks...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "check domain" or "setup domain" | ACTIVE |
| User says "SSL certificate" or "fix SSL" or "check DNS" | ACTIVE |
| Setting up a new domain for a deployed project | ACTIVE |
| Checking domain expiration or renewal status | ACTIVE |
| User is writing code, not managing infrastructure | DORMANT |
| Discussing domain names abstractly (brainstorming names) | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "SSL auto-renews, I don't need to check it" | Auto-renewal fails silently when DNS changes. Verify quarterly. |
| "DNS propagation takes 48 hours" | Most propagation happens in minutes. If it's been 2+ hours, something is misconfigured. |
| "www and non-www both work, that's fine" | Pick one canonical URL and redirect the other. Duplicate content hurts SEO and splits analytics. |
| "HTTPS is enough for security" | Without HSTS, the first request can still be intercepted. HSTS tells browsers to never try HTTP. |
| "I'll check the domain when it stops working" | By then, your site is down. Monitor expiration, SSL, and DNS proactively. |
Protocol
Step 1: Verify DNS Records
Check that DNS records are correctly configured for the target domain:
# A records (points domain to IP)
dig +short A example.com
# CNAME records (points subdomain to another domain)
dig +short CNAME www.example.com
# TXT records (verification, SPF, DKIM)
dig +short TXT example.com
# MX records (email routing, check for conflicts)
dig +short MX example.com
# NS records (authoritative nameservers)
dig +short NS example.com
Expected patterns by hosting provider:
| Provider | Record Type | Value |
|---|---|---|
| Railway | CNAME | *.up.railway.app |
| Netlify | CNAME | *.netlify.app or A record to 75.2.60.5 |
| Vercel | CNAME | cname.vercel-dns.com or A record to 76.76.21.21 |
| Cloudflare (proxied) | A | Cloudflare IPs (check dashboard) |
Check for conflicts:
- ❌ A record AND CNAME on the same subdomain, CNAME takes precedence, A is ignored
- ❌ Multiple A records pointing to different providers: causes random routing
- ❌ Missing TXT record for domain verification: some providers require this
Flag if: DNS records don't match the expected hosting provider configuration.
Step 2: Check SSL Certificate Status
# Check SSL certificate details
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates -subject -issuer
# Check certificate chain
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -text | grep -E "Issuer:|Not Before:|Not After:|Subject:"
# Quick expiration check
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -enddate
Verify:
- ✅ Certificate is valid (not expired)
- ✅ Certificate covers the correct domain(s): check Subject Alternative Names
- ✅ Certificate chain is complete (no missing intermediates)
- ✅ Auto-renewal is configured (Let's Encrypt certs expire every 90 days)
- ✅ Certificate issuer matches expected provider (Let's Encrypt, Cloudflare, AWS ACM)
Renewal timeline:
| Days Until Expiry | Status | Action |
|---|---|---|
| > 30 days | ✅ Healthy | No action |
| 15 to 30 days | ⚠️ Warning | Verify auto-renewal is working |
| < 15 days | ❌ Critical | Manually trigger renewal immediately |
| Expired | 🚨 Down | Site showing security warnings to visitors |
Step 3: Verify www vs non-www Redirect
Pick one canonical form and redirect the other:
# Test non-www → www (or vice versa)
curl -sI http://example.com | grep -i "location"
curl -sI http://www.example.com | grep -i "location"
curl -sI https://example.com | grep -i "location"
curl -sI https://www.example.com | grep -i "location"
Expected redirect chain (non-www canonical):
http://www.example.com → 301 → https://example.com
http://example.com → 301 → https://example.com
https://www.example.com → 301 → https://example.com
https://example.com → 200 (canonical)
Verify:
- ✅ Only ONE canonical URL returns 200, all others 301 redirect to it
- ✅ Redirects use 301 (permanent), not 302 (temporary), 301 is cacheable and SEO-friendly
- ✅ Redirect chain is at most 1 hop (http://www → https://apex, not http://www → https://www → https://apex)
- ❌ Both www and non-www return 200: duplicate content, split SEO
Step 4: Check HSTS Headers
HTTP Strict Transport Security prevents SSL stripping attacks:
# Check for HSTS header
curl -sI https://example.com | grep -i "strict-transport-security"
Expected:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
| Directive | Purpose |
|---|---|
max-age=31536000 | Browser remembers to use HTTPS for 1 year |
includeSubDomains | Applies to all subdomains too |
preload | Eligible for browser HSTS preload list (permanent HTTPS) |
Warning: preload is hard to undo. Only add it if you're committed to HTTPS permanently. Removing it requires submitting to the HSTS preload removal list and waiting for browser updates.
Flag if: No HSTS header present, or max-age is too short (< 6 months / 15768000).
Step 5: Verify DNS Propagation
After making DNS changes, verify propagation across global nameservers:
# Check propagation from multiple DNS resolvers
for dns in 8.8.8.8 1.1.1.1 208.67.222.222 9.9.9.9; do
echo "=== $dns ==="
dig +short A example.com @$dns
done
| DNS Resolver | Provider |
|---|---|
8.8.8.8 | |
1.1.1.1 | Cloudflare |
208.67.222.222 | OpenDNS |
9.9.9.9 | Quad9 |
Also check: dnschecker.org for worldwide propagation view.
Propagation timeline:
| Record Type | Typical Propagation | Max Propagation |
|---|---|---|
| A / AAAA | 5 to 30 minutes | 48 hours |
| CNAME | 5 to 30 minutes | 48 hours |
| TXT | 5 to 60 minutes | 48 hours |
| NS | 24 to 48 hours | 72 hours |
| MX | 1 to 4 hours | 48 hours |
Flag if: Different DNS resolvers return different values after 2+ hours, likely a TTL issue or misconfigured record.
Step 6: Check for Mixed Content
Mixed content (HTTP resources loaded on HTTPS pages) triggers browser security warnings:
# Scan built output for http:// references
grep -rn "http://" dist/ build/ out/ public/ 2>/dev/null | grep -v "http://localhost\|http://127\|http://schemas\|http://www.w3.org\|http://xmlns" | head -20
# Check HTML for mixed content
grep -rn 'src="http://\|href="http://\|url("http://' dist/ build/ out/ public/ 2>/dev/null | head -20
# Check for hardcoded HTTP API endpoints
grep -rn "http://" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . | grep -v node_modules | grep -v "localhost\|127\.0\.0\|schemas\|w3\.org\|xmlns" | head -20
Common mixed content sources:
- ❌ Hardcoded
http://image URLs, change tohttps://or protocol-relative// - ❌ Third-party scripts loaded over HTTP, update to HTTPS CDN URL
- ❌ API endpoints using
http://: update tohttps:// - ❌ CSS
url()references withhttp://: update tohttps:// - ✅
http://localhostin development code, acceptable, won't appear in production build
Flag if: Any http:// references found in production build output (excluding localhost and XML namespaces).
Step 7: Domain Monitoring Checklist
Proactive monitoring prevents surprise outages:
# Check WHOIS for expiration (if whois is available)
whois example.com | grep -i "expir"
# Quick SSL expiry check
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -enddate
| Check | Frequency | What to Verify |
|---|---|---|
| Domain expiration | Monthly | Auto-renew enabled, registrar payment method valid |
| SSL certificate | Monthly | Valid, auto-renewing, > 30 days until expiry |
| DNS records | After any change | Records match expected values, propagation complete |
| HSTS header | Quarterly | Present with adequate max-age |
| Mixed content | After deploys | No HTTP resources on HTTPS pages |
| Registrar access | Quarterly | Login works, 2FA enabled, recovery email current |
| Nameserver delegation | After registrar changes | NS records point to correct DNS provider |
Domain inventory: track for each property:
Domain: example.com
Registrar: [Namecheap / GoDaddy / Cloudflare / Google Domains]
Auto-renew: [Yes / No]
Expires: [YYYY-MM-DD]
DNS provider: [Cloudflare / Registrar / Route53]
SSL issuer: [Let's Encrypt / Cloudflare / ACM]
Hosting: [Railway / Netlify / Vercel]
Canonical: [https://example.com]
Step 8: Multi-Domain and Wildcard Setup
For projects with multiple domains or subdomains:
Wildcard SSL:
# Check if wildcard cert is installed
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -text | grep "DNS:"
Wildcard certs (*.example.com) cover all subdomains at one level:
- ✅ Covers:
app.example.com,api.example.com,www.example.com - ❌ Does NOT cover:
example.com(apex): need separate SAN entry - ❌ Does NOT cover:
staging.api.example.com(two levels deep)
Subdomain routing patterns:
| Pattern | DNS Record | Points To |
|---|---|---|
app.example.com | CNAME | Frontend hosting (Netlify/Vercel) |
api.example.com | CNAME | Backend hosting (Railway) |
docs.example.com | CNAME | Docs hosting (GitBook/Notion) |
mail.example.com | MX + CNAME | Email provider |
*.example.com | CNAME | Catch-all (if needed) |
Multi-domain for same project:
When multiple domains point to the same app (e.g., deedstack.com and www.deedstack.com):
- Set one as canonical (return 200)
- All others 301 redirect to canonical
- Each domain needs its own SSL certificate (or use a multi-SAN cert)
- Update
Content-Security-Policyand CORS origins to include all domains
Output domain health report:
🔒 Domain & SSL: Health Report
Domain: example.com
DNS: ✅ A record → 76.76.21.21 (Vercel)
SSL: ✅ Let's Encrypt, expires 2026-05-15 (75 days)
HSTS: ✅ max-age=31536000; includeSubDomains
Redirect: ✅ www → apex (301)
HTTPS force: ✅ http → https (301)
Mixed content: ✅ none detected
Registrar: Cloudflare (auto-renew ON, expires 2027-01-20)
Subdomains:
app.example.com → ✅ Netlify (SSL valid)
api.example.com → ✅ Railway (SSL valid)
No issues found. Next check recommended: 2026-04-01
Level History
- Lv.1: Base: DNS verification, SSL certificate checks, www/non-www redirects, HSTS validation, DNS propagation testing, mixed content scanning, domain monitoring checklist, multi-domain/wildcard setup. Based on managing adminstack.pro, epsteinscan.org, deedstack.com, and related properties. (Origin: MemStack Pro v3.2, Mar 2026)
🖥️ Hetzner Setup: VPS Provisioning & Deployment
Provision a Hetzner Cloud server with security hardening, reverse proxy, SSL, database setup, monitoring, and automated backups.
Activation
When this skill activates, output:
🖥️ Hetzner Setup: Provisioning your server...
| Context | Status |
|---|---|
| User says "Hetzner", "VPS setup", "server provisioning" | ACTIVE |
| User wants to deploy to a cloud server (Hetzner specifically) | ACTIVE |
| User mentions SSH hardening, fail2ban, or server security | ACTIVE |
| User wants Docker containerization guidance | DORMANT: see docker-setup |
| User wants CI/CD pipeline (not server setup) | DORMANT: see ci-cd-pipeline |
| User wants managed hosting (Railway, Netlify, Vercel) | DORMANT, see railway-deploy or netlify-deploy |
Protocol
Step 1: Gather Inputs
Ask the user for:
- Workload type: Web app, API, database, scraper, background worker?
- Expected traffic: Low (< 1k/day), medium (1k-50k/day), high (50k+/day)?
- Stack: Node.js, Python, Go, Rust? Docker or direct?
- Database needs: PostgreSQL, MySQL, Redis, none?
- Domain: Do you have a domain to point at this server?
- Budget preference: Minimum viable or room to grow?
Step 2: Recommend Instance Type
Match workload to Hetzner Cloud server:
| Instance | vCPU | RAM | SSD | Traffic | Price | Best For |
|---|---|---|---|---|---|---|
| CX22 | 2 | 4 GB | 40 GB | 20 TB | ~$4.5/mo | Small API, static site, hobby project |
| CX32 | 4 | 8 GB | 80 GB | 20 TB | ~$8/mo | Medium web app, small DB |
| CPX31 | 4 | 8 GB | 160 GB | 20 TB | ~$13/mo | High-perf apps (AMD EPYC), scrapers |
| CPX41 | 8 | 16 GB | 240 GB | 20 TB | ~$24/mo | Large apps, multiple services |
| CPX51 | 16 | 32 GB | 360 GB | 20 TB | ~$47/mo | Heavy workloads, large databases |
| CCX13 | 2 | 8 GB | 80 GB | 20 TB | ~$13/mo | Dedicated vCPU: consistent performance |
Recommendation logic:
- Scraper/background worker → CPX31 (AMD EPYC, burst-friendly)
- Web app with DB → CX32 or CPX31 (depends on traffic)
- API-heavy service → CPX31 (fast single-thread)
- Multiple services → CPX41 (headroom for containers)
- Budget-constrained → CX22 (surprisingly capable)
Include: location recommendation (Nuremberg for EU, Ashburn for US).
Step 3: Initial Server Setup Script
Generate a complete setup script:
#!/bin/bash
# Hetzner Server Initial Setup
# Run as root on fresh Ubuntu 22.04/24.04 LTS
set -euo pipefail
echo "=== SYSTEM UPDATE ==="
apt update && apt upgrade -y
apt install -y curl wget git htop ufw fail2ban unattended-upgrades \
apt-listchanges software-properties-common
echo "=== CREATE DEPLOY USER ==="
useradd -m -s /bin/bash deploy
mkdir -p /home/deploy/.ssh
cp /root/.ssh/authorized_keys /home/deploy/.ssh/
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys
usermod -aG sudo deploy
# Set password for sudo (optional, SSH key preferred)
echo "deploy ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/deploy
echo "=== SSH HARDENING ==="
cat > /etc/ssh/sshd_config.d/hardened.conf << 'SSHEOF'
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers deploy
SSHEOF
systemctl restart sshd
echo "=== FIREWALL (UFW) ==="
ufw default deny incoming
ufw default allow outgoing
ufw allow 2222/tcp comment 'SSH'
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'
ufw --force enable
echo "=== FAIL2BAN ==="
cat > /etc/fail2ban/jail.local << 'F2BEOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400
F2BEOF
systemctl enable fail2ban
systemctl restart fail2ban
echo "=== UNATTENDED UPGRADES ==="
cat > /etc/apt/apt.conf.d/20auto-upgrades << 'UUEOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
UUEOF
echo "=== SWAP (for low-RAM instances) ==="
if [ $(free -m | awk '/^Mem:/{print $2}') -lt 8192 ]; then
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
sysctl vm.swappiness=10
echo 'vm.swappiness=10' >> /etc/sysctl.conf
fi
echo "=== KERNEL TUNING ==="
cat >> /etc/sysctl.conf << 'KERNEOF'
# Network performance
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
# Security
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
KERNEOF
sysctl -p
echo "=== SETUP COMPLETE ==="
echo "SSH port changed to 2222"
echo "Root login disabled"
echo "Deploy user created with SSH key"
echo "Firewall enabled (ports: 2222, 80, 443)"
echo "Fail2ban active"
echo "Unattended upgrades enabled"
IMPORTANT: After running this script, reconnect using:
ssh -p 2222 deploy@[server-ip]
Step 4: Application Deployment
Option A: Docker deployment (recommended):
# Install Docker
curl -fsSL https://get.docker.com | sh
usermod -aG docker deploy
# Install Docker Compose
apt install -y docker-compose-plugin
# Create app directory
mkdir -p /opt/app
chown deploy:deploy /opt/app
See docker-setup skill for Dockerfile and docker-compose.yml generation.
Option B: Direct deployment (Node.js example):
# Install Node.js via nvm
su - deploy
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.5/install.sh | bash
source ~/.bashrc
nvm install --lts
# Clone and setup
cd /opt/app
git clone [repo-url] .
npm ci --production
# PM2 process manager
npm install -g pm2
pm2 start ecosystem.config.js
pm2 save
pm2 startup
PM2 ecosystem config:
// ecosystem.config.js
module.exports = {
apps: [{
name: 'app',
script: 'dist/index.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 3000,
},
max_memory_restart: '500M',
error_file: '/var/log/app/error.log',
out_file: '/var/log/app/out.log',
merge_logs: true,
}],
};
Step 5: Reverse Proxy & SSL
Option A: Caddy (auto-SSL, simplest):
apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
apt update && apt install -y caddy
# /etc/caddy/Caddyfile
example.com {
reverse_proxy localhost:3000
encode gzip zstd
header {
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "SAMEORIGIN"
Referrer-Policy "strict-origin-when-cross-origin"
}
log {
output file /var/log/caddy/access.log
format json
}
}
Option B: Nginx + Certbot:
apt install -y nginx certbot python3-certbot-nginx
# /etc/nginx/sites-available/app
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Security headers
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}
# Get SSL certificate
certbot --nginx -d example.com
# Auto-renewal is configured automatically by certbot
Step 6: Database Setup
PostgreSQL:
apt install -y postgresql postgresql-contrib
sudo -u postgres createuser --interactive appuser
sudo -u postgres createdb appdb -O appuser
sudo -u postgres psql -c "ALTER USER appuser PASSWORD 'CHANGE_ME_STRONG_PASSWORD';"
# Listen only on localhost (default: safe)
# For remote access, use SSH tunnel, never expose port 5432
Redis:
apt install -y redis-server
# Secure Redis
sed -i 's/^# requirepass.*/requirepass CHANGE_ME_STRONG_PASSWORD/' /etc/redis/redis.conf
sed -i 's/^bind .*/bind 127.0.0.1 ::1/' /etc/redis/redis.conf
systemctl restart redis-server
Connection security:
- Databases should only listen on
127.0.0.1 - Use SSH tunnels for remote database access
- Never expose database ports to the internet
- Use strong, unique passwords stored in environment variables
Step 7: Monitoring
Resource monitoring script:
#!/bin/bash
# /opt/scripts/health-check.sh
# Disk usage alert (>85%)
DISK_USAGE=$(df / | awk 'NR==2{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 85 ]; then
echo "ALERT: Disk usage at ${DISK_USAGE}%"
# Send notification (webhook, email, etc.)
curl -X POST "https://hooks.slack.com/services/XXX" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"🔴 Disk usage at ${DISK_USAGE}% on $(hostname)\"}"
fi
# Memory usage alert (>90%)
MEM_USAGE=$(free | awk '/Mem:/{printf "%.0f", $3/$2 * 100}')
if [ "$MEM_USAGE" -gt 90 ]; then
echo "ALERT: Memory usage at ${MEM_USAGE}%"
curl -X POST "https://hooks.slack.com/services/XXX" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"🟡 Memory usage at ${MEM_USAGE}% on $(hostname)\"}"
fi
# Check if app is responding
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health)
if [ "$HTTP_CODE" != "200" ]; then
echo "ALERT: App health check failed (HTTP $HTTP_CODE)"
curl -X POST "https://hooks.slack.com/services/XXX" \
-H 'Content-Type: application/json' \
-d "{\"text\":\"🔴 App health check failed on $(hostname): HTTP ${HTTP_CODE}\"}"
fi
# Add to crontab: every 5 minutes
crontab -e
*/5 * * * * /opt/scripts/health-check.sh >> /var/log/health-check.log 2>&1
External uptime monitoring:
- UptimeRobot (free tier: 50 monitors, 5-min checks)
- Better Uptime / Hetrixtools (free alternatives)
- Monitor: HTTPS endpoint, SSL expiry, response time
Log management:
# Logrotate for application logs
cat > /etc/logrotate.d/app << 'LREOF'
/var/log/app/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
}
LREOF
Step 8: Backup Strategy
Hetzner snapshots (server-level):
# Create snapshot via Hetzner CLI
hcloud server create-image --type snapshot --description "Weekly backup $(date +%F)" [server-id]
# Automate weekly snapshots
# Add to crontab (Sunday 3 AM):
0 3 * * 0 hcloud server create-image --type snapshot --description "auto-$(date +\%F)" [server-id]
# Retention: Keep last 4 snapshots, delete older
# Snapshot cost: ~$0.012/GB/month
Database backups (daily):
#!/bin/bash
# /opt/scripts/backup-db.sh
BACKUP_DIR="/opt/backups/db"
RETENTION_DAYS=14
DATE=$(date +%F_%H%M)
mkdir -p "$BACKUP_DIR"
# PostgreSQL
pg_dump -U appuser -h localhost appdb | gzip > "$BACKUP_DIR/appdb_${DATE}.sql.gz"
# Optional: Upload to off-site storage (Hetzner Storage Box or S3)
# rsync -avz "$BACKUP_DIR/" u123456@u123456.your-storagebox.de:backups/
# Cleanup old backups
find "$BACKUP_DIR" -type f -mtime +${RETENTION_DAYS} -delete
echo "Backup complete: appdb_${DATE}.sql.gz"
# Daily at 2 AM
0 2 * * * /opt/scripts/backup-db.sh >> /var/log/backup.log 2>&1
Off-site backup options:
- Hetzner Storage Box: Cheap, same datacenter, rsync/SFTP
- Hetzner Object Storage: S3-compatible, good for large files
- Backblaze B2: Ultra-cheap cloud storage, S3-compatible
- BorgBackup: Deduplication, encryption, efficient for incremental backups
Step 9: Hardening Checklist
Final security hardening verification:
── SERVER HARDENING CHECKLIST ─────────────
SSH:
[x] Root login disabled
[x] Password authentication disabled
[x] SSH port changed from 22
[x] Key-based auth only
[x] MaxAuthTries set to 3
[x] Idle timeout configured
Firewall:
[x] UFW enabled with deny-by-default
[x] Only required ports open (SSH, HTTP, HTTPS)
[x] No database ports exposed
Services:
[x] Fail2ban active on SSH
[x] Unattended security upgrades enabled
[x] Unused services disabled
[x] No unnecessary packages installed
Application:
[x] App runs as non-root user (deploy)
[x] Environment variables for secrets (not in code)
[x] Database listens on localhost only
[x] Redis password set, localhost only
Monitoring:
[x] Disk/memory/CPU alerts configured
[x] App health check endpoint monitored
[x] External uptime monitoring active
[x] Log rotation configured
Backups:
[x] Database backed up daily
[x] Server snapshots weekly
[x] Off-site backup configured
[x] Backup restoration tested
Step 10: Output
Present the complete server setup:
━━━ HETZNER SERVER SETUP ━━━━━━━━━━━━━━━━━
Instance: [type], [vCPU] vCPU, [RAM] GB RAM
Location: [datacenter]
OS: Ubuntu [version] LTS
Cost: ~$[X]/mo
── PROVISIONING SCRIPT ────────────────────
[complete setup script]
── APPLICATION DEPLOYMENT ─────────────────
Method: [Docker / Direct]
Process manager: [Docker / PM2]
Config: [ecosystem.config.js or docker-compose.yml]
── REVERSE PROXY ──────────────────────────
Server: [Caddy / Nginx]
SSL: Let's Encrypt (auto-renewal)
Config: [Caddyfile or nginx.conf]
── DATABASE ───────────────────────────────
[PostgreSQL/Redis setup]
── MONITORING ─────────────────────────────
Internal: [health check script + cron]
External: [uptime monitoring service]
Alerts: [notification channel]
── BACKUPS ────────────────────────────────
Database: Daily, [retention] days
Snapshots: Weekly, last [N] kept
Off-site: [storage solution]
── HARDENING ──────────────────────────────
[checklist with status]
── DEPLOYMENT COMMANDS ────────────────────
[quick reference for common operations]
Inputs
- Workload type and expected traffic
- Application stack (language, framework)
- Database requirements
- Domain name
- Budget preference
Outputs
- Instance type recommendation with justification
- Complete server provisioning script (SSH hardening, firewall, fail2ban, unattended upgrades)
- Application deployment (Docker or direct with PM2)
- Reverse proxy config (Caddy or Nginx) with auto-SSL
- Database setup (PostgreSQL, Redis) with security
- Monitoring script with disk/memory/app health alerts
- Backup strategy (snapshots + database dumps + off-site)
- Server hardening checklist
- Deployment quick-reference commands
Level History
- Lv.1: Base: Hetzner instance selection matrix, full provisioning script (SSH hardening, UFW, fail2ban, unattended upgrades, swap, kernel tuning), Docker and direct deployment, Caddy/Nginx reverse proxy with auto-SSL, PostgreSQL/Redis setup, health monitoring with alerts, backup strategy (snapshots + DB dumps + off-site), hardening checklist. Based on CPX31 production experience. (Origin: MemStack v3.2, Mar 2026)
🌐 Netlify Deploy: Pre-flight check and deploy to Netlify...
Validates build config, redirects, environment variables, and deployment readiness for Netlify static/SPA hosting.
Activation
When this skill activates, output:
🌐 Netlify Deploy: Running pre-flight checks...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "deploy to netlify" or "netlify deploy" | ACTIVE |
| User says "deploy frontend" or "deploy static site" | ACTIVE |
| Preparing a React/Vue/Svelte/Next.js static export for hosting | ACTIVE |
| Deploying a backend service or API server | DORMANT: use railway-deploy |
| Discussing Netlify pricing or features generally | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "I'll configure it in the Netlify UI" | netlify.toml is version-controlled and portable. UI settings get lost across teams. |
| "Redirects work fine without _redirects" | SPA routing breaks on refresh without /* /index.html 200. Every SPA needs this. |
| "Environment vars are the same everywhere" | Build-time vars (baked into JS bundle) vs runtime vars (Netlify Functions) are different. NEXT_PUBLIC_ prefix exposes to client. |
| "The API proxy just works" | /api/* redirects must point to your actual backend URL. Forgetting to update after backend redeploy breaks the frontend. |
| "I'll check the deploy after pushing" | netlify deploy --build locally catches build failures before they hit production. Always build locally first. |
Protocol
Step 1: Check Build Configuration
Look for Netlify config and verify build settings:
# Check for Netlify configuration
ls netlify.toml _redirects _headers 2>/dev/null
# Check package.json for build script
cat package.json | grep -A2 '"scripts"' | grep '"build"'
If netlify.toml exists, verify it:
# Expected structure
[build]
command = "npm run build" # or "yarn build", "pnpm build"
publish = "dist" # or "build", "out", ".next" (varies by framework)
[build.environment]
NODE_VERSION = "20" # Pin Node version for reproducible builds
| Framework | Build Command | Publish Directory |
|---|---|---|
| React (CRA) | npm run build | build |
| React (Vite) | npm run build | dist |
| Next.js (static) | next build && next export | out |
| Vue | npm run build | dist |
| Svelte/SvelteKit | npm run build | build |
| Astro | npm run build | dist |
| Plain HTML | none | . or public |
Flag if: netlify.toml missing or publish directory doesn't match framework default.
Step 2: Verify Redirects and API Proxy
# Check redirect files
cat netlify.toml 2>/dev/null | grep -A5 '\[\[redirects\]\]'
cat _redirects 2>/dev/null
Check for the API proxy pattern (frontend → backend):
# netlify.toml, API proxy to Railway/external backend
[[redirects]]
from = "/api/*"
to = "https://your-backend.up.railway.app/api/:splat"
status = 200
force = true
Or in _redirects:
/api/* https://your-backend.up.railway.app/api/:splat 200
Verify:
- ✅ Backend URL is the production URL (not localhost)
- ✅
status = 200(proxy, not redirect, preserves the URL for the client) - ✅
force = trueif the proxy should override static files at the same path - ❌ Backend URL still points to
localhost:3000: update to production
Flag if: Code references /api/ paths but no proxy redirect is configured.
Step 3: Verify SPA Routing
Single-page apps need a catch-all redirect so deep links and page refreshes work:
# Check for SPA redirect
grep -r "\/\*.*\/index\.html\|\/\*.*200" netlify.toml _redirects 2>/dev/null
Required for SPAs (React Router, Vue Router, etc.):
# In _redirects (must be LAST rule, order matters)
/* /index.html 200
Or in netlify.toml:
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Flag if: Project uses client-side routing but no catch-all redirect exists. Symptoms: pages work when navigated to via links, but return 404 on direct URL access or refresh.
Note: Next.js static export handles this differently. Each page is pre-rendered as its own HTML file. SPA redirect is NOT needed for static Next.js.
Step 4: Verify Environment Variables
# Find env vars used in frontend code
grep -rn "process\.env\.\|import\.meta\.env\.\|VITE_\|NEXT_PUBLIC_\|REACT_APP_" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . | grep -v node_modules
Build-time vs runtime separation:
| Prefix | Framework | When Available | Exposed to Client? |
|---|---|---|---|
REACT_APP_ | CRA | Build time | ⚠️ YES: baked into JS bundle |
NEXT_PUBLIC_ | Next.js | Build time | ⚠️ YES: baked into JS bundle |
VITE_ | Vite | Build time | ⚠️ YES: baked into JS bundle |
| No prefix | Any | Build time only | ❌ No, server-side/build scripts only |
Critical security check:
# Search for secrets that might be exposed to client
grep -rn "NEXT_PUBLIC_.*SECRET\|NEXT_PUBLIC_.*KEY\|VITE_.*SECRET\|REACT_APP_.*SECRET" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.env*" . | grep -v node_modules
Flag if: Any secret (API keys with write access, database URLs, auth secrets) uses a client-exposed prefix. These are baked into the JavaScript bundle and visible to anyone who opens DevTools.
Output: List each variable with where to set it:
- Netlify UI: Site Settings → Environment Variables (for secrets)
netlify.toml[build.environment](for non-sensitive build config likeNODE_VERSION)
Step 5: Check Custom Domain and SSL
# Check for domain configuration
cat netlify.toml 2>/dev/null | grep -A5 '\[context\]'
Verify in Netlify dashboard:
- ✅ Custom domain added (Domain Management → Add domain)
- ✅ DNS points to Netlify (CNAME to
*.netlify.appor A record to Netlify load balancer) - ✅ SSL certificate provisioned (automatic via Let's Encrypt: check HTTPS section)
- ✅ Force HTTPS enabled (redirects http → https)
- ✅ www redirect configured (www → apex or apex → www: pick one, be consistent)
Flag if: Domain is added but DNS hasn't propagated or SSL shows "Waiting for DNS verification."
Step 6: Check for Netlify Functions
# Check for serverless functions
ls netlify/functions/ functions/ 2>/dev/null
cat netlify.toml 2>/dev/null | grep 'functions'
If functions exist, verify:
- Function directory is specified in
netlify.toml:[functions] directory = "netlify/functions" - Functions have correct export pattern:
export const handler = async (event, context) => { ... } - Environment variables needed by functions are set in Netlify dashboard (these are runtime, not build-time)
- Functions are not importing large dependencies that exceed Netlify's 50MB bundle limit
Step 7: Check Headers Configuration
# Check for security headers
cat netlify.toml 2>/dev/null | grep -A10 '\[\[headers\]\]'
cat _headers 2>/dev/null
Recommended security headers:
# netlify.toml
[[headers]]
for = "/*"
[headers.values]
X-Frame-Options = "DENY"
X-Content-Type-Options = "nosniff"
Referrer-Policy = "strict-origin-when-cross-origin"
Permissions-Policy = "camera=(), microphone=(), geolocation=()"
Step 8: Pre-Deploy Checklist
Build locally to catch errors before Netlify builds:
# Local build test
npm run build
# Check output directory exists and has content
ls -la dist/ # or build/, out/, etc.
# Check for common issues
grep -rn "http://localhost\|http://127\.0\.0\.1" dist/ 2>/dev/null
| Check | Command | Pass Criteria |
|---|---|---|
| Build passes | npm run build | Exit code 0, no errors |
| Output directory exists | ls dist/ | Has index.html and assets |
| No localhost in build | grep dist/ for localhost | Zero matches |
| _redirects in output | ls dist/_redirects | Exists if using _redirects approach |
| Env vars documented | Check .env.example | All client vars listed |
| No secrets in client code | grep for exposed secrets | Zero matches |
| Git clean | git status | All changes committed |
Output pre-deploy summary:
🌐 Netlify Deploy: Pre-flight Complete
Project: [name] ([framework])
Build: ✅ passes → [publish directory]
Redirects: ✅ SPA routing + API proxy configured
Env vars: ✅ 8 build-time vars, no secrets exposed
Domain: ✅ [domain] with SSL
Functions: ✅ 2 functions in netlify/functions/
Headers: ✅ security headers configured
Ready to deploy.
Preview: netlify deploy --build
Production: netlify deploy --build --prod
Step 9: Post-Deploy Verification
After deployment completes:
- Preview deploy: Netlify generates a unique URL for every deploy: test there first
- Check build log: Netlify dashboard → Deploys → click deploy → Build Log
- Test SPA routing: Navigate directly to a deep route (e.g.,
/dashboard/settings): should load, not 404 - Test API proxy: Open DevTools Network tab, trigger an API call, verify it reaches backend
- Check SSL: Visit
https://[domain], padlock should appear, no mixed content warnings - Test redirects: Visit
http://[domain]: should redirect tohttps://
Rollback plan:
- Netlify keeps every deploy as an immutable snapshot
- Dashboard → Deploys → click any previous deploy → "Publish deploy"
- Instant rollback, no rebuild required
Level History
- Lv.1: Base: Build config validation, redirect/proxy verification, SPA routing, env var security audit, domain/SSL checks, Netlify Functions, security headers, pre/post-deploy checklists. Based on AdminStack marketing site, GreenAcres frontend, and other Netlify deployments. (Origin: MemStack Pro v3.2, Mar 2026)
🚂 Railway Deploy: Pre-flight check and deploy to Railway...
Validates project configuration, environment variables, and deployment readiness before pushing to Railway.
Activation
When this skill activates, output:
🚂 Railway Deploy: Running pre-flight checks...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "deploy to railway" or "railway deploy" | ACTIVE |
| User says "ship it" or "deploy backend" with a Railway project | ACTIVE |
| Preparing a backend/fullstack app for production | ACTIVE |
| Deploying to Netlify, Vercel, or other non-Railway platform | DORMANT |
| Discussing Railway pricing or features generally | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
"I'll just railway up and see what happens" | Pre-flight catches 90% of deploy failures. Check first. |
| "Environment vars are probably fine" | Missing vars are the #1 cause of Railway deploy failures. Verify every one. |
| "It works locally so it'll work on Railway" | localhost URLs, SQLite paths, and file:// references all break in production. |
| "I'll fix the Dockerfile later" | Railway's nixpacks auto-detect fails on monorepos and custom setups. Define build explicitly. |
| "The database connection works" | Railway internal networking uses *.railway.internal hostnames. External URLs add latency and cost. |
Protocol
Step 1: Detect Project Type
Identify the project framework and runtime:
# Check for framework indicators
ls package.json pyproject.toml requirements.txt Cargo.toml go.mod 2>/dev/null
| Indicator | Project Type |
|---|---|
package.json with next | Next.js |
package.json with express/fastify/hono | Node.js API |
pyproject.toml or requirements.txt | Python (Django/Flask/FastAPI) |
Cargo.toml | Rust |
go.mod | Go |
Report: Detected: [type] project
Step 2: Check Deployment Files
Verify Railway can build the project:
# Check for explicit build configuration
ls Dockerfile Procfile nixpacks.toml railway.toml 2>/dev/null
| File | Purpose | Required? |
|---|---|---|
Dockerfile | Explicit container build | Recommended for complex projects |
Procfile | Process start command | Optional if start script exists |
nixpacks.toml | Nixpacks build config | Optional: auto-detected |
railway.toml | Railway-specific settings | Optional: build/deploy overrides |
If none exist, check that nixpacks can auto-detect:
- Node.js:
package.jsonmust havestartscript ormainfield - Python: Must have
requirements.txtorpyproject.tomlwith dependencies
Flag if missing: No build configuration found. Recommend adding railway.toml or Dockerfile.
Step 3: Verify Environment Variables
Cross-reference what the app needs vs what Railway has:
# Find required env vars
cat .env.example .env.sample 2>/dev/null | grep -v '^#' | grep '=' | cut -d= -f1
Check for these common categories:
| Category | Variables to Verify |
|---|---|
| Database | DATABASE_URL, POSTGRES_URL, REDIS_URL, MONGODB_URI |
| Auth | JWT_SECRET, SESSION_SECRET, NEXTAUTH_SECRET, NEXTAUTH_URL |
| External APIs | STRIPE_SECRET_KEY, SENDGRID_API_KEY, AWS_ACCESS_KEY_ID |
| App Config | NODE_ENV=production, PORT (Railway sets this automatically) |
| URLs | FRONTEND_URL, BACKEND_URL, CORS_ORIGIN |
Output: List each variable with status:
- ✅ Set in
.env.example, verify it's configured in Railway dashboard - ⚠️ Referenced in code but not in
.env.example: add to Railway - ❌ Hardcoded value found: extract to environment variable
Remind user: "Set these in Railway dashboard → Variables tab. Never commit actual values."
Step 4: Verify Build and Start Commands
# Node.js
cat package.json | grep -A2 '"scripts"' | grep -E '"(build|start|dev)"'
# Python
cat Procfile 2>/dev/null || cat pyproject.toml 2>/dev/null | grep -A5 '\[tool.poetry.scripts\]'
Verify:
- Build command exists and produces output (e.g.,
npm run build→dist/or.next/) - Start command uses production mode (not
devornodemon) - Port reads from
process.env.PORToros.environ["PORT"]: Railway assigns this dynamically
Flag if: Start command uses hardcoded port (e.g., app.listen(3000) without PORT env fallback).
Step 5: Verify Database Connection Strings
If the project uses a database:
# Search for connection patterns
grep -r "localhost:5432\|localhost:3306\|localhost:6379\|127.0.0.1" --include="*.ts" --include="*.js" --include="*.py" --include="*.env*" .
Railway internal networking rules:
- ✅
${{Postgres.DATABASE_URL}}: Railway reference variable - ✅
*.railway.internal:5432, internal hostname (no egress cost) - ❌
localhost:5432, won't resolve in Railway container - ❌ Public Railway URL with port, adds latency, uses egress bandwidth
Flag if: Any hardcoded localhost or 127.0.0.1 database URLs found.
Step 6: Check Health Check Endpoint
# Search for common health check patterns
grep -rn "\/health\|\/healthz\|\/api\/health\|\/readyz" --include="*.ts" --include="*.js" --include="*.py" .
If no health endpoint exists, recommend adding one:
// Express/Fastify pattern
app.get('/health', (req, res) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
});
Configure in Railway: Settings → Deploy → Health Check Path → /health
Step 7: Pre-Deploy Checklist
Run the build locally to catch errors before deploying:
# Build test
npm run build # or equivalent
# Search for localhost references
grep -rn "localhost\|127\.0\.0\.1" --include="*.ts" --include="*.js" --include="*.py" . | grep -v node_modules | grep -v .git
| Check | Command | Pass Criteria |
|---|---|---|
| Build passes | npm run build | Exit code 0, no errors |
| No hardcoded URLs | grep for localhost | Zero matches in source |
| Production env vars | Review .env.example | All vars documented |
| Port configuration | grep for PORT | Reads from env, not hardcoded |
| Node version | Check engines in package.json | Specified if needed |
| Git clean | git status | All changes committed |
Output pre-deploy summary:
🚂 Railway Deploy: Pre-flight Complete
Project: [name] ([type])
Build: ✅ passes
Env vars: ✅ 12 documented, verify in Railway dashboard
Database: ✅ uses Railway internal networking
Health check: ✅ /health endpoint configured
Localhost refs: ✅ none found
Port: ✅ reads from process.env.PORT
Ready to deploy. Run: railway up
Step 8: Post-Deploy Verification
After deployment completes:
- Health check:
curl https://[app].up.railway.app/health - Logs: Check Railway dashboard → Deployments → View Logs for startup errors
- Database: Verify migrations ran (check logs for migration output)
- Environment: Confirm
NODE_ENV=productionis active
Rollback plan:
- Railway keeps previous deployments. Go to Deployments → click previous successful deploy → Rollback
- Or via CLI:
railway rollback
If deploy fails:
- Check build logs first, dependency or build script errors
- Check runtime logs, missing env vars show as undefined/null errors
- Check health check timeout, app may be starting slowly (increase timeout in Settings)
- Verify Railway service is connected to correct GitHub branch
Level History
- Lv.1: Base: Project detection, env var verification, build validation, database connection checks, health endpoint, pre/post-deploy checklists. Based on AdminStack, DeedStack, AlgoStack, and EpsteinScan Railway deployments. (Origin: MemStack Pro v3.2, Mar 2026)
🔌 API Designer: Designing routes, validation, and handler patterns...
Produces production-ready Next.js App Router API routes with auth guards, Zod validation, typed responses, and consistent error handling.
Activation
When this skill activates, output:
🔌 API Designer, Designing API routes and handlers...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "design API" or "create API route" or "add endpoint" | ACTIVE |
| User says "REST API" or "route handler" | ACTIVE |
| Building a new feature that needs API routes | ACTIVE |
| Designing webhook endpoints | ACTIVE |
| Discussing API concepts or REST theory | DORMANT |
| Working on frontend components (not API layer) | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "Auth is handled by middleware" | Middleware can be bypassed. Every route handler must verify auth independently. |
| "I'll validate input later" | Unvalidated input is the root of injection, type errors, and 500s. Zod first, logic second. |
| "Return 200 for everything" | Status codes are the API contract. 401 vs 403 vs 404 vs 422 mean different things to clients. |
| "Error details help debugging" | Stack traces and internal errors help attackers. Return safe messages, log details server-side. |
| "Rate limiting is a nice-to-have" | Public endpoints without rate limits get abused within hours of deployment. |
| "TypeScript types are documentation enough" | Types exist at build time. Zod schemas validate at runtime. You need both. |
Protocol
Step 1: Design Route Structure
Map features to Next.js App Router file paths:
app/
api/
auth/
login/route.ts POST - authenticate user
logout/route.ts POST - clear session
callback/route.ts GET - OAuth callback
organizations/
route.ts GET - list user's orgs
POST - create org
[orgId]/
route.ts GET - get org details
PATCH - update org
DELETE - delete org
members/
route.ts GET - list members
POST - invite member
[memberId]/
route.ts PATCH - update role
DELETE - remove member
projects/
route.ts GET - list projects
POST - create project
webhooks/
stripe/route.ts POST - Stripe webhook
github/route.ts POST - GitHub webhook
Naming conventions:
| Convention | Rule | Example |
|---|---|---|
| Resource names | Plural nouns | /organizations, /projects |
| Dynamic segments | [paramName] camelCase | [orgId], [memberId] |
| Nested resources | Parent/child path | /organizations/[orgId]/projects |
| Actions (non-CRUD) | Verb sub-path | /auth/login, /reports/generate |
| Webhooks | /webhooks/{provider} | /webhooks/stripe |
Output route table:
Method Path Auth Description
GET /api/organizations ✅ List user's organizations
POST /api/organizations ✅ Create organization
GET /api/organizations/[orgId] ✅+org Get organization details
PATCH /api/organizations/[orgId] ✅+org Update organization
...
POST /api/webhooks/stripe 🔑sig Handle Stripe webhook
Step 2: Auth Guard Pattern
Every protected route starts with the same two-step auth chain:
import { getAuthContext } from '@/lib/auth';
import { verifyOrgAccess } from '@/lib/auth';
import { NextRequest, NextResponse } from 'next/server';
export async function GET(
req: NextRequest,
{ params }: { params: { orgId: string } }
) {
// Step 1: Authenticate: who is this user?
const auth = await getAuthContext(req);
if (!auth) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
);
}
// Step 2: Authorize, can they access this org?
const access = await verifyOrgAccess(auth.userId, params.orgId);
if (!access) {
return NextResponse.json(
{ error: 'Access denied' },
{ status: 403 }
);
}
// Now proceed with business logic...
}
Auth decision matrix:
| Route Type | Auth Required | Org Check | Example |
|---|---|---|---|
| Public | ❌ | ❌ | GET /api/health |
| Authenticated | ✅ | ❌ | GET /api/user/profile |
| Org-scoped | ✅ | ✅ | GET /api/organizations/[orgId]/projects |
| Admin-only | ✅ | ✅ + role check | DELETE /api/organizations/[orgId] |
| Webhook | 🔑 Signature | ❌ | POST /api/webhooks/stripe |
Step 3: Input Validation with Zod
Every route that accepts input validates it before any logic runs:
import { z } from 'zod';
// Define schema next to the route handler
const createProjectSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
status: z.enum(['draft', 'active', 'archived']).default('draft'),
settings: z.object({
isPublic: z.boolean().default(false),
tags: z.array(z.string().max(50)).max(10).default([]),
}).optional(),
});
type CreateProjectInput = z.infer<typeof createProjectSchema>;
export async function POST(req: NextRequest) {
// ... auth checks ...
// Validate input
const body = await req.json();
const parsed = createProjectSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Validation failed', details: parsed.error.flatten() },
{ status: 422 }
);
}
// parsed.data is fully typed as CreateProjectInput
const project = await createProject(parsed.data);
return NextResponse.json({ data: project }, { status: 201 });
}
Zod patterns for common fields:
// Reusable schemas
const paginationSchema = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
});
const sortSchema = z.object({
sortBy: z.string().default('created_at'),
sortOrder: z.enum(['asc', 'desc']).default('desc'),
});
const uuidParam = z.string().uuid('Invalid ID format');
// Query params validation (GET routes)
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const query = paginationSchema.merge(sortSchema).safeParse(
Object.fromEntries(searchParams)
);
// ...
}
Step 4: Consistent Response Format
All responses follow a strict structure:
// Success responses: always wrap in { data }
return NextResponse.json({ data: result });
return NextResponse.json({ data: results, meta: { total, page, limit } });
// Error responses: always wrap in { error }
return NextResponse.json({ error: 'Not found' }, { status: 404 });
return NextResponse.json(
{ error: 'Validation failed', details: zodError.flatten() },
{ status: 422 }
);
Type definitions for responses:
// types/api.ts
export type ApiResponse<T> = {
data: T;
meta?: {
total: number;
page: number;
limit: number;
};
};
export type ApiError = {
error: string;
details?: unknown;
};
// Helper function
export function apiSuccess<T>(data: T, status = 200): NextResponse {
return NextResponse.json({ data }, { status });
}
export function apiError(error: string, status: number, details?: unknown): NextResponse {
return NextResponse.json({ error, ...(details && { details }) }, { status });
}
Step 5: HTTP Status Codes
Use the correct status code for each situation:
| Code | Meaning | When to Use |
|---|---|---|
200 | OK | Successful GET, PATCH, or general success |
201 | Created | Successful POST that creates a resource |
204 | No Content | Successful DELETE (no response body) |
400 | Bad Request | Malformed request (invalid JSON, wrong Content-Type) |
401 | Unauthorized | Not authenticated (no token, expired session) |
403 | Forbidden | Authenticated but not authorized (wrong org, wrong role) |
404 | Not Found | Resource doesn't exist (or user can't see it, use 404 to avoid leaking existence) |
409 | Conflict | Duplicate resource (unique constraint violation) |
422 | Unprocessable Entity | Valid JSON but failed validation (Zod errors) |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Unexpected server error (log details, return safe message) |
Key distinction, 401 vs 403 vs 404:
401: "I don't know who you are" → redirect to login403: "I know who you are, but you can't do this" → show permission error404: "This doesn't exist (or you can't know it exists)" → use for privacy-preserving access denial
Step 6: Rate Limiting
Protect public and sensitive endpoints:
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '60 s'), // 10 requests per minute
analytics: true,
});
// In route handler
export async function POST(req: NextRequest) {
const ip = req.headers.get('x-forwarded-for') ?? 'anonymous';
const { success, limit, remaining, reset } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Rate limit exceeded. Try again later.' },
{
status: 429,
headers: {
'X-RateLimit-Limit': limit.toString(),
'X-RateLimit-Remaining': remaining.toString(),
'X-RateLimit-Reset': reset.toString(),
},
}
);
}
// Continue with handler...
}
Rate limit tiers:
| Endpoint Type | Limit | Window |
|---|---|---|
| Auth (login, register) | 5 requests | 15 minutes |
| Public API | 60 requests | 1 minute |
| Authenticated API | 120 requests | 1 minute |
| Webhooks | 1000 requests | 1 minute |
| File upload | 10 requests | 1 hour |
Step 7: Webhook Endpoints
Webhooks require signature verification instead of JWT auth:
import { headers } from 'next/headers';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: NextRequest) {
const body = await req.text(); // Raw body for signature verification
const signature = req.headers.get('stripe-signature');
if (!signature) {
return NextResponse.json({ error: 'Missing signature' }, { status: 400 });
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err) {
console.error('Webhook signature verification failed:', err);
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
// Process event by type
switch (event.type) {
case 'checkout.session.completed':
await handleCheckoutComplete(event.data.object);
break;
case 'customer.subscription.updated':
await handleSubscriptionUpdate(event.data.object);
break;
default:
console.log(`Unhandled event type: ${event.type}`);
}
// Always return 200 quickly, process async if needed
return NextResponse.json({ received: true });
}
Webhook rules:
- Always verify signatures before processing
- Return
200quickly: do heavy processing async - Use
req.text()notreq.json(), signature verification needs raw body - Log unhandled event types (don't error on them: providers add new events)
- Implement idempotency, webhooks can be sent multiple times
Step 8: Generate TypeScript Interfaces
Produce type definitions that match the API contract:
// types/api/organizations.ts
// Request types (match Zod schemas)
export interface CreateOrganizationRequest {
name: string;
slug?: string;
plan?: 'free' | 'starter' | 'professional' | 'enterprise';
}
export interface UpdateOrganizationRequest {
name?: string;
settings?: Partial<OrganizationSettings>;
}
// Response types (match database + API transforms)
export interface Organization {
id: string;
name: string;
slug: string;
plan: 'free' | 'starter' | 'professional' | 'enterprise';
createdAt: string; // ISO 8601
updatedAt: string;
}
export interface OrganizationWithMembers extends Organization {
members: OrganizationMember[];
memberCount: number;
}
// List response with pagination
export interface OrganizationListResponse {
data: Organization[];
meta: {
total: number;
page: number;
limit: number;
};
}
Type generation rules:
- Request types match Zod schemas (single source of truth)
- Response types match database models + any API transforms (e.g.,
snake_case→camelCase) - Use
stringfor dates in API types (ISO 8601 format over the wire) - Export all types from a barrel file:
types/api/index.ts
Step 9: Complete Route Handler Template
Full boilerplate for a standard CRUD route:
// app/api/organizations/[orgId]/projects/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getAuthContext, verifyOrgAccess } from '@/lib/auth';
import { apiSuccess, apiError } from '@/lib/api-response';
import { db } from '@/lib/db';
// --- Validation Schemas ---
const createProjectSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
});
const listQuerySchema = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
status: z.enum(['draft', 'active', 'archived']).optional(),
});
// --- GET /api/organizations/[orgId]/projects ---
export async function GET(
req: NextRequest,
{ params }: { params: { orgId: string } }
) {
try {
const auth = await getAuthContext(req);
if (!auth) return apiError('Authentication required', 401);
const access = await verifyOrgAccess(auth.userId, params.orgId);
if (!access) return apiError('Access denied', 403);
const query = listQuerySchema.safeParse(
Object.fromEntries(new URL(req.url).searchParams)
);
if (!query.success) return apiError('Invalid query', 422, query.error.flatten());
const { page, limit, status } = query.data;
const offset = (page - 1) * limit;
const [projects, total] = await Promise.all([
db.projects.list({ orgId: params.orgId, status, limit, offset }),
db.projects.count({ orgId: params.orgId, status }),
]);
return NextResponse.json({
data: projects,
meta: { total, page, limit },
});
} catch (error) {
console.error('GET /projects failed:', error);
return apiError('Internal server error', 500);
}
}
// --- POST /api/organizations/[orgId]/projects ---
export async function POST(
req: NextRequest,
{ params }: { params: { orgId: string } }
) {
try {
const auth = await getAuthContext(req);
if (!auth) return apiError('Authentication required', 401);
const access = await verifyOrgAccess(auth.userId, params.orgId);
if (!access) return apiError('Access denied', 403);
if (access.role === 'viewer') return apiError('Insufficient permissions', 403);
const body = await req.json();
const parsed = createProjectSchema.safeParse(body);
if (!parsed.success) return apiError('Validation failed', 422, parsed.error.flatten());
const project = await db.projects.create({
...parsed.data,
organizationId: params.orgId,
createdBy: auth.userId,
});
return apiSuccess(project, 201);
} catch (error) {
console.error('POST /projects failed:', error);
return apiError('Internal server error', 500);
}
}
Output summary:
🔌 API Designer: Routes Complete
Feature: [name]
Routes: [count] endpoints across [count] resource groups
Route Table:
Method Path Auth Status
GET /api/organizations ✅ List
POST /api/organizations ✅ Create
GET /api/organizations/[orgId] ✅+O Detail
...
Files to create:
- app/api/organizations/route.ts
- app/api/organizations/[orgId]/route.ts
- app/api/organizations/[orgId]/projects/route.ts
- lib/validations/organizations.ts (Zod schemas)
- types/api/organizations.ts (TypeScript interfaces)
Zod schemas: [count] request validators
Type definitions: [count] interfaces
Webhooks: [count] with signature verification
Rate-limited routes: [count]
Level History
- Lv.1: Base: Route structure design, auth guard chain (getAuthContext + verifyOrgAccess), Zod validation, consistent response format, HTTP status codes, rate limiting, webhook signature verification, TypeScript interfaces, full CRUD handler template. Based on AdminStack API patterns. (Origin: MemStack Pro v3.2, Mar 2026)
Changelog Generator: Generating changelog...
Produces a formatted CHANGELOG.md from git commit history, grouped by type and ready for release.
Activation
| Trigger | Status |
|---|---|
| User says "generate changelog" or "update changelog" | ACTIVE |
| User says "what changed" or "release notes" | ACTIVE |
| User says "write changelog" or "changelog since" | ACTIVE |
| User wants to view git log only | NOT this skill: use git commands directly |
| User wants a diary entry | NOT this skill: use Diary |
Context Guard
- Do NOT use for session logging (that's Diary)
- Do NOT use for commit message writing (that's a git workflow)
- Do NOT use for PR descriptions (that's a git workflow)
- This skill ONLY produces CHANGELOG.md content from existing commits
Steps
Step 1: Determine the range
Ask the user or infer from context:
| Parameter | Default | Example |
|---|---|---|
| Since tag/date | Last tag or last 7 days | v3.3.0, 2026-03-01 |
| Until | HEAD | v3.4.0, HEAD |
| Format | Keep a Changelog | Conventional, custom |
# Find the last tag
git describe --tags --abbrev=0 2>/dev/null || echo "No tags found"
# Get commits since last tag (or date)
git log --oneline --no-merges $(git describe --tags --abbrev=0 2>/dev/null || echo "HEAD~50")..HEAD
Step 2: Categorize commits
Parse each commit message and classify by prefix:
| Prefix | Category | Changelog Section |
|---|---|---|
feat: / feature: | Features | ### Added |
fix: / bugfix: | Bug Fixes | ### Fixed |
docs: | Documentation | ### Changed |
refactor: | Refactoring | ### Changed |
perf: | Performance | ### Changed |
test: | Tests | (omit unless user requests) |
chore: / build: / ci: | Maintenance | (omit unless user requests) |
BREAKING CHANGE or !: | Breaking | ### Breaking Changes |
| No prefix | Uncategorized | ### Other |
Step 3: Generate the changelog entry
Follow Keep a Changelog format:
## [version] - YYYY-MM-DD
### Breaking Changes
- Description of breaking change ([commit-hash])
### Added
- New feature description ([commit-hash])
### Fixed
- Bug fix description ([commit-hash])
### Changed
- Refactor/improvement description ([commit-hash])
Writing rules:
- Rewrite technical commit messages into user-facing language
- Group related commits into single entries where sensible
- Lead with the impact, not the implementation ("Users can now..." not "Added handler for...")
- Include short commit hash as reference
- Skip merge commits, version bumps, and trivial chores unless requested
- Order: Breaking Changes > Added > Fixed > Changed > Removed > Other
Step 4: Handle existing CHANGELOG.md
# Check if CHANGELOG.md exists
ls CHANGELOG.md 2>/dev/null
- If exists: prepend the new entry after the title line, before existing entries
- If not exists: create with header:
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/),
and this project adheres to [Semantic Versioning](https://semver.org/).
## [version] - YYYY-MM-DD
...
Step 5: Present for review
Changelog entry for [version] ([date]):
- [N] features added
- [N] bugs fixed
- [N] changes
- [N] breaking changes
Ready to write to CHANGELOG.md? (prepend / overwrite / clipboard only)
Disambiguation
- "generate changelog" / "update changelog" / "release notes" = Changelog Generator
- "save diary" / "log session" = Diary (not Changelog Generator)
- "what did we do" / "last session" = Echo (not Changelog Generator)
- "git log" / "show commits" = Direct git commands (not Changelog Generator)
Level History
- Lv.1: Base: Git-to-changelog with Keep a Changelog format, commit categorization by conventional commits prefix, user-facing rewriting, existing file handling. (Origin: MemStack v3.5, Apr 2026)
🔍 Code Reviewer: Reviewing code for issues and improvements...
Systematic code review across security, performance, maintainability, error handling, testing, and accessibility, with severity-ranked findings and specific fixes.
Activation
When this skill activates, output:
🔍 Code Reviewer: Scanning for issues...
Then execute the protocol below.
| Context | Status |
|---|---|
| User says "review code" or "code review" or "check my code" | ACTIVE |
| User says "audit this" or "review PR" or "review changes" | ACTIVE |
| User asks "what's wrong with this" about code | ACTIVE |
| Reviewing a specific file or set of changes | ACTIVE |
| User is writing code and hasn't asked for review | DORMANT |
| Discussing code architecture at a high level | DORMANT |
Anti-patterns
| Trap | Reality Check |
|---|---|
| "This looks fine to me" | Check every category systematically. Skimming misses auth gaps and N+1 queries. |
| "Style issues are important" | Linters handle style. Focus on logic, security, and correctness. |
| "I'll flag everything I see" | Noise kills reviews. Only report issues with real impact. Severity matters. |
| "The code works so it's fine" | Working does not mean correct. Race conditions, edge cases, and security holes all "work" until they don't. |
| "I'll suggest a complete rewrite" | Review what's there. Propose targeted fixes, not architectural overhauls. |
Severity Levels
| Level | Label | Meaning | Action |
|---|---|---|---|
| 🔴 | Critical | Security vulnerability, data loss risk, crash in production | Fix before merge |
| 🟠 | High | Bug, incorrect behavior, significant performance issue | Fix this sprint |
| 🟡 | Medium | Code smell, minor performance issue, missing edge case | Fix when touching the file |
| 🔵 | Low | Style preference, minor improvement, documentation gap | Consider for future |
Protocol
Step 1: Security Review
Scan for security vulnerabilities: this category takes priority.
Authentication gaps:
Search for route handlers and verify each has auth checks:
grep -rn "export async function\|export function" --include="*.ts" app/api/ | head -20
Flag these patterns:
- Route handler without auth check (e.g.,
getAuthContext) at the top - Org-scoped route without
verifyOrgAccess - Admin action without role verification
- Webhook endpoint without signature verification
Exposed secrets:
Search for hardcoded credentials:
grep -rn "sk_live\|sk_test\|password\s*=\s*['\"]" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.env" . | grep -v node_modules | grep -v .env.example
Flag these patterns:
- API keys or tokens hardcoded in source
.envfiles committed to git- Secrets in client-side code (
NEXT_PUBLIC_prefix on secret values) - Database connection strings in source files
Injection vulnerabilities:
Search for unsafe input handling:
grep -rn "\.raw(\|\.unsafeRaw\|innerHTML\s*=" --include="*.ts" --include="*.tsx" --include="*.js" . | grep -v node_modules
Flag these patterns:
- String concatenation in SQL queries (use parameterized queries)
- Unsafe HTML rendering with user-supplied content
- Unsanitized URL parameters used in redirects (open redirect)
- User input reflected in HTML without escaping (XSS)
Step 2: Performance Review
Identify patterns that degrade under load.
N+1 queries:
# Find loops that might contain database calls
grep -rn "\.forEach\|\.map\|for.*of\|for.*in" --include="*.ts" --include="*.tsx" . | grep -v node_modules | head -20
Flag these patterns:
- Database query inside a loop (fetch all in one query, then map)
awaitinside.map()withoutPromise.all()(sequential when it could be parallel)- Sequential
awaitcalls that could bePromise.all([...])(parallelizable)
Missing indexes:
- Foreign key columns without an index (causes slow JOINs)
- Columns used in
WHEREorORDER BYwithout indexes - Composite queries that need composite indexes
Frontend performance:
# Check for large imports that should be tree-shaken
grep -rn "import .* from ['\"]lodash['\"]" --include="*.ts" --include="*.tsx" . | grep -v node_modules
Flag these patterns:
- Full library imports instead of tree-shakeable imports (
import _ from 'lodash') - Large dependencies in client bundles (check with
next build --analyze) - Missing
React.memo,useMemo, oruseCallbackon expensive renders - Images without width/height or
next/imageoptimization - Unthrottled event handlers (scroll, resize, input without debounce)
Data fetching:
- Fetching more data than needed (SELECT * instead of specific columns)
- Missing pagination on list endpoints
- No caching on expensive, infrequently-changing queries
- Client-side fetching for data that could be server-rendered
Step 3: Maintainability Review
Evaluate code clarity and organization.
Dead code:
grep -rn "export " --include="*.ts" --include="*.tsx" . | grep -v node_modules | head -30
Flag these patterns:
- Functions/components that are never imported
- Commented-out code blocks (delete it: git has history)
- Unused variables, imports, or parameters
- Feature flags for features that shipped months ago
Duplicated logic:
- Same validation logic in multiple route handlers (extract to shared schema)
- Repeated auth patterns (extract to middleware or helper)
- Copy-pasted components with minor differences (extract shared component)
- Same error handling try/catch in every handler (extract to wrapper)
Naming clarity:
- Single-letter variables outside of loops (
d,x,t: what are these?) - Boolean variables without
is/has/shouldprefix (activevsisActive) - Functions that don't describe their action (
process(),handle(),doStuff()) - Inconsistent naming between related files (camelCase in one, snake_case in another)
Type safety:
anytype used where a specific type is known- Type assertions (
as Type) hiding real type errors - Missing return types on exported functions
@ts-ignoreor@ts-expect-errorwithout explanation
Step 4: Error Handling Review
Check that errors are caught and handled appropriately.
Uncaught promises:
grep -rn "await " --include="*.ts" --include="*.tsx" . | grep -v "try\|catch\|\.catch" | grep -v node_modules | head -20
Flag these patterns:
awaitcalls withouttry/catchin route handlers (returns 500 with no context).then()chains without.catch()(unhandled rejection)- Event handlers with
asyncbut no error boundary - Fire-and-forget promises (no
await, no.catch(), novoid)
Error quality:
- Generic
catch (e) { throw e }(adds nothing, let it propagate or add context) - Swallowed errors:
catch (e) {}(at minimum, log them) - Stack traces or internal details exposed to users in API responses
- Missing error boundaries in React component trees
Edge cases:
- No handling for empty arrays/null results from database queries
- No handling for network timeouts or external API failures
- No handling for concurrent modification (optimistic locking)
- No handling for file not found, permission denied, or disk full
Step 5: Testing Review
Assess test coverage for critical paths.
Untested critical paths:
- Auth flows (login, logout, token refresh) without tests
- Payment/billing logic without tests
- Data mutation endpoints (POST, PATCH, DELETE) without tests
- RLS policies without tests (test that users CAN'T access other orgs' data)
Missing edge cases:
- Only happy path tested (what about invalid input? empty data? max limits?)
- No tests for error responses (401, 403, 404, 422)
- No tests for boundary conditions (0 items, 1 item, max items)
- No tests for concurrent operations (race conditions)
Test quality:
- Tests that test implementation details instead of behavior
- Tests with no assertions (they "pass" but verify nothing)
- Flaky tests that depend on timing, external services, or test order
- Test data that doesn't represent realistic scenarios
Step 6: Accessibility Review
Check that UI code is usable by everyone.
Image and media:
<img>withoutaltattribute (screen readers announce nothing)- Decorative images without
alt=""(screen readers read the filename) - Video/audio without captions or transcripts
- Icon buttons without accessible labels
Keyboard navigation:
- Click handlers on non-interactive elements instead of
<button>(not keyboard accessible) - Custom dropdowns/modals without focus trapping
- No visible focus indicator on interactive elements
- Tab order that doesn't match visual layout
ARIA and semantics:
- Missing
aria-labelon icon-only buttons - Using generic elements for navigation instead of
<nav> - Form inputs without associated
<label>elements - Missing
roleattributes on custom interactive components - Live regions (toast notifications) without
aria-live
Color and contrast:
- Information conveyed by color alone (add icons or text)
- Low contrast text (below 4.5:1 ratio for normal text, below 3:1 for large text)
- Focus indicators that rely on color change alone
Step 7: Output Per-File Report
For each file reviewed, output findings grouped by file:
file: app/api/organizations/[orgId]/route.ts
🔴 Critical: No auth check on DELETE handler
Line 45: export async function DELETE(req) { ... }
Fix: Add getAuthContext + verifyOrgAccess + admin role check
```typescript
const auth = await getAuthContext(req);
if (!auth) return apiError('Authentication required', 401);
const access = await verifyOrgAccess(auth.userId, params.orgId);
if (!access || access.role !== 'owner') return apiError('Access denied', 403);
🟠 High: N+1 query in project listing Line 62: projects.map(async (p) => await getProjectMembers(p.id)) Fix: Batch fetch members for all projects in one query
const membersByProject = await db.members.findByProjectIds(
projects.map(p => p.id)
);
🟡 Medium: Generic error message Line 78: catch (e) { return apiError('Something went wrong', 500); } Fix: Log the error with context, return safe message
catch (error) {
console.error('DELETE /organizations failed:', { orgId: params.orgId, error });
return apiError('Failed to delete organization', 500);
}
🔵 Low: Missing return type on handler Line 45: export async function DELETE(req) Fix: Add explicit return type
export async function DELETE(req: NextRequest): Promise<NextResponse>
### Step 8: Summary Report
After reviewing all files, output a summary:
🔍 Code Review: Complete
Files reviewed: [count] Issues found: [total]
By severity: 🔴 Critical: [count], fix before merge 🟠 High: [count], fix this sprint 🟡 Medium: [count], fix when touching the file 🔵 Low: [count]: consider for future
By category: Security: [count] issues Performance: [count] issues Maintainability: [count] issues Error handling: [count] issues Testing: [count] issues Accessibility: [count] issues
Top 3 priorities:
- [Most critical issue with file:line]
- [Second most critical]
- [Third most critical]
Estimated fix effort: Critical + High: ~[X] hours All issues: ~[X] hours
## Level History
- **Lv.1**: Base: Six-category systematic review (security, performance, maintainability, error handling, testing, accessibility), severity-ranked findings, per-file reports with specific code fixes, summary with prioritized action items. (Origin: MemStack Pro v3.2, Mar 2026)
Mentor: Activating mentor mode...
Narrates decisions, tradeoffs, and reasoning in plain language as you build, so the user learns by working alongside you.
Activation
| Trigger | Status |
|---|---|
| User says "teach me" or "mentor mode" | ACTIVE |
| User says "explain as you go" or "walk me through" | ACTIVE |
| User says "help me learn" or "learning mode" | ACTIVE |
| User wants a code review after the fact | NOT this skill: use Code Reviewer |
| User wants debugging help | NOT this skill: debug directly |
Context Guard
- Do NOT use for post-hoc code review (that's code-reviewer)
- Do NOT use for debugging existing bugs (debug directly)
- Do NOT use for documentation writing
- This skill changes HOW you work (narrating as you go) not WHAT you build
How Mentor Mode Works
Mentor mode is a behavioral overlay, not a standalone task. When active, it modifies how you approach ANY other task. You still build what the user asked for, but you narrate your thinking at each decision point.
The rule: Before every non-trivial action, explain WHY in 1-3 sentences. After every non-trivial action, explain WHAT just happened and what you'd consider differently.
Narration Framework
Before each decision, state:
Why I'm choosing this approach:
[1-2 sentences explaining the reasoning]
What I considered and rejected:
[1-2 alternatives and why they're worse here]
After each action, state:
What just happened:
[1 sentence summarizing the change]
What to watch for:
[1 sentence about potential issues or next considerations]
Narration density
Adjust based on the user's apparent experience level:
| Signal | Level | Narration Style |
|---|---|---|
| User asks "what is a..." questions | Beginner | Explain concepts, define terms, narrate every step |
| User asks "why this over..." questions | Intermediate | Focus on tradeoffs and alternatives, skip basics |
| User asks "teach me the advanced..." | Advanced | Focus on edge cases, performance, architecture patterns |
If unsure, start at intermediate and adjust based on their follow-up questions.
Decision Points to Narrate
Not every line of code needs explanation. Focus narration on these moments:
Architecture decisions
- "I'm putting this in a separate file because..."
- "This could be a class or a function, I'm choosing a function because..."
- "I'm using composition over inheritance here because..."
Library/tool choices
- "I'm using X instead of Y because in this context..."
- "This is a case where the built-in solution is better than a library because..."
- "I'd normally use X but your project already uses Y, so..."
Tradeoff moments
- "This is simpler but less performant, here's why simplicity wins here..."
- "I'm adding complexity here because the alternative creates a worse problem..."
- "This violates DRY but that's intentional because..."
Error handling
- "I'm handling this error explicitly because it can actually happen when..."
- "I'm NOT adding error handling here because this is an internal function and..."
- "This try/catch is broad, normally I'd narrow it, but here..."
Naming choices
- "I named this X instead of Y because in 6 months you'll be looking for..."
- "This variable name is verbose on purpose because..."
Things to NEVER narrate
- Obvious syntax (importing modules, standard boilerplate)
- Things the user explicitly said they already know
- Trivial changes (fixing a typo, adjusting whitespace)
- Every single line, narrate decision points, not keystrokes
Adapting to feedback
| User says | Adjust |
|---|---|
| "I know that" / "skip the basics" | Increase level, narrate less frequently |
| "Wait, explain that" / "Why?" | Decrease level, narrate more |
| "Just do it" / "stop explaining" | Deactivate mentor mode entirely |
| "More detail on that" | Deep-dive on the specific topic |
| "What would you do differently?" | Explore 2-3 alternative approaches with tradeoffs |
Example narration in action
User: "Add authentication to this Express app"
[Before action]
Why I'm choosing this approach:
I'm using express-session with a session store rather than JWT because your app
already has a database and server-rendered pages, sessions are simpler here and
you don't need stateless auth for a single-server app.
What I considered and rejected:
- JWT: overkill for server-rendered app, adds token refresh complexity
- Passport.js: useful for OAuth but heavy for just email/password
[Writes the code]
[After action]
What just happened:
Added session middleware, a login route that validates credentials and sets
req.session.userId, and a requireAuth middleware that protects routes.
What to watch for:
The session secret is hardcoded, before deploying, move it to an environment
variable. Also, this stores sessions in memory which won't survive restarts.
We'll add a session store next.
Ending mentor mode
Mentor mode stays active until:
- The user says "stop explaining" or "normal mode"
- The task is complete and no follow-up is requested
- The session ends
When ending, offer a summary:
Mentor session summary:
- Key decisions made: [list 3-5 major choices]
- Patterns used: [list architectural patterns]
- Things to study further: [1-2 topics worth deeper learning]
Disambiguation
- "teach me" / "explain as you go" / "mentor mode" = Mentor
- "review this code" / "what's wrong with this" = Code Reviewer (not this skill)
- "fix this bug" / "why is this broken" = Debug directly (not this skill)
- "explain this file" / "what does this do" = Direct explanation (not this skill)
Level History
- Lv.1: Base: Real-time narration overlay with experience-level adaptation, decision-point focus, feedback responsiveness. (Origin: MemStack v3.5, Apr 2026)
Migration Planner: Planning database migration...
Plans safe database schema migrations with zero-downtime strategies, rollback procedures, data validation checkpoints, and version tracking for PostgreSQL, MySQL, and SQLite.
Activation
When this skill activates, output:
Migration Planner: Planning database migration...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "migration", "schema change", "database migration" | ACTIVE |
| User says "alter table", "add column", "change type", "rollback plan" | ACTIVE |
| User wants to evolve an existing database schema safely | ACTIVE |
| User wants to design a new database from scratch | DORMANT: use Database Architect |
| User wants to refactor application code | DORMANT: use Refactor Planner |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Just ALTER TABLE in production" | Unplanned schema changes cause outages. Lock durations, data backfills, and app compatibility all need planning. |
| "No rollback plan" | Migrations fail. Without a tested rollback, a failed deploy means manual emergency recovery at 3 AM. |
| "Rename columns directly" | Renaming breaks all queries referencing the old name instantly. Use add → migrate → drop (3-phase). |
| "Big bang data migration" | Migrating millions of rows in one transaction locks the table for minutes/hours. Batch in chunks. |
| "Skip validation" | Assuming data migrated correctly without checking is gambling. Validate row counts, checksums, and spot checks. |
Protocol
Step 1: Gather Migration Requirements
If the user hasn't provided details, ask:
- Database: what engine? (PostgreSQL, MySQL, SQLite, MongoDB)
- Current schema: what does the table/schema look like now?
- Target schema: what should it look like after migration?
- Data volume: how many rows in affected tables?
- Downtime tolerance: zero-downtime required, or maintenance window OK?
- Migration tool: what do you use? (Prisma, Knex, Flyway, Alembic, raw SQL, other)
Step 2: Classify the Migration
Migration type classification:
| Change Type | Risk | Lock Behavior (PostgreSQL) | Strategy |
|---|---|---|---|
| Add column (nullable) | Low | Brief ACCESS EXCLUSIVE lock | Direct ALTER |
| Add column (with default) | Low (PG 11+) | Brief lock (PG 11+ doesn't rewrite) | Direct ALTER |
| Add column (NOT NULL, no default) | High | Fails on existing rows | Add nullable → backfill → add constraint |
| Drop column | Medium | Brief lock, but app must not reference it | Remove app refs first → then DROP |
| Rename column | High | Breaks all queries instantly | 3-phase: add new → migrate → drop old |
| Change column type | High | Full table rewrite + lock | New column → backfill → swap → drop |
| Add index | Medium | Blocks writes (without CONCURRENTLY) | CREATE INDEX CONCURRENTLY |
| Add foreign key | Medium | Validates all rows (lock) | NOT VALID → VALIDATE CONSTRAINT separately |
| Drop table | High | Irreversible data loss | Backup → verify no refs → drop |
| Add table | Low | No lock on existing tables | Direct CREATE |
Migration classification output:
## Migration Classification
| # | Change | Type | Risk | Lock Duration | Strategy |
|---|--------|------|------|--------------|----------|
| 1 | [Change description] | [Type] | Low/Med/High | [Est. duration] | [Strategy] |
| 2 | [Change description] | [Type] | Low/Med/High | [Est. duration] | [Strategy] |
Step 3: Design the Migration
Safe migration patterns:
Pattern A: Add nullable column (simple, low risk)
-- Migration UP
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
-- Migration DOWN
ALTER TABLE users DROP COLUMN phone;
Pattern B: Add NOT NULL column (3-step)
-- Step 1: Add nullable column
ALTER TABLE users ADD COLUMN status VARCHAR(20);
-- Step 2: Backfill existing rows (in batches)
UPDATE users SET status = 'active' WHERE status IS NULL AND id BETWEEN 1 AND 10000;
UPDATE users SET status = 'active' WHERE status IS NULL AND id BETWEEN 10001 AND 20000;
-- ... continue in batches
-- Step 3: Add NOT NULL constraint
ALTER TABLE users ALTER COLUMN status SET NOT NULL;
ALTER TABLE users ALTER COLUMN status SET DEFAULT 'active';
Pattern C: Rename column (3-phase, zero-downtime)
-- Phase 1: Add new column + trigger
ALTER TABLE orders ADD COLUMN total_amount DECIMAL(10,2);
-- Create trigger to sync old → new
CREATE OR REPLACE FUNCTION sync_amount() RETURNS TRIGGER AS $$
BEGIN
NEW.total_amount := NEW.amount;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER sync_amount_trigger BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION sync_amount();
-- Phase 2: Backfill existing rows
UPDATE orders SET total_amount = amount WHERE total_amount IS NULL AND id BETWEEN 1 AND 10000;
-- Phase 3: (After app code updated to use total_amount)
DROP TRIGGER sync_amount_trigger ON orders;
DROP FUNCTION sync_amount();
ALTER TABLE orders DROP COLUMN amount;
Pattern D: Change column type (safe swap)
-- Step 1: Add new column with target type
ALTER TABLE products ADD COLUMN price_v2 DECIMAL(12,4);
-- Step 2: Backfill with type conversion
UPDATE products SET price_v2 = price::DECIMAL(12,4) WHERE id BETWEEN 1 AND 10000;
-- Step 3: Swap columns (after app code updated)
ALTER TABLE products DROP COLUMN price;
ALTER TABLE products RENAME COLUMN price_v2 TO price;
Pattern E: Add index without blocking writes
-- PostgreSQL: CONCURRENTLY avoids blocking writes (cannot run in a transaction)
CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
-- MySQL 5.6+: ALGORITHM=INPLACE avoids table copy
ALTER TABLE users ADD INDEX idx_email (email), ALGORITHM=INPLACE, LOCK=NONE;
Pattern F: Add foreign key without full scan lock
-- Step 1: Add constraint as NOT VALID (skips validation, brief lock)
ALTER TABLE orders ADD CONSTRAINT fk_orders_user
FOREIGN KEY (user_id) REFERENCES users(id) NOT VALID;
-- Step 2: Validate separately (scans but allows concurrent writes)
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_user;
Step 4: Data Backfill Strategy
For migrations that require updating existing data:
Batch processing template:
-- Batch update to avoid long locks
DO $$
DECLARE
batch_size INT := 10000;
rows_updated INT;
BEGIN
LOOP
UPDATE target_table
SET new_column = compute_value(old_column)
WHERE new_column IS NULL
AND id IN (
SELECT id FROM target_table
WHERE new_column IS NULL
LIMIT batch_size
FOR UPDATE SKIP LOCKED
);
GET DIAGNOSTICS rows_updated = ROW_COUNT;
RAISE NOTICE 'Updated % rows', rows_updated;
EXIT WHEN rows_updated = 0;
-- Brief pause to reduce load
PERFORM pg_sleep(0.1);
END LOOP;
END $$;
Backfill sizing guide:
| Table Size | Batch Size | Estimated Time | Pause Between |
|---|---|---|---|
| <10K rows | All at once | <1 second | None |
| 10K-100K | 10,000 | 10-60 seconds | 100ms |
| 100K-1M | 10,000 | 1-10 minutes | 100ms |
| 1M-10M | 50,000 | 10-60 minutes | 200ms |
| 10M-100M | 50,000 | 1-8 hours | 500ms |
| >100M | 100,000 | Schedule off-peak | 1s |
Step 5: Write Rollback Procedures
Every migration MUST have a tested rollback:
## Rollback Plan
### Automatic Rollback (migration tool)
[Migration tool command to roll back, e.g.:]
- Prisma: `npx prisma migrate resolve --rolled-back [migration_name]`
- Knex: `npx knex migrate:rollback`
- Flyway: `flyway undo`
- Alembic: `alembic downgrade -1`
### Manual Rollback SQL
[Exact SQL to reverse the migration: tested before deploying forward]
### Rollback Verification
After rolling back, verify:
- [ ] Schema matches pre-migration state
- [ ] Row counts unchanged
- [ ] Application health check passes
- [ ] No orphaned data or broken references
### Point of No Return
[Define when rollback is no longer possible:]
- After Phase 2 backfill: rollback requires data reconstruction
- After old column drop: rollback requires restore from backup
- After app code deployed to new schema: rollback requires app revert too
Rollback SQL templates:
| Migration Type | Rollback SQL |
|---|---|
| Add column | ALTER TABLE t DROP COLUMN c; |
| Drop column | Restore from backup (cannot undo) |
| Add index | DROP INDEX idx_name; |
| Add constraint | ALTER TABLE t DROP CONSTRAINT c_name; |
| Rename column | ALTER TABLE t RENAME COLUMN new TO old; |
| Change type | Reverse swap (if old column still exists) |
Step 6: Validation Checkpoints
Verify migration correctness at each stage:
Pre-migration checks:
-- Record baseline metrics before migration
SELECT COUNT(*) AS total_rows FROM target_table;
SELECT COUNT(*) AS null_count FROM target_table WHERE critical_column IS NULL;
SELECT pg_total_relation_size('target_table') AS table_size;
Post-migration checks:
-- Verify row count unchanged (no accidental deletes)
SELECT COUNT(*) AS total_rows FROM target_table;
-- Should match pre-migration count
-- Verify new column populated correctly
SELECT COUNT(*) AS null_count FROM target_table WHERE new_column IS NULL;
-- Should be 0 (after backfill)
-- Verify data integrity
SELECT COUNT(*) FROM target_table WHERE new_column != expected_transform(old_column);
-- Should be 0
-- Verify constraints active
SELECT conname, convalidated FROM pg_constraint WHERE conrelid = 'target_table'::regclass;
-- All should show convalidated = true
-- Spot check random sample
SELECT * FROM target_table ORDER BY RANDOM() LIMIT 10;
-- Manual verification of data correctness
Validation checklist:
## Migration Validation
| Check | Expected | Actual | Status |
|-------|----------|--------|--------|
| Row count (before) | [X] | [X] | [OK / FAIL] |
| Row count (after) | [X] | [X] | [OK / FAIL] |
| Null count (new column) | 0 | [X] | [OK / FAIL] |
| Constraint validation | All valid | [X] | [OK / FAIL] |
| App health check | 200 OK | [X] | [OK / FAIL] |
| Query performance | <[X]ms | [X]ms | [OK / FAIL] |
Step 7: Build Migration Plan
Assemble everything into an execution plan:
## Migration Execution Plan
### Pre-Flight
- [ ] Backup database (verified restore works)
- [ ] Test migration on staging with production-size data
- [ ] Verify rollback works on staging
- [ ] Schedule maintenance window (if needed): [Date, Time, Duration]
- [ ] Notify stakeholders: [Who to notify]
- [ ] Record baseline metrics
### Execution Steps
**Phase 1: Schema Change** (estimated: [X] minutes)
1. [ ] Run migration: `[migration command]`
2. [ ] Verify schema change applied
3. [ ] Checkpoint: app still functional
**Phase 2: Data Backfill** (estimated: [X] minutes)
1. [ ] Start batch backfill: `[backfill command]`
2. [ ] Monitor progress: `[monitoring query]`
3. [ ] Checkpoint: verify [X]% of rows updated
**Phase 3: Constraint Enforcement** (estimated: [X] minutes)
1. [ ] Add NOT NULL / constraints: `[constraint SQL]`
2. [ ] Validate constraints: `[validation SQL]`
3. [ ] Checkpoint: all constraints valid
**Phase 4: Cleanup** (after app code deployed)
1. [ ] Remove old column/trigger: `[cleanup SQL]`
2. [ ] Run VACUUM ANALYZE: `VACUUM ANALYZE target_table;`
3. [ ] Verify final schema matches target
### Post-Migration
- [ ] Run validation checklist (Step 6)
- [ ] Verify application logs: no errors
- [ ] Monitor query performance for 24 hours
- [ ] Update schema documentation
- [ ] Close migration ticket
Step 8: Version Tracking
Migration file naming convention:
| Tool | Convention | Example |
|---|---|---|
| Prisma | Auto-generated timestamp | 20260303120000_add_phone_to_users/ |
| Knex | YYYYMMDDHHMMSS_description.js | 20260303120000_add_phone_to_users.js |
| Flyway | V[version]__Description.sql | V2.1__Add_phone_to_users.sql |
| Alembic | Auto-generated revision ID | a1b2c3d4_add_phone_to_users.py |
| Raw SQL | [sequence]_[description].sql | 003_add_phone_to_users.sql |
Migration log table (for raw SQL projects):
CREATE TABLE IF NOT EXISTS schema_migrations (
id SERIAL PRIMARY KEY,
version VARCHAR(50) NOT NULL UNIQUE,
description VARCHAR(255),
applied_at TIMESTAMP DEFAULT NOW(),
execution_time_ms INTEGER,
rolled_back_at TIMESTAMP,
checksum VARCHAR(64)
);
Output Format
# Migration Plan: [Description]
## Classification
[From Step 2: change types, risk levels, strategies]
## Migration SQL
[From Step 3, forward migration with safe patterns]
## Backfill Strategy
[From Step 4, batch processing plan, if data migration needed]
## Rollback Plan
[From Step 5, rollback SQL + point of no return]
## Validation
[From Step 6, pre/post checks with expected values]
## Execution Plan
[From Step 7, phased checklist with time estimates]
## Version
[From Step 8, migration file naming and tracking]
Completion
Migration Planner: Complete!
Database: [Engine]
Changes: [X] schema changes planned
Risk level: [Overall Low/Medium/High]
Estimated execution: [X] minutes
Downtime required: [Zero / X minutes window]
Rollback tested: [Yes/No]
Next steps:
1. Test migration on staging with production-size data
2. Test rollback on staging: verify clean reversal
3. Run validation queries after staging migration
4. Schedule production migration: [suggested window]
5. Execute migration following the phased checklist
6. Monitor for 24 hours post-migration
Level History
- Lv.1: Base: 10 migration types with risk/lock classification, 6 safe migration patterns (add nullable, add NOT NULL 3-step, rename 3-phase, type swap, concurrent index, NOT VALID FK), batch backfill with sizing guide, rollback procedures with point-of-no-return, pre/post validation checkpoints, phased execution plan template, version tracking conventions for 5 tools. (Origin: MemStack Pro v3.2, Mar 2026)
🚀 Performance Audit: Full-Stack Performance Scanner
Identify and prioritize performance bottlenecks across frontend, backend, and network layers with measured impact and fix priority.
Activation
When this skill activates, output:
🚀 Performance Audit: Scanning for performance bottlenecks...
| Context | Status |
|---|---|
| User says "performance audit", "optimize", "slow app" | ACTIVE |
| User mentions bundle size, N+1 queries, or Core Web Vitals | ACTIVE |
| User wants to find memory leaks or unnecessary re-renders | ACTIVE |
| User wants database schema optimization specifically | DORMANT: see database-architect |
| User wants API design review (not performance) | DORMANT: see api-designer |
| User wants general code quality review | DORMANT: see code-reviewer |
Protocol
Step 1: Gather Inputs
Ask the user for:
- Stack: Frontend framework, backend language, database?
- Symptoms: What feels slow? (initial load, interactions, API responses, builds)
- Scale: How many users? How much data?
- Metrics: Any existing performance data? (Lighthouse scores, APM dashboards)
- Priority: User-facing speed or server-side efficiency?
Step 2: Frontend: Bundle Analysis
Check bundle size and composition:
# Next.js
npx @next/bundle-analyzer
# or: ANALYZE=true next build
# Webpack (generic)
npx webpack-bundle-analyzer stats.json
# Vite
npx vite-bundle-visualizer
What to look for:
| Issue | Detection | Impact | Fix |
|---|---|---|---|
| Large dependencies | Bundle > 200KB gzipped | Slow initial load | Replace with lighter alternatives |
| Duplicate packages | Same lib in multiple versions | Wasted bytes | Dedupe or pin single version |
| Unused exports | Tree-shaking not working | Wasted bytes | Use ESM imports, avoid barrel files |
| No code splitting | Single large bundle | Slow initial load | Dynamic imports, route-based splitting |
| Unoptimized images | Images > 100KB without optimization | Slow load | next/image, sharp, WebP/AVIF |
| Missing compression | No gzip/brotli on responses | 60-80% larger payloads | Enable in server/CDN config |
Common heavy dependencies and alternatives:
| Package | Size (minified) | Lighter Alternative | Size |
|---|---|---|---|
moment | 72 KB | date-fns (tree-shakeable) | ~2-5 KB used |
lodash (full) | 72 KB | lodash-es (tree-shakeable) | ~1-3 KB used |
axios | 14 KB | fetch (native) | 0 KB |
classnames | 1 KB | Template literals | 0 KB |
uuid | 3 KB | crypto.randomUUID() | 0 KB |
chart.js | 65 KB | Specific chart lib for your use case | Varies |
Tree-shaking checks:
── TREE-SHAKING ISSUES ────────────────────
[x] Barrel files (index.ts re-exporting everything)
File: src/utils/index.ts
Impact: Imports entire utils even if using one function
Fix: Import directly from source file
[x] CommonJS modules (require() instead of import)
File: src/legacy/helper.js
Impact: Cannot tree-shake CJS modules
Fix: Convert to ESM or find ESM version of dependency
[x] Side effects not declared
Package: [name]
Impact: Bundler can't safely remove unused code
Fix: Add "sideEffects": false to package.json
Step 3: Frontend: Core Web Vitals
Audit for the three Core Web Vitals:
── CORE WEB VITALS AUDIT ──────────────────
LCP (Largest Contentful Paint), Target: < 2.5s
Current: [measured or estimated]
Issues found:
[ ] Hero image not optimized (missing width/height, no lazy loading)
[ ] Render-blocking CSS in <head> (large stylesheet before content)
[ ] Web fonts blocking render (no font-display: swap)
[ ] Server response time > 600ms (TTFB too high)
[ ] Third-party scripts blocking main thread
FID / INP (Interaction to Next Paint), Target: < 200ms
Current: [measured or estimated]
Issues found:
[ ] Long tasks on main thread (> 50ms blocks)
[ ] Heavy JavaScript execution on page load
[ ] Synchronous XHR calls blocking interaction
[ ] Event handlers doing expensive computation
CLS (Cumulative Layout Shift), Target: < 0.1
Current: [measured or estimated]
Issues found:
[ ] Images without explicit dimensions (width/height)
[ ] Dynamically injected content above fold
[ ] Web fonts causing layout shift (FOUT/FOIT)
[ ] Ads or embeds without reserved space
Quick LCP fixes:
// 1. Preload hero image
<link rel="preload" as="image" href="/hero.webp" fetchpriority="high" />
// 2. Font display swap
@font-face {
font-family: 'CustomFont';
src: url('/fonts/custom.woff2') format('woff2');
font-display: swap;
}
// 3. Next.js Image component (automatic optimization)
import Image from 'next/image';
<Image src="/hero.jpg" width={1200} height={600} priority alt="Hero" />
Step 4: Frontend: React Performance
Unnecessary re-render detection:
| Pattern | Detection | Impact | Fix |
|---|---|---|---|
| Passing new objects/arrays as props | onClick={() => {}} in JSX | Child re-renders every parent render | Extract handler, use useCallback |
| Missing memoization on expensive computation | Computed value in render body | Recalculated every render | useMemo for expensive calculations |
| Context causing tree-wide re-renders | Context value changes frequently | All consumers re-render | Split context, use selectors |
Missing key on list items | React DevTools warnings | Incorrect DOM reconciliation | Add stable unique key |
| Props drilling deep component trees | Props passed through 5+ levels | Tight coupling, re-render chains | Context or composition pattern |
React performance audit checklist:
── REACT PERFORMANCE ──────────────────────
Component rendering:
[ ] React.memo on pure presentational components
[ ] useCallback for handlers passed to memoized children
[ ] useMemo for expensive computed values (> 1ms)
[ ] Stable keys on list items (not array index for dynamic lists)
State management:
[ ] State colocated to where it's used (not lifted too high)
[ ] Context split: frequent-update values separate from static config
[ ] Avoid storing derived state (compute from source of truth)
[ ] Batch state updates where possible
Data fetching:
[ ] Loading states prevent waterfall fetches
[ ] Parallel fetches where data is independent
[ ] Cache API responses (React Query, SWR)
[ ] Pagination/infinite scroll for large lists
Rendering:
[ ] Virtualize long lists (react-window, @tanstack/virtual)
[ ] Lazy load below-fold components (React.lazy + Suspense)
[ ] Avoid layout thrashing (reading DOM then writing immediately)
[ ] Debounce/throttle scroll and resize handlers
Step 5: Backend: Database Performance
N+1 query detection:
── N+1 QUERY PATTERNS ─────────────────────
Pattern: Fetching related data in a loop
Example:
const users = await db.query('SELECT * FROM users');
for (const user of users) {
user.posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
}
Queries generated: 1 + N (where N = number of users)
Fix: JOIN or subquery
SELECT u.*, p.* FROM users u
LEFT JOIN posts p ON p.user_id = u.id;
ORM fix (Prisma):
await prisma.user.findMany({ include: { posts: true } });
ORM fix (Drizzle):
await db.query.users.findMany({ with: { posts: true } });
Missing index detection:
-- Find slow queries (PostgreSQL)
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;
-- Find missing indexes
SELECT relname, seq_scan, seq_tup_read, idx_scan
FROM pg_stat_user_tables
WHERE seq_scan > 100 AND idx_scan < seq_scan / 10
ORDER BY seq_scan DESC;
-- Suggested indexes for common patterns:
-- Foreign keys: CREATE INDEX idx_posts_user_id ON posts(user_id);
-- Filtered queries: CREATE INDEX idx_users_active ON users(status) WHERE status = 'active';
-- Sorting: CREATE INDEX idx_posts_created ON posts(created_at DESC);
-- Text search: CREATE INDEX idx_users_email ON users(email);
Query optimization checklist:
| Issue | Detection | Impact | Fix |
|---|---|---|---|
| N+1 queries | Loop with DB call inside | O(N) queries → O(1) | JOIN or eager loading |
| Missing indexes | Full table scans on filtered columns | Slow queries as data grows | Add targeted indexes |
| SELECT * | Fetching all columns | Excess data transfer | Select only needed columns |
| No pagination | Returning all records | Memory + transfer overhead | LIMIT/OFFSET or cursor pagination |
| Missing connection pooling | New connection per query | Connection overhead | Use pgBouncer or built-in pool |
| Unoptimized JOINs | Joining on non-indexed columns | Slow JOINs | Index JOIN columns |
Step 6: Backend: API Performance
Over-fetching and under-fetching:
── API RESPONSE AUDIT ─────────────────────
Endpoint: GET /api/users
Response size: 45 KB per request
Fields returned: 28
Fields used by client: 8
Over-fetch ratio: 71% wasted
Fix: Add field selection
GET /api/users?fields=id,name,email,avatar
or: implement GraphQL for flexible queries
Endpoint: GET /api/dashboard
Requests made: 6 sequential API calls
Could be: 1 aggregated endpoint
Waterfall time: 1.8s
Parallel time: 0.4s (if batched)
Fix: Create /api/dashboard aggregate endpoint
or: use Promise.all() on client for parallel fetches
Missing pagination:
── PAGINATION AUDIT ───────────────────────
Endpoint: GET /api/products
Current: Returns ALL products (2,400 records)
Response size: 890 KB
Response time: 1.2s
Fix: Add cursor-based pagination
GET /api/products?cursor=abc123&limit=50
Response: { data: [...], nextCursor: "def456", hasMore: true }
Caching opportunities:
── CACHE AUDIT ────────────────────────────
Endpoint Cacheable? TTL Strategy
────────────────────────────────────────────────────────
GET /api/products Yes 5 min CDN + browser Cache-Control
GET /api/user/:id Conditional 1 min ETag / If-None-Match
GET /api/config Yes 1 hour CDN, stale-while-revalidate
POST /api/orders No, Never cache mutations
GET /api/search Maybe 30 sec Vary by query params
Missing headers:
[ ] Cache-Control not set on static assets
[ ] No ETag on API responses
[ ] No compression (gzip/brotli) on responses
Step 7: Backend: Memory & Resource Leaks
Common memory leak patterns:
| Leak Type | Detection | Symptoms | Fix |
|---|---|---|---|
| Event listeners | Listeners added without removal | Memory grows over time | removeEventListener in cleanup |
| Unclosed DB connections | Connection pool exhaustion | "too many connections" errors | Close connections in finally/cleanup |
| Growing arrays/maps | In-memory cache without eviction | RSS grows indefinitely | Add TTL, LRU cache, or size limit |
| Unreferenced timers | setInterval without clearInterval | Timer continues after context dies | Clear timers on shutdown/cleanup |
| Unresolved promises | Promises that never settle | Memory for callbacks retained | Add timeouts to all async operations |
| Circular references | Objects referencing each other | GC can't collect (rare in V8) | Break cycles, use WeakRef |
Detection approach:
# Node.js heap snapshot
node --inspect app.js
# Open Chrome DevTools → Memory → Take heap snapshot
# Compare two snapshots to find growing objects
# Watch RSS over time
watch -n 5 'ps -o rss -p $(pgrep -f "node app.js") | tail -1'
Cleanup patterns:
// Express: cleanup on server shutdown
const server = app.listen(3000);
const connections = new Set();
server.on('connection', (conn) => {
connections.add(conn);
conn.on('close', () => connections.delete(conn));
});
process.on('SIGTERM', () => {
server.close();
for (const conn of connections) conn.destroy();
db.end(); // Close DB pool
redis.quit(); // Close Redis
clearInterval(heartbeat); // Clear timers
});
Step 8: Network Performance
Unnecessary API calls:
── REDUNDANT REQUEST AUDIT ────────────────
Issue: Same data fetched multiple times
/api/user/me called 4 times on dashboard load
Fix: Cache response, share via context/store
Issue: Polling when WebSocket would work
/api/notifications polled every 5 seconds
Fix: WebSocket/SSE for real-time updates
Issue: No request deduplication
Search input triggers API call per keystroke
Fix: Debounce (300ms), cancel previous request (AbortController)
Issue: Large uncompressed responses
/api/export returns 2.4 MB JSON without gzip
Fix: Enable compression middleware
Compression check:
// Express
const compression = require('compression');
app.use(compression());
// Verify: response should have
// Content-Encoding: gzip (or br for brotli)
CDN and static asset optimization:
── STATIC ASSET AUDIT ─────────────────────
Asset Type Current Optimized Savings
────────────────────────────────────────────────────────
Images PNG 2.4 MB WebP 180 KB 92%
Fonts 4 font files 2 subsetted 60%
CSS 3 files, 120 KB 1 file, 45 KB 62%
JS 1.2 MB bundle 4 chunks, 280 KB 77%
Recommendations:
[ ] Serve images in WebP/AVIF with fallback
[ ] Subset fonts to used characters only
[ ] Enable HTTP/2 for parallel asset loading
[ ] Set Cache-Control: max-age=31536000 for hashed assets
[ ] Use CDN for static assets (Cloudflare, CloudFront)
Step 9: Performance Scorecard
Generate a scored report:
━━━ PERFORMANCE SCORECARD ━━━━━━━━━━━━━━━━
Project: [name]
Audit date: [date]
Overall score: [X/100]
── FRONTEND ───────────────────────────────
Bundle size: [X/25] [size]KB gzipped
Issues: [list]
Core Web Vitals: [X/25]
LCP: [value]s [good/needs-work/poor]
INP: [value]ms [good/needs-work/poor]
CLS: [value] [good/needs-work/poor]
React performance: [X/10]
Re-render issues: [count]
── BACKEND ────────────────────────────────
Database: [X/15]
N+1 queries: [count found]
Missing indexes: [count found]
API efficiency: [X/10]
Over-fetching: [count endpoints]
Missing cache: [count endpoints]
No pagination: [count endpoints]
Memory safety: [X/5]
Potential leaks: [count found]
── NETWORK ────────────────────────────────
Compression: [X/5] [enabled/missing]
Asset optimization: [X/5] [optimized/unoptimized]
── PRIORITIZED FIX LIST ───────────────────
Priority Issue Impact Effort Category
──────────────────────────────────────────────────────────────────────
🔴 P1 [issue description] High Low [area]
🔴 P1 [issue description] High Medium [area]
🟡 P2 [issue description] Medium Low [area]
🟡 P2 [issue description] Medium Medium [area]
🟠 P3 [issue description] Low Low [area]
🟠 P3 [issue description] Medium High [area]
Priority scoring:
- P1 (Do now): High impact + Low-Medium effort: biggest wins
- P2 (Plan soon): Medium impact or High effort for high impact
- P3 (Backlog): Low impact or very high effort
Impact estimation guide:
| Optimization | Typical Impact |
|---|---|
| Fix N+1 queries | 50-90% reduction in query time |
| Add missing indexes | 10-100x faster queries |
| Enable compression | 60-80% smaller responses |
| Code splitting | 30-60% faster initial load |
| Image optimization | 50-90% smaller images |
| Remove unused deps | 10-40% smaller bundle |
| Add caching | 80-99% fewer API calls |
| Virtualize lists | 90% less DOM, smooth scrolling |
Inputs
- Tech stack (frontend framework, backend language, database)
- Performance symptoms (what feels slow)
- Scale information (users, data volume)
- Existing metrics (Lighthouse scores, APM data)
- Priority area (user-facing or server-side)
Outputs
- Bundle analysis with heavy dependency identification and alternatives
- Core Web Vitals audit (LCP, INP, CLS) with specific fixes
- React performance checklist (re-renders, memoization, data fetching)
- Database audit (N+1 detection, missing indexes, query optimization)
- API audit (over-fetching, pagination, caching opportunities)
- Memory leak detection patterns and cleanup
- Network audit (compression, CDN, redundant requests)
- Performance scorecard (0-100) with prioritized fix list
- Impact estimates per optimization
Level History
- Lv.1: Base: Full-stack performance scanner covering frontend (bundle analysis, Core Web Vitals, React re-renders), backend (N+1 queries, missing indexes, API over-fetching, memory leaks), and network (compression, CDN, caching). Performance scorecard with priority-ranked fix list and impact estimates. (Origin: MemStack v3.2, Mar 2026)
Refactor Planner: Planning systematic code improvement...
Identifies code smells, assesses refactoring risk, selects appropriate patterns, and builds incremental execution plans with rollback strategies and verification checkpoints.
Activation
When this skill activates, output:
Refactor Planner: Planning systematic code improvement...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "refactor", "refactoring plan", "code cleanup" | ACTIVE |
| User says "tech debt", "god class", "tight coupling", "reduce duplication" | ACTIVE |
| User wants to improve existing code structure without changing behavior | ACTIVE |
| User wants to write a new feature | DORMANT: use Feature Spec |
| User wants to change database schema | DORMANT: use Migration Planner |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Big bang rewrite" | Rewriting everything at once introduces cascading failures. Incremental changes are safer and shippable. |
| "Refactor without tests" | No test coverage = no safety net. Add characterization tests BEFORE touching code. |
| "Refactor and add features simultaneously" | Mixing behavior changes with structural changes makes bugs impossible to isolate. Separate commits. |
| "No measurable goal" | "Clean up the code" is vague. Define metrics: reduce file from 800 to 200 lines, eliminate 5 duplicate blocks, etc. |
| "Skip the risk assessment" | A function called by 47 files is higher risk than a utility used in 2. Assess blast radius first. |
Protocol
Step 1: Gather Refactoring Context
If the user hasn't provided details, ask:
- Target: what code needs refactoring? (file, module, class, or system)
- Pain point: what's the specific problem? (hard to modify, duplicated, slow, confusing)
- Test coverage: does the target code have tests? (yes, partial, none)
- Constraints: any deadlines, frozen APIs, or deployment concerns?
- Language/framework: what tech stack?
Step 2: Identify Code Smells
Scan the target code for these smell categories:
Bloaters (too big):
| Smell | Detection | Severity |
|---|---|---|
| Long method | Function >30 lines or >3 levels of nesting | Medium |
| Large class / God object | Class >300 lines or >10 public methods | High |
| Long parameter list | Function takes >4 parameters | Medium |
| Primitive obsession | Raw strings/numbers instead of domain types | Low |
| Data clumps | Same group of variables passed together repeatedly | Medium |
Couplers (too connected):
| Smell | Detection | Severity |
|---|---|---|
| Feature envy | Method uses another class's data more than its own | Medium |
| Inappropriate intimacy | Classes access each other's private internals | High |
| Message chains | a.getB().getC().getD().doThing(): chain >2 deep | Medium |
| Middle man | Class delegates nearly everything to another class | Low |
Dispensables (unnecessary):
| Smell | Detection | Severity |
|---|---|---|
| Dead code | Unreachable code, unused variables, commented-out blocks | Low |
| Duplicate code | Same logic in 2+ places (exact or structural) | High |
| Speculative generality | Abstractions, interfaces, or config for cases that don't exist | Medium |
| Lazy class | Class does too little to justify its existence | Low |
Change preventers (hard to modify):
| Smell | Detection | Severity |
|---|---|---|
| Divergent change | One class changed for many different reasons | High |
| Shotgun surgery | One change requires edits across many files | High |
| Parallel inheritance | Creating a subclass in one hierarchy requires one in another | Medium |
Code smell report:
## Code Smell Report: [Target]
| # | Smell | Location | Severity | Lines Affected |
|---|-------|----------|----------|---------------|
| 1 | [Smell name] | [file:line] | High/Med/Low | [X] |
| 2 | [Smell name] | [file:line] | High/Med/Low | [X] |
| ... | | | | |
**Summary:** [X] smells found ([X] high, [X] medium, [X] low)
**Estimated scope:** [X] files, [X] lines affected
Step 3: Assess Risk
For each refactoring target, evaluate:
Risk matrix:
| Factor | Low Risk | Medium Risk | High Risk |
|---|---|---|---|
| Dependents | 0-2 callers | 3-10 callers | 10+ callers |
| Test coverage | >80% covered | 40-80% covered | <40% covered |
| Complexity | Simple extraction | Cross-file changes | Architectural change |
| Reversibility | Easy to revert | Requires migration | Data format changes |
| Blast radius | Single file | Single module | Cross-module |
Risk score per target:
| Target | Dependents | Coverage | Complexity | Reversibility | Blast Radius | Risk Score |
|--------|-----------|----------|-----------|---------------|-------------|------------|
| [File/Class] | [X] callers | [X]% | Low/Med/High | Easy/Med/Hard | File/Module/System | Low/Med/High |
Risk-based ordering rule:
- Start with LOW risk, HIGH value targets (quick wins)
- Then MEDIUM risk targets (with tests added first)
- HIGH risk targets last (with comprehensive test coverage first)
- Never refactor HIGH risk targets without >80% test coverage
Step 4: Select Refactoring Patterns
Match each smell to the appropriate pattern:
Extraction patterns:
| Pattern | Use When | Before → After |
|---|---|---|
| Extract Method | Long method, duplicated logic block | Inline code → Named function |
| Extract Class | God class, divergent change | One class → Two focused classes |
| Extract Interface | Tight coupling, testing difficulty | Concrete dependency → Interface + implementation |
| Extract Variable | Complex expression, magic numbers | if (a > 86400 && b < 3) → if (isExpired && belowRetryLimit) |
Simplification patterns:
| Pattern | Use When | Before → After |
|---|---|---|
| Replace Conditional with Polymorphism | Long switch/if chains on type | Switch statement → Strategy pattern |
| Replace Parameter with Method | Parameter that callee can compute | calc(getX(), getY()) → calc() (fetches internally) |
| Introduce Parameter Object | Long parameter list, data clumps | fn(x, y, z, w) → fn(config) |
| Replace Temp with Query | Temp variable used once after calculation | temp = calc(); use(temp) → use(calc()) |
Structural patterns:
| Pattern | Use When | Before → After |
|---|---|---|
| Move Method/Field | Feature envy, misplaced responsibility | Method in wrong class → Move to correct class |
| Inline Class | Lazy class, middle man | Useless wrapper → Merge into user |
| Replace Inheritance with Composition | Fragile base class, deep hierarchy | extends Base → has Base with delegation |
| Introduce Facade | Complex subsystem, shotgun surgery | Direct subsystem calls → Facade mediates |
Pattern selection table:
| # | Smell | Pattern | Target | Estimated Effort |
|---|-------|---------|--------|-----------------|
| 1 | [Smell] | [Pattern] | [file:line] | [X] hours |
| 2 | [Smell] | [Pattern] | [file:line] | [X] hours |
Step 5: Build Execution Plan
Structure the refactoring into safe, incremental phases:
Phase template:
## Refactoring Plan: [Target]
### Phase 0: Safety Net (do this first)
- [ ] Add characterization tests for current behavior
- [ ] Verify all existing tests pass
- [ ] Create a feature branch: `refactor/[target-name]`
- [ ] Document current behavior snapshot
### Phase 1: Quick Wins (low risk, high value)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run tests, confirm no behavior change
- [ ] Commit: `refactor: [description]`
### Phase 2: Core Improvements (medium risk)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run tests, confirm no behavior change
- [ ] Commit: `refactor: [description]`
### Phase 3: Structural Changes (higher risk)
**Target:** [Smell → Pattern]
- [ ] Step 1: [Specific action]
- [ ] Step 2: [Specific action]
- [ ] Verify: Run full test suite + manual smoke test
- [ ] Commit: `refactor: [description]`
### Verification Checkpoints
After each phase:
1. All tests pass (unit + integration)
2. No behavior change (same inputs → same outputs)
3. Metrics improved (lines reduced, complexity lowered)
4. Code review approved (if team)
Effort estimation guide:
| Pattern | Typical Effort | Risk Level |
|---|---|---|
| Extract Variable | 5-15 min | Very Low |
| Extract Method | 15-30 min | Low |
| Introduce Parameter Object | 30-60 min | Low |
| Extract Class | 1-3 hours | Medium |
| Replace Conditional with Polymorphism | 2-4 hours | Medium |
| Replace Inheritance with Composition | 3-6 hours | High |
| Extract Interface + Dependency Injection | 2-5 hours | Medium-High |
| Architectural restructure (module boundaries) | 1-3 days | High |
Step 6: Define Rollback Strategy
For each phase, document how to reverse:
## Rollback Strategy
| Phase | Rollback Method | Time to Revert |
|-------|----------------|---------------|
| Phase 1 | `git revert [commit]` | <5 min |
| Phase 2 | `git revert [commit]` | <5 min |
| Phase 3 | `git revert [commit]` + re-run migrations if applicable | <15 min |
**Abort criteria (stop refactoring if):**
- Test failures that can't be explained within 30 minutes
- Performance regression >10% on critical paths
- Deadline pressure requires shipping current work
- Discovery of architectural issues requiring design discussion
Step 7: Measure Results
Define before/after metrics:
## Refactoring Metrics
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lines of code (target) | [X] | [X] | -[X]% |
| Cyclomatic complexity | [X] | [X] | -[X]% |
| Number of methods | [X] | [X] | [+/-X] |
| Average method length | [X] lines | [X] lines | -[X]% |
| Duplicate code blocks | [X] | [X] | -[X] |
| Test coverage | [X]% | [X]% | +[X]% |
| Number of dependencies | [X] | [X] | -[X] |
Output Format
# Refactoring Plan: [Target]
## Code Smell Report
[From Step 2, smells identified with severity and location]
## Risk Assessment
[From Step 3, risk matrix for each target]
## Pattern Selection
[From Step 4, matched patterns with estimated effort]
## Execution Plan
[From Step 5, phased plan with verification checkpoints]
## Rollback Strategy
[From Step 6, revert method per phase + abort criteria]
## Success Metrics
[From Step 7: before/after targets]
Completion
Refactor Planner: Complete!
Target: [Target name]
Smells found: [X] ([X] high, [X] medium, [X] low)
Phases: [X]
Estimated effort: [X] hours
Risk level: [Overall Low/Medium/High]
Patterns applied: [List]
Next steps:
1. Add characterization tests for current behavior (Phase 0)
2. Create feature branch: refactor/[target-name]
3. Execute Phase 1 (quick wins) and verify tests pass
4. Continue through phases, committing after each
5. Measure before/after metrics and document improvements
Level History
- Lv.1: Base: 4 code smell categories (bloaters, couplers, dispensables, change preventers) with 16 specific smells, 5-factor risk matrix, 12 refactoring patterns in 3 groups (extraction, simplification, structural), phased execution plan template, rollback strategy with abort criteria, before/after metrics tracking. (Origin: MemStack Pro v3.2, Mar 2026)
Test Writer: Generating test suite...
Generates comprehensive test suites with unit, integration, and e2e tests, proper mocking strategies, edge case coverage, naming conventions, and CI integration patterns.
Activation
When this skill activates, output:
Test Writer: Generating test suite...
Then execute the protocol below.
Context Guard
| Context | Status |
|---|---|
| User says "write tests", "add tests", "test coverage" | ACTIVE |
| User says "unit tests", "integration tests", "component tests", "e2e tests" | ACTIVE |
| User says "mocking", "edge cases", "test this function" | ACTIVE |
| User wants to refactor existing code | DORMANT: use Refactor Planner |
| User wants to change database schema | DORMANT: use Migration Planner |
Common Mistakes
| Mistake | Why It's Wrong |
|---|---|
| "Testing implementation, not behavior" | Tests that break when you refactor internals are brittle. Test WHAT it does, not HOW. |
| "No edge cases" | Happy path tests catch 20% of bugs. Boundaries, nulls, empty inputs, and error paths catch the rest. |
| "Mocking everything" | Over-mocking creates tests that pass but don't catch real bugs. Mock boundaries, not internals. |
| "Test names like test1, test2" | Names should describe behavior: "returns empty array when no items match filter". Self-documenting tests. |
| "No test isolation" | Tests that depend on each other or shared state create flaky test suites that nobody trusts. |
Protocol
Step 1: Gather Test Requirements
If the user hasn't provided details, ask:
- Target: what code needs tests? (function, class, module, API endpoint)
- Language/framework: what tech stack? (JS/TS + Jest/Vitest, Python + pytest, Go, etc.)
- Test level: unit, integration, e2e, or all three?
- Current coverage: any existing tests? What percentage?
- Priority: critical paths first, or comprehensive coverage?
Step 2: Analyze the Code Under Test
Before writing tests, understand the target:
Function/method analysis:
| Property | Value |
|---|---|
| Inputs | [Parameters, types, optional/required] |
| Outputs | [Return type, side effects, thrown exceptions] |
| Dependencies | [External calls: DB, API, file system, other modules] |
| State changes | [What mutates: database records, cache, global state] |
| Branching paths | [Number of if/else/switch branches] |
| Error conditions | [What can fail and how it's handled] |
Dependency map:
[Target Function]
├── [Dependency 1]: mock? [Yes: external / No: pure]
├── [Dependency 2]: mock? [Yes: external / No: pure]
└── [Dependency 3]: mock? [Yes: external / No: pure]
Mock decision rule:
- Mock external boundaries: databases, APIs, file system, network, time
- Don't mock pure functions, internal utilities, simple data transformations
- Sometimes mock sibling modules (mock for unit tests, real for integration)
Step 3: Design Test Cases
Coverage strategy: identify all test scenarios:
Happy path tests:
| # | Scenario | Input | Expected Output |
|---|---|---|---|
| 1 | [Normal case with typical input] | [Input] | [Output] |
| 2 | [Normal case with different valid input] | [Input] | [Output] |
Edge case tests:
| # | Category | Scenario | Input | Expected Output |
|---|---|---|---|---|
| 1 | Boundaries | Minimum valid value | [Input] | [Output] |
| 2 | Boundaries | Maximum valid value | [Input] | [Output] |
| 3 | Boundaries | Exactly at limit | [Input] | [Output] |
| 4 | Empty | Empty string / array / object | "" / [] / {} | [Output] |
| 5 | Null/Undefined | Null input | null | [Output or error] |
| 6 | Type coercion | Unexpected type | "123" vs 123 | [Output] |
| 7 | Large input | Very large dataset | [X items] | [Output / perf] |
| 8 | Unicode | Special characters | "café ñ 中文" | [Output] |
| 9 | Concurrent | Race condition scenario | [Parallel calls] | [Consistent state] |
Error path tests:
| # | Error Condition | Input | Expected Behavior |
|---|---|---|---|
| 1 | Invalid input | [Bad input] | Throws [ErrorType] with message |
| 2 | Dependency failure | [DB timeout] | Returns fallback or propagates error |
| 3 | Permission denied | [Unauthorized] | Returns 403 / throws AuthError |
| 4 | Not found | [Missing resource] | Returns null or throws NotFoundError |
Step 4: Write the Tests
Test file naming conventions:
| Framework | Convention | Example |
|---|---|---|
| Jest / Vitest | [name].test.ts or [name].spec.ts | userService.test.ts |
| pytest | test_[name].py | test_user_service.py |
| Go | [name]_test.go | user_service_test.go |
| JUnit | [Name]Test.java | UserServiceTest.java |
Test naming conventions:
| Style | Pattern | Example |
|---|---|---|
| Behavior-driven | should [expected] when [condition] | should return empty array when no items match filter |
| Given-When-Then | given [state] when [action] then [result] | given expired token when authenticating then throws AuthError |
| Method-focused | [method], [scenario], [expected] | calculateTotal, with discount: applies percentage reduction |
Test structure template (JavaScript/TypeScript):
describe('[ModuleName]', () => {
// Setup shared across tests in this block
let dependency: MockType;
beforeEach(() => {
dependency = createMock();
// Reset state before each test
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('[methodName]', () => {
// Happy path
it('should [expected behavior] when [normal condition]', () => {
// Arrange
const input = { /* test data */ };
dependency.method.mockResolvedValue(expectedData);
// Act
const result = targetMethod(input);
// Assert
expect(result).toEqual(expectedOutput);
});
// Edge case
it('should [expected behavior] when [edge condition]', () => {
// Arrange
const input = { /* edge case data */ };
// Act
const result = targetMethod(input);
// Assert
expect(result).toEqual(edgeCaseOutput);
});
// Error path
it('should throw [ErrorType] when [error condition]', () => {
// Arrange
const input = { /* invalid data */ };
// Act & Assert
expect(() => targetMethod(input)).toThrow(ErrorType);
});
});
});
Test structure template (Python):
import pytest
from unittest.mock import Mock, patch
class TestModuleName:
"""Tests for [ModuleName]."""
def setup_method(self):
"""Reset state before each test."""
self.dependency = Mock()
# Happy path
def test_method_returns_expected_when_normal_input(self):
"""Should [expected behavior] when [condition]."""
# Arrange
input_data = {"key": "value"}
self.dependency.method.return_value = expected_data
# Act
result = target_method(input_data)
# Assert
assert result == expected_output
# Edge case
def test_method_handles_empty_input(self):
"""Should [expected behavior] when input is empty."""
result = target_method([])
assert result == []
# Error path
def test_method_raises_error_when_invalid_input(self):
"""Should raise ValueError when [condition]."""
with pytest.raises(ValueError, match="expected message"):
target_method(invalid_input)
Step 5: Mocking Strategy
Mock patterns by dependency type:
| Dependency | Mock Approach | Example |
|---|---|---|
| Database | Mock repository/ORM layer | jest.spyOn(db, 'query').mockResolvedValue(rows) |
| HTTP API | Mock HTTP client or use MSW/nock | nock('https://api.example.com').get('/users').reply(200, data) |
| File system | Mock fs module or use memfs | jest.mock('fs/promises') |
| Time/Date | Fake timers | jest.useFakeTimers(); jest.setSystemTime(new Date('2026-01-15')) |
| Random | Seed or mock | jest.spyOn(Math, 'random').mockReturnValue(0.5) |
| Environment | Set/restore env vars | process.env.NODE_ENV = 'test' in beforeEach |
| Third-party SDK | Mock the client | jest.mock('stripe', () => mockStripeClient) |
Mock verification patterns:
// Verify a dependency was called correctly
expect(mockDb.query).toHaveBeenCalledWith(
'SELECT * FROM users WHERE id = $1',
[userId]
);
// Verify call count
expect(mockApi.fetch).toHaveBeenCalledTimes(1);
// Verify NOT called (important for caching tests)
expect(mockDb.query).not.toHaveBeenCalled();
// Verify call order (important for transaction tests)
const order = [];
mockDb.begin.mockImplementation(() => order.push('begin'));
mockDb.commit.mockImplementation(() => order.push('commit'));
// ... run test ...
expect(order).toEqual(['begin', 'commit']);
Step 6: Integration & E2E Tests
Integration test patterns:
describe('[Feature] Integration', () => {
// Use real database (test instance), real logic, mock external APIs only
let testDb: TestDatabase;
beforeAll(async () => {
testDb = await createTestDatabase();
await testDb.migrate();
});
afterAll(async () => {
await testDb.destroy();
});
beforeEach(async () => {
await testDb.truncateAll(); // Clean state per test
});
it('should create user and send welcome email', async () => {
// Arrange, mock only the email service (external boundary)
const emailSpy = jest.spyOn(emailService, 'send').mockResolvedValue(true);
// Act: use real DB, real validation, real business logic
const user = await userService.register({
email: 'test@example.com',
name: 'Test User',
});
// Assert, verify real DB state + external call
const dbUser = await testDb.query('SELECT * FROM users WHERE id = $1', [user.id]);
expect(dbUser).toBeDefined();
expect(emailSpy).toHaveBeenCalledWith(
expect.objectContaining({ to: 'test@example.com' })
);
});
});
E2E test patterns (API):
describe('POST /api/users', () => {
it('should create a user and return 201', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'test@example.com', name: 'Test User' })
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: 'test@example.com',
});
});
it('should return 400 for invalid email', async () => {
const response = await request(app)
.post('/api/users')
.send({ email: 'not-an-email', name: 'Test' })
.expect(400);
expect(response.body.error).toContain('email');
});
it('should return 409 for duplicate email', async () => {
// Create first user
await request(app).post('/api/users').send({ email: 'dup@example.com', name: 'First' });
// Attempt duplicate
const response = await request(app)
.post('/api/users')
.send({ email: 'dup@example.com', name: 'Second' })
.expect(409);
});
});
Step 7: Coverage & CI Integration
Coverage targets:
| Level | Target | Rationale |
|---|---|---|
| Critical paths (auth, payments, data writes) | >90% | Bugs here = revenue loss or security issues |
| Business logic (services, domain) | >80% | Core value: must work correctly |
| Utilities / helpers | >70% | Important but lower risk |
| UI components | >60% | Visual testing often complements |
| Overall project | >75% | Healthy baseline |
CI configuration template (GitHub Actions):
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm test -- --coverage
- name: Check coverage thresholds
run: |
npx jest --coverage --coverageThreshold='{
"global": {
"branches": 75,
"functions": 80,
"lines": 80,
"statements": 80
}
}'
Test runner configuration:
// jest.config.js / vitest.config.ts
{
"collectCoverageFrom": [
"src/**/*.{ts,tsx}",
"!src/**/*.d.ts",
"!src/**/index.ts",
"!src/**/*.stories.tsx"
],
"coverageThresholds": {
"global": {
"branches": 75,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
Pre-commit test check:
# Only run tests related to changed files (fast feedback)
npx jest --onlyChanged
# or
npx vitest --changed
Output Format
# Test Suite: [Target Module/Function]
## Analysis
- **Target:** [What's being tested]
- **Dependencies:** [X] total ([X] mocked, [X] real)
- **Branching paths:** [X]
## Test Cases
### Unit Tests ([X] tests)
[Test code from Step 4]
### Edge Cases ([X] tests)
[Edge case tests from Step 3]
### Error Cases ([X] tests)
[Error path tests from Step 3]
### Integration Tests ([X] tests)
[Integration tests from Step 6, if requested]
## Coverage Summary
- Lines: [X]%
- Branches: [X]%
- Functions: [X]%
## CI Integration
[CI config from Step 7, if requested]
Completion
Test Writer: Complete!
Target: [Module/function name]
Tests written: [X] total
- Unit tests: [X]
- Edge cases: [X]
- Error cases: [X]
- Integration tests: [X]
Mocked dependencies: [X]
Estimated coverage: [X]%
Next steps:
1. Run the test suite: [test command]
2. Check coverage report for uncovered branches
3. Add tests to CI pipeline (config provided above)
4. Add pre-commit hook to run related tests on save
5. Review and adjust coverage thresholds quarterly
Level History
- Lv.1: Base: Code analysis template (inputs, outputs, dependencies, branches), 3-category test case design (happy path, edge cases, error paths), test templates for JS/TS and Python, 7 mock patterns by dependency type with verification, integration and E2E test patterns, coverage targets by code criticality, CI integration with GitHub Actions. (Origin: MemStack Pro v3.2, Mar 2026)
Webapp Testing: Writing browser tests...
Produces Playwright end-to-end tests that verify real user flows in a browser.
Activation
| Trigger | Status |
|---|---|
| User says "write browser tests" or "playwright test" | ACTIVE |
| User says "test this page" or "e2e test" | ACTIVE |
| User says "test the UI" or "browser test" | ACTIVE |
| User wants unit tests or API tests | NOT this skill: use standard test patterns |
| User wants load testing | NOT this skill |
Context Guard
- Do NOT use for unit tests (Jest, Vitest without browser)
- Do NOT use for API-only testing (use curl/fetch patterns)
- Do NOT use for performance benchmarking
- This skill ONLY produces Playwright browser tests
Steps
Step 1: Assess the target
Determine what to test:
| Parameter | How to find | Example |
|---|---|---|
| App URL | Check package.json scripts, .env, or ask | http://localhost:3000 |
| Framework | Check package.json dependencies | Next.js, React, SvelteKit |
| Auth required? | Check for login pages, auth middleware | Yes/No |
| Key user flows | Ask or infer from routes | Sign up, checkout, search |
# Check if Playwright is already installed
cat package.json | grep -i playwright
# Check existing test structure
find . -name "*.spec.ts" -o -name "*.test.ts" | head -20
Step 2: Set up Playwright (if not installed)
npm init playwright@latest
# or
pnpm add -D @playwright/test
npx playwright install
Confirm playwright.config.ts exists. If not, create with sensible defaults:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
Step 3: Write tests for each user flow
Follow this structure per flow:
import { test, expect } from '@playwright/test';
test.describe('Feature Name', () => {
test('should [expected behavior] when [action]', async ({ page }) => {
// Arrange, navigate to the page
await page.goto('/path');
// Act, perform user actions
await page.getByRole('button', { name: 'Submit' }).click();
// Assert, verify the result
await expect(page.getByText('Success')).toBeVisible();
});
});
Test writing rules:
- Use
getByRole,getByLabel,getByTextover CSS selectors: they survive refactors - One assertion per test where practical: clear failure messages
- Name tests as user stories: "should show error when email is invalid"
- Use
test.describeto group related flows - Add
test.beforeEachfor shared navigation/auth setup - Never hardcode waits, use
expectwith auto-waiting orwaitForSelector
Step 4: Handle authentication flows
If the app requires login:
// tests/e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('test@example.com');
await page.getByLabel('Password').fill('testpassword');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL('/dashboard');
// Save signed-in state
await page.context().storageState({ path: '.auth/user.json' });
});
Add to playwright.config.ts:
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: '.auth/user.json',
},
dependencies: ['setup'],
},
],
Step 5: Common test patterns
Form validation:
test('should show validation errors for empty required fields', async ({ page }) => {
await page.goto('/form');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByText('Email is required')).toBeVisible();
});
Navigation flow:
test('should navigate from landing to pricing', async ({ page }) => {
await page.goto('/');
await page.getByRole('link', { name: 'Pricing' }).click();
await expect(page).toHaveURL('/pricing');
await expect(page.getByRole('heading', { name: 'Pricing' })).toBeVisible();
});
API response verification:
test('should load and display data', async ({ page }) => {
await page.goto('/dashboard');
await expect(page.getByRole('table')).toBeVisible();
await expect(page.locator('tbody tr')).toHaveCount(10);
});
Step 6: Run and report
# Run all tests
npx playwright test
# Run specific test file
npx playwright test tests/e2e/auth.spec.ts
# Run with UI mode for debugging
npx playwright test --ui
# Show HTML report
npx playwright show-report
Present results:
Playwright tests written:
- [N] test files covering [N] user flows
- Auth setup: [yes/no]
- Flows tested: [list]
Run with: npx playwright test
Disambiguation
- "write browser tests" / "playwright test" / "e2e test" = Webapp Testing
- "write unit tests" / "jest test" / "vitest" = Standard test patterns (not this skill)
- "test the API" / "curl test" = API testing (not this skill)
- "verify my code" / "check this work" = Verify (not this skill)
Level History
- Lv.1: Base: Playwright test generation with role-based selectors, auth flows, common patterns, CI-ready config. (Origin: MemStack v3.5, Apr 2026)
Sponsors
Details
- Marketplace
- cwinvestments/memstack
- Source
- cwinvestments/memstack
- Category
- Productivity
- Keywords
- skills, memory, context, session, productivity, devops, security, database, deployment