A MethodFactory Framework for AI-Assisted Development

F3: Foundation-First Framework

A structured methodology for building high-quality applications with Claude Code. Not just fast—intentional, maintainable, and production-ready.

The Problem: AI-assisted development makes it tempting to skip planning and "just start building"—and also skips the boring stuff: proper logging, error handling, and security. The result? Code that works in demos but fails in production.
The Solution: Foundation-First development that enforces intentional design, keeps human judgment in the loop, and builds production-ready code with security, logging, and error handling from day one.
1

FOUNDATION

Spec It + Plan It
Define Before You Build

2

IMPLEMENTATION

Build It ↔ Guide It
Human Judgment in the Loop

3

DOCUMENTATION

Document It
Maintainable Knowledge

Executive Summary

F3 (Foundation-First Framework) is a structured methodology for building production-ready applications with Claude Code. It solves the core problems of AI-assisted development: skipped planning, autonomous coding that goes off track, and code that works in demos but fails in production.

Note: While optimized for Claude Code, the core methodology is tool-agnostic and validated for use with other AI coding assistants (Copilot, Cursor, etc.).

🎯 What It Is

An Existing Framework Translation + three-area methodology with ready-to-use templates, prompts, and protocols that guide every Claude Code project from concept to production. Works within any existing tech stack.

⚠️ The Problems It Solves

  • AI tempts developers to skip planning → scope creep, rework
  • Autonomous coding goes off track → wasted effort
  • Context lost between sessions → repeated explanations
  • Missing logging, error handling, security, accessibility → production failures

✅ Why Use It

  • Intentional Design: Spec and plan before building
  • Human Oversight: Build ↔ Guide cycle keeps you in control
  • Persistent Context: Documentation survives session resets
  • Production-Ready: Security, logging, error handling, accessibility built-in

📦 What You Get

  • Complete document templates (CLAUDE.md, SPEC.md, PLAN.md, etc.)
  • Copy-paste prompts for every development phase
  • Production standards for security, logging, errors, accessibility
  • Self-correcting protocols that keep Claude on track

The Bottom Line

Without F3, Claude Code produces code fast but fragile. With F3, you get production-ready applications built with intentional design, continuous human oversight, and professional documentation—every time.

Project Structure

F3 creates a consistent documentation structure in every project. Your application code can be organized however you prefer.

F3 Project Structure
your-project/
├── F3_FRAMEWORK.md      # F3 hub — start here (routes to modules)
├── F3_CORE.md           # Methodology, standards, guardrails
├── F3_PROMPTS.md        # All Claude Code prompts
├── F3_TEMPLATES.md      # Document templates (CLAUDE.md, SPEC, etc.)
├── F3_SETUP.md          # Setup guides (new & existing projects)
├── F3_CHANGELOG.md      # Version history & roadmap
├── SPEC.md              # Project requirements
├── PLAN.md              # Architecture & implementation plan
├── CLAUDE.md            # Lean bootstrap — Claude Code
├── CURSOR.md            # Lean bootstrap — Cursor
├── GEMINI.md            # Lean bootstrap — Gemini CLI
├── CONTRIBUTORS.md      # Team roles & ownership registry       ← NEW v5.0.0
├── FIRST_RUN.md         # Bootstrap — written by installer, deleted on first ES  ← gitignored
├── f3-foundation/
│   ├── tools/
│   │   ├── setup-f3.js                   # F3 installer (self-contained — all framework files embedded)
│   │   ├── f3-audit.js                   # Existing Project Protocol — deep codebase audit
│   │   ├── generate-governance-report.js # Session governance report generator
│   │   └── uninstall-f3.js               # F3 removal tool — reverses the installer's changes
│   ├── compat/                          ← NEW v5.0.0
│   │   ├── README.md                     # Index of F3 compatibility guides
│   │   └── superpowers.md                # Running F3 alongside Superpowers (obra / Jesse Vincent)
│   └── scripts/
│       ├── load-context.sh               # On-demand context loader (macOS/Linux)
│       └── load-context.js               # On-demand context loader (Windows)
├── .codex/
│   └── AGENTS.md        # Lean bootstrap — Codex
├── .f3/
│   └── session.active   # Session presence marker               ← gitignored
├── .claude/
│   ├── settings.json    # Claude Code config (hooks + permissions)
│   ├── commands/f3/     # Slash commands — one file per /project:f3:[name]
│   │   ├── ss.md               # /project:f3:ss          — Session Start
│   │   ├── es.md               # /project:f3:es          — Session End (compiles commit/)
│   │   ├── doco.md             # /project:f3:doco        — Documentation Checkpoint
│   │   ├── fd.md               # /project:f3:fd          — Feature Discovery
│   │   ├── fp.md               # /project:f3:fp          — Feature Planning
│   │   ├── fi.md               # /project:f3:fi          — Feature Implementation
│   │   ├── fc.md               # /project:f3:fc          — Feature Complete
│   │   ├── audit.md            # /project:f3:audit       — Discovery Audit Checklist
│   │   ├── gr.md               # /project:f3:gr          — Governance Report
│   │   ├── archrebuild.md      # /project:f3:archrebuild — Weekly Layer 2 rebuild (Lead)
│   │   ├── crash.md            # /project:f3:crash       — Crash Recovery
│   │   ├── thrash.md           # /project:f3:thrash      — Thrash Detection
│   │   ├── reset.md            # /project:f3:reset       — Thrash Reset
│   │   └── update.md           # /project:f3:update      — F3 Version Update
│   └── hooks/
│       ├── f3-phase-gate.sh        # Foundation check (macOS/Linux) — blocks if SPEC/PLAN missing
│       ├── f3-phase-gate.js        # Foundation check (Windows/cross)
│       ├── f3-restart-gate.sh      # Restart Gate (macOS/Linux)
│       ├── f3-restart-gate.js      # Restart Gate (Windows/cross)
│       ├── f3-commit-gate.sh       # Commit Gate — enforcement only (macOS/Linux)
│       ├── f3-commit-gate.js       # Commit Gate — enforcement only (Windows)
│       ├── f3-thrash-detector.sh    # Thrash Detector (macOS/Linux)
│       ├── f3-thrash-detector.js    # Thrash Detector (Windows/cross)
│       ├── f3-first-run-loader.sh   # First-Run Loader (macOS/Linux) — injects FIRST_RUN.md
│       └── f3-first-run-loader.js   # First-Run Loader (Windows/cross)
├── .githooks/
│   └── pre-commit       # Universal Git commit gate — all editors
├── commit/              # Permanent session record ← NEW v5.0.0 (committed)
│   └── YYYY/
│       └── MM/
│           └── YYYY-MM-DD_[developer]_[hash].md   # ES commit document
├── docs/
│   ├── architecture.md  # System design
│   ├── api.md           # API contracts
│   ├── stack.md         # Tech stack details
│   ├── decisions.md     # Architecture Decision Records
│   ├── checkpoint.md    # Session intent — written at session OPEN     ← gitignored
│   ├── devlog.md        # Session logs (append-only)                    ← gitignored
│   ├── TASKS.md         # Developer task tracking               ← gitignored
│   ├── changelog.md     # Release history
│   ├── AUDIT.md         # Discovery audit — Existing Project Protocol only
│   ├── analysis/        # Scratch analysis files                ← gitignored
│   ├── migration/       # Developer briefs + upgrade scratch    ← gitignored
│   └── governance/      # Session governance reports (JSON + Markdown)
└── [your code here]     # Organize however you want
Key Rule
As long as a platform bootstrap (CLAUDE.md, CURSOR.md, .codex/AGENTS.md, or GEMINI.md) is in place, the F3_*.md modules are in the root, and /docs/ has the F3 files, organize your application code however you prefer. f3-foundation/ contains all F3 tooling — installer, audit, governance, and context loaders — cleanly separated from your project code.

New Project

Start a new project with F3 in two commands.

Automated Setup

Download setup-f3.js and place it at f3-foundation/tools/setup-f3.js inside your project folder — the installer expects to live there because every path it writes is relative to the project root. For a new project, you'll need to create the f3-foundation/tools/ folder first, then copy the file into it. The installer is self-contained — every other F3 file is embedded inside setup-f3.js, so you don't need to download the full distribution.

Terminal — from your new project root
# Create the tools folder and drop setup-f3.js into it
mkdir -p f3-foundation/tools
cp ~/Downloads/setup-f3.js f3-foundation/tools/setup-f3.js

# Run the installer — auto-detects project type
node f3-foundation/tools/setup-f3.js
claude

Open Claude, then send the message first-run as your first prompt. The f3-first-run-loader hook injects FIRST_RUN.md into Claude's context before Claude processes your message — Claude acknowledges the first-run session, reviews any audit findings, and proposes the next concrete step. The installer also:

What Files / Actions
Framework modules 6 F3_*.md files in project root
Platform bootstrap CLAUDE.md / CURSOR.md / .codex/AGENTS.md / GEMINI.md — lean, under 1,300 tokens
FIRST_RUN.md Bootstrap file — the f3-first-run-loader hook injects its contents into Claude's context before Claude processes the first user message. The installer tells the user to send first-run as their first prompt to trigger the protocol. Deleted by first /project:f3:es. Three variants: new project / existing project / upgrade.
CONTRIBUTORS.md Team role and ownership registry template
commit/ folder commit/YYYY/MM/ structure created — permanent session record folder
Hook scripts f3-phase-gate, f3-restart-gate, f3-commit-gate, f3-thrash-detector, f3-first-run-loader (.sh and/or .js)
Universal Git hook .githooks/pre-commit → auto-installed to .git/hooks/pre-commit
Configuration .claude/settings.json
Slash commands 14 files in .claude/commands/f3/ (includes archrebuild.md, audit.md, gr.md)
Gitignore Appends .claude/thrash-count, .f3/session.active, docs/checkpoint.md, docs/devlog.md, docs/TASKS.md, docs/analysis/, docs/migration/, FIRST_RUN.md

Existing project or upgrade? The installer detects this automatically. For an existing codebase with no F3 yet, it also runs f3-audit.js --quiet before writing FIRST_RUN.md, so Claude's first session opens with a pre-populated docs/AUDIT.md.

Upgrading from v4.x? Use node f3-foundation/tools/setup-f3.js --update — the safe upgrade path that preserves your customized CLAUDE.md, project docs, and settings while refreshing framework files, hooks, and writing an upgrade-variant FIRST_RUN.md. See Existing Projects → Path B for the full workflow.

Complete First-Session Workflow

New project — no application code exists yet. You're starting from a blank folder. F3 gets set up before a single line of your code is written. SPEC.md and PLAN.md are created through conversation, defining what you're about to build.

New Project — Full Sequence
# Step 0 — Create the tools folder and drop setup-f3.js into it
mkdir -p f3-foundation/tools
cp ~/Downloads/setup-f3.js f3-foundation/tools/setup-f3.js

# Step 1 — Install F3 into your project folder
node f3-foundation/tools/setup-f3.js

# Step 2 — Open Claude Code (or Cursor, Codex, Gemini)
claude

# Step 3 — Send the message "first-run" as your first prompt
# The f3-first-run-loader hook injects FIRST_RUN.md into Claude's context;
# Claude acknowledges the first-run session and guides you from there.

The installer writes FIRST_RUN.md to the project root and prints a banner with your next step. When you send first-run, the f3-first-run-loader hook injects FIRST_RUN.md into Claude's context — Claude then walks you through creating CLAUDE.md, initializing all /docs/ files, and the full Foundation setup. The hook becomes a silent no-op as soon as /project:f3:es deletes FIRST_RUN.md at first session close.

Or set up manually

Option B: Manual Setup

Steps: 1. Create project folder2. Add F3 files3. Add hooks & commands4. Start Claude Code5. Define what you're building6. Set up F3 docs
1

Create your project folder

Create a new folder for your project and open it in VS Code (or your preferred editor).

2

Add F3 module files to your project root

Download or copy all six F3_*.md files into your project folder: F3_FRAMEWORK.md (hub), F3_CORE.md, F3_PROMPTS.md, F3_TEMPLATES.md, F3_SETUP.md, and F3_CHANGELOG.md.

3

Add Claude Code hooks & slash commands

Create .claude/settings.json, three hook scripts, and the F3 slash commands. These mechanically enforce F3's Restart Gate, Commit Gate, and Thrash Detection — and give you shortcuts like /project:f3:ss instead of copy-pasting prompts.

.claude/settings.json
{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": "node .claude/hooks/f3-restart-gate.js" },
          { "type": "command",
            "command": "node .claude/hooks/f3-commit-gate.js" },
          { "type": "command",
            "command": "node .claude/hooks/f3-thrash-detector.js" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": "node .claude/hooks/f3-thrash-detector.js" }
        ]
      }
    ],
    "PostToolUseFailure": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": "node .claude/hooks/f3-thrash-detector.js" }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          { "type": "command",
            "command": "node .claude/hooks/f3-first-run-loader.js" }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command",
            "command": "node .claude/hooks/f3-first-run-loader.js" }
        ]
      }
    ]
  }
}

Then create the hook script at .claude/hooks/f3-restart-gate.js:

.claude/hooks/f3-restart-gate.js
#!/usr/bin/env node

// F3 Restart Gate — blocks server restarts without checkpointing
// Reads hook input from stdin (Claude Code passes JSON via stdin)
// Customize RESTART_PATTERNS for your stack

const RESTART_PATTERNS = [
  /npm run dev/i, /npm start/i, /node --watch/i,
  /flask run/i, /uvicorn/i, /manage\.py runserver/i,
  /docker.*(restart|up|down)/i, /kill/i, /taskkill/i
];

let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
  try {
    const data = JSON.parse(input);
    const command = data?.tool_input?.command || '';

    const isRestart = RESTART_PATTERNS.some(p => p.test(command));
    if (!isRestart) process.exit(0);

    const { execSync } = require('child_process');
    try {
      const diff = execSync('git diff --name-only',
        { encoding: 'utf8' });
      if (diff.includes('docs/checkpoint.md'))
        process.exit(0);
    } catch { /* git failed — block to be safe */ }

    process.stderr.write('BLOCKED: F3 Restart Gate\n');
    process.stderr.write(
      'Update docs/checkpoint.md and docs/devlog.md\n');
    process.stderr.write('before restarting.\n');
    process.exit(2);
  } catch { process.exit(0); }
});

The commit gate at .claude/hooks/f3-commit-gate.js:

.claude/hooks/f3-commit-gate.js
#!/usr/bin/env node

// F3 Commit Gate v5.0.0 — Claude Code variant
// PreToolUse hook — fires inside Claude Code sessions before git commit.
// The universal Git hook (.githooks/pre-commit) enforces the same check
// at actual commit time in every editor.
// Exit 2 = Claude Code blocking convention.

'use strict';

const { execSync } = require('child_process');
const fs = require('fs');

let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
  try {
    const data = JSON.parse(input);
    const command = data?.tool_input?.command || '';
    if (!/^git commit/i.test(command)) process.exit(0);

    let staged = '', unstaged = '';
    try {
      staged   = execSync('git diff --cached --name-only', { encoding: 'utf8' });
      unstaged = execSync('git diff --name-only',          { encoding: 'utf8' });
    } catch { process.exit(0); }

    const modified = staged + '\n' + unstaged;
    const missing  = [];

    if (fs.existsSync('docs/checkpoint.md') &&
        !modified.includes('docs/checkpoint.md'))
      missing.push('docs/checkpoint.md');

    if (fs.existsSync('docs/devlog.md') &&
        !modified.includes('docs/devlog.md'))
      missing.push('docs/devlog.md');

    if (missing.length === 0) process.exit(0);

    const SEP = '─'.repeat(50);
    const msg = [
      '', 'BLOCKED: F3 Commit Gate (Claude Code)', SEP, '',
      'Update before committing:', '',
      ...missing.map(f => `  • ${f}`), '',
      'Verify Doc Update Triggers:',
      '  API changed?          →  docs/api.md',
      '  Architecture changed? →  docs/architecture.md',
      '  Decision made?        →  docs/decisions.md',
      '  Dependency changed?   →  docs/stack.md', '',
      'Confirm Production Standards in changed components:',
      '  ☐ Logging  ☐ Error handling  ☐ Security  ☐ Accessibility',
      '', SEP, '',
    ].join('\n');

    process.stderr.write(msg);
    process.exit(2);
  } catch { process.exit(0); }
});

And the thrash detector at .claude/hooks/f3-thrash-detector.js:

.claude/hooks/f3-thrash-detector.js
#!/usr/bin/env node

// F3 Thrash Detector — blocks after 3 consecutive
// failures until Issue Review Brief is generated
// OR counter is reset. Allows safe commands when
// blocked so Claude can generate the brief.

const fs = require('fs');
const COUNT_FILE = '.claude/thrash-count';
const BRIEF = 'docs/issue-review-brief.md';
const MAX_FAILURES = 3;
const SAFE = [
  /^(cat|head|tail|less|more|wc|grep|find|ls|pwd)(\s|$)/i,
  /^git(\s|$)/i, /docs\//i,
  /issue-review-brief/i, /thrash-count/i
];

