---
name: setup
description: "Infer project stack from manifests, fill in the CLAUDE.md and AGENTS.md project profiles, and scaffold the .forge and aiwiki directories. Run after forge init."
---

# /setup — Configure Project Profile

You are configuring the forge project profile. The CLI (`npx @jamie-tam/forge init`) already installed skills, commands, agents, hooks, all language rules, and the CLAUDE.md / AGENTS.md templates. This command infers the project's tech profile, fills the templates, and scaffolds the working directories.

Language rules ship complete (typescript, react, python). Agents read the rule files matching the work at hand — no install-time pruning needed.

## Step 1: Detect Optional Tools & Build Graph

Detect optional tools first — Graphify's knowledge graph enriches stack inference and reduces tokens for all later steps.

**Graphify (knowledge graph):**

Run the graphify status check from `protocols/graphify.md`:

1. Check three things:
   - `graphify-out/graph.json` exists?
   - `graphify --version` succeeds (CLI installed)?
   - `~/.claude/skills/graphify/SKILL.md` exists (skill installed for `/graphify` to work)?
2. Prompt based on status (see the full guard table in `protocols/graphify.md`):
   - **Nothing installed** → offer install (CLI + skill manual path from protocol)
   - **CLI installed, skill missing** → offer skill install only (so `/graphify` works)
   - **Both installed, no graph** → offer build (`/graphify`)
   - **Graph exists, both installed** → offer update (`/graphify --update`)
   - **Graph exists, CLI missing** → use static files only
3. If user accepts build/update → invoke the `/graphify` skill, then continue.
4. If graph is available after this step, it will enrich Step 2.

**Codex plugin:**
```bash
codex --version 2>/dev/null
```
- If detected: note the version for the report.
- If not detected: do not mention it.

**Gitignore setup:**
Ensure `.forge/local.yaml` is in `.gitignore`. This file stores per-user preferences (e.g., Codex consent, Graphify consent) and must not be committed.

```bash
grep -q '.forge/local.yaml' .gitignore 2>/dev/null || echo '.forge/local.yaml' >> .gitignore
```

<GATE>
STOP. If Graphify was recommended for installation or a graph build was offered, wait for the user's response before proceeding. Do NOT skip ahead to stack inference — the graph data from this step enriches the next step. Only proceed to Step 2 after the user has responded to all tool recommendations.
</GATE>

## Step 2: Infer Project Profile & Fill Templates

Read the project's manifest files to infer the tech profile. Check whichever exist:

| Look for | Tells you |
|---|---|
| `package.json` | name, dependencies, frameworks (React/Vue/Next/Astro/Hono/etc.), test runner (vitest/jest/playwright), bundler |
| `pnpm-workspace.yaml`, `package.json` `workspaces` | monorepo structure — scan each workspace's manifest |
| `pyproject.toml`, `requirements.txt`, `Pipfile` | Python deps, framework (FastAPI/Django/Flask), test runner (pytest) |
| `go.mod`, `Cargo.toml`, `pom.xml`, `build.gradle` | Go / Rust / Java / Kotlin |
| Lock files (`pnpm-lock.yaml`, `yarn.lock`, `bun.lock`, `package-lock.json`, `uv.lock`, `poetry.lock`) | Package manager |
| `tsconfig.json` | TypeScript |
| `Dockerfile`, `docker-compose.yml` | Container setup, often database hints |
| `vite.config.*`, `next.config.*`, `astro.config.*`, etc. | Confirm framework |
| `tailwind.config.*`, `postcss.config.*` | Styling stack |

