> ## Documentation Index
> Fetch the complete documentation index at: https://prof-lee.zikun.me/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime mechanism

> What happens when a user types /office-hours. The anatomy of a SKILL.md, the four-tier preamble, the state directory, and the hook system.

A `SKILL.md` is not magic. It is a Markdown file with a YAML header that Claude Code's native skill loader reads, registers as a slash-command, and feeds back as the system prompt when invoked. Everything sophisticated in gstack (the cross-skill handoff, the safety hooks, the institutional memory) is built out of that single primitive.

## Anatomy of a SKILL.md

The frontmatter declares everything Claude Code needs to know to register and run the skill. The body is the prompt.

```markdown SKILL.md (skeleton) theme={null}
---
name: review
preamble-tier: 4
version: 1.0.0
description: |
  Pre-landing PR review. Analyzes diff against the base branch
  for SQL safety, LLM trust boundary violations, conditional
  side effects, and other structural issues.
allowed-tools:
  - Bash
  - Read
  - Edit
  - Write
  - Grep
  - Glob
  - Agent
  - AskUserQuestion
  - WebSearch
triggers:
  - review this pr
  - code review
  - check my diff
hooks:                         # optional. Only safety skills use this
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "bash ${CLAUDE_SKILL_DIR}/bin/check-careful.sh"
sensitive: true                # optional. Factory host elevates permissions
gbrain:                        # optional. Declares semantic context queries
  schema: 1
  context_queries:
    - id: prior-reviews
      kind: list
      filter: { type: timeline, tags_contains: "repo:{repo_slug}" }
      sort: updated_at_desc
      limit: 5
      render_as: "## Prior reviews in this repo"
---

{{PREAMBLE}}

<the actual instructions to the model. Anywhere from 500 to 2500 lines>
```

<Tip>
  **Templates and rendered files are committed together.** The `.tmpl` is the source of truth. The `.md` is what Claude Code actually reads. The build step (`bun run gen:skill-docs`) expands forty-eight distinct placeholder patterns to produce the final file. Both ship in the repo so installations without the build toolchain still work.
</Tip>

## The four-tier preamble

`scripts/resolvers/preamble.ts` composes the shared preamble in four tiers. Every skill declares which tier it needs with `preamble-tier: 1 to 4` in frontmatter. Lower tiers are leaner. Tier 4 is the full kitchen sink and is also the default when a skill does not declare a tier.

<Tabs>
  <Tab title="Tier 1">
    **Included.** Bash bootstrap, upgrade check, lake-intro, telemetry consent, voice directive (trimmed), completion-status protocol.

    **Used by.** `/browse`, `/setup-browser-cookies`, `/benchmark`, `/make-pdf`, `/benchmark-models`.

    These skills are atomic primitives. They do one thing per invocation and do not need the heavier behavioral framework.
  </Tab>

  <Tab title="Tier 2">
    **Adds on top of tier 1.** Full voice directive, AskUserQuestion format rule, completeness principle ("boil the lake"), confusion protocol, continuous-checkpoint integration, context-health monitor.

    **Used by.** `/investigate`, `/cso`, `/retro`, `/document-release`, `/setup-deploy`, `/canary`, `/context-save`, `/context-restore`, `/health`, `/learn`, `/document-generate`, `/setup-gbrain`, `/sync-gbrain`, `/design-shotgun`, `/design-html`, `/plan-tune`.

    Skills that produce structured artifacts but do not need to challenge the user's framing.
  </Tab>

  <Tab title="Tier 3">
    **Adds on top of tier 2.** Repo-mode detection, Search-Before-Building three-layer framework.

    **Used by.** `/autoplan`, `/codex`, `/claude`, `/design-consultation`, `/office-hours`, `/plan-ceo-review`, `/plan-eng-review`, `/plan-design-review`, `/plan-devex-review`, `/devex-review`.

    Planning and consultation skills that need to search the codebase intelligently and reason about what kind of repo they are in.
  </Tab>

  <Tab title="Tier 4">
    **Same as tier 3.** The `TEST_FAILURE_TRIAGE` block is a separate placeholder, not part of the preamble itself.

    **Used by.** `/ship`, `/review`, `/qa`, `/qa-only`, `/design-review`, `/land-and-deploy`.

    The shipping pipeline skills that need every safeguard the preamble can offer plus the test-failure ownership triage on top.
  </Tab>
