{"owner":"garrytan","repo":"gstack","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md","CLAUDE.md"],"skills":{"AGENTS.md":"# gstack — AI Engineering Workflow\n\ngstack is a collection of SKILL.md files that give AI agents structured roles for\nsoftware development. Each skill is a specialist: CEO reviewer, eng manager,\ndesigner, QA lead, release engineer, debugger, and more.\n\n## Available skills\n\nSkills live in `.agents/skills/` (or `~/.claude/skills/gstack/` on Claude Code).\nInvoke them by name (e.g., `/office-hours`).\n\n### Plan-mode reviews\n\n| Skill | What it does |\n|-------|-------------|\n| `/office-hours` | Start here. Reframes your product idea before you write code. |\n| `/plan-ceo-review` | CEO-level review: find the 10-star product in the request. |\n| `/plan-eng-review` | Lock architecture, data flow, edge cases, and tests. |\n| `/plan-design-review` | Rate each design dimension 0-10, explain what a 10 looks like. |\n| `/plan-devex-review` | DX-mode review: TTHW, magical moments, friction points, persona traces. |\n| `/plan-tune` | Self-tune AskUserQuestion sensitivity per question. |\n| `/autoplan` | One command runs CEO → design → eng → DX review. |\n| `/design-consultation` | Build a complete design system from scratch. |\n| `/spec` | Turn vague intent into a precise, executable spec in five phases. Files a GitHub issue, optionally spawns a Claude Code agent in a fresh worktree, and lets `/ship` close the source issue on merge. |\n\n### Implementation + review\n\n| Skill | What it does |\n|-------|-------------|\n| `/review` | Pre-landing PR review. Finds bugs that pass CI but break in prod. |\n| `/codex` | Second opinion via OpenAI Codex. Review, challenge, or consult modes. |\n| `/investigate` | Systematic root-cause debugging. No fixes without investigation. |\n| `/design-review` | Live-site visual audit + fix loop with atomic commits. |\n| `/design-shotgun` | Generate multiple AI design variants, comparison board, iterate. |\n| `/design-html` | Generate production-quality Pretext-native HTML/CSS. |\n| `/devex-review` | Live developer experience audit (TTHW measured against the real flow). |\n| `/qa` | Open a real browser, find bugs, fix them, re-verify. |\n| `/qa-only` | Same methodology as /qa but report only — no code changes. |\n| `/scrape` | Pull data from a web page. First call prototypes; codified call runs in ~200ms. |\n| `/skillify` | Codify the most recent successful `/scrape` flow into a permanent browser-skill. |\n\n### Release + deploy\n\n| Skill | What it does |\n|-------|-------------|\n| `/ship` | Run tests, review, push, open PR. Workspace-aware version queue. |\n| `/land-and-deploy` | Merge the PR, wait for CI and deploy, verify production health. |\n| `/canary` | Post-deploy monitoring loop using the browse daemon. |\n| `/landing-report` | Read-only dashboard for the workspace-aware ship queue. |\n| `/document-release` | Update all docs to match what you just shipped. |\n| `/document-generate` | Generate Diataxis docs (tutorial / how-to / reference / explanation) from code. |\n| `/setup-deploy` | One-time deploy config detection (Fly.io, Render, Vercel, etc.). |\n| `/gstack-upgrade` | Update gstack to the latest version. |\n\n### Operational + memory\n\n| Skill | What it does |\n|-------|-------------|\n| `/context-save` | Save working context (git state, decisions, remaining work). |\n| `/context-restore` | Resume from a saved context, even across Conductor workspaces. |\n| `/learn` | Manage what gstack learned across sessions. |\n| `/retro` | Weekly retro with per-person breakdowns and shipping streaks. |\n| `/health` | Code quality dashboard (type checker, linter, tests, dead code). |\n| `/benchmark` | Performance regression detection (page load, Core Web Vitals). |\n| `/benchmark-models` | Cross-model benchmark for skills (Claude, GPT, Gemini side-by-side). |\n| `/cso` | OWASP Top 10 + STRIDE security audit. |\n| `/setup-gbrain` | Set up gbrain for cross-machine session memory sync. |\n| `/sync-gbrain` | Keep gbrain current with this repo's code; refresh agent search guidance in CLAUDE.md. |\n\n### Browser + agent integration\n\n| Skill | What it does |\n|-------|-------------|\n| `/browse` | Headless browser — real Chromium, real clicks, ~100ms/command. |\n| `/open-gstack-browser` | Launch the visible GStack Browser with sidebar + stealth. |\n| `/setup-browser-cookies` | Import cookies from your real browser for authenticated testing. |\n| `/pair-agent` | Pair a remote AI agent (OpenClaw, Codex, etc.) with your browser. |\n\n### iOS QA — drive real iPhones over USB or Tailscale (v1.43.0.0+)\n\n| Skill | What it does |\n|-------|-------------|\n| `/ios-qa` | Live-device iOS QA via USB CoreDevice tunnel + embedded StateServer. Optionally exposes the device over Tailscale so remote agents can drive it. |\n| `/ios-fix` | Autonomous iOS bug fixer with regression snapshot capture. |\n| `/ios-design-review` | Designer's-eye QA on a real iPhone — 10-dimension Apple HIG rubric. |\n| `/ios-clean` | Convenience: strip DebugBridge + #if DEBUG wiring before a Release build. |\n| `/ios-sync` | Regenerate the iOS debug bridge against the latest upstream templates. |\n\nCompanion CLIs (run on the Mac that's plugged into the device):\n\n| Command | What it does |\n|---------|-------------|\n| `gstack-ios-qa-daemon` | Mac-side broker. Loopback by default; `--tailnet` adds a Tailscale-facing listener with capability tiers and audit logging. |\n| `gstack-ios-qa-mint` | Owner-grant CLI for the tailnet allowlist (`grant`/`revoke`/`list`). |\n| `gstack-ios-qa-regen` | Regenerate the canonical local DebugBridge package and typed accessors (`--app-source` / `--bridge-dir`). |\n\nEnd-to-end walkthrough: [docs/howto-ios-testing-with-gstack.md](docs/howto-ios-testing-with-gstack.md).\n\n### Safety + scoping\n\n| Skill | What it does |\n|-------|-------------|\n| `/careful` | Warn before destructive commands (rm -rf, DROP TABLE, force-push). |\n| `/freeze` | Lock edits to one directory. Hard block, not just a warning. |\n| `/guard` | Activate both careful + freeze at once. |\n| `/unfreeze` | Remove directory edit restrictions. |\n| `/make-pdf` | Turn any markdown file into a publication-quality PDF. |\n| `/diagram` | English in, diagram out: mermaid source + editable .excalidraw + SVG/PNG, offline. |\n\n## Build commands\n\n```bash\nbun install              # install dependencies\nbun test                 # run free tests (no API spend)\nbun run test:windows     # curated Windows-safe subset (runs on windows-latest)\nbun run build            # generate docs + compile binaries\nbun run gen:skill-docs   # regenerate SKILL.md files from templates\nbun run skill:check      # health dashboard for all skills\n```\n\n## Platform support\n\n- **macOS** + **Linux**: full test suite supported.\n- **Windows**: curated Windows-safe subset runs on `windows-latest` via the\n  `windows-free-tests` CI job. Setup script (`./setup`) requires Git Bash or\n  MSYS today; native PowerShell support is a future expansion. The `bin/gstack-paths`\n  helper resolves state roots through `CLAUDE_PLUGIN_DATA` / `GSTACK_HOME` so plugin\n  installs work on every platform.\n\n## Key conventions\n\n- SKILL.md files are **generated** from `.tmpl` templates. Edit the template, not the output.\n- Run `bun run gen:skill-docs --host codex` to regenerate Codex-specific output.\n- The browse binary provides headless browser access. Use `$B <command>` in skills.\n- Safety skills (careful, freeze, guard) use inline advisory prose — always confirm before destructive operations.\n- State paths resolve via `bin/gstack-paths` (sourced via `eval \"$(...)\"`). Honors `GSTACK_HOME`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLANS_DIR`.\n- The `claude` CLI binary resolves via `browse/src/claude-bin.ts` (`Bun.which()` + `GSTACK_CLAUDE_BIN` override). Set `GSTACK_CLAUDE_BIN=wsl` plus `GSTACK_CLAUDE_BIN_ARGS='[\"claude\"]'` to run Claude through WSL on Windows.\n","CLAUDE.md":"# gstack development\n\n## Commands\n\n```bash\nbun install          # install dependencies\nbun test             # run free tests (browse + snapshot + skill validation)\nbun run test:evals   # run paid evals: LLM judge + E2E (diff-based, ~$4/run max)\nbun run test:evals:all  # run ALL paid evals regardless of diff\nbun run test:gate    # run gate-tier tests only (CI default, blocks merge)\nbun run test:periodic  # run periodic-tier tests only (weekly cron / manual)\nbun run test:gate:sharded    # gate tier via the sharded paid runner (one Bun process per test file)\nbun run test:periodic:sharded  # periodic tier via the sharded paid runner (implies EVALS_ALL=1)\nbun run test:e2e     # run E2E tests only (diff-based, ~$3.85/run max)\nbun run test:e2e:all # run ALL E2E tests regardless of diff\nbun run eval:select  # show which tests would run based on current diff\nbun run dev <cmd>    # run CLI in dev mode, e.g. bun run dev goto https://example.com\nbun run build        # gen docs + compile binaries\nbun run gen:skill-docs  # regenerate SKILL.md files from templates\nbun run skill:check  # health dashboard for all skills\nbun run dev:skill    # watch mode: auto-regen + validate on change\nbun run eval:list    # list all eval runs from ~/.gstack-dev/evals/\nbun run eval:compare # compare two eval runs (auto-picks most recent)\nbun run eval:summary # aggregate stats across all eval runs\nbun run slop          # full slop-scan report (all files)\nbun run slop:diff     # slop findings in files changed on this branch only\n```\n\n`test:evals` requires `ANTHROPIC_API_KEY`. Codex E2E tests (`test/codex-e2e.test.ts`)\nuse Codex's own auth from `~/.codex/` config — no `OPENAI_API_KEY` env var needed.\n\n**Env keys in Conductor workspaces.** The `GSTACK_*` env-shim (v1.39.2.0+,\n`lib/conductor-env-shim.ts`) promotes `GSTACK_ANTHROPIC_API_KEY` /\n`GSTACK_OPENAI_API_KEY` to their canonical names inside gstack's TS binaries.\nTests run through gstack entrypoints inherit this promotion automatically.\nDon't echo the key value to stdout, logs, or shell history. The historical\n\"never pass `env:` to `runAgentSdkTest`\" rule is retired: the failure was\npartial-env replacement (the SDK's `Options.env` REPLACES the child's entire\nenvironment, so an object without the key broke auth). The runner now always\npasses a COMPLETE hermetic env with per-test `env:` merged last, so per-test\noverrides are safe; ambient `process.env.ANTHROPIC_API_KEY` mutation also\nstill works (the env builder reads process.env at call time).\n\n**Hermetic local E2E (default).** Every E2E runner (claude -p, PTY, Agent\nSDK, codex, gemini) spawns children through `test/helpers/hermetic-env.ts`:\nallowlist-scrubbed env (operator `CONDUCTOR_*`, `CLAUDE_*`, `GSTACK_*`,\n`MCP_*`, `GBRAIN_*`, and credentials like `GH_TOKEN` never reach children),\na fresh seeded `CLAUDE_CONFIG_DIR` (no operator `~/.claude` CLAUDE.md /\nMCP servers / skills), a temp `GSTACK_HOME`, and `--strict-mcp-config`.\nLocal eval signal matches CI. Debug against real operator state with\n`EVALS_HERMETIC=0` (restores the legacy env AND drops the strict-MCP flag).\nPer-test `env:` overrides merge last, so deliberate contamination\n(`CONDUCTOR_WORKSPACE_PATH`, per-test `GSTACK_HOME`) keeps working. The\nhermetic config dir seeds NO skills by default; a PTY test that types a\n`/skill` slash command must pass `seedSkills: true` to the PTY runner, which\npoints the child's `CLAUDE_CONFIG_DIR` at `hermeticSkillsConfigDir()` — a\nseeded registry that symlinks the LIVE working tree's SKILL.md files (by\ndesign: the skills ARE the subject under test; a snapshot would measure stale\ncopies). Wiring is pinned by `test/hermetic-wiring.test.ts` (static tripwire),\ntwo gate-tier canaries in `test/skill-e2e-hermetic-canary.test.ts`, and the\nseeding tripwires in `test/hermetic-skills-seeding.test.ts` /\n`test/pty-skill-seeding-wiring.test.ts`.\n\nE2E tests stream progress in real-time (tool-by-tool via `--output-format stream-json\n--verbose`). Results are persisted to `~/.gstack-dev/evals/` with auto-comparison\nagainst the previous finalized run (in-flight `_partial` files are never used as\na baseline, so a run can't compare against itself).\n\n**Diff-based test selection:** `test:evals` and `test:e2e` auto-select tests based\non `git diff` against the base branch. Each test declares its file dependencies in\n`test/helpers/touchfiles.ts`. Changes to global touchfiles (session-runner, eval-store,\ntouchfiles.ts itself) trigger all tests. Use `EVALS_ALL=1` or the `:all` script\nvariants to force all tests. Run `eval:select` to preview which tests would run.\n\n**Two-tier system:** Tests are classified as `gate` or `periodic` in `E2E_TIERS`\n(in `test/helpers/touchfiles.ts`). CI runs only gate tests (`EVALS_TIER=gate`);\nperiodic tests run weekly via cron or manually. Use `EVALS_TIER=gate` or\n`EVALS_TIER=periodic` to filter. When adding new E2E tests, classify them:\n1. Safety guardrail or deterministic functional test? -> `gate`\n2. Quality benchmark, Opus model test, or non-deterministic? -> `periodic`\n3. Requires external service (Codex, Gemini)? -> `periodic`\n\nTier declarations are enforced by `test/e2e-tier-alignment.test.ts` (free, runs\nin `bun test`): a `skill-e2e-*` file named in a touchfiles dep list whose\n`EVALS_TIER` self-gate disagrees with its declared tier in `E2E_TIERS` fails the\nsuite. Files not named in any dep list are reported, not enforced — keep both\nin sync.\n\n## Testing\n\n```bash\nbun test             # run before every commit — free, <2s\nbun run test:evals   # run before shipping — paid, diff-based (~$4/run max)\n```\n\n`bun test` runs skill validation, gen-skill-docs quality checks, and browse\nintegration tests. `bun run test:evals` runs LLM-judge quality evals and E2E\ntests via `claude -p`. Both must pass before creating a PR.\n\n## Project structure\n\n```\ngstack/\n├── browse/          # Headless browser CLI (Playwright)\n│   ├── src/         # CLI + server + commands\n│   │   ├── commands.ts  # Command registry (single source of truth)\n│   │   └── snapshot.ts  # SNAPSHOT_FLAGS metadata array\n│   ├── test/        # Integration tests + fixtures\n│   └── dist/        # Compiled binary\n├── hosts/           # Typed host configs (one per AI agent)\n│   ├── claude.ts    # Primary host config\n│   ├── codex.ts, factory.ts, kiro.ts  # Existing hosts\n│   ├── opencode.ts, slate.ts, cursor.ts, openclaw.ts  # IDE hosts\n│   ├── hermes.ts, gbrain.ts  # Agent runtime hosts\n│   └── index.ts     # Registry: exports all, derives Host type\n├── scripts/         # Build + DX tooling\n│   ├── gen-skill-docs.ts  # Template → SKILL.md generator (config-driven)\n│   ├── host-config.ts     # HostConfig interface + validator\n│   ├── host-config-export.ts  # Shell bridge for setup script\n│   ├── host-adapters/     # Host-specific adapters (OpenClaw tool mapping)\n│   ├── resolvers/   # Template resolver modules (preamble, design, review, gbrain, etc.)\n│   ├── skill-check.ts     # Health dashboard\n│   ├── test-paid-shards.ts  # Sharded paid-tier runner (one Bun process per shard)\n│   └── dev-skill.ts       # Watch mode\n├── test/            # Skill validation + eval tests\n│   ├── helpers/     # skill-parser.ts, session-runner.ts, llm-judge.ts, eval-store.ts\n│   ├── fixtures/    # Ground truth JSON, planted-bug fixtures, eval baselines\n│   ├── skill-validation.test.ts  # Tier 1: static validation (free, <1s)\n│   ├── gen-skill-docs.test.ts    # Tier 1: generator quality (free, <1s)\n│   ├── skill-llm-eval.test.ts   # Tier 3: LLM-as-judge (~$0.15/run)\n│   └── skill-e2e-*.test.ts       # Tier 2: E2E via claude -p (~$3.85/run, split by category)\n├── qa-only/         # /qa-only skill (report-only QA, no fixes)\n├── plan-design-review/  # /plan-design-review skill (report-only design audit)\n├── design-review/    # /design-review skill (design audit + fix loop)\n├── ship/            # Ship workflow skill\n├── review/          # PR review skill\n├── plan-ceo-review/ # /plan-ceo-review skill\n├── plan-eng-review/ # /plan-eng-review skill\n├── autoplan/        # /autoplan skill (auto-review pipeline: CEO → design → eng)\n├── benchmark/       # /benchmark skill (performance regression detection)\n├── canary/          # /canary skill (post-deploy monitoring loop)\n├── codex/           # /codex skill (multi-AI second opinion via OpenAI Codex CLI)\n├── land-and-deploy/ # /land-and-deploy skill (merge → deploy → canary verify)\n├── office-hours/    # /office-hours skill (YC Office Hours — startup diagnostic + builder brainstorm)\n├── investigate/     # /investigate skill (systematic root-cause debugging)\n├── spec/            # /spec skill (five-phase spec → GitHub issue, optional agent spawn, /ship auto-closes)\n├── retro/           # Retrospective skill (includes /retro global cross-project mode)\n├── bin/             # CLI utilities (gstack-repo-mode, gstack-slug, gstack-config, etc.)\n├── document-release/ # /document-release skill (post-ship doc updates + Diataxis coverage map)\n├── document-generate/ # /document-generate skill (Diataxis doc generator: tutorial/how-to/reference/explanation)\n├── cso/             # /cso skill (OWASP Top 10 + STRIDE security audit)\n├── design-consultation/ # /design-consultation skill (design system from scratch)\n├── design-shotgun/  # /design-shotgun skill (visual design exploration)\n├── open-gstack-browser/  # /open-gstack-browser skill (launch GStack Browser)\n├── connect-chrome/  # symlink → open-gstack-browser (backwards compat)\n├── design/          # Design binary CLI (GPT Image API)\n│   ├── src/         # CLI + commands (generate, variants, compare, serve, etc.)\n│   ├── test/        # Integration tests\n│   └── dist/        # Compiled binary\n├── extension/       # Chrome extension (side panel + activity feed + CSS inspector)\n├── lib/             # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts)\n├── docs/designs/    # Design documents\n├── setup-deploy/    # /setup-deploy skill (one-time deploy config)\n├── .github/         # CI workflows + Docker image\n│   ├── workflows/   # evals.yml (E2E on Ubicloud), skill-docs.yml, actionlint.yml\n│   └── docker/      # Dockerfile.ci (pre-baked toolchain + Playwright/Chromium)\n├── contrib/         # Contributor-only tools (never installed for users)\n│   └── add-host/    # /gstack-contrib-add-host skill\n├── setup            # One-time setup: build binary + symlink skills\n├── SKILL.md         # Generated from SKILL.md.tmpl (don't edit directly)\n├── SKILL.md.tmpl    # Template: edit this, run gen:skill-docs\n├── ETHOS.md         # Builder philosophy (Boil the Ocean, Search Before Building)\n└── package.json     # Build scripts for browse\n```\n\n## SKILL.md workflow\n\nSKILL.md files are **generated** from `.tmpl` templates. To update docs:\n\n1. Edit the `.tmpl` file (e.g. `SKILL.md.tmpl` or `browse/SKILL.md.tmpl`)\n2. Run `bun run gen:skill-docs` (or `bun run build` which does it automatically)\n3. Commit both the `.tmpl` and generated `.md` files\n\nTo add a new browse command: add it to `browse/src/commands.ts` and rebuild.\nTo add a snapshot flag: add it to `SNAPSHOT_FLAGS` in `browse/src/snapshot.ts` and rebuild.\n\n**Token ceiling:** Generated SKILL.md files trip a warning above 160KB (~40K tokens).\nThis is a \"watch for feature bloat\" guardrail, not a hard gate. Modern flagship\nmodels have 200K-1M context windows, so 40K is 4-20% of window, and prompt caching\nmakes the marginal cost of larger skills small. The ceiling exists to catch runaway\npreamble/resolver growth, not to force compression on carefully-tuned big skills\n(`ship`, `plan-ceo-review`, `office-hours` legitimately pack 25-35K tokens of\nbehavior). If you blow past 40K, the right fix is usually: (1) look at WHAT grew,\n(2) if one resolver added 10K+ in a single PR, question whether it belongs inline\nor as a reference doc, (3) only compress carefully-tuned prose as a last resort —\ncuts to the coverage audit, review army, or voice directive have real quality cost.\n\nA second, harder ceiling guards the DISCOVERY surface: `test/catalog-budget.test.ts`\ncaps the aggregate frontmatter `name` + `description` across all skills at 1,150\ntoken-equivalents (260-byte per-skill sub-cap), counted through the shared census\nin `test/helpers/skill-census.ts`. This one is enforced, not a warning — every\nhost loads the full catalog every session, so growth here taxes every\nconversation. The failure message carries the re-measure + ratchet protocol.\n`bin/gstack-context-bill` shows the full token bill-of-materials for a skills\ntree (always-on vs per-invocation, `--diff`, `--budget`; `--exact` opts into the\nreal tokenizer and POSTs file text to api.anthropic.com with an egress receipt).\n\n**Merge conflicts on SKILL.md files:** NEVER resolve conflicts on generated SKILL.md\nfiles by accepting either side. Instead: (1) resolve conflicts on the `.tmpl` templates\nand `scripts/gen-skill-docs.ts` (the sources of truth), (2) run `bun run gen:skill-docs`\nto regenerate all SKILL.md files, (3) stage the regenerated files. Accepting one side's\ngenerated output silently drops the other side's template changes.\n\n## Platform-agnostic design\n\nSkills must NEVER hardcode framework-specific commands, file patterns, or directory\nstructures. Instead:\n\n1. **Read CLAUDE.md** for project-specific config (test commands, eval commands, etc.)\n2. **If missing, AskUserQuestion** — let the user tell you or let gstack search the repo\n3. **Persist the answer to CLAUDE.md** so we never have to ask again\n\nThis applies to test commands, eval commands, deploy commands, and any other\nproject-specific behavior. The project owns its config; gstack reads it.\n\n## Writing SKILL templates\n\nSKILL.md.tmpl files are **prompt templates read by Claude**, not bash scripts.\nEach bash code block runs in a separate shell — variables do not persist between blocks.\n\nRules:\n- **Use natural language for logic and state.** Don't use shell variables to pass\n  state between code blocks. Instead, tell Claude what to remember and reference\n  it in prose (e.g., \"the base branch detected in Step 0\").\n- **Don't hardcode branch names.** Detect `main`/`master`/etc dynamically via\n  `gh pr view` or `gh repo view`. Use `{{BASE_BRANCH_DETECT}}` for PR-targeting\n  skills. Use \"the base branch\" in prose, `<base>` in code block placeholders.\n- **Keep bash blocks self-contained.** Each code block should work independently.\n  If a block needs context from a previous step, restate it in the prose above.\n- **Express conditionals as English.** Instead of nested `if/elif/else` in bash,\n  write numbered decision steps: \"1. If X, do Y. 2. Otherwise, do Z.\"\n\n## Writing style (V1)\n\nDefault output from every tier-≥2 skill follows the Writing Style section in\n`scripts/resolvers/preamble.ts`: jargon glossed on first use (curated list in\n`scripts/jargon-list.json`, baked at gen-skill-docs time), questions framed in\noutcome terms (\"what breaks for your users if...\") not implementation terms,\nshort sentences, decisions close with user impact. Power users who want the\ntighter V0 prose set `gstack-config set explain_level terse` (binary switch,\nno middle mode). See `docs/designs/PLAN_TUNING_V1.md` for the full design\nrationale. The review pacing overhaul that originally tried to ride alongside\nwriting-style was extracted to V1.1 — see `docs/designs/PACING_UPDATES_V0.md`.\n\n## Browser interaction\n\nWhen you need to interact with a browser (QA, dogfooding, cookie setup), use the\n`/browse` skill or run the browse binary directly via `$B <command>`. NEVER use\n`mcp__claude-in-chrome__*` tools — they are slow, unreliable, and not what this\nproject uses.\n\n**Sidebar architecture:** Before modifying `sidepanel.js`, `background.js`,\n`content.js`, `terminal-agent.ts`, or sidebar-related server endpoints,\nread `docs/designs/SIDEBAR_MESSAGE_FLOW.md`. The sidebar has one primary\nsurface — the **Terminal** pane (interactive `claude` PTY) — with\nActivity / Refs / Inspector as debug overlays behind the footer's\n`debug` toggle. The chat queue path was ripped once the PTY proved out;\n`sidebar-agent.ts` and the `/sidebar-command` / `/sidebar-chat` /\n`/sidebar-agent/event` endpoints are gone. The doc covers the WS auth\nflow, dual-token model, and threat-model boundary — silent failures\nhere usually trace to not understanding the cross-component flow.\n\n**Embedder terminal-agent ownership** (v1.42.1.0+, identity-based kill v1.44.0.0+).\n`buildFetchHandler` in `browse/src/server.ts` accepts `ServerConfig.ownsTerminalAgent?:\nboolean` (default `true`). When `true`, factory shutdown runs the full teardown:\nidentity-based kill via `killAgentByRecord(readAgentRecord(stateDir))` from\n`browse/src/terminal-agent-control.ts` plus `safeUnlinkQuiet` on\n`<stateDir>/terminal-port`, `<stateDir>/terminal-internal-token`, and\n`<stateDir>/terminal-agent-pid` (the per-boot agent record introduced in v1.44).\nEmbedders (e.g. the gbrowser phoenix overlay) that pre-launch their own PTY\nserver must pass `false` so their discovery files survive gstack teardown cycles.\nThe flag is the third caller-owned teardown gate in `ServerConfig` (alongside\n`xvfb?` and `proxyBridge?`); polarity is inverted (explicit bool vs presence) and\ndocumented in the field's JSDoc. CLI `start()` always passes `true` explicitly —\nthe static-grep test in `browse/test/server-embedder-terminal-port.test.ts` fails\nCI if a refactor drops it. Pre-v1.44 used `pkill -f terminal-agent\\.ts` (regex\nmatch) which would kill sibling gstack sessions on the same host; the new\n`browse/test/terminal-agent-pid-identity.test.ts` static-grep tripwire fails CI\nif any source file re-introduces `pkill ... terminal-agent` or `spawnSync('pkill', ...)`.\n\n**WebSocket auth uses Sec-WebSocket-Protocol, not cookies.** Browsers\ncan't set `Authorization` on a WebSocket upgrade, but they CAN set\n`Sec-WebSocket-Protocol` via `new WebSocket(url, [token])`. The agent\nreads it, validates against `validTokens`, and MUST echo the protocol\nback in the upgrade response — without the echo, Chromium closes the\nconnection immediately. `Set-Cookie: gstack_pty=...` is kept as a\nfallback for non-browser callers (the cross-port `SameSite=Strict`\ncookie path doesn't survive from a chrome-extension origin).\n\n**Cross-pane PTY injection.** The toolbar's Cleanup button and the\nInspector's \"Send to Code\" action both pipe text into the live claude\nPTY via `window.gstackInjectToTerminal(text)`, exposed by\n`sidepanel-terminal.js`. No `/sidebar-command` POST — the live REPL is\nthe only execution surface in the sidebar now.\n\n**`/health` MUST NOT surface any token — and it no longer does** (v1.63+).\nThe historical headed-mode leak of `AUTH_TOKEN` is fixed: `GET /health` is\nliveness/status only in every mode. Token bootstrap is `POST /extension-token`,\nwhich validates the caller's Origin against the pinned extension identity\n(the `key` field in `extension/manifest.json` pins the extension ID —\n`GSTACK_EXTENSION_ID` in `browse/src/server.ts`, derivation reproducible via\n`bun browse/scripts/extension-id.ts`) plus a loopback Host. PTY auth still\nflows through `POST /pty-session` only. Don't add any token to `/health`.\n\n**Transport-layer security** (v1.6.0.0+). When `pair-agent` starts an ngrok tunnel,\nthe daemon binds two HTTP listeners: a local listener (127.0.0.1, full command\nsurface, never forwarded) and a tunnel listener (locked allowlist: `/connect`,\n`/command` with a scoped token + 26-command browser-driving allowlist,\n`/sidebar-chat`). ngrok forwards only the tunnel port. Root tokens over the tunnel\nreturn 403. SSE endpoints use a 30-minute HttpOnly `gstack_sse` cookie minted via\n`POST /sse-session` (never valid against `/command`). Tunnel-surface rejections go\nto `~/.gstack/security/attempts.jsonl` via `tunnel-denial-log.ts`. Before editing\n`server.ts`, `sse-session-cookie.ts`, or `tunnel-denial-log.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#dual-listener-tunnel-architecture-v1600) —\nthe module boundary (no imports from `token-registry.ts` into `sse-session-cookie.ts`)\nis load-bearing for scope isolation.\n\n**Unicode sanitization at server egress** (v1.38.0.0+). Every server egress that\nships page-content-derived strings MUST go through `JSON.stringify(payload,\nsanitizeReplacer)` for object payloads or `sanitizeLoneSurrogates(body)` for text\nbodies. Lone UTF-16 surrogate halves from CDP page content otherwise reach the\nAnthropic API as `\\uD800`-style escapes and trigger a 400. Wired at four egress\npoints today: `handleCommandInternal` (HTTP + batch via a sanitizing wrapper around\n`handleCommandInternalImpl`) and both SSE producers (`/activity/stream`,\n`/inspector/events`). Post-stringify regex is a no-op — `JSON.stringify` has\nalready escaped the surrogate before regex could match, so the replacer must run\ninside the encoding pipeline. Before adding a new SSE/WebSocket writer or HTTP\nresponse in `server.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#unicode-sanitization-at-server-egress-v13800).\n`browse/test/server-sanitize-surrogates.test.ts` pins the wiring with invariant\ntests, so bypasses fail CI.\n\n**Egress receipts at every off-machine sink** (v1.63.0.0+). Every gstack-initiated\nsend off the machine MUST write a hash-chained receipt to\n`~/.gstack/security/egress.jsonl` BEFORE the send: TypeScript callers use\n`writeReceipt` from `lib/egress-receipt.ts`; shell scripts source\n`bin/gstack-egress-lib.sh` and use `_receipted_curl` / `_receipted_git`. Failure\npolarity is per-class: fail-closed for sensitive sinks (brain-sync, memory-ingest,\ngbrain-sync, telemetry, ngrok tunnels, mcp-verify, supabase-provision), fail-open\n+ stderr warning for user-facing ones (design OpenAI calls, update-check,\ndashboards, git-class ops). The new-sink scanner in\n`test/egress-receipt-wiring.test.ts` fails CI on an unreceipted `curl` /\n`git push` / `fetch` to a non-loopback host unless the file carries a reasoned\nentry in its `SCANNER_EXEMPT` list (user-directed page fetches, reachability\nprobes, instruction strings, skill prose) — if you add a new off-machine sink,\nwire it through the helpers and add it to the enumerated sink list. Inspect with\n`bin/gstack-egress` (`list` | `verify`, exit 3 on tamper | `grants`). Threat\nmodel: forensic observability of ATTEMPTED egress, not an exfiltration control.\n\n**SSE endpoint helper** (v1.51.0.0+). New SSE endpoints in `server.ts` MUST route\nthrough `createSseEndpoint(req, config)` from `browse/src/sse-helpers.ts`. The\nhelper owns the cleanup contract (abort + enqueue-throw + heartbeat-throw, all\nidempotent) and bakes in `sanitizeLoneSurrogates` on every JSON.stringify, so\nnew subscribers can't accidentally regress either invariant. Inline\n`ReadableStream` wiring leaked subscribers when the TCP connection died without\nfiring `req.signal.abort` (Chromium MV3 service-worker suspend, intermediate\nproxy half-close). `/activity/stream`, `/inspector/events`, and `/memory`\n(SSE-eligible) all route through it. `browse/test/sse-helpers.test.ts` pins the\ncleanup contract.\n\n**CDP session lifecycle** (v1.51.0.0+). Direct `page.context().newCDPSession(page)`\ncalls outside `browse/src/cdp-bridge.ts` fail CI via the static-grep tripwire in\n`browse/test/cdp-session-cleanup.test.ts`. Use `withCdpSession(page, async (s) => {...})`\nfor one-shot CDP work (try/finally detach) or `getOrCreateCdpSession(page, cache)`\nfor cached sessions tied to a page's lifetime (close-detach via `Map<page, session>`).\nThree sites migrated: cdp-bridge frame events, write-commands archive capture,\ncdp-inspector. The helpers prevent the per-session leak class where successful-path\ndetach happened but error-path detach was missed.\n\n**Setup symlink hardening** (v1.38.0.0+). Every link site in `setup` MUST route\nthrough the `_link_or_copy SRC DST` helper near the `IS_WINDOWS` detection. On\nWindows without Developer Mode, plain `ln -snf` produces frozen file copies that\ndon't refresh on `git pull` — silent staleness across every host adapter. The\nhelper preserves `ln -snf` on Unix and switches to `cp -R` / `cp -f` on Windows.\n`test/setup-windows-fallback.test.ts` enforces a static invariant: a single raw\n`ln` call outside the helper body fails CI. Windows users get a one-line note\nfrom `_print_windows_copy_note_once` reminding them to re-run `./setup` after\nevery `git pull`.\n\n**Sidebar security stack** (layered defense against prompt injection):\n\n| Layer | Module | Lives in |\n|-------|--------|----------|\n| L1-L3 | `content-security.ts` | both server and agent — datamarking, hidden element strip, ARIA regex, URL blocklist, envelope wrapping |\n| L4 | `security-classifier.ts` (TestSavantAI ONNX) | **sidebar-agent only** |\n| L4b | `security-classifier.ts` (Claude Haiku transcript) | **sidebar-agent only** |\n| L5 | `security.ts` (canary) | both — inject in compiled, check in agent |\n| L6 | `security.ts` (combineVerdict ensemble) | both |\n\n**Critical constraint:** `security-classifier.ts` CANNOT be imported from the\ncompiled browse binary. `@huggingface/transformers` v4 requires `onnxruntime-node`\nwhich fails to `dlopen` from Bun compile's temp extract dir. Only `security.ts`\n(pure-string operations — canary, verdict combiner, attack log, status) is safe\nfor `server.ts`. See `~/.gstack/projects/garrytan-gstack/ceo-plans/2026-04-19-prompt-injection-guard.md`\n§\"Pre-Impl Gate 1 Outcome\" for full architectural decision.\n\n**Thresholds** (in `security.ts`):\n- `BLOCK: 0.85` — single-layer score that would cause BLOCK if cross-confirmed\n- `WARN: 0.75` — cross-confirm threshold. When L4 AND L4b both >= 0.75 → BLOCK\n- `LOG_ONLY: 0.40` — gates transcript classifier (skip Haiku when all layers < 0.40)\n- `SOLO_CONTENT_BLOCK: 0.92` — single-layer threshold for label-less content classifiers\n  (testsavant, deberta). Intentionally higher than `BLOCK` because these layers can't\n  distinguish \"this is an injection\" from \"this looks like phishing aimed at the user.\"\n  The transcript classifier keeps a separate, label-gated solo path at `BLOCK` (0.85).\n\n**Ensemble rule:** BLOCK only when the ML content classifier AND the transcript\nclassifier both report >= WARN. Single-layer high confidence degrades to WARN —\nthis is the Stack Overflow instruction-writing FP mitigation. Canary leak\nalways BLOCKs (deterministic).\n\n**Env knobs:**\n- `GSTACK_SECURITY_OFF=1` — emergency kill switch. Classifier stays off even if\n  warmed. Canary is still injected; just the ML scan is skipped.\n- `GSTACK_SECURITY_ENSEMBLE=deberta` — opt-in DeBERTa-v3 ensemble. Adds\n  ProtectAI DeBERTa-v3-base-injection-onnx as L4c classifier for cross-model\n  agreement. 721MB first-run download. With ensemble enabled, BLOCK requires\n  2-of-3 ML classifiers agreeing at >= WARN (testsavant, deberta, transcript).\n  Without ensemble (default), BLOCK requires testsavant + transcript at >= WARN.\n- Classifier model cache: `~/.gstack/models/testsavant-small/` (112MB, first run only)\n  plus `~/.gstack/models/deberta-v3-injection/` (721MB, only when ensemble enabled)\n- Attack log: `~/.gstack/security/attempts.jsonl` (salted sha256 + domain only,\n  rotates at 10MB, 5 generations)\n- Per-device salt: `~/.gstack/security/device-salt` (0600)\n- Session state: `~/.gstack/security/session-state.json` (cross-process, atomic)\n\n## Dev symlink awareness\n\nWhen developing gstack, `.claude/skills/gstack` may be a symlink back to this\nworking directory (gitignored). This means skill changes are **live immediately**,\ngreat for rapid iteration, risky during big refactors where half-written skills\ncould break other Claude Code sessions using gstack concurrently.\n\n**Check once per session:** Run `ls -la .claude/skills/gstack` to see if it's a\nsymlink or a real copy. If it's a symlink to your working directory, be aware that:\n- Template changes + `bun run gen:skill-docs` immediately affect all gstack invocations\n- Breaking changes to SKILL.md.tmpl files can break concurrent gstack sessions\n- During large refactors, remove the symlink (`rm .claude/skills/gstack`) so the\n  global install at `~/.claude/skills/gstack/` is used instead\n\n**Prefix setting:** Setup creates real directories (not symlinks) at the top level\nwith a SKILL.md symlink inside (e.g., `qa/SKILL.md -> gstack/qa/SKILL.md`). This\nensures Claude discovers them as top-level skills, not nested under `gstack/`.\nNames are either short (`qa`) or namespaced (`gstack-qa`), controlled by\n`skill_prefix` in `~/.gstack/config.yaml`. Pass `--no-prefix` or `--prefix` to\nskip the interactive prompt.\n\n**Note:** Vendoring gstack into a project's repo is deprecated. Use global install\n+ `./setup --team` instead. See README.md for team mode instructions.\n\n**For plan reviews:** When reviewing plans that modify skill templates or the\ngen-skill-docs pipeline, consider whether the changes should be tested in isolation\nbefore going live (especially if the user is actively using gstack in other windows).\n\n**Upgrade migrations:** When a change modifies on-disk state (directory structure,\nconfig format, stale files) in ways that could break existing user installs, add a\nmigration script to `gstack-upgrade/migrations/`. Read CONTRIBUTING.md's \"Upgrade\nmigrations\" section for the format and testing requirements. The upgrade skill runs\nthese automatically after `./setup` during `/gstack-upgrade`.\n\n## Compiled binaries — never commit browse/dist/, design/dist/, or make-pdf/dist/\n\nThe `browse/dist/`, `design/dist/`, and `make-pdf/dist/` directories contain\ncompiled Bun binaries (`browse`, `find-browse`, `design`, ~62MB each). These are\nMach-O arm64 only — they do NOT work on Linux, Windows, or Intel Macs. The\n`./setup` script builds from source for every platform.\n\nThese directories are **untracked and gitignored** (`.gitignore:3-6`; the\n`browse/dist/` binaries were untracked in `64d5a3e4`, v0.11.16.0; the others were\nnever tracked). They will NOT appear in `git status`. If a dist binary ever does\nshow up in `git status`, something force-added it (`git add -f`) — do not commit\nit; unstage it and find out how it got there.\n\nWhen staging files, always use specific filenames (`git add file1 file2`) — never\n`git add .` or `git add -A`, which can sweep in build outputs and junk.\n\n## Redaction guard (PII / secrets / legal content)\n\nShared redaction engine catches credentials, PII, and legal/damaging content\nbefore it reaches an external sink (codex dispatch, GitHub issue/PR body, pushed\ncommit). It is a **guardrail, not airtight enforcement** — `git push --no-verify`,\ndirect `gh issue create`, and `GSTACK_REDACT_PREPUSH=skip` all bypass it. It\ncatches accidents and carelessness, the 99% case. Do not claim it stops a\ndetermined leaker (a CHANGELOG line that does would fail a hostile screenshotter).\n\n- **Engine + taxonomy:** `lib/redact-patterns.ts` (the single source of truth —\n  3 tiers; HIGH = genuinely-secret credentials that block, MEDIUM = PII/legal/\n  internal + high-FP credential shapes that confirm via AskUserQuestion, LOW =\n  FYI) and `lib/redact-engine.ts` (pure `scan()` + `applyRedactions()`).\n  Calibration matters: a gate that cries wolf gets ignored, so context-variable\n  shapes (Stripe `pk_live_`, Google `AIza`, JWT, env `*_KEY=`) sit at MEDIUM.\n- **CLI:** `bin/gstack-redact` (exit 0 clean / 2 MEDIUM / 3 HIGH; `--json`,\n  `--auto-redact`, `--repo-visibility`, `--from-file`). `bin/gstack-redact-prepush`\n  is the opt-in git hook.\n- **Skill docs are generated** from `scripts/resolvers/redact-doc.ts`\n  (`{{REDACT_TAXONOMY_TABLE}}`, `{{REDACT_INVOCATION_BLOCK:<sink>}}`) so /spec,\n  /cso, /ship, /document-release, /document-generate never drift from the engine.\n- **Scan-at-sink:** always scan the EXACT bytes that will be sent — write to a\n  temp file, scan that file, pass the SAME file to `gh`/`git`. Never scan a string\n  then re-render (that reopens a scan-vs-send gap).\n- **Visibility (no tier promotion):** resolve once per run, order = local config\n  (`gstack-config get redact_repo_visibility`, ~/.gstack so never committed) → gh\n  → glab → unknown(=public-strict). Public repos get STERNER per-finding\n  confirmation (no batch-acknowledge, no silent-proceed); MEDIUM is never\n  auto-promoted to HIGH.\n- **Tool-attributed fences:** wrap Codex/Greptile/eval output in ` ```codex-review `\n  / ` ```greptile ` fences so example credentials those tools quote WARN-degrade\n  instead of blocking. A live-format credential inside the fence still blocks.\n- **Config keys:** `redact_repo_visibility` (public|private|unknown, local-only\n  override for repos gh/glab can't read), `redact_prepush_hook` (true|false).\n  There is intentionally NO key to disable HIGH blocking.\n- **Audit:** the /spec semantic pass appends a content-free record (categories +\n  body sha256, no spec text) to `~/.gstack/security/semantic-reviews.jsonl` (0600).\n\n## Commit style\n\n**Always bisect commits.** Every commit should be a single logical change. When\nyou've made multiple changes (e.g., a rename + a rewrite + new tests), split them\ninto separate commits before pushing. Each commit should be independently\nunderstandable and revertable.\n\nExamples of good bisection:\n- Rename/move separate from behavior changes\n- Test infrastructure (touchfiles, helpers) separate from test implementations\n- Template changes separate from generated file regeneration\n- Mechanical refactors separate from new features\n\nWhen the user says \"bisect commit\" or \"bisect and push,\" split staged/unstaged\nchanges into logical commits and push.\n\n## Slop-scan: AI code quality, not AI code hiding\n\nWe use [slop-scan](https://github.com/benvinegar/slop-scan) to catch patterns where\nAI-generated code is genuinely worse than what a human would write. We are NOT trying\nto pass as human code. We are AI-coded and proud of it. The goal is code quality.\n\n```bash\nnpx slop-scan scan .          # human-readable report\nnpx slop-scan scan . --json   # machine-readable for diffing\n```\n\nConfig: `slop-scan.config.json` at repo root (currently excludes `**/vendor/**`).\n\n### What to fix (genuine quality improvements)\n\n- **Empty catches around file ops** — use `safeUnlink()` (ignores ENOENT, rethrows\n  EPERM/EIO). A swallowed EPERM in cleanup means silent data loss.\n- **Empty catches around process kills** — use `safeKill()` (ignores ESRCH, rethrows\n  EPERM). A swallowed EPERM means you think you killed something you didn't.\n- **Redundant `return await`** — remove when there's no enclosing try block. Saves a\n  microtask, signals intent.\n- **Typed exception catches** — `catch (err) { if (!(err instanceof TypeError)) throw err }`\n  is genuinely better than `catch {}` when the try block does URL parsing or DOM work.\n  You know what error you expect, so say so.\n\n### What NOT to fix (linter gaming, not quality)\n\n- **String-matching on error messages** — `err.message.includes('closed')` is brittle.\n  Playwright/Chrome can change wording anytime. If a fire-and-forget operation can fail\n  for ANY reason and you don't care, `catch {}` is the correct pattern.\n- **Adding comments to exempt pass-through wrappers** — \"alias for active session\" above\n  a method just to trip slop-scan's exemption rule is noise, not documentation.\n- **Converting extension catch-and-log to selective rethrow** — Chrome extensions crash\n  entirely on uncaught errors. If the catch logs and continues, that IS the right pattern\n  for extension code. Don't make it throw.\n- **Tightening best-effort cleanup paths** — shutdown, emergency cleanup, and disconnect\n  code should use `safeUnlinkQuiet()` (swallows ALL errors). A cleanup path that throws\n  on EPERM means the rest of cleanup doesn't run. That's worse.\n\n### Utilities in `browse/src/error-handling.ts`\n\n| Function | Use when | Behavior |\n|----------|----------|----------|\n| `safeUnlink(path)` | Normal file deletion | Ignores ENOENT, rethrows others |\n| `safeUnlinkQuiet(path)` | Shutdown/emergency cleanup | Swallows all errors |\n| `safeKill(pid, signal)` | Sending signals | Ignores ESRCH, rethrows others |\n| `isProcessAlive(pid)` | Boolean process checks | Returns true/false, never throws |\n\n### Score tracking\n\nBaseline (2026-04-09, before cleanup): 100 findings, 432.8 score, 2.38 score/file.\nAfter cleanup: 90 findings, 358.1 score, 1.96 score/file.\n\nDon't chase the number. Fix patterns that represent actual code quality problems.\nAccept findings where the \"sloppy\" pattern is the correct engineering choice.\n\n## Community PR guardrails\n\nWhen reviewing or merging community PRs, **always AskUserQuestion** before accepting\nany commit that:\n\n1. **Touches ETHOS.md** — this file is Garry's personal builder philosophy. No edits\n   from external contributors or AI agents, period.\n2. **Removes or softens promotional material** — YC references, founder perspective,\n   and product voice are intentional. PRs that frame these as \"unnecessary\" or\n   \"too promotional\" must be rejected.\n3. **Changes Garry's voice** — the tone, humor, directness, and perspective in skill\n   templates, CHANGELOG, and docs are not generic. PRs that rewrite voice to be\n   more \"neutral\" or \"professional\" must be rejected.\n\nEven if the agent strongly believes a change improves the project, these three\ncategories require explicit user approval via AskUserQuestion. No exceptions.\nNo auto-merging. No \"I'll just clean this up.\"\n\n## Checking out PRs from garrytan-agents\n\nWhen the user says \"check out <PR link>\" and the PR is from `garrytan-agents/gstack`\n(or any other fork that is NOT a collaborator on `garrytan/gstack`), do NOT just\n`gh pr checkout`. Fork PRs don't receive base-repo secrets (`ANTHROPIC_API_KEY`,\n`OPENAI_API_KEY`, etc.), so the eval/E2E CI jobs fail with empty-env auth errors\nregardless of what's set on the base repo.\n\n**Workflow:** push the branch to `garrytan/gstack` (the base repo) and re-target\nthe PR from there.\n\nConcretely, after `gh pr checkout <N>`:\n\n1. Note the original PR number and head branch name.\n2. Push the same branch to the base repo: `git push origin HEAD:<branch-name>`\n   (origin = `garrytan/gstack`, since the worktree is set up with that remote).\n3. Close the fork PR (`gh pr close <N> --comment \"moving to base-repo branch for secret access\"`).\n4. Open a new PR from the base-repo branch: `gh pr create --base main --head <branch-name>`.\n5. New PR's workflows will get secrets automatically.\n\nWhy not fix it on the fork side? `garrytan-agents` isn't a collaborator on\n`garrytan/gstack`. Adding it as a collaborator (option A) or flipping the\nrepo-wide \"send secrets to fork PRs\" toggle (option B) would let secrets reach\nfork PRs from anyone — broader blast radius than just moving this one branch.\nOption C (this section) keeps secret-distribution scope tight.\n\nIf the user asks you to skip the move (e.g., \"just leave it as a fork PR\"),\nrespect that — eval CI will fail with empty-env auth, but check-freshness,\nworkflow-lint, and windows-tests will still pass on the fork PR.\n\n## CHANGELOG + VERSION style\n\n**Versioning invariant (workspace-aware ship).** VERSION is a monotonic ordered\nrelease identifier, not a strict semver commitment. The bump level\n(major/minor/patch/micro) expresses intent at ship time. Queue-advancing past a\nclaimed version within the same bump level is explicitly permitted — if branch A\nclaims v1.7.0.0 as a MINOR and branch B is also a MINOR, B lands at v1.8.0.0\n(still a MINOR relative to main). Downstream consumers must NOT rely on\n\"MINOR = feature-only, PATCH = fix-only\" as a strict contract. This is why\n`bin/gstack-next-version` advances within the chosen bump level rather than\nrepicking the level when collisions happen.\n\n**Scale-aware bumps — use common sense.** When the diff is big, bump MINOR (or\nMAJOR), not PATCH. PATCH is for bug fixes and small additions; MINOR is for\nsubstantial new capability or substantial reduction; MAJOR is for breaking\nchanges. Rough guideposts (don't treat as rules, treat as smell-checks):\n\n- **PATCH (X.Y.Z+1.0)**: bug fix, doc tweak, small additive change, single\n  test/file added. Net diff under ~500 lines, no new user-facing capability.\n- **MINOR (X.Y+1.0.0)**: new capability shipped (skill, harness, command, big\n  refactor), substantial code reduction (compression, migration), or coordinated\n  multi-file change. Net diff over ~2000 lines added/removed, OR a user-visible\n  feature you'd put in a tweet.\n- **MAJOR (X+1.0.0.0)**: breaking change to public surface (CLI flag rename,\n  skill removed, config format changed), OR a release big enough to be the\n  headline of a blog post.\n\nIf you find yourself debating \"is 10K added + 24K removed really a PATCH?\" — it\nisn't. Bump MINOR. Same for \"this adds a whole new test harness with 6 new E2E\ntests + helper utilities\" — MINOR. The bump level is communication to the user\nabout what kind of release this is; don't undersell it.\n\nWhen merging origin/main brings a higher VERSION, re-evaluate the bump level\nagainst the SCALE of your branch's work, not just whether main moved forward.\nIf main bumped MINOR and your branch is also a substantial change, you bump\nMINOR again on top (e.g., main at v1.14.0.0, your branch lands v1.15.0.0).\n\n**VERSION and CHANGELOG are branch-scoped.** Every feature branch that ships gets its\nown version bump and CHANGELOG entry. The entry describes what THIS branch adds —\nnot what was already on main.\n\n**The CHANGELOG entry is the diff between main and the shipping branch — what users\nget when they upgrade. NOT how the branch got there.** A reader landing on the entry\nshould learn what they can do now that they couldn't before; they should not learn\nabout the branch's internal version bumps, the bugs we caught and fixed mid-branch,\nthe plan reviews we ran, or the commits we squashed. That is branch development\nnarrative. It belongs in PR descriptions and commit messages, not CHANGELOG.\n\n**Never reference branch-internal versions in a CHANGELOG entry.** If your branch\nbumped VERSION from v1.5.0.0 → v1.5.1.0 → v1.6.0.0 during development and only the\nfinal v1.6.0.0 ships to main, the entry must read as if v1.5.1.0 never existed.\nConcretely, NEVER write:\n- \"v1.5.1.0 had a bug that v1.6.0.0 fixes\" — readers don't know about v1.5.1.0; it's\n  a branch-internal artifact.\n- \"The shipping headline of v1.5.1.0 was broken because...\" — same reason. From main's\n  perspective, v1.5.1.0 was never released.\n- \"Pre-fix tests encoded the broken behavior\" — that's a contributor's victory lap,\n  not a user benefit.\n- \"Two surgical edits, both in the dispatch path\" — micro-narrative of the patch.\n\nInstead, describe the released system: \"Browser-skills run end-to-end with the\nexpected tab-access semantics.\" If a property of the shipped system is worth calling\nout (e.g., \"skill spawns get permissive tab access; pair-agent tunnel tokens require\nownership\"), document it as a property, not as a fix. The shipped system is what\nthe user gets; the path to that system is invisible to them.\n\n**When to write the CHANGELOG entry:**\n- At `/ship` time (Step 13), not during development or mid-branch.\n- The entry covers ALL commits on this branch vs the base branch.\n- Never fold new work into an existing CHANGELOG entry from a prior version that\n  already landed on main. If main has v0.10.0.0 and your branch adds features,\n  bump to v0.10.1.0 with a new entry — don't edit the v0.10.0.0 entry.\n\n**Key questions before writing:**\n1. What branch am I on? What did THIS branch change?\n2. Is the base branch version already released? (If yes, bump and create new entry.)\n3. Does an existing entry on this branch already cover earlier work? (If yes, replace\n   it with one unified entry for the final version.)\n\n**Merging main does NOT mean adopting main's version.** When you merge origin/main into\na feature branch, main may bring new CHANGELOG entries and a higher VERSION. Your branch\nstill needs its OWN version bump on top. If main is at v0.13.8.0 and your branch adds\nfeatures, bump to v0.13.9.0 with a new entry. Never jam your changes into an entry that\nalready landed on main. Your entry goes on top because your branch lands next.\n\n**After merging main, always check:**\n- Does CHANGELOG have your branch's own entry separate from main's entries?\n- Is VERSION higher than main's VERSION?\n- Is your entry the topmost entry in CHANGELOG (above main's latest)?\nIf any answer is no, fix it before continuing.\n\n**After any CHANGELOG edit that moves, adds, or removes entries,** immediately run\n`grep \"^## \\[\" CHANGELOG.md` to verify no duplicates and a sensible reverse-chronological\norder. Gaps between version numbers are fine. A branch that ships at v1.6.4.0 without\na prior v1.5.2.0 or v1.5.3.0 entry on main is correct — those were branch-internal\nversion numbers that never landed. Do not back-fill gaps with placeholder entries.\n\n**Never orphan branch-internal versions.** If your branch bumped VERSION several times\nduring development (v1.5.1.0 → v1.5.2.0 → v1.6.4.0, say) and those earlier entries were\nnever released to main, the final ship consolidates ALL of them into a single entry at\nthe final version (v1.6.4.0). Collapse them — delete the old entries and move their\ncontent into the final entry, re-version table columns accordingly. Readers see one\nrelease, not a branch diary. Gaps are fine (v1.6.3.0 → v1.6.4.0 with no v1.5.x\nin between on main is correct).\n\nCHANGELOG.md is **for users**, not contributors. Write it like product release notes:\n\n- Lead with what the user can now **do** that they couldn't before. Sell the feature.\n- Use plain language, not implementation details. \"You can now...\" not \"Refactored the...\"\n- **Never mention TODOS.md, internal tracking, eval infrastructure, or contributor-facing\n  details.** These are invisible to users and meaningless to them.\n- Put contributor/internal changes in a separate \"For contributors\" section at the bottom.\n- Every entry should make someone think \"oh nice, I want to try that.\"\n- No jargon: say \"every question now tells you which project and branch you're in\" not\n  \"AskUserQuestion format standardized across skill templates via preamble resolver.\"\n\n**Only document what shipped between main and this change.** Readers do not care how\nwe got here. Keep out of the CHANGELOG, always:\n\n- Branch resyncs, merge commits with main, rebase activity.\n- Plan approvals, review outcomes (CEO / eng / design / outside-voice / codex findings),\n  AskUserQuestion decisions, scope negotiations.\n- \"Work queued,\" \"plan approved,\" \"in-progress,\" \"will ship later\" — the CHANGELOG\n  documents what DID ship, not what MIGHT ship.\n- Version-bump housekeeping when no user-facing work actually landed.\n\nIf the diff between the base branch version and this version has no user-facing change\n(only merges, only CHANGELOG edits, only placeholder work), the honest entry is one\nsentence: \"Version bump for branch-ahead discipline. No user-facing changes yet.\" Stop\nthere. Do not pad. Do not explain the plan that will ship eventually. Do not narrate\nthe branch's history. When real work lands, the entry will replace this at /ship time.\n\n### Release-summary format (every `## [X.Y.Z]` entry)\n\nEvery version entry in `CHANGELOG.md` MUST start with a release-summary section in\nthe GStack/Garry voice, one viewport's worth of prose + tables that lands like a\nverdict, not marketing. The itemized changelog (subsections, bullets, files) goes\nBELOW that summary, separated by a `### Itemized changes` header.\n\nThe release-summary section gets read by humans, by the auto-update agent, and by\nanyone deciding whether to upgrade. The itemized list is for agents that need to\nknow exactly what changed.\n\nStructure for the top of every `## [X.Y.Z]` entry:\n\n1. **Two-line bold headline** (10-14 words total). Should land like a verdict, not\n   marketing. Sound like someone who shipped today and cares whether it works.\n2. **Lead paragraph** (3-5 sentences). What shipped, what changed for the user.\n   Specific, concrete, no AI vocabulary, no em dashes, no hype.\n3. **A \"The X numbers that matter\" section** with:\n   - One short setup paragraph naming the source of the numbers (real production\n     deployment OR a reproducible benchmark, name the file/command to run).\n   - A table of 3-6 key metrics with BEFORE / AFTER / Δ columns.\n   - A second optional table for per-category breakdown if relevant.\n   - 1-2 sentences interpreting the most striking number in concrete user terms.\n4. **A \"What this means for [audience]\" closing paragraph** (2-4 sentences) tying\n   the metrics to a real workflow shift. End with what to do.\n\nVoice rules for the release summary:\n- No em dashes (use commas, periods, \"...\").\n- No AI vocabulary (delve, robust, comprehensive, nuanced, fundamental, etc.) or\n  banned phrases (\"here's the kicker\", \"the bottom line\", etc.).\n- Real numbers, real file names, real commands. Not \"fast\" but \"~30s on 30K pages.\"\n- Short paragraphs, mix one-sentence punches with 2-3 sentence runs.\n- Connect to user outcomes: \"the agent does ~3x less reading\" beats \"improved precision.\"\n- Be direct about quality. \"Well-designed\" or \"this is a mess.\" No dancing.\n\nSource material:\n- CHANGELOG previous entry for prior context.\n- Benchmark files or `/retro` output for headline numbers.\n- Recent commits (`git log <prev-version>..HEAD --oneline`) for what shipped.\n- Don't make up numbers. If a metric isn't in a benchmark or production data,\n  don't include it. Say \"no measurement yet\" if asked.\n\nTarget length: ~250-350 words for the summary. Should render as one viewport.\n\n### Itemized changes (below the release summary)\n\nWrite `### Itemized changes` and continue with the detailed subsections (Added,\nChanged, Fixed, For contributors). Same rules as the user-facing voice guidance\nabove, plus:\n\n- **Always credit community contributions.** When an entry includes work from a\n  community PR, name the contributor with `Contributed by @username`. Contributors\n  did real work. Thank them publicly every time, no exceptions.\n\n## AI effort compression\n\nWhen estimating or discussing effort, always show both human-team and CC+gstack time:\n\n| Task type | Human team | CC+gstack | Compression |\n|-----------|-----------|-----------|-------------|\n| Boilerplate / scaffolding | 2 days | 15 min | ~100x |\n| Test writing | 1 day | 15 min | ~50x |\n| Feature implementation | 1 week | 30 min | ~30x |\n| Bug fix + regression test | 4 hours | 15 min | ~20x |\n| Architecture / design | 2 days | 4 hours | ~5x |\n| Research / exploration | 1 day | 3 hours | ~3x |\n\nCompleteness is cheap. Don't recommend shortcuts when the complete implementation\nis achievable. Boil the ocean — the complete thing is the goal; only genuinely\nunrelated multi-quarter migrations are separate scope, never an excuse for a\nshortcut. See the Completeness Principle in the skill preamble for the full\nphilosophy.\n\n## Search before building\n\nBefore designing any solution that involves concurrency, unfamiliar patterns,\ninfrastructure, or anything where the runtime/framework might have a built-in:\n\n1. Search for \"{runtime} {thing} built-in\"\n2. Search for \"{thing} best practice {current year}\"\n3. Check official runtime/framework docs\n\nThree layers of knowledge: tried-and-true (Layer 1), new-and-popular (Layer 2),\nfirst-principles (Layer 3). Prize Layer 3 above all. See ETHOS.md for the full\nbuilder philosophy.\n\n## Local plans\n\nContributors can store long-range vision docs and design documents in `~/.gstack-dev/plans/`.\nThese are local-only (not checked in). When reviewing TODOS.md, check `plans/` for candidates\nthat may be ready to promote to TODOs or implement.\n\n## E2E eval failure blame protocol\n\nWhen an E2E eval fails during `/ship` or any other workflow, **never claim \"not\nrelated to our changes\" without proving it.** These systems have invisible couplings —\na preamble text change affects agent behavior, a new helper changes timing, a\nregenerated SKILL.md shifts prompt context.\n\n**Required before attributing a failure to \"pre-existing\":**\n1. Run the same eval on main (or base branch) and show it fails there too\n2. If it passes on main but fails on the branch — it IS your change. Trace the blame.\n3. If you can't run on main, say \"unverified — may or may not be related\" and flag it\n   as a risk in the PR body\n\n\"Pre-existing\" without receipts is a lazy claim. Prove it or don't say it.\n\n## Long-running tasks: don't give up\n\nWhen running evals, E2E tests, or any long-running background task, **poll until\ncompletion**. Use `sleep 180 && echo \"ready\"` + `TaskOutput` in a loop every 3\nminutes. Never switch to blocking mode and give up when the poll times out. Never\nsay \"I'll be notified when it completes\" and stop checking — keep the loop going\nuntil the task finishes or the user tells you to stop.\n\nThe full E2E suite can take 30-45 minutes. That's 10-15 polling cycles. Do all of\nthem. Report progress at each check (which tests passed, which are running, any\nfailures so far). The user wants to see the run complete, not a promise that\nyou'll check later.\n\n## Running evals as an agent: always detach (SIGTERM-proof)\n\nWhen **you (an agent/harness)** launch a long eval/benchmark run, run it through\n`bin/gstack-detach` — NEVER as a plain backgrounded Bash task. A plain background\ntask lives in the harness's process group, so a SIGTERM (\"polite quit\") on a turn\nboundary, a stopped Monitor, or an interruption kills the run mid-flight (observed:\n`script \"test:gate\" was terminated by signal SIGTERM` ~40 min into a run). On macOS\nthe run can also die to idle-sleep. `gstack-detach` fixes both: a fresh session\n(escapes the group SIGTERM) wrapped in `caffeinate -i` (blocks idle-sleep).\n\n- Use the `eval:bg*` scripts (`eval:bg`, `eval:bg:all`, `eval:bg:gate`,\n  `eval:bg:periodic`) — they wrap the eval command in `gstack-detach` with the\n  machine-wide `gstack-evals` lock (concurrent worktrees serialize instead of\n  saturating the shared model API), a per-tier watchdog, and a **run-scoped** log\n  under `~/.gstack-dev/eval-runs/` (no shared-`/tmp` collision). Each prints its\n  log path. `eval:bg:gate` / `eval:bg:periodic` run their tier through the\n  sharded paid runner (`scripts/test-paid-shards.ts`, also exposed as\n  `test:gate:sharded` / `test:periodic:sharded`): one Bun process per test\n  file, an external wall-clock timeout that kills the shard's process GROUP\n  (stray `claude`/`codex` grandchildren included), a per-shard\n  `GSTACK_EVAL_DIR=<evalDir>/shards/<slug>/` honored by the `EvalCollector`\n  constructor, and an aggregate that separates failed vs timed-out vs\n  never-started shards — the detach timeouts (25200s gate / 28800s periodic)\n  are sized against worst-case shard wall clock. `eval:list` / `eval:compare` /\n  `eval:summary` read the shard dirs too. Or call\n  `gstack-detach [--lock NAME] [--timeout SECS] [--label LBL] --\n  <cmd>` directly for any long agent job. Export `ANTHROPIC_API_KEY` first (never\n  pass keys in argv).\n- Then **poll the printed logfile** with a death-aware watcher: break on the\n  guaranteed `### gstack-detach EXIT=<code> ###` sentinel (success AND failure are\n  both marked, so silence is never mistaken for success). The detached run survives\n  even if your watcher gets reaped, so re-checking the log always works.\n- Why the lock: a shared dev box with several Conductor worktrees will rate-limit\n  the model API if two eval suites run at once (15-way concurrency each), which\n  mass-times-out E2E tests. The lock makes the second run WAIT, not collide.\n- Humans running `bun run test:evals` foreground in their own terminal don't need\n  this — Ctrl-C is intended there. Detachment is for agent-launched runs only.\n\n## E2E test fixtures: extract, don't copy\n\n**NEVER copy a full SKILL.md file into an E2E test fixture.** SKILL.md files are\n1500-2000 lines. When `claude -p` reads a file that large, context bloat causes\ntimeouts, flaky turn limits, and tests that take 5-10x longer than necessary.\n\nInstead, extract only the section the test actually needs:\n\n```typescript\n// BAD — agent reads 1900 lines, burns tokens on irrelevant sections\nfs.copyFileSync(path.join(ROOT, 'ship', 'SKILL.md'), path.join(dir, 'ship-SKILL.md'));\n\n// GOOD — agent reads ~60 lines, finishes in 38s instead of timing out\nconst full = fs.readFileSync(path.join(ROOT, 'ship', 'SKILL.md'), 'utf-8');\nconst start = full.indexOf('## Review Readiness Dashboard');\nconst end = full.indexOf('\\n---\\n', start);\nfs.writeFileSync(path.join(dir, 'ship-SKILL.md'), full.slice(start, end > start ? end : undefined));\n```\n\nAlso when running targeted E2E tests to debug failures:\n- Run in **foreground** (`bun test ...`), not background with `&` and `tee`\n- Never `pkill` running eval processes and restart — you lose results and waste money\n- One clean run beats three killed-and-restarted runs\n\n## Publishing native OpenClaw skills to ClawHub\n\nNative OpenClaw skills live in `openclaw/skills/gstack-openclaw-*/SKILL.md`. These are\nhand-crafted methodology skills (not generated by the pipeline) published to ClawHub\nso any OpenClaw user can install them.\n\n**Publishing:** The command is `clawhub publish` (NOT `clawhub skill publish`):\n\n```bash\nclawhub publish openclaw/skills/gstack-openclaw-office-hours \\\n  --slug gstack-openclaw-office-hours --name \"gstack Office Hours\" \\\n  --version 1.0.0 --changelog \"description of changes\"\n```\n\nRepeat for each skill: `gstack-openclaw-ceo-review`, `gstack-openclaw-investigate`,\n`gstack-openclaw-retro`. Bump `--version` on each update.\n\n**Auth:** `clawhub login` (opens browser for GitHub auth). `clawhub whoami` to verify.\n\n**Updating:** Same `clawhub publish` command with a higher `--version` and `--changelog`.\n\n**Verification:** `clawhub search gstack` to confirm they're live.\n\n## Deploying to the active skill\n\nThe active skill lives at `~/.claude/skills/gstack/`. After making changes:\n\n1. Push your branch\n2. Fetch and reset in the skill directory: `cd ~/.claude/skills/gstack && git fetch origin && git reset --hard origin/main`\n3. Rebuild: `cd ~/.claude/skills/gstack && bun run build`\n\n**If you use gbrain:** the `git reset --hard` in step 2 reverts the brain-aware\n(`GBRAIN_CONTEXT_LOAD` / `GBRAIN_SAVE_RESULTS`) blocks that `gstack-config\ngbrain-refresh` renders into the install (those generated blocks differ from\n`main` by design). After deploying, re-run `gstack-config gbrain-refresh` to\nrestore them across all your projects' Claude sessions. It's idempotent.\n\nOr copy the binaries directly:\n- `cp browse/dist/browse ~/.claude/skills/gstack/browse/dist/browse`\n- `cp design/dist/design ~/.claude/skills/gstack/design/dist/design`\n\n## Skill routing\n\nWhen the user's request matches an available skill, invoke it via the Skill tool. When in doubt, invoke the skill.\n\nKey routing rules:\n- Product ideas/brainstorming → invoke /office-hours\n- Strategy/scope → invoke /plan-ceo-review\n- Architecture → invoke /plan-eng-review\n- Design system/plan review → invoke /design-consultation or /plan-design-review\n- Full review pipeline → invoke /autoplan\n- Bugs/errors → invoke /investigate\n- QA/testing site behavior → invoke /qa or /qa-only\n- Code review/diff check → invoke /review\n- Visual polish → invoke /design-review\n- Ship/deploy/PR → invoke /ship or /land-and-deploy\n- Save progress → invoke /context-save\n- Resume context → invoke /context-restore\n\n## Cross-session decision memory\n\nDurable decisions and their rationale are captured in an append-only, event-sourced\nstore at `~/.gstack/projects/<slug>/decisions.jsonl` so neither you nor the user\nre-litigates a settled call or loses the \"why\" across sessions. This is the reliable,\nfile-only path: it works with gbrain OFF. (gbrain semantic recall is an optional\nenhancement layered on top, never a dependency.)\n\n- **Resurface** active decisions before re-deciding: `bin/gstack-decision-search`\n  (`--recent N`, `--scope repo|branch|issue`, `--query KW`, `--all`, `--json`).\n  Add `--semantic` (with `--query`) to append related hits from gbrain memory when\n  it's up; it degrades silently to the reliable file results when gbrain is off.\n  Session start already surfaces scope-relevant active decisions via Context Recovery.\n  If a decision is listed, treat it as settled with its rationale; if you're about to\n  reverse it, say so explicitly.\n- **Capture** a DURABLE decision when you or the user make one:\n  `bin/gstack-decision-log '{\"decision\":\"...\",\"rationale\":\"...\",\"scope\":\"repo|branch|issue\",\"source\":\"user|skill|agent\",\"confidence\":1-10}'`.\n  Reverse a prior call with `--supersede <id>`; expunge an accidental secret with\n  `--redact <id>`; rewrite the log to the active set with `--compact`. Non-interactive\n  (never prompts), injection-sanitized, and HIGH-secret-blocking on write.\n- **Durable means:** architecture choice, scope cut, tool/vendor choice, or a reversal\n  of a prior call. NOT a turn-level edit, a phrasing tweak, or anything trivially\n  re-derivable. Capture is curated at the source — log durable decisions only, or the\n  store becomes noise.\n\n## GBrain Search Guidance (configured by /sync-gbrain)\n<!-- gstack-gbrain-search-guidance:start -->\n\nGBrain is set up and synced on this machine. The agent should prefer gbrain\nover Grep when the question is semantic or when you don't know the exact\nidentifier yet.\n\n**This worktree is pinned to a worktree-scoped code source** via the\n`.gbrain-source` file in the repo root (kubectl-style context). Any\n`gbrain code-def`, `code-refs`, `code-callers`, `code-callees`, or `query`\ncall from anywhere under this worktree routes to that source by default —\nno `--source` flag needed. Conductor sibling worktrees of the same repo\neach have their own pin and their own indexed pages, so semantic results\nmatch the actual code on disk in this worktree.\n\nTwo indexed corpora available via the `gbrain` CLI:\n- This worktree's code (auto-pinned via `.gbrain-source`).\n- `~/.gstack/` curated memory (registered as `gstack-brain-<user>` source via\n  the existing federation pipeline).\n\nPrefer gbrain when:\n- \"Where is X handled?\" / semantic intent, no exact string yet:\n    `gbrain search \"<terms>\"` or `gbrain query \"<question>\"`\n- \"Where is symbol Y defined?\" / symbol-based code questions:\n    `gbrain code-def <symbol>` or `gbrain code-refs <symbol>`\n- \"What calls Y?\" / \"What does Y depend on?\":\n    `gbrain code-callers <symbol>` / `gbrain code-callees <symbol>`\n- \"What did we decide last time?\" / past plans, retros, learnings:\n    `gbrain search \"<terms>\" --source gstack-brain-<user>`\n\nGrep is still right for known exact strings, regex, multiline patterns, and\nfile globs. Run `/sync-gbrain` after meaningful code changes; for ongoing\nauto-sync across all worktrees, run `gbrain autopilot --install` once per\nmachine — gbrain's daemon handles incremental refresh on a schedule.\n\nSafety: don't run `/sync-gbrain` while `gbrain autopilot` is active — the\norchestrator refuses destructive source ops when it detects a running autopilot\nto avoid racing it (#1734). Prefer registering user repos with `gbrain sources\nadd --path <dir>` (no `--url`): URL-managed sources can auto-reclone, and the\nsync code walk for them requires an explicit `--allow-reclone` opt-in.\n\n<!-- gstack-gbrain-search-guidance:end -->\n"},"files":{"AGENTS.md":"# gstack — AI Engineering Workflow\n\ngstack is a collection of SKILL.md files that give AI agents structured roles for\nsoftware development. Each skill is a specialist: CEO reviewer, eng manager,\ndesigner, QA lead, release engineer, debugger, and more.\n\n## Available skills\n\nSkills live in `.agents/skills/` (or `~/.claude/skills/gstack/` on Claude Code).\nInvoke them by name (e.g., `/office-hours`).\n\n### Plan-mode reviews\n\n| Skill | What it does |\n|-------|-------------|\n| `/office-hours` | Start here. Reframes your product idea before you write code. |\n| `/plan-ceo-review` | CEO-level review: find the 10-star product in the request. |\n| `/plan-eng-review` | Lock architecture, data flow, edge cases, and tests. |\n| `/plan-design-review` | Rate each design dimension 0-10, explain what a 10 looks like. |\n| `/plan-devex-review` | DX-mode review: TTHW, magical moments, friction points, persona traces. |\n| `/plan-tune` | Self-tune AskUserQuestion sensitivity per question. |\n| `/autoplan` | One command runs CEO → design → eng → DX review. |\n| `/design-consultation` | Build a complete design system from scratch. |\n| `/spec` | Turn vague intent into a precise, executable spec in five phases. Files a GitHub issue, optionally spawns a Claude Code agent in a fresh worktree, and lets `/ship` close the source issue on merge. |\n\n### Implementation + review\n\n| Skill | What it does |\n|-------|-------------|\n| `/review` | Pre-landing PR review. Finds bugs that pass CI but break in prod. |\n| `/codex` | Second opinion via OpenAI Codex. Review, challenge, or consult modes. |\n| `/investigate` | Systematic root-cause debugging. No fixes without investigation. |\n| `/design-review` | Live-site visual audit + fix loop with atomic commits. |\n| `/design-shotgun` | Generate multiple AI design variants, comparison board, iterate. |\n| `/design-html` | Generate production-quality Pretext-native HTML/CSS. |\n| `/devex-review` | Live developer experience audit (TTHW measured against the real flow). |\n| `/qa` | Open a real browser, find bugs, fix them, re-verify. |\n| `/qa-only` | Same methodology as /qa but report only — no code changes. |\n| `/scrape` | Pull data from a web page. First call prototypes; codified call runs in ~200ms. |\n| `/skillify` | Codify the most recent successful `/scrape` flow into a permanent browser-skill. |\n\n### Release + deploy\n\n| Skill | What it does |\n|-------|-------------|\n| `/ship` | Run tests, review, push, open PR. Workspace-aware version queue. |\n| `/land-and-deploy` | Merge the PR, wait for CI and deploy, verify production health. |\n| `/canary` | Post-deploy monitoring loop using the browse daemon. |\n| `/landing-report` | Read-only dashboard for the workspace-aware ship queue. |\n| `/document-release` | Update all docs to match what you just shipped. |\n| `/document-generate` | Generate Diataxis docs (tutorial / how-to / reference / explanation) from code. |\n| `/setup-deploy` | One-time deploy config detection (Fly.io, Render, Vercel, etc.). |\n| `/gstack-upgrade` | Update gstack to the latest version. |\n\n### Operational + memory\n\n| Skill | What it does |\n|-------|-------------|\n| `/context-save` | Save working context (git state, decisions, remaining work). |\n| `/context-restore` | Resume from a saved context, even across Conductor workspaces. |\n| `/learn` | Manage what gstack learned across sessions. |\n| `/retro` | Weekly retro with per-person breakdowns and shipping streaks. |\n| `/health` | Code quality dashboard (type checker, linter, tests, dead code). |\n| `/benchmark` | Performance regression detection (page load, Core Web Vitals). |\n| `/benchmark-models` | Cross-model benchmark for skills (Claude, GPT, Gemini side-by-side). |\n| `/cso` | OWASP Top 10 + STRIDE security audit. |\n| `/setup-gbrain` | Set up gbrain for cross-machine session memory sync. |\n| `/sync-gbrain` | Keep gbrain current with this repo's code; refresh agent search guidance in CLAUDE.md. |\n\n### Browser + agent integration\n\n| Skill | What it does |\n|-------|-------------|\n| `/browse` | Headless browser — real Chromium, real clicks, ~100ms/command. |\n| `/open-gstack-browser` | Launch the visible GStack Browser with sidebar + stealth. |\n| `/setup-browser-cookies` | Import cookies from your real browser for authenticated testing. |\n| `/pair-agent` | Pair a remote AI agent (OpenClaw, Codex, etc.) with your browser. |\n\n### iOS QA — drive real iPhones over USB or Tailscale (v1.43.0.0+)\n\n| Skill | What it does |\n|-------|-------------|\n| `/ios-qa` | Live-device iOS QA via USB CoreDevice tunnel + embedded StateServer. Optionally exposes the device over Tailscale so remote agents can drive it. |\n| `/ios-fix` | Autonomous iOS bug fixer with regression snapshot capture. |\n| `/ios-design-review` | Designer's-eye QA on a real iPhone — 10-dimension Apple HIG rubric. |\n| `/ios-clean` | Convenience: strip DebugBridge + #if DEBUG wiring before a Release build. |\n| `/ios-sync` | Regenerate the iOS debug bridge against the latest upstream templates. |\n\nCompanion CLIs (run on the Mac that's plugged into the device):\n\n| Command | What it does |\n|---------|-------------|\n| `gstack-ios-qa-daemon` | Mac-side broker. Loopback by default; `--tailnet` adds a Tailscale-facing listener with capability tiers and audit logging. |\n| `gstack-ios-qa-mint` | Owner-grant CLI for the tailnet allowlist (`grant`/`revoke`/`list`). |\n| `gstack-ios-qa-regen` | Regenerate the canonical local DebugBridge package and typed accessors (`--app-source` / `--bridge-dir`). |\n\nEnd-to-end walkthrough: [docs/howto-ios-testing-with-gstack.md](docs/howto-ios-testing-with-gstack.md).\n\n### Safety + scoping\n\n| Skill | What it does |\n|-------|-------------|\n| `/careful` | Warn before destructive commands (rm -rf, DROP TABLE, force-push). |\n| `/freeze` | Lock edits to one directory. Hard block, not just a warning. |\n| `/guard` | Activate both careful + freeze at once. |\n| `/unfreeze` | Remove directory edit restrictions. |\n| `/make-pdf` | Turn any markdown file into a publication-quality PDF. |\n| `/diagram` | English in, diagram out: mermaid source + editable .excalidraw + SVG/PNG, offline. |\n\n## Build commands\n\n```bash\nbun install              # install dependencies\nbun test                 # run free tests (no API spend)\nbun run test:windows     # curated Windows-safe subset (runs on windows-latest)\nbun run build            # generate docs + compile binaries\nbun run gen:skill-docs   # regenerate SKILL.md files from templates\nbun run skill:check      # health dashboard for all skills\n```\n\n## Platform support\n\n- **macOS** + **Linux**: full test suite supported.\n- **Windows**: curated Windows-safe subset runs on `windows-latest` via the\n  `windows-free-tests` CI job. Setup script (`./setup`) requires Git Bash or\n  MSYS today; native PowerShell support is a future expansion. The `bin/gstack-paths`\n  helper resolves state roots through `CLAUDE_PLUGIN_DATA` / `GSTACK_HOME` so plugin\n  installs work on every platform.\n\n## Key conventions\n\n- SKILL.md files are **generated** from `.tmpl` templates. Edit the template, not the output.\n- Run `bun run gen:skill-docs --host codex` to regenerate Codex-specific output.\n- The browse binary provides headless browser access. Use `$B <command>` in skills.\n- Safety skills (careful, freeze, guard) use inline advisory prose — always confirm before destructive operations.\n- State paths resolve via `bin/gstack-paths` (sourced via `eval \"$(...)\"`). Honors `GSTACK_HOME`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLANS_DIR`.\n- The `claude` CLI binary resolves via `browse/src/claude-bin.ts` (`Bun.which()` + `GSTACK_CLAUDE_BIN` override). Set `GSTACK_CLAUDE_BIN=wsl` plus `GSTACK_CLAUDE_BIN_ARGS='[\"claude\"]'` to run Claude through WSL on Windows.\n","CLAUDE.md":"# gstack development\n\n## Commands\n\n```bash\nbun install          # install dependencies\nbun test             # run free tests (browse + snapshot + skill validation)\nbun run test:evals   # run paid evals: LLM judge + E2E (diff-based, ~$4/run max)\nbun run test:evals:all  # run ALL paid evals regardless of diff\nbun run test:gate    # run gate-tier tests only (CI default, blocks merge)\nbun run test:periodic  # run periodic-tier tests only (weekly cron / manual)\nbun run test:gate:sharded    # gate tier via the sharded paid runner (one Bun process per test file)\nbun run test:periodic:sharded  # periodic tier via the sharded paid runner (implies EVALS_ALL=1)\nbun run test:e2e     # run E2E tests only (diff-based, ~$3.85/run max)\nbun run test:e2e:all # run ALL E2E tests regardless of diff\nbun run eval:select  # show which tests would run based on current diff\nbun run dev <cmd>    # run CLI in dev mode, e.g. bun run dev goto https://example.com\nbun run build        # gen docs + compile binaries\nbun run gen:skill-docs  # regenerate SKILL.md files from templates\nbun run skill:check  # health dashboard for all skills\nbun run dev:skill    # watch mode: auto-regen + validate on change\nbun run eval:list    # list all eval runs from ~/.gstack-dev/evals/\nbun run eval:compare # compare two eval runs (auto-picks most recent)\nbun run eval:summary # aggregate stats across all eval runs\nbun run slop          # full slop-scan report (all files)\nbun run slop:diff     # slop findings in files changed on this branch only\n```\n\n`test:evals` requires `ANTHROPIC_API_KEY`. Codex E2E tests (`test/codex-e2e.test.ts`)\nuse Codex's own auth from `~/.codex/` config — no `OPENAI_API_KEY` env var needed.\n\n**Env keys in Conductor workspaces.** The `GSTACK_*` env-shim (v1.39.2.0+,\n`lib/conductor-env-shim.ts`) promotes `GSTACK_ANTHROPIC_API_KEY` /\n`GSTACK_OPENAI_API_KEY` to their canonical names inside gstack's TS binaries.\nTests run through gstack entrypoints inherit this promotion automatically.\nDon't echo the key value to stdout, logs, or shell history. The historical\n\"never pass `env:` to `runAgentSdkTest`\" rule is retired: the failure was\npartial-env replacement (the SDK's `Options.env` REPLACES the child's entire\nenvironment, so an object without the key broke auth). The runner now always\npasses a COMPLETE hermetic env with per-test `env:` merged last, so per-test\noverrides are safe; ambient `process.env.ANTHROPIC_API_KEY` mutation also\nstill works (the env builder reads process.env at call time).\n\n**Hermetic local E2E (default).** Every E2E runner (claude -p, PTY, Agent\nSDK, codex, gemini) spawns children through `test/helpers/hermetic-env.ts`:\nallowlist-scrubbed env (operator `CONDUCTOR_*`, `CLAUDE_*`, `GSTACK_*`,\n`MCP_*`, `GBRAIN_*`, and credentials like `GH_TOKEN` never reach children),\na fresh seeded `CLAUDE_CONFIG_DIR` (no operator `~/.claude` CLAUDE.md /\nMCP servers / skills), a temp `GSTACK_HOME`, and `--strict-mcp-config`.\nLocal eval signal matches CI. Debug against real operator state with\n`EVALS_HERMETIC=0` (restores the legacy env AND drops the strict-MCP flag).\nPer-test `env:` overrides merge last, so deliberate contamination\n(`CONDUCTOR_WORKSPACE_PATH`, per-test `GSTACK_HOME`) keeps working. The\nhermetic config dir seeds NO skills by default; a PTY test that types a\n`/skill` slash command must pass `seedSkills: true` to the PTY runner, which\npoints the child's `CLAUDE_CONFIG_DIR` at `hermeticSkillsConfigDir()` — a\nseeded registry that symlinks the LIVE working tree's SKILL.md files (by\ndesign: the skills ARE the subject under test; a snapshot would measure stale\ncopies). Wiring is pinned by `test/hermetic-wiring.test.ts` (static tripwire),\ntwo gate-tier canaries in `test/skill-e2e-hermetic-canary.test.ts`, and the\nseeding tripwires in `test/hermetic-skills-seeding.test.ts` /\n`test/pty-skill-seeding-wiring.test.ts`.\n\nE2E tests stream progress in real-time (tool-by-tool via `--output-format stream-json\n--verbose`). Results are persisted to `~/.gstack-dev/evals/` with auto-comparison\nagainst the previous finalized run (in-flight `_partial` files are never used as\na baseline, so a run can't compare against itself).\n\n**Diff-based test selection:** `test:evals` and `test:e2e` auto-select tests based\non `git diff` against the base branch. Each test declares its file dependencies in\n`test/helpers/touchfiles.ts`. Changes to global touchfiles (session-runner, eval-store,\ntouchfiles.ts itself) trigger all tests. Use `EVALS_ALL=1` or the `:all` script\nvariants to force all tests. Run `eval:select` to preview which tests would run.\n\n**Two-tier system:** Tests are classified as `gate` or `periodic` in `E2E_TIERS`\n(in `test/helpers/touchfiles.ts`). CI runs only gate tests (`EVALS_TIER=gate`);\nperiodic tests run weekly via cron or manually. Use `EVALS_TIER=gate` or\n`EVALS_TIER=periodic` to filter. When adding new E2E tests, classify them:\n1. Safety guardrail or deterministic functional test? -> `gate`\n2. Quality benchmark, Opus model test, or non-deterministic? -> `periodic`\n3. Requires external service (Codex, Gemini)? -> `periodic`\n\nTier declarations are enforced by `test/e2e-tier-alignment.test.ts` (free, runs\nin `bun test`): a `skill-e2e-*` file named in a touchfiles dep list whose\n`EVALS_TIER` self-gate disagrees with its declared tier in `E2E_TIERS` fails the\nsuite. Files not named in any dep list are reported, not enforced — keep both\nin sync.\n\n## Testing\n\n```bash\nbun test             # run before every commit — free, <2s\nbun run test:evals   # run before shipping — paid, diff-based (~$4/run max)\n```\n\n`bun test` runs skill validation, gen-skill-docs quality checks, and browse\nintegration tests. `bun run test:evals` runs LLM-judge quality evals and E2E\ntests via `claude -p`. Both must pass before creating a PR.\n\n## Project structure\n\n```\ngstack/\n├── browse/          # Headless browser CLI (Playwright)\n│   ├── src/         # CLI + server + commands\n│   │   ├── commands.ts  # Command registry (single source of truth)\n│   │   └── snapshot.ts  # SNAPSHOT_FLAGS metadata array\n│   ├── test/        # Integration tests + fixtures\n│   └── dist/        # Compiled binary\n├── hosts/           # Typed host configs (one per AI agent)\n│   ├── claude.ts    # Primary host config\n│   ├── codex.ts, factory.ts, kiro.ts  # Existing hosts\n│   ├── opencode.ts, slate.ts, cursor.ts, openclaw.ts  # IDE hosts\n│   ├── hermes.ts, gbrain.ts  # Agent runtime hosts\n│   └── index.ts     # Registry: exports all, derives Host type\n├── scripts/         # Build + DX tooling\n│   ├── gen-skill-docs.ts  # Template → SKILL.md generator (config-driven)\n│   ├── host-config.ts     # HostConfig interface + validator\n│   ├── host-config-export.ts  # Shell bridge for setup script\n│   ├── host-adapters/     # Host-specific adapters (OpenClaw tool mapping)\n│   ├── resolvers/   # Template resolver modules (preamble, design, review, gbrain, etc.)\n│   ├── skill-check.ts     # Health dashboard\n│   ├── test-paid-shards.ts  # Sharded paid-tier runner (one Bun process per shard)\n│   └── dev-skill.ts       # Watch mode\n├── test/            # Skill validation + eval tests\n│   ├── helpers/     # skill-parser.ts, session-runner.ts, llm-judge.ts, eval-store.ts\n│   ├── fixtures/    # Ground truth JSON, planted-bug fixtures, eval baselines\n│   ├── skill-validation.test.ts  # Tier 1: static validation (free, <1s)\n│   ├── gen-skill-docs.test.ts    # Tier 1: generator quality (free, <1s)\n│   ├── skill-llm-eval.test.ts   # Tier 3: LLM-as-judge (~$0.15/run)\n│   └── skill-e2e-*.test.ts       # Tier 2: E2E via claude -p (~$3.85/run, split by category)\n├── qa-only/         # /qa-only skill (report-only QA, no fixes)\n├── plan-design-review/  # /plan-design-review skill (report-only design audit)\n├── design-review/    # /design-review skill (design audit + fix loop)\n├── ship/            # Ship workflow skill\n├── review/          # PR review skill\n├── plan-ceo-review/ # /plan-ceo-review skill\n├── plan-eng-review/ # /plan-eng-review skill\n├── autoplan/        # /autoplan skill (auto-review pipeline: CEO → design → eng)\n├── benchmark/       # /benchmark skill (performance regression detection)\n├── canary/          # /canary skill (post-deploy monitoring loop)\n├── codex/           # /codex skill (multi-AI second opinion via OpenAI Codex CLI)\n├── land-and-deploy/ # /land-and-deploy skill (merge → deploy → canary verify)\n├── office-hours/    # /office-hours skill (YC Office Hours — startup diagnostic + builder brainstorm)\n├── investigate/     # /investigate skill (systematic root-cause debugging)\n├── spec/            # /spec skill (five-phase spec → GitHub issue, optional agent spawn, /ship auto-closes)\n├── retro/           # Retrospective skill (includes /retro global cross-project mode)\n├── bin/             # CLI utilities (gstack-repo-mode, gstack-slug, gstack-config, etc.)\n├── document-release/ # /document-release skill (post-ship doc updates + Diataxis coverage map)\n├── document-generate/ # /document-generate skill (Diataxis doc generator: tutorial/how-to/reference/explanation)\n├── cso/             # /cso skill (OWASP Top 10 + STRIDE security audit)\n├── design-consultation/ # /design-consultation skill (design system from scratch)\n├── design-shotgun/  # /design-shotgun skill (visual design exploration)\n├── open-gstack-browser/  # /open-gstack-browser skill (launch GStack Browser)\n├── connect-chrome/  # symlink → open-gstack-browser (backwards compat)\n├── design/          # Design binary CLI (GPT Image API)\n│   ├── src/         # CLI + commands (generate, variants, compare, serve, etc.)\n│   ├── test/        # Integration tests\n│   └── dist/        # Compiled binary\n├── extension/       # Chrome extension (side panel + activity feed + CSS inspector)\n├── lib/             # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts)\n├── docs/designs/    # Design documents\n├── setup-deploy/    # /setup-deploy skill (one-time deploy config)\n├── .github/         # CI workflows + Docker image\n│   ├── workflows/   # evals.yml (E2E on Ubicloud), skill-docs.yml, actionlint.yml\n│   └── docker/      # Dockerfile.ci (pre-baked toolchain + Playwright/Chromium)\n├── contrib/         # Contributor-only tools (never installed for users)\n│   └── add-host/    # /gstack-contrib-add-host skill\n├── setup            # One-time setup: build binary + symlink skills\n├── SKILL.md         # Generated from SKILL.md.tmpl (don't edit directly)\n├── SKILL.md.tmpl    # Template: edit this, run gen:skill-docs\n├── ETHOS.md         # Builder philosophy (Boil the Ocean, Search Before Building)\n└── package.json     # Build scripts for browse\n```\n\n## SKILL.md workflow\n\nSKILL.md files are **generated** from `.tmpl` templates. To update docs:\n\n1. Edit the `.tmpl` file (e.g. `SKILL.md.tmpl` or `browse/SKILL.md.tmpl`)\n2. Run `bun run gen:skill-docs` (or `bun run build` which does it automatically)\n3. Commit both the `.tmpl` and generated `.md` files\n\nTo add a new browse command: add it to `browse/src/commands.ts` and rebuild.\nTo add a snapshot flag: add it to `SNAPSHOT_FLAGS` in `browse/src/snapshot.ts` and rebuild.\n\n**Token ceiling:** Generated SKILL.md files trip a warning above 160KB (~40K tokens).\nThis is a \"watch for feature bloat\" guardrail, not a hard gate. Modern flagship\nmodels have 200K-1M context windows, so 40K is 4-20% of window, and prompt caching\nmakes the marginal cost of larger skills small. The ceiling exists to catch runaway\npreamble/resolver growth, not to force compression on carefully-tuned big skills\n(`ship`, `plan-ceo-review`, `office-hours` legitimately pack 25-35K tokens of\nbehavior). If you blow past 40K, the right fix is usually: (1) look at WHAT grew,\n(2) if one resolver added 10K+ in a single PR, question whether it belongs inline\nor as a reference doc, (3) only compress carefully-tuned prose as a last resort —\ncuts to the coverage audit, review army, or voice directive have real quality cost.\n\nA second, harder ceiling guards the DISCOVERY surface: `test/catalog-budget.test.ts`\ncaps the aggregate frontmatter `name` + `description` across all skills at 1,150\ntoken-equivalents (260-byte per-skill sub-cap), counted through the shared census\nin `test/helpers/skill-census.ts`. This one is enforced, not a warning — every\nhost loads the full catalog every session, so growth here taxes every\nconversation. The failure message carries the re-measure + ratchet protocol.\n`bin/gstack-context-bill` shows the full token bill-of-materials for a skills\ntree (always-on vs per-invocation, `--diff`, `--budget`; `--exact` opts into the\nreal tokenizer and POSTs file text to api.anthropic.com with an egress receipt).\n\n**Merge conflicts on SKILL.md files:** NEVER resolve conflicts on generated SKILL.md\nfiles by accepting either side. Instead: (1) resolve conflicts on the `.tmpl` templates\nand `scripts/gen-skill-docs.ts` (the sources of truth), (2) run `bun run gen:skill-docs`\nto regenerate all SKILL.md files, (3) stage the regenerated files. Accepting one side's\ngenerated output silently drops the other side's template changes.\n\n## Platform-agnostic design\n\nSkills must NEVER hardcode framework-specific commands, file patterns, or directory\nstructures. Instead:\n\n1. **Read CLAUDE.md** for project-specific config (test commands, eval commands, etc.)\n2. **If missing, AskUserQuestion** — let the user tell you or let gstack search the repo\n3. **Persist the answer to CLAUDE.md** so we never have to ask again\n\nThis applies to test commands, eval commands, deploy commands, and any other\nproject-specific behavior. The project owns its config; gstack reads it.\n\n## Writing SKILL templates\n\nSKILL.md.tmpl files are **prompt templates read by Claude**, not bash scripts.\nEach bash code block runs in a separate shell — variables do not persist between blocks.\n\nRules:\n- **Use natural language for logic and state.** Don't use shell variables to pass\n  state between code blocks. Instead, tell Claude what to remember and reference\n  it in prose (e.g., \"the base branch detected in Step 0\").\n- **Don't hardcode branch names.** Detect `main`/`master`/etc dynamically via\n  `gh pr view` or `gh repo view`. Use `{{BASE_BRANCH_DETECT}}` for PR-targeting\n  skills. Use \"the base branch\" in prose, `<base>` in code block placeholders.\n- **Keep bash blocks self-contained.** Each code block should work independently.\n  If a block needs context from a previous step, restate it in the prose above.\n- **Express conditionals as English.** Instead of nested `if/elif/else` in bash,\n  write numbered decision steps: \"1. If X, do Y. 2. Otherwise, do Z.\"\n\n## Writing style (V1)\n\nDefault output from every tier-≥2 skill follows the Writing Style section in\n`scripts/resolvers/preamble.ts`: jargon glossed on first use (curated list in\n`scripts/jargon-list.json`, baked at gen-skill-docs time), questions framed in\noutcome terms (\"what breaks for your users if...\") not implementation terms,\nshort sentences, decisions close with user impact. Power users who want the\ntighter V0 prose set `gstack-config set explain_level terse` (binary switch,\nno middle mode). See `docs/designs/PLAN_TUNING_V1.md` for the full design\nrationale. The review pacing overhaul that originally tried to ride alongside\nwriting-style was extracted to V1.1 — see `docs/designs/PACING_UPDATES_V0.md`.\n\n## Browser interaction\n\nWhen you need to interact with a browser (QA, dogfooding, cookie setup), use the\n`/browse` skill or run the browse binary directly via `$B <command>`. NEVER use\n`mcp__claude-in-chrome__*` tools — they are slow, unreliable, and not what this\nproject uses.\n\n**Sidebar architecture:** Before modifying `sidepanel.js`, `background.js`,\n`content.js`, `terminal-agent.ts`, or sidebar-related server endpoints,\nread `docs/designs/SIDEBAR_MESSAGE_FLOW.md`. The sidebar has one primary\nsurface — the **Terminal** pane (interactive `claude` PTY) — with\nActivity / Refs / Inspector as debug overlays behind the footer's\n`debug` toggle. The chat queue path was ripped once the PTY proved out;\n`sidebar-agent.ts` and the `/sidebar-command` / `/sidebar-chat` /\n`/sidebar-agent/event` endpoints are gone. The doc covers the WS auth\nflow, dual-token model, and threat-model boundary — silent failures\nhere usually trace to not understanding the cross-component flow.\n\n**Embedder terminal-agent ownership** (v1.42.1.0+, identity-based kill v1.44.0.0+).\n`buildFetchHandler` in `browse/src/server.ts` accepts `ServerConfig.ownsTerminalAgent?:\nboolean` (default `true`). When `true`, factory shutdown runs the full teardown:\nidentity-based kill via `killAgentByRecord(readAgentRecord(stateDir))` from\n`browse/src/terminal-agent-control.ts` plus `safeUnlinkQuiet` on\n`<stateDir>/terminal-port`, `<stateDir>/terminal-internal-token`, and\n`<stateDir>/terminal-agent-pid` (the per-boot agent record introduced in v1.44).\nEmbedders (e.g. the gbrowser phoenix overlay) that pre-launch their own PTY\nserver must pass `false` so their discovery files survive gstack teardown cycles.\nThe flag is the third caller-owned teardown gate in `ServerConfig` (alongside\n`xvfb?` and `proxyBridge?`); polarity is inverted (explicit bool vs presence) and\ndocumented in the field's JSDoc. CLI `start()` always passes `true` explicitly —\nthe static-grep test in `browse/test/server-embedder-terminal-port.test.ts` fails\nCI if a refactor drops it. Pre-v1.44 used `pkill -f terminal-agent\\.ts` (regex\nmatch) which would kill sibling gstack sessions on the same host; the new\n`browse/test/terminal-agent-pid-identity.test.ts` static-grep tripwire fails CI\nif any source file re-introduces `pkill ... terminal-agent` or `spawnSync('pkill', ...)`.\n\n**WebSocket auth uses Sec-WebSocket-Protocol, not cookies.** Browsers\ncan't set `Authorization` on a WebSocket upgrade, but they CAN set\n`Sec-WebSocket-Protocol` via `new WebSocket(url, [token])`. The agent\nreads it, validates against `validTokens`, and MUST echo the protocol\nback in the upgrade response — without the echo, Chromium closes the\nconnection immediately. `Set-Cookie: gstack_pty=...` is kept as a\nfallback for non-browser callers (the cross-port `SameSite=Strict`\ncookie path doesn't survive from a chrome-extension origin).\n\n**Cross-pane PTY injection.** The toolbar's Cleanup button and the\nInspector's \"Send to Code\" action both pipe text into the live claude\nPTY via `window.gstackInjectToTerminal(text)`, exposed by\n`sidepanel-terminal.js`. No `/sidebar-command` POST — the live REPL is\nthe only execution surface in the sidebar now.\n\n**`/health` MUST NOT surface any token — and it no longer does** (v1.63+).\nThe historical headed-mode leak of `AUTH_TOKEN` is fixed: `GET /health` is\nliveness/status only in every mode. Token bootstrap is `POST /extension-token`,\nwhich validates the caller's Origin against the pinned extension identity\n(the `key` field in `extension/manifest.json` pins the extension ID —\n`GSTACK_EXTENSION_ID` in `browse/src/server.ts`, derivation reproducible via\n`bun browse/scripts/extension-id.ts`) plus a loopback Host. PTY auth still\nflows through `POST /pty-session` only. Don't add any token to `/health`.\n\n**Transport-layer security** (v1.6.0.0+). When `pair-agent` starts an ngrok tunnel,\nthe daemon binds two HTTP listeners: a local listener (127.0.0.1, full command\nsurface, never forwarded) and a tunnel listener (locked allowlist: `/connect`,\n`/command` with a scoped token + 26-command browser-driving allowlist,\n`/sidebar-chat`). ngrok forwards only the tunnel port. Root tokens over the tunnel\nreturn 403. SSE endpoints use a 30-minute HttpOnly `gstack_sse` cookie minted via\n`POST /sse-session` (never valid against `/command`). Tunnel-surface rejections go\nto `~/.gstack/security/attempts.jsonl` via `tunnel-denial-log.ts`. Before editing\n`server.ts`, `sse-session-cookie.ts`, or `tunnel-denial-log.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#dual-listener-tunnel-architecture-v1600) —\nthe module boundary (no imports from `token-registry.ts` into `sse-session-cookie.ts`)\nis load-bearing for scope isolation.\n\n**Unicode sanitization at server egress** (v1.38.0.0+). Every server egress that\nships page-content-derived strings MUST go through `JSON.stringify(payload,\nsanitizeReplacer)` for object payloads or `sanitizeLoneSurrogates(body)` for text\nbodies. Lone UTF-16 surrogate halves from CDP page content otherwise reach the\nAnthropic API as `\\uD800`-style escapes and trigger a 400. Wired at four egress\npoints today: `handleCommandInternal` (HTTP + batch via a sanitizing wrapper around\n`handleCommandInternalImpl`) and both SSE producers (`/activity/stream`,\n`/inspector/events`). Post-stringify regex is a no-op — `JSON.stringify` has\nalready escaped the surrogate before regex could match, so the replacer must run\ninside the encoding pipeline. Before adding a new SSE/WebSocket writer or HTTP\nresponse in `server.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#unicode-sanitization-at-server-egress-v13800).\n`browse/test/server-sanitize-surrogates.test.ts` pins the wiring with invariant\ntests, so bypasses fail CI.\n\n**Egress receipts at every off-machine sink** (v1.63.0.0+). Every gstack-initiated\nsend off the machine MUST write a hash-chained receipt to\n`~/.gstack/security/egress.jsonl` BEFORE the send: TypeScript callers use\n`writeReceipt` from `lib/egress-receipt.ts`; shell scripts source\n`bin/gstack-egress-lib.sh` and use `_receipted_curl` / `_receipted_git`. Failure\npolarity is per-class: fail-closed for sensitive sinks (brain-sync, memory-ingest,\ngbrain-sync, telemetry, ngrok tunnels, mcp-verify, supabase-provision), fail-open\n+ stderr warning for user-facing ones (design OpenAI calls, update-check,\ndashboards, git-class ops). The new-sink scanner in\n`test/egress-receipt-wiring.test.ts` fails CI on an unreceipted `curl` /\n`git push` / `fetch` to a non-loopback host unless the file carries a reasoned\nentry in its `SCANNER_EXEMPT` list (user-directed page fetches, reachability\nprobes, instruction strings, skill prose) — if you add a new off-machine sink,\nwire it through the helpers and add it to the enumerated sink list. Inspect with\n`bin/gstack-egress` (`list` | `verify`, exit 3 on tamper | `grants`). Threat\nmodel: forensic observability of ATTEMPTED egress, not an exfiltration control.\n\n**SSE endpoint helper** (v1.51.0.0+). New SSE endpoints in `server.ts` MUST route\nthrough `createSseEndpoint(req, config)` from `browse/src/sse-helpers.ts`. The\nhelper owns the cleanup contract (abort + enqueue-throw + heartbeat-throw, all\nidempotent) and bakes in `sanitizeLoneSurrogates` on every JSON.stringify, so\nnew subscribers can't accidentally regress either invariant. Inline\n`ReadableStream` wiring leaked subscribers when the TCP connection died without\nfiring `req.signal.abort` (Chromium MV3 service-worker suspend, intermediate\nproxy half-close). `/activity/stream`, `/inspector/events`, and `/memory`\n(SSE-eligible) all route through it. `browse/test/sse-helpers.test.ts` pins the\ncleanup contract.\n\n**CDP session lifecycle** (v1.51.0.0+). Direct `page.context().newCDPSession(page)`\ncalls outside `browse/src/cdp-bridge.ts` fail CI via the static-grep tripwire in\n`browse/test/cdp-session-cleanup.test.ts`. Use `withCdpSession(page, async (s) => {...})`\nfor one-shot CDP work (try/finally detach) or `getOrCreateCdpSession(page, cache)`\nfor cached sessions tied to a page's lifetime (close-detach via `Map<page, session>`).\nThree sites migrated: cdp-bridge frame events, write-commands archive capture,\ncdp-inspector. The helpers prevent the per-session leak class where successful-path\ndetach happened but error-path detach was missed.\n\n**Setup symlink hardening** (v1.38.0.0+). Every link site in `setup` MUST route\nthrough the `_link_or_copy SRC DST` helper near the `IS_WINDOWS` detection. On\nWindows without Developer Mode, plain `ln -snf` produces frozen file copies that\ndon't refresh on `git pull` — silent staleness across every host adapter. The\nhelper preserves `ln -snf` on Unix and switches to `cp -R` / `cp -f` on Windows.\n`test/setup-windows-fallback.test.ts` enforces a static invariant: a single raw\n`ln` call outside the helper body fails CI. Windows users get a one-line note\nfrom `_print_windows_copy_note_once` reminding them to re-run `./setup` after\nevery `git pull`.\n\n**Sidebar security stack** (layered defense against prompt injection):\n\n| Layer | Module | Lives in |\n|-------|--------|----------|\n| L1-L3 | `content-security.ts` | both server and agent — datamarking, hidden element strip, ARIA regex, URL blocklist, envelope wrapping |\n| L4 | `security-classifier.ts` (TestSavantAI ONNX) | **sidebar-agent only** |\n| L4b | `security-classifier.ts` (Claude Haiku transcript) | **sidebar-agent only** |\n| L5 | `security.ts` (canary) | both — inject in compiled, check in agent |\n| L6 | `security.ts` (combineVerdict ensemble) | both |\n\n**Critical constraint:** `security-classifier.ts` CANNOT be imported from the\ncompiled browse binary. `@huggingface/transformers` v4 requires `onnxruntime-node`\nwhich fails to `dlopen` from Bun compile's temp extract dir. Only `security.ts`\n(pure-string operations — canary, verdict combiner, attack log, status) is safe\nfor `server.ts`. See `~/.gstack/projects/garrytan-gstack/ceo-plans/2026-04-19-prompt-injection-guard.md`\n§\"Pre-Impl Gate 1 Outcome\" for full architectural decision.\n\n**Thresholds** (in `security.ts`):\n- `BLOCK: 0.85` — single-layer score that would cause BLOCK if cross-confirmed\n- `WARN: 0.75` — cross-confirm threshold. When L4 AND L4b both >= 0.75 → BLOCK\n- `LOG_ONLY: 0.40` — gates transcript classifier (skip Haiku when all layers < 0.40)\n- `SOLO_CONTENT_BLOCK: 0.92` — single-layer threshold for label-less content classifiers\n  (testsavant, deberta). Intentionally higher than `BLOCK` because these layers can't\n  distinguish \"this is an injection\" from \"this looks like phishing aimed at the user.\"\n  The transcript classifier keeps a separate, label-gated solo path at `BLOCK` (0.85).\n\n**Ensemble rule:** BLOCK only when the ML content classifier AND the transcript\nclassifier both report >= WARN. Single-layer high confidence degrades to WARN —\nthis is the Stack Overflow instruction-writing FP mitigation. Canary leak\nalways BLOCKs (deterministic).\n\n**Env knobs:**\n- `GSTACK_SECURITY_OFF=1` — emergency kill switch. Classifier stays off even if\n  warmed. Canary is still injected; just the ML scan is skipped.\n- `GSTACK_SECURITY_ENSEMBLE=deberta` — opt-in DeBERTa-v3 ensemble. Adds\n  ProtectAI DeBERTa-v3-base-injection-onnx as L4c classifier for cross-model\n  agreement. 721MB first-run download. With ensemble enabled, BLOCK requires\n  2-of-3 ML classifiers agreeing at >= WARN (testsavant, deberta, transcript).\n  Without ensemble (default), BLOCK requires testsavant + transcript at >= WARN.\n- Classifier model cache: `~/.gstack/models/testsavant-small/` (112MB, first run only)\n  plus `~/.gstack/models/deberta-v3-injection/` (721MB, only when ensemble enabled)\n- Attack log: `~/.gstack/security/attempts.jsonl` (salted sha256 + domain only,\n  rotates at 10MB, 5 generations)\n- Per-device salt: `~/.gstack/security/device-salt` (0600)\n- Session state: `~/.gstack/security/session-state.json` (cross-process, atomic)\n\n## Dev symlink awareness\n\nWhen developing gstack, `.claude/skills/gstack` may be a symlink back to this\nworking directory (gitignored). This means skill changes are **live immediately**,\ngreat for rapid iteration, risky during big refactors where half-written skills\ncould break other Claude Code sessions using gstack concurrently.\n\n**Check once per session:** Run `ls -la .claude/skills/gstack` to see if it's a\nsymlink or a real copy. If it's a symlink to your working directory, be aware that:\n- Template changes + `bun run gen:skill-docs` immediately affect all gstack invocations\n- Breaking changes to SKILL.md.tmpl files can break concurrent gstack sessions\n- During large refactors, remove the symlink (`rm .claude/skills/gstack`) so the\n  global install at `~/.claude/skills/gstack/` is used instead\n\n**Prefix setting:** Setup creates real directories (not symlinks) at the top level\nwith a SKILL.md symlink inside (e.g., `qa/SKILL.md -> gstack/qa/SKILL.md`). This\nensures Claude discovers them as top-level skills, not nested under `gstack/`.\nNames are either short (`qa`) or namespaced (`gstack-qa`), controlled by\n`skill_prefix` in `~/.gstack/config.yaml`. Pass `--no-prefix` or `--prefix` to\nskip the interactive prompt.\n\n**Note:** Vendoring gstack into a project's repo is deprecated. Use global install\n+ `./setup --team` instead. See README.md for team mode instructions.\n\n**For plan reviews:** When reviewing plans that modify skill templates or the\ngen-skill-docs pipeline, consider whether the changes should be tested in isolation\nbefore going live (especially if the user is actively using gstack in other windows).\n\n**Upgrade migrations:** When a change modifies on-disk state (directory structure,\nconfig format, stale files) in ways that could break existing user installs, add a\nmigration script to `gstack-upgrade/migrations/`. Read CONTRIBUTING.md's \"Upgrade\nmigrations\" section for the format and testing requirements. The upgrade skill runs\nthese automatically after `./setup` during `/gstack-upgrade`.\n\n## Compiled binaries — never commit browse/dist/, design/dist/, or make-pdf/dist/\n\nThe `browse/dist/`, `design/dist/`, and `make-pdf/dist/` directories contain\ncompiled Bun binaries (`browse`, `find-browse`, `design`, ~62MB each). These are\nMach-O arm64 only — they do NOT work on Linux, Windows, or Intel Macs. The\n`./setup` script builds from source for every platform.\n\nThese directories are **untracked and gitignored** (`.gitignore:3-6`; the\n`browse/dist/` binaries were untracked in `64d5a3e4`, v0.11.16.0; the others were\nnever tracked). They will NOT appear in `git status`. If a dist binary ever does\nshow up in `git status`, something force-added it (`git add -f`) — do not commit\nit; unstage it and find out how it got there.\n\nWhen staging files, always use specific filenames (`git add file1 file2`) — never\n`git add .` or `git add -A`, which can sweep in build outputs and junk.\n\n## Redaction guard (PII / secrets / legal content)\n\nShared redaction engine catches credentials, PII, and legal/damaging content\nbefore it reaches an external sink (codex dispatch, GitHub issue/PR body, pushed\ncommit). It is a **guardrail, not airtight enforcement** — `git push --no-verify`,\ndirect `gh issue create`, and `GSTACK_REDACT_PREPUSH=skip` all bypass it. It\ncatches accidents and carelessness, the 99% case. Do not claim it stops a\ndetermined leaker (a CHANGELOG line that does would fail a hostile screenshotter).\n\n- **Engine + taxonomy:** `lib/redact-patterns.ts` (the single source of truth —\n  3 tiers; HIGH = genuinely-secret credentials that block, MEDIUM = PII/legal/\n  internal + high-FP credential shapes that confirm via AskUserQuestion, LOW =\n  FYI) and `lib/redact-engine.ts` (pure `scan()` + `applyRedactions()`).\n  Calibration matters: a gate that cries wolf gets ignored, so context-variable\n  shapes (Stripe `pk_live_`, Google `AIza`, JWT, env `*_KEY=`) sit at MEDIUM.\n- **CLI:** `bin/gstack-redact` (exit 0 clean / 2 MEDIUM / 3 HIGH; `--json`,\n  `--auto-redact`, `--repo-visibility`, `--from-file`). `bin/gstack-redact-prepush`\n  is the opt-in git hook.\n- **Skill docs are generated** from `scripts/resolvers/redact-doc.ts`\n  (`{{REDACT_TAXONOMY_TABLE}}`, `{{REDACT_INVOCATION_BLOCK:<sink>}}`) so /spec,\n  /cso, /ship, /document-release, /document-generate never drift from the engine.\n- **Scan-at-sink:** always scan the EXACT bytes that will be sent — write to a\n  temp file, scan that file, pass the SAME file to `gh`/`git`. Never scan a string\n  then re-render (that reopens a scan-vs-send gap).\n- **Visibility (no tier promotion):** resolve once per run, order = local config\n  (`gstack-config get redact_repo_visibility`, ~/.gstack so never committed) → gh\n  → glab → unknown(=public-strict). Public repos get STERNER per-finding\n  confirmation (no batch-acknowledge, no silent-proceed); MEDIUM is never\n  auto-promoted to HIGH.\n- **Tool-attributed fences:** wrap Codex/Greptile/eval output in ` ```codex-review `\n  / ` ```greptile ` fences so example credentials those tools quote WARN-degrade\n  instead of blocking. A live-format credential inside the fence still blocks.\n- **Config keys:** `redact_repo_visibility` (public|private|unknown, local-only\n  override for repos gh/glab can't read), `redact_prepush_hook` (true|false).\n  There is intentionally NO key to disable HIGH blocking.\n- **Audit:** the /spec semantic pass appends a content-free record (categories +\n  body sha256, no spec text) to `~/.gstack/security/semantic-reviews.jsonl` (0600).\n\n## Commit style\n\n**Always bisect commits.** Every commit should be a single logical change. When\nyou've made multiple changes (e.g., a rename + a rewrite + new tests), split them\ninto separate commits before pushing. Each commit should be independently\nunderstandable and revertable.\n\nExamples of good bisection:\n- Rename/move separate from behavior changes\n- Test infrastructure (touchfiles, helpers) separate from test implementations\n- Template changes separate from generated file regeneration\n- Mechanical refactors separate from new features\n\nWhen the user says \"bisect commit\" or \"bisect and push,\" split staged/unstaged\nchanges into logical commits and push.\n\n## Slop-scan: AI code quality, not AI code hiding\n\nWe use [slop-scan](https://github.com/benvinegar/slop-scan) to catch patterns where\nAI-generated code is genuinely worse than what a human would write. We are NOT trying\nto pass as human code. We are AI-coded and proud of it. The goal is code quality.\n\n```bash\nnpx slop-scan scan .          # human-readable report\nnpx slop-scan scan . --json   # machine-readable for diffing\n```\n\nConfig: `slop-scan.config.json` at repo root (currently excludes `**/vendor/**`).\n\n### What to fix (genuine quality improvements)\n\n- **Empty catches around file ops** — use `safeUnlink()` (ignores ENOENT, rethrows\n  EPERM/EIO). A swallowed EPERM in cleanup means silent data loss.\n- **Empty catches around process kills** — use `safeKill()` (ignores ESRCH, rethrows\n  EPERM). A swallowed EPERM means you think you killed something you didn't.\n- **Redundant `return await`** — remove when there's no enclosing try block. Saves a\n  microtask, signals intent.\n- **Typed exception catches** — `catch (err) { if (!(err instanceof TypeError)) throw err }`\n  is genuinely better than `catch {}` when the try block does URL parsing or DOM work.\n  You know what error you expect, so say so.\n\n### What NOT to fix (linter gaming, not quality)\n\n- **String-matching on error messages** — `err.message.includes('closed')` is brittle.\n  Playwright/Chrome can change wording anytime. If a fire-and-forget operation can fail\n  for ANY reason and you don't care, `catch {}` is the correct pattern.\n- **Adding comments to exempt pass-through wrappers** — \"alias for active session\" above\n  a method just to trip slop-scan's exemption rule is noise, not documentation.\n- **Converting extension catch-and-log to selective rethrow** — Chrome extensions crash\n  entirely on uncaught errors. If the catch logs and continues, that IS the right pattern\n  for extension code. Don't make it throw.\n- **Tightening best-effort cleanup paths** — shutdown, emergency cleanup, and disconnect\n  code should use `safeUnlinkQuiet()` (swallows ALL errors). A cleanup path that throws\n  on EPERM means the rest of cleanup doesn't run. That's worse.\n\n### Utilities in `browse/src/error-handling.ts`\n\n| Function | Use when | Behavior |\n|----------|----------|----------|\n| `safeUnlink(path)` | Normal file deletion | Ignores ENOENT, rethrows others |\n| `safeUnlinkQuiet(path)` | Shutdown/emergency cleanup | Swallows all errors |\n| `safeKill(pid, signal)` | Sending signals | Ignores ESRCH, rethrows others |\n| `isProcessAlive(pid)` | Boolean process checks | Returns true/false, never throws |\n\n### Score tracking\n\nBaseline (2026-04-09, before cleanup): 100 findings, 432.8 score, 2.38 score/file.\nAfter cleanup: 90 findings, 358.1 score, 1.96 score/file.\n\nDon't chase the number. Fix patterns that represent actual code quality problems.\nAccept findings where the \"sloppy\" pattern is the correct engineering choice.\n\n## Community PR guardrails\n\nWhen reviewing or merging community PRs, **always AskUserQuestion** before accepting\nany commit that:\n\n1. **Touches ETHOS.md** — this file is Garry's personal builder philosophy. No edits\n   from external contributors or AI agents, period.\n2. **Removes or softens promotional material** — YC references, founder perspective,\n   and product voice are intentional. PRs that frame these as \"unnecessary\" or\n   \"too promotional\" must be rejected.\n3. **Changes Garry's voice** — the tone, humor, directness, and perspective in skill\n   templates, CHANGELOG, and docs are not generic. PRs that rewrite voice to be\n   more \"neutral\" or \"professional\" must be rejected.\n\nEven if the agent strongly believes a change improves the project, these three\ncategories require explicit user approval via AskUserQuestion. No exceptions.\nNo auto-merging. No \"I'll just clean this up.\"\n\n## Checking out PRs from garrytan-agents\n\nWhen the user says \"check out <PR link>\" and the PR is from `garrytan-agents/gstack`\n(or any other fork that is NOT a collaborator on `garrytan/gstack`), do NOT just\n`gh pr checkout`. Fork PRs don't receive base-repo secrets (`ANTHROPIC_API_KEY`,\n`OPENAI_API_KEY`, etc.), so the eval/E2E CI jobs fail with empty-env auth errors\nregardless of what's set on the base repo.\n\n**Workflow:** push the branch to `garrytan/gstack` (the base repo) and re-target\nthe PR from there.\n\nConcretely, after `gh pr checkout <N>`:\n\n1. Note the original PR number and head branch name.\n2. Push the same branch to the base repo: `git push origin HEAD:<branch-name>`\n   (origin = `garrytan/gstack`, since the worktree is set up with that remote).\n3. Close the fork PR (`gh pr close <N> --comment \"moving to base-repo branch for secret access\"`).\n4. Open a new PR from the base-repo branch: `gh pr create --base main --head <branch-name>`.\n5. New PR's workflows will get secrets automatically.\n\nWhy not fix it on the fork side? `garrytan-agents` isn't a collaborator on\n`garrytan/gstack`. Adding it as a collaborator (option A) or flipping the\nrepo-wide \"send secrets to fork PRs\" toggle (option B) would let secrets reach\nfork PRs from anyone — broader blast radius than just moving this one branch.\nOption C (this section) keeps secret-distribution scope tight.\n\nIf the user asks you to skip the move (e.g., \"just leave it as a fork PR\"),\nrespect that — eval CI will fail with empty-env auth, but check-freshness,\nworkflow-lint, and windows-tests will still pass on the fork PR.\n\n## CHANGELOG + VERSION style\n\n**Versioning invariant (workspace-aware ship).** VERSION is a monotonic ordered\nrelease identifier, not a strict semver commitment. The bump level\n(major/minor/patch/micro) expresses intent at ship time. Queue-advancing past a\nclaimed version within the same bump level is explicitly permitted — if branch A\nclaims v1.7.0.0 as a MINOR and branch B is also a MINOR, B lands at v1.8.0.0\n(still a MINOR relative to main). Downstream consumers must NOT rely on\n\"MINOR = feature-only, PATCH = fix-only\" as a strict contract. This is why\n`bin/gstack-next-version` advances within the chosen bump level rather than\nrepicking the level when collisions happen.\n\n**Scale-aware bumps — use common sense.** When the diff is big, bump MINOR (or\nMAJOR), not PATCH. PATCH is for bug fixes and small additions; MINOR is for\nsubstantial new capability or substantial reduction; MAJOR is for breaking\nchanges. Rough guideposts (don't treat as rules, treat as smell-checks):\n\n- **PATCH (X.Y.Z+1.0)**: bug fix, doc tweak, small additive change, single\n  test/file added. Net diff under ~500 lines, no new user-facing capability.\n- **MINOR (X.Y+1.0.0)**: new capability shipped (skill, harness, command, big\n  refactor), substantial code reduction (compression, migration), or coordinated\n  multi-file change. Net diff over ~2000 lines added/removed, OR a user-visible\n  feature you'd put in a tweet.\n- **MAJOR (X+1.0.0.0)**: breaking change to public surface (CLI flag rename,\n  skill removed, config format changed), OR a release big enough to be the\n  headline of a blog post.\n\nIf you find yourself debating \"is 10K added + 24K removed really a PATCH?\" — it\nisn't. Bump MINOR. Same for \"this adds a whole new test harness with 6 new E2E\ntests + helper utilities\" — MINOR. The bump level is communication to the user\nabout what kind of release this is; don't undersell it.\n\nWhen merging origin/main brings a higher VERSION, re-evaluate the bump level\nagainst the SCALE of your branch's work, not just whether main moved forward.\nIf main bumped MINOR and your branch is also a substantial change, you bump\nMINOR again on top (e.g., main at v1.14.0.0, your branch lands v1.15.0.0).\n\n**VERSION and CHANGELOG are branch-scoped.** Every feature branch that ships gets its\nown version bump and CHANGELOG entry. The entry describes what THIS branch adds —\nnot what was already on main.\n\n**The CHANGELOG entry is the diff between main and the shipping branch — what users\nget when they upgrade. NOT how the branch got there.** A reader landing on the entry\nshould learn what they can do now that they couldn't before; they should not learn\nabout the branch's internal version bumps, the bugs we caught and fixed mid-branch,\nthe plan reviews we ran, or the commits we squashed. That is branch development\nnarrative. It belongs in PR descriptions and commit messages, not CHANGELOG.\n\n**Never reference branch-internal versions in a CHANGELOG entry.** If your branch\nbumped VERSION from v1.5.0.0 → v1.5.1.0 → v1.6.0.0 during development and only the\nfinal v1.6.0.0 ships to main, the entry must read as if v1.5.1.0 never existed.\nConcretely, NEVER write:\n- \"v1.5.1.0 had a bug that v1.6.0.0 fixes\" — readers don't know about v1.5.1.0; it's\n  a branch-internal artifact.\n- \"The shipping headline of v1.5.1.0 was broken because...\" — same reason. From main's\n  perspective, v1.5.1.0 was never released.\n- \"Pre-fix tests encoded the broken behavior\" — that's a contributor's victory lap,\n  not a user benefit.\n- \"Two surgical edits, both in the dispatch path\" — micro-narrative of the patch.\n\nInstead, describe the released system: \"Browser-skills run end-to-end with the\nexpected tab-access semantics.\" If a property of the shipped system is worth calling\nout (e.g., \"skill spawns get permissive tab access; pair-agent tunnel tokens require\nownership\"), document it as a property, not as a fix. The shipped system is what\nthe user gets; the path to that system is invisible to them.\n\n**When to write the CHANGELOG entry:**\n- At `/ship` time (Step 13), not during development or mid-branch.\n- The entry covers ALL commits on this branch vs the base branch.\n- Never fold new work into an existing CHANGELOG entry from a prior version that\n  already landed on main. If main has v0.10.0.0 and your branch adds features,\n  bump to v0.10.1.0 with a new entry — don't edit the v0.10.0.0 entry.\n\n**Key questions before writing:**\n1. What branch am I on? What did THIS branch change?\n2. Is the base branch version already released? (If yes, bump and create new entry.)\n3. Does an existing entry on this branch already cover earlier work? (If yes, replace\n   it with one unified entry for the final version.)\n\n**Merging main does NOT mean adopting main's version.** When you merge origin/main into\na feature branch, main may bring new CHANGELOG entries and a higher VERSION. Your branch\nstill needs its OWN version bump on top. If main is at v0.13.8.0 and your branch adds\nfeatures, bump to v0.13.9.0 with a new entry. Never jam your changes into an entry that\nalready landed on main. Your entry goes on top because your branch lands next.\n\n**After merging main, always check:**\n- Does CHANGELOG have your branch's own entry separate from main's entries?\n- Is VERSION higher than main's VERSION?\n- Is your entry the topmost entry in CHANGELOG (above main's latest)?\nIf any answer is no, fix it before continuing.\n\n**After any CHANGELOG edit that moves, adds, or removes entries,** immediately run\n`grep \"^## \\[\" CHANGELOG.md` to verify no duplicates and a sensible reverse-chronological\norder. Gaps between version numbers are fine. A branch that ships at v1.6.4.0 without\na prior v1.5.2.0 or v1.5.3.0 entry on main is correct — those were branch-internal\nversion numbers that never landed. Do not back-fill gaps with placeholder entries.\n\n**Never orphan branch-internal versions.** If your branch bumped VERSION several times\nduring development (v1.5.1.0 → v1.5.2.0 → v1.6.4.0, say) and those earlier entries were\nnever released to main, the final ship consolidates ALL of them into a single entry at\nthe final version (v1.6.4.0). Collapse them — delete the old entries and move their\ncontent into the final entry, re-version table columns accordingly. Readers see one\nrelease, not a branch diary. Gaps are fine (v1.6.3.0 → v1.6.4.0 with no v1.5.x\nin between on main is correct).\n\nCHANGELOG.md is **for users**, not contributors. Write it like product release notes:\n\n- Lead with what the user can now **do** that they couldn't before. Sell the feature.\n- Use plain language, not implementation details. \"You can now...\" not \"Refactored the...\"\n- **Never mention TODOS.md, internal tracking, eval infrastructure, or contributor-facing\n  details.** These are invisible to users and meaningless to them.\n- Put contributor/internal changes in a separate \"For contributors\" section at the bottom.\n- Every entry should make someone think \"oh nice, I want to try that.\"\n- No jargon: say \"every question now tells you which project and branch you're in\" not\n  \"AskUserQuestion format standardized across skill templates via preamble resolver.\"\n\n**Only document what shipped between main and this change.** Readers do not care how\nwe got here. Keep out of the CHANGELOG, always:\n\n- Branch resyncs, merge commits with main, rebase activity.\n- Plan approvals, review outcomes (CEO / eng / design / outside-voice / codex findings),\n  AskUserQuestion decisions, scope negotiations.\n- \"Work queued,\" \"plan approved,\" \"in-progress,\" \"will ship later\" — the CHANGELOG\n  documents what DID ship, not what MIGHT ship.\n- Version-bump housekeeping when no user-facing work actually landed.\n\nIf the diff between the base branch version and this version has no user-facing change\n(only merges, only CHANGELOG edits, only placeholder work), the honest entry is one\nsentence: \"Version bump for branch-ahead discipline. No user-facing changes yet.\" Stop\nthere. Do not pad. Do not explain the plan that will ship eventually. Do not narrate\nthe branch's history. When real work lands, the entry will replace this at /ship time.\n\n### Release-summary format (every `## [X.Y.Z]` entry)\n\nEvery version entry in `CHANGELOG.md` MUST start with a release-summary section in\nthe GStack/Garry voice, one viewport's worth of prose + tables that lands like a\nverdict, not marketing. The itemized changelog (subsections, bullets, files) goes\nBELOW that summary, separated by a `### Itemized changes` header.\n\nThe release-summary section gets read by humans, by the auto-update agent, and by\nanyone deciding whether to upgrade. The itemized list is for agents that need to\nknow exactly what changed.\n\nStructure for the top of every `## [X.Y.Z]` entry:\n\n1. **Two-line bold headline** (10-14 words total). Should land like a verdict, not\n   marketing. Sound like someone who shipped today and cares whether it works.\n2. **Lead paragraph** (3-5 sentences). What shipped, what changed for the user.\n   Specific, concrete, no AI vocabulary, no em dashes, no hype.\n3. **A \"The X numbers that matter\" section** with:\n   - One short setup paragraph naming the source of the numbers (real production\n     deployment OR a reproducible benchmark, name the file/command to run).\n   - A table of 3-6 key metrics with BEFORE / AFTER / Δ columns.\n   - A second optional table for per-category breakdown if relevant.\n   - 1-2 sentences interpreting the most striking number in concrete user terms.\n4. **A \"What this means for [audience]\" closing paragraph** (2-4 sentences) tying\n   the metrics to a real workflow shift. End with what to do.\n\nVoice rules for the release summary:\n- No em dashes (use commas, periods, \"...\").\n- No AI vocabulary (delve, robust, comprehensive, nuanced, fundamental, etc.) or\n  banned phrases (\"here's the kicker\", \"the bottom line\", etc.).\n- Real numbers, real file names, real commands. Not \"fast\" but \"~30s on 30K pages.\"\n- Short paragraphs, mix one-sentence punches with 2-3 sentence runs.\n- Connect to user outcomes: \"the agent does ~3x less reading\" beats \"improved precision.\"\n- Be direct about quality. \"Well-designed\" or \"this is a mess.\" No dancing.\n\nSource material:\n- CHANGELOG previous entry for prior context.\n- Benchmark files or `/retro` output for headline numbers.\n- Recent commits (`git log <prev-version>..HEAD --oneline`) for what shipped.\n- Don't make up numbers. If a metric isn't in a benchmark or production data,\n  don't include it. Say \"no measurement yet\" if asked.\n\nTarget length: ~250-350 words for the summary. Should render as one viewport.\n\n### Itemized changes (below the release summary)\n\nWrite `### Itemized changes` and continue with the detailed subsections (Added,\nChanged, Fixed, For contributors). Same rules as the user-facing voice guidance\nabove, plus:\n\n- **Always credit community contributions.** When an entry includes work from a\n  community PR, name the contributor with `Contributed by @username`. Contributors\n  did real work. Thank them publicly every time, no exceptions.\n\n## AI effort compression\n\nWhen estimating or discussing effort, always show both human-team and CC+gstack time:\n\n| Task type | Human team | CC+gstack | Compression |\n|-----------|-----------|-----------|-------------|\n| Boilerplate / scaffolding | 2 days | 15 min | ~100x |\n| Test writing | 1 day | 15 min | ~50x |\n| Feature implementation | 1 week | 30 min | ~30x |\n| Bug fix + regression test | 4 hours | 15 min | ~20x |\n| Architecture / design | 2 days | 4 hours | ~5x |\n| Research / exploration | 1 day | 3 hours | ~3x |\n\nCompleteness is cheap. Don't recommend shortcuts when the complete implementation\nis achievable. Boil the ocean — the complete thing is the goal; only genuinely\nunrelated multi-quarter migrations are separate scope, never an excuse for a\nshortcut. See the Completeness Principle in the skill preamble for the full\nphilosophy.\n\n## Search before building\n\nBefore designing any solution that involves concurrency, unfamiliar patterns,\ninfrastructure, or anything where the runtime/framework might have a built-in:\n\n1. Search for \"{runtime} {thing} built-in\"\n2. Search for \"{thing} best practice {current year}\"\n3. Check official runtime/framework docs\n\nThree layers of knowledge: tried-and-true (Layer 1), new-and-popular (Layer 2),\nfirst-principles (Layer 3). Prize Layer 3 above all. See ETHOS.md for the full\nbuilder philosophy.\n\n## Local plans\n\nContributors can store long-range vision docs and design documents in `~/.gstack-dev/plans/`.\nThese are local-only (not checked in). When reviewing TODOS.md, check `plans/` for candidates\nthat may be ready to promote to TODOs or implement.\n\n## E2E eval failure blame protocol\n\nWhen an E2E eval fails during `/ship` or any other workflow, **never claim \"not\nrelated to our changes\" without proving it.** These systems have invisible couplings —\na preamble text change affects agent behavior, a new helper changes timing, a\nregenerated SKILL.md shifts prompt context.\n\n**Required before attributing a failure to \"pre-existing\":**\n1. Run the same eval on main (or base branch) and show it fails there too\n2. If it passes on main but fails on the branch — it IS your change. Trace the blame.\n3. If you can't run on main, say \"unverified — may or may not be related\" and flag it\n   as a risk in the PR body\n\n\"Pre-existing\" without receipts is a lazy claim. Prove it or don't say it.\n\n## Long-running tasks: don't give up\n\nWhen running evals, E2E tests, or any long-running background task, **poll until\ncompletion**. Use `sleep 180 && echo \"ready\"` + `TaskOutput` in a loop every 3\nminutes. Never switch to blocking mode and give up when the poll times out. Never\nsay \"I'll be notified when it completes\" and stop checking — keep the loop going\nuntil the task finishes or the user tells you to stop.\n\nThe full E2E suite can take 30-45 minutes. That's 10-15 polling cycles. Do all of\nthem. Report progress at each check (which tests passed, which are running, any\nfailures so far). The user wants to see the run complete, not a promise that\nyou'll check later.\n\n## Running evals as an agent: always detach (SIGTERM-proof)\n\nWhen **you (an agent/harness)** launch a long eval/benchmark run, run it through\n`bin/gstack-detach` — NEVER as a plain backgrounded Bash task. A plain background\ntask lives in the harness's process group, so a SIGTERM (\"polite quit\") on a turn\nboundary, a stopped Monitor, or an interruption kills the run mid-flight (observed:\n`script \"test:gate\" was terminated by signal SIGTERM` ~40 min into a run). On macOS\nthe run can also die to idle-sleep. `gstack-detach` fixes both: a fresh session\n(escapes the group SIGTERM) wrapped in `caffeinate -i` (blocks idle-sleep).\n\n- Use the `eval:bg*` scripts (`eval:bg`, `eval:bg:all`, `eval:bg:gate`,\n  `eval:bg:periodic`) — they wrap the eval command in `gstack-detach` with the\n  machine-wide `gstack-evals` lock (concurrent worktrees serialize instead of\n  saturating the shared model API), a per-tier watchdog, and a **run-scoped** log\n  under `~/.gstack-dev/eval-runs/` (no shared-`/tmp` collision). Each prints its\n  log path. `eval:bg:gate` / `eval:bg:periodic` run their tier through the\n  sharded paid runner (`scripts/test-paid-shards.ts`, also exposed as\n  `test:gate:sharded` / `test:periodic:sharded`): one Bun process per test\n  file, an external wall-clock timeout that kills the shard's process GROUP\n  (stray `claude`/`codex` grandchildren included), a per-shard\n  `GSTACK_EVAL_DIR=<evalDir>/shards/<slug>/` honored by the `EvalCollector`\n  constructor, and an aggregate that separates failed vs timed-out vs\n  never-started shards — the detach timeouts (25200s gate / 28800s periodic)\n  are sized against worst-case shard wall clock. `eval:list` / `eval:compare` /\n  `eval:summary` read the shard dirs too. Or call\n  `gstack-detach [--lock NAME] [--timeout SECS] [--label LBL] --\n  <cmd>` directly for any long agent job. Export `ANTHROPIC_API_KEY` first (never\n  pass keys in argv).\n- Then **poll the printed logfile** with a death-aware watcher: break on the\n  guaranteed `### gstack-detach EXIT=<code> ###` sentinel (success AND failure are\n  both marked, so silence is never mistaken for success). The detached run survives\n  even if your watcher gets reaped, so re-checking the log always works.\n- Why the lock: a shared dev box with several Conductor worktrees will rate-limit\n  the model API if two eval suites run at once (15-way concurrency each), which\n  mass-times-out E2E tests. The lock makes the second run WAIT, not collide.\n- Humans running `bun run test:evals` foreground in their own terminal don't need\n  this — Ctrl-C is intended there. Detachment is for agent-launched runs only.\n\n## E2E test fixtures: extract, don't copy\n\n**NEVER copy a full SKILL.md file into an E2E test fixture.** SKILL.md files are\n1500-2000 lines. When `claude -p` reads a file that large, context bloat causes\ntimeouts, flaky turn limits, and tests that take 5-10x longer than necessary.\n\nInstead, extract only the section the test actually needs:\n\n```typescript\n// BAD — agent reads 1900 lines, burns tokens on irrelevant sections\nfs.copyFileSync(path.join(ROOT, 'ship', 'SKILL.md'), path.join(dir, 'ship-SKILL.md'));\n\n// GOOD — agent reads ~60 lines, finishes in 38s instead of timing out\nconst full = fs.readFileSync(path.join(ROOT, 'ship', 'SKILL.md'), 'utf-8');\nconst start = full.indexOf('## Review Readiness Dashboard');\nconst end = full.indexOf('\\n---\\n', start);\nfs.writeFileSync(path.join(dir, 'ship-SKILL.md'), full.slice(start, end > start ? end : undefined));\n```\n\nAlso when running targeted E2E tests to debug failures:\n- Run in **foreground** (`bun test ...`), not background with `&` and `tee`\n- Never `pkill` running eval processes and restart — you lose results and waste money\n- One clean run beats three killed-and-restarted runs\n\n## Publishing native OpenClaw skills to ClawHub\n\nNative OpenClaw skills live in `openclaw/skills/gstack-openclaw-*/SKILL.md`. These are\nhand-crafted methodology skills (not generated by the pipeline) published to ClawHub\nso any OpenClaw user can install them.\n\n**Publishing:** The command is `clawhub publish` (NOT `clawhub skill publish`):\n\n```bash\nclawhub publish openclaw/skills/gstack-openclaw-office-hours \\\n  --slug gstack-openclaw-office-hours --name \"gstack Office Hours\" \\\n  --version 1.0.0 --changelog \"description of changes\"\n```\n\nRepeat for each skill: `gstack-openclaw-ceo-review`, `gstack-openclaw-investigate`,\n`gstack-openclaw-retro`. Bump `--version` on each update.\n\n**Auth:** `clawhub login` (opens browser for GitHub auth). `clawhub whoami` to verify.\n\n**Updating:** Same `clawhub publish` command with a higher `--version` and `--changelog`.\n\n**Verification:** `clawhub search gstack` to confirm they're live.\n\n## Deploying to the active skill\n\nThe active skill lives at `~/.claude/skills/gstack/`. After making changes:\n\n1. Push your branch\n2. Fetch and reset in the skill directory: `cd ~/.claude/skills/gstack && git fetch origin && git reset --hard origin/main`\n3. Rebuild: `cd ~/.claude/skills/gstack && bun run build`\n\n**If you use gbrain:** the `git reset --hard` in step 2 reverts the brain-aware\n(`GBRAIN_CONTEXT_LOAD` / `GBRAIN_SAVE_RESULTS`) blocks that `gstack-config\ngbrain-refresh` renders into the install (those generated blocks differ from\n`main` by design). After deploying, re-run `gstack-config gbrain-refresh` to\nrestore them across all your projects' Claude sessions. It's idempotent.\n\nOr copy the binaries directly:\n- `cp browse/dist/browse ~/.claude/skills/gstack/browse/dist/browse`\n- `cp design/dist/design ~/.claude/skills/gstack/design/dist/design`\n\n## Skill routing\n\nWhen the user's request matches an available skill, invoke it via the Skill tool. When in doubt, invoke the skill.\n\nKey routing rules:\n- Product ideas/brainstorming → invoke /office-hours\n- Strategy/scope → invoke /plan-ceo-review\n- Architecture → invoke /plan-eng-review\n- Design system/plan review → invoke /design-consultation or /plan-design-review\n- Full review pipeline → invoke /autoplan\n- Bugs/errors → invoke /investigate\n- QA/testing site behavior → invoke /qa or /qa-only\n- Code review/diff check → invoke /review\n- Visual polish → invoke /design-review\n- Ship/deploy/PR → invoke /ship or /land-and-deploy\n- Save progress → invoke /context-save\n- Resume context → invoke /context-restore\n\n## Cross-session decision memory\n\nDurable decisions and their rationale are captured in an append-only, event-sourced\nstore at `~/.gstack/projects/<slug>/decisions.jsonl` so neither you nor the user\nre-litigates a settled call or loses the \"why\" across sessions. This is the reliable,\nfile-only path: it works with gbrain OFF. (gbrain semantic recall is an optional\nenhancement layered on top, never a dependency.)\n\n- **Resurface** active decisions before re-deciding: `bin/gstack-decision-search`\n  (`--recent N`, `--scope repo|branch|issue`, `--query KW`, `--all`, `--json`).\n  Add `--semantic` (with `--query`) to append related hits from gbrain memory when\n  it's up; it degrades silently to the reliable file results when gbrain is off.\n  Session start already surfaces scope-relevant active decisions via Context Recovery.\n  If a decision is listed, treat it as settled with its rationale; if you're about to\n  reverse it, say so explicitly.\n- **Capture** a DURABLE decision when you or the user make one:\n  `bin/gstack-decision-log '{\"decision\":\"...\",\"rationale\":\"...\",\"scope\":\"repo|branch|issue\",\"source\":\"user|skill|agent\",\"confidence\":1-10}'`.\n  Reverse a prior call with `--supersede <id>`; expunge an accidental secret with\n  `--redact <id>`; rewrite the log to the active set with `--compact`. Non-interactive\n  (never prompts), injection-sanitized, and HIGH-secret-blocking on write.\n- **Durable means:** architecture choice, scope cut, tool/vendor choice, or a reversal\n  of a prior call. NOT a turn-level edit, a phrasing tweak, or anything trivially\n  re-derivable. Capture is curated at the source — log durable decisions only, or the\n  store becomes noise.\n\n## GBrain Search Guidance (configured by /sync-gbrain)\n<!-- gstack-gbrain-search-guidance:start -->\n\nGBrain is set up and synced on this machine. The agent should prefer gbrain\nover Grep when the question is semantic or when you don't know the exact\nidentifier yet.\n\n**This worktree is pinned to a worktree-scoped code source** via the\n`.gbrain-source` file in the repo root (kubectl-style context). Any\n`gbrain code-def`, `code-refs`, `code-callers`, `code-callees`, or `query`\ncall from anywhere under this worktree routes to that source by default —\nno `--source` flag needed. Conductor sibling worktrees of the same repo\neach have their own pin and their own indexed pages, so semantic results\nmatch the actual code on disk in this worktree.\n\nTwo indexed corpora available via the `gbrain` CLI:\n- This worktree's code (auto-pinned via `.gbrain-source`).\n- `~/.gstack/` curated memory (registered as `gstack-brain-<user>` source via\n  the existing federation pipeline).\n\nPrefer gbrain when:\n- \"Where is X handled?\" / semantic intent, no exact string yet:\n    `gbrain search \"<terms>\"` or `gbrain query \"<question>\"`\n- \"Where is symbol Y defined?\" / symbol-based code questions:\n    `gbrain code-def <symbol>` or `gbrain code-refs <symbol>`\n- \"What calls Y?\" / \"What does Y depend on?\":\n    `gbrain code-callers <symbol>` / `gbrain code-callees <symbol>`\n- \"What did we decide last time?\" / past plans, retros, learnings:\n    `gbrain search \"<terms>\" --source gstack-brain-<user>`\n\nGrep is still right for known exact strings, regex, multiline patterns, and\nfile globs. Run `/sync-gbrain` after meaningful code changes; for ongoing\nauto-sync across all worktrees, run `gbrain autopilot --install` once per\nmachine — gbrain's daemon handles incremental refresh on a schedule.\n\nSafety: don't run `/sync-gbrain` while `gbrain autopilot` is active — the\norchestrator refuses destructive source ops when it detects a running autopilot\nto avoid racing it (#1734). Prefer registering user repos with `gbrain sources\nadd --path <dir>` (no `--url`): URL-managed sources can auto-reclone, and the\nsync code walk for them requires an explicit `--allow-reclone` opt-in.\n\n<!-- gstack-gbrain-search-guidance:end -->\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","title":"AGENTS.md","content":"# gstack — AI Engineering Workflow\n\ngstack is a collection of SKILL.md files that give AI agents structured roles for\nsoftware development. Each skill is a specialist: CEO reviewer, eng manager,\ndesigner, QA lead, release engineer, debugger, and more.\n\n## Available skills\n\nSkills live in `.agents/skills/` (or `~/.claude/skills/gstack/` on Claude Code).\nInvoke them by name (e.g., `/office-hours`).\n\n### Plan-mode reviews\n\n| Skill | What it does |\n|-------|-------------|\n| `/office-hours` | Start here. Reframes your product idea before you write code. |\n| `/plan-ceo-review` | CEO-level review: find the 10-star product in the request. |\n| `/plan-eng-review` | Lock architecture, data flow, edge cases, and tests. |\n| `/plan-design-review` | Rate each design dimension 0-10, explain what a 10 looks like. |\n| `/plan-devex-review` | DX-mode review: TTHW, magical moments, friction points, persona traces. |\n| `/plan-tune` | Self-tune AskUserQuestion sensitivity per question. |\n| `/autoplan` | One command runs CEO → design → eng → DX review. |\n| `/design-consultation` | Build a complete design system from scratch. |\n| `/spec` | Turn vague intent into a precise, executable spec in five phases. Files a GitHub issue, optionally spawns a Claude Code agent in a fresh worktree, and lets `/ship` close the source issue on merge. |\n\n### Implementation + review\n\n| Skill | What it does |\n|-------|-------------|\n| `/review` | Pre-landing PR review. Finds bugs that pass CI but break in prod. |\n| `/codex` | Second opinion via OpenAI Codex. Review, challenge, or consult modes. |\n| `/investigate` | Systematic root-cause debugging. No fixes without investigation. |\n| `/design-review` | Live-site visual audit + fix loop with atomic commits. |\n| `/design-shotgun` | Generate multiple AI design variants, comparison board, iterate. |\n| `/design-html` | Generate production-quality Pretext-native HTML/CSS. |\n| `/devex-review` | Live developer experience audit (TTHW measured against the real flow). |\n| `/qa` | Open a real browser, find bugs, fix them, re-verify. |\n| `/qa-only` | Same methodology as /qa but report only — no code changes. |\n| `/scrape` | Pull data from a web page. First call prototypes; codified call runs in ~200ms. |\n| `/skillify` | Codify the most recent successful `/scrape` flow into a permanent browser-skill. |\n\n### Release + deploy\n\n| Skill | What it does |\n|-------|-------------|\n| `/ship` | Run tests, review, push, open PR. Workspace-aware version queue. |\n| `/land-and-deploy` | Merge the PR, wait for CI and deploy, verify production health. |\n| `/canary` | Post-deploy monitoring loop using the browse daemon. |\n| `/landing-report` | Read-only dashboard for the workspace-aware ship queue. |\n| `/document-release` | Update all docs to match what you just shipped. |\n| `/document-generate` | Generate Diataxis docs (tutorial / how-to / reference / explanation) from code. |\n| `/setup-deploy` | One-time deploy config detection (Fly.io, Render, Vercel, etc.). |\n| `/gstack-upgrade` | Update gstack to the latest version. |\n\n### Operational + memory\n\n| Skill | What it does |\n|-------|-------------|\n| `/context-save` | Save working context (git state, decisions, remaining work). |\n| `/context-restore` | Resume from a saved context, even across Conductor workspaces. |\n| `/learn` | Manage what gstack learned across sessions. |\n| `/retro` | Weekly retro with per-person breakdowns and shipping streaks. |\n| `/health` | Code quality dashboard (type checker, linter, tests, dead code). |\n| `/benchmark` | Performance regression detection (page load, Core Web Vitals). |\n| `/benchmark-models` | Cross-model benchmark for skills (Claude, GPT, Gemini side-by-side). |\n| `/cso` | OWASP Top 10 + STRIDE security audit. |\n| `/setup-gbrain` | Set up gbrain for cross-machine session memory sync. |\n| `/sync-gbrain` | Keep gbrain current with this repo's code; refresh agent search guidance in CLAUDE.md. |\n\n### Browser + agent integration\n\n| Skill | What it does |\n|-------|-------------|\n| `/browse` | Headless browser — real Chromium, real clicks, ~100ms/command. |\n| `/open-gstack-browser` | Launch the visible GStack Browser with sidebar + stealth. |\n| `/setup-browser-cookies` | Import cookies from your real browser for authenticated testing. |\n| `/pair-agent` | Pair a remote AI agent (OpenClaw, Codex, etc.) with your browser. |\n\n### iOS QA — drive real iPhones over USB or Tailscale (v1.43.0.0+)\n\n| Skill | What it does |\n|-------|-------------|\n| `/ios-qa` | Live-device iOS QA via USB CoreDevice tunnel + embedded StateServer. Optionally exposes the device over Tailscale so remote agents can drive it. |\n| `/ios-fix` | Autonomous iOS bug fixer with regression snapshot capture. |\n| `/ios-design-review` | Designer's-eye QA on a real iPhone — 10-dimension Apple HIG rubric. |\n| `/ios-clean` | Convenience: strip DebugBridge + #if DEBUG wiring before a Release build. |\n| `/ios-sync` | Regenerate the iOS debug bridge against the latest upstream templates. |\n\nCompanion CLIs (run on the Mac that's plugged into the device):\n\n| Command | What it does |\n|---------|-------------|\n| `gstack-ios-qa-daemon` | Mac-side broker. Loopback by default; `--tailnet` adds a Tailscale-facing listener with capability tiers and audit logging. |\n| `gstack-ios-qa-mint` | Owner-grant CLI for the tailnet allowlist (`grant`/`revoke`/`list`). |\n| `gstack-ios-qa-regen` | Regenerate the canonical local DebugBridge package and typed accessors (`--app-source` / `--bridge-dir`). |\n\nEnd-to-end walkthrough: [docs/howto-ios-testing-with-gstack.md](docs/howto-ios-testing-with-gstack.md).\n\n### Safety + scoping\n\n| Skill | What it does |\n|-------|-------------|\n| `/careful` | Warn before destructive commands (rm -rf, DROP TABLE, force-push). |\n| `/freeze` | Lock edits to one directory. Hard block, not just a warning. |\n| `/guard` | Activate both careful + freeze at once. |\n| `/unfreeze` | Remove directory edit restrictions. |\n| `/make-pdf` | Turn any markdown file into a publication-quality PDF. |\n| `/diagram` | English in, diagram out: mermaid source + editable .excalidraw + SVG/PNG, offline. |\n\n## Build commands\n\n```bash\nbun install              # install dependencies\nbun test                 # run free tests (no API spend)\nbun run test:windows     # curated Windows-safe subset (runs on windows-latest)\nbun run build            # generate docs + compile binaries\nbun run gen:skill-docs   # regenerate SKILL.md files from templates\nbun run skill:check      # health dashboard for all skills\n```\n\n## Platform support\n\n- **macOS** + **Linux**: full test suite supported.\n- **Windows**: curated Windows-safe subset runs on `windows-latest` via the\n  `windows-free-tests` CI job. Setup script (`./setup`) requires Git Bash or\n  MSYS today; native PowerShell support is a future expansion. The `bin/gstack-paths`\n  helper resolves state roots through `CLAUDE_PLUGIN_DATA` / `GSTACK_HOME` so plugin\n  installs work on every platform.\n\n## Key conventions\n\n- SKILL.md files are **generated** from `.tmpl` templates. Edit the template, not the output.\n- Run `bun run gen:skill-docs --host codex` to regenerate Codex-specific output.\n- The browse binary provides headless browser access. Use `$B <command>` in skills.\n- Safety skills (careful, freeze, guard) use inline advisory prose — always confirm before destructive operations.\n- State paths resolve via `bin/gstack-paths` (sourced via `eval \"$(...)\"`). Honors `GSTACK_HOME`, `CLAUDE_PLUGIN_DATA`, `CLAUDE_PLANS_DIR`.\n- The `claude` CLI binary resolves via `browse/src/claude-bin.ts` (`Bun.which()` + `GSTACK_CLAUDE_BIN` override). Set `GSTACK_CLAUDE_BIN=wsl` plus `GSTACK_CLAUDE_BIN_ARGS='[\"claude\"]'` to run Claude through WSL on Windows.\n","category":"root","tokens":1927},{"name":"CLAUDE.md","path":"CLAUDE.md","title":"CLAUDE.md","content":"# gstack development\n\n## Commands\n\n```bash\nbun install          # install dependencies\nbun test             # run free tests (browse + snapshot + skill validation)\nbun run test:evals   # run paid evals: LLM judge + E2E (diff-based, ~$4/run max)\nbun run test:evals:all  # run ALL paid evals regardless of diff\nbun run test:gate    # run gate-tier tests only (CI default, blocks merge)\nbun run test:periodic  # run periodic-tier tests only (weekly cron / manual)\nbun run test:gate:sharded    # gate tier via the sharded paid runner (one Bun process per test file)\nbun run test:periodic:sharded  # periodic tier via the sharded paid runner (implies EVALS_ALL=1)\nbun run test:e2e     # run E2E tests only (diff-based, ~$3.85/run max)\nbun run test:e2e:all # run ALL E2E tests regardless of diff\nbun run eval:select  # show which tests would run based on current diff\nbun run dev <cmd>    # run CLI in dev mode, e.g. bun run dev goto https://example.com\nbun run build        # gen docs + compile binaries\nbun run gen:skill-docs  # regenerate SKILL.md files from templates\nbun run skill:check  # health dashboard for all skills\nbun run dev:skill    # watch mode: auto-regen + validate on change\nbun run eval:list    # list all eval runs from ~/.gstack-dev/evals/\nbun run eval:compare # compare two eval runs (auto-picks most recent)\nbun run eval:summary # aggregate stats across all eval runs\nbun run slop          # full slop-scan report (all files)\nbun run slop:diff     # slop findings in files changed on this branch only\n```\n\n`test:evals` requires `ANTHROPIC_API_KEY`. Codex E2E tests (`test/codex-e2e.test.ts`)\nuse Codex's own auth from `~/.codex/` config — no `OPENAI_API_KEY` env var needed.\n\n**Env keys in Conductor workspaces.** The `GSTACK_*` env-shim (v1.39.2.0+,\n`lib/conductor-env-shim.ts`) promotes `GSTACK_ANTHROPIC_API_KEY` /\n`GSTACK_OPENAI_API_KEY` to their canonical names inside gstack's TS binaries.\nTests run through gstack entrypoints inherit this promotion automatically.\nDon't echo the key value to stdout, logs, or shell history. The historical\n\"never pass `env:` to `runAgentSdkTest`\" rule is retired: the failure was\npartial-env replacement (the SDK's `Options.env` REPLACES the child's entire\nenvironment, so an object without the key broke auth). The runner now always\npasses a COMPLETE hermetic env with per-test `env:` merged last, so per-test\noverrides are safe; ambient `process.env.ANTHROPIC_API_KEY` mutation also\nstill works (the env builder reads process.env at call time).\n\n**Hermetic local E2E (default).** Every E2E runner (claude -p, PTY, Agent\nSDK, codex, gemini) spawns children through `test/helpers/hermetic-env.ts`:\nallowlist-scrubbed env (operator `CONDUCTOR_*`, `CLAUDE_*`, `GSTACK_*`,\n`MCP_*`, `GBRAIN_*`, and credentials like `GH_TOKEN` never reach children),\na fresh seeded `CLAUDE_CONFIG_DIR` (no operator `~/.claude` CLAUDE.md /\nMCP servers / skills), a temp `GSTACK_HOME`, and `--strict-mcp-config`.\nLocal eval signal matches CI. Debug against real operator state with\n`EVALS_HERMETIC=0` (restores the legacy env AND drops the strict-MCP flag).\nPer-test `env:` overrides merge last, so deliberate contamination\n(`CONDUCTOR_WORKSPACE_PATH`, per-test `GSTACK_HOME`) keeps working. The\nhermetic config dir seeds NO skills by default; a PTY test that types a\n`/skill` slash command must pass `seedSkills: true` to the PTY runner, which\npoints the child's `CLAUDE_CONFIG_DIR` at `hermeticSkillsConfigDir()` — a\nseeded registry that symlinks the LIVE working tree's SKILL.md files (by\ndesign: the skills ARE the subject under test; a snapshot would measure stale\ncopies). Wiring is pinned by `test/hermetic-wiring.test.ts` (static tripwire),\ntwo gate-tier canaries in `test/skill-e2e-hermetic-canary.test.ts`, and the\nseeding tripwires in `test/hermetic-skills-seeding.test.ts` /\n`test/pty-skill-seeding-wiring.test.ts`.\n\nE2E tests stream progress in real-time (tool-by-tool via `--output-format stream-json\n--verbose`). Results are persisted to `~/.gstack-dev/evals/` with auto-comparison\nagainst the previous finalized run (in-flight `_partial` files are never used as\na baseline, so a run can't compare against itself).\n\n**Diff-based test selection:** `test:evals` and `test:e2e` auto-select tests based\non `git diff` against the base branch. Each test declares its file dependencies in\n`test/helpers/touchfiles.ts`. Changes to global touchfiles (session-runner, eval-store,\ntouchfiles.ts itself) trigger all tests. Use `EVALS_ALL=1` or the `:all` script\nvariants to force all tests. Run `eval:select` to preview which tests would run.\n\n**Two-tier system:** Tests are classified as `gate` or `periodic` in `E2E_TIERS`\n(in `test/helpers/touchfiles.ts`). CI runs only gate tests (`EVALS_TIER=gate`);\nperiodic tests run weekly via cron or manually. Use `EVALS_TIER=gate` or\n`EVALS_TIER=periodic` to filter. When adding new E2E tests, classify them:\n1. Safety guardrail or deterministic functional test? -> `gate`\n2. Quality benchmark, Opus model test, or non-deterministic? -> `periodic`\n3. Requires external service (Codex, Gemini)? -> `periodic`\n\nTier declarations are enforced by `test/e2e-tier-alignment.test.ts` (free, runs\nin `bun test`): a `skill-e2e-*` file named in a touchfiles dep list whose\n`EVALS_TIER` self-gate disagrees with its declared tier in `E2E_TIERS` fails the\nsuite. Files not named in any dep list are reported, not enforced — keep both\nin sync.\n\n## Testing\n\n```bash\nbun test             # run before every commit — free, <2s\nbun run test:evals   # run before shipping — paid, diff-based (~$4/run max)\n```\n\n`bun test` runs skill validation, gen-skill-docs quality checks, and browse\nintegration tests. `bun run test:evals` runs LLM-judge quality evals and E2E\ntests via `claude -p`. Both must pass before creating a PR.\n\n## Project structure\n\n```\ngstack/\n├── browse/          # Headless browser CLI (Playwright)\n│   ├── src/         # CLI + server + commands\n│   │   ├── commands.ts  # Command registry (single source of truth)\n│   │   └── snapshot.ts  # SNAPSHOT_FLAGS metadata array\n│   ├── test/        # Integration tests + fixtures\n│   └── dist/        # Compiled binary\n├── hosts/           # Typed host configs (one per AI agent)\n│   ├── claude.ts    # Primary host config\n│   ├── codex.ts, factory.ts, kiro.ts  # Existing hosts\n│   ├── opencode.ts, slate.ts, cursor.ts, openclaw.ts  # IDE hosts\n│   ├── hermes.ts, gbrain.ts  # Agent runtime hosts\n│   └── index.ts     # Registry: exports all, derives Host type\n├── scripts/         # Build + DX tooling\n│   ├── gen-skill-docs.ts  # Template → SKILL.md generator (config-driven)\n│   ├── host-config.ts     # HostConfig interface + validator\n│   ├── host-config-export.ts  # Shell bridge for setup script\n│   ├── host-adapters/     # Host-specific adapters (OpenClaw tool mapping)\n│   ├── resolvers/   # Template resolver modules (preamble, design, review, gbrain, etc.)\n│   ├── skill-check.ts     # Health dashboard\n│   ├── test-paid-shards.ts  # Sharded paid-tier runner (one Bun process per shard)\n│   └── dev-skill.ts       # Watch mode\n├── test/            # Skill validation + eval tests\n│   ├── helpers/     # skill-parser.ts, session-runner.ts, llm-judge.ts, eval-store.ts\n│   ├── fixtures/    # Ground truth JSON, planted-bug fixtures, eval baselines\n│   ├── skill-validation.test.ts  # Tier 1: static validation (free, <1s)\n│   ├── gen-skill-docs.test.ts    # Tier 1: generator quality (free, <1s)\n│   ├── skill-llm-eval.test.ts   # Tier 3: LLM-as-judge (~$0.15/run)\n│   └── skill-e2e-*.test.ts       # Tier 2: E2E via claude -p (~$3.85/run, split by category)\n├── qa-only/         # /qa-only skill (report-only QA, no fixes)\n├── plan-design-review/  # /plan-design-review skill (report-only design audit)\n├── design-review/    # /design-review skill (design audit + fix loop)\n├── ship/            # Ship workflow skill\n├── review/          # PR review skill\n├── plan-ceo-review/ # /plan-ceo-review skill\n├── plan-eng-review/ # /plan-eng-review skill\n├── autoplan/        # /autoplan skill (auto-review pipeline: CEO → design → eng)\n├── benchmark/       # /benchmark skill (performance regression detection)\n├── canary/          # /canary skill (post-deploy monitoring loop)\n├── codex/           # /codex skill (multi-AI second opinion via OpenAI Codex CLI)\n├── land-and-deploy/ # /land-and-deploy skill (merge → deploy → canary verify)\n├── office-hours/    # /office-hours skill (YC Office Hours — startup diagnostic + builder brainstorm)\n├── investigate/     # /investigate skill (systematic root-cause debugging)\n├── spec/            # /spec skill (five-phase spec → GitHub issue, optional agent spawn, /ship auto-closes)\n├── retro/           # Retrospective skill (includes /retro global cross-project mode)\n├── bin/             # CLI utilities (gstack-repo-mode, gstack-slug, gstack-config, etc.)\n├── document-release/ # /document-release skill (post-ship doc updates + Diataxis coverage map)\n├── document-generate/ # /document-generate skill (Diataxis doc generator: tutorial/how-to/reference/explanation)\n├── cso/             # /cso skill (OWASP Top 10 + STRIDE security audit)\n├── design-consultation/ # /design-consultation skill (design system from scratch)\n├── design-shotgun/  # /design-shotgun skill (visual design exploration)\n├── open-gstack-browser/  # /open-gstack-browser skill (launch GStack Browser)\n├── connect-chrome/  # symlink → open-gstack-browser (backwards compat)\n├── design/          # Design binary CLI (GPT Image API)\n│   ├── src/         # CLI + commands (generate, variants, compare, serve, etc.)\n│   ├── test/        # Integration tests\n│   └── dist/        # Compiled binary\n├── extension/       # Chrome extension (side panel + activity feed + CSS inspector)\n├── lib/             # Shared libraries (worktree.ts, egress-receipt.ts, context-bill.ts, redact-engine.ts)\n├── docs/designs/    # Design documents\n├── setup-deploy/    # /setup-deploy skill (one-time deploy config)\n├── .github/         # CI workflows + Docker image\n│   ├── workflows/   # evals.yml (E2E on Ubicloud), skill-docs.yml, actionlint.yml\n│   └── docker/      # Dockerfile.ci (pre-baked toolchain + Playwright/Chromium)\n├── contrib/         # Contributor-only tools (never installed for users)\n│   └── add-host/    # /gstack-contrib-add-host skill\n├── setup            # One-time setup: build binary + symlink skills\n├── SKILL.md         # Generated from SKILL.md.tmpl (don't edit directly)\n├── SKILL.md.tmpl    # Template: edit this, run gen:skill-docs\n├── ETHOS.md         # Builder philosophy (Boil the Ocean, Search Before Building)\n└── package.json     # Build scripts for browse\n```\n\n## SKILL.md workflow\n\nSKILL.md files are **generated** from `.tmpl` templates. To update docs:\n\n1. Edit the `.tmpl` file (e.g. `SKILL.md.tmpl` or `browse/SKILL.md.tmpl`)\n2. Run `bun run gen:skill-docs` (or `bun run build` which does it automatically)\n3. Commit both the `.tmpl` and generated `.md` files\n\nTo add a new browse command: add it to `browse/src/commands.ts` and rebuild.\nTo add a snapshot flag: add it to `SNAPSHOT_FLAGS` in `browse/src/snapshot.ts` and rebuild.\n\n**Token ceiling:** Generated SKILL.md files trip a warning above 160KB (~40K tokens).\nThis is a \"watch for feature bloat\" guardrail, not a hard gate. Modern flagship\nmodels have 200K-1M context windows, so 40K is 4-20% of window, and prompt caching\nmakes the marginal cost of larger skills small. The ceiling exists to catch runaway\npreamble/resolver growth, not to force compression on carefully-tuned big skills\n(`ship`, `plan-ceo-review`, `office-hours` legitimately pack 25-35K tokens of\nbehavior). If you blow past 40K, the right fix is usually: (1) look at WHAT grew,\n(2) if one resolver added 10K+ in a single PR, question whether it belongs inline\nor as a reference doc, (3) only compress carefully-tuned prose as a last resort —\ncuts to the coverage audit, review army, or voice directive have real quality cost.\n\nA second, harder ceiling guards the DISCOVERY surface: `test/catalog-budget.test.ts`\ncaps the aggregate frontmatter `name` + `description` across all skills at 1,150\ntoken-equivalents (260-byte per-skill sub-cap), counted through the shared census\nin `test/helpers/skill-census.ts`. This one is enforced, not a warning — every\nhost loads the full catalog every session, so growth here taxes every\nconversation. The failure message carries the re-measure + ratchet protocol.\n`bin/gstack-context-bill` shows the full token bill-of-materials for a skills\ntree (always-on vs per-invocation, `--diff`, `--budget`; `--exact` opts into the\nreal tokenizer and POSTs file text to api.anthropic.com with an egress receipt).\n\n**Merge conflicts on SKILL.md files:** NEVER resolve conflicts on generated SKILL.md\nfiles by accepting either side. Instead: (1) resolve conflicts on the `.tmpl` templates\nand `scripts/gen-skill-docs.ts` (the sources of truth), (2) run `bun run gen:skill-docs`\nto regenerate all SKILL.md files, (3) stage the regenerated files. Accepting one side's\ngenerated output silently drops the other side's template changes.\n\n## Platform-agnostic design\n\nSkills must NEVER hardcode framework-specific commands, file patterns, or directory\nstructures. Instead:\n\n1. **Read CLAUDE.md** for project-specific config (test commands, eval commands, etc.)\n2. **If missing, AskUserQuestion** — let the user tell you or let gstack search the repo\n3. **Persist the answer to CLAUDE.md** so we never have to ask again\n\nThis applies to test commands, eval commands, deploy commands, and any other\nproject-specific behavior. The project owns its config; gstack reads it.\n\n## Writing SKILL templates\n\nSKILL.md.tmpl files are **prompt templates read by Claude**, not bash scripts.\nEach bash code block runs in a separate shell — variables do not persist between blocks.\n\nRules:\n- **Use natural language for logic and state.** Don't use shell variables to pass\n  state between code blocks. Instead, tell Claude what to remember and reference\n  it in prose (e.g., \"the base branch detected in Step 0\").\n- **Don't hardcode branch names.** Detect `main`/`master`/etc dynamically via\n  `gh pr view` or `gh repo view`. Use `{{BASE_BRANCH_DETECT}}` for PR-targeting\n  skills. Use \"the base branch\" in prose, `<base>` in code block placeholders.\n- **Keep bash blocks self-contained.** Each code block should work independently.\n  If a block needs context from a previous step, restate it in the prose above.\n- **Express conditionals as English.** Instead of nested `if/elif/else` in bash,\n  write numbered decision steps: \"1. If X, do Y. 2. Otherwise, do Z.\"\n\n## Writing style (V1)\n\nDefault output from every tier-≥2 skill follows the Writing Style section in\n`scripts/resolvers/preamble.ts`: jargon glossed on first use (curated list in\n`scripts/jargon-list.json`, baked at gen-skill-docs time), questions framed in\noutcome terms (\"what breaks for your users if...\") not implementation terms,\nshort sentences, decisions close with user impact. Power users who want the\ntighter V0 prose set `gstack-config set explain_level terse` (binary switch,\nno middle mode). See `docs/designs/PLAN_TUNING_V1.md` for the full design\nrationale. The review pacing overhaul that originally tried to ride alongside\nwriting-style was extracted to V1.1 — see `docs/designs/PACING_UPDATES_V0.md`.\n\n## Browser interaction\n\nWhen you need to interact with a browser (QA, dogfooding, cookie setup), use the\n`/browse` skill or run the browse binary directly via `$B <command>`. NEVER use\n`mcp__claude-in-chrome__*` tools — they are slow, unreliable, and not what this\nproject uses.\n\n**Sidebar architecture:** Before modifying `sidepanel.js`, `background.js`,\n`content.js`, `terminal-agent.ts`, or sidebar-related server endpoints,\nread `docs/designs/SIDEBAR_MESSAGE_FLOW.md`. The sidebar has one primary\nsurface — the **Terminal** pane (interactive `claude` PTY) — with\nActivity / Refs / Inspector as debug overlays behind the footer's\n`debug` toggle. The chat queue path was ripped once the PTY proved out;\n`sidebar-agent.ts` and the `/sidebar-command` / `/sidebar-chat` /\n`/sidebar-agent/event` endpoints are gone. The doc covers the WS auth\nflow, dual-token model, and threat-model boundary — silent failures\nhere usually trace to not understanding the cross-component flow.\n\n**Embedder terminal-agent ownership** (v1.42.1.0+, identity-based kill v1.44.0.0+).\n`buildFetchHandler` in `browse/src/server.ts` accepts `ServerConfig.ownsTerminalAgent?:\nboolean` (default `true`). When `true`, factory shutdown runs the full teardown:\nidentity-based kill via `killAgentByRecord(readAgentRecord(stateDir))` from\n`browse/src/terminal-agent-control.ts` plus `safeUnlinkQuiet` on\n`<stateDir>/terminal-port`, `<stateDir>/terminal-internal-token`, and\n`<stateDir>/terminal-agent-pid` (the per-boot agent record introduced in v1.44).\nEmbedders (e.g. the gbrowser phoenix overlay) that pre-launch their own PTY\nserver must pass `false` so their discovery files survive gstack teardown cycles.\nThe flag is the third caller-owned teardown gate in `ServerConfig` (alongside\n`xvfb?` and `proxyBridge?`); polarity is inverted (explicit bool vs presence) and\ndocumented in the field's JSDoc. CLI `start()` always passes `true` explicitly —\nthe static-grep test in `browse/test/server-embedder-terminal-port.test.ts` fails\nCI if a refactor drops it. Pre-v1.44 used `pkill -f terminal-agent\\.ts` (regex\nmatch) which would kill sibling gstack sessions on the same host; the new\n`browse/test/terminal-agent-pid-identity.test.ts` static-grep tripwire fails CI\nif any source file re-introduces `pkill ... terminal-agent` or `spawnSync('pkill', ...)`.\n\n**WebSocket auth uses Sec-WebSocket-Protocol, not cookies.** Browsers\ncan't set `Authorization` on a WebSocket upgrade, but they CAN set\n`Sec-WebSocket-Protocol` via `new WebSocket(url, [token])`. The agent\nreads it, validates against `validTokens`, and MUST echo the protocol\nback in the upgrade response — without the echo, Chromium closes the\nconnection immediately. `Set-Cookie: gstack_pty=...` is kept as a\nfallback for non-browser callers (the cross-port `SameSite=Strict`\ncookie path doesn't survive from a chrome-extension origin).\n\n**Cross-pane PTY injection.** The toolbar's Cleanup button and the\nInspector's \"Send to Code\" action both pipe text into the live claude\nPTY via `window.gstackInjectToTerminal(text)`, exposed by\n`sidepanel-terminal.js`. No `/sidebar-command` POST — the live REPL is\nthe only execution surface in the sidebar now.\n\n**`/health` MUST NOT surface any token — and it no longer does** (v1.63+).\nThe historical headed-mode leak of `AUTH_TOKEN` is fixed: `GET /health` is\nliveness/status only in every mode. Token bootstrap is `POST /extension-token`,\nwhich validates the caller's Origin against the pinned extension identity\n(the `key` field in `extension/manifest.json` pins the extension ID —\n`GSTACK_EXTENSION_ID` in `browse/src/server.ts`, derivation reproducible via\n`bun browse/scripts/extension-id.ts`) plus a loopback Host. PTY auth still\nflows through `POST /pty-session` only. Don't add any token to `/health`.\n\n**Transport-layer security** (v1.6.0.0+). When `pair-agent` starts an ngrok tunnel,\nthe daemon binds two HTTP listeners: a local listener (127.0.0.1, full command\nsurface, never forwarded) and a tunnel listener (locked allowlist: `/connect`,\n`/command` with a scoped token + 26-command browser-driving allowlist,\n`/sidebar-chat`). ngrok forwards only the tunnel port. Root tokens over the tunnel\nreturn 403. SSE endpoints use a 30-minute HttpOnly `gstack_sse` cookie minted via\n`POST /sse-session` (never valid against `/command`). Tunnel-surface rejections go\nto `~/.gstack/security/attempts.jsonl` via `tunnel-denial-log.ts`. Before editing\n`server.ts`, `sse-session-cookie.ts`, or `tunnel-denial-log.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#dual-listener-tunnel-architecture-v1600) —\nthe module boundary (no imports from `token-registry.ts` into `sse-session-cookie.ts`)\nis load-bearing for scope isolation.\n\n**Unicode sanitization at server egress** (v1.38.0.0+). Every server egress that\nships page-content-derived strings MUST go through `JSON.stringify(payload,\nsanitizeReplacer)` for object payloads or `sanitizeLoneSurrogates(body)` for text\nbodies. Lone UTF-16 surrogate halves from CDP page content otherwise reach the\nAnthropic API as `\\uD800`-style escapes and trigger a 400. Wired at four egress\npoints today: `handleCommandInternal` (HTTP + batch via a sanitizing wrapper around\n`handleCommandInternalImpl`) and both SSE producers (`/activity/stream`,\n`/inspector/events`). Post-stringify regex is a no-op — `JSON.stringify` has\nalready escaped the surrogate before regex could match, so the replacer must run\ninside the encoding pipeline. Before adding a new SSE/WebSocket writer or HTTP\nresponse in `server.ts`, read\n[ARCHITECTURE.md](ARCHITECTURE.md#unicode-sanitization-at-server-egress-v13800).\n`browse/test/server-sanitize-surrogates.test.ts` pins the wiring with invariant\ntests, so bypasses fail CI.\n\n**Egress receipts at every off-machine sink** (v1.63.0.0+). Every gstack-initiated\nsend off the machine MUST write a hash-chained receipt to\n`~/.gstack/security/egress.jsonl` BEFORE the send: TypeScript callers use\n`writeReceipt` from `lib/egress-receipt.ts`; shell scripts source\n`bin/gstack-egress-lib.sh` and use `_receipted_curl` / `_receipted_git`. Failure\npolarity is per-class: fail-closed for sensitive sinks (brain-sync, memory-ingest,\ngbrain-sync, telemetry, ngrok tunnels, mcp-verify, supabase-provision), fail-open\n+ stderr warning for user-facing ones (design OpenAI calls, update-check,\ndashboards, git-class ops). The new-sink scanner in\n`test/egress-receipt-wiring.test.ts` fails CI on an unreceipted `curl` /\n`git push` / `fetch` to a non-loopback host unless the file carries a reasoned\nentry in its `SCANNER_EXEMPT` list (user-directed page fetches, reachability\nprobes, instruction strings, skill prose) — if you add a new off-machine sink,\nwire it through the helpers and add it to the enumerated sink list. Inspect with\n`bin/gstack-egress` (`list` | `verify`, exit 3 on tamper | `grants`). Threat\nmodel: forensic observability of ATTEMPTED egress, not an exfiltration control.\n\n**SSE endpoint helper** (v1.51.0.0+). New SSE endpoints in `server.ts` MUST route\nthrough `createSseEndpoint(req, config)` from `browse/src/sse-helpers.ts`. The\nhelper owns the cleanup contract (abort + enqueue-throw + heartbeat-throw, all\nidempotent) and bakes in `sanitizeLoneSurrogates` on every JSON.stringify, so\nnew subscribers can't accidentally regress either invariant. Inline\n`ReadableStream` wiring leaked subscribers when the TCP connection died without\nfiring `req.signal.abort` (Chromium MV3 service-worker suspend, intermediate\nproxy half-close). `/activity/stream`, `/inspector/events`, and `/memory`\n(SSE-eligible) all route through it. `browse/test/sse-helpers.test.ts` pins the\ncleanup contract.\n\n**CDP session lifecycle** (v1.51.0.0+). Direct `page.context().newCDPSession(page)`\ncalls outside `browse/src/cdp-bridge.ts` fail CI via the static-grep tripwire in\n`browse/test/cdp-session-cleanup.test.ts`. Use `withCdpSession(page, async (s) => {...})`\nfor one-shot CDP work (try/finally detach) or `getOrCreateCdpSession(page, cache)`\nfor cached sessions tied to a page's lifetime (close-detach via `Map<page, session>`).\nThree sites migrated: cdp-bridge frame events, write-commands archive capture,\ncdp-inspector. The helpers prevent the per-session leak class where successful-path\ndetach happened but error-path detach was missed.\n\n**Setup symlink hardening** (v1.38.0.0+). Every link site in `setup` MUST route\nthrough the `_link_or_copy SRC DST` helper near the `IS_WINDOWS` detection. On\nWindows without Developer Mode, plain `ln -snf` produces frozen file copies that\ndon't refresh on `git pull` — silent staleness across every host adapter. The\nhelper preserves `ln -snf` on Unix and switches to `cp -R` / `cp -f` on Windows.\n`test/setup-windows-fallback.test.ts` enforces a static invariant: a single raw\n`ln` call outside the helper body fails CI. Windows users get a one-line note\nfrom `_print_windows_copy_note_once` reminding them to re-run `./setup` after\nevery `git pull`.\n\n**Sidebar security stack** (layered defense against prompt injection):\n\n| Layer | Module | Lives in |\n|-------|--------|----------|\n| L1-L3 | `content-security.ts` | both server and agent — datamarking, hidden element strip, ARIA regex, URL blocklist, envelope wrapping |\n| L4 | `security-classifier.ts` (TestSavantAI ONNX) | **sidebar-agent only** |\n| L4b | `security-classifier.ts` (Claude Haiku transcript) | **sidebar-agent only** |\n| L5 | `security.ts` (canary) | both — inject in compiled, check in agent |\n| L6 | `security.ts` (combineVerdict ensemble) | both |\n\n**Critical constraint:** `security-classifier.ts` CANNOT be imported from the\ncompiled browse binary. `@huggingface/transformers` v4 requires `onnxruntime-node`\nwhich fails to `dlopen` from Bun compile's temp extract dir. Only `security.ts`\n(pure-string operations — canary, verdict combiner, attack log, status) is safe\nfor `server.ts`. See `~/.gstack/projects/garrytan-gstack/ceo-plans/2026-04-19-prompt-injection-guard.md`\n§\"Pre-Impl Gate 1 Outcome\" for full architectural decision.\n\n**Thresholds** (in `security.ts`):\n- `BLOCK: 0.85` — single-layer score that would cause BLOCK if cross-confirmed\n- `WARN: 0.75` — cross-confirm threshold. When L4 AND L4b both >= 0.75 → BLOCK\n- `LOG_ONLY: 0.40` — gates transcript classifier (skip Haiku when all layers < 0.40)\n- `SOLO_CONTENT_BLOCK: 0.92` — single-layer threshold for label-less content classifiers\n  (testsavant, deberta). Intentionally higher than `BLOCK` because these layers can't\n  distinguish \"this is an injection\" from \"this looks like phishing aimed at the user.\"\n  The transcript classifier keeps a separate, label-gated solo path at `BLOCK` (0.85).\n\n**Ensemble rule:** BLOCK only when the ML content classifier AND the transcript\nclassifier both report >= WARN. Single-layer high confidence degrades to WARN —\nthis is the Stack Overflow instruction-writing FP mitigation. Canary leak\nalways BLOCKs (deterministic).\n\n**Env knobs:**\n- `GSTACK_SECURITY_OFF=1` — emergency kill switch. Classifier stays off even if\n  warmed. Canary is still injected; just the ML scan is skipped.\n- `GSTACK_SECURITY_ENSEMBLE=deberta` — opt-in DeBERTa-v3 ensemble. Adds\n  ProtectAI DeBERTa-v3-base-injection-onnx as L4c classifier for cross-model\n  agreement. 721MB first-run download. With ensemble enabled, BLOCK requires\n  2-of-3 ML classifiers agreeing at >= WARN (testsavant, deberta, transcript).\n  Without ensemble (default), BLOCK requires testsavant + transcript at >= WARN.\n- Classifier model cache: `~/.gstack/models/testsavant-small/` (112MB, first run only)\n  plus `~/.gstack/models/deberta-v3-injection/` (721MB, only when ensemble enabled)\n- Attack log: `~/.gstack/security/attempts.jsonl` (salted sha256 + domain only,\n  rotates at 10MB, 5 generations)\n- Per-device salt: `~/.gstack/security/device-salt` (0600)\n- Session state: `~/.gstack/security/session-state.json` (cross-process, atomic)\n\n## Dev symlink awareness\n\nWhen developing gstack, `.claude/skills/gstack` may be a symlink back to this\nworking directory (gitignored). This means skill changes are **live immediately**,\ngreat for rapid iteration, risky during big refactors where half-written skills\ncould break other Claude Code sessions using gstack concurrently.\n\n**Check once per session:** Run `ls -la .claude/skills/gstack` to see if it's a\nsymlink or a real copy. If it's a symlink to your working directory, be aware that:\n- Template changes + `bun run gen:skill-docs` immediately affect all gstack invocations\n- Breaking changes to SKILL.md.tmpl files can break concurrent gstack sessions\n- During large refactors, remove the symlink (`rm .claude/skills/gstack`) so the\n  global install at `~/.claude/skills/gstack/` is used instead\n\n**Prefix setting:** Setup creates real directories (not symlinks) at the top level\nwith a SKILL.md symlink inside (e.g., `qa/SKILL.md -> gstack/qa/SKILL.md`). This\nensures Claude discovers them as top-level skills, not nested under `gstack/`.\nNames are either short (`qa`) or namespaced (`gstack-qa`), controlled by\n`skill_prefix` in `~/.gstack/config.yaml`. Pass `--no-prefix` or `--prefix` to\nskip the interactive prompt.\n\n**Note:** Vendoring gstack into a project's repo is deprecated. Use global install\n+ `./setup --team` instead. See README.md for team mode instructions.\n\n**For plan reviews:** When reviewing plans that modify skill templates or the\ngen-skill-docs pipeline, consider whether the changes should be tested in isolation\nbefore going live (especially if the user is actively using gstack in other windows).\n\n**Upgrade migrations:** When a change modifies on-disk state (directory structure,\nconfig format, stale files) in ways that could break existing user installs, add a\nmigration script to `gstack-upgrade/migrations/`. Read CONTRIBUTING.md's \"Upgrade\nmigrations\" section for the format and testing requirements. The upgrade skill runs\nthese automatically after `./setup` during `/gstack-upgrade`.\n\n## Compiled binaries — never commit browse/dist/, design/dist/, or make-pdf/dist/\n\nThe `browse/dist/`, `design/dist/`, and `make-pdf/dist/` directories contain\ncompiled Bun binaries (`browse`, `find-browse`, `design`, ~62MB each). These are\nMach-O arm64 only — they do NOT work on Linux, Windows, or Intel Macs. The\n`./setup` script builds from source for every platform.\n\nThese directories are **untracked and gitignored** (`.gitignore:3-6`; the\n`browse/dist/` binaries were untracked in `64d5a3e4`, v0.11.16.0; the others were\nnever tracked). They will NOT appear in `git status`. If a dist binary ever does\nshow up in `git status`, something force-added it (`git add -f`) — do not commit\nit; unstage it and find out how it got there.\n\nWhen staging files, always use specific filenames (`git add file1 file2`) — never\n`git add .` or `git add -A`, which can sweep in build outputs and junk.\n\n## Redaction guard (PII / secrets / legal content)\n\nShared redaction engine catches credentials, PII, and legal/damaging content\nbefore it reaches an external sink (codex dispatch, GitHub issue/PR body, pushed\ncommit). It is a **guardrail, not airtight enforcement** — `git push --no-verify`,\ndirect `gh issue create`, and `GSTACK_REDACT_PREPUSH=skip` all bypass it. It\ncatches accidents and carelessness, the 99% case. Do not claim it stops a\ndetermined leaker (a CHANGELOG line that does would fail a hostile screenshotter).\n\n- **Engine + taxonomy:** `lib/redact-patterns.ts` (the single source of truth —\n  3 tiers; HIGH = genuinely-secret credentials that block, MEDIUM = PII/legal/\n  internal + high-FP credential shapes that confirm via AskUserQuestion, LOW =\n  FYI) and `lib/redact-engine.ts` (pure `scan()` + `applyRedactions()`).\n  Calibration matters: a gate that cries wolf gets ignored, so context-variable\n  shapes (Stripe `pk_live_`, Google `AIza`, JWT, env `*_KEY=`) sit at MEDIUM.\n- **CLI:** `bin/gstack-redact` (exit 0 clean / 2 MEDIUM / 3 HIGH; `--json`,\n  `--auto-redact`, `--repo-visibility`, `--from-file`). `bin/gstack-redact-prepush`\n  is the opt-in git hook.\n- **Skill docs are generated** from `scripts/resolvers/redact-doc.ts`\n  (`{{REDACT_TAXONOMY_TABLE}}`, `{{REDACT_INVOCATION_BLOCK:<sink>}}`) so /spec,\n  /cso, /ship, /document-release, /document-generate never drift from the engine.\n- **Scan-at-sink:** always scan the EXACT bytes that will be sent — write to a\n  temp file, scan that file, pass the SAME file to `gh`/`git`. Never scan a string\n  then re-render (that reopens a scan-vs-send gap).\n- **Visibility (no tier promotion):** resolve once per run, order = local config\n  (`gstack-config get redact_repo_visibility`, ~/.gstack so never committed) → gh\n  → glab → unknown(=public-strict). Public repos get STERNER per-finding\n  confirmation (no batch-acknowledge, no silent-proceed); MEDIUM is never\n  auto-promoted to HIGH.\n- **Tool-attributed fences:** wrap Codex/Greptile/eval output in ` ```codex-review `\n  / ` ```greptile ` fences so example credentials those tools quote WARN-degrade\n  instead of blocking. A live-format credential inside the fence still blocks.\n- **Config keys:** `redact_repo_visibility` (public|private|unknown, local-only\n  override for repos gh/glab can't read), `redact_prepush_hook` (true|false).\n  There is intentionally NO key to disable HIGH blocking.\n- **Audit:** the /spec semantic pass appends a content-free record (categories +\n  body sha256, no spec text) to `~/.gstack/security/semantic-reviews.jsonl` (0600).\n\n## Commit style\n\n**Always bisect commits.** Every commit should be a single logical change. When\nyou've made multiple changes (e.g., a rename + a rewrite + new tests), split them\ninto separate commits before pushing. Each commit should be independently\nunderstandable and revertable.\n\nExamples of good bisection:\n- Rename/move separate from behavior changes\n- Test infrastructure (touchfiles, helpers) separate from test implementations\n- Template changes separate from generated file regeneration\n- Mechanical refactors separate from new features\n\nWhen the user says \"bisect commit\" or \"bisect and push,\" split staged/unstaged\nchanges into logical commits and push.\n\n## Slop-scan: AI code quality, not AI code hiding\n\nWe use [slop-scan](https://github.com/benvinegar/slop-scan) to catch patterns where\nAI-generated code is genuinely worse than what a human would write. We are NOT trying\nto pass as human code. We are AI-coded and proud of it. The goal is code quality.\n\n```bash\nnpx slop-scan scan .          # human-readable report\nnpx slop-scan scan . --json   # machine-readable for diffing\n```\n\nConfig: `slop-scan.config.json` at repo root (currently excludes `**/vendor/**`).\n\n### What to fix (genuine quality improvements)\n\n- **Empty catches around file ops** — use `safeUnlink()` (ignores ENOENT, rethrows\n  EPERM/EIO). A swallowed EPERM in cleanup means silent data loss.\n- **Empty catches around process kills** — use `safeKill()` (ignores ESRCH, rethrows\n  EPERM). A swallowed EPERM means you think you killed something you didn't.\n- **Redundant `return await`** — remove when there's no enclosing try block. Saves a\n  microtask, signals intent.\n- **Typed exception catches** — `catch (err) { if (!(err instanceof TypeError)) throw err }`\n  is genuinely better than `catch {}` when the try block does URL parsing or DOM work.\n  You know what error you expect, so say so.\n\n### What NOT to fix (linter gaming, not quality)\n\n- **String-matching on error messages** — `err.message.includes('closed')` is brittle.\n  Playwright/Chrome can change wording anytime. If a fire-and-forget operation can fail\n  for ANY reason and you don't care, `catch {}` is the correct pattern.\n- **Adding comments to exempt pass-through wrappers** — \"alias for active session\" above\n  a method just to trip slop-scan's exemption rule is noise, not documentation.\n- **Converting extension catch-and-log to selective rethrow** — Chrome extensions crash\n  entirely on uncaught errors. If the catch logs and continues, that IS the right pattern\n  for extension code. Don't make it throw.\n- **Tightening best-effort cleanup paths** — shutdown, emergency cleanup, and disconnect\n  code should use `safeUnlinkQuiet()` (swallows ALL errors). A cleanup path that throws\n  on EPERM means the rest of cleanup doesn't run. That's worse.\n\n### Utilities in `browse/src/error-handling.ts`\n\n| Function | Use when | Behavior |\n|----------|----------|----------|\n| `safeUnlink(path)` | Normal file deletion | Ignores ENOENT, rethrows others |\n| `safeUnlinkQuiet(path)` | Shutdown/emergency cleanup | Swallows all errors |\n| `safeKill(pid, signal)` | Sending signals | Ignores ESRCH, rethrows others |\n| `isProcessAlive(pid)` | Boolean process checks | Returns true/false, never throws |\n\n### Score tracking\n\nBaseline (2026-04-09, before cleanup): 100 findings, 432.8 score, 2.38 score/file.\nAfter cleanup: 90 findings, 358.1 score, 1.96 score/file.\n\nDon't chase the number. Fix patterns that represent actual code quality problems.\nAccept findings where the \"sloppy\" pattern is the correct engineering choice.\n\n## Community PR guardrails\n\nWhen reviewing or merging community PRs, **always AskUserQuestion** before accepting\nany commit that:\n\n1. **Touches ETHOS.md** — this file is Garry's personal builder philosophy. No edits\n   from external contributors or AI agents, period.\n2. **Removes or softens promotional material** — YC references, founder perspective,\n   and product voice are intentional. PRs that frame these as \"unnecessary\" or\n   \"too promotional\" must be rejected.\n3. **Changes Garry's voice** — the tone, humor, directness, and perspective in skill\n   templates, CHANGELOG, and docs are not generic. PRs that rewrite voice to be\n   more \"neutral\" or \"professional\" must be rejected.\n\nEven if the agent strongly believes a change improves the project, these three\ncategories require explicit user approval via AskUserQuestion. No exceptions.\nNo auto-merging. No \"I'll just clean this up.\"\n\n## Checking out PRs from garrytan-agents\n\nWhen the user says \"check out <PR link>\" and the PR is from `garrytan-agents/gstack`\n(or any other fork that is NOT a collaborator on `garrytan/gstack`), do NOT just\n`gh pr checkout`. Fork PRs don't receive base-repo secrets (`ANTHROPIC_API_KEY`,\n`OPENAI_API_KEY`, etc.), so the eval/E2E CI jobs fail with empty-env auth errors\nregardless of what's set on the base repo.\n\n**Workflow:** push the branch to `garrytan/gstack` (the base repo) and re-target\nthe PR from there.\n\nConcretely, after `gh pr checkout <N>`:\n\n1. Note the original PR number and head branch name.\n2. Push the same branch to the base repo: `git push origin HEAD:<branch-name>`\n   (origin = `garrytan/gstack`, since the worktree is set up with that remote).\n3. Close the fork PR (`gh pr close <N> --comment \"moving to base-repo branch for secret access\"`).\n4. Open a new PR from the base-repo branch: `gh pr create --base main --head <branch-name>`.\n5. New PR's workflows will get secrets automatically.\n\nWhy not fix it on the fork side? `garrytan-agents` isn't a collaborator on\n`garrytan/gstack`. Adding it as a collaborator (option A) or flipping the\nrepo-wide \"send secrets to fork PRs\" toggle (option B) would let secrets reach\nfork PRs from anyone — broader blast radius than just moving this one branch.\nOption C (this section) keeps secret-distribution scope tight.\n\nIf the user asks you to skip the move (e.g., \"just leave it as a fork PR\"),\nrespect that — eval CI will fail with empty-env auth, but check-freshness,\nworkflow-lint, and windows-tests will still pass on the fork PR.\n\n## CHANGELOG + VERSION style\n\n**Versioning invariant (workspace-aware ship).** VERSION is a monotonic ordered\nrelease identifier, not a strict semver commitment. The bump level\n(major/minor/patch/micro) expresses intent at ship time. Queue-advancing past a\nclaimed version within the same bump level is explicitly permitted — if branch A\nclaims v1.7.0.0 as a MINOR and branch B is also a MINOR, B lands at v1.8.0.0\n(still a MINOR relative to main). Downstream consumers must NOT rely on\n\"MINOR = feature-only, PATCH = fix-only\" as a strict contract. This is why\n`bin/gstack-next-version` advances within the chosen bump level rather than\nrepicking the level when collisions happen.\n\n**Scale-aware bumps — use common sense.** When the diff is big, bump MINOR (or\nMAJOR), not PATCH. PATCH is for bug fixes and small additions; MINOR is for\nsubstantial new capability or substantial reduction; MAJOR is for breaking\nchanges. Rough guideposts (don't treat as rules, treat as smell-checks):\n\n- **PATCH (X.Y.Z+1.0)**: bug fix, doc tweak, small additive change, single\n  test/file added. Net diff under ~500 lines, no new user-facing capability.\n- **MINOR (X.Y+1.0.0)**: new capability shipped (skill, harness, command, big\n  refactor), substantial code reduction (compression, migration), or coordinated\n  multi-file change. Net diff over ~2000 lines added/removed, OR a user-visible\n  feature you'd put in a tweet.\n- **MAJOR (X+1.0.0.0)**: breaking change to public surface (CLI flag rename,\n  skill removed, config format changed), OR a release big enough to be the\n  headline of a blog post.\n\nIf you find yourself debating \"is 10K added + 24K removed really a PATCH?\" — it\nisn't. Bump MINOR. Same for \"this adds a whole new test harness with 6 new E2E\ntests + helper utilities\" — MINOR. The bump level is communication to the user\nabout what kind of release this is; don't undersell it.\n\nWhen merging origin/main brings a higher VERSION, re-evaluate the bump level\nagainst the SCALE of your branch's work, not just whether main moved forward.\nIf main bumped MINOR and your branch is also a substantial change, you bump\nMINOR again on top (e.g., main at v1.14.0.0, your branch lands v1.15.0.0).\n\n**VERSION and CHANGELOG are branch-scoped.** Every feature branch that ships gets its\nown version bump and CHANGELOG entry. The entry describes what THIS branch adds —\nnot what was already on main.\n\n**The CHANGELOG entry is the diff between main and the shipping branch — what users\nget when they upgrade. NOT how the branch got there.** A reader landing on the entry\nshould learn what they can do now that they couldn't before; they should not learn\nabout the branch's internal version bumps, the bugs we caught and fixed mid-branch,\nthe plan reviews we ran, or the commits we squashed. That is branch development\nnarrative. It belongs in PR descriptions and commit messages, not CHANGELOG.\n\n**Never reference branch-internal versions in a CHANGELOG entry.** If your branch\nbumped VERSION from v1.5.0.0 → v1.5.1.0 → v1.6.0.0 during development and only the\nfinal v1.6.0.0 ships to main, the entry must read as if v1.5.1.0 never existed.\nConcretely, NEVER write:\n- \"v1.5.1.0 had a bug that v1.6.0.0 fixes\" — readers don't know about v1.5.1.0; it's\n  a branch-internal artifact.\n- \"The shipping headline of v1.5.1.0 was broken because...\" — same reason. From main's\n  perspective, v1.5.1.0 was never released.\n- \"Pre-fix tests encoded the broken behavior\" — that's a contributor's victory lap,\n  not a user benefit.\n- \"Two surgical edits, both in the dispatch path\" — micro-narrative of the patch.\n\nInstead, describe the released system: \"Browser-skills run end-to-end with the\nexpected tab-access semantics.\" If a property of the shipped system is worth calling\nout (e.g., \"skill spawns get permissive tab access; pair-agent tunnel tokens require\nownership\"), document it as a property, not as a fix. The shipped system is what\nthe user gets; the path to that system is invisible to them.\n\n**When to write the CHANGELOG entry:**\n- At `/ship` time (Step 13), not during development or mid-branch.\n- The entry covers ALL commits on this branch vs the base branch.\n- Never fold new work into an existing CHANGELOG entry from a prior version that\n  already landed on main. If main has v0.10.0.0 and your branch adds features,\n  bump to v0.10.1.0 with a new entry — don't edit the v0.10.0.0 entry.\n\n**Key questions before writing:**\n1. What branch am I on? What did THIS branch change?\n2. Is the base branch version already released? (If yes, bump and create new entry.)\n3. Does an existing entry on this branch already cover earlier work? (If yes, replace\n   it with one unified entry for the final version.)\n\n**Merging main does NOT mean adopting main's version.** When you merge origin/main into\na feature branch, main may bring new CHANGELOG entries and a higher VERSION. Your branch\nstill needs its OWN version bump on top. If main is at v0.13.8.0 and your branch adds\nfeatures, bump to v0.13.9.0 with a new entry. Never jam your changes into an entry that\nalready landed on main. Your entry goes on top because your branch lands next.\n\n**After merging main, always check:**\n- Does CHANGELOG have your branch's own entry separate from main's entries?\n- Is VERSION higher than main's VERSION?\n- Is your entry the topmost entry in CHANGELOG (above main's latest)?\nIf any answer is no, fix it before continuing.\n\n**After any CHANGELOG edit that moves, adds, or removes entries,** immediately run\n`grep \"^## \\[\" CHANGELOG.md` to verify no duplicates and a sensible reverse-chronological\norder. Gaps between version numbers are fine. A branch that ships at v1.6.4.0 without\na prior v1.5.2.0 or v1.5.3.0 entry on main is correct — those were branch-internal\nversion numbers that never landed. Do not back-fill gaps with placeholder entries.\n\n**Never orphan branch-internal versions.** If your branch bumped VERSION several times\nduring development (v1.5.1.0 → v1.5.2.0 → v1.6.4.0, say) and those earlier entries were\nnever released to main, the final ship consolidates ALL of them into a single entry at\nthe final version (v1.6.4.0). Collapse them — delete the old entries and move their\ncontent into the final entry, re-version table columns accordingly. Readers see one\nrelease, not a branch diary. Gaps are fine (v1.6.3.0 → v1.6.4.0 with no v1.5.x\nin between on main is correct).\n\nCHANGELOG.md is **for users**, not contributors. Write it like product release notes:\n\n- Lead with what the user can now **do** that they couldn't before. Sell the feature.\n- Use plain language, not implementation details. \"You can now...\" not \"Refactored the...\"\n- **Never mention TODOS.md, internal tracking, eval infrastructure, or contributor-facing\n  details.** These are invisible to users and meaningless to them.\n- Put contributor/internal changes in a separate \"For contributors\" section at the bottom.\n- Every entry should make someone think \"oh nice, I want to try that.\"\n- No jargon: say \"every question now tells you which project and branch you're in\" not\n  \"AskUserQuestion format standardized across skill templates via preamble resolver.\"\n\n**Only document what shipped between main and this change.** Readers do not care how\nwe got here. Keep out of the CHANGELOG, always:\n\n- Branch resyncs, merge commits with main, rebase activity.\n- Plan approvals, review outcomes (CEO / eng / design / outside-voice / codex findings),\n  AskUserQuestion decisions, scope negotiations.\n- \"Work queued,\" \"plan approved,\" \"in-progress,\" \"will ship later\" — the CHANGELOG\n  documents what DID ship, not what MIGHT ship.\n- Version-bump housekeeping when no user-facing work actually landed.\n\nIf the diff between the base branch version and this version has no user-facing change\n(only merges, only CHANGELOG edits, only placeholder work), the honest entry is one\nsentence: \"Version bump for branch-ahead discipline. No user-facing changes yet.\" Stop\nthere. Do not pad. Do not explain the plan that will ship eventually. Do not narrate\nthe branch's history. When real work lands, the entry will replace this at /ship time.\n\n### Release-summary format (every `## [X.Y.Z]` entry)\n\nEvery version entry in `CHANGELOG.md` MUST start with a release-summary section in\nthe GStack/Garry voice, one viewport's worth of prose + tables that lands like a\nverdict, not marketing. The itemized changelog (subsections, bullets, files) goes\nBELOW that summary, separated by a `### Itemized changes` header.\n\nThe release-summary section gets read by humans, by the auto-update agent, and by\nanyone deciding whether to upgrade. The itemized list is for agents that need to\nknow exactly what changed.\n\nStructure for the top of every `## [X.Y.Z]` entry:\n\n1. **Two-line bold headline** (10-14 words total). Should land like a verdict, not\n   marketing. Sound like someone who shipped today and cares whether it works.\n2. **Lead paragraph** (3-5 sentences). What shipped, what changed for the user.\n   Specific, concrete, no AI vocabulary, no em dashes, no hype.\n3. **A \"The X numbers that matter\" section** with:\n   - One short setup paragraph naming the source of the numbers (real production\n     deployment OR a reproducible benchmark, name the file/command to run).\n   - A table of 3-6 key metrics with BEFORE / AFTER / Δ columns.\n   - A second optional table for per-category breakdown if relevant.\n   - 1-2 sentences interpreting the most striking number in concrete user terms.\n4. **A \"What this means for [audience]\" closing paragraph** (2-4 sentences) tying\n   the metrics to a real workflow shift. End with what to do.\n\nVoice rules for the release summary:\n- No em dashes (use commas, periods, \"...\").\n- No AI vocabulary (delve, robust, comprehensive, nuanced, fundamental, etc.) or\n  banned phrases (\"here's the kicker\", \"the bottom line\", etc.).\n- Real numbers, real file names, real commands. Not \"fast\" but \"~30s on 30K pages.\"\n- Short paragraphs, mix one-sentence punches with 2-3 sentence runs.\n- Connect to user outcomes: \"the agent does ~3x less reading\" beats \"improved precision.\"\n- Be direct about quality. \"Well-designed\" or \"this is a mess.\" No dancing.\n\nSource material:\n- CHANGELOG previous entry for prior context.\n- Benchmark files or `/retro` output for headline numbers.\n- Recent commits (`git log <prev-version>..HEAD --oneline`) for what shipped.\n- Don't make up numbers. If a metric isn't in a benchmark or production data,\n  don't include it. Say \"no measurement yet\" if asked.\n\nTarget length: ~250-350 words for the summary. Should render as one viewport.\n\n### Itemized changes (below the release summary)\n\nWrite `### Itemized changes` and continue with the detailed subsections (Added,\nChanged, Fixed, For contributors). Same rules as the user-facing voice guidance\nabove, plus:\n\n- **Always credit community contributions.** When an entry includes work from a\n  community PR, name the contributor with `Contributed by @username`. Contributors\n  did real work. Thank them publicly every time, no exceptions.\n\n## AI effort compression\n\nWhen estimating or discussing effort, always show both human-team and CC+gstack time:\n\n| Task type | Human team | CC+gstack | Compression |\n|-----------|-----------|-----------|-------------|\n| Boilerplate / scaffolding | 2 days | 15 min | ~100x |\n| Test writing | 1 day | 15 min | ~50x |\n| Feature implementation | 1 week | 30 min | ~30x |\n| Bug fix + regression test | 4 hours | 15 min | ~20x |\n| Architecture / design | 2 days | 4 hours | ~5x |\n| Research / exploration | 1 day | 3 hours | ~3x |\n\nCompleteness is cheap. Don't recommend shortcuts when the complete implementation\nis achievable. Boil the ocean — the complete thing is the goal; only genuinely\nunrelated multi-quarter migrations are separate scope, never an excuse for a\nshortcut. See the Completeness Principle in the skill preamble for the full\nphilosophy.\n\n## Search before building\n\nBefore designing any solution that involves concurrency, unfamiliar patterns,\ninfrastructure, or anything where the runtime/framework might have a built-in:\n\n1. Search for \"{runtime} {thing} built-in\"\n2. Search for \"{thing} best practice {current year}\"\n3. Check official runtime/framework docs\n\nThree layers of knowledge: tried-and-true (Layer 1), new-and-popular (Layer 2),\nfirst-principles (Layer 3). Prize Layer 3 above all. See ETHOS.md for the full\nbuilder philosophy.\n\n## Local plans\n\nContributors can store long-range vision docs and design documents in `~/.gstack-dev/plans/`.\nThese are local-only (not checked in). When reviewing TODOS.md, check `plans/` for candidates\nthat may be ready to promote to TODOs or implement.\n\n## E2E eval failure blame protocol\n\nWhen an E2E eval fails during `/ship` or any other workflow, **never claim \"not\nrelated to our changes\" without proving it.** These systems have invisible couplings —\na preamble text change affects agent behavior, a new helper changes timing, a\nregenerated SKILL.md shifts prompt context.\n\n**Required before attributing a failure to \"pre-existing\":**\n1. Run the same eval on main (or base branch) and show it fails there too\n2. If it passes on main but fails on the branch — it IS your change. Trace the blame.\n3. If you can't run on main, say \"unverified — may or may not be related\" and flag it\n   as a risk in the PR body\n\n\"Pre-existing\" without receipts is a lazy claim. Prove it or don't say it.\n\n## Long-running tasks: don't give up\n\nWhen running evals, E2E tests, or any long-running background task, **poll until\ncompletion**. Use `sleep 180 && echo \"ready\"` + `TaskOutput` in a loop every 3\nminutes. Never switch to blocking mode and give up when the poll times out. Never\nsay \"I'll be notified when it completes\" and stop checking — keep the loop going\nuntil the task finishes or the user tells you to stop.\n\nThe full E2E suite can take 30-45 minutes. That's 10-15 polling cycles. Do all of\nthem. Report progress at each check (which tests passed, which are running, any\nfailures so far). The user wants to see the run complete, not a promise that\nyou'll check later.\n\n## Running evals as an agent: always detach (SIGTERM-proof)\n\nWhen **you (an agent/harness)** launch a long eval/benchmark run, run it through\n`bin/gstack-detach` — NEVER as a plain backgrounded Bash task. A plain background\ntask lives in the harness's process group, so a SIGTERM (\"polite quit\") on a turn\nboundary, a stopped Monitor, or an interruption kills the run mid-flight (observed:\n`script \"test:gate\" was terminated by signal SIGTERM` ~40 min into a run). On macOS\nthe run can also die to idle-sleep. `gstack-detach` fixes both: a fresh session\n(escapes the group SIGTERM) wrapped in `caffeinate -i` (blocks idle-sleep).\n\n- Use the `eval:bg*` scripts (`eval:bg`, `eval:bg:all`, `eval:bg:gate`,\n  `eval:bg:periodic`) — they wrap the eval command in `gstack-detach` with the\n  machine-wide `gstack-evals` lock (concurrent worktrees serialize instead of\n  saturating the shared model API), a per-tier watchdog, and a **run-scoped** log\n  under `~/.gstack-dev/eval-runs/` (no shared-`/tmp` collision). Each prints its\n  log path. `eval:bg:gate` / `eval:bg:periodic` run their tier through the\n  sharded paid runner (`scripts/test-paid-shards.ts`, also exposed as\n  `test:gate:sharded` / `test:periodic:sharded`): one Bun process per test\n  file, an external wall-clock timeout that kills the shard's process GROUP\n  (stray `claude`/`codex` grandchildren included), a per-shard\n  `GSTACK_EVAL_DIR=<evalDir>/shards/<slug>/` honored by the `EvalCollector`\n  constructor, and an aggregate that separates failed vs timed-out vs\n  never-started shards — the detach timeouts (25200s gate / 28800s periodic)\n  are sized against worst-case shard wall clock. `eval:list` / `eval:compare` /\n  `eval:summary` read the shard dirs too. Or call\n  `gstack-detach [--lock NAME] [--timeout SECS] [--label LBL] --\n  <cmd>` directly for any long agent job. Export `ANTHROPIC_API_KEY` first (never\n  pass keys in argv).\n- Then **poll the printed logfile** with a death-aware watcher: break on the\n  guaranteed `### gstack-detach EXIT=<code> ###` sentinel (success AND failure are\n  both marked, so silence is never mistaken for success). The detached run survives\n  even if your watcher gets reaped, so re-checking the log always works.\n- Why the lock: a shared dev box with several Conductor worktrees will rate-limit\n  the model API if two eval suites run at once (15-way concurrency each), which\n  mass-times-out E2E tests. The lock makes the second run WAIT, not collide.\n- Humans running `bun run test:evals` foreground in their own terminal don't need\n  this — Ctrl-C is intended there. Detachment is for agent-launched runs only.\n\n## E2E test fixtures: extract, don't copy\n\n**NEVER copy a full SKILL.md file into an E2E test fixture.** SKILL.md files are\n1500-2000 lines. When `claude -p` reads a file that large, context bloat causes\ntimeouts, flaky turn limits, and tests that take 5-10x longer than necessary.\n\nInstead, extract only the section the test actually needs:\n\n```typescript\n// BAD — agent reads 1900 lines, burns tokens on irrelevant sections\nfs.copyFileSync(path.join(ROOT, 'ship', 'SKILL.md'), path.join(dir, 'ship-SKILL.md'));\n\n// GOOD — agent reads ~60 lines, finishes in 38s instead of timing out\nconst full = fs.readFileSync(path.join(ROOT, 'ship', 'SKILL.md'), 'utf-8');\nconst start = full.indexOf('## Review Readiness Dashboard');\nconst end = full.indexOf('\\n---\\n', start);\nfs.writeFileSync(path.join(dir, 'ship-SKILL.md'), full.slice(start, end > start ? end : undefined));\n```\n\nAlso when running targeted E2E tests to debug failures:\n- Run in **foreground** (`bun test ...`), not background with `&` and `tee`\n- Never `pkill` running eval processes and restart — you lose results and waste money\n- One clean run beats three killed-and-restarted runs\n\n## Publishing native OpenClaw skills to ClawHub\n\nNative OpenClaw skills live in `openclaw/skills/gstack-openclaw-*/SKILL.md`. These are\nhand-crafted methodology skills (not generated by the pipeline) published to ClawHub\nso any OpenClaw user can install them.\n\n**Publishing:** The command is `clawhub publish` (NOT `clawhub skill publish`):\n\n```bash\nclawhub publish openclaw/skills/gstack-openclaw-office-hours \\\n  --slug gstack-openclaw-office-hours --name \"gstack Office Hours\" \\\n  --version 1.0.0 --changelog \"description of changes\"\n```\n\nRepeat for each skill: `gstack-openclaw-ceo-review`, `gstack-openclaw-investigate`,\n`gstack-openclaw-retro`. Bump `--version` on each update.\n\n**Auth:** `clawhub login` (opens browser for GitHub auth). `clawhub whoami` to verify.\n\n**Updating:** Same `clawhub publish` command with a higher `--version` and `--changelog`.\n\n**Verification:** `clawhub search gstack` to confirm they're live.\n\n## Deploying to the active skill\n\nThe active skill lives at `~/.claude/skills/gstack/`. After making changes:\n\n1. Push your branch\n2. Fetch and reset in the skill directory: `cd ~/.claude/skills/gstack && git fetch origin && git reset --hard origin/main`\n3. Rebuild: `cd ~/.claude/skills/gstack && bun run build`\n\n**If you use gbrain:** the `git reset --hard` in step 2 reverts the brain-aware\n(`GBRAIN_CONTEXT_LOAD` / `GBRAIN_SAVE_RESULTS`) blocks that `gstack-config\ngbrain-refresh` renders into the install (those generated blocks differ from\n`main` by design). After deploying, re-run `gstack-config gbrain-refresh` to\nrestore them across all your projects' Claude sessions. It's idempotent.\n\nOr copy the binaries directly:\n- `cp browse/dist/browse ~/.claude/skills/gstack/browse/dist/browse`\n- `cp design/dist/design ~/.claude/skills/gstack/design/dist/design`\n\n## Skill routing\n\nWhen the user's request matches an available skill, invoke it via the Skill tool. When in doubt, invoke the skill.\n\nKey routing rules:\n- Product ideas/brainstorming → invoke /office-hours\n- Strategy/scope → invoke /plan-ceo-review\n- Architecture → invoke /plan-eng-review\n- Design system/plan review → invoke /design-consultation or /plan-design-review\n- Full review pipeline → invoke /autoplan\n- Bugs/errors → invoke /investigate\n- QA/testing site behavior → invoke /qa or /qa-only\n- Code review/diff check → invoke /review\n- Visual polish → invoke /design-review\n- Ship/deploy/PR → invoke /ship or /land-and-deploy\n- Save progress → invoke /context-save\n- Resume context → invoke /context-restore\n\n## Cross-session decision memory\n\nDurable decisions and their rationale are captured in an append-only, event-sourced\nstore at `~/.gstack/projects/<slug>/decisions.jsonl` so neither you nor the user\nre-litigates a settled call or loses the \"why\" across sessions. This is the reliable,\nfile-only path: it works with gbrain OFF. (gbrain semantic recall is an optional\nenhancement layered on top, never a dependency.)\n\n- **Resurface** active decisions before re-deciding: `bin/gstack-decision-search`\n  (`--recent N`, `--scope repo|branch|issue`, `--query KW`, `--all`, `--json`).\n  Add `--semantic` (with `--query`) to append related hits from gbrain memory when\n  it's up; it degrades silently to the reliable file results when gbrain is off.\n  Session start already surfaces scope-relevant active decisions via Context Recovery.\n  If a decision is listed, treat it as settled with its rationale; if you're about to\n  reverse it, say so explicitly.\n- **Capture** a DURABLE decision when you or the user make one:\n  `bin/gstack-decision-log '{\"decision\":\"...\",\"rationale\":\"...\",\"scope\":\"repo|branch|issue\",\"source\":\"user|skill|agent\",\"confidence\":1-10}'`.\n  Reverse a prior call with `--supersede <id>`; expunge an accidental secret with\n  `--redact <id>`; rewrite the log to the active set with `--compact`. Non-interactive\n  (never prompts), injection-sanitized, and HIGH-secret-blocking on write.\n- **Durable means:** architecture choice, scope cut, tool/vendor choice, or a reversal\n  of a prior call. NOT a turn-level edit, a phrasing tweak, or anything trivially\n  re-derivable. Capture is curated at the source — log durable decisions only, or the\n  store becomes noise.\n\n## GBrain Search Guidance (configured by /sync-gbrain)\n<!-- gstack-gbrain-search-guidance:start -->\n\nGBrain is set up and synced on this machine. The agent should prefer gbrain\nover Grep when the question is semantic or when you don't know the exact\nidentifier yet.\n\n**This worktree is pinned to a worktree-scoped code source** via the\n`.gbrain-source` file in the repo root (kubectl-style context). Any\n`gbrain code-def`, `code-refs`, `code-callers`, `code-callees`, or `query`\ncall from anywhere under this worktree routes to that source by default —\nno `--source` flag needed. Conductor sibling worktrees of the same repo\neach have their own pin and their own indexed pages, so semantic results\nmatch the actual code on disk in this worktree.\n\nTwo indexed corpora available via the `gbrain` CLI:\n- This worktree's code (auto-pinned via `.gbrain-source`).\n- `~/.gstack/` curated memory (registered as `gstack-brain-<user>` source via\n  the existing federation pipeline).\n\nPrefer gbrain when:\n- \"Where is X handled?\" / semantic intent, no exact string yet:\n    `gbrain search \"<terms>\"` or `gbrain query \"<question>\"`\n- \"Where is symbol Y defined?\" / symbol-based code questions:\n    `gbrain code-def <symbol>` or `gbrain code-refs <symbol>`\n- \"What calls Y?\" / \"What does Y depend on?\":\n    `gbrain code-callers <symbol>` / `gbrain code-callees <symbol>`\n- \"What did we decide last time?\" / past plans, retros, learnings:\n    `gbrain search \"<terms>\" --source gstack-brain-<user>`\n\nGrep is still right for known exact strings, regex, multiline patterns, and\nfile globs. Run `/sync-gbrain` after meaningful code changes; for ongoing\nauto-sync across all worktrees, run `gbrain autopilot --install` once per\nmachine — gbrain's daemon handles incremental refresh on a schedule.\n\nSafety: don't run `/sync-gbrain` while `gbrain autopilot` is active — the\norchestrator refuses destructive source ops when it detects a running autopilot\nto avoid racing it (#1734). Prefer registering user repos with `gbrain sources\nadd --path <dir>` (no `--url`): URL-managed sources can auto-reclone, and the\nsync code walk for them requires an explicit `--allow-reclone` opt-in.\n\n<!-- gstack-gbrain-search-guidance:end -->\n","category":"root","tokens":15727}]}