# Forge

> Use when the user has an idea, feature, design, or change that needs exploration before implementation — architecture decisions, new features, system design, refactoring plans, or any creative/building task that benefits from structured design thinking before code.

- Skill: `joogy06/forge` (Agent Skill, multi-file: 13 files)
- Install (CLI): `npx skillmds@latest add joogy06/forge`
- Raw SKILL.md: https://api.skillmd.com/api/skills/joogy06/forge/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Productivity
- Author: joogy06 (https://skillmd.com/u/joogy06)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/joogy06/forge

---


# Forge — Ideas Into Designs & Implementation

## Overview

Turn ideas into fully formed designs through collaborative dialogue, then orchestrate implementation via **bob** (autonomous executor agent). Uses a two-phase approach: **Design Team** explores approaches with dual challengers (Claude + Codex) and UX advocate, then **bob** handles all execution — work package decomposition, team orchestration via agent-teams, verification, and delivery.

Every design and implementation decision must account for real human behaviour — how end users actually see, navigate, and interact with the product.

<HARD-RULE>
**Multi-Model Second Opinion**: For MEDIUM and COMPLEX tasks, run BOTH Codex (GPT-5.5) AND Antigravity CLI (`agy`, via `agy --sandbox -p`) in parallel alongside Claude agents — three models catch what two miss. For SIMPLE tasks, external models are optional. If Codex/agy unavailable, fall back gracefully but note each gap explicitly.
</HARD-RULE>

<HARD-RULE>
**Do NOT invoke `superpowers:brainstorming`**. Forge is the canonical design workflow. Forge has its own internal design exploration team (approach agents, challengers, Codex). The superpowers brainstorming skill is a separate, overlapping workflow that lacks Codex integration, multi-agent teams, and custom skill awareness. If you feel tempted to invoke brainstorming, you are already inside the right workflow — continue with forge.
</HARD-RULE>

<HARD-RULE>
**Codex Escalation**: When Claude agents are stuck on a problem (2+ failed attempts, circular reasoning, or no clear solution), delegate the problem to Codex for a fresh perspective before asking the user.
</HARD-RULE>

<HARD-RULE>
**Contract Map Required**: For any design that introduces components (new services, modules, endpoints, integration points), a valid signed `progress/contract-map.yaml` MUST exist before spawning bob. This is enforced mechanically by bob's G1 subprocess check, not by prose.

- Forge invokes the `component-contract-mapping` skill at Step 8a to produce the map.
- Forge signs it with HMAC-SHA256 using `.forge/session.key` (per spec section 7.4).
- The signed payload MUST include `map_hash`, `map_revision`, `forge_session_id`, and `signed_at`.
- Missing or unsigned map = refuse to spawn bob. No workarounds. No "we'll add it later".
- Pure refactoring / single-file bugfixes with no new components are exempt.
</HARD-RULE>

<HARD-RULE>
**Multi-subsystem requests emit handoff docs, not inline decomposition** (S038 Batch G, 2026-05-25). When forge Step 1 detects that a request describes multiple independent subsystems (existing "Large Project Decomposition" pattern), instead of inline-spawning sub-forge cycles (depth+1), forge MUST invoke the `handoff` skill to emit one `/tmp/handoff-<sub>-<date>-<uuid>.md` per decomposed sub-project. Each handoff doc records the slice of context relevant to that sub-project and a "Suggested skills: forge (MEDIUM cycle on this sub)" directive. The user picks which sub-project to start first; forge does NOT recurse into all of them. Recursion limit (depth≥3 REFUSE per existing rule) remains in effect — handoff is the new exit, not a way around the limit.
</HARD-RULE>

<HARD-GATE>
Do NOT write any code, scaffold any project, or take any implementation action until:
1. A design has been presented and the user has approved it
2. Bob has been spawned with the approved design doc
This applies to EVERY project regardless of perceived simplicity.
</HARD-GATE>

---

## Checklist

You MUST create a task for each item and complete in order:

1. **Explore project context** — read PROJECT.md (architecture map, components, integration edges) and relevant COMPONENT.md files FIRST. Check history.md (if >400 lines, head+tail only — older context lives in `history/INDEX.md`), session_control.md. Invoke `project-documentation` to ensure all docs exist (creates PROJECT.md + COMPONENT.md stubs if missing). **If a wiki exists for the project** (CWD contains `.wiki/` OR `~/.wiki-registry.yaml` lists this project), use Tier 1 access: `Grep` the wiki's `wiki/` directory for prior decisions, research, and ADRs on the task topic. Include any findings in `shared_context` as a "Prior Wiki Knowledge" section so design agents can reference existing decisions. **Also run `python3 ~/.claude/skills/_meta/scan_hard_rules.py`** (plain mode) to scan CLAUDE.md (global + project-local) for hard-rule directives and diff against `~/.claude/skills/_meta/hard-rules-checklist.md`. If any are flagged as potentially missing, surface them to the user with a 1-line summary and ask: "add to checklist / wire into a skill / apply ad-hoc / ignore?" — do NOT silently skip. This is idempotent with the SessionStart hook but catches cases where forge is invoked from a subagent, after `cd`, or in sessions where the hook didn't run.

   **Dependency currency check (advisory only, MEDIUM+ tasks):** if any manifest is present at the project root (`pyproject.toml`, `package.json`, `Cargo.toml`, `go.mod`, `Gemfile`, `pom.xml`), invoke `dep-currency-check` to populate `shared_context.dependency_health`. Run it advisory-only — forge Step 1 NEVER fails on its exit code; blocking enforcement lives at bob's WP boundary, the `G_DEP_CURRENCY` gate, and pre-commit hooks. Skip for TRIVIAL/SIMPLE tasks (latency budget). Pattern:
   ```bash
   if find "$PWD" -maxdepth 4 \( -name 'pyproject.toml' -o -name 'package.json' -o -name 'Cargo.toml' -o -name 'go.mod' -o -name 'Gemfile' -o -name 'pom.xml' \) 2>/dev/null | grep -q .; then
     PYTHONPATH="$HOME/.claude/skills/dep-currency-check" python3 -m dep_currency_check "$PWD" \
       --format json --severity high --quiet \
       --output "/tmp/forge-dep-currency-${FORGE_SESSION_ID:-default}.json" 2>&1 || true
   fi
   ```
   The `|| true` is mandatory — Step 1 MUST NOT fail. Read the JSON if present, include `dependency_health` in shared_context. See `~/.claude/skills/dep-currency-check/references/integration-forge.md` for the full payload shape + skip rules.
2. **Offer visual companion** (if topic involves visual questions) — see Visual Companion section. This is its own message, not combined with clarifying questions.
3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria. If the request describes multiple independent subsystems, flag and decompose first (see Large Project Decomposition). **Founder-intent routing:** if the request is "I have a startup idea" / "generate ideas" / "validate my idea" / "what should I build" / any pre-execution founder / innovator / inventor intent — route to the `founder` skill FIRST (not forge directly). Founder owns pre-execution (ideation, validation, business model, GTM); forge owns execution. Founder will hand back at the Scope→Launch gate with a populated `forge_brief` when the venture is ready for build. See `founder/references/forge-handshake.md` for the full contract.

**Explicit founder handoff**: If the spawn prompt or user message includes `came_from_founder: true` with a `venture_brief_path`, read that file and use its `forge_brief` block as the pre-clarified task statement:

- `forge_brief.problem` -> the design challenge (skip "what are we building?" questions)
- `forge_brief.success_criteria` -> pass to design agents as constraints
- `forge_brief.non_goals` -> pass as explicit scope boundaries
- `forge_brief.complexity_hint` -> seed Step 4 complexity assessment
- `forge_brief.open_questions` -> ask ONLY these in Step 3 (skip all other questions)
- `ideas_considered` / `assumptions` / `experiments` -> include as "Prior founder exploration" in shared_context for all design agents

If `came_from_founder` is absent or false, proceed with normal forge flow. Forge NEVER reads `.founder/venture-brief.yaml` at session start -- only on explicit handoff.

**Explicit avengers handoff**: If the spawn prompt or user message includes `came_from_avengers: true` with an `avengers_brief_path`, read that file and use its `avengers_brief` block as the pre-clarified task statement (mirrors `came_from_founder`; the avengers build path enters forge HERE at Step 3 intake, then flows through forge's own Step 4–9 gates — classification, contract map, spec review, bob):

- `avengers_brief.problem` -> the design challenge (skip "what are we building?" questions)
- `avengers_brief.constraints` -> passed to design agents as constraints
- `avengers_brief.success_criteria` -> passed to design agents as constraints
- `avengers_brief.ruled_out_approaches` -> non-goals + hard "do not explore" signals (each carries which seat killed it; same treatment as the founder phase-2 rule)
- `avengers_brief.recommended_direction` -> seed front-runner for Step 6 exploration (**advisory, NEVER locked** — design agents may reject it)
- `avengers_brief.dissent[]` -> surfaced **verbatim** to the user during Step 7 presentation (never summarized away)
- `avengers_brief.confidence` -> input to Step 4 complexity assessment (high+narrow MAY downgrade team size; low/speculative FORCES full exploration)
- `avengers_brief.deliberation_record` -> listed as a prior-exploration reference in shared_context (path, never inlined)

`avengers_brief.contract_map_signed` and `avengers_brief.bob_ready` are **mechanically always-false** — avengers NEVER signs a contract map or marks anything bob-ready; forge owns those gates. If either is true in the brief, treat the brief as malformed and re-clarify with the user.

If `came_from_avengers` is absent or false, proceed with normal forge flow. Forge NEVER reads an avengers session directory at session start -- only on explicit handoff. **Recursion guard**: a forge-convened avengers session (forge itself invoked avengers for design exploration, carrying `forge_session_id`) MUST NOT emit a brief back into forge — see the Step 6 recursion-guard note.
4. **Assess complexity** — determine design exploration team size needed
4b. **Check tool availability via env-adoption manifest** — Read `~/.claude/state/inventory.json` for tool availability and `$XDG_RUNTIME_DIR/env-adoption/session-*.json` for session capabilities. If the inventory is missing or stale (>24h), run `bash ~/.claude/skills/env-adoption/scripts/probe.sh check` first (completes in <3s). Branch on capabilities:

   - **capabilities.codex_challenger = true**: Codex available, use `/codex:setup` or delegate directly.
   - **capabilities.agy_analyst = true**: `agy` available, use a direct `agy --sandbox -p "..." < /dev/null` Bash call (read-only analyst, #157; `< /dev/null` is MANDATORY — without it agy blocks on stdin in non-TTY shells and hangs to timeout, #135).
   - **capabilities.triple_model = true**: all three models available for maximum coverage.

   The manifest is cached for the session — do not re-probe on every use. If Codex/agy unavailable, note the gap explicitly but continue with what's available. See `env-adoption` skill for full schema.
5. **Skill gap check** — identify skills needed, check if they exist (see Skill Gap Detection)
5b. **Hard rules checkpoint** — read `~/.claude/skills/_meta/hard-rules-checklist.md` DESIGN PHASE + CROSS-MODEL sections. Verify: Codex parallel for MEDIUM/COMPLEX? Performance expectations asked? Gap detection done?
6. **Phase 1: Design Exploration** — spawn design exploration team OR do single-agent exploration
7. **Present design** — in sections, get user approval after each section
7b. **Freeze the design skeleton (UI designs only)** — after the user approves the HTML mockup and BEFORE Step 8a signing: invoke `skeleton-extractor` then `visual-architect`. See "UI designs — design-skeleton freeze (Step 2.5)" under Visual Companion.
8. **Write design doc** — save to `docs/plans/YYYY-MM-DD-<topic>-design.md`
8a. **Generate & sign contract map** (if design introduces components) — invoke `component-contract-mapping` skill, run G2 validation, sign via HMAC (see Contract Map Generation)
8b. **Spec review** — run spec self-review checklist, then dispatch reviewer subagent (see Spec Review)
8c. **User reviews spec** — ask user to review spec file before proceeding. Wait for approval.
8d. **Hard rules checkpoint** — read `~/.claude/skills/_meta/hard-rules-checklist.md` EXECUTION PHASE section before spawning bob.
9. **Spawn bob** — pass design doc path and shared context (see Execution Method Selection)
10. **Wait for bob** — bob handles decomposition, orchestration, verification autonomously
11. **Final integration** — collect execution results, verify, present to user

---

## Complexity Assessment

Before spawning any design exploration team, assess complexity:

| Complexity | Signals | Design Exploration Team Size |
|------------|---------|---------------------|
| **Simple** | Config change, single-file tweak, obvious solution | No team — single agent explores + optional Codex/agy |
| **Medium** | 2-3 valid approaches, touches 3-5 files | 2-3 approach agents + triple challengers (Claude + Codex + agy) |
| **Complex** | Architecture decision, 4+ approaches, cross-layer | 4-5 approach agents + triple challengers (Claude + Codex + agy) + Codex approach agent |

### Adaptive Checklist

| Step | Simple | Medium | Complex |
|------|--------|--------|---------|
| 1. Project context | Read if exists | Read | Read + invoke project-documentation |
| 2. Visual companion | Skip | If UI-facing | If UI-facing |
| 3. Clarifying questions | 1-2 max | As needed | As needed |
| 4. Complexity assessment | Done | Done | Done |
| 4b. Codex + agy check (sandbox-aware) | Skip | Check both + detect mode | Check both + detect mode |
| 5. Skill gap check | Skip | Check | Check |
| 6. Design exploration | Lead proposes directly | 2-3 agents + Codex + agy | Full team + Codex + agy |
| 7. Present design | Brief, 1 section | Sections | Sections with approval each |
| 8. Write design doc | Optional (skip if <20 lines change) | Yes | Yes |
| 8b. Spec review | Self-review only | Self + subagent | Self + subagent |
| 8c. User reviews | Quick confirm | Review file | Review file |
| 9-11. Bob | Direct or bob | Bob | Bob |

---

## Skill Gap Detection

After assessing complexity, identify what domain skills agents will need:

Follow gap-detection protocol at `~/.claude/skills/research-for-skills/gap-detection.md`

---

## Step 4b: Orchestration tier (S055 — feature-detected)

Before Step 6, decide HOW design exploration runs. This is a fast-path choice,
never a dependency — the documented main path (Step 6B below) completes with
ZERO orchestration primitives.

- Read `bash ~/.claude/skills/env-adoption/scripts/probe.sh get capabilities.workflow_tool`
  (the ONLY capability API — never inline-probe, never raw jq) AND confirm the
  live context via `probe.sh context` (must be `main-loop`). The decision rule,
  restated: `can_orchestrate = capabilities.workflow_tool AND context == main-loop`.
  See `env-adoption/references/context-detection.md` — `capabilities.*` alone
  NEVER authorizes orchestration (session files are shared with subagents).
- **If both true (Step 6A fast path):** the main loop MAY run the
  `design-tournament` saved workflow (parallel approach/challenge/converge fan-out
  that returns a DRAFT synthesis + a script-computed disagreement matrix). The
  converge DECISION, all user questions/approvals, and the design-doc write STAY
  inline in forge (Workflow Boundary, below). External challengers are
  PRE-LAUNCHED inline by forge and passed as transcripts (agy is UNREACHABLE from
  workflow stages — WP-2 live finding).
- **Else (Step 6B portable, canonical):** run the existing design exploration
  team inline (Phase 1 below). This is byte-identical to the prior forge flow.
  Codex/Copilot/VS Code/older-Claude hosts always take this path.

## Step 6A fast path — `design-tournament` workflow (optional, main-loop only)

When the orchestration tier (Step 4b) selected the fast path: invoke
`Workflow({name: "design-tournament", args: {...}})` with `run_started_at`,
`run_label`, `brief_path`+`brief_sha256`, `shared_context_path`+`shared_context_sha256`,
`approaches[]`, `consultants[]`, `consultant_cmds{}`, `ui_facing`, `budget_tokens`,
`transcript_dir`, `external_transcripts[]` (pre-launched), `models{}`. The
workflow returns a `design-synthesis.v1` DRAFT + the disagreement matrix; forge
presents it section-by-section and OWNS the converge decision. **Budget floor:**
if the budget cannot cover ≥2 approaches + 1 challenger + synthesis, the workflow
returns `status: INCOMPLETE` with zero synthesis — an under-budget tournament
looks unfinished, not polished. Shed ladder (documented, never silent): codex
approach-explorer → agy analyst → approach agents above the minimum 2; NEVER shed
the Claude challenger or UX-when-`ui_facing`. Spend is reported observe-only
(#147 design half — no enforcement). On ANY fast-path failure, fall back to
Step 6B (byte-identical, portable).

## Step 6B: Design exploration team (portable, canonical) — Phase 1

**Recursion guard (avengers ↔ forge)**: forge MAY convene `avengers` in design-exploration mode as an adjunct to the approach team. When it does, forge passes its `forge_session_id` in the avengers `came_from` block. A forge-convened avengers session is depth-capped and its build path is **BLOCKED**: it returns a `decision` (forced), never a `forge_brief`, so it cannot emit a `came_from_avengers` handoff back into forge (which forge itself started). This prevents infinite forge→avengers→forge recursion. Forge already pays for its own challengers; a convened avengers is for contention, not a second build gate.

### Step 1: Understanding (Lead Only)

The lead handles all user interaction:
- Check current project state (files, docs, recent commits)
- Ask questions **one at a time** (prefer multiple choice)
- Focus on: purpose, constraints, success criteria
- **Performance expectations** (ask if task creates/modifies endpoints, queries, UI, or batch processes):
  - "Expected concurrency / data volume?"
  - "Latency requirements? (e.g., p95 < 200ms)"
  - "Is this on a hot path?"
  - "Existing performance budgets to respect?"
- **Runtime / observability branch** (ask once, not a full questionnaire):
  "Does this change runtime behavior, service boundaries, or SLOs?"
  - If YES: delegate full capacity questionnaire to `performance` skill
    (`references/capacity-questionnaire.md`), full signals-map drafting to
    `observability` skill, BEFORE design-team exploration. Capture the
    signals-map path + capacity answers into `shared_context` so design
    agents consume them as constraints.
  - If NO: skip. Existing performance-expectation questions still apply.
- **Security / threat-model branch** (ask once, not a full questionnaire):
  "Does this component process untrusted input, hold secrets/tokens, cross a
  trust boundary, OR consume content the LLM agent will read (prompts, tool
  results, wiki pages, mail, web)?"
  - If YES: capture into `shared_context.security_model`:
    (a) `trust_boundary` — what's inside vs outside the trust perimeter
    (b) `attacker_model` — who's the adversary, what can they touch
    (c) `sensitive_inputs` — PII / secrets / tokens / untrusted-from-network
    (d) `egress_destinations` — external systems reached
    Then delegate to `threat-modeling` skill for STRIDE / LINDDUN if high-stakes,
    AND to `llm-security` skill if the component is part of an agentic chain
    (prompt injection / OWASP LLM Top 10 defense — Dual LLM pattern where
    consequential tool use meets untrusted text). Design agents consume the
    security_model as constraints, the same way they consume capacity_answers.
  - If NO: skip. (Pure refactors, internal-only changes, no new input surface.)
- Determine complexity level

### Step 2: Approach Exploration

**Simple tasks**: Lead proposes 2-3 approaches directly. Skip to "Present Design."

**Medium/Complex tasks**: Spawn a design exploration team.

#### Design Exploration Team Structure

| Role | Count | Responsibility |
|------|-------|----------------|
| **Lead** | 1 | Coordinates, asks user questions, synthesises design |
| **Approach Agents** | 2-5 | Each deeply explores ONE approach with trade-offs |
| **UX/Usability Agent** | 1 (always for UI-facing work) | Evaluates every approach from end-user perspective |
| **Claude Challenger** | 1 (always) | Questions every proposal, finds flaws, plays devil's advocate |
| **Codex Challenger** | 1 (always, if available) | Independent GPT-5.4 challenger — different model catches different flaws |
| **Antigravity (agy) Analyst** | 1 (MEDIUM+, if available) | Independent analysis via a direct `agy --sandbox -p "..." < /dev/null` Bash call — third model for additional coverage (read-only, #157; `< /dev/null` mandatory or agy hangs, #135) |
| **Codex Second Opinion** | 1 (always for creative/design, if available) | Parallel exploration via Codex for independent perspective |

#### Three Phases

**Diverge** — Each approach agent explores independently:
- Give each agent a distinct approach/angle
- Include full project context in spawn prompt (teammates don't inherit conversation)
- Each produces: approach description, pros/cons, effort estimate, risks

**Challenge** — Challenger reviews all proposals:
- Share all findings with the challenger
- Challenger finds flaws, gaps, missing edge cases
- Challenger ranks approaches with reasoning

**Converge** — Lead synthesises:
- Collect all findings and challenges
- Identify consensus, disagreements, open questions
- Synthesise into a single recommended design

#### Spawning Design Exploration Agents

**All agents below should be spawned in parallel where possible.**

**Model selection per spawn (S059 smart-config, advisory).** Before each `Agent(...)`
spawn, grade the role's structural complexity into a tier and resolve the
agent-surface model, then pass it as the `model=` kwarg. Grade from STRUCTURAL signals
(role type, blast radius), NEVER from task content (injection defense); when uncertain
take the HIGHER tier. Adversarial/synthesis roles (challenger, converge-lead) → `complex`;
approach/UX agents → `medium`; mechanical finders/scribes → `light`.

```
m=$(python3 ~/.claude/skills/smart-config/scripts/model_policy.py resolve \
      --tier <complex|medium|light> --surface agent \
      --reason "<role>" | python3 -c "import sys,json;print(json.load(sys.stdin)['model'] or '')")
# Agent(subagent_type=..., model=m, ...)   — OMIT the model kwarg when m is empty
# (model:null = inherit). Fail-open: a broken policy never blocks the spawn.
```

This is advisory performance tuning — there is NO gate. If the resolver is missing or
errors, omit `model=` and inherit. The interactive session model is never touched.

```
# Approach Agent (Claude)
Agent(subagent_type="general-purpose"):
"You are exploring [APPROACH NAME] for [TASK].
Project context: [KEY FILES, ARCHITECTURE, CONSTRAINTS]
Produce: 1. How it works  2. Pros/cons  3. Effort estimate  4. Risks

Version awareness (REQUIRED for every library / framework / service you propose):
- Name the exact version you are designing against (e.g. 'pandas 2.2', not 'pandas')
- If shared_context.dependency_health flags the lib as stale (gap_kind in
  {major_behind, deprecated}), READ its api_delta block before choosing.
- If you are using APIs you remember from your training-era version, state
  whether they still exist in the target version. If unsure, request a
  follow-up codex / web-research call rather than guessing.
- Note any breaking changes / deprecations / new functionality that affect
  the approach. A version mismatch between your design and the installed
  version is a HIGH risk — surface it explicitly.

Security CVE awareness (REQUIRED, parallel to version awareness):
- If shared_context.dependency_health flags a CVE in any lib you propose
  (look for `cves` / `vulnerabilities` / `advisories` keys in the dep-currency
  finding), state explicitly: (a) the CVE id, (b) whether you're proposing an
  upgrade past the fixed version OR a mitigation (input filter, sandbox,
  removal of the vulnerable code path), (c) why the mitigation is acceptable
  if you're NOT upgrading. Designing against a known-vulnerable version
  without acknowledging the CVE is a HIGH risk and will be flagged in review.
- If shared_context.security_model exists (set by Step 1 security branch),
  treat its attacker_model / sensitive_inputs / egress_destinations as
  constraints. A design that ignores them is structurally wrong, not just
  insecure. Examples: trust_boundary='public API' means your approach MUST
  include input validation at the boundary; sensitive_inputs containing
  tokens/secrets means your approach MUST address storage hardening.
- For agentic components (LLM consuming untrusted text + having tools):
  reference Dual LLM architecture (Quarantined LLM processes untrusted data
  without tool access, Privileged LLM uses only symbolic vars) as the
  default-safe pattern. Deviations need explicit justification."

# UX Agent (for UI-facing work)
# subagent_type MUST be one that exists on this host. Verify against the available
# agent-type list before spawning — a nonexistent type does NOT fail loudly, it
# silently degrades, and the specialist runs without its intended role. (S073: this
# line named `multi-platform-apps:ui-ux-designer`, which was never installed —
# `enabledPlugins` contains only `superpowers` — so every UI-facing forge cycle had
# been falling back silently.)
Agent(subagent_type="general-purpose"):
"You are the UX advocate for [TASK].
Invoke the `ux-reviewer` skill first (and `audience-experience-design` when the task
is design-before-build rather than review-after-build).
Evaluate every approach through: user journey, visual hierarchy,
cognitive load, mobile ergonomics, trust/emotion, accessibility.
Rank approaches by real-world usability."

# Claude Challenger Agent
Agent(subagent_type="general-purpose"):
"You are the devil's advocate for [TASK].
Invoke the `challenger` skill first.
Find flaws in EVERY proposal including UX findings.
Rank approaches with reasoning."
```

#### Spawning Codex Agents (ALWAYS — in parallel with Claude agents)

Check Codex availability first (step 4b). If unavailable, skip Codex agents and note the gap.

**CHECK AVAILABILITY FIRST.** The `/codex:*` commands come from a Codex *plugin*, which is a
separate thing from the `codex` CLI. Having the CLI does NOT mean you have the commands. Verify
the plugin is in `enabledPlugins` (`~/.claude/settings.json`) — or that the commands exist under
`~/.claude/commands/` — before using this path. If it is absent, go straight to raw `codex exec`
below; that path is fully capable and needs only the CLI. (S073: on this host `enabledPlugins`
contains only `superpowers`, so every `/codex:*` invocation documented here was unavailable while
raw `codex exec` worked normally.)

**Preferred when available: Codex plugin commands** (structured output, job tracking, resume capability):

```
# Codex Challenger — use /codex:adversarial-review for design challenge
# Run via Skill("codex:adversarial-review") or invoke the command:
/codex:adversarial-review --background look for scalability, security, maintainability issues and rank approaches

# Codex Research — use /codex:rescue for independent exploration
/codex:rescue --background "Explore approaches for [TASK]. Context: [KEY FILES, ARCHITECTURE, CONSTRAINTS]. Produce top 2-3 approaches with pros/cons, effort, risks."

# Check status of background jobs
/codex:status
# Retrieve results when done
/codex:result [job-id]
```

**Fallback: Raw `codex exec`** (for parallel batch tasks or custom briefs). **STDIN RULE (#155):** the agy stdin rule applies to `codex exec` exactly the same — close stdin (`< /dev/null`) on every headless argv-prompt invocation or it hangs to timeout in background shells:

```bash
CODEX_WORK=$(mktemp -d /tmp/codex-XXXXXXXXXX)

# Codex Challenger (runs simultaneously with Claude challenger)
cat > "$CODEX_WORK/brief-challenger.md" << 'BRIEF'
# Challenger Review Brief
## Context
[TASK DESCRIPTION + KEY CONSTRAINTS]
Project files at: [PROJECT_DIR]
## Your Role
You are a devil's advocate / challenger. Find flaws in EVERY approach.
Focus on: scalability, security, maintainability, edge cases, operational complexity.
For each issue: Severity (critical/moderate/minor), What's wrong, Why it matters, How to fix.
Rank overall design: strong / acceptable / needs-rework / reject.
BRIEF

timeout 600 codex exec --ephemeral -C "$PROJECT_DIR" -s read-only \
  -o "$CODEX_WORK/challenger.md" \
  "Read $CODEX_WORK/brief-challenger.md and execute the challenger review." < /dev/null || echo "CODEX_TIMEOUT: Codex did not respond within 600s" > "$CODEX_WORK/challenger.md" &

# Codex Second Opinion / Approach Explorer (independent perspective)
timeout 600 codex exec --ephemeral -C "$PROJECT_DIR" -s read-only \
  -o "$CODEX_WORK/approach.md" \
  "You are exploring approaches for [TASK].
Context: [KEY FILES, ARCHITECTURE, CONSTRAINTS]
Produce your top 2-3 recommended approaches with:
1. How it works  2. Pros/cons  3. Effort estimate  4. Risks
Be opinionated — recommend the best approach and explain why." < /dev/null || echo "CODEX_TIMEOUT: Codex did not respond within 600s" > "$CODEX_WORK/approach.md" &

# Codex Research (when task needs up-to-date info; web search is automatic — no flag)
timeout 600 codex exec --ephemeral --skip-git-repo-check \
  -o "$CODEX_WORK/research.md" \
  "Research current best practices for [TECHNOLOGY/PATTERN] as of 2026.
Latest versions, known limitations, community adoption, alternatives." < /dev/null || echo "CODEX_TIMEOUT: Codex did not respond within 600s" > "$CODEX_WORK/research.md" &

wait  # Wait for all Codex tasks to complete
```

**When to use plugin vs raw exec**: Plugin commands are preferred for single challenger/research tasks (structured output, job tracking). Use raw `codex exec` when running 3+ parallel tasks in a batch or when custom brief files with skill injection are needed.

#### Spawning Antigravity (agy) Analyst (MEDIUM+ — in parallel with Claude and Codex agents)

Check `agy` availability first: `command -v agy`. If unavailable, skip and note the gap.

`agy -p` returns **plain text on stdout** — the lead parses the text reply, not JSON fields.
Raise `--print-timeout` above the 5m default for long analyses. Append a `served_by` probe
line to the prompt and capture it — self-reported model identity is unreliable.

**STDIN RULE (root-caused 2026-06-05, #135):** headless `agy` MUST have stdin closed or piped —
`< /dev/null` on every call. agy reads non-TTY stdin until EOF *before* the model call; in
background/harness shells stdin never EOFs, so agy hangs forever producing 0 bytes and
`--print-timeout` never fires (it only guards the print phase). Also wrap in a shell `timeout`.

Prompt size is NOT a factor (verified: 30-char prompt hung; 11KB prompt with `< /dev/null`
answered in 9s).

**SANDBOX RULE (S052 rogue-commit incident, #157):** the agy analyst is a READ-ONLY role — ALWAYS
invoke it with `--sandbox`. agy has write/shell/git tools by default; in S052 an un-sandboxed
"analyst" auto-authored and git-committed broken code mid-design (HARD-GATE violation). Codex is
unaffected (it already runs `-s read-only`). FLAG ORDER (root-caused 2026-07-02): `--sandbox` and
every other flag BEFORE `-p`, prompt LAST — `agy -p --sandbox "X"` silently runs UN-sandboxed
with the literal prompt `--sandbox` and discards "X" (agy then improvises from implicit memory —
the "does work instead of consulting" failure mode). Scope caveat (verified 2026-07-02, 1.0.15):
`--sandbox` constrains shell/git only, NOT native file writes — prefer piping content over
`--add-dir` on a writable repo, open the prompt with "Advisory only — do not modify any files;
answer on stdout", and run `git status --short` afterwards if a repo was exposed.

```bash
# Antigravity (agy) Analyst — independent third-model analysis
timeout 600 agy --sandbox -p "You are an analyst for [TASK].
Project context: [KEY FILES, ARCHITECTURE, CONSTRAINTS]
Analyze: 1. Architecture trade-offs  2. Scalability limits  3. Security surface
4. What approaches work best at scale for this pattern?
Be specific and cite real-world precedents where possible.
At the very end print one line: SERVED_BY=<model-id-you-are-running-as>." < /dev/null

# For codebase context, add the relevant paths to the workspace with --add-dir:
# CAUTION: --sandbox does NOT gate native file writes into --add-dir trees — prefer piping;
# if you must --add-dir a writable repo, run `git status --short` afterwards and revert strays.
timeout 600 agy --sandbox --add-dir [PATHS] -p "Advisory only — do not modify any files; answer on stdout.
Review the codebase at [PATHS] for [TASK].
Focus on: cross-cutting concerns, hidden coupling, N+1 patterns, missing error boundaries." < /dev/null

# For multi-methodology brainstorming (frame the methodology in the prompt itself):
timeout 600 agy --sandbox -p "Brainstorm approaches for [TASK] using the Six Thinking Hats methodology —
work through White (facts), Red (intuition), Black (caution), Yellow (benefits),
Green (alternatives), and Blue (process) in turn, then summarise." < /dev/null
```

**When to use agy vs Codex**: `agy` is a useful independent third model for architecture analysis, codebase review (add paths with `--add-dir`), and multi-methodology brainstorming. Codex excels at focused code review, devil's advocate challenger work, and prototype exploration.

#### Converging Triple-Model Findings

When collecting results, the lead MUST:
1. Read Claude challenger output AND Codex challenger output (`$CODEX_WORK/challenger.md`) AND agy analyst output
2. Read Codex approach exploration (`$CODEX_WORK/approach.md`)
3. Identify where models **agree** (high confidence) vs **disagree** (needs deeper analysis)
4. Flag disagreements to the user: "Claude, Codex, and agy disagree on X — here are all perspectives"
5. Weight all model findings equally — each has different blind spots and strengths
6. agy findings that cite real-world precedents — flag these as evidence (and verify per Stage 1.5)

#### Codex Escalation (When Claude Is Stuck)

When Claude agents fail to solve a problem after 2+ attempts or enter circular reasoning:

**Primary: Use `/codex:rescue`** (managed job with resume capability):

```
/codex:rescue "Claude agents are stuck on [PROBLEM]. Tried: [APPROACHES]. Blocker: [ISSUE]. Need a fresh approach — challenge the assumptions that led to the dead end."
```

**Fallback: Raw `codex exec`** (for custom briefs):

```bash
CODEX_WORK=$(mktemp -d /tmp/codex-XXXXXXXXXX)

cat > "$CODEX_WORK/escalation-brief.md" << 'BRIEF'
# Escalation: Claude agents are stuck on [PROBLEM]

## What was tried
[LIST APPROACHES THAT FAILED AND WHY]

## The specific blocker
[DESCRIBE THE EXACT ISSUE]

## Project context
[KEY FILES, ARCHITECTURE]

## What we need
A fresh approach to solve this. Don't repeat what was already tried.
Think differently — challenge the assumptions that led to the dead end.
BRIEF

timeout 600 codex exec --ephemeral -C "$PROJECT_DIR" -s read-only \
  -o "$CODEX_WORK/escalation-result.md" \
  "Read $CODEX_WORK/escalation-brief.md and provide a fresh solution." < /dev/null || echo "CODEX_TIMEOUT: Codex did not respond within 600s" > "$CODEX_WORK/escalation-result.md"
```

### Escalation Termination

Max escalation chain: Claude 2 attempts -> Codex 1 attempt -> user.

If Codex escalation also fails or times out:
1. Present the problem to the user with ALL attempted approaches
2. Include what Claude tried, what Codex tried, and why both failed
3. Ask the user for direction
4. Do NOT retry automatically. Do NOT loop back to Claude.

### Step 3: Present Design

After convergence:
- Present design in sections scaled to complexity
- Ask after each section: "Does this look right so far?"
- Cover: architecture, components, data flow, error handling, testing approach, performance considerations
- **Always include a UX section** for UI-facing work
- **If `came_from_avengers`**: surface the `avengers_brief.dissent[]` entries **verbatim** in the presentation — attributed to the seat, with each entry's trip-wire. Do NOT summarize or drop them; the user judges the design with the deliberation's dissent in view (mirrors the founder minority-report surfacing).
- Be ready to revise based on user feedback

### Step 4: Write Design Doc

- Save to `docs/plans/YYYY-MM-DD-<topic>-design.md`
- Update `history.md` and `index.md`
- Shut down design exploration team (if created)

---

## Contract Map Generation (Step 8a)

### Step 8a.0: Emit + corroborate the classification artifact (S042 / #115)

BEFORE deciding whether to build a map, forge MUST write `.forge/classification.json` (schema `contract-classification.v1`) — the recorded classification that travels with the cycle, analogous to the signed contract map. This closes the bare-`Contract map: N/A` hole at the producer side (not just bob's front door).

The artifact states:
- `introduces_components`: `"yes" | "no"`
- `reason_code`: a value from the **closed enum** {`skill_text`, `doc_only`, `direct_bugfix`, `refactor`, `self_contained_meta_helper`, `sidecar_telemetry`, `agent_text`, `existing_component_extension`} — NOT free-text (free-text reasons are a loophole).
- `design_doc`, `planned_globs`, `evidence` (confirmed_positives / negatives / prose_only).

Forge may hand-write it, or derive a default via the helper:
```bash
python3 ~/.claude/skills/_meta/classify_emit.py "<project_root>" \
  --design-doc "<design-doc-path>" --classified-by forge_design \
  --files-from "<planned-file-touch-list>"
```

Then forge **locally runs `G_CLASSIFY` to fail-fast at design time** (catch a misclassification before bob is ever spawned):
```bash
python3 ~/.claude/skills/_meta/gates.py G_CLASSIFY "<project_root>" \
  --design-doc "<design-doc-path>" \
  --asserted "<N/A if introduces_components==no, else provided>" \
  --files-from "<planned-file-touch-list>"
```
- Exit 0 → classification corroborated; proceed.
- Exit 2 → the scan contradicts the artifact (named signals). Fix the design/classification before continuing; do NOT hand bob a false N/A.
- Exit 3 → ambiguous; resolve with the user before spawning bob.

The artifact is a CLAIM the gate re-derives and corroborates — never trusted (the threat model includes a buggy/drifting producer). `existing_component_extension` makes the Ship-of-Theseus case (appending component logic into existing allowed files) a *declarable, checkable* category rather than a silent dodge.

### Step 8a.1+: Build the signed contract map (component cycles only)

When a design introduces components (new services, modules, APIs, integration points), forge MUST produce a signed contract map BEFORE invoking the spec review (Step 8b) and before spawning bob.

Pure refactors, bugfixes, and single-file changes with no new components are exempt.

### Step 8a.1: Invoke component-contract-mapping

Invoke the `component-contract-mapping` skill with:

1. The draft design doc path
2. Relevant PROJECT.md and COMPONENT.md paths
3. The user's spoken intent from design dialogue

The skill will:
1. Extract components from the design discussion
2. Define types dictionary with semantic_type per field (from the v1 18-type registry)
3. Write `progress/contract-map.yaml` (single writer — only ever written here)
4. Run G2 validation locally by invoking `python -m gates G2 progress/contract-map.yaml`
5. Auto-render a markdown table into the design doc
6. Request forge to sign the map

If G2 validation fails, fix the design doc (not the YAML — the skill rewrites it from the design doc). Re-invoke the skill. Bob will refuse to execute without a valid signed contract map.

### Step 8a.2: Emit session material and sign

Forge is responsible for the session material and the signing payload.

```bash
# Create session material once per forge session (idempotent)
mkdir -p .forge
[[ -f .forge/session-id ]] || uuidgen > .forge/session

…(truncated)
