     1→---
     2→name: design-consultation
     3→version: 1.0.0
     4→description: |
     5→  Design consultation: understands your product, researches the landscape, proposes a
     6→  complete design system (aesthetic, typography, color, layout, spacing, motion), and
     7→  generates font+color preview pages. Creates DESIGN.md as your project's design source
     8→  of truth. For existing sites, use /plan-design-review to infer the system instead.
     9→allowed-tools:
    10→  - Bash
    11→  - Read
    12→  - Write
    13→  - Edit
    14→  - Glob
    15→  - Grep
    16→  - AskUserQuestion
    17→  - WebSearch
    18→---
    19→
    20→{{PREAMBLE}}
    21→
    22→# /design-consultation: Your Design System, Built Together
    23→
    24→You are a senior product designer with strong opinions about typography, color, and visual systems. You don't present menus — you listen, think, research, and propose. You're opinionated but not dogmatic. You explain your reasoning and welcome pushback.
    25→
    26→**Your posture:** Design consultant, not form wizard. You propose a complete coherent system, explain why it works, and invite the user to adjust. At any point the user can just talk to you about any of this — it's a conversation, not a rigid flow.
    27→
    28→---
    29→
    30→## Phase 0: Pre-checks
    31→
    32→**Check for existing DESIGN.md:**
    33→
    34→```bash
    35→ls DESIGN.md design-system.md 2>/dev/null || echo "NO_DESIGN_FILE"
    36→```
    37→
    38→- If a DESIGN.md exists: Read it. Ask the user: "You already have a design system. Want to **update** it, **start fresh**, or **cancel**?"
    39→- If no DESIGN.md: continue.
    40→
    41→**Gather product context from the codebase:**
    42→
    43→```bash
    44→cat README.md 2>/dev/null | head -50
    45→cat package.json 2>/dev/null | head -20
    46→ls src/ app/ pages/ components/ 2>/dev/null | head -30
    47→```
    48→
    49→Look for brainstorm output:
    50→
    51→```bash
    52→eval $(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)
    53→ls ~/.gstack/projects/$SLUG/*brainstorm* 2>/dev/null | head -5
    54→ls .context/*brainstorm* .context/attachments/*brainstorm* 2>/dev/null | head -5
    55→```
    56→
    57→If brainstorm output exists, read it — the product context is pre-filled.
    58→
    59→If the codebase is empty and purpose is unclear, say: *"I don't have a clear picture of what you're building yet. Want to brainstorm first with `/brainstorm`? Once we know the product direction, we can set up the design system."*
    60→
    61→**Find the browse binary (optional — enables visual competitive research):**
    62→
    63→{{BROWSE_SETUP}}
    64→
    65→If browse is not available, that's fine — visual research is optional. The skill works without it using WebSearch and your built-in design knowledge.
    66→
    67→---
    68→
    69→## Phase 1: Product Context
    70→
    71→Ask the user a single question that covers everything you need to know. Pre-fill what you can infer from the codebase.
    72→
    73→**AskUserQuestion Q1 — include ALL of these:**
    74→1. Confirm what the product is, who it's for, what space/industry
    75→2. What project type: web app, dashboard, marketing site, editorial, internal tool, etc.
    76→3. "Want me to research what top products in your space are doing for design, or should I work from my design knowledge?"
    77→4. **Explicitly say:** "At any point you can just drop into chat and we'll talk through anything — this isn't a rigid form, it's a conversation."
    78→
    79→If the README or brainstorm gives you enough context, pre-fill and confirm: *"From what I can see, this is [X] for [Y] in the [Z] space. Sound right? And would you like me to research what's out there in this space, or should I work from what I know?"*
    80→
    81→---
    82→
    83→## Phase 2: Research (only if user said yes)
    84→
    85→If the user wants competitive research:
    86→
    87→**Step 1: Identify what's out there via WebSearch**
    88→
    89→Use WebSearch to find 5-10 products in their space. Search for:
    90→- "[product category] website design"
    91→- "[product category] best websites 2025"
    92→- "best [industry] web apps"
    93→
    94→**Step 2: Visual research via browse (if available)**
    95→
    96→If the browse binary is available (`$B` is set), visit the top 3-5 sites in the space and capture visual evidence:
    97→
    98→```bash
    99→$B goto "https://example-site.com"
   100→$B screenshot "/tmp/design-research-site-name.png"
   101→$B snapshot
   102→```
   103→
   104→For each site, analyze: fonts actually used, color palette, layout approach, spacing density, aesthetic direction. The screenshot gives you the feel; the snapshot gives you structural data.
   105→
   106→If a site blocks the headless browser or requires login, skip it and note why.
   107→
   108→If browse is not available, rely on WebSearch results and your built-in design knowledge — this is fine.
   109→
   110→**Step 3: Synthesize findings**
   111→
   112→The goal of research is NOT to copy. It is to get in the ballpark — to understand the visual language users in this category already expect. This gives you the baseline. The interesting design work starts after you have the baseline: deciding where to follow conventions (so the product feels literate) and where to break from them (so the product is memorable).
   113→
   114→Summarize conversationally:
   115→> "I looked at what's out there. Here's the landscape: they converge on [patterns]. Most of them feel [observation — e.g., interchangeable, polished but generic, etc.]. The opportunity to stand out is [gap]. Here's where I'd play it safe and where I'd take a risk..."
   116→
   117→**Graceful degradation:**
   118→- Browse available → screenshots + snapshots + WebSearch (richest research)
   119→- Browse unavailable → WebSearch only (still good)
   120→- WebSearch also unavailable → agent's built-in design knowledge (always works)
   121→
   122→If the user said no research, skip entirely and proceed to Phase 3 using your built-in design knowledge.
   123→
   124→---
   125→
   126→## Phase 3: The Complete Proposal
   127→
   128→This is the soul of the skill. Propose EVERYTHING as one coherent package.
   129→
   130→**AskUserQuestion Q2 — present the full proposal with SAFE/RISK breakdown:**
   131→
   132→```
   133→Based on [product context] and [research findings / my design knowledge]:
   134→
   135→AESTHETIC: [direction] — [one-line rationale]
   136→DECORATION: [level] — [why this pairs with the aesthetic]
   137→LAYOUT: [approach] — [why this fits the product type]
   138→COLOR: [approach] + proposed palette (hex values) — [rationale]
   139→TYPOGRAPHY: [3 font recommendations with roles] — [why these fonts]
   140→SPACING: [base unit + density] — [rationale]
   141→MOTION: [approach] — [rationale]
   142→
   143→This system is coherent because [explain how choices reinforce each other].
   144→
   145→SAFE CHOICES (category baseline — your users expect these):
   146→  - [2-3 decisions that match category conventions, with rationale for playing safe]
   147→
   148→RISKS (where your product gets its own face):
   149→  - [2-3 deliberate departures from convention]
   150→  - For each risk: what it is, why it works, what you gain, what it costs
   151→
   152→The safe choices keep you literate in your category. The risks are where
   153→your product becomes memorable. Which risks appeal to you? Want to see
   154→different ones? Or adjust anything else?
   155→```
   156→
   157→The SAFE/RISK breakdown is critical. Design coherence is table stakes — every product in a category can be coherent and still look identical. The real question is: where do you take creative risks? The agent should always propose at least 2 risks, each with a clear rationale for why the risk is worth taking and what the user gives up. Risks might include: an unexpected typeface for the category, a bold accent color nobody else uses, tighter or looser spacing than the norm, a layout approach that breaks from convention, motion choices that add personality.
   158→
   159→**Options:** A) Looks great — generate the preview page. B) I want to adjust [section]. C) I want different risks — show me wilder options. D) Start over with a different direction. E) Skip the preview, just write DESIGN.md.
   160→
   161→### Your Design Knowledge (use to inform proposals — do NOT display as tables)
   162→
   163→**Aesthetic directions** (pick the one that fits the product):
   164→- Brutally Minimal — Type and whitespace only. No decoration. Modernist.
   165→- Maximalist Chaos — Dense, layered, pattern-heavy. Y2K meets contemporary.
   166→- Retro-Futuristic — Vintage tech nostalgia. CRT glow, pixel grids, warm monospace.
   167→- Luxury/Refined — Serifs, high contrast, generous whitespace, precious metals.
   168→- Playful/Toy-like — Rounded, bouncy, bold primaries. Approachable and fun.
   169→- Editorial/Magazine — Strong typographic hierarchy, asymmetric grids, pull quotes.
   170→- Brutalist/Raw — Exposed structure, system fonts, visible grid, no polish.
   171→- Art Deco — Geometric precision, metallic accents, symmetry, decorative borders.
   172→- Organic/Natural — Earth tones, rounded forms, hand-drawn texture, grain.
   173→- Industrial/Utilitarian — Function-first, data-dense, monospace accents, muted palette.
   174→
   175→**Decoration levels:** minimal (typography does all the work) / intentional (subtle texture, grain, or background treatment) / expressive (full creative direction, layered depth, patterns)
   176→
   177→**Layout approaches:** grid-disciplined (strict columns, predictable alignment) / creative-editorial (asymmetry, overlap, grid-breaking) / hybrid (grid for app, creative for marketing)
   178→
   179→**Color approaches:** restrained (1 accent + neutrals, color is rare and meaningful) / balanced (primary + secondary, semantic colors for hierarchy) / expressive (color as a primary design tool, bold palettes)
   180→
   181→**Motion approaches:** minimal-functional (only transitions that aid comprehension) / intentional (subtle entrance animations, meaningful state transitions) / expressive (full choreography, scroll-driven, playful)
   182→
   183→**Font recommendations by purpose:**
   184→- Display/Hero: Satoshi, General Sans, Instrument Serif, Fraunces, Clash Grotesk, Cabinet Grotesk
   185→- Body: Instrument Sans, DM Sans, Source Sans 3, Geist, Plus Jakarta Sans, Outfit
   186→- Data/Tables: Geist (tabular-nums), DM Sans (tabular-nums), JetBrains Mono, IBM Plex Mono
   187→- Code: JetBrains Mono, Fira Code, Berkeley Mono, Geist Mono
   188→
   189→**Font blacklist** (never recommend):
   190→Papyrus, Comic Sans, Lobster, Impact, Jokerman, Bleeding Cowboys, Permanent Marker, Bradley Hand, Brush Script, Hobo, Trajan, Raleway, Clash Display, Courier New (for body)
   191→
   192→**Overused fonts** (never recommend as primary — use only if user specifically requests):
   193→Inter, Roboto, Arial, Helvetica, Open Sans, Lato, Montserrat, Poppins
   194→
   195→**AI slop anti-patterns** (never include in your recommendations):
   196→- Purple/violet gradients as default accent
   197→- 3-column feature grid with icons in colored circles
   198→- Centered everything with uniform spacing
   199→- Uniform bubbly border-radius on all elements
   200→- Gradient buttons as the primary CTA pattern
   201→- Generic stock-photo-style hero sections
   202→- "Built for X" / "Designed for Y" marketing copy patterns
   203→
   204→### Coherence Validation
   205→
   206→When the user overrides one section, check if the rest still coheres. Flag mismatches with a gentle nudge — never block:
   207→
   208→- Brutalist/Minimal aesthetic + expressive motion → "Heads up: brutalist aesthetics usually pair with minimal motion. Your combo is unusual — which is fine if intentional. Want me to suggest motion that fits, or keep it?"
   209→- Expressive color + restrained decoration → "Bold palette with minimal decoration can work, but the colors will carry a lot of weight. Want me to suggest decoration that supports the palette?"
   210→- Creative-editorial layout + data-heavy product → "Editorial layouts are gorgeous but can fight data density. Want me to show how a hybrid approach keeps both?"
   211→- Always accept the user's final choice. Never refuse to proceed.
   212→
   213→---
   214→
   215→## Phase 4: Drill-downs (only if user requests adjustments)
   216→
   217→When the user wants to change a specific section, go deep on that section:
   218→
   219→- **Fonts:** Present 3-5 specific candidates with rationale, explain what each evokes, offer the preview page
   220→- **Colors:** Present 2-3 palette options with hex values, explain the color theory reasoning
   221→- **Aesthetic:** Walk through which directions fit their product and why
   222→- **Layout/Spacing/Motion:** Present the approaches with concrete tradeoffs for their product type
   223→
   224→Each drill-down is one focused AskUserQuestion. After the user decides, re-check coherence with the rest of the system.
   225→
   226→---
   227→
   228→## Phase 5: Font & Color Preview Page (default ON)
   229→
   230→Generate a polished HTML preview page and open it in the user's browser. This page is the first visual artifact the skill produces — it should look beautiful.
   231→
   232→```bash
   233→PREVIEW_FILE="/tmp/design-consultation-preview-$(date +%s).html"
   234→```
   235→
   236→Write the preview HTML to `$PREVIEW_FILE`, then open it:
   237→
   238→```bash
   239→open "$PREVIEW_FILE"
   240→```
   241→
   242→### Preview Page Requirements
   243→
   244→The agent writes a **single, self-contained HTML file** (no framework dependencies) that:
   245→
   246→1. **Loads proposed fonts** from Google Fonts (or Bunny Fonts) via `<link>` tags
   247→2. **Uses the proposed color palette** throughout — dogfood the design system
   248→3. **Shows the product name** (not "Lorem Ipsum") as the hero heading
   249→4. **Font specimen section:**
   250→   - Each font candidate shown in its proposed role (hero heading, body paragraph, button label, data table row)
   251→   - Side-by-side comparison if multiple candidates for one role
   252→   - Real content that matches the product (e.g., civic tech → government data examples)
   253→5. **Color palette section:**
   254→   - Swatches with hex values and names
   255→   - Sample UI components rendered in the palette: buttons (primary, secondary, ghost), cards, form inputs, alerts (success, warning, error, info)
   256→   - Background/text color combinations showing contrast
   257→6. **Realistic product mockups** — this is what makes the preview page powerful. Based on the project type from Phase 1, render 2-3 realistic page layouts using the full design system:
   258→   - **Dashboard / web app:** sample data table with metrics, sidebar nav, header with user avatar, stat cards
   259→   - **Marketing site:** hero section with real copy, feature highlights, testimonial block, CTA
   260→   - **Settings / admin:** form with labeled inputs, toggle switches, dropdowns, save button
   261→   - **Auth / onboarding:** login form with social buttons, branding, input validation states
   262→   - Use the product name, realistic content for the domain, and the proposed spacing/layout/border-radius. The user should see their product (roughly) before writing any code.
   263→7. **Light/dark mode toggle** using CSS custom properties and a JS toggle button
   264→8. **Clean, professional layout** — the preview page IS a taste signal for the skill
   265→9. **Responsive** — looks good on any screen width
   266→
   267→The page should make the user think "oh nice, they thought of this." It's selling the design system by showing what the product could feel like, not just listing hex codes and font names.
   268→
   269→If `open` fails (headless environment), tell the user: *"I wrote the preview to [path] — open it in your browser to see the fonts and colors rendered."*
   270→
   271→If the user says skip the preview, go directly to Phase 6.
   272→
   273→---
   274→
   275→## Phase 6: Write DESIGN.md & Confirm
   276→
   277→Write `DESIGN.md` to the repo root with this structure:
   278→
   279→```markdown
   280→# Design System — [Project Name]
   281→
   282→## Product Context
   283→- **What this is:** [1-2 sentence description]
   284→- **Who it's for:** [target users]
   285→- **Space/industry:** [category, peers]
   286→- **Project type:** [web app / dashboard / marketing site / editorial / internal tool]
   287→
   288→## Aesthetic Direction
   289→- **Direction:** [name]
   290→- **Decoration level:** [minimal / intentional / expressive]
   291→- **Mood:** [1-2 sentence description of how the product should feel]
   292→- **Reference sites:** [URLs, if research was done]
   293→
   294→## Typography
   295→- **Display/Hero:** [font name] — [rationale]
   296→- **Body:** [font name] — [rationale]
   297→- **UI/Labels:** [font name or "same as body"]
   298→- **Data/Tables:** [font name] — [rationale, must support tabular-nums]
   299→- **Code:** [font name]
   300→- **Loading:** [CDN URL or self-hosted strategy]
   301→- **Scale:** [modular scale with specific px/rem values for each level]
   302→
   303→## Color
   304→- **Approach:** [restrained / balanced / expressive]
   305→- **Primary:** [hex] — [what it represents, usage]
   306→- **Secondary:** [hex] — [usage]
   307→- **Neutrals:** [warm/cool grays, hex range from lightest to darkest]
   308→- **Semantic:** success [hex], warning [hex], error [hex], info [hex]
   309→- **Dark mode:** [strategy — redesign surfaces, reduce saturation 10-20%]
   310→
   311→## Spacing
   312→- **Base unit:** [4px or 8px]
   313→- **Density:** [compact / comfortable / spacious]
   314→- **Scale:** 2xs(2) xs(4) sm(8) md(16) lg(24) xl(32) 2xl(48) 3xl(64)
   315→
   316→## Layout
   317→- **Approach:** [grid-disciplined / creative-editorial / hybrid]
   318→- **Grid:** [columns per breakpoint]
   319→- **Max content width:** [value]
   320→- **Border radius:** [hierarchical scale — e.g., sm:4px, md:8px, lg:12px, full:9999px]
   321→
   322→## Motion
   323→- **Approach:** [minimal-functional / intentional / expressive]
   324→- **Easing:** enter(ease-out) exit(ease-in) move(ease-in-out)
   325→- **Duration:** micro(50-100ms) short(150-250ms) medium(250-400ms) long(400-700ms)
   326→
   327→## Decisions Log
   328→| Date | Decision | Rationale |
   329→|------|----------|-----------|
   330→| [today] | Initial design system created | Created by /design-consultation based on [product context / research] |
   331→```
   332→
   333→**Update CLAUDE.md** (or create it if it doesn't exist) — append this section:
   334→
   335→```markdown
   336→## Design System
   337→Always read DESIGN.md before making any visual or UI decisions.
   338→All font choices, colors, spacing, and aesthetic direction are defined there.
   339→Do not deviate without explicit user approval.
   340→In QA mode, flag any code that doesn't match DESIGN.md.
   341→```
   342→
   343→**AskUserQuestion Q-final — show summary and confirm:**
   344→
   345→List all decisions. Flag any that used agent defaults without explicit user confirmation (the user should know what they're shipping). Options:
   346→- A) Ship it — write DESIGN.md and CLAUDE.md
   347→- B) I want to change something (specify what)
   348→- C) Start over
   349→
   350→---
   351→
   352→## Important Rules
   353→
   354→1. **Propose, don't present menus.** You are a consultant, not a form. Make opinionated recommendations based on the product context, then let the user adjust.
   355→2. **Every recommendation needs a rationale.** Never say "I recommend X" without "because Y."
   356→3. **Coherence over individual choices.** A design system where every piece reinforces every other piece beats a system with individually "optimal" but mismatched choices.
   357→4. **Never recommend blacklisted or overused fonts as primary.** If the user specifically requests one, comply but explain the tradeoff.
   358→5. **The preview page must be beautiful.** It's the first visual output and sets the tone for the whole skill.
   359→6. **Conversational tone.** This isn't a rigid workflow. If the user wants to talk through a decision, engage as a thoughtful design partner.
   360→7. **Accept the user's final choice.** Nudge on coherence issues, but never block or refuse to write a DESIGN.md because you disagree with a choice.
   361→8. **No AI slop in your own output.** Your recommendations, your preview page, your DESIGN.md — all should demonstrate the taste you're asking the user to adopt.
   362→


     1→/**
     2→ * gstack browse server — persistent Chromium daemon
     3→ *
     4→ * Architecture:
     5→ *   Bun.serve HTTP on localhost → routes commands to Playwright
     6→ *   Console/network/dialog buffers: CircularBuffer in-memory + async disk flush
     7→ *   Chromium crash → server EXITS with clear error (CLI auto-restarts)
     8→ *   Auto-shutdown after BROWSE_IDLE_TIMEOUT (default 30 min)
     9→ *
    10→ * State:
    11→ *   State file: <project-root>/.gstack/browse.json (set via BROWSE_STATE_FILE env)
    12→ *   Log files:  <project-root>/.gstack/browse-{console,network,dialog}.log
    13→ *   Port:       random 10000-60000 (or BROWSE_PORT env for debug override)
    14→ */
    15→
    16→import { BrowserManager } from './browser-manager';
    17→import { handleReadCommand } from './read-commands';
    18→import { handleWriteCommand } from './write-commands';
    19→import { handleMetaCommand } from './meta-commands';
    20→import { handleCookiePickerRoute } from './cookie-picker-routes';
    21→import { COMMAND_DESCRIPTIONS } from './commands';
    22→import { SNAPSHOT_FLAGS } from './snapshot';
    23→import { resolveConfig, ensureStateDir, readVersionHash } from './config';
    24→import * as fs from 'fs';
    25→import * as path from 'path';
    26→import * as crypto from 'crypto';
    27→
    28→// ─── Config ─────────────────────────────────────────────────────
    29→const config = resolveConfig();
    30→ensureStateDir(config);
    31→
    32→// ─── Auth ───────────────────────────────────────────────────────
    33→const AUTH_TOKEN = crypto.randomUUID();
    34→const BROWSE_PORT = parseInt(process.env.BROWSE_PORT || '0', 10);
    35→const IDLE_TIMEOUT_MS = parseInt(process.env.BROWSE_IDLE_TIMEOUT || '1800000', 10); // 30 min
    36→
    37→function validateAuth(req: Request): boolean {
    38→  const header = req.headers.get('authorization');
    39→  return header === `Bearer ${AUTH_TOKEN}`;
    40→}
    41→
    42→// ─── Help text (auto-generated from COMMAND_DESCRIPTIONS) ────────
    43→function generateHelpText(): string {
    44→  // Group commands by category
    45→  const groups = new Map<string, string[]>();
    46→  for (const [cmd, meta] of Object.entries(COMMAND_DESCRIPTIONS)) {
    47→    const display = meta.usage || cmd;
    48→    const list = groups.get(meta.category) || [];
    49→    list.push(display);
    50→    groups.set(meta.category, list);
    51→  }
    52→
    53→  const categoryOrder = [
    54→    'Navigation', 'Reading', 'Interaction', 'Inspection',
    55→    'Visual', 'Snapshot', 'Meta', 'Tabs', 'Server',
    56→  ];
    57→
    58→  const lines = ['gstack browse — headless browser for AI agents', '', 'Commands:'];
    59→  for (const cat of categoryOrder) {
    60→    const cmds = groups.get(cat);
    61→    if (!cmds) continue;
    62→    lines.push(`  ${(cat + ':').padEnd(15)}${cmds.join(', ')}`);
    63→  }
    64→
    65→  // Snapshot flags from source of truth
    66→  lines.push('');
    67→  lines.push('Snapshot flags:');
    68→  const flagPairs: string[] = [];
    69→  for (const flag of SNAPSHOT_FLAGS) {
    70→    const label = flag.valueHint ? `${flag.short} ${flag.valueHint}` : flag.short;
    71→    flagPairs.push(`${label}  ${flag.long}`);
    72→  }
    73→  // Print two flags per line for compact display
    74→  for (let i = 0; i < flagPairs.length; i += 2) {
    75→    const left = flagPairs[i].padEnd(28);
    76→    const right = flagPairs[i + 1] || '';
    77→    lines.push(`  ${left}${right}`);
    78→  }
    79→
    80→  return lines.join('\n');
    81→}
    82→
    83→// ─── Buffer (from buffers.ts) ────────────────────────────────────
    84→import { consoleBuffer, networkBuffer, dialogBuffer, addConsoleEntry, addNetworkEntry, addDialogEntry, type LogEntry, type NetworkEntry, type DialogEntry } from './buffers';
    85→export { consoleBuffer, networkBuffer, dialogBuffer, addConsoleEntry, addNetworkEntry, addDialogEntry, type LogEntry, type NetworkEntry, type DialogEntry };
    86→
    87→const CONSOLE_LOG_PATH = config.consoleLog;
    88→const NETWORK_LOG_PATH = config.networkLog;
    89→const DIALOG_LOG_PATH = config.dialogLog;
    90→let lastConsoleFlushed = 0;
    91→let lastNetworkFlushed = 0;
    92→let lastDialogFlushed = 0;
    93→let flushInProgress = false;
    94→
    95→async function flushBuffers() {
    96→  if (flushInProgress) return; // Guard against concurrent flush
    97→  flushInProgress = true;
    98→
    99→  try {
   100→    // Console buffer
   101→    const newConsoleCount = consoleBuffer.totalAdded - lastConsoleFlushed;
   102→    if (newConsoleCount > 0) {
   103→      const entries = consoleBuffer.last(Math.min(newConsoleCount, consoleBuffer.length));
   104→      const lines = entries.map(e =>
   105→        `[${new Date(e.timestamp).toISOString()}] [${e.level}] ${e.text}`
   106→      ).join('\n') + '\n';
   107→      fs.appendFileSync(CONSOLE_LOG_PATH, lines);
   108→      lastConsoleFlushed = consoleBuffer.totalAdded;
   109→    }
   110→
   111→    // Network buffer
   112→    const newNetworkCount = networkBuffer.totalAdded - lastNetworkFlushed;
   113→    if (newNetworkCount > 0) {
   114→      const entries = networkBuffer.last(Math.min(newNetworkCount, networkBuffer.length));
   115→      const lines = entries.map(e =>
   116→        `[${new Date(e.timestamp).toISOString()}] ${e.method} ${e.url} → ${e.status || 'pending'} (${e.duration || '?'}ms, ${e.size || '?'}B)`
   117→      ).join('\n') + '\n';
   118→      fs.appendFileSync(NETWORK_LOG_PATH, lines);
   119→      lastNetworkFlushed = networkBuffer.totalAdded;
   120→    }
   121→
   122→    // Dialog buffer
   123→    const newDialogCount = dialogBuffer.totalAdded - lastDialogFlushed;
   124→    if (newDialogCount > 0) {
   125→      const entries = dialogBuffer.last(Math.min(newDialogCount, dialogBuffer.length));
   126→      const lines = entries.map(e =>
   127→        `[${new Date(e.timestamp).toISOString()}] [${e.type}] "${e.message}" → ${e.action}${e.response ? ` "${e.response}"` : ''}`
   128→      ).join('\n') + '\n';
   129→      fs.appendFileSync(DIALOG_LOG_PATH, lines);
   130→      lastDialogFlushed = dialogBuffer.totalAdded;
   131→    }
   132→  } catch {
   133→    // Flush failures are non-fatal — buffers are in memory
   134→  } finally {
   135→    flushInProgress = false;
   136→  }
   137→}
   138→
   139→// Flush every 1 second
   140→const flushInterval = setInterval(flushBuffers, 1000);
   141→
   142→// ─── Idle Timer ────────────────────────────────────────────────
   143→let lastActivity = Date.now();
   144→
   145→function resetIdleTimer() {
   146→  lastActivity = Date.now();
   147→}
   148→
   149→const idleCheckInterval = setInterval(() => {
   150→  if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) {
   151→    console.log(`[browse] Idle for ${IDLE_TIMEOUT_MS / 1000}s, shutting down`);
   152→    shutdown();
   153→  }
   154→}, 60_000);
   155→
   156→// ─── Command Sets (from commands.ts — single source of truth) ───
   157→import { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS } from './commands';
   158→export { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS };
   159→
   160→// ─── Server ────────────────────────────────────────────────────
   161→const browserManager = new BrowserManager();
   162→let isShuttingDown = false;
   163→
   164→// Find port: explicit BROWSE_PORT, or random in 10000-60000
   165→async function findPort(): Promise<number> {
   166→  // Explicit port override (for debugging)
   167→  if (BROWSE_PORT) {
   168→    try {
   169→      const testServer = Bun.serve({ port: BROWSE_PORT, fetch: () => new Response('ok') });
   170→      testServer.stop();
   171→      return BROWSE_PORT;
   172→    } catch {
   173→      throw new Error(`[browse] Port ${BROWSE_PORT} (from BROWSE_PORT env) is in use`);
   174→    }
   175→  }
   176→
   177→  // Random port with retry
   178→  const MIN_PORT = 10000;
   179→  const MAX_PORT = 60000;
   180→  const MAX_RETRIES = 5;
   181→  for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
   182→    const port = MIN_PORT + Math.floor(Math.random() * (MAX_PORT - MIN_PORT));
   183→    try {
   184→      const testServer = Bun.serve({ port, fetch: () => new Response('ok') });
   185→      testServer.stop();
   186→      return port;
   187→    } catch {
   188→      continue;
   189→    }
   190→  }
   191→  throw new Error(`[browse] No available port after ${MAX_RETRIES} attempts in range ${MIN_PORT}-${MAX_PORT}`);
   192→}
   193→
   194→/**
   195→ * Translate Playwright errors into actionable messages for AI agents.
   196→ */
   197→function wrapError(err: any): string {
   198→  const msg = err.message || String(err);
   199→  // Timeout errors
   200→  if (err.name === 'TimeoutError' || msg.includes('Timeout') || msg.includes('timeout')) {
   201→    if (msg.includes('locator.click') || msg.includes('locator.fill') || msg.includes('locator.hover')) {
   202→      return `Element not found or not interactable within timeout. Check your selector or run 'snapshot' for fresh refs.`;
   203→    }
   204→    if (msg.includes('page.goto') || msg.includes('Navigation')) {
   205→      return `Page navigation timed out. The URL may be unreachable or the page may be loading slowly.`;
   206→    }
   207→    return `Operation timed out: ${msg.split('\n')[0]}`;
   208→  }
   209→  // Multiple elements matched
   210→  if (msg.includes('resolved to') && msg.includes('elements')) {
   211→    return `Selector matched multiple elements. Be more specific or use @refs from 'snapshot'.`;
   212→  }
   213→  // Pass through other errors
   214→  return msg;
   215→}
   216→
   217→async function handleCommand(body: any): Promise<Response> {
   218→  const { command, args = [] } = body;
   219→
   220→  if (!command) {
   221→    return new Response(JSON.stringify({ error: 'Missing "command" field' }), {
   222→      status: 400,
   223→      headers: { 'Content-Type': 'application/json' },
   224→    });
   225→  }
   226→
   227→  try {
   228→    let result: string;
   229→
   230→    if (READ_COMMANDS.has(command)) {
   231→      result = await handleReadCommand(command, args, browserManager);
   232→    } else if (WRITE_COMMANDS.has(command)) {
   233→      result = await handleWriteCommand(command, args, browserManager);
   234→    } else if (META_COMMANDS.has(command)) {
   235→      result = await handleMetaCommand(command, args, browserManager, shutdown);
   236→    } else if (command === 'help') {
   237→      const helpText = generateHelpText();
   238→      return new Response(helpText, {
   239→        status: 200,
   240→        headers: { 'Content-Type': 'text/plain' },
   241→      });
   242→    } else {
   243→      return new Response(JSON.stringify({
   244→        error: `Unknown command: ${command}`,
   245→        hint: `Available commands: ${[...READ_COMMANDS, ...WRITE_COMMANDS, ...META_COMMANDS].sort().join(', ')}`,
   246→      }), {
   247→        status: 400,
   248→        headers: { 'Content-Type': 'application/json' },
   249→      });
   250→    }


     1→/**
     2→ * Browser lifecycle manager
     3→ *
     4→ * Chromium crash handling:
     5→ *   browser.on('disconnected') → log error → process.exit(1)
     6→ *   CLI detects dead server → auto-restarts on next command
     7→ *   We do NOT try to self-heal — don't hide failure.
     8→ *
     9→ * Dialog handling:
    10→ *   page.on('dialog') → auto-accept by default → store in dialog buffer
    11→ *   Prevents browser lockup from alert/confirm/prompt
    12→ *
    13→ * Context recreation (useragent):
    14→ *   recreateContext() saves cookies/storage/URLs, creates new context,
    15→ *   restores state. Falls back to clean slate on any failure.
    16→ */
    17→
    18→import { chromium, type Browser, type BrowserContext, type BrowserContextOptions, type Page, type Locator } from 'playwright';
    19→import { addConsoleEntry, addNetworkEntry, addDialogEntry, networkBuffer, type DialogEntry } from './buffers';
    20→
    21→export interface RefEntry {
    22→  locator: Locator;
    23→  role: string;
    24→  name: string;
    25→}
    26→
    27→export class BrowserManager {
    28→  private browser: Browser | null = null;
    29→  private context: BrowserContext | null = null;
    30→  private pages: Map<number, Page> = new Map();
    31→  private activeTabId: number = 0;
    32→  private nextTabId: number = 1;
    33→  private extraHeaders: Record<string, string> = {};
    34→  private customUserAgent: string | null = null;
    35→
    36→  /** Server port — set after server starts, used by cookie-import-browser command */
    37→  public serverPort: number = 0;
    38→
    39→  // ─── Ref Map (snapshot → @e1, @e2, @c1, @c2, ...) ────────
    40→  private refMap: Map<string, RefEntry> = new Map();
    41→
    42→  // ─── Snapshot Diffing ─────────────────────────────────────
    43→  // NOT cleared on navigation — it's a text baseline for diffing
    44→  private lastSnapshot: string | null = null;
    45→
    46→  // ─── Dialog Handling ──────────────────────────────────────
    47→  private dialogAutoAccept: boolean = true;
    48→  private dialogPromptText: string | null = null;
    49→
    50→  async launch() {
    51→    this.browser = await chromium.launch({ headless: true });
    52→
    53→    // Chromium crash → exit with clear message
    54→    this.browser.on('disconnected', () => {
    55→      console.error('[browse] FATAL: Chromium process crashed or was killed. Server exiting.');
    56→      console.error('[browse] Console/network logs flushed to .gstack/browse-*.log');
    57→      process.exit(1);
    58→    });
    59→
    60→    const contextOptions: BrowserContextOptions = {
    61→      viewport: { width: 1280, height: 720 },
    62→    };
    63→    if (this.customUserAgent) {
    64→      contextOptions.userAgent = this.customUserAgent;
    65→    }
    66→    this.context = await this.browser.newContext(contextOptions);
    67→
    68→    if (Object.keys(this.extraHeaders).length > 0) {
    69→      await this.context.setExtraHTTPHeaders(this.extraHeaders);
    70→    }
    71→
    72→    // Create first tab
    73→    await this.newTab();
    74→  }
    75→
    76→  async close() {
    77→    if (this.browser) {
    78→      // Remove disconnect handler to avoid exit during intentional close
    79→      this.browser.removeAllListeners('disconnected');
    80→      await this.browser.close();
    81→      this.browser = null;
    82→    }
    83→  }
    84→
    85→  /** Health check — verifies Chromium is connected AND responsive */
    86→  async isHealthy(): Promise<boolean> {
    87→    if (!this.browser || !this.browser.isConnected()) return false;
    88→    try {
    89→      const page = this.pages.get(this.activeTabId);
    90→      if (!page) return true; // connected but no pages — still healthy
    91→      await Promise.race([
    92→        page.evaluate('1'),
    93→        new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 2000)),
    94→      ]);
    95→      return true;
    96→    } catch {
    97→      return false;
    98→    }
    99→  }
   100→
   101→  // ─── Tab Management ────────────────────────────────────────
   102→  async newTab(url?: string): Promise<number> {
   103→    if (!this.context) throw new Error('Browser not launched');
   104→
   105→    const page = await this.context.newPage();
   106→    const id = this.nextTabId++;
   107→    this.pages.set(id, page);
   108→    this.activeTabId = id;
   109→
   110→    // Wire up console/network/dialog capture
   111→    this.wirePageEvents(page);
   112→
   113→    if (url) {
   114→      await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 });
   115→    }
   116→
   117→    return id;
   118→  }
   119→
   120→  async closeTab(id?: number): Promise<void> {
   121→    const tabId = id ?? this.activeTabId;
   122→    const page = this.pages.get(tabId);
   123→    if (!page) throw new Error(`Tab ${tabId} not found`);
   124→
   125→    await page.close();
   126→    this.pages.delete(tabId);
   127→
   128→    // Switch to another tab if we closed the active one
   129→    if (tabId === this.activeTabId) {
   130→      const remaining = [...this.pages.keys()];
   131→      if (remaining.length > 0) {
   132→        this.activeTabId = remaining[remaining.length - 1];
   133→      } else {
   134→        // No tabs left — create a new blank one
   135→        await this.newTab();
   136→      }
   137→    }
   138→  }
   139→
   140→  switchTab(id: number): void {
   141→    if (!this.pages.has(id)) throw new Error(`Tab ${id} not found`);
   142→    this.activeTabId = id;
   143→  }
   144→
   145→  getTabCount(): number {
   146→    return this.pages.size;
   147→  }
   148→
   149→  async getTabListWithTitles(): Promise<Array<{ id: number; url: string; title: string; active: boolean }>> {
   150→    const tabs: Array<{ id: number; url: string; title: string; active: boolean }> = [];
   151→    for (const [id, page] of this.pages) {
   152→      tabs.push({
   153→        id,
   154→        url: page.url(),
   155→        title: await page.title().catch(() => ''),
   156→        active: id === this.activeTabId,
   157→      });
   158→    }
   159→    return tabs;
   160→  }
   161→
   162→  // ─── Page Access ───────────────────────────────────────────
   163→  getPage(): Page {
   164→    const page = this.pages.get(this.activeTabId);
   165→    if (!page) throw new Error('No active page. Use "browse goto <url>" first.');
   166→    return page;
   167→  }
   168→
   169→  getCurrentUrl(): string {
   170→    try {
   171→      return this.getPage().url();
   172→    } catch {
   173→      return 'about:blank';
   174→    }
   175→  }
   176→
   177→  // ─── Ref Map ──────────────────────────────────────────────
   178→  setRefMap(refs: Map<string, RefEntry>) {
   179→    this.refMap = refs;
   180→  }
   181→
   182→  clearRefs() {
   183→    this.refMap.clear();
   184→  }
   185→
   186→  /**
   187→   * Resolve a selector that may be a @ref (e.g., "@e3", "@c1") or a CSS selector.
   188→   * Returns { locator } for refs or { selector } for CSS selectors.
   189→   */
   190→  async resolveRef(selector: string): Promise<{ locator: Locator } | { selector: string }> {
   191→    if (selector.startsWith('@e') || selector.startsWith('@c')) {
   192→      const ref = selector.slice(1); // "e3" or "c1"
   193→      const entry = this.refMap.get(ref);
   194→      if (!entry) {
   195→        throw new Error(
   196→          `Ref ${selector} not found. Run 'snapshot' to get fresh refs.`
   197→        );
   198→      }
   199→      const count = await entry.locator.count();
   200→      if (count === 0) {


Bash

List browse source files


total 176
drwxr-xr-x 2 root root  4096 Mar 18 15:58 .
drwxr-xr-x 5 root root    77 Mar 18 15:58 ..
-rw-r--r-- 1 root root 15877 Mar 18 15:58 browser-manager.ts
-rw-r--r-- 1 root root  4276 Mar 18 15:58 buffers.ts
-rw-r--r-- 1 root root 11046 Mar 18 15:58 cli.ts
-rw-r--r-- 1 root root  7899 Mar 18 15:58 commands.ts
-rw-r--r-- 1 root root  4694 Mar 18 15:58 config.ts
-rw-r--r-- 1 root root 15632 Mar 18 15:58 cookie-import-browser.ts
-rw-r--r-- 1 root root  7704 Mar 18 15:58 cookie-picker-routes.ts
-rw-r--r-- 1 root root 16745 Mar 18 15:58 cookie-picker-ui.ts
-rw-r--r-- 1 root root  1654 Mar 18 15:58 find-browse.ts
-rw-r--r-- 1 root root  9221 Mar 18 15:58 meta-commands.ts
-rw-r--r-- 1 root root 11743 Mar 18 15:58 read-commands.ts
-rw-r--r-- 1 root root 13412 Mar 18 15:58 server.ts
-rw-r--r-- 1 root root 15117 Mar 18 15:58 snapshot.ts
-rw-r--r-- 1 root root 13237 Mar 18 15:58 write-commands.ts


List all skill directories


grep -E "^function generate|const.*=.*function|resolvers\[" /root/projects/gits/gstack/scripts/gen-skill-docs.ts | head -30


     1→---
     2→name: gstack
     3→version: 1.1.0
     4→description: |
     5→  Fast headless browser for QA testing and site dogfooding. Navigate any URL, interact with
     6→  elements, verify page state, diff before/after actions, take annotated screenshots, check
     7→  responsive layouts, test forms and uploads, handle dialogs, and assert element states.
     8→  ~100ms per command. Use when you need to test a feature, verify a deployment, dogfood a
     9→  user flow, or file a bug with evidence.
    10→allowed-tools:
    11→  - Bash
    12→  - Read
    13→  - AskUserQuestion
    14→
    15→---
    16→<!-- AUTO-GENERATED from SKILL.md.tmpl — do not edit directly -->
    17→<!-- Regenerate: bun run gen:skill-docs -->
    18→
    19→## Preamble (run first)
    20→
    21→```bash
    22→_UPD=$(~/.claude/skills/gstack/bin/gstack-update-check 2>/dev/null || .claude/skills/gstack/bin/gstack-update-check 2>/dev/null || true)
    23→[ -n "$_UPD" ] && echo "$_UPD" || true
    24→mkdir -p ~/.gstack/sessions
    25→touch ~/.gstack/sessions/"$PPID"
    26→_SESSIONS=$(find ~/.gstack/sessions -mmin -120 -type f 2>/dev/null | wc -l | tr -d ' ')
    27→find ~/.gstack/sessions -mmin +120 -type f -delete 2>/dev/null || true
    28→_CONTRIB=$(~/.claude/skills/gstack/bin/gstack-config get gstack_contributor 2>/dev/null || true)
    29→_BRANCH=$(git branch --show-current 2>/dev/null || echo "unknown")
    30→echo "BRANCH: $_BRANCH"
    31→_LAKE_SEEN=$([ -f ~/.gstack/.completeness-intro-seen ] && echo "yes" || echo "no")
    32→echo "LAKE_INTRO: $_LAKE_SEEN"
    33→```
    34→
    35→If output shows `UPGRADE_AVAILABLE <old> <new>`: read `~/.claude/skills/gstack/gstack-upgrade/SKILL.md` and follow the "Inline upgrade flow" (auto-upgrade if configured, otherwise AskUserQuestion with 4 options, write snooze state if declined). If `JUST_UPGRADED <from> <to>`: tell user "Running gstack v{to} (just updated!)" and continue.
    36→
    37→If `LAKE_INTRO` is `no`: Before continuing, introduce the Completeness Principle.
    38→Tell the user: "gstack follows the **Boil the Lake** principle — always do the complete
    39→thing when AI makes the marginal cost near-zero. Read more: https://garryslist.org/posts/boil-the-ocean"
    40→Then offer to open the essay in their default browser:
    41→
    42→```bash
    43→open https://garryslist.org/posts/boil-the-ocean
    44→touch ~/.gstack/.completeness-intro-seen
    45→```
    46→
    47→Only run `open` if the user says yes. Always run `touch` to mark as seen. This only happens once.
    48→
    49→## AskUserQuestion Format
    50→
    51→**ALWAYS follow this structure for every AskUserQuestion call:**
    52→1. **Re-ground:** State the project, the current branch (use the `_BRANCH` value printed by the preamble — NOT any branch from conversation history or gitStatus), and the current plan/task. (1-2 sentences)
    53→2. **Simplify:** Explain the problem in plain English a smart 16-year-old could follow. No raw function names, no internal jargon, no implementation details. Use concrete examples and analogies. Say what it DOES, not what it's called.
    54→3. **Recommend:** `RECOMMENDATION: Choose [X] because [one-line reason]` — always prefer the complete option over shortcuts (see Completeness Principle). Include `Completeness: X/10` for each option. Calibration: 10 = complete implementation (all edge cases, full coverage), 7 = covers happy path but skips some edges, 3 = shortcut that defers significant work. If both options are 8+, pick the higher; if one is ≤5, flag it.
    55→4. **Options:** Lettered options: `A) ... B) ... C) ...` — when an option involves effort, show both scales: `(human: ~X / CC: ~Y)`
    56→
    57→Assume the user hasn't looked at this window in 20 minutes and doesn't have the code open. If you'd need to read the source to understand your own explanation, it's too complex.
    58→
    59→Per-skill instructions may add additional formatting rules on top of this baseline.
    60→
    61→## Completeness Principle — Boil the Lake
    62→
    63→AI-assisted coding makes the marginal cost of completeness near-zero. When you present options:
    64→
    65→- If Option A is the complete implementation (full parity, all edge cases, 100% coverage) and Option B is a shortcut that saves modest effort — **always recommend A**. The delta between 80 lines and 150 lines is meaningless with CC+gstack. "Good enough" is the wrong instinct when "complete" costs minutes more.
    66→- **Lake vs. ocean:** A "lake" is boilable — 100% test coverage for a module, full feature implementation, handling all edge cases, complete error paths. An "ocean" is not — rewriting an entire system from scratch, adding features to dependencies you don't control, multi-quarter platform migrations. Recommend boiling lakes. Flag oceans as out of scope.
    67→- **When estimating effort**, always show both scales: human team time and CC+gstack time. The compression ratio varies by task type — use this reference:
    68→
    69→| Task type | Human team | CC+gstack | Compression |
    70→|-----------|-----------|-----------|-------------|
    71→| Boilerplate / scaffolding | 2 days | 15 min | ~100x |
    72→| Test writing | 1 day | 15 min | ~50x |
    73→| Feature implementation | 1 week | 30 min | ~30x |
    74→| Bug fix + regression test | 4 hours | 15 min | ~20x |
    75→| Architecture / design | 2 days | 4 hours | ~5x |
    76→| Research / exploration | 1 day | 3 hours | ~3x |
    77→
    78→- This principle applies to test coverage, error handling, documentation, edge cases, and feature completeness. Don't skip the last 10% to "save time" — with AI, that 10% costs seconds.
    79→
    80→**Anti-patterns — DON'T do this:**
    81→- BAD: "Choose B — it covers 90% of the value with less code." (If A is only 70 lines more, choose A.)
    82→- BAD: "We can skip edge case handling to save time." (Edge case handling costs minutes with CC.)
    83→- BAD: "Let's defer test coverage to a follow-up PR." (Tests are the cheapest lake to boil.)
    84→- BAD: Quoting only human-team effort: "This would take 2 weeks." (Say: "2 weeks human / ~1 hour CC.")
    85→
    86→## Contributor Mode
    87→
    88→If `_CONTRIB` is `true`: you are in **contributor mode**. You're a gstack user who also helps make it better.
    89→
    90→**At the end of each major workflow step** (not after every single command), reflect on the gstack tooling you used. Rate your experience 0 to 10. If it wasn't a 10, think about why. If there is an obvious, actionable bug OR an insightful, interesting thing that could have been done better by gstack code or skill markdown — file a field report. Maybe our contributor will help make us better!
    91→
    92→**Calibration — this is the bar:** For example, `$B js "await fetch(...)"` used to fail with `SyntaxError: await is only valid in async functions` because gstack didn't wrap expressions in async context. Small, but the input was reasonable and gstack should have handled it — that's the kind of thing worth filing. Things less consequential than this, ignore.
    93→
    94→**NOT worth filing:** user's app bugs, network errors to user's URL, auth failures on user's site, user's own JS logic bugs.
    95→
    96→**To file:** write `~/.gstack/contributor-logs/{slug}.md` with **all sections below** (do not truncate — include every section through the Date/Version footer):
    97→
    98→```
    99→# {Title}
   100→


/root/projects/gits/gstack/bin/:
total 32
drwxr-xr-x  2 root root  135 Mar 18 15:58 .
drwxr-xr-x 22 root root 4096 Mar 18 15:58 ..
-rwxr-xr-x  1 root root 1952 Mar 18 15:58 dev-setup
-rwxr-xr-x  1 root root  946 Mar 18 15:58 dev-teardown
-rwxr-xr-x  1 root root 1134 Mar 18 15:58 gstack-config
-rwxr-xr-x  1 root root 2480 Mar 18 15:58 gstack-diff-scope
-rwxr-xr-x  1 root root  476 Mar 18 15:58 gstack-slug
-rwxr-xr-x  1 root root 5636 Mar 18 15:58 gstack-update-check

/root/projects/gits/gstack/browse/:
total 32
drwxr-xr-x  5 root root    77 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
drwxr-xr-x  2 root root    44 Mar 18 15:58 bin
-rw-r--r--  1 root root 16291 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root  3254 Mar 18 15:58 SKILL.md.tmpl
drwxr-xr-x  2 root root  4096 Mar 18 15:58 src
drwxr-xr-x  3 root root  4096 Mar 18 15:58 test

/root/projects/gits/gstack/design-consultation/:
total 52
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 26030 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 18398 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/design-review/:
total 56
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 39162 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root  8529 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/docs/:
total 40
drwxr-xr-x  3 root root    37 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
drwxr-xr-x  2 root root    52 Mar 18 15:58 images
-rw-r--r--  1 root root 32964 Mar 18 15:58 skills.md

/root/projects/gits/gstack/document-release/:
total 44
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 21444 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 13720 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/gstack-upgrade/:
total 20
drwxr-xr-x  2 root root   43 Mar 18 15:58 .
drwxr-xr-x 22 root root 4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 7962 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 7850 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/plan-ceo-review/:
total 112
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 58363 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 48103 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/plan-design-review/:
total 52
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 26803 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 16543 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/plan-eng-review/:
total 52
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 26059 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 16490 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/qa/:
total 52
drwxr-xr-x  4 root root    78 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
drwxr-xr-x  2 root root    31 Mar 18 15:58 references
-rw-r--r--  1 root root 36115 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 10302 Mar 18 15:58 SKILL.md.tmpl
drwxr-xr-x  2 root root    35 Mar 18 15:58 templates

/root/projects/gits/gstack/qa-only/:
total 32
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 21885 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root  3628 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/retro/:
total 56
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 28236 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 21203 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/review/:
total 72
drwxr-xr-x  2 root root   139 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 10034 Mar 18 15:58 checklist.md
-rw-r--r--  1 root root  6603 Mar 18 15:58 design-checklist.md
-rw-r--r--  1 root root  8271 Mar 18 15:58 greptile-triage.md
-rw-r--r--  1 root root 17852 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root  8271 Mar 18 15:58 SKILL.md.tmpl
-rw-r--r--  1 root root  1660 Mar 18 15:58 TODOS-format.md

/root/projects/gits/gstack/scripts/:
total 96
drwxr-xr-x  2 root root   182 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root  2501 Mar 18 15:58 dev-skill.ts
-rw-r--r--  1 root root  3033 Mar 18 15:58 eval-compare.ts
-rw-r--r--  1 root root  3571 Mar 18 15:58 eval-list.ts
-rw-r--r--  1 root root  3186 Mar 18 15:58 eval-select.ts
-rw-r--r--  1 root root  6591 Mar 18 15:58 eval-summary.ts
-rw-r--r--  1 root root  5568 Mar 18 15:58 eval-watch.ts
-rw-r--r--  1 root root 54855 Mar 18 15:58 gen-skill-docs.ts
-rw-r--r--  1 root root  3977 Mar 18 15:58 skill-check.ts

/root/projects/gits/gstack/setup-browser-cookies/:
total 20
drwxr-xr-x  2 root root   43 Mar 18 15:58 .
drwxr-xr-x 22 root root 4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 9699 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 2067 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/ship/:
total 80
drwxr-xr-x  2 root root    43 Mar 18 15:58 .
drwxr-xr-x 22 root root  4096 Mar 18 15:58 ..
-rw-r--r--  1 root root 47354 Mar 18 15:58 SKILL.md
-rw-r--r--  1 root root 28372 Mar 18 15:58 SKILL.md.tmpl

/root/projects/gits/gstack/test/:
total 236
drwxr-xr-x  4 root root   4096 Mar 18 15:58 .
drwxr-xr-x 22 root root   4096 Mar 18 15:58 ..
drwxr-xr-x  2 root root   4096 Mar 18 15:58 fixtures
-rw-r--r--  1 root root  14350 Mar 18 15:58 gen-skill-docs.test.ts
drwxr-xr-x  2 root root   4096 Mar 18 15:58 helpers
-rw-r--r--  1 root root 116100 Mar 18 15:58 skill-e2e.test.ts
-rw-r--r--  1 root root  28582 Mar 18 15:58 skill-llm-eval.test.ts
-rw-r--r--  1 root root   5436 Mar 18 15:58 skill-parser.test.ts
-rw-r--r--  1 root root  39647 Mar 18 15:58 skill-validation.test.ts
-rw-r--r--  1 root root   9678 Mar 18 15:58 touchfiles.test.ts


function generateCommandReference(): string {
function generateSnapshotFlags(): string {
function generatePreamble(): string {
function generateBrowseSetup(): string {
function generateBaseBranchDetect(): string {
function generateQAMethodology(): string {
function generateDesignReviewLite(): string {
function generateDesignMethodology(): string {
function generateReviewDashboard(): string {
function generateTestBootstrap(): string {


     1→---
     2→name: qa-only
     3→version: 1.0.0
     4→description: |
     5→  Report-only QA testing. Systematically tests a web application and produces a
     6→  structured report with health score, screenshots, and repro steps — but never
     7→  fixes anything. Use when asked to "just report bugs", "qa report only", or
     8→  "test but don't fix". For the full test-fix-verify loop, use /qa instead.
     9→allowed-tools:
    10→  - Bash
    11→  - Read
    12→  - Write
    13→  - AskUserQuestion
    14→---
    15→
    16→{{PREAMBLE}}
    17→
    18→# /qa-only: Report-Only QA Testing
    19→
    20→You are a QA engineer. Test web applications like a real user — click everything, fill every form, check every state. Produce a structured report with evidence. **NEVER fix anything.**
    21→
    22→## Setup
    23→
    24→**Parse the user's request for these parameters:**
    25→
    26→| Parameter | Default | Override example |
    27→|-----------|---------|-----------------:|
    28→| Target URL | (auto-detect or required) | `https://myapp.com`, `http://localhost:3000` |
    29→| Mode | full | `--quick`, `--regression .gstack/qa-reports/baseline.json` |
    30→| Output dir | `.gstack/qa-reports/` | `Output to /tmp/qa` |
    31→| Scope | Full app (or diff-scoped) | `Focus on the billing page` |
    32→| Auth | None | `Sign in to user@example.com`, `Import cookies from cookies.json` |
    33→
    34→**If no URL is given and you're on a feature branch:** Automatically enter **diff-aware mode** (see Modes below). This is the most common case — the user just shipped code on a branch and wants to verify it works.
    35→
    36→**Find the browse binary:**
    37→
    38→{{BROWSE_SETUP}}
    39→
    40→**Create output directories:**
    41→
    42→```bash
    43→REPORT_DIR=".gstack/qa-reports"
    44→mkdir -p "$REPORT_DIR/screenshots"
    45→```
    46→
    47→---
    48→
    49→## Test Plan Context
    50→
    51→Before falling back to git diff heuristics, check for richer test plan sources:
    52→
    53→1. **Project-scoped test plans:** Check `~/.gstack/projects/` for recent `*-test-plan-*.md` files for this repo
    54→   ```bash
    55→   eval $(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)
    56→   ls -t ~/.gstack/projects/$SLUG/*-test-plan-*.md 2>/dev/null | head -1
    57→   ```
    58→2. **Conversation context:** Check if a prior `/plan-eng-review` or `/plan-ceo-review` produced test plan output in this conversation
    59→3. **Use whichever source is richer.** Fall back to git diff analysis only if neither is available.
    60→
    61→---
    62→
    63→{{QA_METHODOLOGY}}
    64→
    65→---
    66→
    67→## Output
    68→
    69→Write the report to both local and project-scoped locations:
    70→
    71→**Local:** `.gstack/qa-reports/qa-report-{domain}-{YYYY-MM-DD}.md`
    72→
    73→**Project-scoped:** Write test outcome artifact for cross-session context:
    74→```bash
    75→eval $(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)
    76→mkdir -p ~/.gstack/projects/$SLUG
    77→```
    78→Write to `~/.gstack/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md`
    79→
    80→### Output Structure


     1→---
     2→name: gstack-upgrade
     3→version: 1.1.0
     4→description: |
     5→  Upgrade gstack to the latest version. Detects global vs vendored install,
     6→  runs the upgrade, and shows what's new.
     7→allowed-tools:
     8→  - Bash
     9→  - Read
    10→  - Write
    11→  - AskUserQuestion
    12→---
    13→
    14→# /gstack-upgrade
    15→
    16→Upgrade gstack to the latest version and show what's new.
    17→
    18→## Inline upgrade flow
    19→
    20→This section is referenced by all skill preambles when they detect `UPGRADE_AVAILABLE`.
    21→
    22→### Step 1: Ask the user (or auto-upgrade)
    23→
    24→First, check if auto-upgrade is enabled:
    25→```bash
    26→_AUTO=""
    27→[ "${GSTACK_AUTO_UPGRADE:-}" = "1" ] && _AUTO="true"
    28→[ -z "$_AUTO" ] && _AUTO=$(~/.claude/skills/gstack/bin/gstack-config get auto_upgrade 2>/dev/null || true)
    29→echo "AUTO_UPGRADE=$_AUTO"
    30→```
    31→
    32→**If `AUTO_UPGRADE=true` or `AUTO_UPGRADE=1`:** Skip AskUserQuestion. Log "Auto-upgrading gstack v{old} → v{new}..." and proceed directly to Step 2. If `./setup` fails during auto-upgrade, restore from backup (`.bak` directory) and warn the user: "Auto-upgrade failed — restored previous version. Run `/gstack-upgrade` manually to retry."
    33→
    34→**Otherwise**, use AskUserQuestion:
    35→- Question: "gstack **v{new}** is available (you're on v{old}). Upgrade now?"
    36→- Options: ["Yes, upgrade now", "Always keep me up to date", "Not now", "Never ask again"]
    37→
    38→**If "Yes, upgrade now":** Proceed to Step 2.
    39→
    40→**If "Always keep me up to date":**
    41→```bash
    42→~/.claude/skills/gstack/bin/gstack-config set auto_upgrade true
    43→```
    44→Tell user: "Auto-upgrade enabled. Future updates will install automatically." Then proceed to Step 2.
    45→
    46→**If "Not now":** Write snooze state with escalating backoff (first snooze = 24h, second = 48h, third+ = 1 week), then continue with the current skill. Do not mention the upgrade again.
    47→```bash
    48→_SNOOZE_FILE=~/.gstack/update-snoozed
    49→_REMOTE_VER="{new}"
    50→_CUR_LEVEL=0
    51→if [ -f "$_SNOOZE_FILE" ]; then
    52→  _SNOOZED_VER=$(awk '{print $1}' "$_SNOOZE_FILE")
    53→  if [ "$_SNOOZED_VER" = "$_REMOTE_VER" ]; then
    54→    _CUR_LEVEL=$(awk '{print $2}' "$_SNOOZE_FILE")
    55→    case "$_CUR_LEVEL" in *[!0-9]*) _CUR_LEVEL=0 ;; esac
    56→  fi
    57→fi
    58→_NEW_LEVEL=$((_CUR_LEVEL + 1))
    59→[ "$_NEW_LEVEL" -gt 3 ] && _NEW_LEVEL=3
    60→echo "$_REMOTE_VER $_NEW_LEVEL $(date +%s)" > "$_SNOOZE_FILE"
    61→```
    62→Note: `{new}` is the remote version from the `UPGRADE_AVAILABLE` output — substitute it from the update check result.
    63→
    64→Tell user the snooze duration: "Next reminder in 24h" (or 48h or 1 week, depending on level). Tip: "Set `auto_upgrade: true` in `~/.gstack/config.yaml` for automatic upgrades."
    65→
    66→**If "Never ask again":**
    67→```bash
    68→~/.claude/skills/gstack/bin/gstack-config set update_check false
    69→```
    70→Tell user: "Update checks disabled. Run `~/.claude/skills/gstack/bin/gstack-config set update_check true` to re-enable."
    71→Continue with the current skill.
    72→
    73→### Step 2: Detect install type
    74→
    75→```bash
    76→if [ -d "$HOME/.claude/skills/gstack/.git" ]; then
    77→  INSTALL_TYPE="global-git"
    78→  INSTALL_DIR="$HOME/.claude/skills/gstack"
    79→elif [ -d ".claude/skills/gstack/.git" ]; then
    80→  INSTALL_TYPE="local-git"
    81→  INSTALL_DIR=".claude/skills/gstack"
    82→elif [ -d ".claude/skills/gstack" ]; then
    83→  INSTALL_TYPE="vendored"
    84→  INSTALL_DIR=".claude/skills/gstack"
    85→elif [ -d "$HOME/.claude/skills/gstack" ]; then
    86→  INSTALL_TYPE="vendored-global"
    87→  INSTALL_DIR="$HOME/.claude/skills/gstack"
    88→else
    89→  echo "ERROR: gstack not found"
    90→  exit 1
    91→fi
    92→echo "Install type: $INSTALL_TYPE at $INSTALL_DIR"
    93→```
    94→
    95→The install type and directory path printed above will be used in all subsequent steps.
    96→
    97→### Step 3: Save old version
    98→
    99→Use the install directory from Step 2's output below:
   100→


bash "${CLAUDE_PLUGIN_ROOT}/scripts/hooks/run-with-flags-shell.sh" "post:observe" "skills/continuous-learning-v2/hooks/observe.sh" "standard,strict"


Perfect! Now I have a comprehensive understanding of the gstack project. Let me prepare a detailed summary report.

## AI/Eval System and Testing Infrastructure - Comprehensive Exploration Report

### Project Overview

gstack is a sophisticated AI-assisted CLI development framework that blends headless browser automation with AI-powered code generation, testing, and skill validation. The system is designed around **skills** (autonomous workflows for AI agents) and a **multi-tier testing/eval infrastructure**.

---

## 1. AI EVALUATION PIPELINE

### Architecture (3-Tier Testing)

```
Tier 1 (Free, ~<1s):
  └─ skill-validation.test.ts — Static validation (no AI)
     • $B command syntax checking
     • Snapshot flag validation
     • SKILL.md freshness checks

Tier 2 (E2E, ~$3.85/run):
  └─ skill-e2e.test.ts — Full agent workflows via claude -p
     • Spawns independent `claude` subprocess
     • Streams NDJSON output real-time
     • Detects browse errors + exit codes
     • Planted-bug detection scoring

Tier 3 (LLM-Judge, ~$0.15/run):
  └─ skill-llm-eval.test.ts — Quality scoring via Anthropic API
     • claude-sonnet-4-6 evaluates doc clarity/completeness/actionability
     • Judges command reference, snapshot flags, setup instructions
```

### Key Files

| File | Purpose |
|------|---------|
| `/test/helpers/session-runner.ts` | Spawns `claude -p` subprocess, streams NDJSON, parses results |
| `/test/helpers/llm-judge.ts` | `callJudge<T>()`, `judge()`, `outcomeJudge()` for LLM-as-judge evaluation |
| `/test/helpers/eval-store.ts` | `EvalCollector` — accumulates results, writes to `~/.gstack-dev/evals/`, auto-compares vs previous run |
| `/test/helpers/touchfiles.ts` | Diff-based test selection (glob matching, git diff scanning) |

---

## 2. SESSION RUNNER (E2E ORCHESTRATION)

### `session-runner.ts` - Key Mechanisms

**Subprocess Architecture:**
- Spawns `claude -p --output-format stream-json --verbose --dangerously-skip-permissions --max-turns N`
- Prompt piped via stdin to avoid shell escaping
- Captures stdout as streaming NDJSON, stderr for errors
- Monitors process via `Bun.spawn()` with timeout racing

**Real-Time Progress Tracking:**
- Parses NDJSON events on-the-fly (no buffering)
- Emits progress to stderr: `[elapsed_s] turn N tool #M: ToolName(args...)`
- Writes heartbeat to `~/.gstack-dev/e2e-live.json` (atomic writes)
- Persists progress.log per run

**Result Parsing (`parseNDJSON`):**
```typescript
interface ParsedNDJSON {
  transcript: any[];          // Full event stream
  resultLine: any | null;     // Final result event
  turnCount: number;          // Assistant turns
  toolCallCount: number;
  toolCalls: Array<{ tool, input, output }>;
}
```

**Cost Tracking:**
- Extracts from `resultLine.total_cost_usd`, `usage.{input,output}_tokens`, `num_turns`
- Fallback: estimates from prompt/result char lengths
- Returns `CostEstimate` with USD cost, token usage, turn count

**Error Detection:**
- Scans transcript + stderr against `BROWSE_ERROR_PATTERNS`
- Captures: unknown commands, unknown flags, binary missing, server failure

**Failure Persistence:**
- Saves transcripts to `.gstack/test-transcripts/` or `~/.gstack-dev/e2e-runs/{runId}/`
- Includes: prompt (truncated), exit reason, browse errors, last tool call, stderr snippet

---

## 3. LLM-AS-JUDGE EVALUATION

### `llm-judge.ts` - Quality Assessment

**Judge Architecture:**
```typescript
async function callJudge<T>(prompt: string): Promise<T>
  → client.messages.create({ model: 'claude-sonnet-4-6', max_tokens: 1024 })
  → extract JSON from response
  → retry once on 429 rate limit
```

**Scoring Model (1-5 scale):**
```typescript
interface JudgeScore {
  clarity: number;         // Can agent understand what each command does?
  completeness: number;    // Are all args, values, behaviors documented?
  actionability: number;   // Can agent construct correct invocations?
  reasoning: string;       // Brief explanation
}
```

**Planted-Bug Detection (`outcomeJudge`):**
```typescript
interface OutcomeJudgeResult {
  detected: string[];      // Bug IDs found in report
  missed: string[];        // Bug IDs not found
  false_positives: number; // Issues not matching any planted bug
  detection_rate: number;  // Count of detected bugs
  evidence_quality: 1-5;   // Quality of evidence (screenshots, repro steps)
  reasoning: string;
}
```

---

## 4. EVAL RESULT STORAGE & COMPARISON

### `eval-store.ts` - Persistence & Analytics

**Storage Schema:**
```typescript
interface EvalResult {
  schema_version: number;
  version: string;
  branch: string;
  git_sha: string;
  timestamp: string;
  hostname: string;
  tier: 'e2e' | 'llm-judge';
  total_tests: number;
  passed: number;
  failed: number;
  total_cost_usd: number;
  total_duration_ms: number;
  tests: EvalTestEntry[];
}

interface EvalTestEntry {
  name: string;
  suite: string;
  tier: 'e2e' | 'llm-judge';
  passed: boolean;
  duration_ms: number;
  cost_usd: number;
  // E2E fields
  transcript?: any[];
  output?: string;
  turns_used?: number;
  browse_errors?: string[];
  exit_reason?: string;
  timeout_at_turn?: number;
  last_tool_call?: string;
  // LLM-judge fields
  judge_scores?: Record<string, number>;
  judge_reasoning?: string;
  // Outcome eval (planted bugs)
  detection_rate?: number;
  false_positives?: number;
  evidence_quality?: number;
  detected_bugs?: string[];
  missed_bugs?: string[];
}
```

**File Location:**
- `~/.gstack-dev/evals/{version}-{branch}-{tier}-{timestamp}.json`
- Auto-incremental saves to `_partial-e2e.json` (non-fatal if fails)

**Comparison Algorithm:**
```typescript
compareEvalResults(before: EvalResult, after: EvalResult)
  → Match tests by name
  → Track: improved/regressed/unchanged
  → Extract tool summaries from transcripts
  → Calculate deltas: cost, duration, turns, detection_rate
  → Generate commentary (with thresholds: ≥20% delta triggers report)
```

**Pass/Fail Logic (Planted Bugs):**
```typescript
function judgePassed(judgeResult, groundTruth): boolean {
  return detection_rate >= groundTruth.minimum_detection
      && false_positives <= groundTruth.max_false_positives
      && evidence_quality >= 2;
}
```

---

## 5. SKILL VALIDATION SYSTEM

### `skill-parser.ts` - Static Analysis

**Extraction:**
- Parses SKILL.md for bash code blocks
- Extracts `$B command arg1 arg2 # comment` invocations
- Handles quoted strings, inline comments, multiple commands per line

**Validation:**
```typescript
function validateSkill(skillPath): ValidationResult {
  • Check all $B commands exist in ALL_COMMANDS registry
  • For `snapshot` commands, parse & validate flags
  • Collect: valid, invalid, snapshotFlagErrors, warnings
}

function extractRemoteSlugPatterns(rootDir, subdirs): Map<filename, patterns[]>
  → Finds REMOTE_SLUG=$(...) assignments (checks consistency across files)

function extractWeightsFromTable(content): Map<category, percentage>
  → Parses ### Weights section for validation
```

**Test Coverage (Tier 1):**
- All SKILL.md files: `validateSkill()` for command syntax + flags
- Templates: cross-check `.tmpl` vs generated `.md` files
- Freshness: `gen-skill-docs --dry-run` detects stale files
- Consistency: COMMAND_DESCRIPTIONS, SNAPSHOT_FLAGS coverage
- Usage format: structural skeleton matching (implementation vs docs)

---

## 6. DIFF-BASED TEST SELECTION

### `touchfiles.ts` - Intelligent Test Filtering

**Concept:**
Each test declares **dependencies** (glob patterns of files it cares about). Only tests whose touchfiles were modified run, reducing CI cost.

**Registry:**
```typescript
const E2E_TOUCHFILES = {
  'browse-basic': ['browse/src/**'],
  'qa-quick': ['qa/**', 'browse/src/**'],
  'review-sql-injection': ['review/**', 'test/fixtures/review-eval-vuln.rb'],
  // ...
}

const LLM_JUDGE_TOUCHFILES = {
  'command reference table': ['SKILL.md', 'SKILL.md.tmpl', 'browse/src/commands.ts'],
  'snapshot flags reference': ['SKILL.md', 'SKILL.md.tmpl', 'browse/src/snapshot.ts'],
  // ...
}

const GLOBAL_TOUCHFILES = [
  'test/helpers/session-runner.ts',
  'test/helpers/eval-store.ts',
  'test/helpers/llm-judge.ts',
  'scripts/gen-skill-docs.ts',
  'browse/test/test-server.ts',
]
```

**Selection Algorithm:**
1. Detect base branch: try `origin/main` → `origin/master` → `main` → `master`
2. Get changed files: `git diff --name-only <base>...HEAD`
3. If any file matches GLOBAL_TOUCHFILES → **run all tests**
4. Otherwise, for each test, check if any changed file matches its patterns
5. Return `{ selected: [...], skipped: [...], reason: 'diff' | 'global' }`

**Usage:**
- `bun run test:evals` → diff-based (only changed tests)
- `bun run test:evals:all` → force all tests (override with `EVALS_ALL=1`)
- `bun run eval:select` → preview which tests would run

---

## 7. TEMPLATE GENERATION SYSTEM

### `scripts/gen-skill-docs.ts` - Dynamic Doc Building

**Pipeline:**
```
.tmpl file → find {{PLACEHOLDERS}} → resolve from source → format → .md file
```

**Key Resolvers:**

| Placeholder | Source | Output |
|-------------|--------|--------|
| `{{COMMAND_REFERENCE}}` | `COMMAND_DESCRIPTIONS` | Markdown table, grouped by category |
| `{{SNAPSHOT_FLAGS}}` | `SNAPSHOT_FLAGS` metadata | Formatted flag list with -i, -c, -d, etc. |
| `{{PREAMBLE}}` | Hard-coded | Update check, session tracking, completeness intro, contributor mode |
| `{{BROWSE_SETUP}}` | Hard-coded | Binary discovery & setup checks |
| `{{BASE_BRANCH_DETECT}}` | Hard-coded | Step 0 for PR-targeting skills |
| `{{QA_METHODOLOGY}}` | Hard-coded | Modes: Diff-aware, Full, Quick, Regression |

**Validation:**
- Dry-run mode: `--dry-run` flag generates to memory, exits 1 if different from committed
- No unresolved `{{placeholders}}` should remain
- All generated files must have `AUTO-GENERATED` header

**Update Check Preamble:**
Ensures SKILL.md files call `/gstack-upgrade` on startup:
```bash
_UPD=$(~/.claude/skills/gstack/bin/gstack-update-check 2>/dev/null || true)
[ -n "$_UPD" ] && echo "$_UPD" || true
```

---

## 8. HEALTH DASHBOARD

### `scripts/skill-check.ts` - Status Overview

**Reports:**
1. **Skills:** Validates each SKILL.md file
   - Shows: valid/invalid command count, snapshot errors
   - Symbols: ✅ (all good), ❌ (errors), ⚠ (warnings)

2. **Templates:** Checks .tmpl → .md pairs
   - Ensures generated files exist and are fresh
   - Prompts to run `bun run gen:skill-docs` if stale

3. **Freshness:** Runs `gen-skill-docs --dry-run`
   - Detects drift between templates and committed files

**Exit Code:**
- 0 if all checks pass
- 1 if any errors found

---

## 9. BROWSER AUTOMATION SYSTEM

### `browse/src/` - Architecture

**Command Registry (Single Source of Truth):**
```typescript
// commands.ts
export const READ_COMMANDS = new Set([
  'text', 'html', 'links', 'forms', 'accessibility',
  'js', 'eval', 'css', 'attrs', 'console', 'network', 'cookies', ...
]);

export const WRITE_COMMANDS = new Set([
  'goto', 'back', 'forward', 'reload',
  'click', 'fill', 'select', 'hover', 'type', 'press', 'scroll', 'wait',
  'viewport', 'cookie', 'cookie-import', 'header', 'useragent', 'upload', ...
]);

export const META_COMMANDS = new Set([
  'tabs', 'tab', 'newtab', 'closetab',
  'status', 'stop', 'restart',
  'screenshot', 'pdf', 'responsive',
  'chain', 'diff', 'url', 'snapshot'
]);

export const COMMAND_DESCRIPTIONS = { ... }  // ← used by gen-skill-docs, skill-parser, server
```

**Server Architecture (`server.ts`):**
- **HTTP+Auth:** Bun.serve on random port 10000-60000 (or explicit BROWSE_PORT)
- **Token:** Bearer token authentication (random UUID)
- **Routing:** Dispatch command → `handleReadCommand()`, `handleWriteCommand()`, `handleMetaCommand()`
- **Buffers:** CircularBuffer in-memory + async disk flush (1s interval)
  - Console log: `~/.gstack/browse-console.log`
  - Network log: `~/.gstack/browse-network.log`
  - Dialog log: `~/.gstack/browse-dialog.log`
- **Idle Shutdown:** Default 30 min (`BROWSE_IDLE_TIMEOUT` env)
- **Crash Handling:** Chromium disconnect → log + `process.exit(1)` (CLI auto-restarts)

**BrowserManager (`browser-manager.ts`):**
```typescript
class BrowserManager {
  // Tab management
  async newTab(url?): Promise<number>
  async closeTab(id?): void
  switchTab(id: number): void

  // Ref map (snapshot → @e1, @e2, @c1, @c2)
  setRefMap(refs: Map<string, RefEntry>)
  clearRefs()
  async resolveRef(selector: "@e3" | "body > div"): { locator | selector }

  // Dialog handling
  setDialogAutoAccept(yes: boolean)
  setDialogPromptText(text: string)

  // Health check
  async isHealthy(): boolean  // Verifies Chromium connected + responsive
}
```

**Snapshot System (`snapshot.ts`):**

*Architecture:* **Locator map** (no DOM mutation)
```
1. page.locator(scope).ariaSnapshot() → YAML accessibility tree
2. Parse tree, assign refs @e1, @e2, ... (tree order)
3. Build Playwright Locator for each ref (getByRole + nth)
4. Store Map<"e3", Locator> on BrowserManager
5. Return compact text output
```

*Flags (Source of Truth):*
```typescript
export const SNAPSHOT_FLAGS = [
  { short: '-i', long: '--interactive', optionKey: 'interactive' },        // Buttons, links, inputs only
  { short: '-c', long: '--compact', optionKey: 'compact' },                // No empty structural nodes
  { short: '-d', long: '--depth', takesValue: true, optionKey: 'depth' },  // Limit tree depth
  { short: '-s', long: '--selector', takesValue: true, optionKey: 'selector' },
  { short: '-D', long: '--diff', optionKey: 'diff' },                      // Unified diff vs last
  { short: '-a', long: '--annotate', optionKey: 'annotate' },              // Overlay screenshot
  { short: '-o', long: '--output', takesValue: true, optionKey: 'outputPath' },
  { short: '-C', long: '--cursor-interactive', optionKey: 'cursorInteractive' },
];

export function parseSnapshotArgs(args: string[]): SnapshotOptions { ... }
```

*Output Format:*
```
  @e1 [heading] "Welcome" [level=1]
  @e2 [textbox] "Email"
  @e3 [button] "Submit"
```

*Later:* `click @e3` → look up `refMap.get("e3")` → locator.click()

---

## 10. KEY PATTERNS & PRINCIPLES

### Testing Philosophy

**Completeness Principle — Boil the Lake:**
- With AI assistance, marginal cost of completeness ≈ zero
- Always recommend complete implementation over shortcuts
- When effort scales: human 2 weeks / CC 1 hour → compression ~10x
- Never defer edge cases, error handling, or test coverage to "follow-up PR"

**E2E Eval Failure Blame Protocol:**
> Never claim "pre-existing" without proof. These systems have invisible couplings — preamble text affects agent behavior, SKILL.md regeneration shifts prompt context, timing changes can break flakey tests.
>
> **Required before attributing failure to pre-existing:**
> 1. Run same eval on main branch
> 2. Show it fails there too
> 3. If it passes on main but fails on branch → **it IS your change**

### Commit Style (Bisect Commits)

Every commit = single logical change. Examples:
- Rename/move separate from behavior changes
- Test infrastructure (touchfiles, helpers) separate from test implementations
- Template changes separate from generated file regeneration
- Mechanical refactors separate from new features

### Shared Infrastructure

**Symlinked Vendoring:**
`~/.claude/skills/gstack` may be a symlink to working directory (gitignored `.claude/skills/gstack`).
- Skill changes are **live immediately**
- Breaking changes to SKILL.md.tmpl can break concurrent gstack sessions
- During refactors, remove symlink to use global install instead

---

## 11. FILE MAPPING

| Path | Purpose | Role in Eval Pipeline |
|------|---------|----------------------|
| `/test/helpers/session-runner.ts` | E2E subprocess orchestration | Core: spawns `claude -p`, parses NDJSON, tracks cost |
| `/test/helpers/llm-judge.ts` | LLM quality scoring | Core: Anthropic API calls for clarity/completeness/actionability |
| `/test/helpers/eval-store.ts` | Result persistence & comparison | Core: accumulates, writes to ~/.gstack-dev/evals/, auto-compares |
| `/test/helpers/touchfiles.ts` | Diff-based test selection | Core: glob matching, git diff scanning, test filtering |
| `/test/helpers/skill-parser.ts` | SKILL.md static validation | Supports: command/flag extraction, freshness checks |
| `/test/skill-validation.test.ts` | Tier 1: Static validation | Runs: command syntax, flag validation, template freshness |
| `/test/skill-llm-eval.test.ts` | Tier 3: LLM-as-judge | Runs: doc quality scoring, regression vs baselines |
| `/test/skill-e2e.test.ts` | Tier 2: Full E2E workflows | Runs: planted-bug QA, skill demonstrations |
| `/scripts/gen-skill-docs.ts` | Dynamic SKILL.md generation | Generates: command tables, snapshot flags, preamble |
| `/scripts/skill-check.ts` | Health dashboard | Reports: validation status, template freshness |
| `/browse/src/commands.ts` | Command registry (single source of truth) | Used by: server dispatch, doc generation, skill parser |
| `/browse/src/snapshot.ts` | Snapshot system (accessibility tree + @refs) | Used by: all agents needing page inspection |
| `/browse/src/server.ts` | HTTP server + command dispatch | Routes: all $B commands → read/write/meta handlers |
| `/browse/src/browser-manager.ts` | Chromium lifecycle + state management | Core: tab management, ref map, dialog handling |

---

## Summary

gstack implements a **three-tier AI evaluation pipeline**:
- **Tier 1 (Static):** Validation of SKILL.md command syntax, flags, templates
- **Tier 2 (E2E):** Full autonomous agent workflows via subprocess, with cost & error tracking
- **Tier 3 (LLM-Judge):** Anthropic API quality assessment of documentation

The system uses **diff-based test selection** to minimize CI cost, **shared infrastructure** (single command registry) for consistency, and **persistent eval storage** with auto-comparison to previous runs. The **browser automation** layer provides Playwright-backed Chromium control with accessibility tree snapshots and ref-based element selection (@e1, @e2, etc.).

All validation is testable without AI (Tier 1), and evals are hermetic and reproducible (Tier 2 & 3).

agentId: a7df8a3e4efe9e547 (use SendMessage with to: 'a7df8a3e4efe9e547' to continue this agent)
<usage>total_tokens: 88659
tool_uses: 18
duration_ms: 259868</usage>

Prompt:
Explore the gstack project at /root/projects/gits/gstack focusing on the AI/eval system and testing infrastructure:

1. Read test/helpers/ - especially session-runner.ts, llm-judge.ts, eval-store.ts, skill-parser.ts, touchfiles.ts
2. Read test/skill-e2e.test.ts and test/skill-llm-eval.test.ts to understand how AI evals work
3. Read test/skill-validation.test.ts to understand skill validation
4. Read scripts/gen-skill-docs.ts to understand the template system
5. Read scripts/skill-check.ts for the health dashboard
6. Look at the browse/src/ directory more carefully - how does the browser automation work? Read server.ts, snapshot.ts, commands.ts fully

I need to understand the AI-powered evaluation pipeline, how skills are validated, and how the browser tool works with AI agents.


Perfect! Now I have a comprehensive understanding of the gstack skill system. Let me compile my findings into a complete report.

## Summary: gstack Skill System Architecture

I've thoroughly explored the gstack project's skill template system. Here's the complete picture of how all 15 skills compose together:

### **Core Architecture**

The skill system is built on **template-based generation** using TypeScript. Every skill has:
- A `.tmpl` template file (Markdown with placeholder variables)
- A generated `.md` file (regenerated via `bun run gen:skill-docs`)
- A YAML frontmatter declaring metadata, allowed tools, and description

Template variables (placeholders like `{{PREAMBLE}}`) are resolved by `/root/projects/gits/gstack/scripts/gen-skill-docs.ts`, which defines 10 key generator functions:

1. `generatePreamble()` — shared initialization + upgrade flow + Completeness Principle
2. `generateBrowseSetup()` — locate the browse binary
3. `generateBaseBranchDetect()` — detect main/master branch
4. `generateQAMethodology()` — QA testing phases 1-6 (shared by /qa and /qa-only)
5. `generateDesignMethodology()` — design audit phases 1-6 (shared by /design-review)
6. `generateDesignReviewLite()` — lightweight design audit (embedded in /ship and /review)
7. `generateReviewDashboard()` — status dashboard (used by /ship, /plan-eng-review, /plan-design-review)
8. `generateCommandReference()` — all browse commands + categories (from browse/src/commands.ts)
9. `generateSnapshotFlags()` — all snapshot flags (from browse/src/snapshot.ts)
10. `generateTestBootstrap()` — test framework detection (used by /qa, /design-review)

---

### **15 Skills Across 4 Workflow Tiers**

#### **Tier 1: Foundation Tools (Supporting Skills)**
These are utilities every workflow depends on:

**1. `/browse` (version 1.1.0)** — Headless QA browser
- Location: `browse/SKILL.md.tmpl`
- Auto-starts Chromium, ~100ms per command
- Powers all QA testing, screenshots, interactions
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`, `{{SNAPSHOT_FLAGS}}`, `{{COMMAND_REFERENCE}}`

**2. `/gstack` (version 1.1.0)** — Main entry point (project root skill)
- Location: `SKILL.md.tmpl`
- Same as browse but named "gstack" for project context
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`, `{{SNAPSHOT_FLAGS}}`, `{{COMMAND_REFERENCE}}`

**3. `/setup-browser-cookies` (version 1.0.0)** — Import browser sessions
- Location: `setup-browser-cookies/SKILL.md.tmpl`
- Imports cookies from Chrome, Arc, Brave, Edge, Comet
- Interactive picker UI in browser
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`

**4. `/gstack-upgrade` (version 1.1.0)** — Version management
- Location: `gstack-upgrade/SKILL.md.tmpl`
- Detects global vs local/vendored install
- Auto-upgrade or snooze flow (escalating backoff)
- Referenced inline by preamble when upgrade is available

---

#### **Tier 2: Pre-Ship Planning (Plan Review Skills)**
Review plans BEFORE implementation. Interactive, opinionated, work in plan mode:

**5. `/plan-eng-review` (version 1.0.0)** — Engineering manager review
- Location: `plan-eng-review/SKILL.md.tmpl`
- Walks through: Scope Challenge (Step 0) → Architecture → Code Quality → Tests → Performance
- Produces: "NOT in scope" section, "What already exists" section, test diagram, TODOS proposals
- One AskUserQuestion per issue (never batch)
- Outputs test plan artifact to `~/.gstack/projects/{slug}/{user}-{branch}-test-plan-{datetime}.md`
- Writes review log to `~/.gstack/projects/{slug}/$BRANCH-reviews.jsonl`
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`, `{{REVIEW_DASHBOARD}}`

**6. `/plan-design-review` (version 2.0.0)** — Designer's eye plan review
- Location: `plan-design-review/SKILL.md.tmpl`
- Seven-pass design review: Info Architecture → Interaction States → User Journey → AI Slop Risk → Design System Alignment → Responsive/A11y → Unresolved Decisions
- Rates each dimension 0-10, fixes to get to 10
- Produces: completion summary, design score before/after, deferred decisions
- Writes review log to `~/.gstack/projects/{slug}/$BRANCH-reviews.jsonl`
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`, `{{REVIEW_DASHBOARD}}`

**7. `/plan-ceo-review` (version 1.0.0)** — CEO/founder-mode plan review
- Location: `plan-ceo-review/SKILL.md.tmpl` (50KB template file)
- Four modes: SCOPE EXPANSION, SELECTIVE EXPANSION, HOLD SCOPE, SCOPE REDUCTION
- Rethinks the problem, finds the 10-star product, challenges premises
- Expands scope when it creates a better product
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`

**8. `/design-consultation` (version 1.0.0)** — Complete design system builder
- Location: `design-consultation/SKILL.md.tmpl` (18KB template)
- Phase 0 (pre-checks) → Phase 1 (context) → Phase 2 (research via WebSearch) → Phase 3 (complete proposal) → Phase 4 (drill-downs) → Phase 5 (beautiful preview page) → Phase 6 (write DESIGN.md)
- Generates HTML preview with fonts, colors, mockups, light/dark mode toggle
- Creates DESIGN.md as the design source of truth
- Updates CLAUDE.md with design system reference
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`

---

#### **Tier 3: Implementation QA (Test & Fix Skills)**
Test applications and fix bugs found:

**9. `/qa` (version 2.0.0)** — Test, find bugs, fix bugs
- Location: `qa/SKILL.md.tmpl` (85KB template)
- Phases 1-6: QA baseline testing (same as qa-only)
- Phase 7-11: Triage → Fix Loop → Final QA → Report → TODOS.md Update
- Three tiers: Quick (critical+high) → Standard (+ medium) → Exhaustive (+ cosmetic)
- Phase 8e.5: Generates regression tests (mocks external deps, traces bug codepath first)
- Self-regulation heuristic (WTF-likelihood) after 5 fixes, hard cap at 50 fixes
- Requires clean working tree
- Outputs: `qa-report-{domain}-{YYYY-MM-DD}.md`, before/after screenshots, project-scoped test outcome
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`, `{{BROWSE_SETUP}}`, `{{TEST_BOOTSTRAP}}`, `{{QA_METHODOLOGY}}`

**10. `/qa-only` (version 1.0.0)** — Report-only QA testing
- Location: `qa-only/SKILL.md.tmpl` (70KB template)
- Phases 1-6: Systematically test, produce report with evidence
- **NEVER fixes bugs** — report only
- Diff-aware mode: auto-detects feature branches and tests changed code
- Checks for rich test plan sources before falling back to git diff heuristics
- Outputs: `qa-report-{domain}-{YYYY-MM-DD}.md`, project-scoped test outcome
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`, `{{TEST_BOOTSTRAP}}`, `{{QA_METHODOLOGY}}`

---

#### **Tier 4: Ship & Post-Ship (Delivery Skills)**
Merge and ship code, then update documentation:

**11. `/review` (version 1.0.0)** — Pre-landing PR review
- Location: `review/SKILL.md.tmpl` (55KB template)
- Standalone pre-landing review (also called from `/ship` as Step 3.5)
- Two-pass review: CRITICAL (SQL & Data Safety, Race Conditions, LLM Trust, Enums) → INFORMATIONAL (Conditional Side Effects, Dead Code, Prompts, Tests, View/Frontend)
- Reads `.claude/skills/review/checklist.md` (required)
- Step 2.5: Greptile review comment classification with escalation detection
- Step 4.5: Design Review (lite) — calls `{{DESIGN_REVIEW_LITE}}`
- Step 5: Fix-First workflow (auto-fix mechanical issues, ask about structural)
- Step 5.5: TODOS cross-reference (does PR close open TODOs?)
- Step 5.6: Documentation staleness check
- Greptile reply templates from `.claude/skills/review/greptile-triage.md`
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`, `{{DESIGN_REVIEW_LITE}}`

**12. `/ship` (version 1.0.0)** — Fully automated ship workflow
- Location: `ship/SKILL.md.tmpl` (165KB template — largest skill)
- **Non-interactive, fully automated** (user says `/ship`, next thing they see is PR URL)
- Steps:
  - Step 1: Pre-flight (branch check, uncommitted changes, review dashboard)
  - Step 2: Merge base branch (auto-resolve simple conflicts)
  - Step 2.5: Test framework bootstrap
  - Step 3: Run tests (Rails + Vitest in parallel)
  - Step 3.25: Eval suites (if prompt files changed)
  - Step 3.4: Test coverage audit (ASCII diagram of code paths + user flows, gap detection, test generation)
  - Step 3.5: Pre-landing review (calls `/review` workflow)
  - Step 3.75: Greptile review comments (classified, replied-to)
  - Step 4: Version bump (auto-decide MICRO/PATCH, ask for MINOR/MAJOR)
  - Step 5: CHANGELOG auto-generate (from all commits on branch)
  - Step 5.5: TODOS.md auto-update (marks completed items)
  - Step 6: Commit (bisectable chunks, logical ordering, version+changelog always last)
  - Step 7: Push (with `-u`)
  - Step 8: Create PR (with comprehensive body: Summary, Test Coverage, Pre-Landing Review, Design Review, Eval Results, Greptile, TODOS, Test Plan)
- Only stops for: merge conflicts, test failures, pre-landing ASK items, MINOR/MAJOR bumps
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`, `{{REVIEW_DASHBOARD}}`, `{{TEST_BOOTSTRAP}}`, `{{DESIGN_REVIEW_LITE}}`

**13. `/document-release` (version 1.0.0)** — Post-ship doc update
- Location: `document-release/SKILL.md.tmpl` (70KB template)
- Runs AFTER `/ship` (code committed, PR exists) but BEFORE merge
- Steps:
  - Step 1: Pre-flight + diff analysis
  - Step 2: Per-file audit (README, ARCHITECTURE, CONTRIBUTING, CLAUDE.md)
  - Step 3: Apply auto-updates (Edit tool, never Write on CHANGELOG)
  - Step 4: Ask about risky/questionable changes
  - Step 5: CHANGELOG voice polish (preserve content, polish wording only)
  - Step 6: Cross-doc consistency check + discoverability
  - Step 7: TODOS.md cleanup (mark completed items, capture deferred work)
  - Step 8: VERSION bump (never silent — always ask)
  - Step 9: Commit docs + update PR body
- Outputs: structured doc health summary table
- Uses: `{{PREAMBLE}}`, `{{BASE_BRANCH_DETECT}}`

**14. `/design-review` (version 2.0.0)** — Live site design audit + fix
- Location: `design-review/SKILL.md.tmpl` (100KB template)
- Like `/qa` but for visual/UX issues
- Phases 1-6: Design audit baseline (like QA methodology)
- Phase 7: Triage (High Impact → Medium Impact → Polish)
- Phase 8: Fix loop (locate source → fix → commit → re-test → classify)
- Phase 8e.5: Regression tests (CSS-only skipped, JS behavior tested)
- Phase 8f: Self-regulation (design-fix risk heuristic, hard cap 30 fixes)
- Phase 9-11: Final audit, report, TODOS.md update
- Requires clean working tree
- Outputs: `design-audit-{domain}-{YYYY-MM-DD}.md`, before/after screenshot pairs
- Uses: `{{PREAMBLE}}`, `{{BROWSE_SETUP}}`, `{{TEST_BOOTSTRAP}}`, `{{DESIGN_METHODOLOGY}}`

**15. `/retro` (version 2.0.0)** — Weekly engineering retrospective
- Location: `retro/SKILL.md.tmpl` (80KB template)
- Analyzes commit history, work patterns, code quality metrics
- Arguments: `/retro`, `/retro 24h`, `/retro 14d`, `/retro compare`
- Steps 1-14:
  - Raw data gathering (12 parallel git commands in one bash block)
  - Metrics computation (per-author leaderboard, test health, backlog health, Greptile signal)
  - Commit time distribution (hourly histogram in Pacific time)
  - Work session detection (45-min gap threshold, classify deep/medium/micro)
  - Commit type breakdown (feat/fix/refactor/test/chore/docs percentages)
  - Hotspot analysis (most-changed files)
  - PR size distribution
  - Focus score + Ship of the Week
  - Team member analysis (per-person praise + growth area)
  - Week-over-week trends (if window >= 14d)
  - Streak tracking (consecutive days with commits, team + personal)
  - Load history & compare (vs prior retro)
  - Save JSON snapshot to `.context/retros/{date}-{seq}.json`
  - Write narrative (tweetable summary, tables, prose)
- Outputs: Console narrative (3000-4500 words), JSON snapshot
- Uses: `{{PREAMBLE}}`

---

### **Shared Template Variables (Generated Functions)**

Each template variable is resolved to dynamically generated markdown:

| Variable | Generator | Used By | Contents |
|----------|-----------|---------|----------|
| `{{PREAMBLE}}` | generatePreamble() | All 15 skills | Update check, branch detection, gstack-upgrade inline flow, Completeness Principle intro, Contributor mode, AskUserQuestion format |
| `{{BROWSE_SETUP}}` | generateBrowseSetup() | /browse, /gstack, /setup-browser-cookies, /qa, /qa-only, /design-review, /design-consultation | Shell code to locate `$B` binary, auto-start server, setup paths |
| `{{BASE_BRANCH_DETECT}}` | generateBaseBranchDetect() | /ship, /review, /plan-eng-review, /plan-design-review, /plan-ceo-review, /qa, /document-release | Detects main/master dynamically, `git diff <base>...HEAD`, `git log <base>..HEAD` |
| `{{SNAPSHOT_FLAGS}}` | generateSnapshotFlags() | /browse, /gstack | All snapshot command flags (-i, -a, -o, -D, -C, etc.) as markdown table |
| `{{COMMAND_REFERENCE}}` | generateCommandReference() | /browse, /gstack | All ~50 browse commands grouped by category (Navigation, Reading, Interaction, etc.) |
| `{{QA_METHODOLOGY}}` | generateQAMethodology() | /qa, /qa-only | Phases 1-6 testing workflow (scope detection, diff analysis, page visits, interaction testing, screenshot evidence, health score) |
| `{{DESIGN_METHODOLOGY}}` | generateDesignMethodology() | /design-review | Phases 1-6 design audit (visual inspection, hierarchy, spacing, contrast, slop detection, accessibility, components, animation) |
| `{{DESIGN_REVIEW_LITE}}` | generateDesignReviewLite() | /ship (Step 3.5), /review (Step 4.5) | Lightweight design audit (single pass, not full /design-review, embedded in code review) |
| `{{REVIEW_DASHBOARD}}` | generateReviewDashboard() | /ship (Step 1), /plan-eng-review (footer), /plan-design-review (footer) | Status display reading `~/.gstack/projects/{slug}/$BRANCH-reviews.jsonl` (Eng Review, CEO Review, Design Review status) |
| `{{TEST_BOOTSTRAP}}` | generateTestBootstrap() | /ship (Step 2.5), /qa, /design-review | Detects test framework (npm test, pytest, rspec, bin/test-lane) and offers to bootstrap if missing |

---

### **Key Composition Patterns**

1. **Preamble in every skill** — All 15 skills start with `{{PREAMBLE}}`, which gives them:
   - Upgrade detection + inline upgrade flow
   - Completeness Principle intro (once per gstack session)
   - Contributor mode (field reports)
   - Shared AskUserQuestion format

2. **Browser tools as foundation** — `/browse` and `/gstack` provide the QA infrastructure. All QA skills (`/qa`, `/qa-only`, `/design-review`, `/design-consultation`) depend on the browse binary location.

3. **Review workflow composition** — `/review` is standalone AND called from `/ship` Step 3.5. Both use the same checklist.md + greptile-triage.md + design-review-lite.

4. **Methodology sharing** — QA phases 1-6 and Design phases 1-6 are shared across multiple skills:
   - `/qa` and `/qa-only` both use `{{QA_METHODOLOGY}}`
   - `/design-review` uses `{{DESIGN_METHODOLOGY}}`
   - `/ship` and `/review` both embed `{{DESIGN_REVIEW_LITE}}`

5. **Status persistence** — Plan review skills (`/plan-eng-review`, `/plan-design-review`) write to `~/.gstack/projects/{slug}/$BRANCH-reviews.jsonl`. This is read by:
   - `/ship` Step 1 (review dashboard)
   - `/plan-design-review` and `/plan-eng-review` footers (to show prior reviews)

6. **Test plan artifact** — `/plan-eng-review` writes a test plan to `~/.gstack/projects/{slug}/{user}-{branch}-test-plan-{datetime}.md` which is consumed by `/qa` and `/qa-only` to replace lossy git diff heuristics.

7. **Skill hierarchy**:
   ```
   Plan Phase (/plan-*) → Implementation Phase (/qa or /design-review) → Ship Phase (/ship) → Post-Ship (/document-release)
   Or: Foundation (/browse) ← QA/Design skills ← Ship (/ship) ← All reporting
   ```

---

### **File Locations (Absolute Paths)**

- `/root/projects/gits/gstack/SKILL.md.tmpl` — Root project skill (gstack)
- `/root/projects/gits/gstack/browse/SKILL.md.tmpl` — Browse binary interface
- `/root/projects/gits/gstack/setup-browser-cookies/SKILL.md.tmpl`
- `/root/projects/gits/gstack/gstack-upgrade/SKILL.md.tmpl`
- `/root/projects/gits/gstack/plan-eng-review/SKILL.md.tmpl`
- `/root/projects/gits/gstack/plan-design-review/SKILL.md.tmpl`
- `/root/projects/gits/gstack/plan-ceo-review/SKILL.md.tmpl`
- `/root/projects/gits/gstack/design-consultation/SKILL.md.tmpl`
- `/root/projects/gits/gstack/qa/SKILL.md.tmpl`
- `/root/projects/gits/gstack/qa-only/SKILL.md.tmpl`
- `/root/projects/gits/gstack/review/SKILL.md.tmpl`
- `/root/projects/gits/gstack/ship/SKILL.md.tmpl`
- `/root/projects/gits/gstack/document-release/SKILL.md.tmpl`
- `/root/projects/gits/gstack/design-review/SKILL.md.tmpl`
- `/root/projects/gits/gstack/retro/SKILL.md.tmpl`

Generator script: `/root/projects/gits/gstack/scripts/gen-skill-docs.ts`

---

This architecture enables each skill to be self-contained yet coordinated. Skills can be invoked standalone or as part of a larger workflow, and the template system ensures consistent methodology, messaging, and integration points across the entire gstack ecosystem.

agentId: a4dc1548ef9c7ef81 (use SendMessage with to: 'a4dc1548ef9c7ef81' to continue this agent)
<usage>total_tokens: 91776
tool_uses: 26
duration_ms: 286520</usage>

Prompt:
Explore the gstack project at /root/projects/gits/gstack focusing on all the skill template files and how they work together:

1. Read every SKILL.md.tmpl file in the project root and subdirectories (ship/, review/, qa-only/, plan-design-review/, design-review/, plan-ceo-review/, plan-eng-review/, retro/, document-release/)
2. Read the generated SKILL.md files to see what the final output looks like
3. Read the scripts/gen-skill-docs.ts to understand template variables and how they're resolved
4. Look for any preamble or shared template fragments
5. Read browse/SKILL.md.tmpl if it exists

I need to understand exactly what each skill does and how they compose together.