---
name: deliver-deploy
description: "Use when the user says 'deploy', 'ship it', 'push to staging', 'release', 'roll out', 'promote to prod', or asks how to deploy after tests pass and review is complete. Drives the deploy checklist (build, env vars, migrations applied, smoke check, rollback plan). Skip if tests are failing or review is open — route back to those gates first."
---

# Deliver: Deploy

## Overview

This skill enforces a strict pre-deploy to post-deploy pipeline that treats every deployment as a production event -- even to staging.

**Core Principle:** Shipping is a process, not an action. Every deploy follows the same pipeline regardless of how "small" the change is.

## The Iron Laws of Deployment

```
NEVER deploy with failing tests.
NEVER deploy without code review.
NEVER deploy without a rollback plan.
NEVER deploy without smoke tests defined.
NEVER skip staging when staging exists.
```

If any of these conditions are not met, STOP. Do not proceed. Do not rationalize.

## When to Use

- All tests pass (unit, integration, E2E, smoke)
- Code review is complete and approved
- Feature manifest shows all quality gates passed
- User explicitly requests deployment
- `/feature` or `/hotfix` command reaches the deploy phase

**Do NOT use when:**
- Tests are still failing ("we'll fix in production")
- Code review has open items ("reviewer will approve after deploy")
- You're "just deploying to staging to test" (use test execution skill instead)
- No rollback plan exists ("we can always revert the commit")

## I/O Contract

| Field | Value |
|---|---|
| **Requires** | Passing test results (`test-results.md`) + approved code review + feature manifest with all gates passed |
| **Produces** | Deployed application + deployment record |
| **Updates** | `.forge/work/{type}/{name}/manifest.yaml`: `artifacts.deliver.locked_at`, deployment record at `artifacts.deliver.deployment`, environment. |
| **Feeds into** | `deliver-onboarding` (update docs if needed), `support-gotcha` (record any deployment lessons) |

### Input Verification

Before starting, read and verify these artifacts exist:

```
.forge/work/{type}/{name}/
  manifest.yaml          -> readiness: artifacts.production-build.locked_at present AND phases.quality.code-review-final.gate-passed: true AND phases.quality.test-execution.gate-passed: true
  test-results.md        -> must exist, all tests passing
  architecture/           -> must exist (needed for rollback context)
```

### Output Artifacts

```
.forge/work/{type}/{name}/
  manifest.yaml          -> updated: artifacts.deliver.locked_at, artifacts.deliver.deployment (timestamp + environment)
  deploy-log.md          -> record of what was deployed, when, where, by whom
```

## The Deployment Pipeline

### Phase 1: Pre-Deploy Verification

**Purpose:** Confirm everything is genuinely ready. Trust nothing -- verify everything.

**Steps:**

1. **Read the Feature Manifest**
   ```yaml
   # Verify readiness in manifest.yaml
   artifacts:
     production-build:
       locked_at: "..."         # MUST be present
   phases:
     quality:
       code-review-final:
         gate-passed: true      # Review completed
       test-execution:
         gate-passed: true      # All test types passing
   # Security audit is required when changes touch auth, payments, encryption,
   # PII, user-input handling (injection/XSS), or external integrations.
   ```

2. **Verify Test Results Are Current**
   - Read `test-results.md` -- when were tests last run?
   - If code changed since last test run, tests MUST be re-executed
   - Check: unit tests, integration tests, E2E tests, smoke test definitions
   - Any skipped tests must have documented justification

3. **Verify Code Review Approval**
   - Check PR status: approved, no outstanding change requests
   - If PR has comments marked "must fix" -- STOP, those must be addressed
   - Verify reviewer is not the same person as the author (when team size allows)

4. **Check for Rollback Plan**
   - Database rollback scripts exist (if migration involved -- see `deliver-db-migration`)
   - Previous known-good version identified
   - Rollback procedure documented (even if it is "revert this commit")
   - Verify rollback can be executed without data loss

5. **Environment Readiness**
   - Target environment is accessible
   - Required environment variables are set
   - Required services are running (database, cache, message queue)
   - Sufficient resources (disk space, memory) for deployment

**Gate:** ALL checks must pass. If ANY check fails, output the specific failure and STOP.

```
PRE-DEPLOY CHECKLIST
--------------------
[PASS] Manifest readiness: production-build locked, code-review-final + test-execution gates passed
[PASS] Test results current (ran 12 min ago)
[PASS] All test types passing (unit: 142/142, integration: 38/38, e2e: 12/12)
[PASS] Code review approved (reviewer: @teammate, 2 hours ago)
[PASS] Rollback plan documented
[PASS] Environment accessible
[PASS] Required services running

VERDICT: Ready to deploy
```

### Phase 2: Staging Validation (When Staging Exists)

**Purpose:** Catch environment-specific issues before production.

**If project has a staging environment:**

1. **Deploy to Staging First**
   - Use the same deployment mechanism as production
   - Same config structure (different values, same shape)
   - Same deployment scripts

2. **Run Smoke Tests Against Staging**
   - Execute the smoke test suite from `test-plan.md`
   - Verify critical user paths work end-to-end
   - Check integrations with external services (if staging versions exist)

