~cytrogen/gstack

4f435e45c517822014a852804c3da57bab121516 — Garry Tan 13 days ago 7665adf
feat: /land-and-deploy first-run dry run + staging-first + trust ladder (v0.12.2.0) (#518)

* feat: /land-and-deploy first-run dry-run, staging-first, trust ladder

First run shows a dry run — detect deploy infrastructure, validate commands,
show what will happen — then confirm before proceeding. Staging-first option
when staging detected. Config decay: re-triggers dry run if deploy config
changes. Full wordsmithed copy for every user-facing message.

Key changes:
- Step 1.5: first-run dry-run with infrastructure validation table
- Step 3.5a-bis: inline review gate before deploy
- Step 4a/4b: merge queue + CI auto-deploy detection and messaging
- Step 5a: staging-first option with verify-then-promote flow
- Voice & Tone section: narrate-the-journey, teacher mode vs efficient mode
- Config fingerprinting: trust decays when deploy config changes

* chore: bump version and changelog (v0.12.2.0)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
M CHANGELOG.md => CHANGELOG.md +20 -0
@@ 1,5 1,25 @@
# Changelog

## [0.12.2.0] - 2026-03-26 — Deploy with Confidence: First-Run Dry Run

The first time you run `/land-and-deploy` on a project, it does a dry run. It detects your deploy infrastructure, tests that every command works, and shows you exactly what will happen... before it touches anything. You confirm, and from then on it just works.

If your deploy config changes later (new platform, different workflow, updated URLs), it automatically re-runs the dry run. Trust is earned, maintained, and re-validated when the ground shifts.

### Added

- **First-run dry run.** Shows your deploy infrastructure in a validation table: platform, CLI status, production URL reachability, staging detection, merge method, merge queue status. You confirm before anything irreversible happens.
- **Staging-first option.** If staging is detected (CLAUDE.md config, GitHub Actions workflow, or Vercel/Netlify preview), you can deploy there first, verify it works, then proceed to production.
- **Config decay detection.** The dry-run confirmation stores a fingerprint of your deploy config. If CLAUDE.md's deploy section or your deploy workflows change, the dry run re-triggers automatically.
- **Inline review gate.** If no recent code review exists, offers a quick safety check on the diff before merging. Catches SQL safety, race conditions, and security issues at deploy time.
- **Merge queue awareness.** Detects when your repo uses merge queues and explains what's happening while it waits.
- **CI auto-deploy detection.** Identifies deploy workflows triggered by the merge and monitors them.

### Changed

- **Full copy rewrite.** Every user-facing message rewritten to narrate what's happening, explain why, and be specific. First run = teacher mode. Subsequent runs = efficient mode.
- **Voice & Tone section.** New guidelines for how the skill communicates: be a senior release engineer sitting next to the developer, not a robot.

## [0.12.1.0] - 2026-03-26 — Smarter Browsing: Network Idle, State Persistence, Iframes

Every click, fill, and select now waits for the page to settle before returning. No more stale snapshots because an XHR was still in-flight. Chain accepts pipe-delimited format for faster multi-step flows. You can save and restore browser sessions (cookies + open tabs). And iframe content is now reachable.

M VERSION => VERSION +1 -1
@@ 1,1 1,1 @@
0.12.1.0
0.12.2.0

M land-and-deploy/SKILL.md => land-and-deploy/SKILL.md +435 -65
@@ 358,7 358,8 @@ the ones listed below. The user said `/land-and-deploy` which means DO IT — bu
readiness first.

**Always stop for:**
- **Pre-merge readiness gate (Step 3.5)** — this is the ONE confirmation before merge
- **First-run dry-run validation (Step 1.5)** — shows deploy infrastructure and confirms setup
- **Pre-merge readiness gate (Step 3.5)** — reviews, tests, docs check before merge
- GitHub CLI not authenticated
- No PR found for this branch
- CI failures or merge conflicts


@@ 370,15 371,29 @@ readiness first.
- Choosing merge method (auto-detect from repo settings)
- Timeout warnings (warn and continue gracefully)

## Voice & Tone

Every message to the user should make them feel like they have a senior release engineer
sitting next to them. The tone is:
- **Narrate what's happening now.** "Checking your CI status..." not just silence.
- **Explain why before asking.** "Deploys are irreversible, so I check X before proceeding."
- **Be specific, not generic.** "Your Fly.io app 'myapp' is healthy" not "deploy looks good."
- **Acknowledge the stakes.** This is production. The user is trusting you with their users' experience.
- **First run = teacher mode.** Walk them through everything. Explain what each check does and why.
- **Subsequent runs = efficient mode.** Brief status updates, no re-explanations.
- **Never be robotic.** "I ran 4 checks and found 1 issue" not "CHECKS: 4, ISSUES: 1."

---

## Step 1: Pre-flight

Tell the user: "Starting deploy sequence. First, let me make sure everything is connected and find your PR."

1. Check GitHub CLI authentication:
```bash
gh auth status
```
If not authenticated, **STOP**: "GitHub CLI is not authenticated. Run `gh auth login` first."
If not authenticated, **STOP**: "I need GitHub CLI access to merge your PR. Run `gh auth login` to connect, then try `/land-and-deploy` again."

2. Parse arguments. If the user specified `#NNN`, use that PR number. If a URL was provided, save it for canary verification in Step 7.



@@ 387,16 402,238 @@ If not authenticated, **STOP**: "GitHub CLI is not authenticated. Run `gh auth l
gh pr view --json number,state,title,url,mergeStateStatus,mergeable,baseRefName,headRefName
```

4. Validate the PR state:
   - If no PR exists: **STOP.** "No PR found for this branch. Run `/ship` first to create one."
   - If `state` is `MERGED`: "PR is already merged. Nothing to do."
   - If `state` is `CLOSED`: "PR is closed (not merged). Reopen it first."
4. Tell the user what you found: "Found PR #NNN — '{title}' (branch → base)."

5. Validate the PR state:
   - If no PR exists: **STOP.** "No PR found for this branch. Run `/ship` first to create a PR, then come back here to land and deploy it."
   - If `state` is `MERGED`: "This PR is already merged — nothing to deploy. If you need to verify the deploy, run `/canary <url>` instead."
   - If `state` is `CLOSED`: "This PR was closed without merging. Reopen it on GitHub first, then try again."
   - If `state` is `OPEN`: continue.

---

## Step 1.5: First-run dry-run validation

Check whether this project has been through a successful `/land-and-deploy` before,
and whether the deploy configuration has changed since then:

```bash
eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)"
if [ ! -f ~/.gstack/projects/$SLUG/land-deploy-confirmed ]; then
  echo "FIRST_RUN"