let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
  try {
    const data = JSON.parse(input);
    const event = data?.hook_event_name || '';
    const cmd = data?.tool_input?.command || '';
    let count = 0;
    try {
      count = parseInt(
        fs.readFileSync(COUNT_FILE, 'utf8')) || 0;
    } catch {}

    switch (event) {
      case 'PostToolUseFailure':
        count++;
        fs.writeFileSync(COUNT_FILE, String(count));
        if (count >= MAX_FAILURES) {
          process.stderr.write(
            `WARNING: ${count} consecutive failures.\n`);
          process.stderr.write(
            'Generate an Issue Review Brief.\n');
        }
        break;
      case 'PostToolUse':
        fs.writeFileSync(COUNT_FILE, '0');
        break;
      case 'PreToolUse':
        if (count >= MAX_FAILURES) {
          try {
            const stat = fs.statSync(BRIEF);
            const age = (Date.now() - stat.mtimeMs) / 1000;
            if (age < 300) {
              fs.writeFileSync(COUNT_FILE, '0');
              process.exit(0);
            }
          } catch {}
          // Allow safe commands + reset
          if (SAFE.some(p => p.test(cmd)))
            process.exit(0);
          process.stderr.write(
            'BLOCKED: F3 Thrash Detection\n');
          process.stderr.write(
            `${count} consecutive failures.\n`);
          process.stderr.write(
            'Generate Issue Review Brief or reset:\n');
          process.stderr.write(
            'echo 0 > .claude/thrash-count\n');
          process.exit(2);
        }
        break;
    }
    process.exit(0);
  } catch { process.exit(0); }
});

All files are committed to git. Add .claude/thrash-count to .gitignore (runtime state). macOS/Linux users: bash versions of both scripts are available — see Restart Gate and Thrash Detection for details.

Add F3 slash commands: Create .claude/commands/f3/ and add one .md file per command. Each file contains the prompt text from All Prompts. See Slash Commands for the full directory structure and file contents.

.claude/commands/f3/  ← add: ss.md, es.md, doco.md, fd.md, fp.md, fi.md, fc.md, crash.md, thrash.md, reset.md, update.md

Once added, type /project:f3:ss in Claude Code to start a session, /project:f3:es to end one, etc. The f3/ subdirectory namespaces the commands so they don't collide with Claude Code built-ins.

4

Start Claude Code

Open a terminal in your project folder and run:

claude
5

Tell Claude what you want to build

Use this prompt to kick off the F3 workflow:

New Project Prompt
Read @F3_FRAMEWORK.md

I want to build [DESCRIBE YOUR PROJECT].

Let's use F3 to do this right. Start by helping me create 
SPEC.md - ask me questions one at a time to understand 
what I'm building.
6

Set up F3 documentation system

Once SPEC.md and PLAN.md are complete, set up the full F3 documentation structure:

Initial Setup Prompt
Read @F3_FRAMEWORK.md and @F3_TEMPLATES.md, then set up the F3 
documentation system.

Using the templates in @F3_TEMPLATES.md, create:

1. CLAUDE.md in the project root
   - Use the CLAUDE.md template
   - Fill in project name, tech stack, current phase
   - Keep all F3 standard sections (Session Protocol, etc.)

2. /docs directory with:
   - architecture.md (system design)
   - api.md (API contracts, if applicable)
   - stack.md (tech stack details)
   - decisions.md (Architecture Decision Records)
   - checkpoint.md (session intent — written at session open)
   - devlog.md (session logs)
   - TASKS.md (task tracking — gitignored)
   - changelog.md (release history)

Pull information from SPEC.md and PLAN.md to populate these files.
Mark anything needing my input with [TODO: ...]

What Happens Next

Claude will guide you through the F3 workflow:

1 Foundation

Claude asks questions to understand your project, then creates SPEC.md (requirements) and PLAN.md (architecture).

2 Implementation

Claude builds components one at a time, stopping after each for your review. You guide, Claude corrects, you approve.

3 Documentation

Claude creates and updates documentation as you build—architecture, API, decisions, devlog—so context is never lost.

💡 The Key Insight
F3 keeps you in control. Claude proposes, you approve. Every component gets reviewed before Claude moves on. This prevents Claude from going off-track on your project.

Existing Projects — 4-Phase Protocol

The F3 Existing Project Protocol is the structured onboarding path for inherited, undocumented, or production codebases. It runs in four phases, each with a formal approval gate. Automated scanning is included — no manual checklist required.

Two paths to the same output: Run node f3-foundation/tools/f3-audit.js for fully automated execution, or use the Upgrade Existing Project Prompt to run interactively in Claude Code. Both produce all four phase outputs and pause for approval between phases.

Automated Update

Download setup-f3.js, place it at f3-foundation/tools/setup-f3.js in your project, run it, and open Claude. The installer auto-detects the existing codebase, runs f3-audit.js --quiet automatically, and writes an existing-project FIRST_RUN.md that includes the audit summary. Claude reads it at first session open and self-directs the full onboarding sequence — no manual steps required. The installer is self-contained: every other F3 file is embedded inside setup-f3.js, so you only need that one file.

Path A — F3 not yet installed
# Create the tools folder and drop setup-f3.js into it
mkdir -p f3-foundation/tools
cp ~/Downloads/setup-f3.js f3-foundation/tools/setup-f3.js

# Install F3 — auto-detects existing codebase, runs audit, writes FIRST_RUN.md
node f3-foundation/tools/setup-f3.js

# Open Claude, then send the message "first-run" to trigger the onboarding sequence
claude
# (in Claude, type:) first-run
Path B — F3 already installed, upgrading to v5.x
# f3-foundation/tools/ already exists from the previous install —
# just copy the new setup-f3.js over the old one.
cp ~/Downloads/setup-f3.js f3-foundation/tools/setup-f3.js

# Use --update — preserves your customized CLAUDE.md, docs/, and project content.
# Overwrites framework files, hooks, and settings; writes upgrade-variant FIRST_RUN.md.
node f3-foundation/tools/setup-f3.js --update

# Open Claude, then send "first-run" to trigger the v5.x upgrade sequence
claude
# (in Claude, type:) first-run

Why --update? A bare setup-f3.js is a fresh install — it replaces CLAUDE.md, settings, and hooks wholesale. The --update flag is the safe upgrade path: it refreshes framework files and hooks, preserves your project-specific content, and writes an upgrade-variant FIRST_RUN.md, CONTRIBUTORS.md, and commit/YYYY/MM/ for parity with a fresh install. If you run the bare installer on a project that already has F3, it will detect the existing install and direct you to re-run with --update.

What Happens in the First Session

After the installer runs, Claude's first session is fully self-directed via FIRST_RUN.md. The existing-project variant instructs Claude to:

  1. Read docs/AUDIT.md — pre-populated by the installer's automatic f3-audit.js --quiet pass
  2. Create CLAUDE.md and all /docs/ files from F3 templates, populated from codebase analysis
  3. Build a retroactive SPEC.md and PLAN.md from what's already been built
  4. Seed docs/TASKS.md with Critical and High findings from AUDIT.md
  5. Pause for your review and approval before proceeding to the Build phase

FIRST_RUN.md is deleted automatically by /project:f3:es at the end of the first session.

Existing Project — Full Sequence
# Step 0 — Create the tools folder and drop setup-f3.js into it
mkdir -p f3-foundation/tools
cp ~/Downloads/setup-f3.js f3-foundation/tools/setup-f3.js

# Step 1 — Run the installer (auto-detects existing codebase)
node f3-foundation/tools/setup-f3.js
# Runs f3-audit.js --quiet automatically
# Writes FIRST_RUN.md with audit summary baked in
# Creates commit/YYYY/MM/, CONTRIBUTORS.md, updates .gitignore

# Step 2 — Open Claude
claude

# Step 3 — Send the message "first-run" as your first prompt
# The f3-first-run-loader hook injects FIRST_RUN.md into Claude's context.
# Claude acknowledges the first-run session and self-directs:
#   → Reviews docs/AUDIT.md findings
#   → Creates CLAUDE.md + all docs/ files from templates
#   → Builds retroactive SPEC.md + PLAN.md
#   → Seeds TASKS.md with Critical/High audit findings
#   → Pauses for your approval before Build phase begins

After first-session approval and all four phase gates are completed, the project is F3-compliant and the standard Build ↔ Guide cycle begins.

CommandWhat It DoesWhen to Run
setup-f3.jsFresh install — auto-detects project type (new / existing). Deploys framework files, hooks, config, creates commit/, writes FIRST_RUN.md and CONTRIBUTORS.md. Runs f3-audit.js --quiet automatically on existing codebases. Detects prior F3 installs and directs you to --update.First install on new or existing codebase
setup-f3.js --updateSafe upgrade path — refreshes framework files and hook scripts, merges .claude/settings.json, trims CLAUDE.md to lean format, and writes upgrade-variant FIRST_RUN.md + CONTRIBUTORS.md + commit/YYYY/MM/. Preserves your customized CLAUDE.md, docs/, and project content. Prompts before overwriting locally modified hooks.Upgrading a project already running a previous F3 version
f3-audit.jsFull 4-phase audit — scans codebase, produces Foundation documents. Pauses for approval between phases.Existing projects — run manually for a full interactive audit after initial install
f3-audit.js --reauditDelta re-audit — appends to existing AUDIT.mdQuarterly, after major releases, new developer onboarding
f3-audit.js --phase NSingle-phase execution — re-run one phase independentlyWhen re-running a specific phase after review
New projects skip f3-audit.js entirely. The installer detects a new project and writes a new-project FIRST_RUN.md — no audit scan runs. Claude builds SPEC.md and PLAN.md from scratch through conversation. For existing codebases, run setup-f3.js — the audit runs automatically.

First Run Project Audit

Phase 1 (Discovery Audit) performs automated scanning across seven categories. Every finding is rated Critical / High / Medium / Low. The output is docs/AUDIT.md — the document a security auditor, new CTO, or compliance reviewer sees on day one.

CategoryWhat Gets DetectedTools Used
Security Hardcoded API keys, passwords, tokens in source files; tracked .env files in git; SQL injection via string concatenation; missing auth/authz on sensitive routes Pattern matching across all source files
Accessibility div/span used as buttons; images missing alt; form inputs without labels; missing <main> / <nav> landmarks; aria-hidden on interactive elements Static HTML/JSX analysis; axe-core and pa11y detected if installed
Dead Files Source files with no detected importers — components, routes, utilities, CSS files that are never referenced Import graph analysis across all JS/TS/JSX/TSX files
Dependencies Known CVEs by severity; packages outdated by 2+ major versions; unlicensed or license-conflict packages npm audit · pip-audit · composer audit · bundle-audit — graceful fallback if not installed
Docs Gaps Missing README; no .env.example; no architecture documentation; API endpoints with no docs; components with no description File presence and content checks
Version Control .gitignore gaps; .env files tracked in git; large binary files committed; stale unmerged branches git ls-files, git diff, git branch
Production Standards Presence of logging calls; error handling patterns; test files — each confirmed as found / sparse / absent Pattern matching across source files; test file count

Three annotation flags are used throughout AUDIT.md when the script cannot determine ground truth from static analysis alone:

  • [INFERRED — REQUIRES CONFIRMATION] — conclusion drawn from code that needs developer verification before becoming a guardrail
  • [CONTRADICTION — REQUIRES DECISION] — two conflicting patterns found; developer must decide which to standardize
  • [UNKNOWN — REQUIRES INVESTIGATION] — genuinely unknowable from static analysis; becomes a first-priority TASKS.md item

Automated Script

Terminal
node f3-foundation/tools/f3-audit.js              # Full 4-phase audit
node f3-foundation/tools/f3-audit.js --phase 1    # Phase 1 only (Discovery Audit)
node f3-foundation/tools/f3-audit.js --reaudit    # Delta re-audit against existing AUDIT.md
node f3-foundation/tools/f3-audit.js --help       # Usage reference

Phase 1 — Discovery Audit → docs/AUDIT.md

Automated scanning across 7 categories. Developer reviews and approves AUDIT.md before Phase 2 begins.

CategoryWhat Gets Scanned
SecurityHardcoded secrets, API keys, SQL injection patterns, tracked .env files, auth gaps
Accessibilitydiv-buttons, missing alt attributes, unlabeled inputs, missing landmarks (static HTML/JSX analysis)
Dead FilesImport graph analysis — files with no detected importers
Dependenciesnpm audit, pip-audit, composer audit, bundle-audit — graceful fallback
Docs GapsREADME, API docs, architecture docs, .env.example — presence and completeness check
Version Control.gitignore gaps, committed secrets, large binaries, stale branches
Production StandardsEvidence of logging, error handling, test files

Every finding is rated Critical / High / Medium / Low. Three annotation flags are used throughout AUDIT.md:

  • [INFERRED — REQUIRES CONFIRMATION] — conclusions drawn from code analysis that need developer verification before becoming guardrails
  • [CONTRADICTION — REQUIRES DECISION] — conflicting patterns found in the codebase that must be resolved before Phase 2
  • [UNKNOWN — REQUIRES INVESTIGATION] — genuinely unknowable from static analysis alone

Phase 2 — Retroactive Foundation → SPEC.md + PLAN.md

Retroactive SPEC.md documents what the project does — not what was originally planned. Retroactive PLAN.md documents the architecture as it exists, including inconsistencies and technical debt flagged in Phase 1. A minimum quality bar applies: at least 3 core features with acceptance criteria in SPEC.md, and all active API endpoints listed in PLAN.md. Items that genuinely cannot be determined are marked [UNKNOWN — REQUIRES INVESTIGATION] and become first-priority TASKS.md items.

Phase 3 — Documentation Build → all 8 docs/ files

Populates the full F3 documentation system from codebase analysis. All 8 files are created from actual content — not empty templates. Inferred architectural decisions are marked [RETROACTIVE ADR] in docs/decisions.md. docs/todo.md is seeded with Critical + High findings from AUDIT.md.

Phase 4 — Risk Summary → docs/TASKS.md

Translates AUDIT.md findings into a prioritized remediation backlog. Each task includes: severity-based priority, time estimate, exact files to touch, acceptance criteria, and a test step. This TASKS.md becomes the first build queue — Critical and High items are worked before any new features are added.

Re-Audit Protocol

AUDIT.md is a permanent record. Re-audits append a delta report — resolved findings, new findings, and unresolved escalations — without overwriting the original. Recommended cadence: after every major release, every new developer onboarding, and at minimum quarterly.

Terminal
node f3-foundation/tools/f3-audit.js --reaudit

After All 4 Phases: F3-Compliant

A project that has completed all four phases has: docs/AUDIT.md (permanent discovery baseline), SPEC.md + PLAN.md (retroactive Foundation), all 8 docs/ files populated, and docs/TASKS.md (prioritized remediation backlog). The project enters the standard F3 Build ↔ Guide cycle. Phase Gate hooks enforce Foundation compliance going forward.

Context Loader

CLAUDE.md is intentionally lean — under 1,300 tokens — so Claude Code reads it on every session start without burning context budget. The context loader is how you pump full framework detail into Claude's context on demand, only when you need it.

Two commands, same modules — pick based on your platform:

f3-foundation/scripts/load-context.sh [module]      # macOS/Linux
node f3-foundation/scripts/load-context.js [module]  # Windows / cross-platform

First Session — Pick Your Onboarding Path

After running the installer and opening Claude Code, the first thing you'll do is run one of these two modules. Which one depends on your project state:

If your project is… Run this module What Claude does next
A blank folder — nothing built yet new-project Creates CLAUDE.md + all /docs/ files from F3 templates, customized for your project
An existing codebase — code already written, F3 being adopted mid-project existing-project Runs the 4-phase audit: assess codebase → create retroactive SPEC.md → create retroactive PLAN.md → set up F3 docs

After the module prints its output, tell Claude: "Read what was just printed and [set up F3 for this project / begin the existing project audit]."

All Modules

Use these any time Claude needs full detail on a topic — mid-session, at the start of a complex task, or when Claude's responses suggest it's working from incomplete context.

Module Approx. tokens When to use
new-project ~500 First session on a brand-new project — tells Claude how to create CLAUDE.md and /docs from templates
existing-project ~2K First session on an existing codebase — loads the 4-phase Existing Project Protocol for retroactive documentation
guardrails ~2K When Claude needs full G-01 through G-10 text — e.g. before a complex session or when a guardrail is being misapplied
production-standards ~1.5K When building security-sensitive, accessibility-critical, or compliance-relevant features and you want Claude to apply every standard explicitly
prompts ~6K When you need the full prompts library — equivalent to reading F3_PROMPTS.md; use when slash commands aren't available
templates ~5.5K When setting up or rebuilding docs — loads complete CLAUDE.md, SPEC.md, and all /docs/ templates so Claude can populate them accurately
framework-translation ~1.5K Before running the Existing Framework Translation — loads the 11-category walkthrough so Claude captures your stack's DNA accurately
governance varies Loads the most recent governance report into context — useful when reviewing compliance at session start or sharing with a stakeholder
setup ~6K Full F3_SETUP.md — use when troubleshooting installation or onboarding a new team member who needs complete setup context
all ~22K Loads F3_CORE + F3_PROMPTS + F3_TEMPLATES in one pass — use sparingly; only when starting a complex session that will touch every part of F3

