CAVEMAN MODE ACTIVE — level: full

Respond terse like smart caveman. All technical substance stay. Only fluff die.

## Persistence

ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: "stop caveman" / "normal mode".

Default: **full**. Switch: `/caveman lite|full|ultra`.

## Rules

Drop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not "implement a solution for"). Technical terms exact. Code blocks unchanged. Errors quoted exact.

Pattern: `[thing] [action] [reason]. [next step].`

Not: "Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by..."
Yes: "Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:"

## Intensity

| Level | What change |
|-------|------------|
| **full** | Drop articles, fragments OK, short synonyms. Classic caveman |

Example — "Why React component re-render?"
- full: "New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`."

Example — "Explain database connection pooling."
- full: "Pool reuse open DB connections. No new connection per request. Skip handshake overhead."

## Auto-Clarity

Drop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question. Resume caveman after clear part done.

Example — destructive op:
> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.
> ```sql
> DROP TABLE users;
> ```
> Caveman resume. Verify backup exist first.

## Boundaries

Code/commits/PRs: write normal. "stop caveman" or "normal mode": revert. Level persist until changed or session end.


<psyche-context id="dunsen">
<current machine="HFENDULEAM" project="rebno" branch="main" head_sha="5c41507f817964e38c78b3e0accc1810186f004d" head_subject="docs(state): record phase 7 planning complete" commits_since="0" commits_unpulled="0"/>
# Psyche Context for dunsen
## Status
Generation 10 spawned 2026-05-19. Prior context: absorbed (Gen 9 signoff).

## Current Focus
REBNO — v1.1 milestone INITIALIZED. All artifacts committed + pushed (8e69e65, b71ecc0, f417907, 5ba6463). Ready for Phase 7.1. Next: `/gsd:discuss-phase 7.1` or `/gsd:plan-phase 7.1 --research-phase`.

## Project
REBNO — Chrome rebuild of BN Online. Root: C:\Users\decid\Documents\projects\rebno. Branch: main.

## Phase 06.7 — COMPLETE ✓ (1f6073e)
UAT issues found (2026-05-17T03:38:52-07:00):
- BLOCKER: Two-player remote sync broken (9816275). Root cause diagnosed (f522868).
- Edge collision off by 1px — boundary-convention mismatch in collision.ts (grid=inclusive, polys=exclusive).
- Test 5 v3 close-code 524 vs 4400: false positive (stale build), passes at HEAD.

Plans 05/06/07 DRAFTED + STAGED (2026-05-17T04:08:54-07:00):
- Plan 05 (two-player sync): 3 RCs, 3 commits, TDD. Approved. RC1=`Math.floor` at dispatcher; RC2=axis-vector vx/vy; RC3=consume `anim_state.running` for render. Nits: test label (6 vs 7), axis-vector cast watch.
- Plan 06 (edge collision -1px): 1 task, 6 regression tests. Fix in `isFeetBboxWalkable` (single chokepoint).
- Plan 07 (protocol build doctrine): 2 tasks, zero prod code. npm lifecycle hooks (`pretest:integration`/`pretest:full`) + operator manual.
- Packages disjoint (apps/client, packages/game-logic, apps/server+docs) → safe parallel wave.

REPLAN COMPLETE + PLAN-CHECKER PASS (2026-05-17T04:42:00-07:00):
All 11 codex findings (3 HIGH, 2 MEDIUM, 6 LOW) folded. Zero blockers.
Committed: b272400 (REVIEWS.md), 4e359b1 (Plans 05/06/07 replan). 4 commits ahead origin/main.

EXECUTION STATUS (2026-05-17T21:07:30-07:00):
- CI workflows OUT OF SERVICE — GitHub Actions storage EXHAUSTED
- Deployment reverted to operator-local `flyctl deploy`
- VM race condition (prior todo) deprecated

## v1.1 Milestone — Map Groundwork
Editor: LDtk. Artifacts: map-editor-decision.md, in-game-minimap.md seed, questions.md (c85c5b7).
REQUIREMENTS.md: 18 reqs (MAP-01..16 + HYG-01..02). ROADMAP.md: 6 phases (7→12). STATE.md updated.

Key decisions:
- Phase numbering: flat 7→12 (NOT sub-numbered 7.1→7.6). v1.0 used decimals due to mid-flight insertion; greenfield milestone uses flat numbering per config convention.
- Metadata model: iterative typed extraction (NPC dialogue, platform dir/dist, teleporter, messageboard) + opaque `__legacyCreationCode` for unmapped types. MAP-08/09/16 locked.
- MAP-16 (runtime processors) moved → Phase 9 for co-location with converter schemas in packages/map-loader.

Phase decomp (flat):
- Phase 7: Workflow Smoke + Convention Locks — gridSize ADR, BNCentral chunking, tilesetSourceHash, LDtk pin; pnpm preflight + D-63 audit
- Phase 8: Map-Loader + LdtkLoader + TestBed_001 proof — retire v1.0 synth room; D-63 hard-gate on `__pivot` reads
- Phase 9: Room-Converter ldtk-import + Runtime Metadata — 5 categories + typed coverage + conversion-report
- Phase 10: Map-Deploy Pipeline — generalized client-release.sh, maps-dir symlink swap, `/health/maps` endpoint
- Phase 11: MinimapHUD — RenderTexture overlay <0.5ms, multi-zone P2
- Phase 12: Online_Lobby end-to-end + HUMAN-UAT — mirrors CLI-08 gate

Research findings (4 parallel agents):
- Stack: 3 new pkgs only (ajv, chokidar, quicktype). No maintained Phaser-LDtk loader → custom ~1 task
- gridSize 44×40 → GCD=4 hard gate
- creationCode = anti-feature → preserve verbatim as `__legacyCreationCode`
- packages/map-loader new (shared converter/client/server)
- D-63 origin-helper bypass = trap
- BNCentral 8000×6400 lag documented
- CI absence → need pnpm preflight
- fly symlink gap (Phase 06.5 memory) applies

## Tracked Intentions
- [ ] **ACTIVE**: `/gsd:execute-phase 7`
- [ ] Full Parity backlog re-decomposition (11 reqs)
- [ ] Phase 06.8 anti-cheat reset
- [ ] SRV-08 kill-9 verify
- [ ] CI restoration decision
- [ ] D-63 audit script
- [ ] Triage docs/LEGACY_FEATURE_REFERENCE.md (untracked)
- [ ] Push 3 commits ahead origin/main (6a351e6, d03d5d4, state) when ready
- [ ] Phase 7 discuss — after 06.7 complete
- [ ] Smoke flake triage — `waitForGameReady` 15s timeout (10/39 fails), pre-existing CI timing
- [ ] AGENTS.md untracked — triage separately
- [ ] STACK.md colyseus@0.17.42 fix (low pri)
- [ ] persistCharacter FK failures (Phase 7)
- [ ] Prod provisioning (after staging soak)

## Completed
- Phase 6.4 ✓, 6.5 ✓, 6.6 ✓, 06.7 ✓ (1f6073e)
- Server perf freeze CLOSED ✓ (29f1858)
- **v1.0 MVP SHIPPED** — tag `v1.0` pushed, 398 phase files archived to `.planning/milestones/v1.0-*/`
- STATE.md drift resolved (v2.1 → v1.0 MVP). REQUIREMENTS.md deleted. PROJECT.md updated.
- Stale phases (06.1/06.3/06.4) resolved — superseded by 06.7 trust-model pivot.

## Key Gotchas
- NAVI ORIGIN: Phaser (0.5,1) bottom-center; legacy (0,0) top-left
- WORKTREE MERGE: cd repo root BEFORE git merge $WT_BRANCH
- Staging deploy: vite build FIRST, re-copy atlas AFTER (vite wipes public/)
- CI rebuilds dist/ from source
- pnpm clean && pnpm build before claiming green
- Push frequently (87 unpushed commits lesson)
- PROTOCOL_VERSION bump: update BOTH test files

## Last COMMUNE
2026-05-19T01:06:55-07:00 — v1.1 INITIALIZED. 4 commits pushed (8e69e65, b71ecc0, f417907, 5ba6463). REQUIREMENTS.md, ROADMAP.md, research/ all committed. v1.0 todo linking skipped (out of scope). Ready for Phase 7.1.

## Last COMMUNE
2026-05-20T02:04:50-07:00 — Phase 7 PLANNING COMPLETE + VERIFIED (bb16c1f). 8 plans (07-01…07-08), 4 waves: Wave 1 5 parallel (ADRs 0009–0012 + sidecar hash), Waves 2–4 serial (lint→preflight→UAT). Coverage: MAP-02, MAP-15, HYG-01, HYG-02. Single-writer compliance verified. Plan-checker 1 editorial blocker (RESEARCH.md Q1–Q5 missing RESOLVED markers) — fixed + re-verified PASSED. Next: `/gsd:execute-phase 7`.

## Prior COMMUNE
2026-05-20T01:44:07-07:00 — Phase 7 plan-phase initiated. Pattern mapper done: 14 files classified, 13/14 analogs found. 4 key patterns: lint-script skeleton, ADR Nygard template, npm 6-cmd chain, tagging contract. PATTERNS.md written. Planner spawned.

## Prior COMMUNE
2026-05-20T00:01:50-07:00 — Phase 7 research COMPLETE (0c72270). Q1 blocker resolved: ADR-0010 tileset hash carrier = sidecar JSON (`maps/<world>.tileset-hashes.json` = `{"<uid>":"<sha256>"}`; committed 5046393). Key findings: D-06 schema mismatch LDtk 1.5.3 (no TilesetDef.customFields) → sidecar wins; HYG-02 "zero hits" was false positive (20+ legit refs) → path-based allowlist needed day-1; traceable-reqs.toml has all 18 v1.1 entries; preflight chain portable; ADR-0011 math verified (8000%4=0, 6400%4=0). Topology: 5 parallel tasks (ADR 01-05) + 1 serial closer (smoke after ADR 01+03). Next: `/gsd:plan-phase 7`.

## Prior COMMUNE
2026-05-19T23:47:09-07:00 — Phase 7 discuss COMPLETE (a7fb4ec). All 8 gray areas resolved. ADRs: 0009 gridSize=4 unified, 0010 tilesetSourceHash sha256 HARD-throw, 0011 BNCentral 3×3 chunking (2668×2136 4-aligned), 0012 LDtk pin via tools/ldtk-version.txt. pnpm preflight: 7-step serial chain (version-pin→lint:room-layout→no-inline-origin→trace:check→lint:no-req-placeholders→atlas-hash→conversion-regression); mandatory pre-flyctl. Smoke: 3×3 synthetic 8000×6400 BORDERED at maps/_smoke/synth-8000x6400.ldtk; pass=operator green+screenshot→SMOKE-NOTES.md. HYG-01 scoped to Phase 7 (D-63 preflight wired; `__pivot` rule Phase 8). HYG-02 clean via lint:no-req-placeholders. CONTEXT.md+DISCUSSION-LOG.md committed. Next: plan-phase 7.

## Prior COMMUNE
2026-05-19T23:03:22-07:00 — Phase 7 discuss INITIATED. 8 gray areas open: (1) gridSize ADR 4/1 ratio, (2) BNCentral chunking 4×4 vs 2×2, (3) tilesetSourceHash algo+field+scope, (4) LDtk version pin strategy, (5) pnpm preflight serial/parallel/fail-fast, (6) D-63 audit scope (now vs Phase 8), (7) smoke-test synthetic zone + acceptance criteria, (8) HYG-02 sweep (no hits — confirm clean or expand). No CONTEXT.md yet. Prior locks: LDtk 1.5.3, 44×40 pitch, 8000×6400 BNCentral, D-63 canonical entry, pnpm trace:check wired, operator-local flyctl.