else
  # Check if deploy config has changed since confirmation
  SAVED_HASH=$(cat ~/.gstack/projects/$SLUG/land-deploy-confirmed 2>/dev/null)
  CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
  # Also hash workflow files that affect deploy behavior
  WORKFLOW_HASH=$(cat .github/workflows/*deploy* .github/workflows/*cd* 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
  COMBINED_HASH="${CURRENT_HASH}-${WORKFLOW_HASH}"
  if [ "$SAVED_HASH" != "$COMBINED_HASH" ] && [ -n "$SAVED_HASH" ]; then
    echo "CONFIG_CHANGED"
  else
    echo "CONFIRMED"
  fi
fi
```

**If CONFIRMED:** Print "I've deployed this project before and know how it works. Moving straight to readiness checks." Proceed to Step 2.

**If CONFIG_CHANGED:** The deploy configuration has changed since the last confirmed deploy.
Re-trigger the dry run. Tell the user:

"I've deployed this project before, but your deploy configuration has changed since the last
time. That could mean a new platform, a different workflow, or updated URLs. I'm going to
do a quick dry run to make sure I still understand how your project deploys."

Then proceed to the FIRST_RUN flow below (steps 1.5a through 1.5e).

**If FIRST_RUN:** This is the first time `/land-and-deploy` is running for this project. Before doing anything irreversible, show the user exactly what will happen. This is a dry run — explain, validate, and confirm.

Tell the user:

"This is the first time I'm deploying this project, so I'm going to do a dry run first.

Here's what that means: I'll detect your deploy infrastructure, test that my commands actually work, and show you exactly what will happen — step by step — before I touch anything. Deploys are irreversible once they hit production, so I want to earn your trust before I start merging.

Let me take a look at your setup."

### 1.5a: Deploy infrastructure detection

Run the deploy configuration bootstrap to detect the platform and settings:

```bash
# Check for persisted deploy config in CLAUDE.md
DEPLOY_CONFIG=$(grep -A 20 "## Deploy Configuration" CLAUDE.md 2>/dev/null || echo "NO_CONFIG")
echo "$DEPLOY_CONFIG"

# If config exists, parse it
if [ "$DEPLOY_CONFIG" != "NO_CONFIG" ]; then
  PROD_URL=$(echo "$DEPLOY_CONFIG" | grep -i "production.*url" | head -1 | sed 's/.*: *//')
  PLATFORM=$(echo "$DEPLOY_CONFIG" | grep -i "platform" | head -1 | sed 's/.*: *//')
  echo "PERSISTED_PLATFORM:$PLATFORM"
  echo "PERSISTED_URL:$PROD_URL"
fi

# Auto-detect platform from config files
[ -f fly.toml ] && echo "PLATFORM:fly"
[ -f render.yaml ] && echo "PLATFORM:render"
([ -f vercel.json ] || [ -d .vercel ]) && echo "PLATFORM:vercel"
[ -f netlify.toml ] && echo "PLATFORM:netlify"
[ -f Procfile ] && echo "PLATFORM:heroku"
([ -f railway.json ] || [ -f railway.toml ]) && echo "PLATFORM:railway"

# Detect deploy workflows
for f in .github/workflows/*.yml .github/workflows/*.yaml; do
  [ -f "$f" ] && grep -qiE "deploy|release|production|cd" "$f" 2>/dev/null && echo "DEPLOY_WORKFLOW:$f"
  [ -f "$f" ] && grep -qiE "staging" "$f" 2>/dev/null && echo "STAGING_WORKFLOW:$f"
done
```

If `PERSISTED_PLATFORM` and `PERSISTED_URL` were found in CLAUDE.md, use them directly
and skip manual detection. If no persisted config exists, use the auto-detected platform
to guide deploy verification. If nothing is detected, ask the user via AskUserQuestion
in the decision tree below.

If you want to persist deploy settings for future runs, suggest the user run `/setup-deploy`.

Parse the output and record: the detected platform, production URL, deploy workflow (if any),
and any persisted config from CLAUDE.md.

### 1.5b: Command validation

Test each detected command to verify the detection is accurate. Build a validation table:

```bash
# Test gh auth (already passed in Step 1, but confirm)
gh auth status 2>&1 | head -3

# Test platform CLI if detected
# Fly.io: fly status --app {app} 2>/dev/null
# Heroku: heroku releases --app {app} -n 1 2>/dev/null
# Vercel: vercel ls 2>/dev/null | head -3

# Test production URL reachability
# curl -sf {production-url} -o /dev/null -w "%{http_code}" 2>/dev/null
```

Run whichever commands are relevant based on the detected platform. Build the results into this table:

```
╔══════════════════════════════════════════════════════════╗
║         DEPLOY INFRASTRUCTURE VALIDATION                  ║
╠══════════════════════════════════════════════════════════╣
║                                                            ║
║  Platform:    {platform} (from {source})                   ║
║  App:         {app name or "N/A"}                          ║
║  Prod URL:    {url or "not configured"}                    ║
║                                                            ║
║  COMMAND VALIDATION                                        ║
║  ├─ gh auth status:     ✓ PASS                             ║
║  ├─ {platform CLI}:     ✓ PASS / ⚠ NOT INSTALLED / ✗ FAIL ║
║  ├─ curl prod URL:      ✓ PASS (200 OK) / ⚠ UNREACHABLE   ║
║  └─ deploy workflow:    {file or "none detected"}          ║
║                                                            ║
║  STAGING DETECTION                                         ║
║  ├─ Staging URL:        {url or "not configured"}          ║
║  ├─ Staging workflow:   {file or "not found"}              ║
║  └─ Preview deploys:    {detected or "not detected"}       ║
║                                                            ║
║  WHAT WILL HAPPEN                                          ║
║  1. Run pre-merge readiness checks (reviews, tests, docs)  ║
║  2. Wait for CI if pending                                 ║
║  3. Merge PR via {merge method}                            ║
║  4. {Wait for deploy workflow / Wait 60s / Skip}           ║
║  5. {Run canary verification / Skip (no URL)}              ║
║                                                            ║
║  MERGE METHOD: {squash/merge/rebase} (from repo settings)  ║
║  MERGE QUEUE:  {detected / not detected}                   ║
╚══════════════════════════════════════════════════════════╝
```

**Validation failures are WARNINGs, not BLOCKERs** (except `gh auth status` which already
failed at Step 1). If `curl` fails, note "I couldn't reach that URL — might be a network
issue, VPN requirement, or incorrect address. I'll still be able to deploy, but I won't
be able to verify the site is healthy afterward."
If platform CLI is not installed, note "The {platform} CLI isn't installed on this machine.
I can still deploy through GitHub, but I'll use HTTP health checks instead of the platform
CLI to verify the deploy worked."

### 1.5c: Staging detection

Check for staging environments in this order:

1. **CLAUDE.md persisted config:** Check for a staging URL in the Deploy Configuration section:
```bash
grep -i "staging" CLAUDE.md 2>/dev/null | head -3
```

2. **GitHub Actions staging workflow:** Check for workflow files with "staging" in the name or content:
```bash
for f in .github/workflows/*.yml .github/workflows/*.yaml; do
  [ -f "$f" ] && grep -qiE "staging" "$f" 2>/dev/null && echo "STAGING_WORKFLOW:$f"
done
```

3. **Vercel/Netlify preview deploys:** Check PR status checks for preview URLs:
```bash
gh pr checks --json name,targetUrl 2>/dev/null | head -20
```
Look for check names containing "vercel", "netlify", or "preview" and extract the target URL.

Record any staging targets found. These will be offered in Step 5.

### 1.5d: Readiness preview

Tell the user: "Before I merge any PR, I run a series of readiness checks — code reviews, tests, documentation, PR accuracy. Let me show you what that looks like for this project."

Preview the readiness checks that will run at Step 3.5 (without re-running tests):

```bash
~/.claude/skills/gstack/bin/gstack-review-read 2>/dev/null
```

Show a summary of review status: which reviews have been run, how stale they are.
Also check if CHANGELOG.md and VERSION have been updated.

Explain in plain English: "When I merge, I'll check: has the code been reviewed recently? Do the tests pass? Is the CHANGELOG updated? Is the PR description accurate? If anything looks off, I'll flag it before merging."

### 1.5e: Dry-run confirmation

Tell the user: "That's everything I detected. Take a look at the table above — does this match how your project actually deploys?"

Present the full dry-run results to the user via AskUserQuestion:

- **Re-ground:** "First deploy dry-run for [project] on branch [branch]. Above is what I detected about your deploy infrastructure. Nothing has been merged or deployed yet — this is just my understanding of your setup."
- Show the infrastructure validation table from 1.5b above.
- List any warnings from command validation, with plain-English explanations.
- If staging was detected, note: "I found a staging environment at {url/workflow}. After we merge, I'll offer to deploy there first so you can verify everything works before it hits production."
- If no staging was detected, note: "I didn't find a staging environment. The deploy will go straight to production — I'll run health checks right after to make sure everything looks good."
- **RECOMMENDATION:** Choose A if all validations passed. Choose B if there are issues to fix. Choose C to run /setup-deploy for a more thorough configuration.
- A) That's right — this is how my project deploys. Let's go. (Completeness: 10/10)
- B) Something's off — let me tell you what's wrong (Completeness: 10/10)
- C) I want to configure this more carefully first (runs /setup-deploy) (Completeness: 10/10)

**If A:** Tell the user: "Great — I've saved this configuration. Next time you run `/land-and-deploy`, I'll skip the dry run and go straight to readiness checks. If your deploy setup changes (new platform, different workflows, updated URLs), I'll automatically re-run the dry run to make sure I still have it right."

Save the deploy config fingerprint so we can detect future changes:
```bash
mkdir -p ~/.gstack/projects/$SLUG
CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
WORKFLOW_HASH=$(cat .github/workflows/*deploy* .github/workflows/*cd* 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > ~/.gstack/projects/$SLUG/land-deploy-confirmed
```
Continue to Step 2.

**If B:** **STOP.** "Tell me what's different about your setup and I'll adjust. You can also run `/setup-deploy` to walk through the full configuration."

**If C:** **STOP.** "Running `/setup-deploy` will walk through your deploy platform, production URL, and health checks in detail. It saves everything to CLAUDE.md so I'll know exactly what to do next time. Run `/land-and-deploy` again when that's done."

---

## Step 2: Pre-merge checks

Tell the user: "Checking CI status and merge readiness..."

Check CI status and merge readiness:

```bash


@@ 404,15 641,15 @@ gh pr checks --json name,state,status,conclusion
```

Parse the output:
1. If any required checks are **FAILING**: **STOP.** Show the failing checks.
2. If required checks are **PENDING**: proceed to Step 3.
3. If all checks pass (or no required checks): skip Step 3, go to Step 4.
1. If any required checks are **FAILING**: **STOP.** "CI is failing on this PR. Here are the failing checks: {list}. Fix these before deploying — I won't merge code that hasn't passed CI."
2. If required checks are **PENDING**: Tell the user "CI is still running. I'll wait for it to finish." Proceed to Step 3.
3. If all checks pass (or no required checks): Tell the user "CI passed." Skip Step 3, go to Step 4.

Also check for merge conflicts:
```bash
gh pr view --json mergeable -q .mergeable
```
If `CONFLICTING`: **STOP.** "PR has merge conflicts. Resolve them and push before landing."
If `CONFLICTING`: **STOP.** "This PR has merge conflicts with the base branch. Resolve the conflicts and push, then run `/land-and-deploy` again."

---



@@ 426,9 663,9 @@ gh pr checks --watch --fail-fast

Record the CI wait time for the deploy report.

If CI passes within the timeout: continue to Step 4.
If CI fails: **STOP.** Show failures.
If timeout (15 min): **STOP.** "CI has been running for 15 minutes. Investigate manually."
If CI passes within the timeout: Tell the user "CI passed after {duration}. Moving to readiness checks." Continue to Step 4.
If CI fails: **STOP.** "CI failed. Here's what broke: {failures}. This needs to pass before I can merge."
If timeout (15 min): **STOP.** "CI has been running for over 15 minutes — that's unusual. Check the GitHub Actions tab to see if something is stuck."

---



@@ 438,6 675,8 @@ If timeout (15 min): **STOP.** "CI has been running for 15 minutes. Investigate 
be undone without a revert commit. Gather ALL evidence, build a readiness report,
and get explicit user confirmation before proceeding.

Tell the user: "CI is green. Now I'm running readiness checks — this is the last gate before I merge. I'm checking code reviews, test results, documentation, and PR accuracy. Once you see the readiness report and approve, the merge is final."

Collect evidence for each check below. Track warnings (yellow) and blockers (red).

### 3.5a: Review staleness check


@@ 468,6 707,44 @@ If any commits after the review contain words like "fix", "refactor", "rewrite",
"overhaul", or touch more than 5 files — flag as **STALE (significant changes
since review)**. The review was done on different code than what's about to merge.

**Also check for adversarial review (`codex-review`).** If codex-review has been run
and is CURRENT, mention it in the readiness report as an extra confidence signal.
If not run, note as informational (not a blocker): "No adversarial review on record."

### 3.5a-bis: Inline review offer

**We are extra careful about deploys.** If engineering review is STALE (4+ commits since)
or NOT RUN, offer to run a quick review inline before proceeding.

Use AskUserQuestion:
- **Re-ground:** "I noticed {the code review is stale / no code review has been run} on this branch. Since this code is about to go to production, I'd like to do a quick safety check on the diff before we merge. This is one of the ways I make sure nothing ships that shouldn't."
- **RECOMMENDATION:** Choose A for a quick safety check. Choose B if you want the full
  review experience. Choose C only if you're confident in the code.
- A) Run a quick review (~2 min) — I'll scan the diff for common issues like SQL safety, race conditions, and security gaps (Completeness: 7/10)
- B) Stop and run a full `/review` first — deeper analysis, more thorough (Completeness: 10/10)
- C) Skip the review — I've reviewed this code myself and I'm confident (Completeness: 3/10)

**If A (quick checklist):** Tell the user: "Running the review checklist against your diff now..."

Read the review checklist:
```bash
cat ~/.claude/skills/gstack/review/checklist.md 2>/dev/null || echo "Checklist not found"
```
Apply each checklist item to the current diff. This is the same quick review that `/ship`
runs in its Step 3.5. Auto-fix trivial issues (whitespace, imports). For critical findings
(SQL safety, race conditions, security), ask the user.

**If any code changes are made during the quick review:** Commit the fixes, then **STOP**
and tell the user: "I found and fixed a few issues during the review. The fixes are committed — run `/land-and-deploy` again to pick them up and continue where we left off."

**If no issues found:** Tell the user: "Review checklist passed — no issues found in the diff."

**If B:** **STOP.** "Good call — run `/review` for a thorough pre-landing review. When that's done, run `/land-and-deploy` again and I'll pick up right where we left off."

**If C:** Tell the user: "Understood — skipping review. You know this code best." Continue. Log the user's choice to skip review.

**If review is CURRENT:** Skip this sub-step entirely — no question asked.

### 3.5b: Test results

**Free tests — run them now:**


@@ 545,6 822,8 @@ If only docs changed (no code): skip this check.

### 3.5e: Readiness report and confirmation

Tell the user: "Here's the full readiness report. This is everything I checked before merging."

Build the full readiness report:

```


@@ 585,28 864,32 @@ If everything is green: recommend A.

Use AskUserQuestion:

- **Re-ground:** "About to merge PR #NNN (title) from branch X to Y. Here's the
  readiness report." Show the report above.
- List each warning and blocker explicitly.
- **Re-ground:** "Ready to merge PR #NNN — '{title}' into {base}. Here's what I found."
  Show the report above.
- If everything is green: "All checks passed. This PR is ready to merge."
- If there are warnings: List each one in plain English. E.g., "The engineering review
  was done 6 commits ago — the code has changed since then" not "STALE (6 commits)."
- If there are blockers: "I found issues that need to be fixed before merging: {list}"
- **RECOMMENDATION:** Choose A if green. Choose B if there are significant warnings.
  Choose C only if the user understands the risks.
- A) Merge — readiness checks passed (Completeness: 10/10)
- B) Don't merge yet — address the warnings first (Completeness: 10/10)
- C) Merge anyway — I understand the risks (Completeness: 3/10)
- A) Merge it — everything looks good (Completeness: 10/10)
- B) Hold off — I want to fix the warnings first (Completeness: 10/10)
- C) Merge anyway — I understand the warnings and want to proceed (Completeness: 3/10)

If the user chooses B: **STOP.** List exactly what needs to be done:
- If reviews are stale: "Re-run `/plan-eng-review`, `/review`, or `/autoplan` to review current code."
- If E2E not run: "Run `bun run test:e2e` to verify."
- If docs not updated: "Run /document-release to update documentation."
- If PR body stale: "Update the PR body to reflect current changes."
If the user chooses B: **STOP.** Give specific next steps:
- If reviews are stale: "Run `/review` or `/autoplan` to review the current code, then `/land-and-deploy` again."
- If E2E not run: "Run your E2E tests to make sure nothing is broken, then come back."
- If docs not updated: "Run `/document-release` to update CHANGELOG and docs."
- If PR body stale: "The PR description doesn't match what's actually in the diff — update it on GitHub."

If the user chooses A or C: continue to Step 4.
If the user chooses A or C: Tell the user "Merging now." Continue to Step 4.

---

## Step 4: Merge the PR

Record the start timestamp for timing data.
Record the start timestamp for timing data. Also record which merge path is taken
(auto-merge vs direct) for the deploy report.

Try auto-merge first (respects repo merge settings and merge queues):



@@ 614,27 897,59 @@ Try auto-merge first (respects repo merge settings and merge queues):
gh pr merge --auto --delete-branch
```

If `--auto` succeeds: record `MERGE_PATH=auto`. This means the repo has auto-merge enabled
and may use merge queues.

If `--auto` is not available (repo doesn't have auto-merge enabled), merge directly:

```bash
gh pr merge --squash --delete-branch
```

If the merge fails with a permission error: **STOP.** "You don't have merge permissions on this repo. Ask a maintainer to merge."
If direct merge succeeds: record `MERGE_PATH=direct`. Tell the user: "PR merged successfully. The branch has been cleaned up."

If the merge fails with a permission error: **STOP.** "I don't have permission to merge this PR. You'll need a maintainer to merge it, or check your repo's branch protection rules."

If merge queue is active, `gh pr merge --auto` will enqueue. Poll for the PR to actually merge:
### 4a: Merge queue detection and messaging

If `MERGE_PATH=auto` and the PR state does not immediately become `MERGED`, the PR is
in a **merge queue**. Tell the user:

"Your repo uses a merge queue — that means GitHub will run CI one more time on the final merge commit before it actually merges. This is a good thing (it catches last-minute conflicts), but it means we wait. I'll keep checking until it goes through."

Poll for the PR to actually merge:

```bash
gh pr view --json state -q .state
```

Poll every 30 seconds, up to 30 minutes. Show a progress message every 2 minutes: "Waiting for merge queue... (Xm elapsed)"
Poll every 30 seconds, up to 30 minutes. Show a progress message every 2 minutes:
"Still in the merge queue... ({X}m so far)"

If the PR state changes to `MERGED`: capture the merge commit SHA. Tell the user:
"Merge queue finished — PR is merged. Took {duration}."

If the PR is removed from the queue (state goes back to `OPEN`): **STOP.** "The PR was removed from the merge queue — this usually means a CI check failed on the merge commit, or another PR in the queue caused a conflict. Check the GitHub merge queue page to see what happened."
If timeout (30 min): **STOP.** "The merge queue has been processing for 30 minutes. Something might be stuck — check the GitHub Actions tab and the merge queue page."

### 4b: CI auto-deploy detection

After the PR is merged, check if a deploy workflow was triggered by the merge:

```bash
gh run list --branch <base> --limit 5 --json name,status,workflowName,headSha
```

Look for runs matching the merge commit SHA. If a deploy workflow is found:
- Tell the user: "PR merged. I can see a deploy workflow ('{workflow-name}') kicked off automatically. I'll monitor it and let you know when it's done."

If no deploy workflow is found after merge:
- Tell the user: "PR merged. I don't see a deploy workflow — your project might deploy a different way, or it might be a library/CLI that doesn't have a deploy step. I'll figure out the right verification in the next step."

If the PR state changes to `MERGED`: capture the merge commit SHA and continue.
If the PR is removed from the queue (state goes back to `OPEN`): **STOP.** "PR was removed from the merge queue."
If timeout (30 min): **STOP.** "Merge queue has been processing for 30 minutes. Check the queue manually."
If `MERGE_PATH=auto` and the repo uses merge queues AND a deploy workflow exists:
- Tell the user: "PR made it through the merge queue and the deploy workflow is running. Monitoring it now."

Record merge timestamp and duration.
Record merge timestamp, duration, and merge path for the deploy report.

---



@@ 667,7 982,8 @@ fi

# Detect deploy workflows
for f in .github/workflows/*.yml .github/workflows/*.yaml; do
  [ -f "$f" ] && grep -qiE "deploy|release|production|staging|cd" "$f" 2>/dev/null && echo "DEPLOY_WORKFLOW:$f"
  [ -f "$f" ] && grep -qiE "deploy|release|production|cd" "$f" 2>/dev/null && echo "DEPLOY_WORKFLOW:$f"
  [ -f "$f" ] && grep -qiE "staging" "$f" 2>/dev/null && echo "STAGING_WORKFLOW:$f"
done
```



@@ 693,15 1009,45 @@ echo "FRONTEND=$SCOPE_FRONTEND BACKEND=$SCOPE_BACKEND DOCS=$SCOPE_DOCS CONFIG=$S
```bash
gh run list --branch <base> --limit 5 --json name,status,conclusion,headSha,workflowName
```
Look for workflow names containing "deploy", "release", "production", "staging", or "cd". If found: poll the deploy workflow in Step 6, then run canary.
Look for workflow names containing "deploy", "release", "production", or "cd". If found: poll the deploy workflow in Step 6, then run canary.

3. If SCOPE_DOCS is the only scope that's true (no frontend, no backend, no config): skip verification entirely. Output: "PR merged. Documentation-only change — no deploy verification needed." Go to Step 9.
3. If SCOPE_DOCS is the only scope that's true (no frontend, no backend, no config): skip verification entirely. Tell the user: "This was a docs-only change — nothing to deploy or verify. You're all set." Go to Step 9.

4. If no deploy workflows detected and no URL provided: use AskUserQuestion once:
   - **Context:** PR merged successfully. No deploy workflow or production URL detected.
   - **Re-ground:** "PR is merged, but I don't see a deploy workflow or a production URL for this project. If this is a web app, I can verify the deploy if you give me the URL. If it's a library or CLI tool, there's nothing to verify — we're done."
   - **RECOMMENDATION:** Choose B if this is a library/CLI tool. Choose A if this is a web app.
   - A) Provide a production URL to verify
   - B) Skip verification — this project doesn't have a web deploy
   - A) Here's the production URL: {let them type it}
   - B) No deploy needed — this isn't a web app

### 5a: Staging-first option

If staging was detected in Step 1.5c (or from CLAUDE.md deploy config), and the changes
include code (not docs-only), offer the staging-first option:

Use AskUserQuestion:
- **Re-ground:** "I found a staging environment at {staging URL or workflow}. Since this deploy includes code changes, I can verify everything works on staging first — before it hits production. This is the safest path: if something breaks on staging, production is untouched."
- **RECOMMENDATION:** Choose A for maximum safety. Choose B if you're confident.
- A) Deploy to staging first, verify it works, then go to production (Completeness: 10/10)
- B) Skip staging — go straight to production (Completeness: 7/10)
- C) Deploy to staging only — I'll check production later (Completeness: 8/10)

**If A (staging first):** Tell the user: "Deploying to staging first. I'll run the same health checks I'd run on production — if staging looks good, I'll move on to production automatically."

Run Steps 6-7 against the staging target first. Use the staging
URL or staging workflow for deploy verification and canary checks. After staging passes,
tell the user: "Staging is healthy — your changes are working. Now deploying to production." Then run
Steps 6-7 again against the production target.

**If B (skip staging):** Tell the user: "Skipping staging — going straight to production." Proceed with production deployment as normal.

**If C (staging only):** Tell the user: "Deploying to staging only. I'll verify it works and stop there."

Run Steps 6-7 against the staging target. After verification,
print the deploy report (Step 9) with verdict "STAGING VERIFIED — production deploy pending."
Then tell the user: "Staging looks good. When you're ready for production, run `/land-and-deploy` again."
**STOP.** The user can re-run `/land-and-deploy` later for production.

**If no staging detected:** Skip this sub-step entirely. No question asked.

---



@@ 755,23 1101,25 @@ If CLAUDE.md has a custom deploy status command in the "Custom deploy hooks" sec

### Common: Timing and failure handling

Record deploy start time. Show progress every 2 minutes: "Deploy in progress... (Xm elapsed)"
Record deploy start time. Show progress every 2 minutes: "Deploy is still running... ({X}m so far). This is normal for most platforms."

If deploy succeeds (`conclusion` is `success` or health check passes): record deploy duration, continue to Step 7.
If deploy succeeds (`conclusion` is `success` or health check passes): Tell the user "Deploy finished successfully. Took {duration}. Now I'll verify the site is healthy." Record deploy duration, continue to Step 7.

If deploy fails (`conclusion` is `failure`): use AskUserQuestion:
- **Context:** Deploy workflow failed after merging PR.
- **Re-ground:** "The deploy workflow failed after the merge. The code is merged but may not be live yet. Here's what I can do:"
- **RECOMMENDATION:** Choose A to investigate before reverting.
- A) Investigate the deploy logs
- B) Create a revert commit on the base branch
- C) Continue anyway — the deploy failure might be unrelated
- A) Let me look at the deploy logs to figure out what went wrong
- B) Revert the merge immediately — roll back to the previous version
- C) Continue to health checks anyway — the deploy failure might be a flaky step, and the site might actually be fine

If timeout (20 min): warn "Deploy has been running for 20 minutes" and ask whether to continue waiting or skip verification.
If timeout (20 min): "The deploy has been running for 20 minutes, which is longer than most deploys take. The site might still be deploying, or something might be stuck." Ask whether to continue waiting or skip verification.

---

## Step 7: Canary verification (conditional depth)

Tell the user: "Deploy is done. Now I'm going to check the live site to make sure everything looks good — loading the page, checking for errors, and measuring performance."

Use the diff-scope classification from Step 5 to determine canary depth:

| Diff Scope | Canary Depth |


@@ 820,14 1168,14 @@ Take an annotated screenshot as evidence.
- Page has real content (not blank or error screen) → PASS
- Loads in under 10 seconds → PASS

If all pass: mark as HEALTHY, continue to Step 9.
If all pass: Tell the user "Site is healthy. Page loaded in {X}s, no console errors, content looks good. Screenshot saved to {path}." Mark as HEALTHY, continue to Step 9.

If any fail: show the evidence (screenshot path, console errors, perf numbers). Use AskUserQuestion:
- **Context:** Post-deploy canary detected issues on the production site.
- **Re-ground:** "I found some issues on the live site after the deploy. Here's what I see: {specific issues}. This might be temporary (caches clearing, CDN propagating) or it might be a real problem."
- **RECOMMENDATION:** Choose based on severity — B for critical (site down), A for minor (console errors).
- A) Expected (deploy in progress, cache clearing) — mark as healthy
- B) Broken — create a revert commit
- C) Investigate further (open the site, look at logs)
- A) That's expected — the site is still warming up. Mark it as healthy.
- B) That's broken — revert the merge and roll back to the previous version
- C) Let me investigate more — open the site and look at logs before deciding

---



@@ 835,6 1183,8 @@ If any fail: show the evidence (screenshot path, console errors, perf numbers). 

If the user chose to revert at any point:

Tell the user: "Reverting the merge now. This will create a new commit that undoes all the changes from this PR. The previous version of your site will be restored once the revert deploys."

```bash
git fetch origin <base>
git checkout <base>


@@ 842,11 1192,12 @@ git revert <merge-commit-sha> --no-edit
git push origin <base>
```

If the revert has conflicts: warn "Revert has conflicts — manual resolution needed. The merge commit SHA is `<sha>`. You can run `git revert <sha>` manually."
If the revert has conflicts: "The revert has merge conflicts — this can happen if other changes landed on {base} after your merge. You'll need to resolve the conflicts manually. The merge commit SHA is `<sha>` — run `git revert <sha>` to try again."

If the base branch has push protections: warn "Branch protections may prevent direct push — create a revert PR instead: `gh pr create --title 'revert: <original PR title>'`"
If the base branch has push protections: "This repo has branch protections, so I can't push the revert directly. I'll create a revert PR instead — merge it to roll back."
Then create a revert PR: `gh pr create --title 'revert: <original PR title>'`

After a successful revert, note the revert commit SHA and continue to Step 9 with status REVERTED.
After a successful revert: Tell the user "Revert pushed to {base}. The deploy should roll back automatically once CI passes. Keep an eye on the site to confirm." Note the revert commit SHA and continue to Step 9 with status REVERTED.

---



@@ 867,23 1218,32 @@ PR:           #<number> — <title>
Branch:       <head-branch> → <base-branch>
Merged:       <timestamp> (<merge method>)
Merge SHA:    <sha>
Merge path:   <auto-merge / direct / merge queue>
First run:    <yes (dry-run validated) / no (previously confirmed)>

Timing:
  Dry-run:    <duration or "skipped (confirmed)">
  CI wait:    <duration>
  Queue:      <duration or "direct merge">
  Deploy:     <duration or "no workflow detected">
  Staging:    <duration or "skipped">
  Canary:     <duration or "skipped">
  Total:      <end-to-end duration>

Reviews:
  Eng review: <CURRENT / STALE / NOT RUN>
  Inline fix: <yes (N fixes) / no / skipped>

CI:           <PASSED / SKIPPED>
Deploy:       <PASSED / FAILED / NO WORKFLOW>
Deploy:       <PASSED / FAILED / NO WORKFLOW / CI AUTO-DEPLOY>
Staging:      <VERIFIED / SKIPPED / N/A>
Verification: <HEALTHY / DEGRADED / SKIPPED / REVERTED>
  Scope:      <FRONTEND / BACKEND / CONFIG / DOCS / MIXED>
  Console:    <N errors or "clean">
  Load time:  <Xs>
  Screenshot: <path or "none">

VERDICT: <DEPLOYED AND VERIFIED / DEPLOYED (UNVERIFIED) / REVERTED>
VERDICT: <DEPLOYED AND VERIFIED / DEPLOYED (UNVERIFIED) / STAGING VERIFIED / REVERTED>
```

Save report to `.gstack/deploy-reports/{date}-pr{number}-deploy.md`.


@@ 897,28 1257,38 @@ mkdir -p ~/.gstack/projects/$SLUG

Write a JSONL entry with timing data:
```json
{"skill":"land-and-deploy","timestamp":"<ISO>","status":"<SUCCESS/REVERTED>","pr":<number>,"merge_sha":"<sha>","deploy_status":"<HEALTHY/DEGRADED/SKIPPED>","ci_wait_s":<N>,"queue_s":<N>,"deploy_s":<N>,"canary_s":<N>,"total_s":<N>}
{"skill":"land-and-deploy","timestamp":"<ISO>","status":"<SUCCESS/REVERTED>","pr":<number>,"merge_sha":"<sha>","merge_path":"<auto/direct/queue>","first_run":<true/false>,"deploy_status":"<HEALTHY/DEGRADED/SKIPPED>","staging_status":"<VERIFIED/SKIPPED>","review_status":"<CURRENT/STALE/NOT_RUN/INLINE_FIX>","ci_wait_s":<N>,"queue_s":<N>,"deploy_s":<N>,"staging_s":<N>,"canary_s":<N>,"total_s":<N>}
```

---

## Step 10: Suggest follow-ups

After the deploy report, suggest relevant follow-ups:
After the deploy report:

If verdict is DEPLOYED AND VERIFIED: Tell the user "Your changes are live and verified. Nice ship."

If verdict is DEPLOYED (UNVERIFIED): Tell the user "Your changes are merged and should be deploying. I wasn't able to verify the site — check it manually when you get a chance."

If verdict is REVERTED: Tell the user "The merge was reverted. Your changes are no longer on {base}. The PR branch is still available if you need to fix and re-ship."

- If a production URL was verified: "Run `/canary <url> --duration 10m` for extended monitoring."
- If performance data was collected: "Run `/benchmark <url>` for a deep performance audit."
- "Run `/document-release` to update project documentation."
Then suggest relevant follow-ups:
- If a production URL was verified: "Want extended monitoring? Run `/canary <url>` to watch the site for the next 10 minutes."
- If performance data was collected: "Want a deeper performance analysis? Run `/benchmark <url>`."
- "Need to update docs? Run `/document-release` to sync README, CHANGELOG, and other docs with what you just shipped."

---

## Important Rules

- **Never force push.** Use `gh pr merge` which is safe.
- **Never skip CI.** If checks are failing, stop.
- **Auto-detect everything.** PR number, merge method, deploy strategy, project type. Only ask when information genuinely can't be inferred.
- **Never skip CI.** If checks are failing, stop and explain why.
- **Narrate the journey.** The user should always know: what just happened, what's happening now, and what's about to happen next. No silent gaps between steps.
- **Auto-detect everything.** PR number, merge method, deploy strategy, project type, merge queues, staging environments. Only ask when information genuinely can't be inferred.
- **Poll with backoff.** Don't hammer GitHub API. 30-second intervals for CI/deploy, with reasonable timeouts.
- **Revert is always an option.** At every failure point, offer revert as an escape hatch.
- **Revert is always an option.** At every failure point, offer revert as an escape hatch. Explain what reverting does in plain English.
- **Single-pass verification, not continuous monitoring.** `/land-and-deploy` checks once. `/canary` does the extended monitoring loop.
- **Clean up.** Delete the feature branch after merge (via `--delete-branch`).
- **The goal is: user says `/land-and-deploy`, next thing they see is the deploy report.**
- **First run = teacher mode.** Walk the user through everything. Explain what each check does and why it matters. Show them their infrastructure. Let them confirm before proceeding. Build trust through transparency.
- **Subsequent runs = efficient mode.** Brief status updates, no re-explanations. The user already trusts the tool — just do the job and report results.
- **The goal is: first-timers think "wow, this is thorough — I trust it." Repeat users think "that was fast — it just works."**

M land-and-deploy/SKILL.md.tmpl => land-and-deploy/SKILL.md.tmpl +400 -64
@@ 45,7 45,8 @@ the ones listed below. The user said `/land-and-deploy` which means DO IT — bu
readiness first.

**Always stop for:**
- **Pre-merge readiness gate (Step 3.5)** — this is the ONE confirmation before merge
- **First-run dry-run validation (Step 1.5)** — shows deploy infrastructure and confirms setup
- **Pre-merge readiness gate (Step 3.5)** — reviews, tests, docs check before merge
- GitHub CLI not authenticated
- No PR found for this branch
- CI failures or merge conflicts


@@ 57,15 58,29 @@ readiness first.
- Choosing merge method (auto-detect from repo settings)
- Timeout warnings (warn and continue gracefully)

## Voice & Tone

Every message to the user should make them feel like they have a senior release engineer
sitting next to them. The tone is:
- **Narrate what's happening now.** "Checking your CI status..." not just silence.
- **Explain why before asking.** "Deploys are irreversible, so I check X before proceeding."
- **Be specific, not generic.** "Your Fly.io app 'myapp' is healthy" not "deploy looks good."
- **Acknowledge the stakes.** This is production. The user is trusting you with their users' experience.
- **First run = teacher mode.** Walk them through everything. Explain what each check does and why.
- **Subsequent runs = efficient mode.** Brief status updates, no re-explanations.
- **Never be robotic.** "I ran 4 checks and found 1 issue" not "CHECKS: 4, ISSUES: 1."

---

## Step 1: Pre-flight

Tell the user: "Starting deploy sequence. First, let me make sure everything is connected and find your PR."

1. Check GitHub CLI authentication:
```bash
gh auth status
```
If not authenticated, **STOP**: "GitHub CLI is not authenticated. Run `gh auth login` first."
If not authenticated, **STOP**: "I need GitHub CLI access to merge your PR. Run `gh auth login` to connect, then try `/land-and-deploy` again."

2. Parse arguments. If the user specified `#NNN`, use that PR number. If a URL was provided, save it for canary verification in Step 7.



@@ 74,16 89,205 @@ If not authenticated, **STOP**: "GitHub CLI is not authenticated. Run `gh auth l
gh pr view --json number,state,title,url,mergeStateStatus,mergeable,baseRefName,headRefName
```

4. Validate the PR state:
   - If no PR exists: **STOP.** "No PR found for this branch. Run `/ship` first to create one."
   - If `state` is `MERGED`: "PR is already merged. Nothing to do."
   - If `state` is `CLOSED`: "PR is closed (not merged). Reopen it first."
4. Tell the user what you found: "Found PR #NNN — '{title}' (branch → base)."

5. Validate the PR state:
   - If no PR exists: **STOP.** "No PR found for this branch. Run `/ship` first to create a PR, then come back here to land and deploy it."
   - If `state` is `MERGED`: "This PR is already merged — nothing to deploy. If you need to verify the deploy, run `/canary <url>` instead."
   - If `state` is `CLOSED`: "This PR was closed without merging. Reopen it on GitHub first, then try again."
   - If `state` is `OPEN`: continue.

---

## Step 1.5: First-run dry-run validation

Check whether this project has been through a successful `/land-and-deploy` before,
and whether the deploy configuration has changed since then:

```bash
{{SLUG_EVAL}}
if [ ! -f ~/.gstack/projects/$SLUG/land-deploy-confirmed ]; then
  echo "FIRST_RUN"
else
  # Check if deploy config has changed since confirmation
  SAVED_HASH=$(cat ~/.gstack/projects/$SLUG/land-deploy-confirmed 2>/dev/null)
  CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
  # Also hash workflow files that affect deploy behavior
  WORKFLOW_HASH=$(cat .github/workflows/*deploy* .github/workflows/*cd* 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
  COMBINED_HASH="${CURRENT_HASH}-${WORKFLOW_HASH}"
  if [ "$SAVED_HASH" != "$COMBINED_HASH" ] && [ -n "$SAVED_HASH" ]; then
    echo "CONFIG_CHANGED"
  else
    echo "CONFIRMED"
  fi
fi
```

**If CONFIRMED:** Print "I've deployed this project before and know how it works. Moving straight to readiness checks." Proceed to Step 2.

**If CONFIG_CHANGED:** The deploy configuration has changed since the last confirmed deploy.
Re-trigger the dry run. Tell the user:

"I've deployed this project before, but your deploy configuration has changed since the last
time. That could mean a new platform, a different workflow, or updated URLs. I'm going to
do a quick dry run to make sure I still understand how your project deploys."

Then proceed to the FIRST_RUN flow below (steps 1.5a through 1.5e).

**If FIRST_RUN:** This is the first time `/land-and-deploy` is running for this project. Before doing anything irreversible, show the user exactly what will happen. This is a dry run — explain, validate, and confirm.

Tell the user:

"This is the first time I'm deploying this project, so I'm going to do a dry run first.

Here's what that means: I'll detect your deploy infrastructure, test that my commands actually work, and show you exactly what will happen — step by step — before I touch anything. Deploys are irreversible once they hit production, so I want to earn your trust before I start merging.

Let me take a look at your setup."

### 1.5a: Deploy infrastructure detection

Run the deploy configuration bootstrap to detect the platform and settings:

{{DEPLOY_BOOTSTRAP}}

Parse the output and record: the detected platform, production URL, deploy workflow (if any),
and any persisted config from CLAUDE.md.

### 1.5b: Command validation

Test each detected command to verify the detection is accurate. Build a validation table:

```bash
# Test gh auth (already passed in Step 1, but confirm)
gh auth status 2>&1 | head -3

# Test platform CLI if detected
# Fly.io: fly status --app {app} 2>/dev/null
# Heroku: heroku releases --app {app} -n 1 2>/dev/null
# Vercel: vercel ls 2>/dev/null | head -3

# Test production URL reachability
# curl -sf {production-url} -o /dev/null -w "%{http_code}" 2>/dev/null
```

Run whichever commands are relevant based on the detected platform. Build the results into this table:

```
╔══════════════════════════════════════════════════════════╗
║         DEPLOY INFRASTRUCTURE VALIDATION                  ║
╠══════════════════════════════════════════════════════════╣
║                                                            ║
║  Platform:    {platform} (from {source})                   ║
║  App:         {app name or "N/A"}                          ║
║  Prod URL:    {url or "not configured"}                    ║
║                                                            ║
║  COMMAND VALIDATION                                        ║
║  ├─ gh auth status:     ✓ PASS                             ║
║  ├─ {platform CLI}:     ✓ PASS / ⚠ NOT INSTALLED / ✗ FAIL ║
║  ├─ curl prod URL:      ✓ PASS (200 OK) / ⚠ UNREACHABLE   ║
║  └─ deploy workflow:    {file or "none detected"}          ║
║                                                            ║
║  STAGING DETECTION                                         ║
║  ├─ Staging URL:        {url or "not configured"}          ║
║  ├─ Staging workflow:   {file or "not found"}              ║
║  └─ Preview deploys:    {detected or "not detected"}       ║
║                                                            ║
║  WHAT WILL HAPPEN                                          ║
║  1. Run pre-merge readiness checks (reviews, tests, docs)  ║
║  2. Wait for CI if pending                                 ║
║  3. Merge PR via {merge method}                            ║
║  4. {Wait for deploy workflow / Wait 60s / Skip}           ║
║  5. {Run canary verification / Skip (no URL)}              ║
║                                                            ║
║  MERGE METHOD: {squash/merge/rebase} (from repo settings)  ║
║  MERGE QUEUE:  {detected / not detected}                   ║
╚══════════════════════════════════════════════════════════╝
```

**Validation failures are WARNINGs, not BLOCKERs** (except `gh auth status` which already
failed at Step 1). If `curl` fails, note "I couldn't reach that URL — might be a network
issue, VPN requirement, or incorrect address. I'll still be able to deploy, but I won't
be able to verify the site is healthy afterward."
If platform CLI is not installed, note "The {platform} CLI isn't installed on this machine.
I can still deploy through GitHub, but I'll use HTTP health checks instead of the platform
CLI to verify the deploy worked."

### 1.5c: Staging detection

Check for staging environments in this order:

1. **CLAUDE.md persisted config:** Check for a staging URL in the Deploy Configuration section:
```bash
grep -i "staging" CLAUDE.md 2>/dev/null | head -3
```

2. **GitHub Actions staging workflow:** Check for workflow files with "staging" in the name or content:
```bash
for f in .github/workflows/*.yml .github/workflows/*.yaml; do
  [ -f "$f" ] && grep -qiE "staging" "$f" 2>/dev/null && echo "STAGING_WORKFLOW:$f"
done
```

3. **Vercel/Netlify preview deploys:** Check PR status checks for preview URLs:
```bash
gh pr checks --json name,targetUrl 2>/dev/null | head -20
```
Look for check names containing "vercel", "netlify", or "preview" and extract the target URL.

Record any staging targets found. These will be offered in Step 5.

### 1.5d: Readiness preview

Tell the user: "Before I merge any PR, I run a series of readiness checks — code reviews, tests, documentation, PR accuracy. Let me show you what that looks like for this project."

Preview the readiness checks that will run at Step 3.5 (without re-running tests):

```bash
~/.claude/skills/gstack/bin/gstack-review-read 2>/dev/null
```

Show a summary of review status: which reviews have been run, how stale they are.
Also check if CHANGELOG.md and VERSION have been updated.

Explain in plain English: "When I merge, I'll check: has the code been reviewed recently? Do the tests pass? Is the CHANGELOG updated? Is the PR description accurate? If anything looks off, I'll flag it before merging."

### 1.5e: Dry-run confirmation

Tell the user: "That's everything I detected. Take a look at the table above — does this match how your project actually deploys?"

Present the full dry-run results to the user via AskUserQuestion:

- **Re-ground:** "First deploy dry-run for [project] on branch [branch]. Above is what I detected about your deploy infrastructure. Nothing has been merged or deployed yet — this is just my understanding of your setup."
- Show the infrastructure validation table from 1.5b above.
- List any warnings from command validation, with plain-English explanations.
- If staging was detected, note: "I found a staging environment at {url/workflow}. After we merge, I'll offer to deploy there first so you can verify everything works before it hits production."
- If no staging was detected, note: "I didn't find a staging environment. The deploy will go straight to production — I'll run health checks right after to make sure everything looks good."
- **RECOMMENDATION:** Choose A if all validations passed. Choose B if there are issues to fix. Choose C to run /setup-deploy for a more thorough configuration.
- A) That's right — this is how my project deploys. Let's go. (Completeness: 10/10)
- B) Something's off — let me tell you what's wrong (Completeness: 10/10)
- C) I want to configure this more carefully first (runs /setup-deploy) (Completeness: 10/10)

**If A:** Tell the user: "Great — I've saved this configuration. Next time you run `/land-and-deploy`, I'll skip the dry run and go straight to readiness checks. If your deploy setup changes (new platform, different workflows, updated URLs), I'll automatically re-run the dry run to make sure I still have it right."

Save the deploy config fingerprint so we can detect future changes:
```bash
mkdir -p ~/.gstack/projects/$SLUG
CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
WORKFLOW_HASH=$(cat .github/workflows/*deploy* .github/workflows/*cd* 2>/dev/null | shasum -a 256 | cut -d' ' -f1)
echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > ~/.gstack/projects/$SLUG/land-deploy-confirmed
```
Continue to Step 2.

**If B:** **STOP.** "Tell me what's different about your setup and I'll adjust. You can also run `/setup-deploy` to walk through the full configuration."

**If C:** **STOP.** "Running `/setup-deploy` will walk through your deploy platform, production URL, and health checks in detail. It saves everything to CLAUDE.md so I'll know exactly what to do next time. Run `/land-and-deploy` again when that's done."

---

## Step 2: Pre-merge checks

Tell the user: "Checking CI status and merge readiness..."

Check CI status and merge readiness:

```bash


@@ 91,15 295,15 @@ gh pr checks --json name,state,status,conclusion
```

Parse the output:
1. If any required checks are **FAILING**: **STOP.** Show the failing checks.
2. If required checks are **PENDING**: proceed to Step 3.
3. If all checks pass (or no required checks): skip Step 3, go to Step 4.
1. If any required checks are **FAILING**: **STOP.** "CI is failing on this PR. Here are the failing checks: {list}. Fix these before deploying — I won't merge code that hasn't passed CI."
2. If required checks are **PENDING**: Tell the user "CI is still running. I'll wait for it to finish." Proceed to Step 3.
3. If all checks pass (or no required checks): Tell the user "CI passed." Skip Step 3, go to Step 4.

Also check for merge conflicts:
```bash
gh pr view --json mergeable -q .mergeable
```
If `CONFLICTING`: **STOP.** "PR has merge conflicts. Resolve them and push before landing."
If `CONFLICTING`: **STOP.** "This PR has merge conflicts with the base branch. Resolve the conflicts and push, then run `/land-and-deploy` again."

---



@@ 113,9 317,9 @@ gh pr checks --watch --fail-fast

Record the CI wait time for the deploy report.

If CI passes within the timeout: continue to Step 4.
If CI fails: **STOP.** Show failures.
If timeout (15 min): **STOP.** "CI has been running for 15 minutes. Investigate manually."
If CI passes within the timeout: Tell the user "CI passed after {duration}. Moving to readiness checks." Continue to Step 4.
If CI fails: **STOP.** "CI failed. Here's what broke: {failures}. This needs to pass before I can merge."
If timeout (15 min): **STOP.** "CI has been running for over 15 minutes — that's unusual. Check the GitHub Actions tab to see if something is stuck."

---



@@ 125,6 329,8 @@ If timeout (15 min): **STOP.** "CI has been running for 15 minutes. Investigate 
be undone without a revert commit. Gather ALL evidence, build a readiness report,
and get explicit user confirmation before proceeding.

Tell the user: "CI is green. Now I'm running readiness checks — this is the last gate before I merge. I'm checking code reviews, test results, documentation, and PR accuracy. Once you see the readiness report and approve, the merge is final."

Collect evidence for each check below. Track warnings (yellow) and blockers (red).

### 3.5a: Review staleness check


@@ 155,6 361,44 @@ If any commits after the review contain words like "fix", "refactor", "rewrite",
"overhaul", or touch more than 5 files — flag as **STALE (significant changes
since review)**. The review was done on different code than what's about to merge.

**Also check for adversarial review (`codex-review`).** If codex-review has been run
and is CURRENT, mention it in the readiness report as an extra confidence signal.
If not run, note as informational (not a blocker): "No adversarial review on record."

### 3.5a-bis: Inline review offer

**We are extra careful about deploys.** If engineering review is STALE (4+ commits since)
or NOT RUN, offer to run a quick review inline before proceeding.

Use AskUserQuestion:
- **Re-ground:** "I noticed {the code review is stale / no code review has been run} on this branch. Since this code is about to go to production, I'd like to do a quick safety check on the diff before we merge. This is one of the ways I make sure nothing ships that shouldn't."
- **RECOMMENDATION:** Choose A for a quick safety check. Choose B if you want the full
  review experience. Choose C only if you're confident in the code.
- A) Run a quick review (~2 min) — I'll scan the diff for common issues like SQL safety, race conditions, and security gaps (Completeness: 7/10)
- B) Stop and run a full `/review` first — deeper analysis, more thorough (Completeness: 10/10)
- C) Skip the review — I've reviewed this code myself and I'm confident (Completeness: 3/10)

**If A (quick checklist):** Tell the user: "Running the review checklist against your diff now..."

Read the review checklist:
```bash
cat ~/.claude/skills/gstack/review/checklist.md 2>/dev/null || echo "Checklist not found"
```
Apply each checklist item to the current diff. This is the same quick review that `/ship`
runs in its Step 3.5. Auto-fix trivial issues (whitespace, imports). For critical findings
(SQL safety, race conditions, security), ask the user.

**If any code changes are made during the quick review:** Commit the fixes, then **STOP**
and tell the user: "I found and fixed a few issues during the review. The fixes are committed — run `/land-and-deploy` again to pick them up and continue where we left off."

**If no issues found:** Tell the user: "Review checklist passed — no issues found in the diff."

**If B:** **STOP.** "Good call — run `/review` for a thorough pre-landing review. When that's done, run `/land-and-deploy` again and I'll pick up right where we left off."

**If C:** Tell the user: "Understood — skipping review. You know this code best." Continue. Log the user's choice to skip review.

**If review is CURRENT:** Skip this sub-step entirely — no question asked.

### 3.5b: Test results

**Free tests — run them now:**


@@ 232,6 476,8 @@ If only docs changed (no code): skip this check.

### 3.5e: Readiness report and confirmation

Tell the user: "Here's the full readiness report. This is everything I checked before merging."

Build the full readiness report:

```


@@ 272,28 518,32 @@ If everything is green: recommend A.

Use AskUserQuestion:

- **Re-ground:** "About to merge PR #NNN (title) from branch X to Y. Here's the
  readiness report." Show the report above.
- List each warning and blocker explicitly.
- **Re-ground:** "Ready to merge PR #NNN — '{title}' into {base}. Here's what I found."
  Show the report above.
- If everything is green: "All checks passed. This PR is ready to merge."
- If there are warnings: List each one in plain English. E.g., "The engineering review
  was done 6 commits ago — the code has changed since then" not "STALE (6 commits)."
- If there are blockers: "I found issues that need to be fixed before merging: {list}"
- **RECOMMENDATION:** Choose A if green. Choose B if there are significant warnings.
  Choose C only if the user understands the risks.
- A) Merge — readiness checks passed (Completeness: 10/10)
- B) Don't merge yet — address the warnings first (Completeness: 10/10)
- C) Merge anyway — I understand the risks (Completeness: 3/10)
- A) Merge it — everything looks good (Completeness: 10/10)
- B) Hold off — I want to fix the warnings first (Completeness: 10/10)
- C) Merge anyway — I understand the warnings and want to proceed (Completeness: 3/10)

If the user chooses B: **STOP.** List exactly what needs to be done:
- If reviews are stale: "Re-run `/plan-eng-review`, `/review`, or `/autoplan` to review current code."
- If E2E not run: "Run `bun run test:e2e` to verify."
- If docs not updated: "Run /document-release to update documentation."
- If PR body stale: "Update the PR body to reflect current changes."
If the user chooses B: **STOP.** Give specific next steps:
- If reviews are stale: "Run `/review` or `/autoplan` to review the current code, then `/land-and-deploy` again."
- If E2E not run: "Run your E2E tests to make sure nothing is broken, then come back."
- If docs not updated: "Run `/document-release` to update CHANGELOG and docs."
- If PR body stale: "The PR description doesn't match what's actually in the diff — update it on GitHub."

If the user chooses A or C: continue to Step 4.
If the user chooses A or C: Tell the user "Merging now." Continue to Step 4.

---

## Step 4: Merge the PR

Record the start timestamp for timing data.
Record the start timestamp for timing data. Also record which merge path is taken
(auto-merge vs direct) for the deploy report.

Try auto-merge first (respects repo merge settings and merge queues):



@@ 301,27 551,59 @@ Try auto-merge first (respects repo merge settings and merge queues):
gh pr merge --auto --delete-branch
```

If `--auto` succeeds: record `MERGE_PATH=auto`. This means the repo has auto-merge enabled
and may use merge queues.

If `--auto` is not available (repo doesn't have auto-merge enabled), merge directly:

```bash
gh pr merge --squash --delete-branch
```

If the merge fails with a permission error: **STOP.** "You don't have merge permissions on this repo. Ask a maintainer to merge."
If direct merge succeeds: record `MERGE_PATH=direct`. Tell the user: "PR merged successfully. The branch has been cleaned up."

If the merge fails with a permission error: **STOP.** "I don't have permission to merge this PR. You'll need a maintainer to merge it, or check your repo's branch protection rules."

### 4a: Merge queue detection and messaging

If `MERGE_PATH=auto` and the PR state does not immediately become `MERGED`, the PR is
in a **merge queue**. Tell the user:

If merge queue is active, `gh pr merge --auto` will enqueue. Poll for the PR to actually merge:
"Your repo uses a merge queue — that means GitHub will run CI one more time on the final merge commit before it actually merges. This is a good thing (it catches last-minute conflicts), but it means we wait. I'll keep checking until it goes through."

Poll for the PR to actually merge:

```bash
gh pr view --json state -q .state
```

Poll every 30 seconds, up to 30 minutes. Show a progress message every 2 minutes: "Waiting for merge queue... (Xm elapsed)"
Poll every 30 seconds, up to 30 minutes. Show a progress message every 2 minutes:
"Still in the merge queue... ({X}m so far)"

If the PR state changes to `MERGED`: capture the merge commit SHA. Tell the user:
"Merge queue finished — PR is merged. Took {duration}."

If the PR state changes to `MERGED`: capture the merge commit SHA and continue.
If the PR is removed from the queue (state goes back to `OPEN`): **STOP.** "PR was removed from the merge queue."
If timeout (30 min): **STOP.** "Merge queue has been processing for 30 minutes. Check the queue manually."
If the PR is removed from the queue (state goes back to `OPEN`): **STOP.** "The PR was removed from the merge queue — this usually means a CI check failed on the merge commit, or another PR in the queue caused a conflict. Check the GitHub merge queue page to see what happened."
If timeout (30 min): **STOP.** "The merge queue has been processing for 30 minutes. Something might be stuck — check the GitHub Actions tab and the merge queue page."

Record merge timestamp and duration.
### 4b: CI auto-deploy detection

After the PR is merged, check if a deploy workflow was triggered by the merge:

```bash
gh run list --branch <base> --limit 5 --json name,status,workflowName,headSha
```

Look for runs matching the merge commit SHA. If a deploy workflow is found:
- Tell the user: "PR merged. I can see a deploy workflow ('{workflow-name}') kicked off automatically. I'll monitor it and let you know when it's done."

If no deploy workflow is found after merge:
- Tell the user: "PR merged. I don't see a deploy workflow — your project might deploy a different way, or it might be a library/CLI that doesn't have a deploy step. I'll figure out the right verification in the next step."

If `MERGE_PATH=auto` and the repo uses merge queues AND a deploy workflow exists:
- Tell the user: "PR made it through the merge queue and the deploy workflow is running. Monitoring it now."

Record merge timestamp, duration, and merge path for the deploy report.

---



@@ 348,15 630,45 @@ echo "FRONTEND=$SCOPE_FRONTEND BACKEND=$SCOPE_BACKEND DOCS=$SCOPE_DOCS CONFIG=$S
```bash
gh run list --branch <base> --limit 5 --json name,status,conclusion,headSha,workflowName
```
Look for workflow names containing "deploy", "release", "production", "staging", or "cd". If found: poll the deploy workflow in Step 6, then run canary.
Look for workflow names containing "deploy", "release", "production", or "cd". If found: poll the deploy workflow in Step 6, then run canary.

3. If SCOPE_DOCS is the only scope that's true (no frontend, no backend, no config): skip verification entirely. Output: "PR merged. Documentation-only change — no deploy verification needed." Go to Step 9.
3. If SCOPE_DOCS is the only scope that's true (no frontend, no backend, no config): skip verification entirely. Tell the user: "This was a docs-only change — nothing to deploy or verify. You're all set." Go to Step 9.

4. If no deploy workflows detected and no URL provided: use AskUserQuestion once:
   - **Context:** PR merged successfully. No deploy workflow or production URL detected.
   - **Re-ground:** "PR is merged, but I don't see a deploy workflow or a production URL for this project. If this is a web app, I can verify the deploy if you give me the URL. If it's a library or CLI tool, there's nothing to verify — we're done."
   - **RECOMMENDATION:** Choose B if this is a library/CLI tool. Choose A if this is a web app.
   - A) Provide a production URL to verify
   - B) Skip verification — this project doesn't have a web deploy
   - A) Here's the production URL: {let them type it}
   - B) No deploy needed — this isn't a web app

### 5a: Staging-first option

If staging was detected in Step 1.5c (or from CLAUDE.md deploy config), and the changes
include code (not docs-only), offer the staging-first option:

Use AskUserQuestion:
- **Re-ground:** "I found a staging environment at {staging URL or workflow}. Since this deploy includes code changes, I can verify everything works on staging first — before it hits production. This is the safest path: if something breaks on staging, production is untouched."
- **RECOMMENDATION:** Choose A for maximum safety. Choose B if you're confident.
- A) Deploy to staging first, verify it works, then go to production (Completeness: 10/10)
- B) Skip staging — go straight to production (Completeness: 7/10)
- C) Deploy to staging only — I'll check production later (Completeness: 8/10)

**If A (staging first):** Tell the user: "Deploying to staging first. I'll run the same health checks I'd run on production — if staging looks good, I'll move on to production automatically."

Run Steps 6-7 against the staging target first. Use the staging
URL or staging workflow for deploy verification and canary checks. After staging passes,
tell the user: "Staging is healthy — your changes are working. Now deploying to production." Then run
Steps 6-7 again against the production target.

**If B (skip staging):** Tell the user: "Skipping staging — going straight to production." Proceed with production deployment as normal.

**If C (staging only):** Tell the user: "Deploying to staging only. I'll verify it works and stop there."

Run Steps 6-7 against the staging target. After verification,
print the deploy report (Step 9) with verdict "STAGING VERIFIED — production deploy pending."
Then tell the user: "Staging looks good. When you're ready for production, run `/land-and-deploy` again."
**STOP.** The user can re-run `/land-and-deploy` later for production.

**If no staging detected:** Skip this sub-step entirely. No question asked.

---



@@ 410,23 722,25 @@ If CLAUDE.md has a custom deploy status command in the "Custom deploy hooks" sec

### Common: Timing and failure handling

Record deploy start time. Show progress every 2 minutes: "Deploy in progress... (Xm elapsed)"
Record deploy start time. Show progress every 2 minutes: "Deploy is still running... ({X}m so far). This is normal for most platforms."

If deploy succeeds (`conclusion` is `success` or health check passes): record deploy duration, continue to Step 7.
If deploy succeeds (`conclusion` is `success` or health check passes): Tell the user "Deploy finished successfully. Took {duration}. Now I'll verify the site is healthy." Record deploy duration, continue to Step 7.

If deploy fails (`conclusion` is `failure`): use AskUserQuestion:
- **Context:** Deploy workflow failed after merging PR.
- **Re-ground:** "The deploy workflow failed after the merge. The code is merged but may not be live yet. Here's what I can do:"
- **RECOMMENDATION:** Choose A to investigate before reverting.
- A) Investigate the deploy logs
- B) Create a revert commit on the base branch
- C) Continue anyway — the deploy failure might be unrelated
- A) Let me look at the deploy logs to figure out what went wrong
- B) Revert the merge immediately — roll back to the previous version
- C) Continue to health checks anyway — the deploy failure might be a flaky step, and the site might actually be fine

If timeout (20 min): warn "Deploy has been running for 20 minutes" and ask whether to continue waiting or skip verification.
If timeout (20 min): "The deploy has been running for 20 minutes, which is longer than most deploys take. The site might still be deploying, or something might be stuck." Ask whether to continue waiting or skip verification.

---

## Step 7: Canary verification (conditional depth)

Tell the user: "Deploy is done. Now I'm going to check the live site to make sure everything looks good — loading the page, checking for errors, and measuring performance."

Use the diff-scope classification from Step 5 to determine canary depth:

| Diff Scope | Canary Depth |


@@ 475,14 789,14 @@ Take an annotated screenshot as evidence.
- Page has real content (not blank or error screen) → PASS
- Loads in under 10 seconds → PASS

If all pass: mark as HEALTHY, continue to Step 9.
If all pass: Tell the user "Site is healthy. Page loaded in {X}s, no console errors, content looks good. Screenshot saved to {path}." Mark as HEALTHY, continue to Step 9.

If any fail: show the evidence (screenshot path, console errors, perf numbers). Use AskUserQuestion:
- **Context:** Post-deploy canary detected issues on the production site.
- **Re-ground:** "I found some issues on the live site after the deploy. Here's what I see: {specific issues}. This might be temporary (caches clearing, CDN propagating) or it might be a real problem."
- **RECOMMENDATION:** Choose based on severity — B for critical (site down), A for minor (console errors).
- A) Expected (deploy in progress, cache clearing) — mark as healthy
- B) Broken — create a revert commit
- C) Investigate further (open the site, look at logs)
- A) That's expected — the site is still warming up. Mark it as healthy.
- B) That's broken — revert the merge and roll back to the previous version
- C) Let me investigate more — open the site and look at logs before deciding

---



@@ 490,6 804,8 @@ If any fail: show the evidence (screenshot path, console errors, perf numbers). 

If the user chose to revert at any point:

Tell the user: "Reverting the merge now. This will create a new commit that undoes all the changes from this PR. The previous version of your site will be restored once the revert deploys."

```bash
git fetch origin <base>
git checkout <base>


@@ 497,11 813,12 @@ git revert <merge-commit-sha> --no-edit
git push origin <base>
```

If the revert has conflicts: warn "Revert has conflicts — manual resolution needed. The merge commit SHA is `<sha>`. You can run `git revert <sha>` manually."
If the revert has conflicts: "The revert has merge conflicts — this can happen if other changes landed on {base} after your merge. You'll need to resolve the conflicts manually. The merge commit SHA is `<sha>` — run `git revert <sha>` to try again."

If the base branch has push protections: warn "Branch protections may prevent direct push — create a revert PR instead: `gh pr create --title 'revert: <original PR title>'`"
If the base branch has push protections: "This repo has branch protections, so I can't push the revert directly. I'll create a revert PR instead — merge it to roll back."
Then create a revert PR: `gh pr create --title 'revert: <original PR title>'`

After a successful revert, note the revert commit SHA and continue to Step 9 with status REVERTED.
After a successful revert: Tell the user "Revert pushed to {base}. The deploy should roll back automatically once CI passes. Keep an eye on the site to confirm." Note the revert commit SHA and continue to Step 9 with status REVERTED.

---



@@ 522,23 839,32 @@ PR:           #<number> — <title>
Branch:       <head-branch> → <base-branch>
Merged:       <timestamp> (<merge method>)
Merge SHA:    <sha>
Merge path:   <auto-merge / direct / merge queue>
First run:    <yes (dry-run validated) / no (previously confirmed)>

Timing:
  Dry-run:    <duration or "skipped (confirmed)">
  CI wait:    <duration>
  Queue:      <duration or "direct merge">
  Deploy:     <duration or "no workflow detected">
  Staging:    <duration or "skipped">
  Canary:     <duration or "skipped">
  Total:      <end-to-end duration>

Reviews:
  Eng review: <CURRENT / STALE / NOT RUN>
  Inline fix: <yes (N fixes) / no / skipped>

CI:           <PASSED / SKIPPED>
Deploy:       <PASSED / FAILED / NO WORKFLOW>
Deploy:       <PASSED / FAILED / NO WORKFLOW / CI AUTO-DEPLOY>
Staging:      <VERIFIED / SKIPPED / N/A>
Verification: <HEALTHY / DEGRADED / SKIPPED / REVERTED>
  Scope:      <FRONTEND / BACKEND / CONFIG / DOCS / MIXED>
  Console:    <N errors or "clean">
  Load time:  <Xs>
  Screenshot: <path or "none">

VERDICT: <DEPLOYED AND VERIFIED / DEPLOYED (UNVERIFIED) / REVERTED>
VERDICT: <DEPLOYED AND VERIFIED / DEPLOYED (UNVERIFIED) / STAGING VERIFIED / REVERTED>
```

Save report to `.gstack/deploy-reports/{date}-pr{number}-deploy.md`.


@@ 552,28 878,38 @@ mkdir -p ~/.gstack/projects/$SLUG

Write a JSONL entry with timing data:
```json
{"skill":"land-and-deploy","timestamp":"<ISO>","status":"<SUCCESS/REVERTED>","pr":<number>,"merge_sha":"<sha>","deploy_status":"<HEALTHY/DEGRADED/SKIPPED>","ci_wait_s":<N>,"queue_s":<N>,"deploy_s":<N>,"canary_s":<N>,"total_s":<N>}
{"skill":"land-and-deploy","timestamp":"<ISO>","status":"<SUCCESS/REVERTED>","pr":<number>,"merge_sha":"<sha>","merge_path":"<auto/direct/queue>","first_run":<true/false>,"deploy_status":"<HEALTHY/DEGRADED/SKIPPED>","staging_status":"<VERIFIED/SKIPPED>","review_status":"<CURRENT/STALE/NOT_RUN/INLINE_FIX>","ci_wait_s":<N>,"queue_s":<N>,"deploy_s":<N>,"staging_s":<N>,"canary_s":<N>,"total_s":<N>}
```

---

## Step 10: Suggest follow-ups

After the deploy report, suggest relevant follow-ups:
After the deploy report:

If verdict is DEPLOYED AND VERIFIED: Tell the user "Your changes are live and verified. Nice ship."

If verdict is DEPLOYED (UNVERIFIED): Tell the user "Your changes are merged and should be deploying. I wasn't able to verify the site — check it manually when you get a chance."

If verdict is REVERTED: Tell the user "The merge was reverted. Your changes are no longer on {base}. The PR branch is still available if you need to fix and re-ship."

- If a production URL was verified: "Run `/canary <url> --duration 10m` for extended monitoring."
- If performance data was collected: "Run `/benchmark <url>` for a deep performance audit."
- "Run `/document-release` to update project documentation."
Then suggest relevant follow-ups:
- If a production URL was verified: "Want extended monitoring? Run `/canary <url>` to watch the site for the next 10 minutes."
- If performance data was collected: "Want a deeper performance analysis? Run `/benchmark <url>`."
- "Need to update docs? Run `/document-release` to sync README, CHANGELOG, and other docs with what you just shipped."

---

## Important Rules

- **Never force push.** Use `gh pr merge` which is safe.
- **Never skip CI.** If checks are failing, stop.
- **Auto-detect everything.** PR number, merge method, deploy strategy, project type. Only ask when information genuinely can't be inferred.
- **Never skip CI.** If checks are failing, stop and explain why.
- **Narrate the journey.** The user should always know: what just happened, what's happening now, and what's about to happen next. No silent gaps between steps.
- **Auto-detect everything.** PR number, merge method, deploy strategy, project type, merge queues, staging environments. Only ask when information genuinely can't be inferred.
- **Poll with backoff.** Don't hammer GitHub API. 30-second intervals for CI/deploy, with reasonable timeouts.
- **Revert is always an option.** At every failure point, offer revert as an escape hatch.
- **Revert is always an option.** At every failure point, offer revert as an escape hatch. Explain what reverting does in plain English.
- **Single-pass verification, not continuous monitoring.** `/land-and-deploy` checks once. `/canary` does the extended monitoring loop.
- **Clean up.** Delete the feature branch after merge (via `--delete-branch`).
- **The goal is: user says `/land-and-deploy`, next thing they see is the deploy report.**
- **First run = teacher mode.** Walk the user through everything. Explain what each check does and why it matters. Show them their infrastructure. Let them confirm before proceeding. Build trust through transparency.
- **Subsequent runs = efficient mode.** Brief status updates, no re-explanations. The user already trusts the tool — just do the job and report results.
- **The goal is: first-timers think "wow, this is thorough — I trust it." Repeat users think "that was fast — it just works."**

M scripts/resolvers/utility.ts => scripts/resolvers/utility.ts +2 -1
@@ 73,7 73,8 @@ fi

# Detect deploy workflows
for f in .github/workflows/*.yml .github/workflows/*.yaml; do
  [ -f "$f" ] && grep -qiE "deploy|release|production|staging|cd" "$f" 2>/dev/null && echo "DEPLOY_WORKFLOW:$f"
  [ -f "$f" ] && grep -qiE "deploy|release|production|cd" "$f" 2>/dev/null && echo "DEPLOY_WORKFLOW:$f"
  [ -f "$f" ] && grep -qiE "staging" "$f" 2>/dev/null && echo "STAGING_WORKFLOW:$f"
done
\`\`\`


M test/helpers/touchfiles.ts => test/helpers/touchfiles.ts +8 -4
@@ 134,10 134,12 @@ export const E2E_TOUCHFILES: Record<string, string[]> = {
  'gstack-upgrade-happy-path': ['gstack-upgrade/**'],

  // Deploy skills
  'land-and-deploy-workflow':   ['land-and-deploy/**', 'scripts/gen-skill-docs.ts'],
  'canary-workflow':            ['canary/**', 'browse/src/**'],
  'benchmark-workflow':         ['benchmark/**', 'browse/src/**'],
  'setup-deploy-workflow':      ['setup-deploy/**', 'scripts/gen-skill-docs.ts'],
  'land-and-deploy-workflow':      ['land-and-deploy/**', 'scripts/gen-skill-docs.ts'],
  'land-and-deploy-first-run':     ['land-and-deploy/**', 'scripts/gen-skill-docs.ts', 'bin/gstack-slug'],
  'land-and-deploy-review-gate':   ['land-and-deploy/**', 'bin/gstack-review-read'],
  'canary-workflow':               ['canary/**', 'browse/src/**'],
  'benchmark-workflow':            ['benchmark/**', 'browse/src/**'],
  'setup-deploy-workflow':         ['setup-deploy/**', 'scripts/gen-skill-docs.ts'],

  // Autoplan
  'autoplan-core':  ['autoplan/**', 'plan-ceo-review/**', 'plan-eng-review/**', 'plan-design-review/**'],


@@ 254,6 256,8 @@ export const E2E_TIERS: Record<string, 'gate' | 'periodic'> = {

  // Deploy skills
  'land-and-deploy-workflow': 'gate',
  'land-and-deploy-first-run': 'gate',
  'land-and-deploy-review-gate': 'gate',
  'canary-workflow': 'gate',
  'benchmark-workflow': 'gate',
  'setup-deploy-workflow': 'gate',

M test/skill-e2e-deploy.test.ts => test/skill-e2e-deploy.test.ts +155 -0
@@ 85,6 85,161 @@ Do NOT use AskUserQuestion. Do NOT run gh or fly commands.`,
  }, 180_000);
});

// --- Land-and-Deploy First-Run E2E ---

describeIfSelected('Land-and-Deploy first-run E2E', ['land-and-deploy-first-run'], () => {
  let firstRunDir: string;

  beforeAll(() => {
    firstRunDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-land-first-run-'));
    const run = (cmd: string, args: string[]) =>
      spawnSync(cmd, args, { cwd: firstRunDir, stdio: 'pipe', timeout: 5000 });

    run('git', ['init', '-b', 'main']);
    run('git', ['config', 'user.email', 'test@test.com']);
    run('git', ['config', 'user.name', 'Test']);

    fs.writeFileSync(path.join(firstRunDir, 'app.ts'), 'export function hello() { return "world"; }\n');
    fs.writeFileSync(path.join(firstRunDir, 'fly.toml'), 'app = "first-run-app"\n\n[http_service]\n  internal_port = 3000\n');
    run('git', ['add', '.']);
    run('git', ['commit', '-m', 'initial']);

    run('git', ['checkout', '-b', 'feat/first-deploy']);
    fs.writeFileSync(path.join(firstRunDir, 'app.ts'), 'export function hello() { return "first deploy"; }\n');
    run('git', ['add', '.']);
    run('git', ['commit', '-m', 'feat: first deploy']);

    copyDirSync(path.join(ROOT, 'land-and-deploy'), path.join(firstRunDir, 'land-and-deploy'));
  });

  afterAll(() => {
    try { fs.rmSync(firstRunDir, { recursive: true, force: true }); } catch {}
  });

  testConcurrentIfSelected('land-and-deploy-first-run', async () => {
    const result = await runSkillTest({
      prompt: `Read land-and-deploy/SKILL.md for the /land-and-deploy skill instructions.

You are on branch feat/first-deploy. This is the FIRST TIME running /land-and-deploy
for this project — there is NO land-deploy-confirmed file.

This repo has a fly.toml with app = "first-run-app", indicating a Fly.io deployment.

IMPORTANT: There is NO remote and NO GitHub PR — you cannot run gh commands.
Instead, simulate the Step 1.5 first-run dry-run validation:
1. Detect that this is a FIRST_RUN (no land-deploy-confirmed file)
2. Detect the deploy platform from fly.toml (Fly.io, app = first-run-app)
3. Infer the production URL (https://first-run-app.fly.dev)
4. Build the DEPLOY INFRASTRUCTURE VALIDATION table showing:
   - Platform detected
   - Command validation results (simulated as all passing)
   - Staging detection results (none expected)
   - What will happen steps
5. Write the dry-run report to .gstack/deploy-reports/dry-run-validation.md

Do NOT use AskUserQuestion. Do NOT run gh or fly commands.
Just demonstrate the first-run dry-run output.`,
      workingDirectory: firstRunDir,
      maxTurns: 20,
      allowedTools: ['Bash', 'Read', 'Write', 'Edit', 'Grep', 'Glob'],
      timeout: 120_000,
      testName: 'land-and-deploy-first-run',
      runId,
    });

    logCost('/land-and-deploy first-run', result);
    recordE2E(evalCollector, '/land-and-deploy first-run', 'Land-and-Deploy first-run E2E', result);
    expect(result.exitReason).toBe('success');

    // Verify dry-run report was created
    const reportDir = path.join(firstRunDir, '.gstack', 'deploy-reports');
    expect(fs.existsSync(reportDir)).toBe(true);

    // Check report content mentions platform detection
    const reportFiles = fs.readdirSync(reportDir);
    expect(reportFiles.length).toBeGreaterThan(0);
    const reportContent = fs.readFileSync(path.join(reportDir, reportFiles[0]), 'utf-8');
    const hasPlatform = reportContent.toLowerCase().includes('fly') || reportContent.toLowerCase().includes('first-run-app');
    expect(hasPlatform).toBe(true);
  }, 180_000);
});

// --- Land-and-Deploy Review Gate E2E ---

describeIfSelected('Land-and-Deploy review gate E2E', ['land-and-deploy-review-gate'], () => {
  let reviewDir: string;

  beforeAll(() => {
    reviewDir = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-e2e-land-review-'));
    const run = (cmd: string, args: string[]) =>
      spawnSync(cmd, args, { cwd: reviewDir, stdio: 'pipe', timeout: 5000 });

    run('git', ['init', '-b', 'main']);
    run('git', ['config', 'user.email', 'test@test.com']);
    run('git', ['config', 'user.name', 'Test']);

    fs.writeFileSync(path.join(reviewDir, 'app.ts'), 'export function hello() { return "world"; }\n');
    run('git', ['add', '.']);
    run('git', ['commit', '-m', 'initial']);

    // Create 6 more commits to make any review stale
    for (let i = 1; i <= 6; i++) {
      fs.writeFileSync(path.join(reviewDir, `file${i}.ts`), `export const x${i} = ${i};\n`);
      run('git', ['add', '.']);
      run('git', ['commit', '-m', `feat: add file${i}`]);
    }

    copyDirSync(path.join(ROOT, 'land-and-deploy'), path.join(reviewDir, 'land-and-deploy'));
  });

  afterAll(() => {
    try { fs.rmSync(reviewDir, { recursive: true, force: true }); } catch {}
  });

  testConcurrentIfSelected('land-and-deploy-review-gate', async () => {
    const result = await runSkillTest({
      prompt: `Read land-and-deploy/SKILL.md for the /land-and-deploy skill instructions.

Focus on Step 3.5a and Step 3.5a-bis (the review staleness check and inline review offer).

This repo has 6 commits since the initial commit. There are NO review logs
(gstack-review-read would return NO_REVIEWS).

Simulate what the readiness gate would show:
1. Run gstack-review-read equivalent (simulate NO_REVIEWS output)
2. Determine review staleness: Eng Review should be "NOT RUN"
3. Note that Step 3.5a-bis would offer an inline review
4. Write a simulated readiness report to .gstack/deploy-reports/readiness-report.md
   showing the review status as NOT RUN with the inline review offer text

Do NOT use AskUserQuestion. Do NOT run gh commands.
Show what the readiness gate output would look like.`,
      workingDirectory: reviewDir,
      maxTurns: 15,
      allowedTools: ['Bash', 'Read', 'Write', 'Edit', 'Grep', 'Glob'],
      timeout: 120_000,
      testName: 'land-and-deploy-review-gate',
      runId,
    });

    logCost('/land-and-deploy review-gate', result);
    recordE2E(evalCollector, '/land-and-deploy review-gate', 'Land-and-Deploy review gate E2E', result);
    expect(result.exitReason).toBe('success');

    // Verify readiness report was created
    const reportDir = path.join(reviewDir, '.gstack', 'deploy-reports');
    expect(fs.existsSync(reportDir)).toBe(true);

    const reportFiles = fs.readdirSync(reportDir);
    expect(reportFiles.length).toBeGreaterThan(0);
    const reportContent = fs.readFileSync(path.join(reportDir, reportFiles[0]), 'utf-8');
    // Should mention review status
    const hasReviewMention = reportContent.toLowerCase().includes('review') ||
                              reportContent.toLowerCase().includes('not run');
    expect(hasReviewMention).toBe(true);
  }, 180_000);
});

// --- Canary skill E2E ---

describeIfSelected('Canary skill E2E', ['canary-workflow'], () => {