Run node f3-foundation/scripts/load-context.js with no arguments to print the full module list and token estimates.

Removing F3 from a Project

To remove all F3 files from a project, run the uninstaller from the project root. It backs up customized files before removing anything and never touches your project content.

Terminal
node f3-foundation/tools/uninstall-f3.js              # Interactive uninstall
node f3-foundation/tools/uninstall-f3.js --dry-run    # Preview what would be removed
node f3-foundation/tools/uninstall-f3.js --force      # Skip per-step confirmations
node f3-foundation/tools/uninstall-f3.js --help       # Full usage reference
Always run --dry-run first. It shows you exactly what will be removed without touching anything. Confirm the list looks right, then run without the flag.

What Gets Removed

CategoryFiles / DirectoriesNotes
Framework modules F3_FRAMEWORK.md, F3_CORE.md, F3_PROMPTS.md, F3_TEMPLATES.md, F3_SETUP.md, F3_CHANGELOG.md Safe to remove — F3 owns these entirely
Platform bootstraps CLAUDE.md, CURSOR.md, GEMINI.md, .codex/AGENTS.md Backed up to .f3-backup/ before removal
Claude Code settings .claude/settings.json Backed up to .f3-backup/ before removal
Hook scripts .claude/hooks/ — f3-phase-gate, f3-restart-gate, f3-commit-gate, f3-thrash-detector, f3-first-run-loader (.sh and .js) All F3-created — safe to remove
Slash commands .claude/commands/f3/ — all 14 command files All F3-created — safe to remove
Directories tools/, tools/, scripts/, f3-foundation/compat/ Removed entirely — all contents are F3 files
Universal Git hook .git/hooks/pre-commit Only removed if it's the F3 version — custom hooks are left alone
.gitignore .claude/thrash-count entry F3-added entry removed; rest of .gitignore untouched

What Is Never Touched

Files / DirectoriesWhy
SPEC.md, PLAN.mdYour project Foundation documents — not F3 files
docs/Your entire documentation directory — session logs, architecture docs, ADRs
Your application codeF3 never touches src/, app/, or any application directory
.git/Your git history is never modified (only the hook file may be removed)

Backups

Customized files — platform bootstraps and .claude/settings.json — are copied to .f3-backup/ in the project root before being removed. The backup directory is safe to delete once you have confirmed nothing important was lost. It is not created during --dry-run.

After Uninstalling

Your project retains all documentation produced during F3 use — SPEC.md, PLAN.md, docs/AUDIT.md, and the full docs/ directory. These are your project's permanent record, independent of the framework. To reinstall F3 at any time, run node f3-foundation/tools/setup-f3.js again.

F3 Governance Report

The F3 Governance Report is a machine-readable JSON + human-readable Markdown record generated at session close. Every component changed. Every Production Standards check result per pillar. Every architectural decision. Deferred items listed explicitly. The organizational accountability deliverable that no other AI development framework produces.

Two ways to generate: The script (node f3-foundation/tools/generate-governance-report.js) reads your docs/ files and produces a structural report — works without Claude, fully automatable. The slash command (/project:f3:gr) generates a richer report using Claude's complete session knowledge — it knows exactly which Production Standards checks passed, what was deferred, and why.

Generating a Report

Terminal
# Both JSON + Markdown (default)
node f3-foundation/tools/generate-governance-report.js

# Format options
node f3-foundation/tools/generate-governance-report.js --format json   # JSON only
node f3-foundation/tools/generate-governance-report.js --format md     # Markdown only

# List existing reports
node f3-foundation/tools/generate-governance-report.js --list

# In Claude Code (richer — uses full session context)
/project:f3:gr

Output is written to docs/governance/YYYY-MM-DD-HHMM.json and docs/governance/YYYY-MM-DD-HHMM.md. The directory is created automatically on first run.

What the Report Contains

SectionJSON fieldContents
Report metadata report Generated timestamp, project name, F3 version, schema version
Session summary summary Components completed, decisions recorded, blockers, open/completed/blocked tasks
Changes changes Each component with: timestamp, files changed, Production Standards result per pillar (passed / deferred / not_applicable), SPEC and PLAN coverage flags
Decisions decisions All ADRs from docs/decisions.md — ID, date, one-sentence decision, retroactive flag
Production Standards production_standards_summary Per-pillar roll-up across all session components: all_passed / some_deferred / not_assessed
Compliance compliance All changes in SPEC? In PLAN? Docs current? Deferred items listed explicitly — no hidden gaps
Audit status audit_summary If docs/AUDIT.md exists: overall risk level, open Critical/High count, last audit date
Git activity git Recent commit count, last commit message

Governance Statement

The Markdown report ends with a Governance Statement — one plain-language paragraph a CTO or security auditor can read without F3 knowledge. It summarizes what changed, whether Production Standards were met, what was deferred, and the overall health of the project at the time of the report. This is the deliverable that justifies the session to anyone outside the development team.

Who Reads It

ReaderWhat They're Looking ForWhere It Is in the Report
Security auditorWere security checks performed? Any deferred vulnerabilities?Production Standards — security pillar; compliance.deferred_items
New CTOWhat changed and why? What architectural decisions were made?Changes array; decisions array; Governance Statement
AI assistant picking up the projectFull structured context to resume without re-reading everythingEntire JSON — machine-parseable session state
Project managerWere tasks completed? What's still open? Any blockers?summary; compliance; changes
Board / governance reviewIs this project being run with appropriate controls?Governance Statement; production_standards_summary; compliance

Load the governance report into Claude's context on demand using the governance module — see Context Loader reference for full module details.

Quick Start

You're installed and Claude is open. Here is what you do every day, which slash commands you'll actually use, and the three guardrails you'll hit first.

The Daily Session Loop

Every F3 session follows the same four steps. Each step has a slash command that owns it.

1

Start /project:f3:ss

Claude reads FIRST_RUN.md (if present), then checkpoint.md, TASKS.md, and the last devlog.md entry. You get a one-paragraph status: what you were working on, what's next, any blockers. State what you're taking on this session and Claude writes a fresh checkpoint.md.

2

Build /project:f3:fd/project:f3:fp/project:f3:fi

Feature Discovery defines the feature. Feature Planning turns it into component-level SPEC/PLAN entries. Feature Implementation runs the Build ↔ Guide cycle — Claude builds one component, stops, announces, asks; you review and approve; repeat. Never skip Discovery before Implementation — the phase-gate will refuse.

3

Close the feature /project:f3:fc

Once a feature is approved and tested, Feature Complete documents it while context is fresh — updates architecture.md, api.md, decisions.md, stack.md, and devlog.md per the Doc Update Triggers. Never defer this to session end; long sessions lose nuance to context compaction.

4

End /project:f3:es

Session End compiles the full session record into the commit/ folder, appends a timestamped devlog.md entry, overwrites checkpoint.md with final state, updates TASKS.md, and executes git commit. You do not commit separately.

Most-Used Slash Commands

F3 has 14 slash commands total (see Slash Commands). These 8 are the ones you'll actually reach for.

CommandWhen to useFrequency
/project:f3:ssFirst thing every sessionEvery session
/project:f3:esLast thing every session — compiles and commitsEvery session
/project:f3:fiStarting work on a planned feature (Build ↔ Guide)Multiple times per session
/project:f3:fcWrapping up a feature — runs all doc triggersAfter every feature
/project:f3:docoMid-session doc sync during long sessionsWhen session runs long
/project:f3:crashAfter a connection drop or terminal restartWhen things go wrong
/project:f3:thrashClaude stuck after 3 failed attempts — stops and writes Issue Review BriefWhen things go very wrong
/project:f3:resetUnblock after you've reviewed the Issue Review BriefAfter thrash

First-Time Run

Pick the path that matches your situation. Full instructions live in New Project and Existing Projects.

New project (blank folder)
node setup-f3.jsclaude → send first-run as your first message → Claude reads FIRST_RUN.md and guides you through SPEC.md, PLAN.md, and the first session. No further configuration.
Existing project (code already there)
node setup-f3.js --update (non-destructive) → audit runs automatically, producing docs/AUDIT.mdclaude → send first-run as your first message → FIRST_RUN.md walks you through the 4-phase Existing Project Protocol.

Three Rules You'll Hit Day One

F3 enforces these mechanically. You'll try to do something and be refused. Here is how to move forward.

The blockWhat's happeningHow to move forward
Phase Gate refuses to buildSPEC.md or PLAN.md missing. Claude will not implement features without a plan.Run /project:f3:fd (Feature Discovery) to draft, then /project:f3:fp (Feature Planning) to update PLAN.md. Then retry implementation.
Restart Gate refuses server restartcheckpoint.md has not been updated. Server restarts drop Claude's context — unsafe without saving state first.Update checkpoint.md with current intent and devlog.md with what you are about to do. Then retry the restart.
Thrash Detector blocks everythingThree consecutive failures on the same problem. Continuing makes it worse — each attempt mutates the code around the original issue.Do not try another approach. Run /project:f3:thrash to generate an Issue Review Brief, share it with a fresh advisor (another LLM conversation or a senior engineer), then /project:f3:reset with their approach.

Where to Find What You Need

I want to...Go to
Install F3 on a new or existing projectNew Project · Existing Projects
Find a specific promptPrompts Library
Understand the methodology in depthThe F3 Process
Look up what a file is forFile Glossary
Something refuses or something is brokenTroubleshooting

Functionality Discovery

Before improving or migrating a piece of functionality, understand it completely. These three prompts peel back the onion on a specific area of an existing project — producing an architecture reference, an architecture brief structured for FDS/TDS documentation, and a developer task brief ready for execution.

Run these in sequence. Each stage reads the previous stage's output as its primary input. Nothing is re-interpreted from the codebase after Stage 1.

Stage Output Location Purpose
Stage 1 Architecture Reference docs/analysis/[name]-architecture-reference.md Deep codebase scan — source of truth for all subsequent stages
Stage 2 Architecture Brief docs/analysis/[name]-architecture-brief.md Structured to feed FDS and TDS — written for an architect
Stage 3 Developer Brief docs/migration/[name]-developer-brief.md Task lists by component — ready for developer execution
Prerequisites: F3 is installed and the project audit (f3-audit.js) has been run. The docs/analysis/ and docs/migration/ directories are created automatically when Claude saves each output file.

Stage 1 — Architecture Reference

Existing Projects

Use when: Starting a functionality discovery session. Run this first against the codebase. The output becomes the input for both Stage 2 and Stage 3 — do not proceed until Stage 1 is complete and reviewed.

What it produces: A comprehensive architecture reference covering system context, all files involved, business rules, the combined scenario (how all sub-systems work together in a single real-world transaction), data model, integration boundaries, and flagged concerns. Saved to docs/analysis/.

Stage 1 — Architecture Reference Prompt
I want to document the current state of [FUNCTIONALITY NAME] in this
project before proposing any changes.

This is Stage 1 — Architecture Reference. Understand and document
what exists today. No migration proposals, no recommendations. Facts only.

Replace [FUNCTIONALITY NAME] with the specific area you are documenting.
If you know where it lives, add: "Start your search in [path/to/area]"

---

**Step 1: System Context**
Before touching files, establish the big picture:
- What is this functionality and what business purpose does it serve?
- What triggers it? (user action, event, API call, cron, message queue)
- What systems does it touch? (databases, external APIs, internal services,
  message queues, third-party platforms)
- What does it produce or change? (state changes, records created, emails
  sent, payments processed, etc.)
- What are the system boundaries — what is inside this functionality
  vs. what it depends on?

Write a 3–5 sentence system context summary before proceeding.

**Step 2: File Inventory**
Find every file, class, function, route, model, config, migration,
and test that is part of or directly touches [FUNCTIONALITY NAME]:
- Entry points (routes, endpoints, event listeners, CLI commands)
- Core logic (services, utilities, helpers, pipelines, processors)
- Data layer (models, schema, migrations, queries, stored procedures)
- Configuration (env vars, config files, feature flags, admin settings)
- Integration points (external service clients, XML/API contracts)
- Tests (what exists — note if none)

Present as a table: File path | Role in this functionality.
Group by category (Core Logic, Configuration, UI, etc.)

**Step 3: Business Rules**
Extract the explicit business rules from the code — not the implementation,
the rules the implementation enforces:
- Calculation rules (formulas, rates, thresholds, caps, rounding)
- Conditional rules (when X apply Y, if state = Z then...)
- Validation rules (what is required, what is rejected)
- Exception rules (what bypasses normal processing)
- State rules (what triggers state changes, what states are possible)

State each rule in plain language. Reference the file that enforces it.
Flag any rules that appear to be hardcoded vs. configurable.

**Step 4: Combined Scenario**
This is the most important step. Trace a single realistic transaction
that exercises ALL sub-systems simultaneously — the most complex real-world
case this functionality handles.

For example: an order with mixed taxable and non-taxable items,
a shippable product and a non-shippable item, a discount voucher applied,
and a non-standard tax jurisdiction.

Show:
- The exact sequence of operations in order
- Intermediate values at each calculation step
- Which component produces each value
- The final output and how each number was derived

This combined scenario is the definitive test of whether the architecture
is understood. If it cannot be traced end-to-end, flag what is missing.

**Step 5: Data Model**
For every database table, schema, entity, or data structure involved:
- Field names, types, constraints, defaults
- Relationships and foreign keys
- Custom fields, dynamic properties, or key-value stores
- What each field is set by, and when
- Indexes relevant to this functionality

**Step 6: Integration Contracts**
For every external system or service this functionality touches:
- What data is sent (format, fields, timing)
- What data is received (format, fields, error handling)
- What breaks if the contract changes
- Any known versioning or compatibility constraints

**Step 7: Flags and Concerns**
Without proposing fixes, document:
- [CONCERN] — patterns that are fragile, inconsistent, or risky
- [INFERRED] — behavior read from code that cannot be fully confirmed
- [UNCLEAR] — logic that is ambiguous or hard to follow
- [UNDOCUMENTED] — behavior with no tests or comments explaining intent
- [DEPENDENCY] — non-obvious things this functionality relies on
- [HARDCODED] — values that should be configurable but are not
- [DUPLICATE] — logic that exists in more than one place

**Step 8: Open Questions**
List every question that would need to be answered before a migration
or improvement could be safely planned. Be specific — not "how does
discount work" but "which campaign award types are currently active
in the database and what are their targeting rules?"

**Step 9: Save the output**
Save to: docs/analysis/[functionality-name]-architecture-reference.md

Include at the top:
- Date
- Scope (exactly what was included and excluded)
- Status: Stage 1 — Architecture Reference. Facts only.

Present the completed document for review before Stage 2 begins.

Stage 2 — Architecture Brief

Existing Projects

Use when: Stage 1 has been reviewed and approved. The architecture brief is written for an architect — not a developer. It is structured so sections can be lifted directly into a Functional Design Specification (FDS) and a Technical Design Specification (TDS) without requiring the architect to re-read the codebase.

What it produces: A structured brief with clearly separated FDS-facing content (business rules, user-facing behavior, acceptance criteria) and TDS-facing content (system architecture, technical constraints, integration contracts, risk surface). Saved to docs/analysis/.

Stage 2 — Architecture Brief Prompt
Read docs/analysis/[functionality-name]-architecture-reference.md

This is Stage 2 — Architecture Brief. Using only the Stage 1 reference
as your source, produce a structured brief written for an architect.
The brief must be structured so sections can be lifted directly into
an FDS (Functional Design Specification) and a TDS (Technical Design
Specification) without the architect needing to re-read the codebase.

Do not re-scan the codebase. Work from Stage 1 only. If Stage 1 is
missing information required for a section, flag it explicitly rather
than going back to the code.

---

**Section 1: Executive Summary**
3–5 sentences. What does this functionality do, why does it exist,
and what is its role in the larger system? Written for someone who
has never seen this codebase. No technical jargon — business language.

**Section 2: Key Facts** (FDS input)
A scannable reference block. Each fact on one line:
- What triggers this functionality
- Who or what it affects
- What it produces or changes
- What it does NOT do (explicit scope boundary)
- Platform/framework it runs on
- Any known limitations or constraints a business stakeholder should know

**Section 3: Business Rules** (FDS input)
Every business rule from Stage 1, stated in plain language suitable
for an FDS. Group by sub-system. Each rule should be:
- Stated as a declarative sentence ("Tax is calculated on...")
- Attributed to its source ("configured in X" / "hardcoded in Y")
- Flagged if it is assumed vs. confirmed

**Section 4: User-Facing Behavior** (FDS input)
What the user experiences at each stage of this functionality:
- What they see before, during, and after
- What triggers state changes from the user's perspective
- What feedback they receive (success, error, edge cases)
- What they cannot do (blocked states, validation messages)

**Section 5: Combined Scenario** (FDS + TDS input)
Reproduce the combined scenario from Stage 1 — the single realistic
transaction that exercises all sub-systems simultaneously.
This section serves both documents:
- FDS: the scenario as a narrative ("A member adds two products...")
- TDS: the scenario as a technical trace (exact sequence, values, components)

Present both versions.

