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-memstack

Run it inside Claude Code after adding the marketplace with /plugin marketplace add cwinvestments/memstack.

Contents

Discovered from source

Skills 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

ContextStatus
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 systemsACTIVE
User wants a visual n8n workflowDORMANT: use n8n Workflow Builder
User wants to receive webhooksDORMANT: use Webhook Designer

Common Mistakes

MistakeWhy 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:

  1. Source system: where does the data come from? (API name, docs URL)
  2. Destination: where does it go? (your DB, another API, file)
  3. Data: what entities are synced? (users, orders, products, events)
  4. Direction: one-way, two-way, or event-driven?
  5. Auth: how does the API authenticate? (API key, OAuth 2.0, JWT, Basic)
  6. Volume: how much data? How often? (1K records/day vs 1M)

Step 2: Implement Authentication

Auth TypeImplementationToken Lifecycle
API KeyHeader: X-API-Key: {key} or query paramStatic: rotate manually
Bearer TokenHeader: Authorization: Bearer {token}Expires: refresh needed
OAuth 2.0Auth code flow → access + refresh tokensAuto-refresh on 401
JWTSign claims → Authorization: Bearer {jwt}Short-lived: re-sign
Basic AuthHeader: Authorization: Basic {base64}Static
HMACSign request body → custom headerPer-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:

PatternHow to DetectImplementation
Offset/limit?offset=0&limit=100Increment offset until empty results
Page number?page=1&per_page=100Increment page until last page
Cursor-basednext_cursor in responseUse cursor until null/empty
Link headerLink: <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

ContextStatus
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 distributionACTIVE
User wants a single blog postDORMANT: use Blog Post
User wants a single social media postDORMANT, use Twitter Thread or TikTok Script

Common Mistakes

MistakeWhy 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:

  1. Content types: what do you produce? (blog, newsletter, social, video, podcast)
  2. Platforms: where do you publish? (website, Twitter/X, LinkedIn, Instagram, YouTube, email)
  3. Frequency: how often? (daily, 3x/week, weekly)
  4. Team: who's involved? (writer, editor, designer, social manager)
  5. CMS: what do you use? (WordPress, Ghost, Notion, Webflow, headless CMS)
  6. 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:

StageOwnerInputOutputAutomation Level
IdeationContent leadKeyword research, trending topics, audience questionsContent briefSemi-auto (AI-assisted topic generation)
DraftWriterContent briefRaw draft (Markdown/Docs)Manual (AI-assisted)
ReviewEditorRaw draftEdited draft with feedbackManual
ApproveContent leadEdited draftApproved for publishingManual (checklist-gated)
FormatPipelineApproved contentPlatform-specific versionsFully automated
SchedulePipelineFormatted contentQueued posts with dates/timesFully automated
PublishPipelineScheduled postsLive content across platformsFully automated
MonitorMarketingPublished contentEngagement metricsSemi-auto (dashboard)

Step 3: Content Repurposing Matrix

Define how one piece of content becomes many:

Source→ Blog Post→ Twitter Thread→ LinkedIn→ Newsletter→ Instagram
Blog postOriginalKey points (5-10 tweets)Summary + insightsFeatured articleQuote card + carousel
VideoTranscript → postKey quotesBehind-the-scenesRecap + linkClips (15-60s)
PodcastShow notesSoundbite quotesEpisode summaryWeekly roundupAudiogram
NewsletterExpanded articleThread from sectionCross-postOriginalHighlight 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:

PlatformSizeAspect RatioMax File SizeFormat
Blog (hero)1200×6301.91:1200KBWebP (JPEG fallback)
Twitter1200×67516:95MBPNG/JPEG
LinkedIn1200×6271.91:15MBPNG/JPEG
Instagram (feed)1080×10801:18MBJPEG
Instagram (story)1080×19209:168MBJPEG
Newsletter600×3002:1100KBPNG/JPEG
Open Graph1200×6301.91:1200KBPNG/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):

PlatformBest DaysBest Times (ET)Frequency
BlogTue-Thu10 AM1-3x/week
Twitter/XMon-Fri8 AM, 12 PM, 5 PM1-3x/day
LinkedInTue-Thu7-8 AM, 12 PM3-5x/week
InstagramMon, Wed, Fri11 AM, 1 PM3-5x/week
NewsletterTue or Thu9-10 AM1x/week
YouTubeThu-Sat2-4 PM1-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):

MetricBlogTwitterLinkedInNewsletter
Views/ImpressionsPage viewsImpressionsImpressionsOpens
EngagementTime on pageLikes + repliesReactions + commentsClick rate
ConversionCTA clicksLink clicksLink clicksReply rate
Share/ViralSocial sharesRetweetsRepostsForwards

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

ContextStatus
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 monitoringACTIVE
User wants a visual n8n workflowDORMANT: use n8n Workflow Builder
User wants an event-driven webhookDORMANT: use Webhook Designer

Common Mistakes