3. **Manual Verification Window**
   - Ask user: "Staging deploy complete. Smoke tests passing. Want to verify manually before production?"
   - If user says yes -- WAIT for their go-ahead
   - If user says no -- proceed to production
   - If user does not respond -- WAIT (never auto-proceed to production)

4. **Staging-Specific Checks**
   - Response times within acceptable range
   - No new error logs appearing
   - Database migrations applied cleanly
   - Feature flags in correct state

**If NO staging environment exists:**
- Document this in the deploy log: "No staging environment -- deploying directly to production"
- Extra caution: ensure smoke tests are comprehensive
- Recommend to user: consider adding staging (but do not block deployment)

### Phase 3: Production Deploy

**Purpose:** Execute the actual deployment with maximum safety.

**Steps:**

1. **Announce Deployment**
   - Log: "Starting production deployment of {feature-name} at {timestamp}"
   - If team communication channel exists, notify

2. **Execute Deployment**
   - Use project's deployment mechanism (detected from project structure):
     - `Dockerfile` / `docker-compose.yml` -- container deployment
     - `fly.toml` -- Fly.io deployment
     - `vercel.json` / `next.config.js` -- Vercel deployment
     - `serverless.yml` -- Serverless Framework
     - `terraform/` -- Infrastructure as Code
     - `Procfile` -- Heroku
     - `package.json` scripts -- custom deployment
     - Manual steps documented in project README
   - If deployment mechanism is unclear, ASK the user

3. **Database Migrations (if applicable)**
   - Run forward migration BEFORE deploying new application code
   - Verify migration succeeded before proceeding
   - If migration fails -- STOP, do not deploy application code
   - See `deliver-db-migration` for migration-specific process

4. **Monitor Deployment Progress**
   - Watch for deployment errors in output
   - If deployment tool provides health checks, monitor them
   - Set a reasonable timeout (project-specific, default 5 minutes)

5. **Handle Deployment Failures**
   - If deployment fails: capture error output completely
   - Do NOT retry automatically without understanding the failure
   - Present failure to user with context
   - If rollback is needed, ask user for confirmation before rolling back

### Phase 4: Post-Deploy Verification

**Purpose:** Confirm the deployment is healthy in production.

**Steps:**

1. **Run Smoke Tests Against Production**
   - Execute the smoke test suite against the production URL
   - These should be non-destructive (read-only where possible)
   - Verify critical paths:
     - Application responds (health check endpoint)
     - Authentication works (if applicable)
     - Core business operations function
     - Database connectivity confirmed

2. **Monitor for Errors**
   - Check application logs for new errors (first 5 minutes minimum)
   - Check error tracking service if configured (Sentry, Bugsnag, etc.)
   - Check monitoring dashboards if available
   - Compare error rates to pre-deployment baseline

3. **Performance Baseline**
   - Is response time comparable to pre-deployment?
   - Any new slow queries appearing?
   - Memory usage within expected range?
   - CPU usage within expected range?

4. **Declare Deployment Status**

   **Success:**
   ```
   POST-DEPLOY VERIFICATION
   ------------------------
   [PASS] Smoke tests passing (5/5 critical paths)
   [PASS] No new errors in logs (5 min observation)
   [PASS] Response time within baseline (avg 120ms, baseline 115ms)
   [PASS] All services healthy

   DEPLOYMENT SUCCESSFUL
   Feature: {feature-name}
   Environment: production
   Timestamp: {ISO 8601}
   Version: {git SHA or tag}
   ```

   **Failure:**
   ```
   POST-DEPLOY VERIFICATION
   ------------------------
   [PASS] Smoke tests passing (5/5 critical paths)
   [FAIL] New errors detected: TypeError in /api/payments (12 occurrences in 3 min)
   [PASS] Response time within baseline
   [WARN] Memory usage elevated (85% vs baseline 60%)

   DEPLOYMENT REQUIRES ATTENTION
   Recommended action: Investigate /api/payments errors before declaring success.
   Rollback available: [describe rollback procedure]
   ```

### Phase 5: Manifest Update and Wrap-Up

1. **Update Feature Manifest**
   ```yaml
   artifacts:
     deliver:
       locked_at: "2026-03-25T14:30:00Z"
       deployment:
         environment: production
         timestamp: "2026-03-25T14:30:00Z"
         version: "abc123"
         deployed_by: "claude-code"
         smoke_tests: pass
         rollback_plan: "git revert abc123; run db:rollback"
   ```

2. **Create Deploy Log Entry**
   ```markdown
   # Deploy: {feature-name}
   **Date**: {date}
   **Environment**: production
   **Version**: {git SHA}
   **Duration**: {time from start to verification}

   ## Changes Deployed
   - {list of changes from PR description}

   ## Verification Results
   - Smoke tests: PASS
   - Error monitoring: CLEAN
   - Performance: NOMINAL

   ## Rollback Plan
   {documented rollback procedure}
   ```

3. **Trigger Post-Deploy Skills**
   - If documentation needs updating, flag for `deliver-onboarding`
   - If any issues were encountered during deploy, invoke `support-gotcha`
   - If deployment revealed process improvements, note for `/forge-evolve`