</Tabs>

## What the preamble bash actually does

Every skill, on every invocation, runs roughly this sequence before the user-facing prompt starts.

<Steps>
  <Step title="Check for a gstack version upgrade" icon="cloud-download">
    Emits `UPGRADE_AVAILABLE x to y` if the global install is behind. Subsequent steps respect the user's snooze preference.
  </Step>

  <Step title="Touch a per-session file" icon="circle-dot">
    `~/.gstack/sessions/$PPID`. Used to detect concurrent sessions. Files older than 120 minutes are swept.
  </Step>

  <Step title="Read user config" icon="settings">
    `proactive`, `skill_prefix`, `explain_level`, `telemetry`, `question_tuning`, `checkpoint_mode` from `~/.gstack/config.yaml`.
  </Step>

  <Step title="Detect git branch plus repo mode" icon="git-branch">
    Distinguishes a regular checkout from a Conductor worktree from a vendored install. Affects path resolution downstream.
  </Step>

  <Step title="Log to analytics" icon="trending-up">
    Append-only JSONL at `~/.gstack/analytics/skill-usage.jsonl`. If telemetry is set to `community`, also fires `gstack-telemetry-log` for remote reporting.
  </Step>

  <Step title="Resolve $SLUG via gstack-slug" icon="hash">
    The project identifier used in every `~/.gstack/projects/<slug>/` path.
  </Step>

  <Step title="Load learnings count plus recent learnings" icon="brain">
    `~/.gstack/projects/$SLUG/learnings.jsonl`. If count exceeds 5, fires `gstack-learnings-search` to surface relevant prior patterns.
  </Step>

  <Step title="Fire gstack-timeline-log in the background" icon="timer">
    Records the skill invocation for `/retro` to read later.
  </Step>

  <Step title="Run one-time onboarding gates if needed" icon="circle-check">
    Telemetry consent, proactive-suggestion consent, "Boil the Lake" philosophy intro, writing-style choice. Each fires at most once per machine and writes a marker file.
  </Step>
</Steps>

## The state directory is the glue

Skills do not share runtime memory. Each invocation is a fresh `claude -p` process. The hand-off mechanism is the filesystem. Every skill that produces output for downstream consumption writes to a predictable path under `~/.gstack/`. Every downstream skill reads from that same path.

```text ~/.gstack/ (the substrate) theme={null}
~/.gstack/
├── config.yaml                         # User preferences
├── sessions/$PPID                       # Per-session marker (swept after 120 min)
├── analytics/skill-usage.jsonl          # Append-only usage log
├── analytics/eureka.jsonl               # First-principles insights
├── security/attempts.jsonl              # Prompt-injection attack log (salted SHA-256)
├── security/device-salt                 # Per-device hash salt (0600)
├── projects/$SLUG/
│   ├── learnings.jsonl                  # Patterns, pitfalls, preferences
│   ├── timeline.jsonl                   # Session events for /retro
│   ├── *-design-*.md                    # Design docs from /office-hours
│   ├── ceo-plans/*.md                   # Plans from /plan-ceo-review
│   ├── *-test-plan-*.md                 # Test plans from /plan-eng-review
│   ├── *-test-outcome-*.md              # QA outcomes from /qa
│   ├── designs/<screen>-<date>/         # Visual mockups from /design-shotgun
│   ├── taste-profile.json               # Decay-weighted design preferences
│   ├── $BRANCH-reviews.jsonl            # Ship metrics for /retro
│   └── retros/*.md                      # Retros from /retro
├── builder-profile.jsonl                # /office-hours session tier progression
└── retro-context.md                     # User-authored notes injected into /retro
```

<Info>
  **The discovery mechanism is `ls -t`.** `/plan-ceo-review` runs `ls -t ~/.gstack/projects/$SLUG/*-design-*.md | head -1` to find the most recent design doc. `/qa` runs `ls -t ~/.gstack/projects/$SLUG/*-test-plan-*.md | head -1` to find the test plan. No registry, no manifest. The most recently modified file with the matching glob is the source of truth.
</Info>

## The hook system