**Section 6: System Architecture** (TDS input)
- System context diagram (ASCII) — this system and everything it connects to
- Component map — what each layer owns (platform vs. custom code)
- Key architectural decisions and their rationale
- What the platform provides vs. what custom code overrides
- Upgrade and maintainability implications of the current architecture

**Section 7: Integration Contracts** (TDS input)
For every external system:
- What is sent, in what format, when
- What is received, in what format
- What breaks if the contract changes
- Migration risk rating: Low / Medium / High

**Section 8: Data Model Summary** (TDS input)
The data model at architecture level — not field-by-field, but:
- Key entities and their relationships
- Custom fields or dynamic property stores
- Data that lives outside the primary database (config files, settings)
- What must be preserved exactly in any migration

**Section 9: Risk Surface** (TDS input)
Ranked list of the top concerns from Stage 1, grouped by category:
- Data integrity risks
- Integration risks
- Performance risks
- Business logic risks (silent failures, hardcoded values, etc.)
- Testing gaps

For each: one sentence description, one sentence on migration implication.

**Section 10: Open Questions**
Carry forward the open questions from Stage 1 plus any new ones
surfaced during brief preparation. Flag which questions must be
answered before migration can be planned vs. which can be deferred.

---

**Save the output**
Save to: docs/analysis/[functionality-name]-architecture-brief.md

Include at the top:
- Date
- Source: docs/analysis/[functionality-name]-architecture-reference.md
- Status: Stage 2 — Architecture Brief. Input for FDS and TDS.

Present the completed brief for review before Stage 3 begins.

Stage 3 — Developer Brief

Existing Projects

Use when: Stage 1 and Stage 2 have been reviewed and approved. The developer brief is not a narrative — it is a set of task lists organized by component. A developer picks up a task, executes it, and checks it off. Nothing to interpret.

What it produces: Task lists grouped by component, each task specifying the file, what to change, why, dependencies, and acceptance check. Saved to docs/migration/ because this is the point where discovery transitions into planned execution.

Stage 3 — Developer Brief Prompt
Read docs/analysis/[functionality-name]-architecture-reference.md
Read docs/analysis/[functionality-name]-architecture-brief.md

This is Stage 3 — Developer Brief. Using Stage 1 and Stage 2 as your
source, produce a task-oriented brief for a developer. This is not a
narrative document. It is a set of task lists. A developer picks up
a task, executes it, checks it off. No interpretation required.

Do not re-scan the codebase. Work from Stage 1 and Stage 2 only.

---

**Structure the output as follows:**

**1. Orientation Block**
5 lines maximum. The developer needs to know:
- What this functionality does (one sentence)
- Where it lives (primary directories/files)
- What platform/framework it runs on
- The single most important thing to understand before touching it
- Where to go if something is unclear (Stage 1 reference path)

**2. Component Map**
A flat list of every component involved, each with:
- Component name
- File path(s)
- One-line description of its role
- Dependencies (what it calls, what calls it)

No narrative. Reference only.

**3. Task Lists by Component**
For each component, a numbered task list. Each task must include:

  [ ] Task title (verb-noun: "Update", "Replace", "Remove", "Add")
      File: [exact file path]
      What: [exactly what to change — specific enough to act on]
      Why: [one sentence — the business or technical reason]
      Depends on: [task number(s) that must complete first, or "none"]
      Acceptance: [how to verify this task is complete]

Group tasks within each component in execution order.
Flag tasks that can run in parallel vs. tasks that must be sequential.

**4. Execution Order**
A numbered sequence showing which components to work on in what order,
and which tasks within each component must complete before the next
component begins. Flag any parallel tracks.

**5. Integration Checkpoints**
For every external system touched:
- What must be verified before touching integration code
- What must be tested after any change
- Who owns the external system (contact or team if known)
- Rollback procedure if integration breaks

**6. Acceptance Criteria**
The combined scenario from Stage 2, restated as a developer checklist:
- [ ] Given [condition], when [action], then [expected result]
One line per testable behavior. These are the pass/fail criteria
for the complete functionality, not individual tasks.

**7. Open Questions**
Carry forward any unresolved questions from Stage 1 and Stage 2
that a developer would need answered before starting work.
Flag which questions block specific tasks.

---

**Save the output**
Save to: docs/migration/[functionality-name]-developer-brief.md

Include at the top:
- Date
- Source: Stage 1 + Stage 2 reference paths
- Status: Stage 3 — Developer Brief. Ready for execution.

Present the completed brief for review.

Claude Code Implementation Prompts

Copy and paste these prompts into Claude Code. These assume the F3_*.md module files are in your project root.

Upgrade Existing Project to F3 Prompt

Setup

Use when: You have an existing project that has never used F3 and you want to run the full 4-phase Existing Project Protocol interactively in Claude Code. For automated execution, run node f3-foundation/tools/f3-audit.js instead.

Prompt
Read @F3_CORE.md section "EXISTING PROJECT PROTOCOL — 4-Phase Deep Buildout" 
and @F3_TEMPLATES.md, then execute all four phases for this project.

Each phase pauses for my approval before proceeding to the next.

---

PHASE 1: Discovery Audit → docs/AUDIT.md

Analyze this codebase and produce docs/AUDIT.md using the AUDIT.md 
template from @F3_TEMPLATES.md. Cover all seven audit categories:

1. Security — hardcoded secrets, exposed endpoints, unvalidated inputs
2. Accessibility — WCAG violations, missing ARIA, inaccessible elements
3. Dead Files — unused components, orphaned routes, unreferenced assets
4. Dependencies — outdated packages, vulnerabilities, license issues
5. Docs Gaps — missing README, undocumented APIs, no architecture docs
6. Version Control — .gitignore gaps, untracked sensitive files
7. Production Standards — evidence of logging, error handling, testing

Rate every finding: Critical / High / Medium / Low.
Flag inferred findings: [INFERRED — REQUIRES CONFIRMATION]
Flag contradictions: [CONTRADICTION — REQUIRES DECISION]
Flag unknowables: [UNKNOWN — REQUIRES INVESTIGATION]

Present AUDIT.md and wait for my approval before Phase 2.

---

PHASE 2: Retroactive Foundation → SPEC.md + PLAN.md

Create SPEC.md documenting what this application DOES (not what was planned).
Create PLAN.md documenting the architecture AS IT EXISTS.
Minimum bar: 3 core features with acceptance criteria; all active API 
endpoints listed. Mark genuinely unknowable items [UNKNOWN].
Present both and wait for my approval before Phase 3.

---

PHASE 3: Documentation Build → all 8 docs/ files

Populate the full F3 documentation system from codebase analysis.
No empty templates — real content only.
Inferred decisions marked [RETROACTIVE ADR] in decisions.md.
todo.md seeded with Critical + High findings from AUDIT.md.
Present summary and wait for my approval before Phase 4.

---

PHASE 4: Risk Summary → docs/TASKS.md

Generate docs/TASKS.md from AUDIT.md findings.
Priority: Critical → High → Medium → Low.
Each task: time estimate, exact files, acceptance criteria, test step.
Present TASKS.md and wait for my approval.

---

After all four phases:
1. List all files created or updated
2. Summarize key findings from AUDIT.md
3. List all flags requiring my decision ([INFERRED], [CONTRADICTION], [UNKNOWN])
4. Recommended first 3 tasks from TASKS.md
5. Confirm project is now F3-compliant

Discovery Audit Checklist Prompt

Existing Projects

Use when: Running Phase 1 of the Existing Project Protocol interactively in Claude Code. Output saved as docs/AUDIT.md.

Script vs. prompt — which to use? They do different things and work best in sequence:

Tool What it does What it can't do
f3-audit.js
Run first
Deterministic filesystem + code scan. Checks F3 file presence, phase gate status, security patterns, dead files. No Claude context consumed. Runs in CI. Produces objective facts. Can't make judgment calls — it finds what's there, not what it means. Won't evaluate whether a SPEC.md is well-written or whether an architecture matches F3 intent.
This prompt
Run second
Claude reads and understands the codebase. Can assess intent, evaluate quality, flag architectural drift, and produce a richer retroactive SPEC.md and PLAN.md because it understands context, not just presence. Consumes Claude context. Slower than a script. Findings are inferred — deterministic checks are better handled by the script.

Recommended sequence: Run node f3-foundation/tools/f3-audit.js first — no Claude needed, fast, objective. Then run this prompt with Claude reading the generated docs/AUDIT.md as a head start. Claude applies judgment on top of the script's facts rather than rediscovering them from scratch.

Prompt
Read @F3_CORE.md section "EXISTING PROJECT PROTOCOL" and 
@F3_TEMPLATES.md section "docs/AUDIT.md", then run a full 
Discovery Audit on this codebase.

Work through all seven audit categories:

Category 1: Security
- Hardcoded secrets, API keys, passwords, tokens in source files
- .env files committed to version control
- Unvalidated or unsanitized user inputs
- SQL queries built by string concatenation
- Missing authentication or authorization on sensitive operations
- Sensitive data logged (passwords, PII, tokens)

Category 2: Accessibility
- Interactive elements using div/span instead of button/a
- Images missing alt attributes
- Form inputs missing associated labels
- Missing ARIA landmarks (main, nav, header, footer)
- No visible focus indicators on interactive elements
- Dynamic content not announced via aria-live

Category 3: Dead Files
- Components imported nowhere
- Routes never linked to or loaded
- CSS/SCSS files never imported
- Commented-out code blocks 10+ lines
- Test files for components that no longer exist

Category 4: Dependencies
- Packages more than 2 major versions behind
- Known CVEs (from npm audit / pip-audit / composer audit)
- Duplicate packages serving the same purpose
- Dev dependencies in production bundle

Category 5: Docs Gaps
- README absent or missing setup instructions
- API endpoints with no documentation
- No architecture documentation
- No .env.example

Category 6: Version Control
- .gitignore missing or inadequate
- .env files not in .gitignore
- Large binary files committed

Category 7: Production Standards
- No logging library or logging calls present
- Raw errors returned to users
- No test files present

For each finding:
- Assign severity: Critical / High / Medium / Low
- Reference the exact file(s)
- Describe the remediation action
- Flag inferred items: [INFERRED — REQUIRES CONFIRMATION]
- Flag contradictions: [CONTRADICTION — REQUIRES DECISION]
- Flag unknowables: [UNKNOWN — REQUIRES INVESTIGATION]

Populate docs/AUDIT.md using the template from @F3_TEMPLATES.md.
Present the completed AUDIT.md for my review.
Wait for my approval before proceeding to Phase 2.

Re-Audit Prompt

Existing Projects

Use when: Re-running the Discovery Audit on a project that already has docs/AUDIT.md. Generates a delta report showing what improved, what regressed, and what remains unresolved. Appends to AUDIT.md without overwriting the original.

Recommended cadence: After every major release · every new developer onboarding · minimum quarterly

Prompt
Read @F3_CORE.md section "EXISTING PROJECT PROTOCOL" and the 
existing docs/AUDIT.md, then run a Re-Audit of this codebase.

This is a delta audit — compare current state against the previous AUDIT.md.

Step 1: Establish baseline
Read docs/AUDIT.md and note:
- Previous audit date
- Finding counts by category and severity
- Items previously marked [INFERRED], [CONTRADICTION], or [UNKNOWN]
- Items in the Remediation Backlog

Step 2: Re-scan all seven categories
Run the same Discovery Audit Checklist against the current codebase:
Security · Accessibility · Dead Files · Dependencies · Docs Gaps · 
Version Control · Production Standards

Step 3: Generate delta report
For each category, produce a delta table:
| Finding | Previous Status | Current Status | Change |
- ✅ Fixed — finding resolved since last audit
- ⚠️ Unresolved — still present
- 🆕 New — not in previous audit

Step 4: Check flag resolution
For each previous [INFERRED], [CONTRADICTION], [UNKNOWN] flag:
- Confirmed? Resolved?
- Still unresolved? → Escalate to next severity level.

Step 5: Append re-audit to docs/AUDIT.md
Do NOT overwrite original. Append:
- Delta summary table
- Resolved findings list
- New findings list  
- Still-unresolved list (with escalations)
- Updated remediation backlog

Step 6: Present delta report showing:
- What improved (resolved findings)
- What regressed or is new
- What remains unresolved (with escalations)
- Whether Critical/High severity decreased, increased, or held

Architecture Rebuild Prompt /project:f3:archrebuild

Maintenance

Use when: Running the weekly Lead-role rebuild of Layer 2 stable-reference docs from the commit/ session record. Rebuilds architecture.md, api.md, stack.md, and decisions.md from scratch using the commit-record synthesis — not from the existing doc — so stale content does not propagate.

Recommended cadence: Weekly · more often during heavy architectural change · less often during stable maintenance

Prompt
Rebuild the stable-reference documentation from the commit/ record.

This command rebuilds /docs/architecture.md, /docs/api.md, /docs/stack.md,
and /docs/decisions.md from scratch by synthesizing every session recorded
in the commit/ folder. Lead-role command. Run weekly.

Step 1: Inventory the commit record
Read every file in commit/ in chronological order. Build a synthesis of:
- Components added, modified, removed (architecture)
- API endpoints added, modified, removed (api)
- Dependencies added, removed, or version-changed (stack)
- Architectural and technical decisions made (decisions)

Step 2: Cross-reference with current code
For each synthesized finding, verify against current code:
- Architecture — component inventory vs src/ or app/ or lib/
- API — documented endpoints vs what the code exposes
- Stack — documented dependencies vs package.json, composer.json, requirements.txt
- Decisions — each ADR vs current implementation

Flag every discrepancy as a DOC-DRIFT item in /docs/todo.md.

Step 3: Rebuild each doc from scratch
Using the templates from @F3_TEMPLATES.md and the synthesized commit-record
findings, rebuild each of the four docs. Start from the template — not
from the existing doc. Starting from the existing doc propagates stale
content.

For each rebuilt doc:
1. Show me the current version vs the proposed new version (diff)
2. Highlight what changed and why
3. Wait for my explicit approval before overwriting

Step 4: Update devlog.md
Append an archrebuild entry:
## ARCHREBUILD - [TIMESTAMP]
**Commit range synthesized:** [first commit file] through [last commit file]
**Docs rebuilt:** [unchanged or rewritten per doc]
**DOC-DRIFT items flagged:** [count and brief description]
**Approved by:** [Lead name]

Authority
This is a Lead-role command. It overwrites Layer 2 stable-reference
documentation — the project's architectural contract.
- Do not run without Lead approval
- If a non-Lead requests it: refuse; explain it requires Lead approval

F3 Version Update Prompt /project:f3:update

Setup

Use when: Your project already uses F3 and you've dropped in updated F3_*.md module files. Claude reads the changelog to discover what changed, compares templates against your project, and applies all updates automatically.

Prompt
I've updated the F3 Framework files in this project. Please bring 
everything up to date.

**Step 1: Discover what changed**
- Read @F3_FRAMEWORK.md to confirm the new version number
- Read @F3_CHANGELOG.md and find every version between this project's 
  current version (check CLAUDE.md → "Current F3 Version") and the 
  new version
- List all changes: new files, updated templates, new prompts, new 
  workflow steps, breaking changes, fixes, new hooks

**Step 2: Audit the project against the new version**
- Read @F3_TEMPLATES.md and compare the CLAUDE.md template against 
  this project's actual CLAUDE.md — identify every section that is 
  missing, outdated, or differs from the current template
- Check /docs/ for any new files the updated version requires that 
  don't exist yet
- Read @F3_SETUP.md and compare .claude/settings.json against the 
  current starter config — identify missing hooks, permissions, or 
  hook events
- Check .claude/hooks/ for any new or updated hook scripts the 
  version requires
- Check .gitignore for any new entries needed
- Check for any renamed, moved, or restructured sections

**Step 3: Show me the plan**
For each change, show:
- What needs to be added, updated, or created
- For CLAUDE.md: the specific sections affected (not the whole file)
- For new /docs/ files: which template they come from
- For .claude/settings.json: the specific hooks or events to add
- For new hook scripts: which platform version to use (ask if unclear)
- Anything that looks like it conflicts with project-specific content

**Step 4: Wait for my approval**
Do NOT make changes until I approve the plan.

**Step 5: Apply approved changes**
- Update CLAUDE.md F3 framework sections (Session Protocol, Build ↔ 
  Guide Cycle, Documentation Map, Doc Update Triggers, Operational 
  Guardrails, Session Start/End checklists, Pre-Implementation 
  Checkpoint, etc.)
- Create any new /docs/ files using templates from @F3_TEMPLATES.md, 
  initialized with current project state
- Update .claude/settings.json with any new hooks or hook events
- Create any new hook scripts in .claude/hooks/ from @F3_SETUP.md
- Update .gitignore if needed
- Update the "Current F3 Version" in CLAUDE.md

**Step 6: Confirm**
- List every file created or modified
- Confirm the version number is current
- Note any manual follow-up needed (e.g., chmod +x on new .sh scripts)

Do NOT change project-specific content (Quick Context, Tech Stack, 
Current Development Phase, Critical Conventions, project-specific 
warnings, etc.) — only update F3 framework sections, hooks, and 
create new F3 files.

Session Start Prompt /project:f3:ss

Session

Use when: Beginning a new work session.

Prompt
Let's start a new session. Please:

1. Read CLAUDE.md for project context
2. If FIRST_RUN.md exists — read it and follow its instructions first
3. Write /docs/checkpoint.md — declare starting state and what we're
   taking on this session
4. Read the most recent file in commit/ — full previous session record
5. Check /docs/TASKS.md for current priorities
6. Review the last entry in /docs/devlog.md
7. Give me a brief status: where we left off, what's next, any blockers

Then let's continue with [describe what you want to work on].

Session End Prompt /project:f3:es

Session

Use when: Ending a work session. This command compiles the full session record, executes the git commit, and closes the session marker. Do not close sessions manually.

Prompt
See .claude/commands/f3/es.md for the full v5.0.0 session close protocol.

Summary of what /project:f3:es does:
1. Updates devlog.md, TASKS.md, decisions.md, CLAUDE.md current phase
2. Compiles full ES commit document to commit/YYYY/MM/
3. Deletes .f3/session.active and FIRST_RUN.md if present
4. Executes git commit with session summary message
5. Renames commit document with actual hash, then amends

Run /project:f3:es to execute.

Blocker Documentation Prompt

Blocker

Use when: You hit a technical issue that stops progress.

Prompt
STOP - we hit a blocker that's halting progress.

Document this NOW in /docs/devlog.md:

## BLOCKER - [TIMESTAMP]