4. **Retrospective dream (Phase 7 auto-fire on lock).** After writing `artifacts.deliver.locked_at`, invoke the **support-dream** skill to consolidate the full feature's wiki accumulation. This is the last consolidation pass for the feature — gotchas, conventions, and any deploy-time learnings get merged into the durable wiki state before the manifest closes.
   - **scope:** `aiwiki/raw/`, `aiwiki/gotchas/`, `aiwiki/conventions/`, `aiwiki/sessions/` (any subfolder touched during this feature's lifetime)
   - **trigger:** `phase-close`
   - **trigger_detail:** `"Phase 7 (deliver) retrospective — {feature/name}"`

   Surface the dream id + review path to the user. The feature manifest's `status: completed` transition should wait until the retrospective dream is reviewed — this is the consolidation pass the next feature's `discover-codebase-analysis` will read from.

   **Skip when:** no `aiwiki/` writes occurred during this feature (rare — most non-trivial features produce at least one gotcha or convention).

## Rollback Procedures

### When to Roll Back

- Smoke tests fail in production
- Error rate spikes above baseline
- Critical user path is broken
- Data corruption detected
- Security vulnerability exposed

### Rollback Decision Tree

```
Smoke tests fail?
  +-- Yes --> Roll back immediately (do not debug in production)
  +-- No  --> Continue monitoring
       |
       Error rate spike?
       +-- Yes, critical path --> Roll back, then debug
       +-- Yes, non-critical  --> Ask user: rollback or hotfix?
       +-- No                 --> Deployment healthy
```

### Rollback Execution

1. **Ask user for confirmation** (unless immediate data corruption risk)
2. Execute rollback procedure (documented in deploy log)
3. Verify rollback succeeded (run smoke tests against previous version)
4. Record in manifest: rollback timestamp, reason, outcome
5. Invoke `support-debug` to investigate the failure
6. Invoke `support-gotcha` to record what went wrong

## Environment Detection

This skill auto-detects the deployment mechanism from project structure:

| Indicator | Deployment Method |
|---|---|
| `Dockerfile` + `docker-compose.yml` | Docker Compose |
| `fly.toml` | Fly.io (`fly deploy`) |
| `vercel.json` or Next.js project | Vercel (`vercel --prod`) |
| `netlify.toml` | Netlify |
| `serverless.yml` | Serverless Framework |
| `terraform/` directory | Terraform (`terraform apply`) |
| `.github/workflows/deploy.yml` | GitHub Actions (trigger workflow) |
| `Procfile` | Heroku (`git push heroku main`) |
| `render.yaml` | Render |
| Custom scripts in `package.json` | Run the deploy script |

If multiple deployment mechanisms are detected, ASK the user which to use.
If no deployment mechanism is detected, ASK the user how they deploy.

## Red Flags -- STOP and Reconsider

If you catch yourself thinking:

| Thought | Reality |
|---|---|
| "Tests are mostly passing" | ALL tests must pass. No exceptions. |
| "Code review is basically done" | Approved means approved. Open comments mean not done. |
| "It's just a small change" | Small changes cause outages. Follow the full pipeline. |
| "We can fix it in production" | No. Roll back. Fix. Redeploy. |
| "Staging worked, production will be fine" | Staging reduces risk. It does not eliminate it. |
| "Skip smoke tests, we already tested" | Post-deploy smoke tests catch deployment-specific issues. |
| "Rollback is easy, we don't need a plan" | If you do not write it down, you will not remember under pressure. |
| "Let me just retry the deploy" | Understand why it failed before retrying. |

## Integration with Feature Manifest

This skill is the final phase of the feature lifecycle. The manifest tracks the entire journey:

```yaml
# Example manifest at deployment time
name: add-payment-processing
phase_plan:
  concept: active
  wireframe: active
  prototype: active
  codify: active
  production-build: active
  deliver: active
artifacts:
  concept: { deck_path: decks/{name}/slides.md, locked_at: "..." }
  wireframe: { html_path: pocs/{name}-wireframe/index.html, locked_at: "..." }
  prototype: { path: pocs/{name}-prototype/, locked_at: "..." }
  codify: { locked_at: "..." }
  production-build: { locked_at: "..." }
  deliver:                       # <-- Added by this skill
    locked_at: "2026-03-25T14:30:00Z"
    deployment:
      environment: production
      timestamp: "2026-03-25T14:30:00Z"
      version: "abc123"
      smoke_tests: pass
```

## Quick Reference

| Phase | Key Actions | Gate Criteria |
|---|---|---|
| **1. Pre-Deploy** | Read manifest, verify tests, check review, confirm rollback plan | ALL checks pass |
| **2. Staging** | Deploy to staging, run smoke tests, optional manual check | Smoke tests pass |
| **3. Production** | Execute deployment, run migrations, monitor | Deployment completes without error |
| **4. Post-Deploy** | Smoke tests, error monitoring, performance check | All verification passes |
| **5. Wrap-Up** | Update manifest, create deploy log, trigger follow-up skills | Manifest updated |