Safety skills (`/careful`, `/freeze`, `/guard`, `/investigate`) declare `PreToolUse` hooks in their frontmatter. When the skill is active, Claude Code fires the hook script before every matching tool call. The hook reads the tool input as JSON, decides, and emits a verdict.

```bash careful/bin/check-careful.sh theme={null}
#!/usr/bin/env bash
set -euo pipefail
INPUT=$(cat)
CMD=$(printf '%s' "$INPUT" | grep -o '"command"[[:space:]]*:[[:space:]]*"[^"]*"' \
        | head -1 | sed 's/.*:[[:space:]]*"//;s/"$//' || true)

# ... pattern check against rm -rf, DROP TABLE, git push --force, etc.

if matched_destructive_pattern; then
  echo '{"permissionDecision":"ask","message":"<warning text>"}'
else
  echo '{}'
fi
```

<CardGroup cols={3}>
  <Card title="Empty object means allow" icon="circle-check">
    Empty JSON means the tool call proceeds normally with no user prompt.
  </Card>

  <Card title="permissionDecision ask means warn" icon="circle-alert">
    Surfaces the warning to the user, who can override and proceed or cancel.
  </Card>

  <Card title="permissionDecision deny means block" icon="circle-x">
    The tool call is rejected outright. Used by `/freeze` to block edits outside the boundary.
  </Card>
</CardGroup>

## Cross-skill invocation

Skills invoke other skills through Claude Code's native `Skill` tool. The top-level `SKILL.md` contains explicit routing rules in its body.

```text theme={null}
- User describes a new idea, asks "is this worth building" -> invoke /office-hours
- User reports a bug, error, "wtf", "something's wrong"   -> invoke /investigate
- User asks to ship                                       -> invoke /ship
- User asks for a second opinion                          -> invoke /codex
- User asks about security or vulnerabilities             -> invoke /cso
```

A handful of skills also use the `{{INVOKE_SKILL:office-hours}}` template placeholder mid-flow. For example, `/plan-ceo-review` offers to drop into `/office-hours` mid-session when the user cannot articulate the problem.

## Subagent dispatch

`/ship` and `/cso` use Claude Code's `Agent` tool (`subagent_type: "general-purpose"`) to dispatch self-contained subtasks that would otherwise bloat the parent context. Coverage audits, plan-completion audits, Greptile review-comment triage, parallel security verifiers.

```text Subagent contract theme={null}
1. Parent crafts a prompt with explicit input plus output format.
2. Subagent runs in a fresh context window.
3. Subagent's last line is a single JSON object.
4. Parent parses that JSON and proceeds.
5. Parent never sees the subagent's intermediate file reads or thinking.
```

This is the cleanest pattern in the repo for protecting expensive context. The audit subagent might read 20 files and run 5 greps. The parent only sees `{"coverage_pct":87,"gaps":3,"diagram":"...","tests_added":[...]}`.

## The /autoplan meta-orchestrator

`/autoplan` is structurally different from every other skill. It reads other `SKILL.md` files from disk through the `Read` tool and follows their instructions inline, while overriding the AskUserQuestion calls with six encoded decision principles. It is a skill that programmatically runs other skills as if they were a library.

```text /autoplan execution model theme={null}
Phase 0. read CEO plus Design plus Eng plus DX skill files
Phase 1. execute CEO review at full depth, auto-decide via principles
Phase 2. execute Design review (if UI scope detected)
Phase 3. execute Eng review at full depth
Phase 3.5. execute DX review (if developer-facing scope)
Phase 4. final approval gate (only taste decisions surface)
```

The six principles encode Garry's defaults. Choose completeness. Boil the lake (fix everything in blast radius under 1 day CC effort). Pragmatic (cleaner option wins). DRY (reject duplicates). Explicit over clever. Bias toward action.

## What this is, mechanically

<Warning>
  There is no runtime, no agent, no framework. Every skill invocation is `claude -p` with the skill file as the system prompt. The "intelligence" is Claude Opus 4.7 reading a well-tuned prompt. The repository's value is the prompts themselves plus the shared `~/.gstack/` state directory that lets them compose across sessions.
</Warning>

Continue to the [sprint pipeline](/pipeline) to see how the skills compose end-to-end, or jump to the [verbatim prompts](/prompts) for the exact text inside the biggest specialists.