MistakeWhy 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:

  1. Task: what does the job do? (sync data, send emails, clean up, generate reports)
  2. Schedule: how often? (every 5 min, hourly, daily at 2 AM, weekly)
  3. Duration: how long does a typical run take?
  4. Timezone: which timezone matters? (UTC, user's local, business hours)
  5. Platform: where does this run? (server crontab, cloud function, Docker, Kubernetes)
  6. 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:

ScheduleExpressionNotes
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 hour0 * * * *At minute 0 of every hour
Every 6 hours0 */6 * * *4x daily
Daily at 2 AM UTC0 2 * * *Maintenance window
Daily at 9 AM ET0 14 * * *14:00 UTC = 9:00 AM ET (EST, adjust for DST)
Weekdays at 8 AM0 8 * * 1-5Monday through Friday
Weekly (Sunday midnight)0 0 * * 0Weekly 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:

PlatformLock MethodTTL Support
RedisSET key value NX EX ttlYes
PostgreSQLpg_advisory_lock(id)Session-based
File systemflock or PID fileManual cleanup
DynamoDBConditional put with TTLYes
KubernetesCronJob concurrencyPolicy: ForbidBuilt-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:

ConditionSeverityAction
Job didn't run (missed heartbeat)CriticalPage on-call
Job failed (error thrown)HighSlack + email alert
Job duration > 2x normalWarningSlack notification
Job processed 0 items (expected >0)WarningReview logs
Job overlap detected (lock contention)InfoLog, 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

TriggerStatus
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 serverNOT this skill: use mcp-builder
User wants to configure local MCPNOT 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:

ServerURLToolsUse Case
Vercelhttps://mcp.vercel.comDeploy, logs, env vars, projectsVercel deployment management
Supabasehttps://mcp.supabase.com/mcpDB queries, migrations, RLSDatabase management
Sentryhttps://mcp.sentry.dev/mcpIssues, errors, performanceError tracking
Stripehttps://mcp.stripe.comPayments, customers, invoicesPayment processing
Linearhttps://mcp.linear.app/mcpIssues, projects, cyclesProject management
Slackhttps://mcp.slack.com/mcpMessages, channels, searchTeam communication
Greptilehttps://api.greptile.com/mcpCodebase search, understandingCode 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 databaseSupabase
Track errors/bugsSentry
Deploy codeVercel
Process paymentsStripe
Manage issues/ticketsLinear
Send team messagesSlack
Search codebasesGreptile

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:

  1. The server appears in the MCP tools list
  2. Authentication completes (if required)
  3. A simple tool call succeeds

Discovery Resources

When the catalog above doesn't cover the user's need:

ResourceURLDescription
Anthropic MCP Registryhttps://github.com/modelcontextprotocol/serversOfficial MCP server list
Smitheryhttps://smithery.aiMCP server marketplace
MCP.sohttps://mcp.soCommunity MCP directory
Glamahttps://glama.ai/mcp/serversCurated 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

ContextStatus
User says "n8n workflow", "build a workflow", "automation workflow"ACTIVE
User says "connect services" or wants visual automationACTIVE
User wants to automate a multi-step process with n8nACTIVE
User needs a standalone webhook endpointDORMANT: use Webhook Designer
User needs a cron/scheduled job without n8nDORMANT: use Cron Scheduler

Common Mistakes

MistakeWhy 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:

  1. Trigger: what starts the workflow? (webhook, schedule, app event, manual)
  2. Input: what data comes in? (payload shape, source service)
  3. Actions: what should happen step-by-step?
  4. Output: where does the result go? (database, API, email, Slack, file)
  5. Error handling: what happens if a step fails?
  6. Frequency: how often does this run? (per event, hourly, daily)

Step 2: Select Trigger Node

Trigger Typen8n NodeWhen to Use
Incoming webhookWebhookExternal service sends data to you
ScheduleSchedule TriggerRun at fixed intervals (cron)
App event[App] TriggerSlack message, GitHub PR, Stripe payment, etc.
ManualManual TriggerTesting or on-demand execution
EmailEmail Trigger (IMAP)React to incoming emails
File changeLocal File TriggerWatch a directory for new files
Another workflowExecute Workflow TriggerSub-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:

PatternNodesUse Case
Filter & routeIF / SwitchRoute data based on conditions
TransformSet / Code / Item ListsReshape data between nodes
Batch processSplitInBatches → LoopProcess large datasets without timeout
Merge streamsMergeCombine data from parallel branches
Lookup & enrichHTTP Request → MergeAdd data from external APIs
DeduplicateCode (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:

TransformationNodeExpression Example
Rename fieldSetnewName: {{ $json.oldName }}
Format dateSet / Code{{ DateTime.fromISO($json.date).toFormat('yyyy-MM-dd') }}
Filter itemsIF{{ $json.status === 'active' }}
ConcatenateSet{{ $json.first + ' ' + $json.last }}
Parse JSON stringCodeJSON.parse($json.rawBody)
Map arrayCodeitems.map(i => ({ json: { id: i.json.id } }))
AggregateCode[{ 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:

LayerImplementationPurpose
Node retrySettings → Retry on Fail (max 3, wait 1s)Transient failures (network, rate limits)
Error TriggerError Trigger node → notification workflowCatch any unhandled errors
Dead letterOn error → write to DB/queue for later replayDon'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

ContextStatus
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 eventsACTIVE
User wants a full n8n automation workflowDORMANT: use n8n Workflow Builder
User wants a scheduled/cron jobDORMANT: use Cron Scheduler

Common Mistakes

MistakeWhy 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:

  1. Source: what service sends the webhook? (Stripe, GitHub, Shopify, custom)
  2. Events: which events do you need to handle? (e.g., payment.completed, push)
  3. Payload: what does the payload look like? (JSON schema or example)
  4. Auth: how does the source authenticate? (HMAC, bearer token, IP whitelist)
  5. Processing: what should happen when an event arrives?
  6. 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:

ProviderHeaderAlgorithmPrefix
StripeStripe-SignatureHMAC-SHA256t=timestamp,v1=signature
GitHubX-Hub-Signature-256HMAC-SHA256sha256=
ShopifyX-Shopify-Hmac-Sha256HMAC-SHA256 (base64)None
TwilioX-Twilio-SignatureHMAC-SHA1 (base64)None
SlackX-Slack-SignatureHMAC-SHA256v0=
CustomX-Webhook-SignatureHMAC-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

ContextStatus
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 engagementACTIVE
User wants a contract or agreementDORMANT: use Contract Template
User wants to send an invoiceDORMANT: use Invoice Generator

Common Mistakes

MistakeWhy 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:

  1. Client: company name, primary contact, industry
  2. Project: what was sold? (service type, scope, deliverables)
  3. Timeline: start date, key milestones, end date
  4. Communication: preferred channel (email, Slack, calls)?
  5. 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):

#ItemStatusOwnerNotes
1Website CMS login[ ] PendingClient[URL]
2Google Analytics (Editor access)[ ] PendingClientAdd [email]
3Google Search Console[ ] PendingClientAdd [email]
4Social media accounts[ ] PendingClient[Platforms]
5Email marketing platform[ ] PendingClient[Platform]
6Brand assets (logo, fonts, guide)[ ] PendingClientShared drive link
7Hosting / DNS access[ ] PendingClient[Provider]
8Payment processor (if applicable)[ ] PendingClient[Stripe, etc.]
9Project management tool invite[ ] PendingYouAdd client to [tool]
10Slack / Teams channel setup[ ] PendingYouCreate 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

CheckpointWhenFocusFormat
Week 1Day 5Quick pulse: any blockers? Access complete?15-min call or Slack
30 daysDay 30Progress review, milestone check, feedback loop30-min call
60 daysDay 60Mid-project review, scope check, quality audit30-min call
90 daysDay 90Results review, project wrap-up or renewal45-min call

Check-in agenda (30/60/90):

  1. Progress update: what's been completed, what's next
  2. Metrics review: are we hitting the success criteria?
  3. Client satisfaction: what's working, what could improve?
  4. Scope check: any changes needed? (change order if yes)
  5. 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

ContextStatus
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 workACTIVE
User wants an invoiceDORMANT: use Invoice Generator
User wants a project proposalDORMANT: use Proposal Writer

Common Mistakes

MistakeWhy 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:

  1. Contract type: service agreement, NDA, subcontractor agreement, or other?
  2. Parties: who is the provider and who is the client?
  3. Scope: what work is being performed?
  4. Payment: flat fee, hourly, retainer, milestone-based?
  5. Duration: start date, end date, or ongoing?
  6. Special terms: non-compete, exclusivity, IP considerations?

Step 2: Select Contract Type

TypeUse WhenKey Clauses
Service AgreementProviding professional services to a clientScope, payment, IP, liability, termination
NDA (Mutual)Both parties share confidential informationDefinition of confidential info, exclusions, duration, remedies
NDA (One-way)Only one party shares confidential infoSame as mutual but obligations on one side
Subcontractor AgreementHiring someone to help deliver client workScope, payment, IP assignment, confidentiality, non-solicitation
Retainer AgreementOngoing monthly services at a fixed rateHours/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

ContextStatus
User says "financial model", "projections", "revenue forecast"ACTIVE
User mentions MRR, churn, CAC, LTV, runway, or break-evenACTIVE
User wants to forecast revenue, expenses, or cash flowACTIVE
User wants to set pricing tiersDORMANT: use Pricing Strategy
User wants to generate an invoiceDORMANT: use Invoice Generator

Common Mistakes

MistakeWhy 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:

  1. Business model: SaaS, e-commerce, service, marketplace, or other?
  2. Revenue streams: subscriptions, one-time sales, services, ads?
  3. Current numbers: existing revenue, customers, growth rate?
  4. Pricing: price points, tiers, average revenue per user?
  5. Costs: known fixed and variable costs?
  6. 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)
MonthStartingNewChurnedEndingMRRARR
10[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:

MetricValueTargetStatus
ARPU (monthly)$[X]nonenone
Monthly churn rate[X]%<5%[OK / At Risk]
CAC$[X]nonenone
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):

CategoryMonthly CostAnnual CostNotes
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):

CategoryCost BasisMonthly EstimateNotes
Hosting / infrastructure[X]% of revenue$[X]Scales with users
Payment processing2.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 1Mo 3Mo 6Mo 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:

AssumptionWorst CaseBase CaseBest Case
Monthly new customers[X][X][X]
Monthly churn rate[X]%[X]%[X]%
ARPU$[X]$[X]$[X]
Marketing spend$[X]$[X]$[X]
Hiring timelineDelayedOn timeAccelerated

12-month outcome by scenario:

MetricWorstBaseBest
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 monthMo [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:

MonthRevenueExpensesNetCumulative
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

TriggerStatus
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 SOWNOT this skill, use Proposal Writer or Scope of Work
User wants a generic invoice templateNOT 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

ParameterDefaultExample
Hourly rateAsk$150/hr, $85/hr
CurrencyUSDEUR, GBP, AUD
Billing cycleMonthlyWeekly, per-project
ClientsAskAcme Corp, StartupX
Tax rate0% (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:

  1. Log daily, reconstructing from memory loses hours
  2. Separate billable from non-billable (admin, learning, invoicing)
  3. Round to nearest 15 minutes (0.25 hr increments)
  4. Include project and task for accurate per-project reporting
  5. 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:

AlertThresholdAction
Low utilization< 70% billableReview non-billable time, reduce admin overhead
Client concentration> 50% one clientDiversify: pursue new leads
Outstanding invoices> 30 daysSend payment reminder
Effective rate below target< 80% of hourly rateReview scope creep, renegotiate
Overwork> 45 hrs/week sustainedRaise 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

ContextStatus
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 GDPRACTIVE
User wants a generic security auditDORMANT: use owasp-top10
User wants a service agreement or NDADORMANT: use contract-template
User wants RLS / database access policiesDORMANT: use rls-checker

Common Mistakes

MistakeWhy 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:

ClassExamplesGDPR Treatment
Identifiername, email, phone, address, account ID, IPStandard personal data, Art 6 lawful basis required
Financialcard number, bank account, billing addressStandard personal data + PCI scope considerations
Locationprecise GPS, geo, IP-derived cityStandard personal data; precise location may require explicit consent
Behavioralclickstream, page views, session recording, fingerprintStandard personal data; consent for non-essential cookies/tracking
Government IDpassport, SSN, national ID, driver's licenceStandard personal data but elevated risk; often national-law restricted
Special category (Art 9health, biometric, genetic, race, ethnicity, religion, political, sexual orientation, trade-unionProhibited unless an Art 9(2) condition applies) almost always explicit consent
Children's data, Art 8any data from users under 16 (age varies 13 to 16 by member state)Requires parental consent for information-society services
Criminal data, Art 10offences, convictionsOnly 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:

ScenarioVerdictCriticality
No personal data at allGDPR does not applyNone
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 subjectsGDPR applies🟨 MEDIUM
Identifiers + financial / location / behavioral trackingGDPR applies, multiple obligations🟧 HIGH
Any Art 9 special category dataGDPR applies, strict🟥 CRITICAL
Any children's dataGDPR applies, strict + Art 8 parental consent🟥 CRITICAL
Large-scale systematic monitoring or profilingGDPR applies, DPIA required🟥 CRITICAL

Step 4: Map required roles

Based on the verdict, list which roles the project must staff:

RoleTriggered WhenStatus
Controller (Art 4(7))Project decides purposes and means of processing: almost always youRequired
Joint controllers (Art 26)Shared decisions with another orgCheck
Processor (Art 4(8))You process data on behalf of another controllerCheck
DPO (Art 37)Public authority, OR core activities = large-scale systematic monitoring, OR core activities = large-scale special categoryRequired if any trigger
Art 27 EU representativeController/processor not established in EU but processes EU data, AND processing is not occasionalRequired if any trigger
Internal ownerEvery project, accountable for GDPR posture day-to-dayRequired

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:

ArticleObligationTriggered?Concrete action
Art 5: PrinciplesLawfulness, fairness, transparency, purpose limitation, minimisation, accuracy, storage limitation, integrity, accountabilityAlwaysDocument each principle is met
Art 6, Lawful basisPick one of 6 bases per processing activityAlwaysAdd lawful basis column to ROPA
Art 7: Conditions for consentIf any basis is consentIf consentImplement explicit, granular, withdrawable consent UI
Art 8, ChildrenIf under-16 usersIf childrenParental consent flow
Art 9, Special categoryIf health/biometric/etc.If Art 9 dataExplicit consent + extra safeguards
Art 13/14, TransparencyPrivacy notice at collectionAlwaysPublish privacy policy that mirrors actual processing
Art 15 to 22: Subject rightsAccess, rectification, erasure, restriction, portability, objection, ADMAlwaysImplement DSAR endpoint + 30-day SLA
Art 25, Privacy by designDefault settings minimise dataAlwaysCode review checklist
Art 28, ProcessorsWritten DPA before processingIf any processorSign DPAs with every vendor
Art 30, ROPARecord of Processing ActivitiesIf 250+ employees OR not occasional OR Art 9Maintain ROPA
Art 32: SecurityTIA-equivalent technical/organisational measuresAlwaysDocument encryption, access control, backups
Art 33, Breach to authority72h notificationAlwaysBreach runbook
Art 34, Breach to subjectsWithout undue delay if high riskAlwaysSubject notification template
Art 35, DPIAHigh-risk processingIf profiling/large scale/Art 9Run DPIA before launch
Art 37 to 39, DPOIf triggered (see Step 4)If triggeredAppoint and publish
Chapter V, TransfersInternational transfersIf anySCCs / 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

ContextStatus
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 clientACTIVE
User wants a contract or service agreementDORMANT: use Contract Template
User wants financial projectionsDORMANT: use Financial Model

Common Mistakes

MistakeWhy 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:

  1. Client: company name, contact person, billing address
  2. Your business: business name, address, tax ID / EIN (if applicable)
  3. Line items: what are you billing for? (description, quantity, rate)
  4. Payment terms: Net 30, Net 15, due on receipt?
  5. Tax: applicable tax rate? (state sales tax, VAT, or exempt)
  6. Currency: USD, EUR, GBP, etc.?

Step 2: Generate Invoice Number

Invoice numbering convention:

[PREFIX]-[YEAR][MONTH]-[SEQUENCE]
Example: INV-202603-001
ComponentRule
PrefixINV (standard), PRO (proforma), CR (credit note)
DateYYYYMM of invoice date
Sequence001, 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:

#DescriptionQtyUnitRateAmount
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:

TermMeaningBest For
Due on receiptPay immediatelySmall amounts, first-time clients
Net 15Due within 15 daysFreelance, small projects
Net 30Due within 30 daysStandard business term
Net 60Due within 60 daysEnterprise, government
50/5050% upfront, 50% on completionProjects >$5,000
MilestonePayment at each project phaseLarge 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

ContextStatus
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, copyleftACTIVE
User is preparing to ship, sell, or relicense a productACTIVE
User wants security vulnerability scanningDORMANT: use dependency-audit
User wants a service contract or NDADORMANT: use contract-template

Common Mistakes

MistakeWhy 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.

StackManifestDiscovery command
Node.jspackage.json, package-lock.json, pnpm-lock.yaml, yarn.locknpm ls --all --json then npx license-checker --json --production
Pythonrequirements*.txt, pyproject.toml, Pipfile.lock, poetry.lockpip-licenses --format=json --with-license-file --with-urls
RustCargo.toml, Cargo.lockcargo license --json
Gogo.mod, go.sumgo-licenses report ./... --template '{{.Name}},{{.LicenseName}},{{.LicenseURL}}'
Javapom.xml, build.gradlemvn license:add-third-party or gradle-license-report
RubyGemfile, Gemfile.lockbundle exec license_finder report --format json
PHPcomposer.json, composer.lockcomposer licenses --format=json
.NET*.csproj, packages.lock.jsondotnet list package --include-transitive + nuget-license
Container base imagesDockerfilesyft <image> -o spdx-json then read package licenses
Vendored / submodulesvendor/, third_party/, .gitmoduleswalk directories: look for LICENSE, LICENSE.md, COPYING, NOTICE
Fonts / icons / mediaassets/, public/, static/check each asset's source license: commonly missed
Snippets and copy-pasted codecomments, 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:

ProjectVersion cutOld → New
Elasticsearch7.10 → 7.11Apache-2.0 → SSPL/Elastic
Redis7.2 → 7.4BSD → SSPL/RSAL
Terraform1.5 → 1.6MPL-2.0 → BSL
MongoDB4.0AGPL → SSPL
HashiCorp tools2023MPL-2.0 → BSL
Sentry8.xBSD → 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

ClassExamplesCommercial use allowed?Reach
Public domainCC0, Unlicense, WTFPL, 0BSDYes: no obligationsNone
PermissiveMIT, BSD-2/3, ISC, Apache-2.0, ZlibYes: preserve noticeNone
Weak copyleftLGPL-2.1, LGPL-3.0, MPL-2.0, EPL-2.0Yes with obligationsFile-level (MPL) or dynamic-linking carve-out (LGPL)
Strong copyleftGPL-2.0, GPL-3.0Yes, but derivative works become GPL on distributionWhole derivative work
Network copyleftAGPL-3.0Yes, but SaaS triggers source disclosureWhole derivative work + network use
Source-available (non-OSI)BSL, SSPL, Elastic v2, Commons Clause, RSAL, FSLRestricted: usually no competing hosted servicePer terms
Creative CommonsCC-BY, CC-BY-SA, CC-BY-NC, CC-BY-NDNC = no commercial; SA = share-alike; ND = no derivativesPer variant
Proprietary / commercial EULAVendor SDKs, paid librariesPer contractPer contract
Unknown / no licenseNo LICENSE fileNo, all rights reserved by defaultN/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:

VerdictSymbolMeaning
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 classA. SaaSB. BinaryC. OSS libraryD. 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 EULAper contractper contractper contractper 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.

ContextStatus
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 clientACTIVE
Writing internal project plans (no client)DORMANT: use scope-of-work
Discussing pricing strategy generallyDORMANT

Anti-patterns

TrapReality 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:

  1. Client name and company
  2. Project type (web app, mobile app, marketing site, API, etc.)
  3. Core problem: what does the client need solved?
  4. Rough scope: key features or deliverables
  5. Timeline: any deadlines or target launch date?
  6. 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:

  1. Name the problem the client faces, in their language, not technical jargon
  2. Present the solution at a high level, what you'll build and why it works
  3. State the outcome: what the client gets (revenue, time saved, users served)
  4. 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.

ContextStatus
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 engagementACTIVE
Writing internal task lists (no formal scope needed)DORMANT: use Work skill
Writing a proposal (includes pricing/sales)DORMANT: use proposal-writer

Anti-patterns

TrapReality 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.

ContextStatus
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 workflowACTIVE
Writing a one-time guide or tutorialDORMANT
Discussing process improvement at a high levelDORMANT

Anti-patterns

TrapReality 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:

  1. Process name: clear, specific title
  2. Audience: who will follow this SOP? (developer, ops, new hire, non-technical)
  3. Trigger: what event kicks off this process? (PR merged, customer request, scheduled)
  4. Frequency: how often is this run? (daily, weekly, per release, ad-hoc)
  5. 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
  1. 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 ci and 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: Yes step 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
  1. 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

  1. Post in #incidents: "Rolled back [deployment name]. Investigating [brief issue]."
  2. Update status page if customer-facing
  3. 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

ContextStatus
User says "tokenstack", "compression stats", "check proxy"ACTIVE - run status check
User asks about token savings or context windowACTIVE - point to dashboard report
Proxy errors or API connection failures appearACTIVE - run health diagnostics
General discussion about CC featuresDORMANT - 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:8787 and sets ANTHROPIC_BASE_URL automatically.
  • 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

TierTransforms
FreeSix lossless text reductions, always applied
ProAdds 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

SymptomFix
No response on /healthProxy 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 ProLicense cache may be stale. The proxy revalidates the license on next start.
Cost figures differ from Anthropic ConsoleEstimates 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

SkillScopeWhen to Use
Token OptimizationFull TokenStack overview, enable steps, transform tablesUnderstanding or turning on compression
Compress (this)Health, routing, troubleshootingProxy 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 /stats curl; 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.

ContextStatus
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 publicationACTIVE
Writing landing page copy (short-form, conversion-focused)DORMANT: use landing-page-copy
Writing email contentDORMANT: use email-sequence
Writing social media postsDORMANT

Anti-patterns

TrapReality 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:

  1. Topic: what's this post about?
  2. Target audience: who are you writing for? (developers, business owners, beginners, etc.)
  3. Target keyword: what search term should this rank for?
  4. Tone: casual/conversational, professional, technical, inspirational?
  5. 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:

  1. Identify 3-5 key points the post must cover
  2. Find supporting data: statistics, examples, or case studies that strengthen each point
  3. Note counterarguments: addressing objections builds credibility
  4. 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):

  1. Hook: bold claim, surprising stat, relatable pain point, or provocative question
  2. Relevance: why this matters to the reader right now
  3. 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
MetricTargetWhy
Flesch-Kincaid Grade8 or belowAccessible to 80% of readers
Sentence lengthAverage 15-20 wordsLonger sentences lose readers
Paragraph lengthMax 3-4 sentencesShort paragraphs feel faster
Passive voiceBelow 10%Active voice is direct and clear
Adverb usageMinimal"Ran quickly" loses to "sprinted"
JargonDefine or avoidUnless 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.

ContextStatus
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 campaignACTIVE
Writing a single one-off emailDORMANT, just write the email directly
Writing newsletter contentDORMANT
Writing email for support or personal communicationDORMANT

Anti-patterns

TrapReality 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:

  1. Product/service: what are you promoting or onboarding for?
  2. Target audience: who receives these emails? (new signups, leads, customers, etc.)
  3. 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)
  4. Entry trigger: what puts someone into this sequence? (signup, purchase, abandoned cart, etc.)
  5. 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:

GoalEmailsCadenceArc
Nurture5-7Every 2-3 daysWelcome → Story → Value → Value → Soft pitch → Hard pitch → Last chance
Launch4-6Daily during launch weekAnnouncement → Behind-the-scenes → Early access → Launch day → Reminder → Last chance
Onboarding3-5Day 0, 1, 3, 7, 14Welcome → Quick win → Key feature → Advanced tip → Check-in
Re-engagement3-4Every 3-5 daysMiss 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.

ContextStatus
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 pageACTIVE
Writing blog content (long-form, educational)DORMANT: use blog-post
Writing email copyDORMANT: use email-sequence
Designing the page layout (not writing copy)DORMANT

Anti-patterns

TrapReality 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:

  1. Product/service name: what are we selling?
  2. Target audience: who is the ideal customer? (role, pain point, situation)
  3. Key benefit: what's the #1 thing they get? (in their words, not yours)
  4. Price point: free, freemium, one-time, subscription? (affects urgency strategy)
  5. CTA goal: what's the primary action? (sign up, buy, book a call, download)
  6. 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:

FormulaExample
[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

ContextStatus
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 newsletterACTIVE
User wants a lead magnet with email captureDORMANT: use Lead Magnet
User wants a full content automation pipelineDORMANT: use Content Pipeline

Common Mistakes

MistakeWhy 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:

  1. Topic/niche: what's the newsletter about?
  2. Audience: who reads it? (role, industry, experience level)
  3. Frequency: weekly, biweekly, or monthly?
  4. Type: curated links, original essays, tips, industry news, or mixed?
  5. Current state: new or existing? (subscriber count, open rates)
  6. Monetization: free, paid, or sponsored?

Step 2: Write the Subject Line

Subject line formulas:

FormulaTemplateExample
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"
QuestionWhy [common practice] [doesn't work / is wrong]?"Why your landing page isn't converting?"
PersonalI [did thing], here's what happened"I quit meetings for a month"
Direct valueHow 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):

SectionContentPurpose
Deep DiveOriginal essay or analysis (500-800 words)Demonstrate expertise
Quick Hits3-5 curated links with one-line summariesDeliver breadth of value
Tool/ResourceFeatured tool with your take on itPractical value
Tip of the WeekOne actionable tactic they can use todayQuick win
Community SpotlightReader question, testimonial, or submissionBuild community
Sponsor SectionSponsored content (clearly labeled)Monetization
Poll/QuestionAsk readers something: drives repliesEngagement 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:

TechniqueImplementationImpact
First name in subject"Hey {first_name}, [subject]"+10-15% open rate
Segment by interestTag subscribers → send relevant content+20-30% click rate
Reference past behavior"Since you read about [topic]..."Higher engagement
Reader-submitted contentFeature reader questions or winsCommunity loyalty

Step 5: Link Placement Strategy

Link placement hierarchy:

PositionPurposeClick Priority
Above the fold (first 100 words)Primary CTA or featured linkHighest
End of main sectionDeeper reading linkHigh
Quick hits sectionCurated resource linksMedium
CloserSocial follow or referral linkLow

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:

ChannelTacticExpected Growth
WebsiteEmail capture in header, footer, and exit-intent popupSteady baseline
Social mediaShare a highlight from each edition with subscribe link5-15 subs/post
Twitter/X threadsEnd threads with "I go deeper in my newsletter: [link]"10-50 subs/thread
Cross-promotionSwap recommendations with similar-sized newsletters50-200 per swap
Referral program"Refer 3 friends → get [bonus]"10-20% of new subs
Gated contentBest content behind email signup (lead magnet)High conversion
Guest postsWrite for others, link to newsletter in bio20-100 per post

Retention metrics to track:

MetricTargetRed 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% monthlyNegative (losing subs)

Step 7: Scheduling & Send Optimization

Optimal send times:

AudienceBest DayBest TimeWhy
Business / B2BTuesday-Thursday9-10 AM localMorning inbox check
Creators / SoloTuesday or Saturday8-9 AM localBefore the day fills up
DevelopersWednesday10 AM localMid-week engagement peak
General / ConsumerSunday or Tuesday9-10 AM localWeekend 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

ContextStatus
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 listingACTIVE
User wants to set pricingDORMANT: use Pricing Strategy
User wants a full sales funnelDORMANT: use Sales Funnel

Common Mistakes

MistakeWhy 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:

  1. Product: what is it? (name, category, physical/digital)
  2. Features: what are its key specs and features? (list 5-10)
  3. Audience: who buys this? (demographics, use case, pain point)
  4. Platform: where is it listed? (Amazon, Shopify, Etsy, other)
  5. Price point: what does it cost? (affects copy tone and positioning)
  6. 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:

SenseWordsUse For
TouchSilky, rugged, lightweight, cushioned, velvetyClothing, furniture, tools
SightVibrant, sleek, crystal-clear, polished, matteElectronics, decor, fashion
SoundWhisper-quiet, crisp, deep bass, silentElectronics, appliances
TasteRich, smooth, zesty, creamy, boldFood, beverages
SmellFresh, earthy, aromatic, clean, invigoratingCandles, 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 TypeWhere to UseExample
Primary keywordTitle, first sentence of description"insulated water bottle"
Secondary keywordsBullet points, body description"BPA-free", "stainless steel", "cold 24 hours"
Long-tail keywordsBackend/tags, lower in description"best water bottle for hiking 2026"
Competitor keywordsBackend/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

ContextStatus
User says "TikTok script", "TikTok video", "Reels script", "Shorts script"ACTIVE
User says "short-form video" and wants a scripted 15-60 second videoACTIVE
User wants to create content for TikTok, Instagram Reels, or YouTube ShortsACTIVE
User wants a Twitter/X threadDORMANT: use Twitter Thread
User wants a long-form video (YouTube)DORMANT: use YouTube Script

Common Mistakes

MistakeWhy 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:

  1. Topic: what's the video about?
  2. Format: talking head, tutorial, storytime, POV, or visual showcase?
  3. Platform: TikTok, Instagram Reels, YouTube Shorts, or all three?
  4. Length: 15s, 30s, or 60s?
  5. Goal: views, followers, website traffic, or product sales?
  6. Audience: who's watching? (age, interests, awareness level)

Step 2: Choose Video Format

FormatBest ForHook Style
Talking headTips, hot takes, storytellingDirect eye contact + bold statement
Tutorial/how-toTeaching a skill, showing a process"Here's how to [outcome] in [X] seconds"
StorytimePersonal experience, relatable content"The time I [dramatic event]..."
POVRelatable situations, humorText overlay: "POV: [situation]"
Before/AfterTransformations, resultsShow the "after" first (pattern interrupt)
Duet/StitchReacting to trends, adding commentaryResponse to existing content
Visual showcaseProducts, travel, foodSatisfying 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:

FormulaExampleOn-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 interruptStart mid-action, unexpected visual[Eye-catching visual]
Controversy"Unpopular opinion: [take]""UNPOPULAR OPINION"
Result firstShow 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:

TimestampShot TypeDescriptionText Overlay
0:00Close-upFace, direct eye contactHook text (bold)
0:02MediumUpper body, gesturingnone
0:05B-roll / screenDemo or visualStep 1 text
0:10Close-upBack to face, different angleStep 2 text
0:15B-roll / screenSecond demoStep 3 text
0:20MediumWrap-up, high energyCTA 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:

FormatAudio Strategy
Talking headYour voice only, OR voice over trending sound at 10% volume
TutorialVoiceover narration + trending sound at low volume
StorytimeYour voice with ambient/emotional background music
POVTrending sound at full volume (lip sync or background)
Visual showcaseTrending 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):

TypeExamplePurpose
Niche-specific#saastips #ecommercetipsReach your target audience
Trending#fyp #viral #trendingAlgorithmic boost
Content-type#learnontiktok #tutorialPlatform-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

ContextStatus
User says "twitter thread", "tweet thread", "X thread"ACTIVE
User says "viral thread" or wants multi-tweet contentACTIVE
User wants to share insights, stories, or frameworks on Twitter/XACTIVE
User wants a TikTok or Reels scriptDORMANT: use TikTok Script
User wants a newsletterDORMANT: use Newsletter

Common Mistakes

MistakeWhy 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:

  1. Topic: what's the thread about?
  2. Angle: personal story, tactical how-to, hot take, data breakdown, or curated list?
  3. Goal: followers, engagement, traffic to a link, or brand awareness?
  4. Length: short (5-7 tweets), medium (8-12), or long (13-15)?
  5. Key points: what are the 3-5 main takeaways?

Step 2: Choose Thread Structure

StructureBest ForPattern
Story arcPersonal experience, case studySetup → Conflict → Turning point → Resolution → Lesson
ListicleTips, tools, resourcesHook → Item 1 → Item 2 → ... → Summary → CTA
FrameworkTeaching a methodHook → Context → Step 1 → Step 2 → Step 3 → Recap → CTA
ContrarianHot takes, challenging normsBold claim → Evidence 1 → Evidence 2 → Nuance → Reframe → CTA
Before/AfterTransformations, resultsOld way → Problems → Discovery → New way → Results → CTA

Step 3: Write the Hook (Tweet 1)

The hook tweet determines 90% of thread performance.

Hook formulas:

FormulaTemplateExample
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:

GoalCTA 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.

ContextStatus
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 platformACTIVE
Writing a blog post (not video)DORMANT: use blog-post
Writing a podcast outlineDORMANT
Discussing YouTube strategy at a high levelDORMANT

Anti-patterns

TrapReality 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:

  1. Topic: what's this video about?
  2. Target viewer: who is watching? (beginner dev, business owner, tech enthusiast, etc.)
  3. Video length goal: short (5-8 min), standard (10-15 min), long-form (20+ min)?
  4. CTA goal: what should viewers do? (subscribe, click a link, watch next video, buy)
  5. Channel context: is this part of a series? What's the channel about?
  6. 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 TypeWhen to UseExample
B-roll cutEvery 30-60 seconds of talking headShow the thing being discussed
On-screen textKey stats, definitions, listsBold text highlighting the main point
Camera angle changeEvery 2-3 minutesSwitch between close-up and medium shot
Music shiftSection transitionsBackground music changes mood
Direct addressWhen making a key pointLook directly at camera, pause, then speak
Screen recordingTutorial/demo sectionsSwitch 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 LengthSectionsTime per SectionPattern Breaks
5-8 minutes31.5-2 min eachEvery 45-60 sec
10-15 minutes4-52-3 min eachEvery 60-90 sec
20+ minutes6-82.5-3.5 min eachEvery 60-90 sec

Step 5: Write Section Transitions

Transitions keep viewers watching through section boundaries (where most drop-off happens):

Transition formulas:

TypeTemplateWhen 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...

ContextStatus
User says "CI/CD", "pipeline", "GitHub Actions"ACTIVE
User wants automated testing and deploymentACTIVE
User mentions branch strategy, deploy gates, or rollbacksACTIVE
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 onlyDORMANT, 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 SignalPlatform RecommendationReason
.github/ existsGitHub ActionsAlready on GitHub, native integration
vercel.json or Next.jsVercel (auto-deploy) + GitHub Actions (CI)Vercel handles deploy, GHA handles testing
railway.jsonRailway (auto-deploy) + GitHub Actions (CI)Railway handles deploy, GHA handles testing
netlify.tomlNetlify (auto-deploy) + GitHub Actions (CI)Netlify handles deploy, GHA handles testing
Dockerfile presentGitHub Actions → Docker registry → deployFull control pipeline
Monorepo (packages/)GitHub Actions with matrix/path filtersNeed per-package CI
Self-hosted serverGitHub Actions → SSH deployPush-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:

StageTriggerFailure ActionDuration Target
LintEvery push, every PRBlock merge< 1 min
TestEvery push, every PRBlock merge< 5 min
BuildPR merge to main/developBlock deploy< 3 min
DeployBuild passes on target branchAlert + rollback< 2 min
VerifyAfter deploy completesAuto-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)
BranchDeploys ToCI RunsAuto-Deploy?
feature/*noneLint + TestNo
developStagingLint + Test + Build + DeployYes
mainProductionLint + Test + Build + DeployYes (or manual gate)
hotfix/*noneLint + TestNo (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_TOKEN for 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:

TargetRollback MethodSpeedData Safety
VercelInstant rollback in dashboard or CLIInstantSafe: immutable deploys
Railwayrailway rollback or dashboardInstantSafe: previous deploy preserved
NetlifyDeploy previous build in dashboardInstantSafe: immutable deploys
DockerTag previous image as latest, restartSecondsSafe: images preserved
VPS/PM2git revert + pm2 restartMinutesCheck DB migrations first
Kuberneteskubectl rollout undoSecondsCheck DB migrations first

Database migration caution:

  • If the deploy includes DB migrations, rollback is complex
  • Always write reversible migrations (up + down)
  • Test down migration before deploying up
  • 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...

ContextStatus
User says "Docker", "Dockerfile", "docker-compose"ACTIVE
User wants to containerize their applicationACTIVE
User mentions multi-stage builds, Docker optimization, or .dockerignoreACTIVE
User wants CI/CD with Docker (pipeline focus)DORMANT: see ci-cd-pipeline
User wants server provisioning with Docker installedDORMANT: see hetzner-setup
User wants Kubernetes orchestrationDORMANT: 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):

  1. docker run -e VAR=value (command line)
  2. environment: in docker-compose.yml
  3. env_file: in docker-compose.yml
  4. ENV in Dockerfile (build-time defaults only)

Secrets handling:

  • Never put secrets in Dockerfile ENV (visible in image layers)
  • Use env_file for production (file on server, not in repo)
  • For CI/CD: inject via docker run -e from 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:

TechniqueImpactApplied In
Multi-stage build50-80% smaller imageSeparate build/run stages
Alpine base~5MB vs ~100MB basenode:20-alpine vs node:20
Non-root userSecurity hardeningUSER appuser in final stage
Layer cachingFaster rebuildsCopy package.json before source
.dockerignoreSmaller build contextExclude node_modules, .git, docs
Minimal final stageOnly runtime filesNo dev deps, no source in prod
Combined RUNFewer layersChain apt commands with &&

Image size comparison:

ApproachTypical SizeNotes
node:20 (no optimization)~1 GBFull Debian + dev tools
node:20-slim~200 MBSlim Debian
node:20-alpine (multi-stage)~80-150 MBAlpine + app only
Go with scratch~5-20 MBBinary only, no OS
Python slim (multi-stage)~100-200 MBSlim + 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:5432 instead of 5432:5432 to 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.

ContextStatus
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 projectACTIVE
Checking domain expiration or renewal statusACTIVE
User is writing code, not managing infrastructureDORMANT
Discussing domain names abstractly (brainstorming names)DORMANT

Anti-patterns

TrapReality 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:

ProviderRecord TypeValue
RailwayCNAME*.up.railway.app
NetlifyCNAME*.netlify.app or A record to 75.2.60.5
VercelCNAMEcname.vercel-dns.com or A record to 76.76.21.21
Cloudflare (proxied)ACloudflare 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 ExpiryStatusAction
> 30 days✅ HealthyNo action
15 to 30 days⚠️ WarningVerify auto-renewal is working
< 15 days❌ CriticalManually trigger renewal immediately
Expired🚨 DownSite 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
DirectivePurpose
max-age=31536000Browser remembers to use HTTPS for 1 year
includeSubDomainsApplies to all subdomains too
preloadEligible 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 ResolverProvider
8.8.8.8Google
1.1.1.1Cloudflare
208.67.222.222OpenDNS
9.9.9.9Quad9

Also check: dnschecker.org for worldwide propagation view.

Propagation timeline:

Record TypeTypical PropagationMax Propagation
A / AAAA5 to 30 minutes48 hours
CNAME5 to 30 minutes48 hours
TXT5 to 60 minutes48 hours
NS24 to 48 hours72 hours
MX1 to 4 hours48 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 to https:// or protocol-relative //
  • ❌ Third-party scripts loaded over HTTP, update to HTTPS CDN URL
  • ❌ API endpoints using http://: update to https://
  • ❌ CSS url() references with http://: update to https://
  • ✅ http://localhost in 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
CheckFrequencyWhat to Verify
Domain expirationMonthlyAuto-renew enabled, registrar payment method valid
SSL certificateMonthlyValid, auto-renewing, > 30 days until expiry
DNS recordsAfter any changeRecords match expected values, propagation complete
HSTS headerQuarterlyPresent with adequate max-age
Mixed contentAfter deploysNo HTTP resources on HTTPS pages
Registrar accessQuarterlyLogin works, 2FA enabled, recovery email current
Nameserver delegationAfter registrar changesNS 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:

PatternDNS RecordPoints To
app.example.comCNAMEFrontend hosting (Netlify/Vercel)
api.example.comCNAMEBackend hosting (Railway)
docs.example.comCNAMEDocs hosting (GitBook/Notion)
mail.example.comMX + CNAMEEmail provider
*.example.comCNAMECatch-all (if needed)

Multi-domain for same project: When multiple domains point to the same app (e.g., deedstack.com and www.deedstack.com):

  1. Set one as canonical (return 200)
  2. All others 301 redirect to canonical
  3. Each domain needs its own SSL certificate (or use a multi-SAN cert)
  4. Update Content-Security-Policy and 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...

ContextStatus
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 securityACTIVE
User wants Docker containerization guidanceDORMANT: 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:

InstancevCPURAMSSDTrafficPriceBest For
CX2224 GB40 GB20 TB~$4.5/moSmall API, static site, hobby project
CX3248 GB80 GB20 TB~$8/moMedium web app, small DB
CPX3148 GB160 GB20 TB~$13/moHigh-perf apps (AMD EPYC), scrapers
CPX41816 GB240 GB20 TB~$24/moLarge apps, multiple services
CPX511632 GB360 GB20 TB~$47/moHeavy workloads, large databases
CCX1328 GB80 GB20 TB~$13/moDedicated 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.

ContextStatus
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 hostingACTIVE
Deploying a backend service or API serverDORMANT: use railway-deploy
Discussing Netlify pricing or features generallyDORMANT

Anti-patterns

TrapReality 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
FrameworkBuild CommandPublish Directory
React (CRA)npm run buildbuild
React (Vite)npm run builddist
Next.js (static)next build && next exportout
Vuenpm run builddist
Svelte/SvelteKitnpm run buildbuild
Astronpm run builddist
Plain HTMLnone. 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 = true if 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:

PrefixFrameworkWhen AvailableExposed to Client?
REACT_APP_CRABuild time⚠️ YES: baked into JS bundle
NEXT_PUBLIC_Next.jsBuild time⚠️ YES: baked into JS bundle
VITE_ViteBuild time⚠️ YES: baked into JS bundle
No prefixAnyBuild 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 like NODE_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.app or 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
CheckCommandPass Criteria
Build passesnpm run buildExit code 0, no errors
Output directory existsls dist/Has index.html and assets
No localhost in buildgrep dist/ for localhostZero matches
_redirects in outputls dist/_redirectsExists if using _redirects approach
Env vars documentedCheck .env.exampleAll client vars listed
No secrets in client codegrep for exposed secretsZero matches
Git cleangit statusAll 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:

  1. Preview deploy: Netlify generates a unique URL for every deploy: test there first
  2. Check build log: Netlify dashboard → Deploys → click deploy → Build Log
  3. Test SPA routing: Navigate directly to a deep route (e.g., /dashboard/settings): should load, not 404
  4. Test API proxy: Open DevTools Network tab, trigger an API call, verify it reaches backend
  5. Check SSL: Visit https://[domain], padlock should appear, no mixed content warnings
  6. Test redirects: Visit http://[domain]: should redirect to https://

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.

ContextStatus
User says "deploy to railway" or "railway deploy"ACTIVE
User says "ship it" or "deploy backend" with a Railway projectACTIVE
Preparing a backend/fullstack app for productionACTIVE
Deploying to Netlify, Vercel, or other non-Railway platformDORMANT
Discussing Railway pricing or features generallyDORMANT

Anti-patterns

TrapReality 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
IndicatorProject Type
package.json with nextNext.js
package.json with express/fastify/honoNode.js API
pyproject.toml or requirements.txtPython (Django/Flask/FastAPI)
Cargo.tomlRust
go.modGo

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
FilePurposeRequired?
DockerfileExplicit container buildRecommended for complex projects
ProcfileProcess start commandOptional if start script exists
nixpacks.tomlNixpacks build configOptional: auto-detected
railway.tomlRailway-specific settingsOptional: build/deploy overrides

If none exist, check that nixpacks can auto-detect:

  • Node.js: package.json must have start script or main field
  • Python: Must have requirements.txt or pyproject.toml with 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:

CategoryVariables to Verify
DatabaseDATABASE_URL, POSTGRES_URL, REDIS_URL, MONGODB_URI
AuthJWT_SECRET, SESSION_SECRET, NEXTAUTH_SECRET, NEXTAUTH_URL
External APIsSTRIPE_SECRET_KEY, SENDGRID_API_KEY, AWS_ACCESS_KEY_ID
App ConfigNODE_ENV=production, PORT (Railway sets this automatically)
URLsFRONTEND_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 dev or nodemon)
  • Port reads from process.env.PORT or os.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
CheckCommandPass Criteria
Build passesnpm run buildExit code 0, no errors
No hardcoded URLsgrep for localhostZero matches in source
Production env varsReview .env.exampleAll vars documented
Port configurationgrep for PORTReads from env, not hardcoded
Node versionCheck engines in package.jsonSpecified if needed
Git cleangit statusAll 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:

  1. Health check: curl https://[app].up.railway.app/health
  2. Logs: Check Railway dashboard → Deployments → View Logs for startup errors
  3. Database: Verify migrations ran (check logs for migration output)
  4. Environment: Confirm NODE_ENV=production is active

Rollback plan:

  • Railway keeps previous deployments. Go to Deployments → click previous successful deploy → Rollback
  • Or via CLI: railway rollback

If deploy fails:

  1. Check build logs first, dependency or build script errors
  2. Check runtime logs, missing env vars show as undefined/null errors
  3. Check health check timeout, app may be starting slowly (increase timeout in Settings)
  4. 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.

ContextStatus
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 routesACTIVE
Designing webhook endpointsACTIVE
Discussing API concepts or REST theoryDORMANT
Working on frontend components (not API layer)DORMANT

Anti-patterns

TrapReality 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:

ConventionRuleExample
Resource namesPlural nouns/organizations, /projects
Dynamic segments[paramName] camelCase[orgId], [memberId]
Nested resourcesParent/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 TypeAuth RequiredOrg CheckExample
Public❌❌GET /api/health
Authenticated✅❌GET /api/user/profile
Org-scoped✅✅GET /api/organizations/[orgId]/projects
Admin-only✅✅ + role checkDELETE /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:

CodeMeaningWhen to Use
200OKSuccessful GET, PATCH, or general success
201CreatedSuccessful POST that creates a resource
204No ContentSuccessful DELETE (no response body)
400Bad RequestMalformed request (invalid JSON, wrong Content-Type)
401UnauthorizedNot authenticated (no token, expired session)
403ForbiddenAuthenticated but not authorized (wrong org, wrong role)
404Not FoundResource doesn't exist (or user can't see it, use 404 to avoid leaking existence)
409ConflictDuplicate resource (unique constraint violation)
422Unprocessable EntityValid JSON but failed validation (Zod errors)
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server error (log details, return safe message)

Key distinction, 401 vs 403 vs 404:

  • 401: "I don't know who you are" → redirect to login
  • 403: "I know who you are, but you can't do this" → show permission error
  • 404: "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 TypeLimitWindow
Auth (login, register)5 requests15 minutes
Public API60 requests1 minute
Authenticated API120 requests1 minute
Webhooks1000 requests1 minute
File upload10 requests1 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 200 quickly: do heavy processing async
  • Use req.text() not req.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 string for 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

TriggerStatus
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 onlyNOT this skill: use git commands directly
User wants a diary entryNOT 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:

ParameterDefaultExample
Since tag/dateLast tag or last 7 daysv3.3.0, 2026-03-01
UntilHEADv3.4.0, HEAD
FormatKeep a ChangelogConventional, 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:

PrefixCategoryChangelog 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 prefixUncategorized### 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:

  1. Rewrite technical commit messages into user-facing language
  2. Group related commits into single entries where sensible
  3. Lead with the impact, not the implementation ("Users can now..." not "Added handler for...")
  4. Include short commit hash as reference
  5. Skip merge commits, version bumps, and trivial chores unless requested
  6. 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.

ContextStatus
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 codeACTIVE
Reviewing a specific file or set of changesACTIVE
User is writing code and hasn't asked for reviewDORMANT
Discussing code architecture at a high levelDORMANT

Anti-patterns

TrapReality 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

LevelLabelMeaningAction
🔴CriticalSecurity vulnerability, data loss risk, crash in productionFix before merge
🟠HighBug, incorrect behavior, significant performance issueFix this sprint
🟡MediumCode smell, minor performance issue, missing edge caseFix when touching the file
🔵LowStyle preference, minor improvement, documentation gapConsider 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
  • .env files 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)
  • await inside .map() without Promise.all() (sequential when it could be parallel)
  • Sequential await calls that could be Promise.all([...]) (parallelizable)

Missing indexes:

  • Foreign key columns without an index (causes slow JOINs)
  • Columns used in WHERE or ORDER BY without 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, or useCallback on expensive renders
  • Images without width/height or next/image optimization
  • 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/should prefix (active vs isActive)
  • Functions that don't describe their action (process(), handle(), doStuff())
  • Inconsistent naming between related files (camelCase in one, snake_case in another)

Type safety:

  • any type used where a specific type is known
  • Type assertions (as Type) hiding real type errors
  • Missing return types on exported functions
  • @ts-ignore or @ts-expect-error without 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:

  • await calls without try/catch in route handlers (returns 500 with no context)
  • .then() chains without .catch() (unhandled rejection)
  • Event handlers with async but no error boundary
  • Fire-and-forget promises (no await, no .catch(), no void)

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> without alt attribute (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-label on icon-only buttons
  • Using generic elements for navigation instead of <nav>
  • Form inputs without associated <label> elements
  • Missing role attributes 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:

  1. [Most critical issue with file:line]
  2. [Second most critical]
  3. [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

TriggerStatus
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 factNOT this skill: use Code Reviewer
User wants debugging helpNOT 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:

SignalLevelNarration Style
User asks "what is a..." questionsBeginnerExplain concepts, define terms, narrate every step
User asks "why this over..." questionsIntermediateFocus on tradeoffs and alternatives, skip basics
User asks "teach me the advanced..."AdvancedFocus 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 saysAdjust
"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

ContextStatus
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 safelyACTIVE
User wants to design a new database from scratchDORMANT: use Database Architect
User wants to refactor application codeDORMANT: use Refactor Planner

Common Mistakes

MistakeWhy 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:

  1. Database: what engine? (PostgreSQL, MySQL, SQLite, MongoDB)
  2. Current schema: what does the table/schema look like now?
  3. Target schema: what should it look like after migration?
  4. Data volume: how many rows in affected tables?
  5. Downtime tolerance: zero-downtime required, or maintenance window OK?
  6. Migration tool: what do you use? (Prisma, Knex, Flyway, Alembic, raw SQL, other)

Step 2: Classify the Migration

Migration type classification:

Change TypeRiskLock Behavior (PostgreSQL)Strategy
Add column (nullable)LowBrief ACCESS EXCLUSIVE lockDirect ALTER
Add column (with default)Low (PG 11+)Brief lock (PG 11+ doesn't rewrite)Direct ALTER
Add column (NOT NULL, no default)HighFails on existing rowsAdd nullable → backfill → add constraint
Drop columnMediumBrief lock, but app must not reference itRemove app refs first → then DROP
Rename columnHighBreaks all queries instantly3-phase: add new → migrate → drop old
Change column typeHighFull table rewrite + lockNew column → backfill → swap → drop
Add indexMediumBlocks writes (without CONCURRENTLY)CREATE INDEX CONCURRENTLY
Add foreign keyMediumValidates all rows (lock)NOT VALID → VALIDATE CONSTRAINT separately
Drop tableHighIrreversible data lossBackup → verify no refs → drop
Add tableLowNo lock on existing tablesDirect 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 SizeBatch SizeEstimated TimePause Between
<10K rowsAll at once<1 secondNone
10K-100K10,00010-60 seconds100ms
100K-1M10,0001-10 minutes100ms
1M-10M50,00010-60 minutes200ms
10M-100M50,0001-8 hours500ms
>100M100,000Schedule off-peak1s

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 TypeRollback SQL
Add columnALTER TABLE t DROP COLUMN c;
Drop columnRestore from backup (cannot undo)
Add indexDROP INDEX idx_name;
Add constraintALTER TABLE t DROP CONSTRAINT c_name;
Rename columnALTER TABLE t RENAME COLUMN new TO old;
Change typeReverse 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:

ToolConventionExample
PrismaAuto-generated timestamp20260303120000_add_phone_to_users/
KnexYYYYMMDDHHMMSS_description.js20260303120000_add_phone_to_users.js
FlywayV[version]__Description.sqlV2.1__Add_phone_to_users.sql
AlembicAuto-generated revision IDa1b2c3d4_add_phone_to_users.py
Raw SQL[sequence]_[description].sql003_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...

ContextStatus
User says "performance audit", "optimize", "slow app"ACTIVE
User mentions bundle size, N+1 queries, or Core Web VitalsACTIVE
User wants to find memory leaks or unnecessary re-rendersACTIVE
User wants database schema optimization specificallyDORMANT: see database-architect
User wants API design review (not performance)DORMANT: see api-designer
User wants general code quality reviewDORMANT: 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:

IssueDetectionImpactFix
Large dependenciesBundle > 200KB gzippedSlow initial loadReplace with lighter alternatives
Duplicate packagesSame lib in multiple versionsWasted bytesDedupe or pin single version
Unused exportsTree-shaking not workingWasted bytesUse ESM imports, avoid barrel files
No code splittingSingle large bundleSlow initial loadDynamic imports, route-based splitting
Unoptimized imagesImages > 100KB without optimizationSlow loadnext/image, sharp, WebP/AVIF
Missing compressionNo gzip/brotli on responses60-80% larger payloadsEnable in server/CDN config

Common heavy dependencies and alternatives:

PackageSize (minified)Lighter AlternativeSize
moment72 KBdate-fns (tree-shakeable)~2-5 KB used
lodash (full)72 KBlodash-es (tree-shakeable)~1-3 KB used
axios14 KBfetch (native)0 KB
classnames1 KBTemplate literals0 KB
uuid3 KBcrypto.randomUUID()0 KB
chart.js65 KBSpecific chart lib for your use caseVaries

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:

PatternDetectionImpactFix
Passing new objects/arrays as propsonClick={() => {}} in JSXChild re-renders every parent renderExtract handler, use useCallback
Missing memoization on expensive computationComputed value in render bodyRecalculated every renderuseMemo for expensive calculations
Context causing tree-wide re-rendersContext value changes frequentlyAll consumers re-renderSplit context, use selectors
Missing key on list itemsReact DevTools warningsIncorrect DOM reconciliationAdd stable unique key
Props drilling deep component treesProps passed through 5+ levelsTight coupling, re-render chainsContext 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:

IssueDetectionImpactFix
N+1 queriesLoop with DB call insideO(N) queries → O(1)JOIN or eager loading
Missing indexesFull table scans on filtered columnsSlow queries as data growsAdd targeted indexes
SELECT *Fetching all columnsExcess data transferSelect only needed columns
No paginationReturning all recordsMemory + transfer overheadLIMIT/OFFSET or cursor pagination
Missing connection poolingNew connection per queryConnection overheadUse pgBouncer or built-in pool
Unoptimized JOINsJoining on non-indexed columnsSlow JOINsIndex 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 TypeDetectionSymptomsFix
Event listenersListeners added without removalMemory grows over timeremoveEventListener in cleanup
Unclosed DB connectionsConnection pool exhaustion"too many connections" errorsClose connections in finally/cleanup
Growing arrays/mapsIn-memory cache without evictionRSS grows indefinitelyAdd TTL, LRU cache, or size limit
Unreferenced timerssetInterval without clearIntervalTimer continues after context diesClear timers on shutdown/cleanup
Unresolved promisesPromises that never settleMemory for callbacks retainedAdd timeouts to all async operations
Circular referencesObjects referencing each otherGC 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:

OptimizationTypical Impact
Fix N+1 queries50-90% reduction in query time
Add missing indexes10-100x faster queries
Enable compression60-80% smaller responses
Code splitting30-60% faster initial load
Image optimization50-90% smaller images
Remove unused deps10-40% smaller bundle
Add caching80-99% fewer API calls
Virtualize lists90% 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

ContextStatus
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 behaviorACTIVE
User wants to write a new featureDORMANT: use Feature Spec
User wants to change database schemaDORMANT: use Migration Planner

Common Mistakes

MistakeWhy 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:

  1. Target: what code needs refactoring? (file, module, class, or system)
  2. Pain point: what's the specific problem? (hard to modify, duplicated, slow, confusing)
  3. Test coverage: does the target code have tests? (yes, partial, none)
  4. Constraints: any deadlines, frozen APIs, or deployment concerns?
  5. Language/framework: what tech stack?

Step 2: Identify Code Smells

Scan the target code for these smell categories:

Bloaters (too big):

SmellDetectionSeverity
Long methodFunction >30 lines or >3 levels of nestingMedium
Large class / God objectClass >300 lines or >10 public methodsHigh
Long parameter listFunction takes >4 parametersMedium
Primitive obsessionRaw strings/numbers instead of domain typesLow
Data clumpsSame group of variables passed together repeatedlyMedium

Couplers (too connected):

SmellDetectionSeverity
Feature envyMethod uses another class's data more than its ownMedium
Inappropriate intimacyClasses access each other's private internalsHigh
Message chainsa.getB().getC().getD().doThing(): chain >2 deepMedium
Middle manClass delegates nearly everything to another classLow

Dispensables (unnecessary):

SmellDetectionSeverity
Dead codeUnreachable code, unused variables, commented-out blocksLow
Duplicate codeSame logic in 2+ places (exact or structural)High
Speculative generalityAbstractions, interfaces, or config for cases that don't existMedium
Lazy classClass does too little to justify its existenceLow

Change preventers (hard to modify):

SmellDetectionSeverity
Divergent changeOne class changed for many different reasonsHigh
Shotgun surgeryOne change requires edits across many filesHigh
Parallel inheritanceCreating a subclass in one hierarchy requires one in anotherMedium

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:

FactorLow RiskMedium RiskHigh Risk
Dependents0-2 callers3-10 callers10+ callers
Test coverage>80% covered40-80% covered<40% covered
ComplexitySimple extractionCross-file changesArchitectural change
ReversibilityEasy to revertRequires migrationData format changes
Blast radiusSingle fileSingle moduleCross-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:

  1. Start with LOW risk, HIGH value targets (quick wins)
  2. Then MEDIUM risk targets (with tests added first)
  3. HIGH risk targets last (with comprehensive test coverage first)
  4. Never refactor HIGH risk targets without >80% test coverage

Step 4: Select Refactoring Patterns

Match each smell to the appropriate pattern:

Extraction patterns:

PatternUse WhenBefore → After
Extract MethodLong method, duplicated logic blockInline code → Named function
Extract ClassGod class, divergent changeOne class → Two focused classes
Extract InterfaceTight coupling, testing difficultyConcrete dependency → Interface + implementation
Extract VariableComplex expression, magic numbersif (a > 86400 && b < 3) → if (isExpired && belowRetryLimit)

Simplification patterns:

PatternUse WhenBefore → After
Replace Conditional with PolymorphismLong switch/if chains on typeSwitch statement → Strategy pattern
Replace Parameter with MethodParameter that callee can computecalc(getX(), getY()) → calc() (fetches internally)
Introduce Parameter ObjectLong parameter list, data clumpsfn(x, y, z, w) → fn(config)
Replace Temp with QueryTemp variable used once after calculationtemp = calc(); use(temp) → use(calc())

Structural patterns:

PatternUse WhenBefore → After
Move Method/FieldFeature envy, misplaced responsibilityMethod in wrong class → Move to correct class
Inline ClassLazy class, middle manUseless wrapper → Merge into user
Replace Inheritance with CompositionFragile base class, deep hierarchyextends Base → has Base with delegation
Introduce FacadeComplex subsystem, shotgun surgeryDirect 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:

PatternTypical EffortRisk Level
Extract Variable5-15 minVery Low
Extract Method15-30 minLow
Introduce Parameter Object30-60 minLow
Extract Class1-3 hoursMedium
Replace Conditional with Polymorphism2-4 hoursMedium
Replace Inheritance with Composition3-6 hoursHigh
Extract Interface + Dependency Injection2-5 hoursMedium-High
Architectural restructure (module boundaries)1-3 daysHigh

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

ContextStatus
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 codeDORMANT: use Refactor Planner
User wants to change database schemaDORMANT: use Migration Planner

Common Mistakes

MistakeWhy 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:

  1. Target: what code needs tests? (function, class, module, API endpoint)
  2. Language/framework: what tech stack? (JS/TS + Jest/Vitest, Python + pytest, Go, etc.)
  3. Test level: unit, integration, e2e, or all three?
  4. Current coverage: any existing tests? What percentage?
  5. Priority: critical paths first, or comprehensive coverage?

Step 2: Analyze the Code Under Test

Before writing tests, understand the target:

Function/method analysis:

PropertyValue
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:

#ScenarioInputExpected Output
1[Normal case with typical input][Input][Output]
2[Normal case with different valid input][Input][Output]

Edge case tests:

#CategoryScenarioInputExpected Output
1BoundariesMinimum valid value[Input][Output]
2BoundariesMaximum valid value[Input][Output]
3BoundariesExactly at limit[Input][Output]
4EmptyEmpty string / array / object"" / [] / {}[Output]
5Null/UndefinedNull inputnull[Output or error]
6Type coercionUnexpected type"123" vs 123[Output]
7Large inputVery large dataset[X items][Output / perf]
8UnicodeSpecial characters"café ñ 中文"[Output]
9ConcurrentRace condition scenario[Parallel calls][Consistent state]

Error path tests:

#Error ConditionInputExpected Behavior
1Invalid input[Bad input]Throws [ErrorType] with message
2Dependency failure[DB timeout]Returns fallback or propagates error
3Permission denied[Unauthorized]Returns 403 / throws AuthError
4Not found[Missing resource]Returns null or throws NotFoundError

Step 4: Write the Tests

Test file naming conventions:

FrameworkConventionExample
Jest / Vitest[name].test.ts or [name].spec.tsuserService.test.ts
pytesttest_[name].pytest_user_service.py
Go[name]_test.gouser_service_test.go
JUnit[Name]Test.javaUserServiceTest.java

Test naming conventions:

StylePatternExample
Behavior-drivenshould [expected] when [condition]should return empty array when no items match filter
Given-When-Thengiven [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:

DependencyMock ApproachExample
DatabaseMock repository/ORM layerjest.spyOn(db, 'query').mockResolvedValue(rows)
HTTP APIMock HTTP client or use MSW/nocknock('https://api.example.com').get('/users').reply(200, data)
File systemMock fs module or use memfsjest.mock('fs/promises')
Time/DateFake timersjest.useFakeTimers(); jest.setSystemTime(new Date('2026-01-15'))
RandomSeed or mockjest.spyOn(Math, 'random').mockReturnValue(0.5)
EnvironmentSet/restore env varsprocess.env.NODE_ENV = 'test' in beforeEach
Third-party SDKMock the clientjest.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:

LevelTargetRationale
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

TriggerStatus
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 testsNOT this skill: use standard test patterns
User wants load testingNOT 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:

ParameterHow to findExample
App URLCheck package.json scripts, .env, or askhttp://localhost:3000
FrameworkCheck package.json dependenciesNext.js, React, SvelteKit
Auth required?Check for login pages, auth middlewareYes/No
Key user flowsAsk or infer from routesSign 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:

  1. Use getByRole, getByLabel, getByText over CSS selectors: they survive refactors
  2. One assertion per test where practical: clear failure messages
  3. Name tests as user stories: "should show error when email is invalid"
  4. Use test.describe to group related flows
  5. Add test.beforeEach for shared navigation/auth setup
  6. Never hardcode waits, use expect with auto-waiting or waitForSelector

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)
diaryechofamiliarforgegoalgovernorgrimoirehumanizecompetitor-analysisfacebook-adgoogle-adlaunch-planlead-magnetmarketplace-submitpricing-strategysales-funnelwebinar-scriptfeature-specfeedback-analyzermvp-scoperprd-writerroadmap-builderuser-story-generatorprojectquillreportscanapi-auditcsp-headersdependency-auditgit-guardowasp-top10rls-checkerrls-guardiansecrets-scannerai-search-visibilitykeyword-researchlocal-seometa-tag-optimizerschema-markupsite-auditshardsightstatetoken-optimizationverifywork

Sponsors

Details

Marketplace
cwinvestments/memstack
Source
cwinvestments/memstack
Category
Productivity
Keywords
skills, memory, context, session, productivity, devops, security, database, deployment