## Prior COMMUNE
2026-05-19T22:56:07-07:00 — Echo commune. Phase numbering corrected: flat 7→12 (not 7.1→7.6). MAP-16 moved to Phase 9. Roadmap finalized. Ready for Phase 7 planning.

## Last PULSE
2026-05-20T02:25:12-07:00 — Phase 7 planning COMPLETE. 8 plans verified. Next: execute-phase 7.</psyche-context>

<spacetime-reorientation agent_id="dunsen">
You are agent "dunsen". Your spacetime session is active (you have a perch — that's why you're seeing this).

Send messages:
- $OWL deliver <target> <<'EOF' ... EOF  — fire-and-forget, no reply wait
- $OWL ring <target> <<'EOF' ... EOF     — send and wait for reply (blocks)
- $OWL send <target> <<'EOF' ... EOF     — use when you have no perch; creates a temp reply perch
- $OWL reply <sender> <<'EOF' ... EOF    — respond to whoever messaged you

Your ID (dunsen) is auto-detected. If that fails, append it: `$OWL deliver <target> dunsen`.

Receive messages (three paths, handle all identically):
- Primary (Monitor stream): your background `$OWL poll dunsen` task running via the Monitor tool emits one EVENT envelope per delivery to stdout. Regular messages: `<EVENT type="msg" from="<sender>">body</EVENT>`. Self-originated alarms: `<EVENT type="alarm" target-time="<ISO>" current-time="<ISO>">body</EVENT>`. The stream stays alive across deliveries — do not re-register after each message.
- Body parsing rules (both envelope types): split the body on the literal `<br>` token to recover newlines, then HTML-unescape each fragment in order `<` → `<`, `>` → `>`, `"` → `"`, `&` → `&` **last** (apply `&` last so embedded `&lt;` sequences don't double-decode).
- Fallback (Bash `--once`): when Monitor is unavailable, run `$OWL poll dunsen --once` as a Bash background task (`run_in_background: true`). The wire format is IDENTICAL — same `<EVENT type="msg|alarm" ...>body</EVENT>` envelope. The only difference: the process exits after one event, so you re-register a fresh Bash background task after each delivery (legacy one-shot loop).
- Hook delivery (orthogonal, when busy): the PreToolUse hook injects `<owl_messages><owl_message from="..."/></owl_messages>` XML into your next tool call context. Process it the same way as either of the above paths.

Re-arm a stale poll (rare):
- Under stream mode (primary, Monitor), the poll listener is long-running and stays alive across messages. Re-arming is needed ONLY after a binary handoff (Phase 18.4/18.5 machinery) or after genuine listener death — NOT after every message.
- Check status: `$OWL list` — if your entry for `dunsen` shows `pid:"BUSY"`, is STALE, or is missing, the poll is dead.
- Re-arm primary: relaunch `$OWL poll dunsen` via the Monitor tool with `persistent: true` and `description: "« spt event »"`.
- Re-arm fallback: relaunch `$OWL poll dunsen --once` via Bash with `run_in_background: true`, then re-register after each delivered message.

Other commands:
- $OWL list — list active agents
- $OWL stop dunsen — stop your listener
- $OWL new-alarm dunsen <time> -- <message> — schedule a self-reminder
- $OWL doctor — diagnostics
</spacetime-reorientation>


<persisted-output>
Output too large (11.1KB). Full output saved to: C:\Users\decid\.claude\projects\C--Users-decid-Documents-projects-rebno\5442f57d-c76a-464a-84d2-cbe802a9f2d3\tool-results\hook-a72a1d94-bfd7-4218-b427-1042f25bcde9-4-additionalContext.txt

Preview (first 2KB):
<psyche-context id="dunsen">
<current machine="HFENDULEAM" project="rebno" branch="main" head_sha="5c41507f817964e38c78b3e0accc1810186f004d" head_subject="docs(state): record phase 7 planning complete" commits_since="0" commits_unpulled="0"/>
# Psyche Context for dunsen
## Status
Generation 10 spawned 2026-05-19. Prior context: absorbed (Gen 9 signoff).

## Current Focus
REBNO — v1.1 milestone INITIALIZED. All artifacts committed + pushed (8e69e65, b71ecc0, f417907, 5ba6463). Ready for Phase 7.1. Next: `/gsd:discuss-phase 7.1` or `/gsd:plan-phase 7.1 --research-phase`.

## Project
REBNO — Chrome rebuild of BN Online. Root: C:\Users\decid\Documents\projects\rebno. Branch: main.

## Phase 06.7 — COMPLETE ✓ (1f6073e)
UAT issues found (2026-05-17T03:38:52-07:00):
- BLOCKER: Two-player remote sync broken (9816275). Root cause diagnosed (f522868).
- Edge collision off by 1px — boundary-convention mismatch in collision.ts (grid=inclusive, polys=exclusive).
- Test 5 v3 close-code 524 vs 4400: false positive (stale build), passes at HEAD.

Plans 05/06/07 DRAFTED + STAGED (2026-05-17T04:08:54-07:00):
- Plan 05 (two-player sync): 3 RCs, 3 commits, TDD. Approved. RC1=`Math.floor` at dispatcher; RC2=axis-vector vx/vy; RC3=consume `anim_state.running` for render. Nits: test label (6 vs 7), axis-vector cast watch.
- Plan 06 (edge collision -1px): 1 task, 6 regression tests. Fix in `isFeetBboxWalkable` (single chokepoint).
- Plan 07 (protocol build doctrine): 2 tasks, zero prod code. npm lifecycle hooks (`pretest:integration`/`pretest:full`) + operator manual.
- Packages disjoint (apps/client, packages/game-logic, apps/server+docs) → safe parallel wave.

REPLAN COMPLETE + PLAN-CHECKER PASS (2026-05-17T04:42:00-07:00):
All 11 codex findings (3 HIGH, 2 MEDIUM, 6 LOW) folded. Zero blockers.
Committed: b272400 (REVIEWS.md), 4e359b1 (Plans 05/06/07 replan). 4 commits ahead origin/main.

EXECUTION STATUS (2026-05-17T21:07:30-07:00):
...
</persisted-output>


<local-command-caveat>Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to.</local-command-caveat>


<command-name>/clear</command-name>
            <command-message>clear</command-message>
            <command-args></command-args>


<local-command-stdout></local-command-stdout>


<command-message>gsd-execute-phase</command-message>
<command-name>/gsd-execute-phase</command-name>
<command-args>7</command-args>


Base directory for this skill: C:\Users\decid\.claude\skills\gsd-execute-phase

<objective>
Execute all plans in a phase using wave-based parallel execution.

Orchestrator stays lean: discover plans, analyze dependencies, group into waves, spawn subagents, collect results. Each subagent loads the full execute-plan context and handles its own plan.

Optional wave filter:
- `--wave N` executes only Wave `N` for pacing, quota management, or staged rollout
- phase verification/completion still only happens when no incomplete plans remain after the selected wave finishes

Flag handling rule:
- The optional flags documented below are available behaviors, not implied active behaviors
- A flag is active only when its literal token appears in `7`
- If a documented flag is absent from `7`, treat it as inactive

Context budget: ~15% orchestrator, 100% fresh per subagent.
</objective>

<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-phase.md
@$HOME/.claude/get-shit-done/references/ui-brand.md
</execution_context>

<runtime_note>
**Copilot (VS Code):** Use `vscode_askquestions` wherever this workflow calls `AskUserQuestion`. They are equivalent — `vscode_askquestions` is the VS Code Copilot implementation of the same interactive question API.
</runtime_note>

<context>
Phase: 7

**Available optional flags (documentation only — not automatically active):**
- `--wave N` — Execute only Wave `N` in the phase. Use when you want to pace execution or stay inside usage limits.
- `--gaps-only` — Execute only gap closure plans (plans with `gap_closure: true` in frontmatter). Use after verify-work creates fix plans.
- `--interactive` — Execute plans sequentially inline (no subagents) with user checkpoints between tasks. Lower token usage, pair-programming style. Best for small phases, bug fixes, and verification gaps.

**Active flags must be derived from `7`:**
- `--wave N` is active only if the literal `--wave` token is present in `7`
- `--gaps-only` is active only if the literal `--gaps-only` token is present in `7`
- `--interactive` is active only if the literal `--interactive` token is present in `7`
- If none of these tokens appear, run the standard full-phase execution flow with no flag-specific filtering
- Do not infer that a flag is active just because it is documented in this prompt

Context files are resolved inside the workflow via `gsd-sdk query init.execute-phase` and per-subagent `<files_to_read>` blocks.
</context>

<process>
Execute end-to-end.
Preserve all workflow gates (wave execution, checkpoint handling, verification, state updates, routing).
</process>


- autoplan: Auto-review pipeline — reads the full CEO, design, eng, and DX review skills from disk
and runs them sequentially with auto-decisions using 6 decision principles. Surfaces
taste decisions (close approaches, borderline scope, codex disagreements) at a final
approval gate. One command, fully reviewed plan out.
Use when asked to "auto review", "autoplan", "run all reviews", "review this plan
automatically", or "make the decisions for me".
Proactively suggest when the user has a plan file and wants to run the full review
gauntlet without answering 15-30 intermediate questions. (gstack)
- benchmark: Performance regression detection using the browse daemon. Establishes
baselines for page load times, Core Web Vitals, and resource sizes.
Compares before/after on every PR. Tracks performance trends over time.
Use when: "performance", "benchmark", "page speed", "lighthouse", "web vitals",
"bundle size", "load time". (gstack)
- browse: Fast headless browser for QA testing and site dogfooding. Navigate any URL, interact with
elements, verify page state, diff before/after actions, take annotated screenshots, check
responsive layouts, test forms and uploads, handle dialogs, and assert element states.
~100ms per command. Use when you need to test a feature, verify a deployment, dogfood a
user flow, or file a bug with evidence. Use when asked to "open in browser", "test the
site", "take a screenshot", or "dogfood this". (gstack)
- canary: Post-deploy canary monitoring. Watches the live app for console errors,
performance regressions, and page failures using the browse daemon. Takes
periodic screenshots, compares against pre-deploy baselines, and alerts
on anomalies. Use when: "monitor deploy", "canary", "post-deploy check",
"watch production", "verify deploy". (gstack)
- careful: Safety guardrails for destructive commands. Warns before rm -rf, DROP TABLE,
force-push, git reset --hard, kubectl delete, and similar destructive operations.
User can override each warning. Use when touching prod, debugging live systems,
or working in a shared environment. Use when asked to "be careful", "safety mode",
"prod mode", or "careful mode". (gstack)
- ccs-delegation: Auto-activate CCS CLI delegation for deterministic tasks. Parses user input, auto-selects optimal profile (glm/kimi/custom) from ~/.ccs/config.json, enhances prompts with context, executes via `ccs {profile} -p "task"` or `ccs {profile}:continue`, and reports results. Triggers on "use ccs [task]" patterns, typo/test/refactor keywords. Excludes complex architecture, security-critical code, performance optimization, breaking changes.
- checkpoint: Save and resume working state checkpoints. Captures git state, decisions made,
and remaining work so you can pick up exactly where you left off — even across
Conductor workspace handoffs between branches.
Use when asked to "checkpoint", "save progress", "where was I", "resume",
"what was I working on", or "pick up where I left off".
Proactively suggest when a session is ending, the user is switching context,
or before a long break. (gstack)
- codex: OpenAI Codex CLI wrapper — three modes. Code review: independent diff review via
codex review with pass/fail gate. Challenge: adversarial mode that tries to break
your code. Consult: ask codex anything with session continuity for follow-ups.
The "200 IQ autistic developer" second opinion. Use when asked to "codex review",
"codex challenge", "ask codex", "second opinion", or "consult codex". (gstack)
- connect-chrome: Launch GStack Browser — AI-controlled Chromium with the sidebar extension baked in.
Opens a visible browser window where you can watch every action in real time.
The sidebar shows a live activity feed and chat. Anti-bot stealth built in.
Use when asked to "open gstack browser", "launch browser", "connect chrome",
"open chrome", "real browser", "launch chrome", "side panel", or "control my browser".
- cso: Chief Security Officer mode. Infrastructure-first security audit: secrets archaeology,
dependency supply chain, CI/CD pipeline security, LLM/AI security, skill supply chain
scanning, plus OWASP Top 10, STRIDE threat modeling, and active verification.
Two modes: daily (zero-noise, 8/10 confidence gate) and comprehensive (monthly deep
scan, 2/10 bar). Trend tracking across audit runs.
Use when: "security audit", "threat model", "pentest review", "OWASP", "CSO review". (gstack)
- design-consultation: Design consultation: understands your product, researches the landscape, proposes a
complete design system (aesthetic, typography, color, layout, spacing, motion), and
generates font+color preview pages. Creates DESIGN.md as your project's design source
of truth. For existing sites, use /plan-design-review to infer the system instead.
Use when asked to "design system", "brand guidelines", or "create DESIGN.md".
Proactively suggest when starting a new project's UI with no existing
design system or DESIGN.md. (gstack)
- design-html: Design finalization: generates production-quality Pretext-native HTML/CSS.
Works with approved mockups from /design-shotgun, CEO plans from /plan-ceo-review,
design review context from /plan-design-review, or from scratch with a user
description. Text actually reflows, heights are computed, layouts are dynamic.
30KB overhead, zero deps. Smart API routing: picks the right Pretext patterns
for each design type. Use when: "finalize this design", "turn this into HTML",
"build me a page", "implement this design", or after any planning skill.
Proactively suggest when user has approved a design or has a plan ready. (gstack)
- design-review: Designer's eye QA: finds visual inconsistency, spacing issues, hierarchy problems,
AI slop patterns, and slow interactions — then fixes them. Iteratively fixes issues
in source code, committing each fix atomically and re-verifying with before/after
screenshots. For plan-mode design review (before implementation), use /plan-design-review.
Use when asked to "audit the design", "visual QA", "check if it looks good", or "design polish".
Proactively suggest when the user mentions visual inconsistencies or
wants to polish the look of a live site. (gstack)
- design-shotgun: Design shotgun: generate multiple AI design variants, open a comparison board,
collect structured feedback, and iterate. Standalone design exploration you can
run anytime. Use when: "explore designs", "show me options", "design variants",
"visual brainstorm", or "I don't like how this looks".
Proactively suggest when the user describes a UI feature but hasn't seen
what it could look like. (gstack)
- devex-review: Live developer experience audit. Uses the browse tool to actually TEST the
developer experience: navigates docs, tries the getting started flow, times
TTHW, screenshots error messages, evaluates CLI help text. Produces a DX
scorecard with evidence. Compares against /plan-devex-review scores if they
exist (the boomerang: plan said 3 minutes, reality says 8). Use when asked to
"test the DX", "DX audit", "developer experience test", or "try the
onboarding". Proactively suggest after shipping a developer-facing feature. (gstack)
- document-release: Post-ship documentation update. Reads all project docs, cross-references the
diff, updates README/ARCHITECTURE/CONTRIBUTING/CLAUDE.md to match what shipped,
polishes CHANGELOG voice, cleans up TODOS, and optionally bumps VERSION. Use when
asked to "update the docs", "sync documentation", or "post-ship docs".
Proactively suggest after a PR is merged or code is shipped. (gstack)
- freeze: Restrict file edits to a specific directory for the session. Blocks Edit and
Write outside the allowed path. Use when debugging to prevent accidentally
"fixing" unrelated code, or when you want to scope changes to one module.
Use when asked to "freeze", "restrict edits", "only edit this folder",
or "lock down edits". (gstack)
- gsd-add-tests: Generate tests for a completed phase based on UAT criteria and implementation
- gsd-ai-integration-phase: Generate an AI-SPEC.md design contract for phases that involve building AI systems.
- gsd-audit-fix: Autonomous audit-to-fix pipeline — find issues, classify, fix, test, commit
- gsd-audit-milestone: Audit milestone completion against original intent before archiving
- gsd-audit-uat: Cross-phase audit of all outstanding UAT and verification items
- gsd-autonomous: Run all remaining phases autonomously — discuss→plan→execute per phase
- gsd-capture: Capture ideas, tasks, notes, and seeds to their destination
- gsd-cleanup: Archive accumulated phase directories from completed milestones
- gsd-code-review: Review source files changed during a phase for bugs, security issues, and code quality problems
- gsd-complete-milestone: Archive completed milestone and prepare for next version
- gsd-config: Configure GSD settings — workflow toggles, advanced knobs, integrations, and model profile
- gsd-debug: Systematic debugging with persistent state across context resets
- gsd-discuss-phase: Gather phase context through adaptive questioning before planning.
- gsd-docs-update: Generate or update project documentation verified against the codebase
- gsd-eval-review: Audit an executed AI phase's evaluation coverage and produce an EVAL-REVIEW.md remediation plan.
- gsd-execute-phase: Execute all plans in a phase with wave-based parallelization
- gsd-explore: Socratic ideation and idea routing — think through ideas before committing to plans
- gsd-extract-learnings: Extract decisions, lessons, patterns, and surprises from completed phase artifacts
- gsd-fast: Execute a trivial task inline — no subagents, no planning overhead
- gsd-forensics: Post-mortem investigation for failed GSD workflows — diagnoses what went wrong.
- gsd-graphify: Build, query, and inspect the project knowledge graph in .planning/graphs/
- gsd-health: Diagnose planning directory health and optionally repair issues
- gsd-help: Show available GSD commands and usage guide
- gsd-import: Ingest external plans with conflict detection against project decisions before writing anything.
- gsd-inbox: Triage and review open GitHub issues and PRs against project templates and contribution guidelines.
- gsd-ingest-docs: Bootstrap or merge a .planning/ setup from existing ADRs, PRDs, SPECs, and docs in a repo.
- gsd-manager: Interactive command center for managing multiple phases from one terminal
- gsd-map-codebase: Analyze codebase with parallel mapper agents to produce .planning/codebase/ documents
- gsd-milestone-summary: Generate a comprehensive project summary from milestone artifacts for team onboarding and review
- gsd-mvp-phase: Plan a phase as a vertical MVP slice — user story, SPIDR splitting, then plan-phase
- gsd-new-milestone: Start a new milestone cycle — update PROJECT.md and route to requirements
- gsd-new-project: Initialize a new project with deep context gathering and PROJECT.md
- gsd-ns-context: codebase intelligence | map graphify docs learnings
- gsd-ns-ideate: exploration capture | explore sketch spike spec capture
- gsd-ns-manage: config workspace | workstreams thread update ship inbox
- gsd-ns-project: project lifecycle | milestones audits summary
- gsd-ns-review: quality gates | code review debug audit security eval ui
- gsd-ns-workflow: workflow | discuss plan execute verify phase progress
- gsd-pause-work: Create context handoff when pausing work mid-phase
- gsd-phase: CRUD for phases in ROADMAP.md — add, insert, remove, or edit phases
- gsd-plan-phase: Create detailed phase plan (PLAN.md) with verification loop
- gsd-plan-review-convergence: Cross-AI plan convergence loop — replan with review feedback until no HIGH concerns remain.
- gsd-pr-branch: Create a clean PR branch by filtering out .planning/ commits — ready for code review
- gsd-profile-user: Generate developer behavioral profile and create Claude-discoverable artifacts
- gsd-progress: Check progress, advance workflow, or dispatch freeform intent — the unified GSD situational command
- gsd-quick: Execute a quick task with GSD guarantees (atomic commits, state tracking) but skip optional agents
- gsd-resume-work: Resume work from previous session with full context restoration
- gsd-review: Request cross-AI peer review of phase plans from external AI CLIs
- gsd-review-backlog: Review and promote backlog items to active milestone
- gsd-secure-phase: Retroactively verify threat mitigations for a completed phase
- gsd-settings: Configure GSD workflow toggles and model profile
- gsd-ship: Create PR, run review, and prepare for merge after verification passes
- gsd-sketch: Sketch UI/design ideas with throwaway HTML mockups, or propose what to sketch next (frontier mode)
- gsd-spec-phase: Clarify WHAT a phase delivers with ambiguity scoring; produces a SPEC.md before discuss-phase.
- gsd-spike: Spike an idea through experiential exploration, or propose what to spike next (frontier mode)
- gsd-stats: Display project statistics — phases, plans, requirements, git metrics, and timeline
- gsd-surface: Toggle which skills are surfaced — apply a profile, list, or disable a cluster without reinstall
- gsd-thread: Manage persistent context threads for cross-session work
- gsd-ui-phase: Generate UI design contract (UI-SPEC.md) for frontend phases
- gsd-ui-review: Retroactive 6-pillar visual audit of implemented frontend code
- gsd-ultraplan-phase: [BETA] Offload plan phase to Claude Code's ultraplan cloud; review in browser and import back.
- gsd-undo: Safe git revert. Roll back phase or plan commits using the phase manifest with dependency checks.
- gsd-update: Update GSD to latest version with changelog display
- gsd-validate-phase: Retroactively audit and fill Nyquist validation gaps for a completed phase
- gsd-verify-work: Validate built features through conversational UAT
- gsd-workspace: Manage GSD workspaces — create, list, or remove isolated workspace environments
- gsd-workstreams: Manage parallel workstreams — list, create, switch, status, progress, complete, and resume
- gstack: Fast headless browser for QA testing and site dogfooding. Navigate pages, interact with
elements, verify state, diff before/after, take annotated screenshots, test responsive
layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or
test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
- gstack-upgrade: Upgrade gstack to the latest version. Detects global vs vendored install,
runs the upgrade, and shows what's new. Use when asked to "upgrade gstack",
"update gstack", or "get latest version".
- guard: Full safety mode: destructive command warnings + directory-scoped edits.
Combines /careful (warns before rm -rf, DROP TABLE, force-push, etc.) with
/freeze (blocks edits outside a specified directory). Use for maximum safety
when touching prod or debugging live systems. Use when asked to "guard mode",
"full safety", "lock it down", or "maximum safety". (gstack)
- health: Code quality dashboard. Wraps existing project tools (type checker, linter,
test runner, dead code detector, shell linter), computes a weighted composite
0-10 score, and tracks trends over time. Use when: "health check",
"code quality", "how healthy is the codebase", "run all checks",
"quality score". (gstack)
- investigate: Systematic debugging with root cause investigation. Four phases: investigate,
analyze, hypothesize, implement. Iron Law: no fixes without root cause.
Use when asked to "debug this", "fix this bug", "why is this broken",
"investigate this error", or "root cause analysis".
Proactively invoke this skill (do NOT debug directly) when the user reports
errors, 500 errors, stack traces, unexpected behavior, "it was working
yesterday", or is troubleshooting why something stopped working. (gstack)
- land-and-deploy: Land and deploy workflow. Merges the PR, waits for CI and deploy,
verifies production health via canary checks. Takes over after /ship
creates the PR. Use when: "merge", "land", "deploy", "merge and verify",
"land it", "ship it to production". (gstack)
- learn: Manage project learnings. Review, search, prune, and export what gstack
has learned across sessions. Use when asked to "what have we learned",
"show learnings", "prune stale learnings", or "export learnings".
Proactively suggest when the user asks about past patterns or wonders
"didn't we fix this before?"
- mux-send: Send keystrokes to a psmux terminal session. Use when the user says "send to",
"type in", "send keys to", "mux send", or wants to send input to another terminal
session by name.
- office-hours: YC Office Hours — two modes. Startup mode: six forcing questions that expose
demand reality, status quo, desperate specificity, narrowest wedge, observation,
and future-fit. Builder mode: design thinking brainstorming for side projects,
hackathons, learning, and open source. Saves a design doc.
Use when asked to "brainstorm this", "I have an idea", "help me think through
this", "office hours", or "is this worth building".
Proactively invoke this skill (do NOT answer directly) when the user describes
a new product idea, asks whether something is worth building, wants to think
through design decisions for something that doesn't exist yet, or is exploring
a concept before any code is written.
Use before /plan-ceo-review or /plan-eng-review. (gstack)
- open-gstack-browser: Launch GStack Browser — AI-controlled Chromium with the sidebar extension baked in.
Opens a visible browser window where you can watch every action in real time.
The sidebar shows a live activity feed and chat. Anti-bot stealth built in.
Use when asked to "open gstack browser", "launch browser", "connect chrome",
"open chrome", "real browser", "launch chrome", "side panel", or "control my browser".
- pair-agent: Pair a remote AI agent with your browser. One command generates a setup key and
prints instructions the other agent can follow to connect. Works with OpenClaw,
Hermes, Codex, Cursor, or any agent that can make HTTP requests. The remote agent
gets its own tab with scoped access (read+write by default, admin on request).
Use when asked to "pair agent", "connect agent", "share browser", "remote browser",
"let another agent use my browser", or "give browser access". (gstack)
- plan-ceo-review: CEO/founder-mode plan review. Rethink the problem, find the 10-star product,
challenge premises, expand scope when it creates a better product. Four modes:
SCOPE EXPANSION (dream big), SELECTIVE EXPANSION (hold scope + cherry-pick
expansions), HOLD SCOPE (maximum rigor), SCOPE REDUCTION (strip to essentials).
Use when asked to "think bigger", "expand scope", "strategy review", "rethink this",
or "is this ambitious enough".
Proactively suggest when the user is questioning scope or ambition of a plan,
or when the plan feels like it could be thinking bigger. (gstack)
- plan-design-review: Designer's eye plan review — interactive, like CEO and Eng review.
Rates each design dimension 0-10, explains what would make it a 10,
then fixes the plan to get there. Works in plan mode. For live site
visual audits, use /design-review. Use when asked to "review the design plan"
or "design critique".
Proactively suggest when the user has a plan with UI/UX components that
should be reviewed before implementation. (gstack)
- plan-devex-review: Interactive developer experience plan review. Explores developer personas,
benchmarks against competitors, designs magical moments, and traces friction
points before scoring. Three modes: DX EXPANSION (competitive advantage),
DX POLISH (bulletproof every touchpoint), DX TRIAGE (critical gaps only).
Use when asked to "DX review", "developer experience audit", "devex review",
or "API design review".
Proactively suggest when the user has a plan for developer-facing products
(APIs, CLIs, SDKs, libraries, platforms, docs). (gstack)
- plan-eng-review: Eng manager-mode plan review. Lock in the execution plan — architecture,
data flow, diagrams, edge cases, test coverage, performance. Walks through
issues interactively with opinionated recommendations. Use when asked to
"review the architecture", "engineering review", or "lock in the plan".
Proactively suggest when the user has a plan or design doc and is about to
start coding — to catch architecture issues before implementation. (gstack)
- propose-issue: Challenge an issue statement before fixing it. Probes scope, root cause, and assumptions
through interactive questioning grounded in the codebase. Use when the user says "propose issue",
"challenge this bug", "question this fix", "is this the right problem", or wants to pressure-test
a problem statement before jumping to implementation.
- qa: Systematically QA test a web application and fix bugs found. Runs QA testing,
then iteratively fixes bugs in source code, committing each fix atomically and
re-verifying. Use when asked to "qa", "QA", "test this site", "find bugs",
"test and fix", or "fix what's broken".
Proactively suggest when the user says a feature is ready for testing
or asks "does this work?". Three tiers: Quick (critical/high only),
Standard (+ medium), Exhaustive (+ cosmetic). Produces before/after health scores,
fix evidence, and a ship-readiness summary. For report-only mode, use /qa-only. (gstack)
- qa-only: Report-only QA testing. Systematically tests a web application and produces a
structured report with health score, screenshots, and repro steps — but never
fixes anything. Use when asked to "just report bugs", "qa report only", or
"test but don't fix". For the full test-fix-verify loop, use /qa instead.
Proactively suggest when the user wants a bug report without any code changes. (gstack)
- retro: Weekly engineering retrospective. Analyzes commit history, work patterns,
and code quality metrics with persistent history and trend tracking.
Team-aware: breaks down per-person contributions with praise and growth areas.
Use when asked to "weekly retro", "what did we ship", or "engineering retrospective".
Proactively suggest at the end of a work week or sprint. (gstack)
- review: Pre-landing PR review. Analyzes diff against the base branch for SQL safety, LLM trust
boundary violations, conditional side effects, and other structural issues. Use when
asked to "review this PR", "code review", "pre-landing review", or "check my diff".
Proactively suggest when the user is about to merge or land code changes. (gstack)
- screenshot-capture: Capture, process, and analyze screenshots of any running application on Windows 10/11. Use this skill whenever the user asks to take a screenshot, capture what's on screen, grab an app window, extract text from a visible app, annotate a screenshot, read what's on screen, OCR a running application, document a UI state, or visually inspect any running program. Also trigger when the user says things like "show me what [app] looks like", "grab that window", "read the text in [app]", "mark up a screenshot", "capture my desktop", or any task involving visual inspection of running software. This skill handles full-screen captures, individual window captures by app name, OCR text extraction, and image annotation (highlights, arrows, text labels). Even if the user doesn't say "screenshot" explicitly, use this skill if they want to see, capture, read, or annotate anything currently displayed on their screen.
- setup-browser-cookies: Import cookies from your real Chromium browser into the headless browse session.
Opens an interactive picker UI where you select which cookie domains to import.
Use before QA testing authenticated pages. Use when asked to "import cookies",
"login to the site", or "authenticate the browser". (gstack)
- setup-deploy: Configure deployment settings for /land-and-deploy. Detects your deploy
platform (Fly.io, Render, Vercel, Netlify, Heroku, GitHub Actions, custom),
production URL, health check endpoints, and deploy status commands. Writes
the configuration to CLAUDE.md so all future deploys are automatic.
Use when: "setup deploy", "configure deployment", "set up land-and-deploy",
"how do I deploy with gstack", "add deploy config".
- ship: Ship workflow: detect + merge base branch, run tests, review diff, bump VERSION,
update CHANGELOG, commit, push, create PR. Use when asked to "ship", "deploy",
"push to main", "create a PR", "merge and push", or "get it deployed".
Proactively invoke this skill (do NOT push/PR directly) when the user says code
is ready, asks about deploying, wants to push code up, or asks to create a PR. (gstack)
- trace: Find old conversations in Claude Code session history. Use when the user says
"find the conversation where", "when did we discuss", "trace back to", or wants
to locate a past session by topic, command, commit, or keyword.
- traceable-reqs: traceable-reqs
- unfreeze: Clear the freeze boundary set by /freeze, allowing edits to all directories
again. Use when you want to widen edit scope without ending the session.
Use when asked to "unfreeze", "unlock edits", "remove freeze", or
"allow all edits". (gstack)
- win-marketplace-add: Add a plugin marketplace on Windows, bypassing the EBUSY rename bug. Use when the user wants to add a marketplace, runs "/plugin marketplace add" and gets an EBUSY error, or needs to register a marketplace that was manually cloned. Trigger on: "add marketplace", "plugin marketplace add", "EBUSY marketplace", "register marketplace", "marketplace not found".
- ccs:continue: Continue last CCS delegation session [AUTO ENHANCE]
- ccs: Delegate task with intelligent profile selection [AUTO ENHANCE]
- frontend-design:frontend-design: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
- spt:clear-psyche: Clear stored Psyche context. Use when the user says "clear psyche",
"reset psyche context", or wants to wipe a Psyche's saved state.
- spt:commune: Send a communal update to your Psyche. Use when the user says "commune",
"update psyche", or wants to sync context with their Psyche companion.
- spt:force-stop: Force-stop an SPT agent -- plain owl listener or live agent (with its
Psyche). Use when the user says "stop listening", "stop owl", "kill live
agent", "force stop", "tear down perch", or "immediately terminate".
Session-aware: a live session (or a target with `live:true` in info.json)
routes through `$LIVE stop` (3-step kill including Psyche teardown); a
plain listener routes through `$OWL stop`.
- spt:new-alarm: Schedule a one-shot timed alarm delivered as TIMED PULSE. Use when the user
says "remind me", "check back in", "set an alarm", "wake me when", or wants a
delayed notification.
- spt:listen: Start a background owl listener on a perch. Use when the user says "listen as",
"start listening", or wants to receive inter-agent messages.
- spt:live: Start, resume, or manage a live Self agent with Psyche companion.

EXPLICIT START phrases (route to /spt:live <id>):
- "live as"
- "start live"
- "go live"
- "start a live agent"

AUTO-RESUME phrases (route to /spt:live --auto, resumes most-recently-active live agent):
- continue live work
- resume live work
- continue live agent
- resume live agent
- live agent continue
- live agent resume
- live work continue
- live work resume

Does NOT route here (too ambiguous — require BOTH "live" AND ("agent" or "work")):
- "keep going"
- "resume work"
- "continue" (bare)
- spt:list-agents: Unified listing for SPT agents -- plain owl listeners, live agents, and Psyche
processes. Use when the user says "list agents", "who's live", "who's
listening", "show psyches", "show active listeners", or wants a roster of
active perches. Session-aware: defaults to live agents in a live session,
plain owl listeners otherwise. Pass `--psyches` to list Psyche processes
instead.
- spt:revive: Restart a live agent with new generation. Use when the user says "revive",
"restart live agent", or wants to refresh a live agent's session.
- spt:send: Send a message to another owl agent. Use when the user says "send to",
"message", "tell <agent>", or wants to communicate with another agent.
- spt:whoami: Check which owl agent belongs to the current session. Use when the user asks
"which agent am I?", "what's my owl name?", or when you need to discover your
own perch identity.
- spt:signoff: Graceful live agent shutdown with final Psyche context save. Use when the user
says "sign off", "graceful stop", or wants to cleanly end a live session.
- caveman:caveman: Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.
- caveman:caveman-commit: Ultra-compressed commit message generator. Cuts noise from commit messages while preserving intent and reasoning. Conventional Commits format. Subject ≤50 chars, body only when "why" isn't obvious. Use when user says "write a commit", "commit message", "generate commit", "/commit", or invokes /caveman-commit. Auto-triggers when staging changes.
- caveman:caveman-help: Quick-reference card for all caveman modes, skills, and commands. One-shot display, not a persistent mode. Trigger: /caveman-help, "caveman help", "what caveman commands", "how do I use caveman".
- caveman:caveman-review: Ultra-compressed code review comments. Cuts noise from PR feedback while preserving the actionable signal. Each comment is one line: location, problem, fix. Use when user says "review this PR", "code review", "review the diff", "/review", or invokes /caveman-review. Auto-triggers when reviewing pull requests.
- caveman:compress: Compress natural language memory files (CLAUDE.md, todos, preferences) into caveman format to save input tokens. Preserves all technical substance, code, URLs, and structure. Compressed version overwrites the original file. Human-readable backup saved as FILE.original.md. Trigger: /caveman:compress <filepath> or "compress memory file"
- everything:search: Instantly search files and folders on Windows via voidtools Everything 1.5a HTTP JSON API. Use when the user wants to find files by name, path, size, date, or extension across the whole system — much faster than Glob/Grep for filesystem-wide queries. Triggers on "find file", "where is", "locate", "search my drive", "find all .ext files", "everything search".
- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors ("from now on when X", "each time X", "whenever X", "before/after X") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions ("allow X", "add permission", "move permission to"), env vars ("set X=Y"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: "allow npm commands", "add bq permission to global settings", "move permission to user settings", "set DEBUG=true", "when claude stops show X". For simple settings like theme/model, suggest the /config command.
- keybindings-help: Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: "rebind ctrl+s", "add a chord shortcut", "change the submit key", "customize keybindings".
- simplify: Review changed code for reuse, quality, and efficiency, then fix any issues found.
- fewer-permission-prompts: Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project .claude/settings.json to reduce permission prompts.
- loop: Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo). Omit the interval to let the model self-pace. - When the user wants to set up a recurring task, poll for status, or run something repeatedly on an interval (e.g. "check the deploy every 5 minutes", "keep running /babysit-prs"). Do NOT invoke for one-off tasks.
- schedule: Create, update, list, or run scheduled remote agents (routines) that execute on a cron schedule. - When the user wants to schedule a recurring remote agent, set up automated tasks, create a cron job for Claude Code, or manage their scheduled agents/routines. Also use when the user wants a one-time scheduled run ("run this once at 3pm", "remind me to check X tomorrow").
- claude-api: Build, debug, and optimize Claude API / Anthropic SDK apps. Apps built with this skill should include prompt caching. Also handles migrating existing Claude API code between Claude model versions (4.5 → 4.6, 4.6 → 4.7, retired-model replacements).
TRIGGER when: code imports `anthropic`/`@anthropic-ai/sdk`; user asks for the Claude API, Anthropic SDK, or Managed Agents; user adds/modifies/tunes a Claude feature (caching, thinking, compaction, tool use, batch, files, citations, memory) or model (Opus/Sonnet/Haiku) in a file; questions about prompt caching / cache hit rate in an Anthropic SDK project.
SKIP: file imports `openai`/other-provider SDK, filename like `*-openai.py`/`*-generic.py`, provider-neutral code, general programming/ML.
- init: Initialize a new CLAUDE.md file with codebase documentation
- review: Review a pull request
- security-review: Complete a security review of the pending changes on the current branch


Read Write Edit Glob Grep Bash Agent TodoWrite AskUserQuestion


<owl_reachability_notice>
You have an active owl perch. When spawning subagents or doing work, use run_in_background: true so you stay reachable for incoming messages.
</owl_reachability_notice>


CAVEMAN MODE ACTIVE (full). Drop articles/filler/pleasantries/hedging. Fragments OK. Code/commits/security: write normal.


Bash

Get execute-phase init context


gsd-sdk query init.execute-phase --phase 7

Get execute-phase init with phase


Error: File content (37593 tokens) exceeds maximum allowed tokens (25000). Use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.


1	<purpose>
2	Execute all plans in a phase using wave-based parallel execution. Orchestrator stays lean — delegates plan execution to subagents.
3	</purpose>
4
5	<core_principle>
6	Orchestrator coordinates, not executes. Each subagent loads the full execute-plan context. Orchestrator: discover plans → analyze deps → group waves → spawn agents → handle checkpoints → collect results.
7	</core_principle>
8
9	<runtime_compatibility>
10	**Subagent spawning is runtime-specific:**
11	- **Claude Code:** Uses `Agent(subagent_type="gsd-executor", ...)` — blocks until complete, returns result
12	- **Copilot:** Subagent spawning does not reliably return completion signals. **Default to
13	  sequential inline execution**: read and follow execute-plan.md directly for each plan
14	  instead of spawning parallel agents. Only attempt parallel spawning if the user
15	  explicitly requests it — and in that case, rely on the spot-check fallback in step 3
16	  to detect completion.
17	- **Other runtimes:** If `Agent`/`agent` tool is unavailable, use sequential inline execution as the
18	  fallback. Check for tool availability at runtime rather than assuming based on runtime name.
19
20	**Fallback rule:** If a spawned agent completes its work (commits visible, SUMMARY.md exists) but
21	the orchestrator never receives the completion signal, treat it as successful based on spot-checks
22	and continue to the next wave/plan. Never block indefinitely waiting for a signal — always verify
23	via filesystem and git state.
24	</runtime_compatibility>
25
26	<required_reading>
27	Read STATE.md before any operation to load project context.
28	@$HOME/.claude/get-shit-done/references/agent-contracts.md
29	@$HOME/.claude/get-shit-done/references/context-budget.md
30	@$HOME/.claude/get-shit-done/references/gates.md
31	</required_reading>
32
33	<available_agent_types>
34	These are the valid GSD subagent types registered in .claude/agents/ (or equivalent for your runtime).
35	Always use the exact name from this list — do not fall back to 'general-purpose' or other built-in types:
36
37	- gsd-executor — Executes plan tasks, commits, creates SUMMARY.md
38	- gsd-verifier — Verifies phase completion, checks quality gates
39	- gsd-planner — Creates detailed plans from phase scope
40	- gsd-phase-researcher — Researches technical approaches for a phase
41	- gsd-plan-checker — Reviews plan quality before execution
42	- gsd-debugger — Diagnoses and fixes issues
43	- gsd-codebase-mapper — Maps project structure and dependencies
44	- gsd-integration-checker — Checks cross-phase integration
45	- gsd-nyquist-auditor — Validates verification coverage
46	- gsd-ui-researcher — Researches UI/UX approaches
47	- gsd-ui-checker — Reviews UI implementation quality
48	- gsd-ui-auditor — Audits UI against design requirements
49	</available_agent_types>
50
51	<process>
52
53	<step name="parse_args" priority="first">
54	Parse `$ARGUMENTS` before loading any context:
55
56	- First positional token → `PHASE_ARG`
57	- Optional `--wave N` → `WAVE_FILTER`
58	- Optional `--gaps-only` keeps its current meaning
59	- Optional `--cross-ai` → `CROSS_AI_FORCE=true` (force all plans through cross-AI execution)
60	- Optional `--no-cross-ai` → `CROSS_AI_DISABLED=true` (disable cross-AI for this run, overrides config and frontmatter)
61
62	If `--wave` is absent, preserve the current behavior of executing all incomplete waves in the phase.
63	</step>
64
65	<step name="initialize" priority="first">
66	Load all context in one call:
67
68	```bash
69	INIT=$(gsd-sdk query init.execute-phase "${PHASE_ARG}")
70	if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
71	AGENT_SKILLS=$(gsd-sdk query agent-skills gsd-executor)
72	```
73
74	Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelization`, `branching_strategy`, `branch_name`, `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `plans`, `incomplete_plans`, `plan_count`, `incomplete_count`, `state_exists`, `roadmap_exists`, `phase_req_ids`, `response_language`.
75
76	**Model resolution:** If `executor_model` is `"inherit"`, omit the `model=` parameter from all `Agent()` calls — do NOT pass `model="inherit"` to Agent. Omitting the `model=` parameter causes Claude Code to inherit the current orchestrator model automatically. Only set `model=` when `executor_model` is an explicit model name (e.g., `"claude-sonnet-4-6"`, `"claude-opus-4-7"`).
77
78	**If `response_language` is set:** Include `response_language: {value}` in all spawned subagent prompts so any user-facing output stays in the configured language.
79
80	Read runtime/worktree config and fail closed before any executor dispatch:
81
82	```bash
83	RUNTIME=$(gsd-sdk query config-get runtime --default claude 2>/dev/null || echo "claude")
84	USE_WORKTREES=$(gsd-sdk query config-get workflow.use_worktrees 2>/dev/null || echo "true")
85	EXECUTOR_STALL_INTERVAL_MINUTES=$(gsd-sdk query config-get executor.stall_detect_interval_minutes 2>/dev/null || echo "5")
86	EXECUTOR_STALL_THRESHOLD_MINUTES=$(gsd-sdk query config-get executor.stall_threshold_minutes 2>/dev/null || echo "10")
87
88	if [ "$RUNTIME" = "codex" ] && [ "$USE_WORKTREES" != "false" ]; then
89	  echo "FATAL: Codex execute-phase worktree isolation is unsupported. Set workflow.use_worktrees=false or use a runtime with Agent isolation=\"worktree\" support." >&2
90	  exit 1
91	fi
92	```
93	Codex maps subagents to `spawn_agent`, which has no direct Codex mapping for Claude Code's `isolation="worktree"` parameter. Failing closed prevents main-checkout edits while the workflow believes agents are isolated.
94
95	If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.
96
97	```bash
98	# Parse submodule paths from .gitmodules once (empty if no .gitmodules).
99	# SUBMODULE_PATHS is a newline-separated list of repo-relative paths.
100	if [ -f .gitmodules ]; then
101	  SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
102	else
103	  SUBMODULE_PATHS=""
104	fi
105	```
106
107	`SUBMODULE_PATHS` is exported to the `execute_waves` step, where the per-plan decision actually happens (see "Per-plan worktree decision" sub-step inside `execute_waves`). The decision is per-plan because different plans in the same wave can touch different files — only plans whose paths intersect a submodule must drop worktree isolation; plans nowhere near a submodule keep parallel isolation.
108
109	When `USE_WORKTREES` (project-level) is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees. The per-plan decision below has no effect when worktrees are project-disabled.
110
111	Read context window size for adaptive prompt enrichment:
112
113	```bash
114	CONTEXT_WINDOW=$(gsd-sdk query config-get context_window 2>/dev/null || echo "200000")
115	```
116
117	When `CONTEXT_WINDOW >= 500000` (1M-class models), subagent prompts include richer context:
118	- Executor agents receive prior wave SUMMARY.md files and the phase CONTEXT.md/RESEARCH.md
119	- Verifier agents receive all PLAN.md, SUMMARY.md, CONTEXT.md files plus REQUIREMENTS.md
120	- This enables cross-phase awareness and history-aware verification
121
122	When `CONTEXT_WINDOW < 200000` (sub-200K models), subagent prompts are thinned to reduce static overhead:
123	- Executor agents omit extended deviation rule examples and checkpoint examples from inline prompt — load on-demand via @$HOME/.claude/get-shit-done/references/executor-examples.md
124	- Planner agents omit extended anti-pattern lists and specificity examples from inline prompt — load on-demand via @$HOME/.claude/get-shit-done/references/planner-antipatterns.md
125	- Core rules and decision logic remain inline; only verbose examples and edge-case lists are extracted
126	- This reduces executor static overhead by ~40% while preserving behavioral correctness
127
128	**If `phase_found` is false:** Error — phase directory not found.
129	**If `plan_count` is 0:** Error — no plans found in phase.
130	**If `state_exists` is false but `.planning/` exists:** Offer reconstruct or continue.
131
132	When `parallelization` is false, plans within a wave execute sequentially.
133
134	**Runtime detection for Copilot:**
135	Check if the current runtime is Copilot by testing for the `@gsd-executor` agent pattern
136	or absence of the `Agent()` subagent API. If running under Copilot, force sequential inline
137	execution regardless of the `parallelization` setting — Copilot's subagent completion
138	signals are unreliable (see `<runtime_compatibility>`). Set `COPILOT_SEQUENTIAL=true`
139	internally and skip the `execute_waves` step in favor of `check_interactive_mode`'s
140	inline path for each plan.
141
142	**REQUIRED — Sync chain flag with intent.** If user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This prevents stale `_auto_chain_active: true` from causing unwanted auto-advance. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference). You MUST execute this bash block before any config reads:
143	```bash
144	# REQUIRED: prevents stale auto-chain from previous --auto runs
145	if [[ ! "$ARGUMENTS" =~ --auto ]]; then
146	  gsd-sdk query config-set workflow._auto_chain_active false || true
147	fi
148	```
149
150	Resolve `MVP_MODE` once via the centralized `phase.mvp-mode` query verb (precedence chain: CLI flag → ROADMAP `**Mode:** mvp` → `workflow.mvp_mode` config → false):
151	```bash
152	MVP_FLAG_ARG=""
153	if [[ "$ARGUMENTS" =~ (^|[[:space:]])--mvp([[:space:]]|$) ]]; then MVP_FLAG_ARG="--cli-flag"; fi
154	MVP_MODE=$(gsd-sdk query phase.mvp-mode "${PHASE_NUMBER}" $MVP_FLAG_ARG --pick active)
155	TDD_MODE=$(gsd-sdk query config-get workflow.tdd_mode 2>/dev/null || echo "false")
156	```
157
158	<step name="safe_resume_gate">
159	Before trusting `STATE.md` or dispatching any executor, derive `CURRENT_PLAN_ID`
160	from the active incomplete plan in `INIT`, then search recent history:
161	```bash
162	CURRENT_PLAN_ID="{phase_number}-{plan_padded}"
163	SUMMARY_PATH="{phase_dir}/{plan_padded}-SUMMARY.md"
164	PLAN_COMMITS=$(git log --oneline --grep="${CURRENT_PLAN_ID}" -30)
165	```
166	If production commits exist and `SUMMARY.md is missing`, stop before spawning a
167	new executor; continuing risks duplicate work and stale `STATE.md`/ROADMAP progress.
168	Offer these recovery options:
169	- `close out manually` — inspect commits, write SUMMARY.md, then update STATE/ROADMAP.
170	- `re-execute from scratch` — revert or supersede partial commits before dispatch.
171	- `mark-and-skip` — record the anomaly and move on only with explicit confirmation.
172	</step>
173
174	**MVP+TDD gate.** Task-scoped enforcement runs inside plan execution (immediately before each implementation step), where `TASK_FILE`, `PLAN_ID`, and `TASK_ID` are defined. Keep the same predicate and RED-commit contract:
175	```bash
176	if [ "$MVP_MODE" = "true" ] && [ "$TDD_MODE" = "true" ]; then
177	  IS_BEHAVIOR_ADDING=$(gsd-sdk query task.is-behavior-adding "$TASK_FILE" --pick is_behavior_adding)
178	  if [ "$IS_BEHAVIOR_ADDING" = "true" ]; then
179	    RED_COMMIT=$(git log --oneline --grep="^test(${PHASE_NUMBER}-${PLAN_ID}):" -- "**/*.test.*" "**/*.spec.*" "tests/" | head -1)
180	    if [ -z "$RED_COMMIT" ]; then
181	      gsd-sdk query state.update last_gate_trip "${PLAN_ID}/${TASK_ID}" || true
182	      echo "MVP+TDD GATE TRIPPED: missing RED commit for ${PLAN_ID}/${TASK_ID}"
183	      exit 1
184	    fi
185	  fi
186	fi
187	```
188	Pure doc-only / config-only / test-only tasks return `is_behavior_adding=false` and are exempt. See `execute-mvp-tdd.md` for the halt report format.
189	</step>
190
191	<step name="check_blocking_antipatterns" priority="first">
192	**MANDATORY — Check for blocking anti-patterns before any other work.**
193
194	Look for a `.continue-here.md` in the current phase directory:
195
196	```bash
197	ls ${phase_dir}/.continue-here.md 2>/dev/null || true
198	```
199
200	If `.continue-here.md` exists, parse its "Critical Anti-Patterns" table for rows with `severity` = `blocking`.
201
202	**If one or more `blocking` anti-patterns are found:**
203
204	This step cannot be skipped. Before proceeding to `check_interactive_mode` or any other step, the agent must demonstrate understanding of each blocking anti-pattern by answering all three questions for each one:
205
206	1. **What is this anti-pattern?** — Describe it in your own words, not by quoting the handoff.
207	2. **How did it manifest?** — Explain the specific failure that caused it to be recorded.
208	3. **What structural mechanism (not acknowledgment) prevents it?** — Name the concrete step, checklist item, or enforcement mechanism that stops recurrence.
209
210	Write these answers inline before continuing. If a blocking anti-pattern cannot be answered from the context in `.continue-here.md`, stop and ask the user for clarification.
211
212	**If no `.continue-here.md` exists, or no `blocking` rows are found:** Proceed directly to `check_interactive_mode`.
213	</step>
214
215	<step name="check_interactive_mode">
216	**Parse `--interactive` flag from $ARGUMENTS.**
217
218	**If `--interactive` flag present:** Switch to interactive execution mode.
219
220	Interactive mode executes plans sequentially **inline** (no subagent spawning) with user
221	checkpoints between tasks. The user can review, modify, or redirect work at any point.
222
223	**Interactive execution flow:**
224
225	1. Load plan inventory as normal (discover_and_group_plans)
226	2. For each plan (sequentially, ignoring wave grouping):
227
228	   a. **Present the plan to the user:**
229	      ```
230	      ## Plan {plan_id}: {plan_name}
231
232	      Objective: {from plan file}
233	      Tasks: {task_count}
234
235	      Options:
236	      - Execute (proceed with all tasks)
237	      - Review first (show task breakdown before starting)
238	      - Skip (move to next plan)
239	      - Stop (end execution, save progress)
240	      ```
241
242	   b. **If "Review first":** Read and display the full plan file. Ask again: Execute, Modify, Skip.
243
244	   c. **If "Execute":** Read and follow `$HOME/.claude/get-shit-done/workflows/execute-plan.md` **inline**
245	      (do NOT spawn a subagent). Execute tasks one at a time.
246
247	   d. **After each task:** Pause briefly. If the user intervenes (types anything), stop and address
248	      their feedback before continuing. Otherwise proceed to next task.
249
250	   e. **After plan complete:** Show results, commit, create SUMMARY.md, then present next plan.
251
252	3. After all plans: proceed to verification (same as normal mode).
253
254	**Benefits of interactive mode:**
255	- No subagent overhead — dramatically lower token usage
256	- User catches mistakes early — saves costly verification cycles
257	- Maintains GSD's planning/tracking structure
258	- Best for: small phases, bug fixes, verification gaps, learning GSD
259
260	**Skip to handle_branching step** (interactive plans execute inline after grouping).
261	</step>
262
263	<step name="handle_branching">
264	Check `branching_strategy` from init:
265
266	**"none":** Skip, continue on current branch.
267
268	**"phase" or "milestone":** Use pre-computed `branch_name` from init.
269
270	Fork the new phase branch off `origin/HEAD` (the project's default branch), not the current HEAD — otherwise consecutive phases compound and stay unpushed (#2916). If `$BRANCH_NAME` already exists locally, reuse it as-is.
271
272	```bash
273	DEFAULT_BRANCH=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')
274	DEFAULT_BRANCH=${DEFAULT_BRANCH:-main}
275
276	if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
277	  git switch "$BRANCH_NAME" || { echo "ERROR: Could not switch to existing branch '$BRANCH_NAME'." >&2; exit 1; }
278	else
279	  if ! git fetch --quiet origin "$DEFAULT_BRANCH"; then  # #2916
280	    git show-ref --verify --quiet "refs/remotes/origin/$DEFAULT_BRANCH" \
281	      || { echo "ERROR: fetch origin/$DEFAULT_BRANCH failed and no local copy exists. Refusing to create '$BRANCH_NAME' off current HEAD (#2916)." >&2; exit 1; }
282	    echo "WARNING: fetch origin/$DEFAULT_BRANCH failed; using local copy as base." >&2
283	  fi
284	  if [ -n "$(git status --porcelain)" ]; then
285	    echo "WARNING: Uncommitted changes will be carried onto '$BRANCH_NAME' (branched off origin/$DEFAULT_BRANCH, not previous HEAD)."
286	  else
287	    git switch --quiet "$DEFAULT_BRANCH" 2>/dev/null && git merge --ff-only --quiet "origin/$DEFAULT_BRANCH" 2>/dev/null || true
288	  fi
289	  # Pinned base + fail-fast: on success HEAD is exactly at origin/$DEFAULT_BRANCH,
290	  # so a post-creation merge-base or "ahead-of" guard would be unreachable. The
291	  # explicit base argument here is the single source of correctness for #2916.
292	  git checkout -b "$BRANCH_NAME" "origin/$DEFAULT_BRANCH" \
293	    || { echo "ERROR: Could not create '$BRANCH_NAME' from origin/$DEFAULT_BRANCH (#2916)." >&2; exit 1; }
294	fi
295	```
296
297	All subsequent commits go to this branch. User handles merging.
298	</step>
299
300	<step name="validate_phase">
301	From init JSON: `phase_dir`, `plan_count`, `incomplete_count`.
302
303	Report: "Found {plan_count} plans in {phase_dir} ({incomplete_count} incomplete)"
304
305	**Update STATE.md for phase start:**
306	```bash
307	gsd-sdk query state.begin-phase --phase "${PHASE_NUMBER}" --name "${PHASE_NAME}" --plans "${PLAN_COUNT}"
308	```
309	This updates Status, Last Activity, Current focus, Current Position, and plan counts in STATE.md so frontmatter and body text reflect the active phase immediately.
310	</step>
311
312	<step name="discover_and_group_plans">
313	Load plan inventory with wave grouping in one call:
314
315	```bash
316	PLAN_INDEX=$(gsd-sdk query phase-plan-index "${PHASE_NUMBER}")
317	```
318
319	Parse JSON for: `phase`, `plans[]` (each with `id`, `wave`, `autonomous`, `objective`, `files_modified`, `task_count`, `has_summary`), `waves` (map of wave number → plan IDs), `incomplete`, `has_checkpoints`.
320
321	**Filtering:** Skip plans where `has_summary: true`. If `--gaps-only`: also skip non-gap_closure plans. If `WAVE_FILTER` is set: also skip plans whose `wave` does not equal `WAVE_FILTER`.
322
323	**Wave safety check:** If `WAVE_FILTER` is set and there are still incomplete plans in any lower wave that match the current execution mode, STOP and tell the user to finish earlier waves first. Do not let Wave 2+ execute while prerequisite earlier-wave plans remain incomplete.
324
325	If all filtered: "No matching incomplete plans" → exit.
326
327	Report:
328	```
329	## Execution Plan
330
331	**Phase {X}: {Name}** — {total_plans} matching plans across {wave_count} wave(s)
332
333	{If WAVE_FILTER is set: `Wave filter active: executing only Wave {WAVE_FILTER}`.}
334
335	| Wave | Plans | What it builds |
336	|------|-------|----------------|
337	| 1 | 01-01, 01-02 | {from plan objectives, 3-8 words} |
338	| 2 | 01-03 | ... |
339	```
340	</step>
341
342	<step name="cross_ai_delegation">
343	**Optional step 2.5 — Delegate plans to an external AI runtime.**
344
345	This step runs after plan discovery and before normal wave execution. It identifies plans
346	that should be delegated to an external AI command and executes them via stdin-based prompt
347	delivery. Plans handled here are removed from the execute_waves plan list so the normal
348	executor skips them.
349
350	**Activation logic:**
351
352	1. If `CROSS_AI_DISABLED` is true (`--no-cross-ai` flag): skip this step entirely.
353	2. If `CROSS_AI_FORCE` is true (`--cross-ai` flag): mark ALL incomplete plans for cross-AI execution.
354	3. Otherwise: check each plan's frontmatter for `cross_ai: true` AND verify config
355	   `workflow.cross_ai_execution` is `true`. Plans matching both conditions are marked for cross-AI.
356
357	```bash
358	CROSS_AI_ENABLED=$(gsd-sdk query config-get workflow.cross_ai_execution 2>/dev/null || echo "false")
359	CROSS_AI_CMD=$(gsd-sdk query config-get workflow.cross_ai_command 2>/dev/null || echo "")
360	CROSS_AI_TIMEOUT=$(gsd-sdk query config-get workflow.cross_ai_timeout 2>/dev/null || echo "300")
361	```
362
363	**If no plans are marked for cross-AI:** Skip to execute_waves.
364
365	**If plans are marked but `cross_ai_command` is empty:** Error — tell user to set
366	`workflow.cross_ai_command` via `gsd-sdk query config-set workflow.cross_ai_command "<command>"`.
367
368	**For each cross-AI plan (sequentially):**
369
370	1. **Construct the task prompt** from the plan file:
371	   - Extract `<objective>` and `<tasks>` sections from the PLAN.md
372	   - Append PROJECT.md context (project name, description, tech stack)
373	   - Format as a self-contained execution prompt
374
375	2. **Check for dirty working tree before execution:**
376	   ```bash
377	   if ! git diff --quiet HEAD 2>/dev/null; then
378	     echo "WARNING: dirty working tree detected — the external AI command may produce uncommitted changes that conflict with existing modifications"
379	   fi
380	   ```
381
382	3. **Run the external command** from the project root, writing the prompt to stdin.
383	   Never shell-interpolate the prompt — always pipe via stdin to prevent injection:
384	   ```bash
385	   echo "$TASK_PROMPT" | timeout "${CROSS_AI_TIMEOUT}s" ${CROSS_AI_CMD} > "$CANDIDATE_SUMMARY" 2>"$ERROR_LOG"
386	   EXIT_CODE=$?
387	   ```
388
389	4. **Evaluate the result:**
390
391	   **Success (exit 0 + valid summary):**
392	   - Read `$CANDIDATE_SUMMARY` and validate it contains meaningful content
393	     (not empty, has at least a heading and description — a valid SUMMARY.md structure)
394	   - Write it as the plan's SUMMARY.md file
395	   - Update STATE.md plan status to complete
396	   - Update ROADMAP.md progress
397	   - Mark plan as handled — skip it in execute_waves
398
399	   **Failure (non-zero exit or invalid summary):**
400	   - Display the error output and exit code

<purpose>
Execute all plans in a phase using wave-based parallel execution. Orchestrator stays lean — delegates plan execution to subagents.
</purpose>

<core_principle>
Orchestrator coordinates, not executes. Each subagent loads the full execute-plan context. Orchestrator: discover plans → analyze deps → group waves → spawn agents → handle checkpoints → collect results.
</core_principle>

<runtime_compatibility>
**Subagent spawning is runtime-specific:**
- **Claude Code:** Uses `Agent(subagent_type="gsd-executor", ...)` — blocks until complete, returns result
- **Copilot:** Subagent spawning does not reliably return completion signals. **Default to
  sequential inline execution**: read and follow execute-plan.md directly for each plan
  instead of spawning parallel agents. Only attempt parallel spawning if the user
  explicitly requests it — and in that case, rely on the spot-check fallback in step 3
  to detect completion.
- **Other runtimes:** If `Agent`/`agent` tool is unavailable, use sequential inline execution as the
  fallback. Check for tool availability at runtime rather than assuming based on runtime name.

**Fallback rule:** If a spawned agent completes its work (commits visible, SUMMARY.md exists) but
the orchestrator never receives the completion signal, treat it as successful based on spot-checks
and continue to the next wave/plan. Never block indefinitely waiting for a signal — always verify
via filesystem and git state.
</runtime_compatibility>

<required_reading>
Read STATE.md before any operation to load project context.
@$HOME/.claude/get-shit-done/references/agent-contracts.md
@$HOME/.claude/get-shit-done/references/context-budget.md
@$HOME/.claude/get-shit-done/references/gates.md
</required_reading>

<available_agent_types>
These are the valid GSD subagent types registered in .claude/agents/ (or equivalent for your runtime).
Always use the exact name from this list — do not fall back to 'general-purpose' or other built-in types:

- gsd-executor — Executes plan tasks, commits, creates SUMMARY.md
- gsd-verifier — Verifies phase completion, checks quality gates
- gsd-planner — Creates detailed plans from phase scope
- gsd-phase-researcher — Researches technical approaches for a phase
- gsd-plan-checker — Reviews plan quality before execution
- gsd-debugger — Diagnoses and fixes issues
- gsd-codebase-mapper — Maps project structure and dependencies
- gsd-integration-checker — Checks cross-phase integration
- gsd-nyquist-auditor — Validates verification coverage
- gsd-ui-researcher — Researches UI/UX approaches
- gsd-ui-checker — Reviews UI implementation quality
- gsd-ui-auditor — Audits UI against design requirements
</available_agent_types>

<process>

<step name="parse_args" priority="first">
Parse `$ARGUMENTS` before loading any context:

- First positional token → `PHASE_ARG`
- Optional `--wave N` → `WAVE_FILTER`
- Optional `--gaps-only` keeps its current meaning
- Optional `--cross-ai` → `CROSS_AI_FORCE=true` (force all plans through cross-AI execution)
- Optional `--no-cross-ai` → `CROSS_AI_DISABLED=true` (disable cross-AI for this run, overrides config and frontmatter)

If `--wave` is absent, preserve the current behavior of executing all incomplete waves in the phase.
</step>

<step name="initialize" priority="first">
Load all context in one call:

```bash
INIT=$(gsd-sdk query init.execute-phase "${PHASE_ARG}")
if [[ "$INIT" == @file:* ]]; then INIT=$(cat "${INIT#@file:}"); fi
AGENT_SKILLS=$(gsd-sdk query agent-skills gsd-executor)
```

Parse JSON for: `executor_model`, `verifier_model`, `commit_docs`, `parallelization`, `branching_strategy`, `branch_name`, `phase_found`, `phase_dir`, `phase_number`, `phase_name`, `phase_slug`, `plans`, `incomplete_plans`, `plan_count`, `incomplete_count`, `state_exists`, `roadmap_exists`, `phase_req_ids`, `response_language`.

**Model resolution:** If `executor_model` is `"inherit"`, omit the `model=` parameter from all `Agent()` calls — do NOT pass `model="inherit"` to Agent. Omitting the `model=` parameter causes Claude Code to inherit the current orchestrator model automatically. Only set `model=` when `executor_model` is an explicit model name (e.g., `"claude-sonnet-4-6"`, `"claude-opus-4-7"`).

**If `response_language` is set:** Include `response_language: {value}` in all spawned subagent prompts so any user-facing output stays in the configured language.

Read runtime/worktree config and fail closed before any executor dispatch:

```bash
RUNTIME=$(gsd-sdk query config-get runtime --default claude 2>/dev/null || echo "claude")
USE_WORKTREES=$(gsd-sdk query config-get workflow.use_worktrees 2>/dev/null || echo "true")
EXECUTOR_STALL_INTERVAL_MINUTES=$(gsd-sdk query config-get executor.stall_detect_interval_minutes 2>/dev/null || echo "5")
EXECUTOR_STALL_THRESHOLD_MINUTES=$(gsd-sdk query config-get executor.stall_threshold_minutes 2>/dev/null || echo "10")

if [ "$RUNTIME" = "codex" ] && [ "$USE_WORKTREES" != "false" ]; then
  echo "FATAL: Codex execute-phase worktree isolation is unsupported. Set workflow.use_worktrees=false or use a runtime with Agent isolation=\"worktree\" support." >&2
  exit 1
fi
```
Codex maps subagents to `spawn_agent`, which has no direct Codex mapping for Claude Code's `isolation="worktree"` parameter. Failing closed prevents main-checkout edits while the workflow believes agents are isolated.

If the project uses git submodules, worktree isolation is unsafe **only when a plan touches a submodule path** — the executor commit protocol cannot correctly handle submodule commits inside isolated worktrees. The previous behavior unconditionally disabled worktree isolation whenever `.gitmodules` existed, which penalised every plan in a submodule project even when the plan was nowhere near a submodule. Compute submodule paths once and intersect them per-plan with the plan's declared `files_modified` frontmatter.

```bash
# Parse submodule paths from .gitmodules once (empty if no .gitmodules).
# SUBMODULE_PATHS is a newline-separated list of repo-relative paths.
if [ -f .gitmodules ]; then
  SUBMODULE_PATHS=$(git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}')
else
  SUBMODULE_PATHS=""
fi
```

`SUBMODULE_PATHS` is exported to the `execute_waves` step, where the per-plan decision actually happens (see "Per-plan worktree decision" sub-step inside `execute_waves`). The decision is per-plan because different plans in the same wave can touch different files — only plans whose paths intersect a submodule must drop worktree isolation; plans nowhere near a submodule keep parallel isolation.

When `USE_WORKTREES` (project-level) is `false`, all executor agents run without `isolation="worktree"` — they execute sequentially on the main working tree instead of in parallel worktrees. The per-plan decision below has no effect when worktrees are project-disabled.

Read context window size for adaptive prompt enrichment:

```bash
CONTEXT_WINDOW=$(gsd-sdk query config-get context_window 2>/dev/null || echo "200000")
```

When `CONTEXT_WINDOW >= 500000` (1M-class models), subagent prompts include richer context:
- Executor agents receive prior wave SUMMARY.md files and the phase CONTEXT.md/RESEARCH.md
- Verifier agents receive all PLAN.md, SUMMARY.md, CONTEXT.md files plus REQUIREMENTS.md
- This enables cross-phase awareness and history-aware verification

When `CONTEXT_WINDOW < 200000` (sub-200K models), subagent prompts are thinned to reduce static overhead:
- Executor agents omit extended deviation rule examples and checkpoint examples from inline prompt — load on-demand via @$HOME/.claude/get-shit-done/references/executor-examples.md
- Planner agents omit extended anti-pattern lists and specificity examples from inline prompt — load on-demand via @$HOME/.claude/get-shit-done/references/planner-antipatterns.md
- Core rules and decision logic remain inline; only verbose examples and edge-case lists are extracted
- This reduces executor static overhead by ~40% while preserving behavioral correctness

**If `phase_found` is false:** Error — phase directory not found.
**If `plan_count` is 0:** Error — no plans found in phase.
**If `state_exists` is false but `.planning/` exists:** Offer reconstruct or continue.

When `parallelization` is false, plans within a wave execute sequentially.

**Runtime detection for Copilot:**
Check if the current runtime is Copilot by testing for the `@gsd-executor` agent pattern
or absence of the `Agent()` subagent API. If running under Copilot, force sequential inline
execution regardless of the `parallelization` setting — Copilot's subagent completion
signals are unreliable (see `<runtime_compatibility>`). Set `COPILOT_SEQUENTIAL=true`
internally and skip the `execute_waves` step in favor of `check_interactive_mode`'s
inline path for each plan.

**REQUIRED — Sync chain flag with intent.** If user invoked manually (no `--auto`), clear the ephemeral chain flag from any previous interrupted `--auto` chain. This prevents stale `_auto_chain_active: true` from causing unwanted auto-advance. This does NOT touch `workflow.auto_advance` (the user's persistent settings preference). You MUST execute this bash block before any config reads:
```bash
# REQUIRED: prevents stale auto-chain from previous --auto runs
if [[ ! "$ARGUMENTS" =~ --auto ]]; then
  gsd-sdk query config-set workflow._auto_chain_active false || true
fi
```

Resolve `MVP_MODE` once via the centralized `phase.mvp-mode` query verb (precedence chain: CLI flag → ROADMAP `**Mode:** mvp` → `workflow.mvp_mode` config → false):
```bash
MVP_FLAG_ARG=""
if [[ "$ARGUMENTS" =~ (^|[[:space:]])--mvp([[:space:]]|$) ]]; then MVP_FLAG_ARG="--cli-flag"; fi
MVP_MODE=$(gsd-sdk query phase.mvp-mode "${PHASE_NUMBER}" $MVP_FLAG_ARG --pick active)
TDD_MODE=$(gsd-sdk query config-get workflow.tdd_mode 2>/dev/null || echo "false")
```

<step name="safe_resume_gate">
Before trusting `STATE.md` or dispatching any executor, derive `CURRENT_PLAN_ID`
from the active incomplete plan in `INIT`, then search recent history:
```bash
CURRENT_PLAN_ID="{phase_number}-{plan_padded}"
SUMMARY_PATH="{phase_dir}/{plan_padded}-SUMMARY.md"
PLAN_COMMITS=$(git log --oneline --grep="${CURRENT_PLAN_ID}" -30)
```
If production commits exist and `SUMMARY.md is missing`, stop before spawning a
new executor; continuing risks duplicate work and stale `STATE.md`/ROADMAP progress.
Offer these recovery options:
- `close out manually` — inspect commits, write SUMMARY.md, then update STATE/ROADMAP.
- `re-execute from scratch` — revert or supersede partial commits before dispatch.
- `mark-and-skip` — record the anomaly and move on only with explicit confirmation.
</step>

**MVP+TDD gate.** Task-scoped enforcement runs inside plan execution (immediately before each implementation step), where `TASK_FILE`, `PLAN_ID`, and `TASK_ID` are defined. Keep the same predicate and RED-commit contract:
```bash
if [ "$MVP_MODE" = "true" ] && [ "$TDD_MODE" = "true" ]; then
  IS_BEHAVIOR_ADDING=$(gsd-sdk query task.is-behavior-adding "$TASK_FILE" --pick is_behavior_adding)
  if [ "$IS_BEHAVIOR_ADDING" = "true" ]; then
    RED_COMMIT=$(git log --oneline --grep="^test(${PHASE_NUMBER}-${PLAN_ID}):" -- "**/*.test.*" "**/*.spec.*" "tests/" | head -1)
    if [ -z "$RED_COMMIT" ]; then
      gsd-sdk query state.update last_gate_trip "${PLAN_ID}/${TASK_ID}" || true
      echo "MVP+TDD GATE TRIPPED: missing RED commit for ${PLAN_ID}/${TASK_ID}"
      exit 1
    fi
  fi
fi
```
Pure doc-only / config-only / test-only tasks return `is_behavior_adding=false` and are exempt. See `execute-mvp-tdd.md` for the halt report format.
</step>

<step name="check_blocking_antipatterns" priority="first">
**MANDATORY — Check for blocking anti-patterns before any other work.**

Look for a `.continue-here.md` in the current phase directory:

```bash
ls ${phase_dir}/.continue-here.md 2>/dev/null || true
```

If `.continue-here.md` exists, parse its "Critical Anti-Patterns" table for rows with `severity` = `blocking`.

**If one or more `blocking` anti-patterns are found:**

This step cannot be skipped. Before proceeding to `check_interactive_mode` or any other step, the agent must demonstrate understanding of each blocking anti-pattern by answering all three questions for each one:

1. **What is this anti-pattern?** — Describe it in your own words, not by quoting the handoff.
2. **How did it manifest?** — Explain the specific failure that caused it to be recorded.
3. **What structural mechanism (not acknowledgment) prevents it?** — Name the concrete step, checklist item, or enforcement mechanism that stops recurrence.

Write these answers inline before continuing. If a blocking anti-pattern cannot be answered from the context in `.continue-here.md`, stop and ask the user for clarification.

**If no `.continue-here.md` exists, or no `blocking` rows are found:** Proceed directly to `check_interactive_mode`.
</step>

<step name="check_interactive_mode">
**Parse `--interactive` flag from $ARGUMENTS.**

**If `--interactive` flag present:** Switch to interactive execution mode.

Interactive mode executes plans sequentially **inline** (no subagent spawning) with user
checkpoints between tasks. The user can review, modify, or redirect work at any point.

**Interactive execution flow:**

1. Load plan inventory as normal (discover_and_group_plans)
2. For each plan (sequentially, ignoring wave grouping):

   a. **Present the plan to the user:**
      ```
      ## Plan {plan_id}: {plan_name}

      Objective: {from plan file}
      Tasks: {task_count}

      Options:
      - Execute (proceed with all tasks)
      - Review first (show task breakdown before starting)
      - Skip (move to next plan)
      - Stop (end execution, save progress)
      ```

   b. **If "Review first":** Read and display the full plan file. Ask again: Execute, Modify, Skip.

   c. **If "Execute":** Read and follow `$HOME/.claude/get-shit-done/workflows/execute-plan.md` **inline**
      (do NOT spawn a subagent). Execute tasks one at a time.

   d. **After each task:** Pause briefly. If the user intervenes (types anything), stop and address
      their feedback before continuing. Otherwise proceed to next task.

   e. **After plan complete:** Show results, commit, create SUMMARY.md, then present next plan.

3. After all plans: proceed to verification (same as normal mode).

**Benefits of interactive mode:**
- No subagent overhead — dramatically lower token usage
- User catches mistakes early — saves costly verification cycles
- Maintains GSD's planning/tracking structure
- Best for: small phases, bug fixes, verification gaps, learning GSD

**Skip to handle_branching step** (interactive plans execute inline after grouping).
</step>

<step name="handle_branching">
Check `branching_strategy` from init:

**"none":** Skip, continue on current branch.

**"phase" or "milestone":** Use pre-computed `branch_name` from init.

Fork the new phase branch off `origin/HEAD` (the project's default branch), not the current HEAD — otherwise consecutive phases compound and stay unpushed (#2916). If `$BRANCH_NAME` already exists locally, reuse it as-is.

```bash
DEFAULT_BRANCH=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')
DEFAULT_BRANCH=${DEFAULT_BRANCH:-main}

if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
  git switch "$BRANCH_NAME" || { echo "ERROR: Could not switch to existing branch '$BRANCH_NAME'." >&2; exit 1; }
else
  if ! git fetch --quiet origin "$DEFAULT_BRANCH"; then  # #2916
    git show-ref --verify --quiet "refs/remotes/origin/$DEFAULT_BRANCH" \
      || { echo "ERROR: fetch origin/$DEFAULT_BRANCH failed and no local copy exists. Refusing to create '$BRANCH_NAME' off current HEAD (#2916)." >&2; exit 1; }
    echo "WARNING: fetch origin/$DEFAULT_BRANCH failed; using local copy as base." >&2
  fi
  if [ -n "$(git status --porcelain)" ]; then
    echo "WARNING: Uncommitted changes will be carried onto '$BRANCH_NAME' (branched off origin/$DEFAULT_BRANCH, not previous HEAD)."
  else
    git switch --quiet "$DEFAULT_BRANCH" 2>/dev/null && git merge --ff-only --quiet "origin/$DEFAULT_BRANCH" 2>/dev/null || true
  fi
  # Pinned base + fail-fast: on success HEAD is exactly at origin/$DEFAULT_BRANCH,
  # so a post-creation merge-base or "ahead-of" guard would be unreachable. The
  # explicit base argument here is the single source of correctness for #2916.
  git checkout -b "$BRANCH_NAME" "origin/$DEFAULT_BRANCH" \
    || { echo "ERROR: Could not create '$BRANCH_NAME' from origin/$DEFAULT_BRANCH (#2916)." >&2; exit 1; }
fi
```

All subsequent commits go to this branch. User handles merging.
</step>

<step name="validate_phase">
From init JSON: `phase_dir`, `plan_count`, `incomplete_count`.

Report: "Found {plan_count} plans in {phase_dir} ({incomplete_count} incomplete)"

**Update STATE.md for phase start:**
```bash
gsd-sdk query state.begin-phase --phase "${PHASE_NUMBER}" --name "${PHASE_NAME}" --plans "${PLAN_COUNT}"
```
This updates Status, Last Activity, Current focus, Current Position, and plan counts in STATE.md so frontmatter and body text reflect the active phase immediately.
</step>

<step name="discover_and_group_plans">
Load plan inventory with wave grouping in one call:

```bash
PLAN_INDEX=$(gsd-sdk query phase-plan-index "${PHASE_NUMBER}")
```

Parse JSON for: `phase`, `plans[]` (each with `id`, `wave`, `autonomous`, `objective`, `files_modified`, `task_count`, `has_summary`), `waves` (map of wave number → plan IDs), `incomplete`, `has_checkpoints`.

**Filtering:** Skip plans where `has_summary: true`. If `--gaps-only`: also skip non-gap_closure plans. If `WAVE_FILTER` is set: also skip plans whose `wave` does not equal `WAVE_FILTER`.

**Wave safety check:** If `WAVE_FILTER` is set and there are still incomplete plans in any lower wave that match the current execution mode, STOP and tell the user to finish earlier waves first. Do not let Wave 2+ execute while prerequisite earlier-wave plans remain incomplete.

If all filtered: "No matching incomplete plans" → exit.

Report:
```
## Execution Plan

**Phase {X}: {Name}** — {total_plans} matching plans across {wave_count} wave(s)

{If WAVE_FILTER is set: `Wave filter active: executing only Wave {WAVE_FILTER}`.}

| Wave | Plans | What it builds |
|------|-------|----------------|
| 1 | 01-01, 01-02 | {from plan objectives, 3-8 words} |
| 2 | 01-03 | ... |
```
</step>

<step name="cross_ai_delegation">
**Optional step 2.5 — Delegate plans to an external AI runtime.**

This step runs after plan discovery and before normal wave execution. It identifies plans
that should be delegated to an external AI command and executes them via stdin-based prompt
delivery. Plans handled here are removed from the execute_waves plan list so the normal
executor skips them.

**Activation logic:**

1. If `CROSS_AI_DISABLED` is true (`--no-cross-ai` flag): skip this step entirely.
2. If `CROSS_AI_FORCE` is true (`--cross-ai` flag): mark ALL incomplete plans for cross-AI execution.
3. Otherwise: check each plan's frontmatter for `cross_ai: true` AND verify config
   `workflow.cross_ai_execution` is `true`. Plans matching both conditions are marked for cross-AI.

```bash
CROSS_AI_ENABLED=$(gsd-sdk query config-get workflow.cross_ai_execution 2>/dev/null || echo "false")
CROSS_AI_CMD=$(gsd-sdk query config-get workflow.cross_ai_command 2>/dev/null || echo "")
CROSS_AI_TIMEOUT=$(gsd-sdk query config-get workflow.cross_ai_timeout 2>/dev/null || echo "300")
```

**If no plans are marked for cross-AI:** Skip to execute_waves.

**If plans are marked but `cross_ai_command` is empty:** Error — tell user to set
`workflow.cross_ai_command` via `gsd-sdk query config-set workflow.cross_ai_command "<command>"`.

**For each cross-AI plan (sequentially):**

1. **Construct the task prompt** from the plan file:
   - Extract `<objective>` and `<tasks>` sections from the PLAN.md
   - Append PROJECT.md context (project name, description, tech stack)
   - Format as a self-contained execution prompt

2. **Check for dirty working tree before execution:**
   ```bash
   if ! git diff --quiet HEAD 2>/dev/null; then
     echo "WARNING: dirty working tree detected — the external AI command may produce uncommitted changes that conflict with existing modifications"
   fi
   ```

3. **Run the external command** from the project root, writing the prompt to stdin.
   Never shell-interpolate the prompt — always pipe via stdin to prevent injection:
   ```bash
   echo "$TASK_PROMPT" | timeout "${CROSS_AI_TIMEOUT}s" ${CROSS_AI_CMD} > "$CANDIDATE_SUMMARY" 2>"$ERROR_LOG"
   EXIT_CODE=$?
   ```

4. **Evaluate the result:**

   **Success (exit 0 + valid summary):**
   - Read `$CANDIDATE_SUMMARY` and validate it contains meaningful content
     (not empty, has at least a heading and description — a valid SUMMARY.md structure)
   - Write it as the plan's SUMMARY.md file
   - Update STATE.md plan status to complete
   - Update ROADMAP.md progress
   - Mark plan as handled — skip it in execute_waves

   **Failure (non-zero exit or invalid summary):**
   - Display the error output and exit code