**Issue:** [Exactly what broke or what's missing]
**Impact:** [Why this stops progress completely]
**Context:** [What we were doing when this happened]
**Resolution Plan:** [Steps needed to fix this]
**Estimated Downtime:** [Your time estimate]

Then pause work until the blocker is resolved.

Feature Complete Documentation Prompt /project:f3:fc

Documentation

Use when: A feature, component, or task has been approved and verified — BEFORE starting the next one. Don't batch documentation for session end.

Why this matters: In long sessions, context compaction can lose implementation details from earlier work. Documenting immediately captures decisions, patterns, and rationale while they're still in full context.

Prompt
We just completed [FEATURE/COMPONENT NAME]. Before moving on, 
document this work NOW:

1. **devlog.md** — Add a timestamped entry:
   - What was built and why
   - Key decisions made during implementation
   - Any deviations from the original plan and rationale
   - Any gotchas or lessons learned

2. **Run the Documentation Update Triggers:**
   Check every trigger in the F3 Documentation Update Triggers table 
   and update all applicable docs:
   - API endpoints added/changed → api.md
   - Modules/services/data flow changed → architecture.md  
   - Non-trivial tech choices made → decisions.md (add ADR)
   - Dependencies changed → stack.md
   - Schema changes → architecture.md + api.md
   - Auth changes → architecture.md + api.md + decisions.md

3. **todo.md** — Mark completed items done, add any new items 
   that surfaced during implementation

4. **CLAUDE.md** — Update "Current Development Phase" if the 
   completed feature changes project status

5. **Confirm** — List which docs were updated and summarize 
   changes in 2-3 sentences.

Do NOT skip this step. Do NOT defer to session end.

Documentation Checkpoint Prompt /project:f3:doco

Documentation

Use when: A session has been running for an extended period (hours or days) and you need to ensure all work is fully documented up to this point — without ending the session.

Why this matters: Long-running sessions accumulate work across multiple features. Even with per-feature documentation, details drift, docs fall behind, and context compaction erases nuance. This prompt forces a comprehensive documentation sweep so nothing is lost if the session continues, compacts, or crashes.

Prompt
DOCUMENTATION CHECKPOINT — This session has been running for a while. 
Before we continue, do a full documentation sweep NOW.

**1. Audit devlog.md**
   - Review everything we've done since the last checkpoint or 
     session start
   - Add timestamped entries for ANY work not yet documented
   - Include decisions made, problems solved, and workarounds applied
   - Flag anything that feels incomplete or uncertain

**2. Verify all docs against current code**
   Run through every Documentation Update Trigger:
   - architecture.md — Does it reflect all current components and 
     data flow?
   - api.md — Are all endpoints documented with current signatures?
   - decisions.md — Are all non-trivial tech choices captured as ADRs?
   - stack.md — Do dependencies match what's actually installed?
   - todo.md — Is the completed/pending status accurate right now?

**3. Check for doc drift**
   Compare docs against actual code. For each file:
   - If docs match code: Confirm ✓
   - If docs are behind: Update now
   - If unclear whether docs or code are correct: Log a DOC-DRIFT 
     item in todo.md and flag for my review

**4. Update CLAUDE.md**
   - "Current Development Phase" should reflect where we actually are
   - Active work items should match reality
   - Any new conventions or warnings discovered during this session

**5. Update checkpoint.md**
   Overwrite /docs/checkpoint.md with current state so crash recovery 
   is current through this point.

**6. Checkpoint marker**
   Add this to devlog.md:
   
   ## CHECKPOINT - [TIMESTAMP]
   Docs verified against code. All entries current through this point.
   Next priorities: [list what's next]

**7. Report**
   Give me a summary:
   - What was documented or updated
   - Any DOC-DRIFT items found
   - Any gaps or concerns
   - Confirmation that all F3 docs are current

Do NOT skip any file. We are continuing after this — this is not 
session end.

Resume After Blocker Prompt

Blocker

Use when: Restarting work after resolving a technical blocker.

Prompt
Resuming after [BLOCKER_TYPE] was resolved:

1. Read the last BLOCKER entry in /docs/devlog.md
2. Confirm what was fixed and how
3. Tell me exactly where we left off before the blocker
4. Verify the fix is working (run any relevant tests)
5. Continue from the precise point before interruption

We were working on [FEATURE] when [BLOCKER] stopped us.

Crash Recovery Prompt /project:f3:crash

Recovery

Use when: The terminal dropped, Claude Code lost connection, or a server restart killed the session. Claude has restarted with no memory of what was happening.

Why this exists: Server restarts and connection drops are the #1 cause of context loss. This prompt gets Claude back to full speed in one step by reading the crash recovery file first.

Prompt
Connection dropped. Read /docs/checkpoint.md — it has our last saved 
state.

Then:
1. Confirm: what was the last approved component?
2. Confirm: what were we working on next?
3. Check if there's any partially completed work (files modified but 
   not yet announced/approved)
4. Read the last entry in /docs/devlog.md for additional context
5. Tell me exactly where we are and what to do next

Resume from the checkpoint. Do NOT re-read the full project — 
checkpoint.md has everything you need to continue.

Tip: If checkpoint.md is stale or missing, fall back to the Context Recovery Prompt for a full project re-read.

Thrash Detection Prompt /project:f3:thrash

Recovery

Use when: Claude has tried 2-3 different approaches to the same problem and keeps failing, or you notice Claude modifying increasingly unrelated code to work around an issue.

Why this exists: Each failed attempt mutates the codebase. By attempt #4, Claude is solving the mess from attempts #1-3, not the original problem. An outside advisor with fresh eyes must review.

Prompt
STOP. You've attempted this [N] times and it's not working.

Do NOT try another approach. Instead:

1. **Roll back** to the last known good state (last checkpoint 
   or last passing commit). Undo all changes from the failed 
   attempts.

2. **Generate an Issue Review Brief** using the template in 
   @F3_TEMPLATES.md. Include:
   - The EXACT original requirement from SPEC.md
   - Each approach you tried and why it failed
   - Your honest assessment of the root cause
   - The current state of the code
   - Questions you're uncertain about

3. **Save the brief** as /docs/issue-review-brief.md

4. **Present it to me** with this message:
   "I've been unable to resolve this after [N] attempts. 
   I've generated an Issue Review Brief for outside review. 
   Please share this with a fresh advisor to get an 
   unbiased approach."

5. **WAIT** — do not attempt any more fixes until I return 
   with an approved approach from the outside review.

When I return with the approved approach:
- Implement ONLY that approach
- Verify against the ORIGINAL requirement in SPEC.md
- Document the resolution in devlog.md

Tip: Paste the contents of /docs/issue-review-brief.md into a separate LLM conversation (Claude.ai, ChatGPT, etc.) or share with a senior engineer. The outside advisor has no sunk cost and can see what Claude Code can't.

Thrash Reset Prompt /project:f3:reset

Recovery

Use when: You've reviewed the situation (with or without an outside advisor) and want to unblock Claude Code to continue working.

Prompt
Reset thrash detection — I've reviewed the situation.

1. Run: echo 0 > .claude/thrash-count
2. Read /docs/issue-review-brief.md (if it exists) for 
   context on what was tried

[CHOOSE ONE:]

OPTION A — Outside advisor provided an approach:
Here's the approved approach from the review:
[PASTE THE ADVISOR'S RECOMMENDED APPROACH HERE]
Implement ONLY this approach. Do not deviate.

OPTION B — I'm providing direction:
The issue is [DESCRIBE]. Try this approach: [YOUR DIRECTION].

OPTION C — Start fresh:
Forget all previous attempts. Re-read the original requirement 
in SPEC.md and propose a completely new approach before 
implementing anything. Show me the plan first.

Tip: Even with Option B or C, consider pasting the Issue Review Brief into a fresh LLM conversation first. Five minutes of outside review prevents another thrash cycle.

Context Recovery Prompt

Session

Use when: Returning after a long break or when Claude seems lost.

Prompt
I need you to rebuild your understanding of this project. Please:

1. Read CLAUDE.md for the project overview
2. Read /docs/checkpoint.md for last approved state
3. Read /docs/architecture.md for system design
4. Read the last 3 entries in /docs/devlog.md for recent context
5. Check /docs/devlog.md for any unresolved BLOCKERs
6. Check /docs/todo.md for current priorities
7. Review /docs/decisions.md for key architectural choices

Then give me a summary of:
- What this project is and does
- The current development state
- Any unresolved blockers
- What we should work on next

Feature Discovery Prompt /project:f3:fd

Feature

Use when: A new feature idea emerges mid-project that isn't in SPEC.md or PLAN.md yet.

Prompt
I want to explore a new feature idea: [FEATURE_IDEA]

Before we build anything, let's run this through F3 Foundation:

**1. Explore the idea:**
- What problem does this feature solve?
- Who benefits from it?
- What's the user story? ("As a [user], I want [feature] so that [benefit]")

**2. Check fit with existing vision:**
- Read SPEC.md - how does this align with project goals?
- Does it enhance or distract from core functionality?
- Are there any conflicts with existing features?

**3. Assess implementation impact:**
- What existing components does this touch?
- What new components would be needed?
- Any database schema changes?
- Any API changes?
- Rough complexity estimate (small/medium/large)

**4. Recommend:**
- Should we add this to the spec? (Yes/No/Defer/Modify)
- If yes, draft the SPEC.md addition
- Flag any concerns or alternatives

Don't implement anything yet—just explore and recommend.

Feature Planning Prompt /project:f3:fp

Feature

Use when: A feature has been approved and needs to be added to SPEC.md and PLAN.md.

Prompt
Let's add [FEATURE_NAME] to our Foundation documents.

**1. Update SPEC.md:**
- Add feature to appropriate section (Core Features, Phase 2, etc.)
- Include user story and acceptance criteria
- Note any new constraints or requirements

**2. Create implementation plan in PLAN.md:**
- Break down into components (what needs to be built)
- Define the implementation order
- Identify dependencies on existing code
- Note any architectural decisions needed

**3. Update related docs:**
- If API changes: update api.md
- If architecture changes: update architecture.md  
- If new decisions: add ADR to decisions.md
- Add to todo.md with priority

**4. Summary:**
- Show me the additions to each file
- Confirm the implementation order
- Ask if I want to proceed to implementation

Wait for my approval before making any changes to the docs.

Feature Implementation Prompt /project:f3:fi

Feature

Use when: Starting implementation of a feature that's already in PLAN.md.

Prompt
Let's implement [FEATURE_NAME] from PLAN.md.

Following the Build ↔ Guide cycle with explicit checkpoints:

1. Build the [FIRST_COMPONENT] (backend/frontend/database)
2. When complete, STOP and announce:
   - "I've completed [COMPONENT_NAME]"
   - Show what you built (summary, files, key functionality)
   - Ask: "Would you like to review before I continue to [NEXT]?"
3. WAIT for my review and approval
4. After I approve, proceed to next component
5. Repeat: Build → Stop → Announce → Show → Ask → Wait → Approve

**Rules:**
- Complete ONE component at a time
- ALWAYS stop and announce when done
- NEVER proceed without my explicit approval
- Show me what you created before moving on
- If I give feedback, make corrections before continuing

Begin with [FIRST_COMPONENT]. Think through the implementation 
carefully, build it, then STOP and show me what you created.

**Production Standards (required for EVERY component):**
- ☐ Logging: Key actions and errors logged with context
- ☐ Error Handling: User-friendly messages, no raw errors exposed
- ☐ Security: Input validation, parameterized queries, output escaping
- ☐ Accessibility: Semantic HTML, ARIA attributes, keyboard navigation

Complex Feature Architecture Prompt

Feature

Use when: Planning a complex feature that needs deep thinking.

Prompt
ultrathink: Design the [COMPLEX_FEATURE] architecture.

Consider:
- How this scales to 100k+ users
- Security implications and attack vectors
- Performance bottlenecks and optimization strategies
- Error handling and recovery
- Data consistency requirements
- Integration points with existing components

Propose a complete architecture before we start coding.

Threat Check Prompt (5-Minute Security Review)

Security

Use when: Building features involving auth, payments, user data, or any sensitive operations.

Prompt
Before we implement [FEATURE], let's do a quick threat check (5 minutes):

1. **Assets:** What are we protecting? (user data, credentials, money, etc.)

2. **Actors:** Who might want to abuse this? (attackers, malicious users, bots)

3. **Attack Surface:** What inputs/endpoints are exposed? What could be manipulated?

4. **Abuse Cases:** How could this feature be misused? (spam, data scraping, 
   credential stuffing, privilege escalation, injection, etc.)

5. **Mitigations:** What protections do we need? (rate limiting, validation, 
   authorization checks, logging, monitoring, etc.)

Give me a brief assessment before we proceed to implementation.

Quick Reference Commands

Quick Commands
Starting work "Read CLAUDE.md, checkpoint.md, and devlog — tell me where we left off"
Ending work "Summarize this session and update devlog and todo"
Hit blocker "STOP - document blocker in devlog NOW: [issue, impact, context]"
After blocker fixed "Resume after blocker: read BLOCKER entry, tell me where we stopped"
Made a decision "Add an ADR for [decision] to decisions.md"
Connection dropped "Read checkpoint.md — tell me where we were and resume"
Lost context "Re-read all docs and summarize project state"
New feature "Before we start, update architecture.md with the planned changes"
Stuck in a loop "STOP. Generate an Issue Review Brief for outside review."
Need deep thinking "ultrathink: Design [feature] considering scale, security, performance"

Existing Framework Translation

Before defining requirements or writing code, the F3-Framework needs to understand your existing framework. The Existing Framework Translation captures your framework's DNA so every subsequent session starts warm.

Framework-agnostic by design. The Existing Framework Translation doesn't prescribe a tech stack — it describes yours. Whether you build with Next.js, Laravel, .NET, Rails, WordPress, or anything else, it translates your choices into machine-readable context.

Two Paths — Same Outcome

The translation offers two paths. Both produce the same output (Foundation context files), and both include Claude asking follow-up questions regardless of which path you choose:

PATH A: SELF-GUIDED

Complete the Framework Translation Worksheet at your own pace before the session. Claude uses your answers as a starting point and asks targeted follow-ups.

PATH B: F3-FRAMEWORK-GUIDED

Skip the homework. Run the Framework Translation Prompt and Claude walks you through all 11 categories conversationally in real-time.

Download Translation Worksheet View Worksheet Online Fillable .docx — complete offline and bring to your F3-Framework session

The 11 Translation Categories

Each category produces both a description (what the F3-Framework should know) and a guardrail (what the F3-Framework should never do):

# Category What It Captures
01Tech Stack DeclarationFramework, language, CSS, state, DB, auth, tooling — with versions
02Folder Structure MapDirectory layout, purpose of each folder, where file types belong
03Naming ConventionsFile, component, function, CSS, variable, DB, API, and test naming
04Architectural PatternsArchitecture pattern, data flow, separation of concerns, API design
05Component & Module PatternsInternal structure, props/types, exports, state handling patterns
06Styling RulesTokens, breakpoints, styling pattern, animations, dark mode, UI library
07State ManagementGlobal state, local/global boundaries, server state, forms, caching
08Dependency BoundariesApproved packages, banned packages, addition policy, internal libs
09Testing StrategyFrameworks, coverage, test location, mocking, utilities
10Environment & DeploymentEnv vars, pipeline, hosting, configs, CI/CD
11"Never Do" ListType safety, security, imports, architecture, style hard rules

Framework Translation Prompt

Run this with or without a completed worksheet. Claude walks through all 11 categories and asks follow-up questions.

Framework Translation Prompt
Read @F3_FRAMEWORK.md and @F3_CORE.md, then begin the Existing 
Framework Translation for this project.

Your goal is to capture my framework's DNA across all 11 translation 
categories so you can generate accurate Foundation context files.

For EACH of the 11 categories:
1. Ask me specific questions about my conventions and patterns
2. Probe for details I might not think to mention
3. Confirm your understanding before moving to the next category
4. Note the guardrail that will be enforced for that category

The 11 categories are:
01. Tech Stack Declaration
02. Folder Structure Map
03. Naming Conventions
04. Architectural Patterns
05. Component & Module Patterns
06. Styling Rules
07. State Management Approach
08. Dependency Boundaries
09. Testing Strategy
10. Environment & Deployment Context
11. "Never Do" List

After completing all categories, generate:
1. A project-context.md file with the full framework translation
2. Recommendations for what should go into CLAUDE.md
3. A summary of all guardrails that will be enforced

Let's start with Category 01: Tech Stack Declaration.

What the Translation Produces

After completing the Existing Framework Translation, it generates:

  • project-context.md — Full framework translation with explicit guardrails
  • CLAUDE.md updates — Project-specific conventions added to the session bootstrap
  • Guardrail summary — Consolidated list of all enforced rules

These outputs feed directly into Area 1: Foundation.

Area 1: Foundation (Define & Architect)

Build the foundation before any code. This area has two activities:

Spec It: Define Requirements

Create SPEC.md to define the application vision.

Prompt to Start Specification
I want to build a [TYPE] application for [TARGET USERS].

The core problem: [DESCRIBE PROBLEM]

Let's create a comprehensive SPEC.md. Ask me one question at a 
time to develop a thorough specification. Each question should 
build on my previous answers.

Start by asking about the problem and users.

Plan It: Research & Architect

Once SPEC.md is complete, have Claude create the implementation plan:

Prompt
Read @SPEC.md thoroughly.

Before any coding, please:

1. RESEARCH:
   - Ask clarifying questions about any unclear requirements
   - Research current best practices for [TECH_STACK]
   - Identify potential technical challenges
   - Suggest optimal tech stack choices

2. CREATE PLAN.MD:
   - Development phases (MVP → Phase 2 → Phase 3)
   - Complete file structure to create
   - Component hierarchy and relationships
   - Database schema design
   - API endpoint list with methods
   - Dependencies needed
   - Estimated complexity per feature

3. WAIT FOR APPROVAL:
   Show me the plan and wait for my approval before coding.

Start with research and clarifying questions.

Area 2: Implementation (Integrated Build ↔ Guide Cycle)

This is where the actual development happens. Build and Guide are not sequential phases—they're a continuous integrated cycle.

The Implementation Cycle

1. Claude BUILDS 2. You GUIDE 3. Claude CORRECTS 4. You VERIFY 5. You APPROVE 6. Repeat

After completing each component, Claude MUST:

  1. STOP - Halt all forward progress
  2. ANNOUNCE - State what was completed
  3. SHOW - Provide summary of what was built
  4. ASK - Request review before continuing
  5. WAIT - Do not proceed without approval

Guide: You Steer in Real-Time

Active guidance prevents wasted work and maintains quality.

When Claude Goes Off Track

Redirect Prompt
Stop. That's not following our pattern in CLAUDE.md.

We use [CORRECT PATTERN] not [WHAT CLAUDE DID].

Please:
1. Read @CLAUDE.md section on [PATTERN]
2. Rewrite using the correct approach
3. Explain why this pattern is better

Before Complex Implementations

Prompt
Before you code this, explain:
1. Your approach to solving this
2. Why this is the right approach  
3. What tradeoffs you're making
4. What could go wrong

I want to validate the approach first.

Manage Scope Creep

Prompt
That feature isn't in SPEC.md.

Let's:
1. Add it to SPEC.md as Phase 2 if important
2. Document why in decisions.md
3. Stay focused on MVP for now

Get back to [CURRENT_FEATURE].

Warning Signs You Need to Guide More

  • Creating files not in the plan
  • Changing established patterns without asking
  • Adding features not in SPEC.md
  • Skipping error handling or validation
  • Not writing tests
  • Over-engineering simple features
  • Making assumptions about requirements

When you see these, stop and redirect immediately.

Area 3: Documentation (Persistent Knowledge)

Documentation happens continuously throughout development, not as a final step. This three-layer system solves Claude's context loss problem.

The Three-Layer Documentation System

Layer 1: Session Bootstrap (Auto-Read on Startup)

CLAUDE.md — Claude reads this automatically when you start

  • Project identity and tech stack (brief)
  • Current development phase and active work
  • Pointers to detailed docs
  • Critical conventions and warnings
  • Keep under 500 lines (it's an index, not a dump)

Layer 2: Stable Reference (Rarely Changes)

Deep context that doesn't change often:

  • docs/architecture.md — System design, components, data flow
  • docs/decisions.md — Architecture Decision Records (ADRs)
  • docs/stack.md — Tech choices and configuration
  • docs/api.md — API contracts and endpoints

Layer 3: Living State (Changes Frequently)

Active development tracking:

  • docs/checkpoint.md — Session intent declaration (written at SESSION OPEN — overwritten each session start) (gitignored — developer-local)
  • docs/devlog.md — Session-by-session progress summaries (append-only) (gitignored — developer-local; shared record lives in commit/)
  • docs/TASKS.md — Developer task tracking (gitignored)
  • docs/changelog.md — Release history

Permanent Session Record (New in v5.0.0)

  • commit/YYYY/MM/[date]_[developer]_[hash].md — Full ES commit document generated by /project:f3:es. Contains: session summary, files changed, project state, TASKS snapshot, decisions, architecture/api/stack state, production standards checklist, open items. Committed to git. Never deleted.

Handling Interruptions and Blockers

Technical issues that halt progress are inevitable. Proper documentation ensures you can resume efficiently.

Hard Stops (Session-Ending):

  • Missing dependencies (Docker, Node.js, Python)
  • Configuration errors that prevent running the app
  • API keys or credentials not configured
  • Database connection failures
  • Server restarts (dev server, API server — #1 cause of connection drops)

Soft Issues (Worked Around):

  • API rate limits (switched endpoints)
  • Slow performance (continued anyway)
  • Warning messages (noted but not blocking)

F3 Operational Guardrails

These guardrails close operational gaps and ensure consistent execution across projects. They prevent "paper compliance" where docs exist but quality still drifts.

1. Instruction Precedence (Conflict Resolution)

When multiple sources conflict, follow this precedence order:

PrioritySourceGoverns
1System/platform constraintsSecurity policies, environment limits
2CLAUDE.mdWorkflow, conventions, quality gates
3SPEC.mdRequirements, acceptance criteria
4PLAN.mdImplementation steps, sequencing
5/docs/*Reference docs (architecture, API, etc.)

Examples of System/platform constraints: No secrets in logs, no writing outside repo, approved licenses only, no eval().

Conflict rules:

  • PLAN vs SPEC: Pause and propose plan correction
  • Docs vs Code: If safe + obvious, update docs; if unclear, log DOC-DRIFT and ask
  • Code vs SPEC: Treat as bug; fix code or update SPEC with approval + ADR

2. Component Definition (Size Control)

A component is one reviewable unit that can be validated quickly.

LimitDefaultNotes
Max files changed~5 filesExcluding tests/docs
Max new code~300 linesNet-new only
Risky changesSingle-layer onlyAuth, billing, migrations

If limits exceeded: Break down into smaller components and get approval before proceeding.

3. Definition of Done (DoD) Checklist

Before claiming "I've completed [COMPONENT]", all items must be satisfied:

DoD Checklist
## Scope
- [ ] Matches SPEC/PLAN requirements
- [ ] No scope creep (extra features)

## Quality
- [ ] Tests added/updated and passing
- [ ] Code follows project conventions

## Production Standards
- [ ] Logging: Key actions + errors logged
- [ ] Errors: User-safe messages only
- [ ] Security: Inputs validated, authz checked
- [ ] Accessibility: Semantic HTML, ARIA, keyboard nav

## Documentation
- [ ] Required docs updated (see triggers)

## Verification
- [ ] Commands run + outcomes captured

4. Documentation Update Triggers

When You Change...Update...
API endpoint/docs/api.md
Module/data flow/docs/architecture.md
Tech decision/docs/decisions.md (ADR)
Dependency/docs/stack.md
Component approved/docs/devlog.md (append) + /docs/TASKS.md (mark done)
Session start/docs/checkpoint.md (overwrite — declare starting state + session intent)
Server restart/docs/checkpoint.md (overwrite) + devlog.md (append) BEFORE restart
Mid-session git commitcompile lightweight commit doc to commit/YYYY/MM/ + devlog.md + TASKS.md BEFORE commit
Session closerun /project:f3:es — compiles ES commit document + executes git commit

5. Lightweight Security Gate

For any new endpoint, form, or job input:

Security Gate Checklist
1. Inputs identified: [List sources + types]
2. Validation: [Schema/approach]
3. Authorization: [Who can call? How enforced?]
4. Output handling: [Escaped if rendering]
5. Logging redaction: [No secrets/PII]
6. Abuse prevention: [Rate/size limits]

6. Lightweight Accessibility Gate

For any new UI component, page, or interactive element:

Accessibility Gate Checklist
1. Semantic HTML: [Correct elements — no div-buttons]
2. ARIA attributes: [Landmarks, roles, labels applied]
3. Keyboard navigation: [Tab, Enter, Escape reachable]
4. Focus management: [Visible indicators, logical order]
5. Color contrast: [4.5:1 minimum on all text]
6. Alt text: [Meaningful alt or alt="" for decorative]

7. Restart Gate (HARD STOP)

This is NOT advisory. Violation = total context loss. Server restarts are the #1 cause of Claude Code connection drops. The WebSocket times out when a long-running process blocks the terminal during kill/rebind.

Before executing ANY restart command:

  1. Overwrite /docs/checkpoint.md with: current task, findings so far, next step
  2. Append timestamped entry to /docs/devlog.md
  3. THEN execute the restart

Commands that trigger this gate: npm run dev, npm start, node --watch, flask run, uvicorn, docker-compose restart/up/down, kill, taskkill, or any command that stops and starts a long-running process.

Mechanical enforcement: Add the F3 Restart Gate hook to .claude/settings.json + a hook script (both committed to git). Choose the version for your platform:

Important: Claude Code passes hook input via stdin as JSON, not environment variables. Bash scripts also have known issues on Windows — use the Node.js version if you're on Windows.

macOS / Linux: f3-restart-gate.sh

.claude/hooks/f3-restart-gate.sh
#!/usr/bin/env bash
set -euo pipefail

# F3 Restart Gate — blocks server restarts
# without checkpointing.
# Reads hook input from stdin (JSON).
# Customize RESTART_PATTERN for your stack.

# Read JSON from stdin
INPUT=$(cat)

# Extract the command from JSON
COMMAND=$(echo "$INPUT" \
  | grep -oP '"command"\s*:\s*"\K[^"]*' \
  | head -1)

RESTART_PATTERN='npm run dev|npm start|node --watch'
RESTART_PATTERN+='|flask run|uvicorn|manage\.py runserver'
RESTART_PATTERN+='|docker.*(restart|up|down)'
RESTART_PATTERN+='|kill|taskkill'

if echo "$COMMAND" | grep -qiE "$RESTART_PATTERN"; then
  if ! git diff --name-only \
       | grep -q 'docs/checkpoint.md'; then
    echo "BLOCKED: F3 Restart Gate" >&2
    echo "Update docs/checkpoint.md and" >&2
    echo "docs/devlog.md before restarting." >&2
    exit 2
  fi
fi

Run chmod +x .claude/hooks/f3-restart-gate.sh after creating.

Windows (or cross-platform): f3-restart-gate.js

See Getting Started Step 3 for the full Node.js script and its corresponding settings.json (uses "node .claude/hooks/f3-restart-gate.js").

Commit Gate — Enforcement Only

v5.0.0: Enforcement only. The Commit Gate no longer compiles documentation — that is owned by /project:f3:es (session close) and Claude's mid-session commit behavior. The gate mechanically blocks commits that are missing the minimum required state.

The Claude Code hook (.claude/hooks/f3-commit-gate) blocks git commit if any of these are missing:

  1. /docs/devlog.md has been modified (session is documented)
  2. /docs/TASKS.md has been modified (task state is current)
  3. .f3/session.active exists (confirms active F3 session)

For session close: run /project:f3:es — it satisfies all gate checks automatically and handles the commit.
For mid-session commits: update devlog.md + TASKS.md + compile lightweight commit document to commit/YYYY/MM/ first, then commit.

The universal Git hook (.githooks/pre-commit) still runs at actual git commit time in all editors. Bypass with git commit --no-verify when intentional.

Layer 1 — Universal Git Hook (.githooks/pre-commit)

Auto-installed to .git/hooks/pre-commit by f3-foundation/tools/setup-f3.js. Runs in every editor at actual commit time. Node.js — works on macOS, Linux, and Windows.

.githooks/pre-commit
#!/usr/bin/env node

// F3 Universal Commit Gate v5.0.0
// Standard Git pre-commit hook — runs at `git commit` time in every editor.
// Exit 1 = Git convention (differs from Claude Code hooks which use exit 2).
// Auto-installed to .git/hooks/pre-commit by setup-f3.js.
// Manual: cp .githooks/pre-commit .git/hooks/ && chmod +x .git/hooks/pre-commit
// Bypass: git commit --no-verify

'use strict';

const { execSync } = require('child_process');
const fs = require('fs');

// Skip silently if not an F3 project
const isF3 = ['CLAUDE.md','CURSOR.md','AGENTS.md','GEMINI.md','F3_CORE.md']
  .some(f => fs.existsSync(f));
if (!isF3) process.exit(0);
if (!fs.existsSync('docs')) process.exit(0);

function getModified() {
  try {
    const staged   = execSync('git diff --cached --name-only', { encoding: 'utf8' });
    const unstaged = execSync('git diff --name-only',          { encoding: 'utf8' });
    return staged + '\n' + unstaged;
  } catch { return ''; }
}

const modified = getModified();
const REQUIRED = ['docs/checkpoint.md', 'docs/devlog.md']
  .filter(f => fs.existsSync(f));
const missing  = REQUIRED.filter(f => !modified.includes(f));

if (missing.length === 0) process.exit(0);

const SEP = '─'.repeat(50);
const msg = [
  '', 'BLOCKED: F3 Commit Gate (universal)', SEP, '',
  'Update these docs before committing:', '',
  ...missing.map(f => `  • ${f}`), '',
  'Also check Doc Update Triggers:',
  '  API endpoint changed?     →  docs/api.md',
  '  Architecture changed?     →  docs/architecture.md',
  '  Tech decision made?       →  docs/decisions.md',
  '  Dependency changed?       →  docs/stack.md', '',
  'After updating, commit again.',
  'To skip: git commit --no-verify',
  '', SEP, '',
].join('\n');

process.stderr.write(msg);
process.exit(1);

Layer 2 — Claude Code Variant (macOS / Linux)

Fires inside Claude Code sessions as a PreToolUse hook. Adds Production Standards reminder. Uses exit 2 (Claude Code blocking convention).

.claude/hooks/f3-commit-gate.sh
#!/usr/bin/env bash
set -euo pipefail

# F3 Commit Gate v5.0.0 — Claude Code variant
# Runs as a Claude Code PreToolUse hook when Claude attempts git commit.
# Exit 2 = Claude Code blocking convention.

INPUT=$(cat)
COMMAND=$(echo "$INPUT" \
  | grep -oP '"command"\s*:\s*"\K[^"]*' \
  | head -1)

if ! echo "$COMMAND" | grep -qiE '^git commit'; then
  exit 0
fi

MISSING=""

if ! git diff --cached --name-only | grep -q 'docs/checkpoint.md'; then
  if ! git diff --name-only | grep -q 'docs/checkpoint.md'; then
    if [ -f "docs/checkpoint.md" ]; then
      MISSING+="  • docs/checkpoint.md\n"
    fi
  fi
fi

if ! git diff --cached --name-only | grep -q 'docs/devlog.md'; then
  if ! git diff --name-only | grep -q 'docs/devlog.md'; then
    if [ -f "docs/devlog.md" ]; then
      MISSING+="  • docs/devlog.md\n"
    fi
  fi
fi

if [ -n "$MISSING" ]; then
  echo "BLOCKED: F3 Commit Gate (Claude Code)" >&2
  echo "Update before committing:" >&2
  echo -e "$MISSING" >&2
  echo "Verify Doc Update Triggers:" >&2
  echo "  API changed?          →  docs/api.md" >&2
  echo "  Architecture changed? →  docs/architecture.md" >&2
  echo "  Decision made?        →  docs/decisions.md" >&2
  echo "Confirm Production Standards:" >&2
  echo "  ☐ Logging  ☐ Error handling  ☐ Security  ☐ Accessibility" >&2
  exit 2
fi

Make executable: chmod +x .claude/hooks/f3-commit-gate.sh

Layer 2 — Claude Code Variant (Windows)

See Getting Started Step 3 for the full Node.js script (uses "node .claude/hooks/f3-commit-gate.js").

8. Foundation Enforcement (REFUSE — not advisory)

Claude must REFUSE to implement changes not in PLAN.md, even if the user says "just go for it." This is the most important behavioral guardrail in F3. Without it, a single "just do it" bypasses the entire Foundation layer.

When Claude detects a significant change not in PLAN.md, Claude MUST:

  1. REFUSE to proceed — not ask, not suggest, refuse
  2. Explain why — "Undocumented changes mean the next session starts blind."
  3. Offer the correct path — "Let's run Feature Discovery, update PLAN.md, then I can implement it."

Triggers: Any restructure touching 3+ files across different layers, new components not in SPEC.md, architecture changes, anything described as "significant" or "major," or user requests not in the original plan.

If the user insists ("just do it")

Claude should hold firm:

Claude's Response
"I understand the urgency, but implementing undocumented 
architectural changes is the #1 cause of project drift. 
Feature Discovery takes 5 minutes. The cleanup from 
skipping it takes hours.

I'll run Feature Discovery now — it's fast."

This is not about slowing down. It's about preventing the cleanup that costs 10x more later. A junior dev saying "just go for it" can bypass the entire Foundation layer — Claude is the last line of defense.

9. Thrash Detection & Multi-Agent Review (HARD STOP)

After 2-3 failed attempts at the same problem, Claude MUST stop trying and escalate. Each failed attempt mutates the codebase. By attempt #4, Claude is solving the mess from attempts #1-3, not the original problem. Self-evaluation is the blind spot — an outside advisor must review.

When triggered, Claude MUST:

  1. STOP all implementation — no more "let me try one more thing"
  2. Roll back to last known good state
  3. Generate an Issue Review Brief — a structured document for outside review
  4. Present it and say: "Please share this with a fresh advisor"
  5. WAIT — do not attempt any more fixes

The developer pastes the brief into a separate LLM conversation (Claude.ai, ChatGPT, etc.) or shares with a senior engineer. The outside advisor has no sunk cost, no tunnel vision. They challenge assumptions and propose fresh approaches.

Mechanical enforcement: The Thrash Detector hook tracks consecutive Bash failures via a counter file. After 3 failures, it blocks all further commands until /docs/issue-review-brief.md is generated.

macOS / Linux: f3-thrash-detector.sh

.claude/hooks/f3-thrash-detector.sh
#!/usr/bin/env bash
set -euo pipefail

# F3 Thrash Detector — blocks after 3 consecutive
# failures until Issue Review Brief is generated
# OR counter is reset. Allows safe commands when
# blocked so Claude can generate the brief.

COUNT_FILE=".claude/thrash-count"
BRIEF="docs/issue-review-brief.md"
MAX_FAILURES=3

INPUT=$(cat)

EVENT=$(echo "$INPUT" \
  | grep -oP '"hook_event_name"\s*:\s*"\K[^"]*' \
  | head -1)
COMMAND=$(echo "$INPUT" \
  | grep -oP '"command"\s*:\s*"\K[^"]*' \
  | head -1)

COUNT=0
if [ -f "$COUNT_FILE" ]; then
  COUNT=$(cat "$COUNT_FILE")
fi

case "$EVENT" in
  PostToolUseFailure)
    COUNT=$((COUNT + 1))
    echo "$COUNT" > "$COUNT_FILE"
    if [ "$COUNT" -ge "$MAX_FAILURES" ]; then
      echo "WARNING: $COUNT consecutive failures." >&2
      echo "Generate an Issue Review Brief." >&2
    fi
    ;;
  PostToolUse)
    echo "0" > "$COUNT_FILE"
    ;;
  PreToolUse)
    if [ "$COUNT" -ge "$MAX_FAILURES" ]; then
      if [ -f "$BRIEF" ]; then
        AGE=$(( $(date +%s) - $(stat -c %Y "$BRIEF") ))
        if [ "$AGE" -lt 300 ]; then
          echo "0" > "$COUNT_FILE"
          exit 0
        fi
      fi
      # Allow thrash-count reset
      if echo "$COMMAND" | grep -qiE 'thrash-count'; then
        exit 0
      fi
      # Allow safe commands for brief generation
      if echo "$COMMAND" | grep -qiE \
        '^(cat|head|tail|less|more|wc|grep|find|ls|pwd)(\s|$)'; then
        exit 0
      fi
      if echo "$COMMAND" | grep -qiE '^git(\s|$)'; then
        exit 0
      fi
      if echo "$COMMAND" | grep -qiE \
        'docs/|issue-review-brief|mkdir.*docs'; then
        exit 0
      fi
      echo "BLOCKED: F3 Thrash Detection" >&2
      echo "$COUNT consecutive failures." >&2
      echo "Generate Issue Review Brief or reset:" >&2
      echo "echo 0 > .claude/thrash-count" >&2
      exit 2
    fi
    ;;
esac

Make executable: chmod +x .claude/hooks/f3-thrash-detector.sh

Windows (or cross-platform): f3-thrash-detector.js

See Getting Started Step 3 for the full Node.js script (uses "node .claude/hooks/f3-thrash-detector.js").

After the outside advisor returns an approach: Claude implements ONLY that approach, then verifies against the original requirement in SPEC.md — not "does the error go away" but "does this satisfy what SPEC.md asked for."

First-Run Loader — Session Start Injection

Context injection, not enforcement. Unlike the other hooks in this section, the First-Run Loader does not block commands. It mechanically ensures Claude sees FIRST_RUN.md before processing the first user message — making the self-directing first-session behavior deterministic rather than dependent on Claude noticing the conditional instruction in CLAUDE.md.

User flow: The installer's post-install banner tells the user to open Claude and send first-run as their first prompt. The hook fires on that message, injects FIRST_RUN.md contents into Claude's context, and Claude acknowledges the first-run session — reviewing any audit findings and proposing the next concrete step before doing anything else.

Mechanical enforcement: The hook is wired into two Claude Code events for redundancy:

  1. SessionStart — fires once when the session opens. Purpose-built for context injection. Has a known Claude Code bug (#10373) where stdout is silently dropped on brand-new interactive sessions.
  2. UserPromptSubmit — fires before each user message is processed. Reliable. This is the guaranteed injection path.

On each fire, the hook checks if FIRST_RUN.md exists at the project root. If not, it exits silently (no-op). If present, it reads the file, truncates to Claude Code's 10K context cap if needed, wraps the contents in a directive block, and emits the result as structured JSON (hookSpecificOutput.additionalContext).

Self-suppressing: The hook stops injecting as soon as /project:f3:es deletes FIRST_RUN.md at first session close. No cleanup required — the file-exists check at the top of the hook makes every subsequent fire a silent no-op.

Platform variants: .claude/hooks/f3-first-run-loader.sh (macOS/Linux, uses node internally for JSON-safe serialization) and .claude/hooks/f3-first-run-loader.js (Windows/cross-platform, pure Node.js). Both are written automatically by setup-f3.js — no manual installation.

settings.json wiring: Both events are wired automatically by the installer. See the Hook Configuration block below for the full settings.json with all five event types (PreToolUse, PostToolUse, PostToolUseFailure, SessionStart, UserPromptSubmit).

10. Session Close — /project:f3:es

Session close is owned by /project:f3:es. Do not close sessions with a manual git commit. The command handles the full protocol and ensures the permanent record is created correctly.

/project:f3:es executes in this order:

  1. Updates devlog.md, TASKS.md, decisions.md, and CLAUDE.md current phase
  2. Compiles the full ES commit document — the permanent session record
  3. Writes to commit/YYYY/MM/YYYY-MM-DD_[developer]_PENDING.md
  4. Deletes .f3/session.active and FIRST_RUN.md if present
  5. Executes git commit with session summary message
  6. Renames the document with actual hash, then amends

ES commit document contains: session summary, files changed (diff stat), project state (checkpoint.md), TASKS.md snapshot, decisions made, architecture/api/stack state, production standards checklist, and open items. Every ES document is a complete pickup record for any future developer or Claude session.

11. Architecture Rebuild — /project:f3:archrebuild

Lead-only command. Run weekly. Reads all ES commit documents since the last reconciliation and rebuilds the stable reference documents.

Documents rebuilt: docs/architecture.md, docs/api.md, docs/stack.md, docs/decisions.md

Versioned header written to each rebuilt document:

Versioned Header
**Version:** 1.3
**Last Reconciled:** 2026-04-18
**Reconciled By:** Scott Rains
**Sessions Incorporated:** a1b2c3d, e4f5g6h, i7j8k9l

Conflict model: When two ES documents contain different values for the same subject (endpoint, component, dependency), archrebuild surfaces both and asks the Lead which is authoritative — it does not silently pick a winner. This is standard git reconciliation applied to documentation.

Handoff readiness: A project is pickup-ready when commit/ contains at least one ES document and CONTRIBUTORS.md identifies who owns what. Any developer can read the most recent ES document and understand exactly where the project stands.

Hook Configuration (macOS / Linux)

This settings.json wires all three hooks for macOS/Linux. For Windows, see Getting Started Step 3 which uses the Node.js versions.

.claude/settings.json (macOS / Linux)
{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/f3-restart-gate.sh" },
          { "type": "command",
            "command": ".claude/hooks/f3-commit-gate.sh" },
          { "type": "command",
            "command": ".claude/hooks/f3-thrash-detector.sh" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/f3-thrash-detector.sh" }
        ]
      }
    ],
    "PostToolUseFailure": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/f3-thrash-detector.sh" }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/f3-first-run-loader.sh" }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command",
            "command": ".claude/hooks/f3-first-run-loader.sh" }
        ]
      }
    ]
  }
}

Slash Commands

Type a slash command in Claude Code instead of copying and pasting prompts. Each command loads the full prompt from a .md file in .claude/commands/f3/.

How it works: Claude Code reads .claude/commands/f3/*.md files and registers them as /project:f3:command-name. The f3/ subdirectory namespaces F3 commands so they don't collide with Claude Code built-ins or other tools. Commit to git so the whole team gets them.

Command Reference

Command Prompt When to Use
/project:f3:ss Session Start Beginning of every session
/project:f3:es Session End End of every session — compiles ES commit document and executes git commit
/project:f3:archrebuild Architecture Rebuild Lead only. Weekly — rebuilds architecture.md, api.md, stack.md, decisions.md from commit/ record
/project:f3:doco Documentation Checkpoint Mid-session doc sync (long sessions)
/project:f3:fd Feature Discovery Exploring a new feature or change
/project:f3:fp Feature Planning Adding a discovered feature to PLAN.md
/project:f3:fi Feature Implementation Starting the Build ↔ Guide cycle
/project:f3:fc Feature Complete Wrapping up a feature with full docs
/project:f3:crash Crash Recovery After a connection drop or restart
/project:f3:thrash Thrash Detection Claude stuck in a failure loop
/project:f3:reset Thrash Reset Unblocking after outside review
/project:f3:update F3 Version Update After dropping in new F3 module files
/project:f3:gr Governance Report Session close — generates JSON + Markdown governance record
/project:f3:audit Discovery Audit Checklist Run 7-category codebase audit, populate docs/AUDIT.md

Setup

Create .claude/commands/f3/ in your project root and add one .md file per command:

Directory Structure
.claude/
├── commands/
│   └── f3/
│       ├── ss.md        # /project:f3:ss → Session Start
│       ├── es.md        # /project:f3:es → Session End
│       ├── doco.md      # /project:f3:doco → Documentation Checkpoint
│       ├── fd.md        # /project:f3:fd → Feature Discovery
│       ├── fp.md        # /project:f3:fp → Feature Planning
│       ├── fi.md        # /project:f3:fi → Feature Implementation
│       ├── fc.md        # /project:f3:fc → Feature Complete
│       ├── crash.md     # /project:f3:crash → Crash Recovery
│       ├── thrash.md    # /project:f3:thrash → Thrash Detection
│       ├── reset.md     # /project:f3:reset → Thrash Reset
│       ├── update.md    # /project:f3:update → F3 Version Update
│       ├── gr.md        # /project:f3:gr → Governance Report
│       └── audit.md     # /project:f3:audit → Discovery Audit Checklist
├── hooks/
│   ├── f3-phase-gate.sh (or .js)
│   ├── f3-restart-gate.sh (or .js)
│   ├── f3-commit-gate.sh (or .js)
│   └── f3-thrash-detector.sh (or .js)
└── settings.json

Each .md file contains the exact prompt text from the corresponding prompt section above. The F3 Version Update Prompt (/project:f3:update) will create these files automatically when upgrading to v5.0.0+.

Why the f3/ subdirectory? It namespaces F3 commands so they don't collide with Claude Code built-ins or other tools' shortcuts. Claude Code uses the directory path to create the project:f3: prefix automatically. Works on all platforms (colons in filenames fail on Windows — subdirectories don't).

Manual setup: Copy the prompt content from each prompt section (between the ``` markers in @F3_PROMPTS.md) into the corresponding .md file. Commit .claude/commands/f3/ to git so the whole team gets the same shortcuts.

Complete Documentation Templates

CLAUDE.md (Layer 1 - Session Bootstrap)

CLAUDE.md Template
# [PROJECT NAME]

> Brief one-line description

## Quick Context
[2-3 sentences: purpose, users, value proposition]

## F3 Framework Reference

This project uses F3 (Foundation-First Framework). The framework is split 
into modular files in the project root:

| Module | Contents |
|--------|----------|
| `F3_FRAMEWORK.md` | Hub — read this first, routes to all modules |
| `F3_CORE.md` | Methodology, production standards, guardrails |
| `F3_PROMPTS.md` | All Claude Code implementation prompts |
| `F3_TEMPLATES.md` | Document templates (CLAUDE.md, SPEC, docs/*) |
| `F3_SETUP.md` | Setup guides for new & existing projects |
| `F3_CHANGELOG.md` | Version history & roadmap |

**Claude: Read @F3_FRAMEWORK.md first — it routes you to the right module.**
- Need templates? → @F3_TEMPLATES.md
- Need methodology or guardrails? → @F3_CORE.md
- Need prompts? → @F3_PROMPTS.md

**Current F3 Version:** 5.0.0

## Tech Stack
- Frontend: [React, Next.js, etc.]
- Backend: [Node.js, Python, etc.]
- Database: [PostgreSQL, MongoDB, etc.]
- Infrastructure: [AWS, Vercel, etc.]

## Architecture Overview
See /docs/architecture.md for full system design.

Key Components:
- [Component 1]: [one-line description]
- [Component 2]: [one-line description]

## Current Development Phase
Phase: [MVP, Beta, Feature Development]

Active Work:
- [ ] [Current task]
- [ ] [Next priority]

Blocked By: [None or description]

Last Session: [Date] - [Brief summary]

## Critical Conventions
Code Patterns:
- [Pattern 1]: [explanation]
- [Pattern 2]: [explanation]

Git Workflow:
- Branch naming: [convention]
- Commit format: [convention]

## Operational Guardrails

### Instruction Precedence (when sources conflict)
1. System/platform constraints → 2. CLAUDE.md → 3. SPEC.md → 4. PLAN.md → 5. /docs/*

**If code conflicts with SPEC:** Treat as bug; fix code or update SPEC with approval + ADR.

### Component Sizing
- Max: ~5 files, ~300 lines per component (only tests/** and docs/** excluded)
- Risky changes (auth, billing, migrations): Single-layer only + rollback notes required

### Definition of Done (required)
- [ ] Scope matches SPEC/PLAN
- [ ] Tests passing
- [ ] Lint passes (if configured) or TODOs logged
- [ ] Logging, errors, security implemented
- [ ] Accessibility: semantic HTML, ARIA, keyboard nav
- [ ] Docs updated

### Doc Update Triggers
API change → api.md | Architecture → architecture.md | Decision → decisions.md | Schema affecting API → api.md | Component approved → checkpoint.md (overwrite) + devlog.md (append) | **Server restart → checkpoint.md + devlog.md BEFORE restart** | **Git commit → checkpoint.md + devlog.md + all docs BEFORE commit**

### Security Gate (new endpoints)
Inputs → Validate → Authorize → Escape output → Redact logs → Rate limit

### Accessibility Gate (new UI components/pages)
Semantic HTML → ARIA attributes → Keyboard nav → Focus management → Color contrast → Alt text

### Restart Gate (HARD STOP — before ANY server restart)
**⚠️ This is NOT advisory. Violation = total context loss.**
Before ANY restart command (npm run dev, flask run, docker-compose restart, kill, etc.):
1. Overwrite /docs/checkpoint.md → 2. Append to /docs/devlog.md → 3. THEN restart

### Commit Gate (before ANY git commit)
Before running `git commit`, verify:
1. /docs/checkpoint.md is updated with current state
2. /docs/devlog.md has entries for all work since last commit
3. All Doc Update Triggers satisfied (api.md, architecture.md, decisions.md, stack.md)
**If docs are stale, update them BEFORE committing.**

## Session Protocol

### F3 Methodology Reminder

This project follows F3 (Foundation-First Framework) v5.0.0:

**Area 1: Foundation** - Spec + Plan defined upfront  
**Area 2: Implementation** - Build ↔ Guide continuous cycle  
**Area 3: Documentation** - Continuous logging for persistent context
**Production Standards** - Security, logging, error handling, accessibility, and testing in every implementation

**Critical F3 Behaviors:**
- Show me each component before moving on (Build ↔ Guide cycle)
- **After completing each component: STOP, announce completion, wait for approval**
- Never proceed to next component without explicit permission
- **REFUSE to implement changes not in PLAN.md — require Feature Discovery first, even if told "just go for it"**
- Checkpoint progress to /docs/checkpoint.md after every approval
- **BEFORE any server restart: overwrite checkpoint.md + append to devlog.md FIRST (Restart Gate)**
- Document blockers immediately when they occur
- Never assume - always ask for approval before major changes
- **After 2-3 failed attempts at the same problem: STOP trying. Generate an Issue Review Brief for outside review.**
- **Before any git commit: verify checkpoint.md, devlog.md, and all Doc Update Triggers are current**
- **Include logging, error handling, security, and accessibility in EVERY component**

**⚠️ CRITICAL:** If a requested change is NOT in PLAN.md, do NOT implement it.
**REFUSE to proceed.** Say: "I cannot implement this — it's not in PLAN.md. We need to run Feature Discovery and update the plan first. This is an F3 requirement, not a suggestion."

### Pre-Implementation Checkpoint

**Before starting ANY significant work, verify:**

1. ☐ Is this feature/change in SPEC.md?
2. ☐ Is there an implementation plan in PLAN.md?
3. ☐ If NO to either: **REFUSE to proceed.** Run Feature Discovery Prompt first. Do NOT accept "just go for it" — undocumented architectural changes break the project for every future session.

**Before completing ANY component, verify Production Standards:**

4. ☐ Logging implemented for key actions and errors?
5. ☐ Error handling with user-friendly messages?
6. ☐ Security considerations addressed (input validation, auth, etc.)?
7. ☐ Accessibility: semantic HTML, ARIA attributes, keyboard navigation?

**Triggers for this checkpoint:**
- "Significant restructure" or "major refactor"
- Multi-file changes
- New components or features
- Architecture changes
- Anything described as "comprehensive" or "major"

**If you catch yourself about to implement without spec/plan:**
STOP → REFUSE: "I cannot proceed without updating PLAN.md first."

### Build ↔ Guide Cycle Protocol

**After completing EVERY component, you MUST:**

1. **STOP** - Do not continue to the next component
2. **ANNOUNCE:** "I've completed [COMPONENT_NAME]"
3. **SHOW:** Summary of what was built (files created/modified, key functionality)
4. **ASK:** "Would you like to review this before I continue to [NEXT_COMPONENT]?"
5. **WAIT:** Do not proceed until I give explicit approval
6. **CHECKPOINT:** After approval, overwrite /docs/checkpoint.md and append to /docs/devlog.md before starting the next component

## Important Warnings
⚠️ Never edit files in /legacy or /vendor
⚠️ Always run tests before committing
⚠️ Checkpoint to /docs/checkpoint.md after every approval — crashes lose context
⚠️ **NEVER restart a server without updating checkpoint.md + devlog.md FIRST**

## Documentation Map
| Document | Purpose |
|----------|---------|
| /docs/architecture.md | System design |
| /docs/decisions.md | ADRs, rationale |
| /docs/stack.md | Tech choices |
| /docs/api.md | Endpoints |
| /docs/checkpoint.md | Last approved state (crash recovery) |
| /docs/devlog.md | Session history |
| /docs/todo.md | Tasks |
| /docs/changelog.md | Releases |

## Session Start Checklist
1. Read this file (automatic)
2. Read /docs/checkpoint.md for last approved state and next task
3. Check /docs/todo.md for priorities
4. Review last /docs/devlog.md entry (including BLOCKERs)
5. Verify no unexpected shutdowns left incomplete work

## Session End Protocol
Before closing:
1. Summarize accomplishments and append to /docs/devlog.md
2. Overwrite /docs/checkpoint.md with final session state
3. Update "Current Development Phase" above
4. Update /docs/todo.md with completed/new items
5. Document any decisions in /docs/decisions.md

SPEC.md Template

SPEC.md Template
# Project Specification

## Vision Statement
[One paragraph: What is this application and why does it exist?]

## Problem & Solution
- **Problem:** What pain point does this solve?
- **Target Users:** Who are they?
- **Solution:** How does this solve their problem?

## Core Features (MVP)
1. **[Feature Name]**
   - User Story: As a [user], I want to [action] so that [benefit]
   - Acceptance Criteria:
     * [Criterion 1]
     * [Criterion 2]
   - Priority: [High/Medium/Low]

2. **[Feature Name]**
   - User Story: ...
   - Acceptance Criteria: ...
   - Priority: ...

## User Flows
### Primary Flow: [Name]
1. User [action]
2. System [response]
3. User [action]
4. Result: [outcome]

## Success Metrics
- User engagement: [How measured]
- Performance: [LCP < 2.5s, etc.]
- Business: [Revenue, conversions, etc.]

## Technical Constraints
- Budget: [Limitations]
- Performance requirements: [Specific targets]
- Security requirements: [Authentication, compliance]
- Accessibility: [WCAG level]

## Out of Scope (v1)
- [Features explicitly NOT in MVP]
- [Features for later phases]

## Design Requirements
- Mobile-first responsive design
- Color scheme: [Colors]
- Accessibility: WCAG 2.1 AA compliance (see Accessibility Requirements below)

## Accessibility Requirements
- [ ] Semantic HTML for all UI components (no div-buttons)
- [ ] ARIA landmark roles on all page regions
- [ ] ARIA attributes on interactive widgets (menus, modals, tabs, accordions)
- [ ] Keyboard navigation: all features accessible without a mouse
- [ ] Visible focus indicators on all interactive elements
- [ ] Color contrast: 4.5:1 minimum (normal text), 3:1 (large text)
- [ ] Alt text on all informational images
- [ ] Form labels, error messages, and required field indicators
- [ ] Skip navigation link on pages with repeated nav
- [ ] Dynamic content announced via aria-live regions
- [ ] Target compliance level: [WCAG 2.1 AA / WCAG 2.2 AA / Section 508]
- [ ] Testing approach: [Manual screen reader testing / axe-core / Lighthouse / pa11y]

PLAN.md Template

PLAN.md Template
# Implementation Plan

## Phase 1: Foundation (Week 1-2)
- [ ] Project initialization and configuration
- [ ] Database schema setup
- [ ] Authentication system
- [ ] Basic UI framework

## Phase 2: Core Features (Week 3-4)
- [ ] Feature 1: [Name]
  - [ ] Backend API endpoints
  - [ ] Frontend components
  - [ ] Integration tests

## Phase 3: Polish (Week 5-6)
- [ ] Performance optimization
- [ ] Accessibility audit
- [ ] Security review

## Database Schema
[Schema definitions]

## API Endpoints
| Method | Endpoint | Purpose | Priority |
|--------|----------|---------|----------|
| POST | /api/auth/login | User login | High |

## Component Hierarchy
[Component tree structure]

## Dependencies
- Production: [list]
- Development: [list]

Layer 2: Stable Reference Templates

See F3_TEMPLATES.md for complete templates for:

  • docs/architecture.md - System design documentation
  • docs/decisions.md - Architecture Decision Records
  • docs/stack.md - Technology stack details
  • docs/api.md - API documentation

Layer 3: Living State Templates

See F3_TEMPLATES.md for complete templates for:

  • docs/devlog.md - Development session logs
  • docs/todo.md - Task tracking
  • docs/changelog.md - Release history

Why F3 Works

✅ Area 1: Foundation (Spec + Plan)

Clarity before code. Requirements and architecture documented upfront prevent scope creep and architectural mistakes. You know exactly WHAT you're building and HOW before writing code.

✅ Area 2: Implementation (Build ↔ Guide)

Continuous quality control. The integrated Build ↔ Guide cycle means Claude's work is reviewed immediately, not after hours of autonomous coding. You catch issues early, maintain standards, and prevent wasted work.

This is the critical differentiator: You're not just setting Claude loose and hoping for the best. You're actively pair programming, steering every decision.

✅ Area 3: Documentation (Persistent Context)

Never lose your place. The three-layer documentation system solves Claude's context loss problem. Every session starts with full project knowledge. Session logs mean you can resume after any break.

Blocker resilience: Immediate documentation of technical issues ensures you can restart exactly where you stopped, even after system crashes or forced restarts.

Pro Tips

Foundation Area

  • Use Claude to ask probing questions you might miss
  • Write user stories with real scenarios, not generic ones
  • Define success metrics before building
  • Review the plan thoroughly before approving

Implementation Area (Critical)

  • Review every component before allowing Claude to continue
  • Redirect immediately when Claude deviates from standards
  • Require explanations for complex features before implementation
  • Enforce step-by-step progress—never let Claude run ahead
  • Watch for warning signs (unplanned features, skipped tests, etc.)
  • Remember: This is pair programming, not autonomous coding
  • Use ultrathink for major architectural decisions

Documentation Area

  • Keep CLAUDE.md under 500 lines (it's an index)
  • Update docs during development, not after
  • Use /clear between unrelated tasks
  • Review docs weekly for accuracy
  • Version control everything

File Glossary

A lookup reference for every file F3 creates or expects in a project. Grouped by role. Use this when you need to answer "what is this file for?" without reading the rest of the docs.

Framework Modules (project root)

Read on demand via @F3_*.md syntax in Claude Code. Each module stays under the 25,000-token per-file read limit.

FileContainsWhen Claude reads it
F3-README.mdFile & folder reference — authoritative map of every file F3 creates or expectsOn request; orientation
F3_FRAMEWORK.mdHub and routing table — points to the other modulesFirst; then whichever module the task needs
F3_CORE.mdMethodology, production standards, and the ten operational guardrails (G-01 through G-10)Starting a project; understanding F3 rules
F3_PROMPTS.mdEvery implementation prompt — copy-paste form plus slash-command shortcutsWhen a specific prompt is needed outside its slash command
F3_TEMPLATES.mdCLAUDE.md, SPEC.md, and every /docs/ templateSetting up F3 for the first time in a project
F3_SETUP.mdInstallation, onboarding, new vs. existing project workflowsFirst-time setup or adding F3 to an existing project
F3_CHANGELOG.mdVersion history, migration notes, roadmapChecking what changed between versions

Platform Bootstrap (project root)

Lean session bootstrap, under 1,300 tokens. One of these is always present and platform-specific. Auto-read every session.

FilePlatformNotes
CLAUDE.mdClaude CodeAuto-read every session. Contains project identity, active phase, and pointers to F3_*.md modules.
CURSOR.mdCursorSame lean pattern; uses Cursor's @-mention / composer attachment.
GEMINI.mdGemini CLISame pattern; files must live in working dir for Gemini to see them.
.codex/AGENTS.mdOpenAI CodexSame pattern; lives in .codex/ per Codex convention.

Foundation Documents (project root)

FilePurposeWho writes it
SPEC.mdProject specification — vision, features, acceptance criteria, non-functional requirementsDeveloper + Claude via Feature Specification prompt
PLAN.mdImplementation plan — phases, architecture, component list, file structureClaude after reading SPEC.md; developer approves
CONTRIBUTORS.mdTeam role and ownership registry — Lead, Developer, Reviewer roles by areaInstaller creates; team maintains
FIRST_RUN.mdFirst-session bootstrap written by the installer. Self-deletes at first /project:f3:es. Local-only (gitignored).Installer writes; /project:f3:es deletes

F3 Tooling (f3-foundation/)

FileRole
f3-foundation/tools/setup-f3.jsInstaller. Fresh install + --update smart update. Two-predicate detection of project state. Self-contained — every other F3 file is embedded inside this script, so users only need to download this one file to install or upgrade.
f3-foundation/tools/f3-audit.jsDiscovery audit scanner — produces docs/AUDIT.md. Runs automatically on install for existing codebases. Deployed by the installer (embedded).
f3-foundation/tools/generate-governance-report.jsSession governance report generator. Invoked by /project:f3:gr. Deployed by the installer (embedded).
f3-foundation/tools/uninstall-f3.jsF3 removal tool. Reverses the installer's changes — removes framework files, hooks, and config while preserving project content (SPEC.md, PLAN.md, docs/, application code). Deployed by the installer (embedded).
f3-foundation/compat/README.mdIndex of F3 compatibility guides. Catalogs external frameworks and tools that F3 has documented integration patterns with. Deployed by the installer (embedded).
f3-foundation/compat/superpowers.mdCompatibility guide for running F3 alongside Superpowers (obra / Jesse Vincent). Covers integration points, conflict avoidance, and recommended configuration when both frameworks are active. Deployed by the installer (embedded).
f3-foundation/scripts/load-context.jsOn-demand context loader (cross-platform). Pumps specific modules into Claude's context without reading the whole framework.
f3-foundation/scripts/load-context.shSame as above, macOS/Linux shell variant.

Claude Code Configuration (.claude/)

FileRole
.claude/settings.jsonWires all F3 hooks across five Claude Code events: PreToolUse, PostToolUse, PostToolUseFailure, SessionStart, and UserPromptSubmit. Committed to git.
.claude/commands/f3/*.mdSlash command prompts. Each file becomes /project:f3:[name]. See Slash Commands section for the full list.
.claude/hooks/f3-phase-gate.{sh,js}Foundation check. Blocks work if SPEC.md or PLAN.md are missing.
.claude/hooks/f3-restart-gate.{sh,js}Blocks server restart commands until checkpoint.md has been updated.
.claude/hooks/f3-commit-gate.{sh,js}Blocks git commit if devlog.md, TASKS.md, or .f3/session.active are stale. Enforcement only — /project:f3:es owns compilation.
.claude/hooks/f3-thrash-detector.{sh,js}Blocks all commands after 3 consecutive failures until an Issue Review Brief is generated or the counter is manually reset.
.claude/hooks/f3-first-run-loader.{sh,js}Injects FIRST_RUN.md contents into Claude's context on first session open via SessionStart and UserPromptSubmit events. The installer tells the user to send first-run as their first message; the hook fires on any prompt and handles the protocol regardless. Makes the self-directing first-session behavior mechanically enforced rather than dependent on Claude noticing the conditional instruction in CLAUDE.md. Becomes a silent no-op once /project:f3:es deletes FIRST_RUN.md at first session close. Dual-event wiring dodges Claude Code bug #10373 where SessionStart stdout is dropped on brand-new sessions.
.claude/thrash-countRuntime counter for thrash detection. Gitignored.

Universal Git Hook (.githooks/)

FileRole
.githooks/pre-commitRuns at actual git commit time in every editor — VS Code, terminal, anywhere. Same enforcement as f3-commit-gate but catches commits made outside a Claude Code session. Auto-installed to .git/hooks/pre-commit by setup-f3.js.

Project Documentation (docs/)

Layer 2 — Stable Reference. Change when project architecture changes.

FileContains
docs/architecture.mdSystem design, components, data flow, integration points.
docs/decisions.mdArchitecture Decision Records (ADRs) — rationale for every non-trivial technical choice.
docs/stack.mdTech stack inventory, dependencies, environment setup, version constraints.
docs/api.mdAPI contracts — endpoints, request/response shapes, authentication.

Layer 3 — Living State. Change every session.

FileContainsLocal-only?
docs/checkpoint.mdSession intent — written at session OPEN. Declares starting state and what the session is taking on.Yes (gitignored)
docs/devlog.mdSession log — append-only, timestamped entries for every session.Yes (gitignored)
docs/TASKS.mdDeveloper task tracking — current priorities, backlog, DOC-DRIFT items.Yes (gitignored)
docs/changelog.mdRelease history — committed to git.No

Generated artifacts.

FileGenerated byPurpose
docs/AUDIT.mdf3-audit.js (auto on install)Discovery audit — security, accessibility, dead files, dependency drift, production-standards gaps. First thing Claude reads on existing projects.
docs/analysis/Claude, during workScratch analysis files. Local-only (gitignored).
docs/migration/Claude, during workDeveloper briefs and upgrade scratch. Local-only (gitignored).
docs/governance//project:f3:grSession governance reports — JSON + Markdown pair per report. Committed to git.

Session Record (commit/)

PathRole
commit/YYYY/MM/YYYY-MM-DD_[developer]_[hash].mdPermanent session record. One file per /project:f3:es commit. Filename encodes date, developer (from git), and commit hash. Committed to git — this is the long-term project history. Synthesized by /project:f3:archrebuild to rebuild Layer 2 docs.

Session Marker (.f3/)

FileRole
.f3/session.activeSession presence marker. Created at session open, deleted at session close by /project:f3:es. Checked by the commit gate to detect stale sessions. Local-only (gitignored).

Troubleshooting

Claude ignoring standards:

  • Verify CLAUDE.md is in project root
  • Use /memory to check loaded files
  • Be more explicit in critical rules section
  • Guide more actively—don't let Claude run ahead

Context window filling:

  • Use /clear between unrelated tasks
  • Move completed notes out of chat
  • Use external files for checklists

Lost context after restart:

  • Connection dropped? Use "Crash Recovery" prompt — reads checkpoint.md for fast resume
  • If checkpoint.md is stale, fall back to "Context Recovery" prompt for full re-read
  • Check CLAUDE.md updated recently
  • Review last devlog entry (including BLOCKERs)
  • If resuming after blocker, use "Resume After Blocker" prompt

Implementation going off track:

  • Guide more frequently—review every component
  • Redirect immediately when deviating
  • Require explanations before implementations
  • Break tasks into smaller pieces