If a Graphify graph is available, cross-reference its technology nodes and community labels to validate and enrich the inference (especially for monorepos and modern frameworks the manifests don't fully reveal).

Synthesize what you find into a profile. Aim for accurate version numbers (read package versions, not just names). Present for confirmation:

```
Inferred project profile:
  Name:            my-app
  Stack:           typescript/react 18 + next 14
  Database:        postgresql (via @prisma/client)
  Unit tests:      vitest
  E2E tests:       playwright
  Package manager: pnpm
  Notable libs:    zustand, tailwind 4, lucide-react

Is this right? (y / correct field=value / describe what's off)
```

Let the user correct any fields. Honor user corrections — they know their project; you're inferring.

<GATE>
STOP. Do NOT proceed until the user has confirmed or corrected the inferred profile. The values flow into project docs and the wiki — wrong values mislead every later session.
</GATE>

After confirmation, fill both project docs. Show the filled content for review before writing:

- **`.claude/CLAUDE.md`** — populate the `project:` YAML block: name, stack, database, test_runner, package_manager.
- **`AGENTS.md`** (repo root) — populate the Project section: Name, Stack, Test runner, Package manager. Replace the `(run /setup)` placeholders with actual values.

<GATE>
STOP. Present the filled CLAUDE.md and AGENTS.md content to the user for review before writing. Do NOT write files without user confirmation.
</GATE>

## Step 2.5: Project Mode Declaration

Ask the user how to classify this project. The answer is the **authoritative** input to `rules/common/skill-selection.md` Step 1 — every later session's mode detection reads it from `.claude/CLAUDE.md`. Without an explicit declaration, behavioral signals misclassify fresh forge installs into existing production codebases as prototype work (the "empty aiwiki" trap).

```
Which best describes this codebase?
  1. production  — established codebase with users, CI, tests, deploy pipeline (most common).
  2. prototype   — a POC validating concept + UX, no production users yet.
  3. greenfield  — brand-new project starting from zero (treated as prototype until the prototype locks, then becomes production).

Pick one.
```

Write the answer into `.claude/CLAUDE.md`'s `project:` block as `mode: "<choice>"`. Examples:
- A 5-year-old Next.js codebase that just installed forge → `production`. `/feature`, `/refactor`, `/bugfix` route through harden / build-tdd / quality gates by default, not through `iterate-prototype`.
- A new `pocs/my-feature-prototype/` Vite app → `prototype`. `/feature` offers the `iterate-prototype` redirect.
- A new project being scaffolded from scratch via `/greenfield` → `greenfield`.

The user can edit `project.mode:` later (e.g., flip `prototype` → `production` after the prototype locks). Per-work-item local context (path under `pocs/`, manifest phase_plan) still overrides per `skill-selection.md` mixed-mode rule.

<GATE>
STOP. Do NOT proceed to Step 2a (gate enforcement) until the user has chosen a mode. The mode drives Step 2a's default.
</GATE>

## Step 2a: Apply Gate Enforcement Mode

`npx @jamie-tam/forge init` installs PreToolUse hooks that block manifest `gate-passed: true` edits unless telemetry shows the matching skill was invoked via the Skill tool for this work item. Note: this enforces **invocation** (the workflow ran), not **completion** (the skill produced correct output) — content correctness still depends on the skill itself and on user review. Useful for production-grade work; high-friction for prototype iteration where most phases are explicitly skipped.

**Apply automatically based on the declared mode from Step 2.5** (no prompt — the user has not yet seen a gate fire and can't reasonably decide upfront; setup chooses the mode-appropriate default and tells the user how to change it later).

| Declared mode (Step 2.5) | Decision |
|---|---|
| `prototype` or `greenfield` | **Disable** — prototype iteration; faster loop |
| `production` | **Keep enabled** — production discipline; manifests cannot mark a gate passed without the matching skill having been invoked |

**On "disable"**: remove the three gate-enforcer matcher entries from `.claude/settings.local.json` (the entries with `matcher: Edit`, `matcher: Write`, OR `matcher: MultiEdit` whose command invokes `.claude/hooks/scripts/gate-enforcer.sh`). All three matchers are installed by `forge init` per `hooks/hooks.json:29-58`; missing any one leaves a gap (e.g. MultiEdit writes still block). The settings file is gitignored so this is a local-only change. Keep the PostToolUse telemetry hook — telemetry is still recorded for retrospective audit; only the blocking is removed.

**On "keep enabled"**: leave settings.local.json as installed.

**Then tell the user, plainly:**

```
Gate enforcement: <enabled | disabled>
  Reason: <mode signal that triggered it>
  To change: remove or restore the three gate-enforcer PreToolUse entries
  (Edit, Write, MultiEdit matchers) in .claude/settings.local.json
  (canonical entries in hooks/hooks.json).
  First time you hit a real gate-passed edit and want to opt in (or out),
  surface the toggle then — no upfront commitment.
```

Note in the manifest or session memo what was applied, so future sessions don't have to re-detect.

## Step 3: Create .forge Directory

Create the working directory structure if it doesn't exist:

```
.forge/
├── work/               # Per-work-item artifacts and manifests, one subdir per type
│   ├── feature/
│   ├── bugfix/
│   ├── refactor/
│   ├── hotfix/
│   └── greenfield/
├── state/              # Runtime state (telemetry, wiki receipts, dream history)
└── wiki-history/       # Pre-swap snapshots of aiwiki/ before atomic accept (for rollback)
```

Only create the top-level directories. Individual work-item folders are created on demand by the relevant command.

## Step 4: Opt In to the aiwiki Knowledge Layer

The `aiwiki/` is the project's persistent context layer — typed pages (decisions, gotchas, conventions, architecture, oracles, sessions), an auto-loaded usage rules file, and schema definitions LINT validates against. It powers `harden` (oracle capture), `build-tdd` (slice-oracle reads), `quality-test-plan` / `quality-test-execution` (oracle traceability), `support-gotcha` (recurring-failure capture), `support-dream` (consolidation), `/note`, and `/wrap`. For projects expecting more than a couple of weeks of work — anything that re-reads its own history — aiwiki pays for itself fast. For one-shot research, ad-hoc evaluation, or short-lived runbooks, it's overhead.

### Step 4a: Ask the user

Use the declared mode from Step 2.5 to pick the default, then ask:

| Step 2.5 mode | Default | Prompt |
|---|---|---|
| `production` | **Y** | "Enable aiwiki/ (typed knowledge layer used by harden, TDD, and quality gates)? Recommended for production work — every later session reads from it. [Y/n]" |
| `greenfield` | **Y** | "Enable aiwiki/ (typed knowledge layer used by harden, TDD, and quality gates)? Recommended for greenfield projects that will reach production. [Y/n]" |
| `prototype` | **N** | "Enable aiwiki/ (typed knowledge layer used by harden, TDD, and quality gates)? Prototype mode skips harden and quality gates by default, so aiwiki is optional. Enable if you expect this prototype to graduate to production. [y/N]" |

Honor the user's explicit choice over the default — they know the project.

<GATE>
STOP. Wait for the user's Y/N before proceeding. The choice changes which files get scaffolded and which downstream skills become active.
</GATE>

### Step 4b — User picked Y: scaffold aiwiki

```
aiwiki/
├── CLAUDE.md          # Auto-loaded by Claude Code at session start (wiki usage rules)
├── INDEX.md           # Sortable index of recent activity (dream-maintained)
├── projectbrief.md    # One-pager: what this project is (filled by user)
├── decisions/         # ADRs
├── gotchas/           # Recurring failures + prevention
├── conventions/       # Codebase patterns + rationale
├── architecture/      # System-shape docs (one file per subsystem)
├── oracles/           # Prototype-behavior snapshots production code must reproduce
├── sessions/          # Per-session handoff index (hook + dream maintained)
├── raw/               # Incoming, unclassified — compile or delete at phase close
├── proposed/          # Dream output awaiting user review (input untouched)
└── schemas/           # Per-page-type schemas used by wiki-lint
```

REQUIRED SUB-SKILL: Use **support-wiki-bootstrap** to ensure `aiwiki/` exists.

After bootstrap:
1. Update `aiwiki/projectbrief.md` with the project name and stack from Step 2 (replace the placeholder description). Ask the user to fill `projectbrief.md` before continuing — the wiki references it for orientation context.
2. Write `aiwiki_enabled: true` into the `project:` block in `.claude/CLAUDE.md`.

<GATE>
STOP. The `aiwiki/CLAUDE.md` is auto-loaded by Claude Code on every session start in this project. Confirm with the user that they accept the wiki usage rules (citation requirements, typed page schemas, no-speculation rule, dream review flow) before completing setup. They can edit `aiwiki/CLAUDE.md` to customize.
</GATE>

### Step 4c — User picked N: skip scaffold

1. Do NOT run `support-wiki-bootstrap`. Do NOT create `aiwiki/` or copy `aiwiki/CLAUDE.md` into the project root.
2. Delete the installed `.claude/templates/aiwiki/` directory so a stray scaffolder cannot find it later: `rm -rf .claude/templates/aiwiki`. (Re-installed by `forge update` if the user opts in later.)
3. Write `aiwiki_enabled: false` into the `project:` block in `.claude/CLAUDE.md`.
4. Surface to the user: "aiwiki layer skipped. Downstream skills (`support-gotcha`, `harden`, `iterate-prototype` capture, `/note`, `/wrap`) will surface an upgrade hint instead of writing. Re-run `/setup` and pick Y to enable later, or scaffold manually by restoring `.claude/templates/aiwiki/` from the forge package and re-running `support-wiki-bootstrap`."

## Step 5: Report

Print a summary:
```
Setup complete!

Project profile:
  Name:            {name}
  Stack:           {stack}
  Test runner:     {test_runner}
  Package manager: {package_manager}

Configured:
  - CLAUDE.md and AGENTS.md profiles filled
  - .forge/ working directory (work/, state/, wiki-history/)
  - aiwiki/ knowledge layer: {enabled — scaffolded with CLAUDE.md, schemas/, projectbrief.md, typed-page subdirs | DISABLED — re-run /setup and pick Y to enable, or restore .claude/templates/aiwiki/ + run support-wiki-bootstrap}

Optional tools:
  - Codex plugin: {detected version | not detected}
    {If detected: "Second opinions available during quality and planning phases."}
  - Graphify: {detected version | "not installed — pip install graphifyy"}
    {If detected + graph built: "Knowledge graph available ({N} nodes, {N} communities)."}
    {If detected + no graph: "Run /graphify to build a knowledge graph."}

Next steps:
  1. Run /discover for a one-screen orientation (installed capabilities, suggested next move)
  2. Review .claude/CLAUDE.md and AGENTS.md
  3. Run /validate to verify system health
  4. Start with /feature or /greenfield
```

## Deferred: `forge wiki enable` CLI subcommand

A dedicated CLI subcommand for enabling aiwiki after setup is not yet implemented. The contract, once added to `src/cli.ts` + `src/wiki.ts`:

```
forge wiki enable

  Behavior:
    1. Read project.aiwiki_enabled from .claude/CLAUDE.md.
       - If true and aiwiki/ exists: exit 0 with message "aiwiki already enabled."
       - If true but aiwiki/ missing: re-run support-wiki-bootstrap equivalent and exit 0.
       - If false (or unset): proceed.
    2. Re-install .claude/templates/aiwiki/ from the forge package if it was
       removed by /setup Step 4c (use the same copy logic as `forge update`).
    3. Run the support-wiki-bootstrap procedure inline (mkdir + schema copy +
       top-level files), idempotent.
    4. Flip project.aiwiki_enabled to true in .claude/CLAUDE.md (parse the YAML
       block between the FORGE markers' siblings; preserve all other fields).
    5. Print "aiwiki enabled. Re-run /discover to see the knowledge layer in
       the orientation." and exit 0.

  Until shipped, the workaround is: re-run /setup and pick Y at Step 4, or
  manually restore .claude/templates/aiwiki/ via `forge update` and invoke
  support-wiki-bootstrap from a Claude session.
```
