Metadata-Version: 2.4
Name: spechatch
Version: 0.48.0
Summary: Spec-Driven Development (SDD) CLI, Native MCP Server & Multi-Project Incubator Server for human + AI agent teams.
Keywords: sdd,spec-driven-development,ai-agents,mcp,model-context-protocol,cli,roadmap,fastapi
Author: Carlo Tasca
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Documentation
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Dist: pydantic-settings>=2.16.3
Requires-Dist: pyyaml>=6.0.4
Requires-Dist: alembic>=1.20.1 ; extra == 'incubator'
Requires-Dist: argon2-cffi>=25.1.0 ; extra == 'incubator'
Requires-Dist: fastapi>=0.165.0 ; extra == 'incubator'
Requires-Dist: psycopg[binary]>=3.3.9 ; extra == 'incubator'
Requires-Dist: sqlmodel>=0.0.50 ; extra == 'incubator'
Requires-Dist: uvicorn[standard]>=0.54.0 ; extra == 'incubator'
Requires-Dist: mcp>=2.3.0 ; extra == 'mcp'
Requires-Dist: cryptography>=50.0.2 ; extra == 'mysql'
Requires-Dist: pymysql>=1.2.4 ; extra == 'mysql'
Requires-Python: >=3.11
Project-URL: Homepage, https://spechatch.dev
Project-URL: Documentation, https://github.com/ctasca/spechatch#readme
Project-URL: Repository, https://github.com/ctasca/spechatch
Project-URL: Issues, https://github.com/ctasca/spechatch/issues
Provides-Extra: incubator
Provides-Extra: mcp
Provides-Extra: mysql
Description-Content-Type: text/markdown

<p>
  <img src="https://raw.githubusercontent.com/ctasca/spechatch/main/media/spechatch-logo.svg" alt="spechatch — Spec-Driven Incubator" width="340" />
</p>

![Version](https://img.shields.io/badge/version-0.48.0-6366f1)
[![CI](https://img.shields.io/badge/CI-passing-brightgreen.svg)](https://github.com/ctasca/spechatch/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ctasca/spechatch/blob/main/LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-3776ab?logo=python&logoColor=white)](https://www.python.org/)
![Tests](https://img.shields.io/badge/tests-234%20passed-22c55e)
[![Code style: ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Type checked: mypy](https://img.shields.io/badge/type--checked-mypy-blue?logo=python&logoColor=white)](https://mypy-lang.org/)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
[![MCP](https://img.shields.io/badge/MCP-native%20server-0891b2)](https://modelcontextprotocol.io/)
[![FastAPI](https://img.shields.io/badge/FastAPI-incubator-009688?logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com/)
![Databases](https://img.shields.io/badge/DB-Postgres%20%7C%20MySQL%20%7C%20SQLite-336791)
![Locales](https://img.shields.io/badge/locales-5%20languages-8b5cf6)
![Specs](https://img.shields.io/badge/specs-67%20verified-10b981)

**Spec-Driven Development (SDD) CLI, Native MCP Server & Multi-Project Incubator Server** for human + AI agent teams.

`spechatch` keeps specifications as the living source of truth across one or many repositories: it scaffolds project constitutions, multi-lingual templates (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`), a 3-tier catalog of bundled & team-owned AI agent skills and rule packs (Antigravity, Cursor, Claude Code, Codex, VS Code / GitHub Copilot), a native Model Context Protocol (MCP) server, monotonic spec IDs (`promote` from `BS-*`/`NTH-*` to `spec`/`epic`), deterministic roadmaps ([specs/ROADMAP.md](https://github.com/ctasca/spechatch/blob/main/specs/ROADMAP.md)), Keep a Changelog generation (`changelog`), SemVer/CalVer manifest bumping (`version`), single-command workspace diagnostics (`doctor`), zero-dependency shell autocompletion (`zsh`, `bash`, `fish`, `powershell`), Unix `man` pages, `sh-*` Makefile & `justfile` shortcuts, pre-commit spec-to-code drift verification, JUnit CI regression attribution, and an optional stateless FastAPI + PostgreSQL (Neon) / MySQL / MariaDB / SQLite incubator server for multi-developer and multi-agent coordination.

---

## Table of Contents

- [Documentation Guides](#documentation-guides)
- [Core Features](#core-features)
- [Installation](#installation)
- [Quickstart](#quickstart)
  - [1. Standalone Local SDD Workflow](#1-standalone-local-sdd-workflow)
  - [2. Multi-Project Incubator (Neon PostgreSQL / MySQL / SQLite)](#2-multi-project-incubator-neon-postgresql--mysql--sqlite)
- [CLI Reference](#cli-reference)
  - [Global Options (`man`, `completion`, `mcp`)](#global-options)
  - [Project & Agent Setup (`init`, `constitute`, `create`, `skills`, `rules`, `agents`)](#project--agent-setup)
  - [Spec Authoring & Local Verification (`new`, `promote`, `step`, `test`, `verify`, `resolve`, `doctor`, `roadmap`, `changelog`, `version`, `install-hooks`)](#spec-authoring--local-verification)
  - [Secrets Management (`secret`)](#secrets-management)
  - [Incubator Server & Coordination (`incubator`, `serve`, `admin`, `bootstrap`, `healthcheck`, `ping`, `sync`, `approve`, `revise`, `claim`, `epic`, `context`, `webhook`)](#incubator-server--coordination)
- [Agent Skills & Rule Packs (3-Tier Catalog)](#agent-skills--rule-packs-3-tier-catalog)
- [Configuration (`spechatch.project.yml`)](#configuration-spechatchprojectyml)
- [Secrets & Environment Variables (`SPECHATCH_*`)](#secrets--environment-variables-spechatch_)
- [Incubator HTTP & SSE API](#incubator-http--sse-api)
  - [Auth, RBAC & Open Mode](#auth-rbac--open-mode)
  - [Endpoints Reference](#endpoints-reference)
- [Docker Deployment](#docker-deployment)
- [Contributing & Roadmap](#contributing--roadmap)

---

## Documentation Guides

Prefer a step-by-step walkthrough with screenshots over the full reference below? Start here:

| Guide | What You'll Learn |
| :--- | :--- |
| **[Methodology & Philosophy](https://github.com/ctasca/spechatch/blob/main/docs/methodology-and-philosophy.md)** | Why SDD solves team/agent sync (`specdriven.ai` + TDD + BDD), human-in-the-loop checkpoints, architecture blueprinting, `GIVEN / WHEN / THEN` living docs, and canonical `Makefile`/`justfile` command entrypoints. |
| **[Getting Started (Local SDD)](https://github.com/ctasca/spechatch/blob/main/docs/getting-started.md)** | Install `spechatch`, scan your repo, author & promote specs, sync `ROADMAP.md`, bump versions, and generate `CHANGELOG.md`. |
| **[AI Agents & Native MCP](https://github.com/ctasca/spechatch/blob/main/docs/ai-agents-and-mcp.md)** | Browse & sync the 31-pack catalog across Antigravity, Cursor, Claude Code, Codex & Copilot, build custom packs, and wire up the 15-tool MCP server. |
| **[Incubator Server Setup](https://github.com/ctasca/spechatch/blob/main/docs/incubator-setup.md)** | Deploy the multi-project FastAPI Incubator (Neon PostgreSQL, MySQL/MariaDB, SQLite, or Docker), bootstrap RBAC, manage users/keys/projects via CLI, and ingest test health. |
| **[Webhooks & Notifications](https://github.com/ctasca/spechatch/blob/main/docs/webhooks-and-notifications.md)** | Stream HMAC-SHA256 signed lifecycle, regression, and version-bump alerts to Slack, Discord, Microsoft Teams, or custom JSON/Markdown templates. |
| **[Complete CLI Reference](https://github.com/ctasca/spechatch/blob/main/docs/cli-reference.md)** | Exhaustive reference of all 34 CLI commands, every nested subcommand, flag, option, example, file, and exit code (generated from `spechatch man`). |

---

## Core Features

- **Zero-Ambiguity Spec Lifecycle & Ideation Promotion:** Multi-artifact specs (`specification.md`, `plan.md`, `tasks.md`) for full features, single-file stubs for `bugfix` (`BUG-*`), `hotfix` (`HF-*`), `brainstorm` (`BS-*`), `nice-to-have` (`NTH-*`), and `code-review` (`CR-*`), first-class `epic` (`E-*`) initiatives with acyclic `depends_on` DAGs, and `spechatch promote` to graduate `BS-*`/`NTH-*` ideas into full specs or epics with full `promoted_from`/`promoted_to` audit trails. Built-in BCP 47 localization (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`) keeps prose and roadmaps localized while preserving canonical English frontmatter keys and statuses.
- **Project Constitution & 3-Tier Multi-Agent Packs:** `spechatch init --scan` and `spechatch constitute --scan` ground AI agents in your repository's real stack, test runners, and canonical command entrypoints across **Antigravity** (`.agents/`), **Cursor** (`.cursor/rules/*.mdc`), **Claude Code** (`.claude/skills/` + managed `CLAUDE.md`), **Codex** (managed `AGENTS.md`), and **VS Code / GitHub Copilot** (`.github/skills/`, `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md`). Browse and toggle 31 bundled packs (12 skills + 19 rule packs across Core, Tier 1 Methodology, and Tier 2 Stack-Detected Tooling) plus **Tier 3 Custom/Team packs** from `.spechatch/packs/` or shared directories (`agents.pack_dirs`).
- **Native MCP Server (`[mcp]` extra) & Auto-Sync:** `spechatch mcp` exposes **15 SDD tools** and **3 live resources** (`spechatch://constitution`, `spechatch://roadmap`, `spechatch://config`) over `stdio` or `streamable-http`. Setting `SPECHATCH_INCUBATOR_AUTO_SYNC=true` enables automatic Incubator sync across both CLI commands (with `--local` opt-out) and MCP tools, falling back gracefully with a warning when offline.
- **Developer Ergonomics (`doctor`, Autocompletion, `man` Pages & `sh-*` Shortcuts):** Single-command workspace audit (`spechatch doctor`), zero-dependency native shell autocompletion (`spechatch completion <zsh|bash|fish|powershell> --install` with live spec-ID completion), grouped `--help`, dynamically generated Unix `man` pages (`spechatch man [COMMAND] --install`), and `spechatch create makefile` / `spechatch create justfile` for low-typing `sh-*` wrappers across macOS, Linux, and Windows.
- **Deterministic Validation & Pre-Commit Drift Guard:** `spechatch test`, `spechatch test run`, and `spechatch verify --staged` enforce frontmatter schemas, Clarify ambiguity gates (`[NEEDS CLARIFICATION]`), dead test-link detection, non-empty JUnit execution (`executed_count > 0`), roadmap sync, and `files:`/`contracts:` spec-to-implementation drift checks (`mode: advisory | strict`).
- **Multi-Project Incubator Server (`[incubator]` & `[mysql]` extras):** FastAPI + SQLModel + Alembic supporting Neon/PostgreSQL, MySQL 8+/MariaDB 10.6+ (`[mysql]`), and local SQLite with `SPECHATCH_TABLE_PREFIX`, live DB healthchecks (`SELECT 1`), Argon2id users, SHA-256 `shk_*` API keys (`actor_type: human | agent | ci`), project RBAC, atomic monotonic IDs (`Idempotency-Key`), human-only checkpoint approvals, living revisions with Change Deltas, soft advisory TTL leases, Epics DAG roll-up, live SSE streams, JUnit CI regression attribution (`health: healthy | regressed`), and HMAC-SHA256 signed filtered webhooks.
- **Project-Scoped Local & Global Secrets:** `spechatch secret` manages `0600`-permissioned `.env` stores (`~/.config/spechatch/.env` with `SPECHATCH_<SECRET_PREFIX>_<KEY>` isolation + `.spechatch/.env` auto-gitignored overrides that keep `.spechatch/templates/` and `.spechatch/packs/` committable) and automatically trims stray outer whitespace on write.

---

## Installation

`spechatch` requires **Python 3.11+** and can be installed globally via [uv](https://docs.astral.sh/uv/) (recommended), `pipx`, or `pip`:

```bash
# With uv (recommended — isolated global CLI)
uv tool install spechatch                          # Core standalone CLI
uv tool install "spechatch[incubator,mcp,mysql]"   # Core + Incubator + MCP + MySQL/MariaDB

# With pipx (isolated global CLI)
pipx install "spechatch[incubator,mcp,mysql]"

# With pip (inside a virtual environment)
pip install spechatch                              # Core standalone CLI
pip install "spechatch[incubator,mcp,mysql]"       # All optional extras
```

For contributors working from a source checkout:

```bash
# Core CLI + dev tools
uv sync

# Optional extras (combine as needed):
uv sync --extra incubator          # FastAPI / SQLModel / Alembic / PostgreSQL (Neon) / SQLite
uv sync --extra mcp                # Native Model Context Protocol (MCP) server
uv sync --extra mysql              # PyMySQL + cryptography driver for MySQL / MariaDB
uv sync --all-extras               # Everything (recommended for contributors & full setups)
```

**Windows (PowerShell):**

```powershell
# Install uv (if not already installed)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Install spechatch with all extras
uv tool install ".[incubator,mcp,mysql]"

# Optional: native PowerShell autocompletion & cross-platform justfile shortcuts
spechatch completion powershell --install
spechatch create justfile
```

---

## Quickstart

### 1. Standalone Local SDD Workflow

```bash
# 1. Scan repository and generate spechatch.project.yml
uv run spechatch init --scan

# 2. Generate starter specs/constitution.md from your repo stack
uv run spechatch constitute --scan

# 3. Sync bundled SDD skills & rules (Antigravity, Cursor, Claude Code, Codex)
uv run spechatch agents sync

# 4. Optional: set a default author handle and add low-typing `make sh-*` shortcuts
uv run spechatch secret put AUTHOR your-handle
uv run spechatch create makefile --append

# 5. Scaffold an epic and a child spec
uv run spechatch new epic "User Authentication"
uv run spechatch new spec "JWT Login Flow" --epic E-0001 --version 0.2.0

# 6. Validate specs, sync specs/ROADMAP.md, and audit workspace health
uv run spechatch test
uv run spechatch roadmap sync
uv run spechatch verify
uv run spechatch doctor --skip-remote

# 7. Optional: install pre-commit hook, shell autocompletion, and Unix man pages
uv run spechatch install-hooks
uv run spechatch completion zsh --install
uv run spechatch man --install
```

### 2. Multi-Project Incubator (Neon PostgreSQL / MySQL / SQLite)

No local database Docker container is needed — connect directly to [Neon](https://neon.tech/) (PostgreSQL 15+), MySQL 8+/MariaDB 10.6+ (with `--extra mysql`), or fall back to local SQLite.

**Terminal 1 — Store your database URL and start the server:**

```bash
# Saves SPECHATCH_<PREFIX>_DATABASE_URL into ~/.config/spechatch/.env (0600)
# (or pass --shared to share one database across all projects)
uv run --all-extras spechatch secret put DATABASE_URL

# Optional: wake/verify the database directly before starting the server
uv run --all-extras spechatch ping --db

# Starts FastAPI + uvicorn on 127.0.0.1:8787 and runs Alembic migrations (0001-0008) automatically
uv run --all-extras spechatch serve
```

**Terminal 2 — Register the project and bootstrap existing specs:**

```bash
# Verify server health & live DB latency
uv run --all-extras spechatch healthcheck

# Create the project row (SPECHATCH_AUTH_ENABLED defaults to false for local dev;
# for authenticated deployments, first run `spechatch admin init` to mint a superuser key)
uv run --all-extras spechatch incubator project create my-project --name "My Project"

# Seed monotonic counters (highest + 1) and import existing local specs into the ledger
uv run --all-extras spechatch bootstrap

# Query live epic progress and agent orientation context
uv run --all-extras spechatch epic status E-0001
uv run --all-extras spechatch context
```

---

## CLI Reference

### Global Options

```text
spechatch [--version] [--config PATH] [--lang LOCALE] <command> [options]
```

| Flag | Description |
| :--- | :--- |
| `--version` | Print installed `spechatch` version and exit. |
| `--config PATH` | Path to `spechatch.project.yml` (overrides `SPECHATCH_CONFIG`). |
| `--lang LOCALE` | BCP 47 locale for generated templates and roadmap (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`; overrides `SPECHATCH_LOCALE` and `spechatch.project.yml`). |

#### `spechatch man [COMMAND]`
View, print, or install dynamically generated Unix man pages (`spechatch(1)` and `spechatch-<command>(1)`) derived from the live CLI parser and `SpechatchSettings`.

| Option | Description |
| :--- | :--- |
| `COMMAND` | Optional subcommand name (e.g. `new`, `roadmap`, `secret`); omit for `spechatch(1)`. |
| `--raw` | Print raw roff/troff source to stdout instead of opening the `man` pager. |
| `--install` | Install `spechatch.1` and all `spechatch-<command>.1` pages into `~/.local/share/man/man1` (or `--dir`) for native `man spechatch`. |
| `--dir PATH` | Custom target directory for `--install`. |

#### `spechatch completion <zsh|bash|fish|powershell>`
Generate or install zero-dependency native shell autocompletion scripts derived directly from the live CLI parser — completing all commands, nested subcommands, flags, value choices, paths, and live spec/epic IDs from `specs/` with instant Tab response.

| Option | Description |
| :--- | :--- |
| `shell` | Target shell: `zsh`, `bash`, `fish`, or `powershell`. |
| `--install` | Write the completion script into the shell's user completion directory (`~/.zsh/completions/_spechatch`, `~/.local/share/bash-completion/completions/spechatch`, `~/.config/fish/completions/spechatch.fish`, or your PowerShell `$PROFILE`). |
| `--dir PATH` | Custom target directory for `--install`. |

Quick activation:

```bash
# Zsh (add to ~/.zshrc) — or run: spechatch completion zsh --install
eval "$(spechatch completion zsh)"

# Bash (add to ~/.bashrc) — or run: spechatch completion bash --install
eval "$(spechatch completion bash)"

# Fish — or run: spechatch completion fish --install
spechatch completion fish | source

# PowerShell — or run: spechatch completion powershell --install
spechatch completion powershell | Out-String | Invoke-Expression
```

#### `spechatch mcp`
Start the native Model Context Protocol (MCP) server for AI coding agents (Antigravity, Cursor, Claude Code, Codex). Requires the optional `[mcp]` extra (`uv sync --extra mcp` or `pip install spechatch[mcp]`). Works standalone locally and automatically syncs with the Incubator when `SPECHATCH_INCUBATOR_AUTO_SYNC=true` (falling back gracefully with a warning if the server is unreachable).

- **Resources (3):** `spechatch://constitution`, `spechatch://roadmap`, `spechatch://config`.
- **Tools (15):** `spechatch_context`, `spechatch_list_specs`, `spechatch_new_spec`, `spechatch_promote`, `spechatch_step`, `spechatch_verify`, `spechatch_doctor`, `spechatch_version`, `spechatch_roadmap_sync`, `spechatch_claim`, `spechatch_revise`, `spechatch_epic_status`, `spechatch_epic_next`, `spechatch_healthcheck`, `spechatch_test_run`.

| Option | Description |
| :--- | :--- |
| `--transport MODE` | Transport mode: `stdio` (default) or `streamable-http`. |
| `--host HOST` | Bind host for `streamable-http` (default `127.0.0.1`). |
| `--port PORT` | Bind port for `streamable-http` (default `8788`). |

#### MCP Client Configuration (Project-Local vs. Global)

| IDE / Agent | Project-Local Config | Global User Config | Root Key |
| :--- | :--- | :--- | :--- |
| **Antigravity** | `.agents/plugins/spechatch/mcp_config.json` *(via workspace plugin)* | `~/.gemini/config/mcp_config.json` | `mcpServers` |
| **Cursor** | `.cursor/mcp.json` | `~/.cursor/mcp.json` | `mcpServers` |
| **VS Code (Copilot)** | `.vscode/mcp.json` | User `mcp.json` (`MCP: Open User Configuration`) | `servers` |
| **Claude Code** | `.mcp.json` | `~/.claude.json` *(or `claude mcp add ...`)* | `mcpServers` |
| **Codex CLI** | `.codex/config.toml` | `~/.codex/config.toml` | `[mcp_servers.spechatch]` |
| **Windsurf** | — | `~/.codeium/windsurf/mcp_config.json` | `mcpServers` |

> **Tip (macOS / GUI IDEs):** Desktop apps often do not inherit your shell `PATH`. For **global** configs, use the absolute path to `uv` (run `which uv`, e.g. `/Users/<you>/.local/bin/uv`) and pass `--directory /path/to/your/repo` so `uv` finds your project's `pyproject.toml` and `spechatch.project.yml`.

**1. Project-Local — Cursor (`.cursor/mcp.json`) & Claude Code (`.mcp.json`):**

```json
{
  "mcpServers": {
    "spechatch": {
      "command": "uv",
      "args": ["run", "--extra", "mcp", "spechatch", "mcp"]
    }
  }
}
```

**2. Global — Antigravity (`~/.gemini/config/mcp_config.json`), Cursor (`~/.cursor/mcp.json`), Claude Code & Windsurf:**

```json
{
  "mcpServers": {
    "spechatch": {
      "command": "/Users/<you>/.local/bin/uv",
      "args": [
        "run",
        "--directory",
        "/path/to/your/repo",
        "--extra",
        "mcp",
        "spechatch",
        "mcp"
      ]
    }
  }
}
```

**3. VS Code / GitHub Copilot — Project-Local (`.vscode/mcp.json`) or Global User `mcp.json`:**

```json
{
  "servers": {
    "spechatch": {
      "type": "stdio",
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "${workspaceFolder}",
        "--extra",
        "mcp",
        "spechatch",
        "mcp"
      ]
    }
  }
}
```

*(For VS Code's global User `mcp.json`, replace `"uv"` with `/Users/<you>/.local/bin/uv` and `"${workspaceFolder}"` with your repo path — or use a globally installed `spechatch` via `uv tool install ".[incubator,mcp,mysql]"`.)*

**4. Antigravity — Project-Local Workspace Plugin (`.agents/plugins/spechatch/`):**

Create two files inside your repo so Antigravity discovers and scopes the MCP server strictly to that workspace:

```json
// .agents/plugins/spechatch/plugin.json
{
  "name": "spechatch"
}
```

```json
// .agents/plugins/spechatch/mcp_config.json
{
  "mcpServers": {
    "spechatch": {
      "command": "/Users/<you>/.local/bin/uv",
      "args": ["run", "--extra", "mcp", "spechatch", "mcp"]
    }
  }
}
```

**5. Codex CLI — Project-Local (`.codex/config.toml`) or Global (`~/.codex/config.toml`):**

```toml
[mcp_servers.spechatch]
command = "uv"
args = ["run", "--extra", "mcp", "spechatch", "mcp"]
# For global ~/.codex/config.toml, use absolute uv path and add "--directory", "/path/to/your/repo"
```

**Windows Global MCP Config Paths:**
- **Antigravity:** `%USERPROFILE%\.gemini\antigravity\mcp_config.json` (or portable workspace plugin at `.agents/plugins/spechatch/`)
- **VS Code (Copilot):** `%APPDATA%\Code\User\mcp.json` (or portable `.vscode/mcp.json` using `${workspaceFolder}`)
- **Cursor:** `%USERPROFILE%\.cursor\mcp.json` (or portable `.cursor/mcp.json`)
- **Claude Code:** `%USERPROFILE%\.claude.json` (or portable `.mcp.json`)
- **Codex CLI:** `%USERPROFILE%\.codex\config.toml` (or portable `.codex/config.toml`)
- **Windsurf:** `%USERPROFILE%\.codeium\windsurf\mcp_config.json`
- *(On Windows, `uv` installs to `%USERPROFILE%\.local\bin\uv.exe`; JSON configs accept either escaped backslashes `C:\\Users\\...\\repo` or forward slashes `C:/Users/.../repo`, and `"command": "uv"` works portably across OSes when `uv` is on `PATH`.)*

---

### Project & Agent Setup

#### `spechatch init`
Generate `spechatch.project.yml` for the current repository.

| Option | Description |
| :--- | :--- |
| `--scan` | Scan repository languages, frameworks, `Makefile`/entrypoints, test runners, and existing `specs/` layout. |
| `--project SLUG` | Explicit project slug (defaults to scanned project name or directory name; also derives `secret_prefix`). |
| `--lang LOCALE` | Default project locale written to `spechatch.project.yml` (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`). |
| `--auto-packs` | Automatically enable stack-detected Tier 2 rule packs (`python-uv`, `typescript-strict`, `go-standard`, `rust-cargo`) when used with `--scan`. |
| `--packs NAMES` | Comma-separated bundled skills or rule packs to enable immediately in `spechatch.project.yml`. |
| `--force` | Overwrite an existing `spechatch.project.yml`. |

#### `spechatch constitute`
Generate starter `constitution.md` at `paths.constitution_file` (default `specs/constitution.md`). Resolves templates in order: explicit `--template` > `.spechatch/templates/constitution.md` > built-in renderer.

| Option | Description |
| :--- | :--- |
| `--scan` | Pre-populate tech stack and tooling sections from a repository scan. |
| `--template PATH` | Optional path to a custom Markdown template file (`{{project}}`, `{{languages}}`, `{{frameworks}}`, `{{mode}}`, `{{date}}`, etc.). |
| `--force` | Overwrite an existing constitution file. |

#### `spechatch create blueprint`
Scaffold a high-level architecture blueprint Markdown file (works even before `spechatch init`). Resolves templates in order: explicit `--template` > `.spechatch/templates/blueprint.md` > built-in template, substituting `{{name}}`, `{{slug}}`, `{{project}}`, and `{{date}}`.

| Option | Description |
| :--- | :--- |
| `--name NAME` | *(required)* Human-readable blueprint title (default output: `<slug>-blueprint.md`). |
| `--template PATH` | Optional path to a custom Markdown template file. |
| `--output PATH` | Optional output path (creates missing parent directories). |
| `--force` | Overwrite an existing blueprint file. |

#### `spechatch create makefile`
Generate a standalone `Makefile` (or non-destructively append/update a managed block in an existing `Makefile`) with low-typing `sh-*` shortcuts for every `spechatch` command.

| Option | Description |
| :--- | :--- |
| `--dir PATH` | Target directory where the `Makefile` will be created (defaults to project root). |
| `--output PATH` | Output filename or path (defaults to `Makefile` inside `--dir`). |
| `--runner CMD` | Override the `SPECHATCH` command prefix (auto-detects `uv run spechatch` or `spechatch`). |
| `--local-only` | Include only standalone Local SDD shortcuts (omit Incubator targets). |
| `--append` | Append or idempotently update the managed `# --- spechatch:begin ---` block inside an existing `Makefile`. |
| `--force` | Overwrite an existing `Makefile` completely. |

#### `spechatch create justfile`
Generate a cross-platform `justfile` (or non-destructively append/update a managed block in an existing `justfile`/`Justfile`) with `set windows-shell := ["powershell.exe", "-NoLogo", "-Command"]` and `sh-*` recipes for macOS, Linux, and Windows.

| Option | Description |
| :--- | :--- |
| `--dir PATH` | Target directory where the `justfile` will be created (defaults to project root). |
| `--output PATH` | Output filename or path (defaults to `justfile` inside `--dir`). |
| `--runner CMD` | Override the `spechatch` command prefix (auto-detects `uv run spechatch` or `spechatch`). |
| `--local-only` | Include only standalone Local SDD recipes (omit Incubator recipes). |
| `--append` | Append or idempotently update the managed `# --- spechatch:begin ---` block inside an existing `justfile`. |
| `--force` | Overwrite an existing `justfile` completely. |
| `--dry-run` | Preview the rendered `justfile` without writing to disk. |

#### `spechatch skills` / `spechatch rules` / `spechatch agents`
Manage bundled SDD skills (3 core + 9 optional methodology skills: `spechatch-code-review`, `spechatch-bug-triage`, `spechatch-safe-refactor`, `spechatch-security-review`, `spechatch-semver`, `spechatch-architecture-design`, `spechatch-accessibility-audit`, `spechatch-bdd-testing`, `spechatch-domain-driven-design`), rule packs (4 core + 11 methodology + 4 tooling: `python-uv`, `typescript-strict`, `go-standard`, `rust-cargo`), canonical command entrypoint rules, and multi-agent mirrors across Antigravity (`.agents/`), Cursor (`.cursor/rules/*.mdc`), Claude Code (`.claude/skills/*/SKILL.md` + managed `CLAUDE.md` block), Codex (managed `AGENTS.md` block), and VS Code / GitHub Copilot (`.github/skills/`, `.github/copilot-instructions.md`, `.github/instructions/*.instructions.md`). All Tier 1/2 packs are localized across all 5 BCP 47 locales (see full table in [Agent Skills & Rule Packs](#agent-skills--rule-packs-3-tier-catalog)).

- `spechatch <skills|rules|agents> catalog [--tier core|methodology|tooling|custom]` — Browse all bundled and Tier 3 custom/team skills and rule packs (`agents.pack_dirs`, default `[".spechatch/packs"]`) with enabled status.
- `spechatch <skills|rules|agents> add <NAME...> [--sync]` — Enable bundled skills/rule packs in `spechatch.project.yml` (and optionally sync immediately with `--sync`).
- `spechatch <skills|rules|agents> remove <NAME...>` — Disable bundled skills/rule packs in `spechatch.project.yml`.
- `spechatch <skills|rules|agents> list` — Show sync status (`synced`, `drifted`, `missing`, `unmanaged`).
- `spechatch <skills|rules|agents> sync [--dry-run] [--diff] [--force]` — Render and write managed files (`<!-- managed-by: spechatch -->`). Never overwrites custom unmanaged rules unless `--force` is passed.

---

### Spec Authoring & Local Verification

#### `spechatch new <kind> <title>`
Scaffold a new spec using configured counters and templates, executing matching `before-spec` and `after-spec` hooks.

| Option | Description |
| :--- | :--- |
| `kind` | Spec kind configured in `paths.kinds` (`epic`, `spec`, `bugfix`, `hotfix`, `brainstorm`, `nice-to-have`, `code-review`, or custom). |
| `title` | Human-readable spec title. |
| `--epic ID` | Owning epic ID (e.g. `E-0001`). |
| `--depends-on IDS` | Comma-separated upstream spec IDs (e.g. `000001,000002`). |
| `--version VER` | Target or shipped SemVer version (e.g. `0.4.1`). |
| `--author HANDLE` | Author handle written to frontmatter `authors:` (defaults to `SPECHATCH_AUTHOR` when configured). |
| `--offline` | Allocate a non-colliding `DRAFT-YYYYMMDD-<slug>` ID without advancing counters (reconcile later with `spechatch sync`). |
| `--remote` | Atomically allocate the spec ID from the incubator server (`POST /ids` with `Idempotency-Key`) and upsert to `/roadmap`. |
| `--id ID` | Explicit spec ID override. |
| `--no-hooks` | Skip configured `before-spec` and `after-spec` hooks. |

#### `spechatch promote <spec_id>`
Promote a `brainstorm` (`BS-*`) or `nice-to-have` (`NTH-*`) spec into a full `spec` (default) or `epic`, preserving the source file and full audit trail (`promoted_from` / `promoted_to` cross-links, `status: done` on source, and automatic `ROADMAP.md` sync).

| Option | Description |
| :--- | :--- |
| `spec_id` | Source `brainstorm` or `nice-to-have` ID (e.g. `BS-0001`, `NTH-0001`). |
| `--to KIND` | Target kind: `spec` (default) or `epic`. |
| `--title TITLE` | Optional title override for the promoted spec (defaults to source title). |
| `--epic ID` | Owning epic ID (e.g. `E-0001`). |
| `--depends-on IDS` | Comma-separated upstream spec IDs. |
| `--version VER` | Target SemVer version. |
| `--author HANDLE` | Author handle (defaults to `SPECHATCH_AUTHOR` or source authors). |
| `--remote` | Atomically allocate the target ID from the incubator and upsert both specs. |
| `--id ID` | Explicit target spec ID override. |
| `--force` | Allow re-promoting a spec that already has `promoted_to` set. |
| `--no-hooks` | Skip configured `after-spec` hooks. |

#### `spechatch step <spec_id>`
Parse `tasks.md` checkboxes and print granular completion (`tasks_done/tasks_total`).

| Option | Description |
| :--- | :--- |
| `--remote` | Upsert updated task progress to the incubator ledger. |

#### `spechatch test [spec_id]`, `spechatch test run` & `spechatch test ingest`
Validate specs locally, run configured test runners with automatic JUnit attribution, or ingest pre-built CI JUnit XML reports.

- **Local Spec Validation:** `spechatch test [spec_id] [--run-linked]`
  - Validates YAML frontmatter, required multi-artifacts, Clarify `[NEEDS CLARIFICATION]` markers, and dead test links.
  - `--run-linked` executes linked test commands declared in spec frontmatter and enforces the non-empty JUnit execution gate (`executed_count > 0`).
- **One-Command Run & Health Sync (Language-Agnostic):** `spechatch test run [--runner NAME] [--commit SHA] [--branch NAME] [--remote]`
  - Executes all configured `tests.runners` from `spechatch.project.yml` (Python, Vitest, Playwright, Go, Rust, etc.) into temporary JUnit XML file(s), auto-detects Git commit & branch, attributes results to linked specs, and with `--remote` updates live spec `health` (`untested` → `healthy` | `regressed`) in the incubator DB in one step:
  ```bash
  uv run --all-extras spechatch test run --remote
  ```
- **CI JUnit Regression Attribution:** `spechatch test ingest --junit <path_or_glob> [--junit ...] [--commit SHA] [--branch NAME] [--remote]`
  - Parses standard JUnit XML reports (`pytest`, `vitest`, `jest`, `playwright`, `go test`, `cargo nextest`) and maps passing/failing test cases back to linked specs.
  - Exits `1` if any spec regressed; with `--remote`, pushes attribution to `POST /tests/ingest`, updates live `health` (`untested` → `healthy` | `regressed`), and triggers `spec.regressed` SSE & webhook alerts.

  Example — run pytest and update spec `health` in the incubator database:
  ```bash
  uv run --all-extras pytest --junitxml=/tmp/junit.xml
  uv run --all-extras spechatch test ingest --junit /tmp/junit.xml \
    --commit $(git rev-parse --short HEAD) \
    --branch $(git branch --show-current) \
    --remote
  ```

#### `spechatch verify`
Unified offline pre-commit and CI gate combining spec validation, roadmap drift detection, and staged spec-to-implementation drift checks.

| Option | Description |
| :--- | :--- |
| `--staged` | Inspect staged Git files (`git diff --cached`) against `files:` and `contracts:` ownership globs of `complete` specs. |
| `--run-linked` | Also execute linked test commands declared in spec frontmatter. |
| `--no-roadmap` | Skip `specs/ROADMAP.md` drift verification. |
| `--json` | Emit a machine-readable JSON verification report. |

Respects `mode` in `spechatch.project.yml`: exits `1` on findings in `strict` mode; prints warnings and exits `0` in `advisory` mode.

#### `spechatch resolve`
Deterministically resolve post-merge conflicts in standalone/multi-branch repos: renumbers duplicate spec IDs (keeping the earliest spec by `created` timestamp, or `--keep PATH`), regenerates conflicted `specs/ROADMAP.md`, and flags any spec files with unresolved prose Git conflict markers (`<<<<<<<`) without modifying them.

| Option | Description |
| :--- | :--- |
| `--dry-run` | Preview planned renumbering and roadmap regeneration without writing files. |
| `--keep PATH` | Spec path that should retain its original ID when resolving a duplicate (repeatable). |
| `--json` | Emit a machine-readable JSON resolution report. |

#### `spechatch doctor`
Run a read-only, single-command diagnostic audit of your workspace (`config`, `constitution`, `specs`, `git-hooks`, `agents`, `secrets`, `shell-docs`, and `incubator`).

| Option | Description |
| :--- | :--- |
| `--skip-remote` | Skip the Incubator HTTP/DB health probe (for standalone offline workspaces). |
| `--timeout SECONDS` | HTTP timeout in seconds for the Incubator probe (default `5.0`). |
| `--strict` | Treat warnings as failures (exit code `1`). |
| `--json` | Emit a machine-readable JSON diagnostic report. |

#### `spechatch roadmap`
- `spechatch roadmap sync [--dry-run] [--remote]` — Deterministically render `specs/ROADMAP.md` grouped by kind (`Epics`, `Specs`, `Bugfixes`, `Hotfixes`, etc.) with `Version` and `YYYY-MM-DD HH:MM` timestamps. Pass `--remote` to also upsert all local specs to the incubator database (`developer+` role).
- `spechatch roadmap diff` — Exit `1` and show unified diff if `specs/ROADMAP.md` is out of sync with `specs/`.

#### `spechatch changelog`
Deterministically generate Keep a Changelog Markdown (or structured JSON) directly from completed, versioned specifications (`Features` for `spec`/`epic`, `Bug Fixes` for `bugfix`/`hotfix`, sorted by descending SemVer).

| Option | Description |
| :--- | :--- |
| `--version VER` | Render release notes for a single SemVer version (exits `1` if not found). |
| `-o, --output PATH` | Write rendered Markdown to `PATH` instead of stdout (e.g. `CHANGELOG.md`). |
| `--include-unreleased` | Include active non-done specs under an `## [Unreleased]` section. |
| `--json` | Emit structured JSON (`project`, `versions`, `unreleased`). |

#### `spechatch version`
Inspect or bump the project's version across all auto-detected manifests (`pyproject.toml` + `uv.lock`, `package.json` + `package-lock.json`, `Cargo.toml`, `VERSION`, and `README.md` Shields.io version badges) using SemVer or CalVer.

- `spechatch version [show] [--remote | --local] [--file PATH] [--json]` — Print the current project version and detected manifests; with `--remote` (or `SPECHATCH_INCUBATOR_AUTO_SYNC=true`), compares against the Incubator's tracked version and flags drift.
- `spechatch version bump [patch|minor|major|<explicit>] [--semver | --calver] [--pre LABEL] [--remote | --local] [--file PATH] [--dry-run] [--no-lock] [--json]` — Bump and synchronize manifests (with `--remote`, atomically allocates the next monotonic version on the Incubator and dispatches `version.bumped` webhooks).

#### `spechatch install-hooks`
Install or remove the managed `.git/hooks/pre-commit` shim (`# managed-by: spechatch`, chmod `0755`, supports Git worktrees) that runs `spechatch verify --staged`.

| Option | Description |
| :--- | :--- |
| `--force` | Overwrite an existing unmanaged `.git/hooks/pre-commit` file. |
| `--uninstall` | Remove the managed pre-commit hook (refuses to delete unmanaged hooks). |

---

### Secrets Management

#### `spechatch secret <put|edit|get|list|delete>`
Manage `0600`-permissioned secrets without editing `.env` files by hand or leaking credentials in shell history. Leading and trailing whitespace is automatically stripped on write (`put` / `edit`), and whitespace-only values are rejected.

| Subcommand | Description |
| :--- | :--- |
| `secret put <KEY> [VALUE]` | Create or update a secret (prompts securely via `getpass` when `VALUE` is omitted). |
| `secret edit <KEY> [VALUE]` | Update an existing secret (fails if key does not exist). |
| `secret get <KEY> [--reveal]` | Print a stored secret (masked by default; pass `--reveal` for plaintext). |
| `secret list [--reveal]` | List stored secrets with `[global\|local]` origin. |
| `secret delete <KEY>` | Remove a secret key from the store. |

**Scope & Prefix Flags:**

| Flag | Behavior |
| :--- | :--- |
| *(default)* | Stores in `~/.config/spechatch/.env` prefixed with the project's `secret_prefix` (`SPECHATCH_<PREFIX>_<KEY>`) so multiple projects never collide. |
| `--shared` | Stores in `~/.config/spechatch/.env` without project prefix (`SPECHATCH_<KEY>`) as a cross-project fallback. |
| `--local` | Stores in `<repo>/.spechatch/.env` (auto-added to `.gitignore`) without project prefix (`SPECHATCH_<KEY>`) since the file is already repo-scoped. |
| `--global` | *(on `get` / `list`)* Restrict lookup to `~/.config/spechatch/.env`. |

---

### Incubator Server & Coordination

#### `spechatch incubator <init | user | key | project | member | audit>`
Scaffold Docker deployment files and manage multi-project Incubator users, API keys, projects, per-project RBAC memberships, and audit logs from the CLI (no raw `curl` needed):

- `spechatch incubator init [--path DIR] [--filename NAME] [--version VER] [--force]` — Generate a PyPI-based `Dockerfile` (with non-root `USER spechatch`, `[incubator,mysql]` drivers, and `/api/spechatch/v1/health` `HEALTHCHECK`) and `.dockerignore`.
- `spechatch incubator user <create|list|update|activate|deactivate>` — Manage user accounts (`superuser` only; blocks deactivating/demoting the last active superuser).
- `spechatch incubator key <create|list|revoke>` — Mint (`human`/`agent`/`ci`), list, or revoke `shk_*` API keys.
- `spechatch incubator project <create|list|show|update|activate|deactivate>` — Create (`superuser`), inspect, update, or archive projects (`owner`/`superuser`).
- `spechatch incubator member <add|list|remove>` — Assign (`owner`/`maintainer`/`developer`/`viewer`), list, or remove project memberships (accepts user ID or username).
- `spechatch incubator audit [--limit N] [--json]` — View recent auth and admin audit log events (`superuser` only).

#### `spechatch serve`
Start the FastAPI incubator server (requires `[incubator]` extra). Automatically runs Alembic `upgrade head` on startup.

| Option | Description |
| :--- | :--- |
| `--host HOST` | Bind host (default `127.0.0.1`). Non-loopback binds require `SPECHATCH_AUTH_ENABLED=true` unless `--allow-insecure-open-mode` is passed. |
| `--port PORT` | Bind port (default `8787`). |
| `--reload` | Enable uvicorn auto-reload for local development. |
| `--allow-insecure-open-mode` | Explicitly allow non-loopback binding with `SPECHATCH_AUTH_ENABLED=false`. |

#### `spechatch admin <init|reset-password|transfer-superuser>`
DB-direct operator bootstrap and break-glass recovery commands against `SPECHATCH_DATABASE_URL` (requires `[incubator]` extra; all actions are logged to `auth_audit_events`):

- `spechatch admin init [--username USER] [--full-name NAME] [--key-name LABEL]` — One-time creation of the initial `superuser` and one-time `shk_*` `human` API key (refuses to run if a `superuser` already exists).
- `spechatch admin reset-password <username> [--rotate-key] [--key-name LABEL]` — Resets the user's Argon2id password via `getpass`; with `--rotate-key`, revokes all prior API keys and mints a fresh one-time `shk_*` key.
- `spechatch admin transfer-superuser --from <old_user> --to <new_user> [--full-name NAME] [--key-name LABEL]` — Demotes and deactivates `<old_user>` (revoking all their API keys immediately) and promotes or creates `<new_user>` as `superuser` with a fresh one-time `shk_*` key.

#### `spechatch bootstrap`
Idempotently seed the incubator server's counters (`highest + 1`) and ledger rows from existing local `specs/` on disk.

#### `spechatch healthcheck` / `spechatch ping`
Check Incubator server availability, version, auth mode, and live database latency (`SELECT 1` via `GET /api/spechatch/v1/health`) — or pass `--db` to ping `SPECHATCH_DATABASE_URL` directly without a running server (useful for waking scale-to-zero Neon databases).

| Option | Description |
| :--- | :--- |
| `--db` | Ping `SPECHATCH_DATABASE_URL` directly (`SELECT 1`) without requiring a running server (requires `[incubator]` extra). |
| `--timeout SECONDS` | HTTP request timeout in seconds (default `15.0`). |
| `--json` | Print machine-readable JSON output. |

#### `spechatch sync`
Reconcile offline `DRAFT-*` specs against the incubator: atomically allocates sequential IDs (deterministic `Idempotency-Key`), renames draft folders/files, rewrites frontmatter `id:` + headings + cross-references (`depends_on` / `epic_id`), upserts to `/roadmap`, and syncs `specs/ROADMAP.md`.

#### `spechatch approve <spec_id> --phase <phase> [--comment NOTE]`
Record an immutable human checkpoint approval (`phase`: `specify | clarify | plan | tasks | implement`) bound to the spec's `content_hash` and `constitution_hash`. When `SPECHATCH_AUTH_ENABLED=true`, requires a `human` API key (`agent`/`ci` keys receive `403 Forbidden`).

#### `spechatch revise <spec_id> --summary TEXT [--added ...] [--modified ...] [--removed ...] [--no-local-delta]`
Open a new living revision (`rev + 1`) with a structured Change Delta (`Added` / `Modified` / `Removed`), append the Change Delta section to the local spec file (unless `--no-local-delta`), and reopen a `done` spec to `in_progress`.

#### `spechatch claim <spec_id> [--ttl 1800] [--force] [--release]`
Acquire, renew, or release a soft advisory TTL lease (default 30 min; `60`–`86400`s). Prevents parallel agents from picking the same spec; expired leases auto-release.

#### `spechatch epic <status|next> <epic_id>`
- `spechatch epic status <epic_id>` — Show dynamically computed child progress (`done/total`, `active`, `ready`, `blocked`, `derived_status`).
- `spechatch epic next <epic_id>` — List unblocked, unleased child specs ready for parallel dispatch.

#### `spechatch webhook <add|list|update|test|toggle|deliveries|delete>`
Manage project-scoped actionable webhooks on the Incubator server (dispatched asynchronously on `spec.claimed`, `spec.released`, `spec.approved`, `spec.revised`, `spec.regressed`, `spec.recovered`, `spec.abandoned`, `version.bumped`, and status/version-changing `roadmap.upserted` events):

- `spechatch webhook add <url> [--events CSV] [--format json|slack|discord|teams] [--template PATH] [--secret STR]` — Register a project webhook with optional event filtering, payload preset, custom local JSON/Markdown template (`{{event}}`, `{{project}}`, `{{spec_id}}`, `{{title}}`, `{{kind}}`, `{{status}}`, `{{previous_status}}`, `{{status_transition}}`, `{{version}}`, `{{actor}}`, `{{next_action}}`, `{{timestamp}}`), and HMAC-SHA256 signing.
- `spechatch webhook update <webhook_id> [--events CSV] [--format ...] [--template PATH] [--clear-template]` — Update a webhook's events, format, or custom payload template (or revert to built-in cards with `--clear-template`).
- `spechatch webhook list [--json]` — List project webhooks (secrets are never exposed).
- `spechatch webhook test <webhook_id>` — Send a synchronous signed `webhook.ping` delivery and report HTTP status and latency.
- `spechatch webhook toggle <webhook_id> --enable|--disable` — Enable or disable a webhook.
- `spechatch webhook deliveries <webhook_id> [--limit 20] [--json]` — Inspect persisted delivery logs (rolling 50-row retention per webhook).
- `spechatch webhook delete <webhook_id>` — Delete a webhook.

#### `spechatch context [--spec SPEC_ID] [--json]`
Fetch project orientation context (active specs, active leases, regressed specs, parent epic, upstream `depends_on`, active siblings, and local `constitution.md` hash).

---

## Agent Skills & Rule Packs (3-Tier Catalog)

`spechatch` organizes AI agent skills and rule packs into three opt-in tiers so repositories stay lean while getting immediate day-1 guardrails:

| Tier | Contents | Localization & Behavior |
| :--- | :--- | :--- |
| **Core** | **Skills:** `spechatch-driven-development`, `spechatch-context`, `spechatch-sync-cursor`<br>**Rules:** `spechatch-core`, `gitflow`, `quality-gate`, `release` | Parameterized from `spechatch.project.yml` (`paths`, `statuses`, `commands.entrypoints`). |
| **Tier 1 — Methodology** | **Skills:** `spechatch-code-review`, `spechatch-bug-triage`, `spechatch-safe-refactor`, `spechatch-security-review`, `spechatch-semver`, `spechatch-architecture-design`, `spechatch-accessibility-audit`, `spechatch-bdd-testing`, `spechatch-domain-driven-design`<br>**Rules:** `conventional-commits`, `tdd-first`, `security-hygiene`, `sql-migrations`, `docs-sync`, `always-bump-semver`, `acceptance-criteria`, `clean-code`, `design-patterns`, `accessibility`, `domain-driven-design` | Stack-agnostic, timeless engineering practices; localized across all 5 BCP 47 locales (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`). |
| **Tier 2 — Tooling** | **Rules:** `python-uv`, `typescript-strict`, `go-standard`, `rust-cargo` | Suggested by `spechatch init --scan` (or auto-enabled with `--auto-packs`); localized across all 5 locales. |
| **Tier 3 — Custom / Team** | Repo-local `.spechatch/packs/` or shared company/submodule dirs listed in `agents.pack_dirs` | Drop skills at `skills/<name>/SKILL.md` and rule packs at `rules/<name>.md` or `rules/<name>/*.md`. Supports `{{project}}`/`{{specs_dir}}`/`{{locale}}` substitution, auto-injects `<!-- managed-by: spechatch -->`, can override built-in packs, and mirrors to Antigravity, Cursor, Claude Code, and Codex. |

```bash
# Browse all bundled + custom packs by tier
spechatch agents catalog
spechatch agents catalog --tier tooling
spechatch agents catalog --tier custom

# Enable packs in spechatch.project.yml and sync across all targets
spechatch agents add spechatch-code-review tdd-first python-uv --sync

# Disable a pack
spechatch agents remove tdd-first
```

---

## Configuration (`spechatch.project.yml`)

Generated by `spechatch init [--scan]` and validated via Pydantic (`src/spechatch/config.py`):

```yaml
schema_version: 1
project: my-project
secret_prefix: MY_PROJECT          # Uppercase env-var namespace for global secrets
locale: en-US                      # Template & roadmap locale (en-US, es-ES, it-IT, fr-FR, de-DE)
mode: strict                       # advisory (warn + exit 0) | strict (block + exit 1)

paths:
  specs_dir: specs
  constitution_file: specs/constitution.md
  roadmap_file: specs/ROADMAP.md
  templates_dir: .spechatch/templates
  kinds:
    epic: epics
    spec: "."
    bugfix: bugfixes
    hotfix: hotfixes
    brainstorm: brainstorms
    nice-to-have: nice-to-have
    code-review: reviews

artifacts:
  epic: [EPIC.md]
  spec: [specification.md, plan.md, tasks.md]
  bugfix: [single]
  hotfix: [single]
  brainstorm: [single]
  nice-to-have: [single]
  code-review: [single]

counters:
  global: { prefix: "", start: 1, pad: 6, step: 1 }
  epic:   { counter: epic, prefix: "E-", start: 1, pad: 4, step: 1 }
  spec:   { counter: global }
  bugfix: { counter: bugfix, prefix: "BUG-", start: 1, pad: 4, step: 1 }
  hotfix: { counter: hotfix, prefix: "HF-", start: 1, pad: 4, step: 1 }

tests:
  required: [epic, spec, bugfix, hotfix, code-review]
  optional: [brainstorm, nice-to-have]
  runners:
    pytest:
      command: "uv run pytest {targets} --junitxml={report}"

hooks:
  before-spec: []                  # Optional executable commands receiving JSON payload on stdin
  after-spec: []                   # Each entry supports optional `kinds: [hotfix, ...]` filter

agents:
  targets: [antigravity, cursor]   # Supports: antigravity, cursor, claude, codex, copilot
  skills: [spechatch-driven-development, spechatch-context, spechatch-sync-cursor]
  rule_packs: [spechatch-core]
  pack_dirs: [.spechatch/packs]    # Optional repo-local or shared team skill/rule pack dirs

commands:
  strict: true
  entrypoints:
    - name: make
      file: Makefile
      invoke: "make {target}"
      forbid_raw: [pytest, ruff, mypy]
      targets:
        check: { description: "Run full quality gate", require_confirmation: true }
```

---

## Secrets & Environment Variables (`SPECHATCH_*`)

All runtime configuration is loaded through `SpechatchSettings` (`pydantic-settings` in `src/spechatch/settings.py`) with strict layer precedence:

1. **Process environment variables** (highest — CI/CD, Docker)
2. **Repo-local `.spechatch/.env`** (`spechatch secret ... --local`, auto-gitignored)
3. **Repo root `.env`**
4. **User-global `~/.config/spechatch/.env`** (default `spechatch secret ...`)

Within each layer, project-prefixed `SPECHATCH_<SECRET_PREFIX>_<KEY>` overrides shared `SPECHATCH_<KEY>`. When running inside a project directory, `load_settings()` automatically detects `secret_prefix` from `spechatch.project.yml`.

See [.env.example](https://github.com/ctasca/spechatch/blob/main/.env.example) for a ready-to-copy template.

| Variable | Default | Description |
| :--- | :--- | :--- |
| `SPECHATCH_URL` | `http://127.0.0.1:8787` | Base URL of the incubator server used by CLI commands. |
| `SPECHATCH_CONFIG` | `spechatch.project.yml` | Default path to project configuration file. |
| `SPECHATCH_LOCALE` | *(unset; falls back to project `locale` / `en-US`)* | BCP 47 locale override for generated templates and roadmap (`en-US`, `es-ES`, `it-IT`, `fr-FR`, `de-DE`). |
| `SPECHATCH_AUTHOR` | *(unset)* | Default author handle auto-populated into frontmatter `authors:` by `spechatch new` and `spechatch_new_spec` (overridden by `--author`). |
| `SPECHATCH_INCUBATOR_AUTO_SYNC` | `false` | Set `true` so both CLI commands (`new`, `promote`, `roadmap sync`, `step`, `test run`/`ingest`, `version`; pass `--local` to opt out) and MCP tools automatically sync with the Incubator (gracefully warns and continues locally if unreachable). |
| `SPECHATCH_API_KEY` | *(unset)* | Bearer API key (`shk_...`) for authenticating against the incubator. |
| `SPECHATCH_API_TOKEN` | *(unset)* | Legacy alias for `SPECHATCH_API_KEY`. |
| `SPECHATCH_DATABASE_URL` | `sqlite:///spechatch.db` | PostgreSQL/Neon (`postgres://`/`postgresql://` → `postgresql+psycopg://`), MySQL/MariaDB (`mysql://`/`mariadb://` → `mysql+pymysql://`, requires `[mysql]` extra), or local SQLite fallback. |
| `SPECHATCH_TABLE_PREFIX` | `spechatch_` | Table name prefix applied to all SQLModel tables and Alembic's `alembic_version` table for safe shared-database isolation. |
| `SPECHATCH_AUTH_ENABLED` | `false` | Set `true` to enforce Bearer API keys, project RBAC, and `human`-only checkpoint approvals; `false` runs in solo local open mode. |
| `SPECHATCH_ADMIN_USERNAME` | *(unset)* | Initial superuser username bootstrapped on server startup. |
| `SPECHATCH_ADMIN_PASSWORD` | *(unset)* | Initial superuser password (hashed with Argon2id on startup). |
| `SPECHATCH_BOOTSTRAP_API_KEY` | *(unset)* | Optional deterministic initial `shk_...` API key for the bootstrapped superuser. |

---

## Incubator HTTP & SSE API

All endpoints live under `/api/spechatch/v1`.

### Auth, RBAC & Open Mode

- **Global Roles:** `superuser` (creates projects, users, and memberships), `member`.
- **Project Roles:** `owner` > `maintainer` > `developer` > `viewer`.
- **API Keys (`Authorization: Bearer shk_...`):** Stored only as SHA-256 hash + prefix; carry `actor_type` (`human` | `agent` | `ci`). When `SPECHATCH_AUTH_ENABLED=true`, `POST /specs/{id}/approvals` requires `maintainer+` AND `actor_type == "human"`.
- **Solo Open Mode:** With `SPECHATCH_AUTH_ENABLED=false` (default), all endpoints execute as an anonymous principal with zero auth friction.

### Onboarding a New Developer (Users, Memberships & API Keys)

Using your superuser `shk_*` API key configured via `spechatch secret put API_KEY` (or interactively via Swagger UI at `http://127.0.0.1:8787/docs` → **Authorize**):

```bash
# 1. Create the user (role: member | superuser)
spechatch incubator user create alice --full-name "Alice Dev" --role member

# 2. Assign the user to a project (role: owner | maintainer | developer | viewer)
spechatch incubator member add spechatch alice --role developer

# 3. Issue a personal API key for the user (actor_type: human | agent | ci)
spechatch incubator key create alice --name alice-laptop --actor-type human
```

The developer then stores the returned `shk_*` key on their machine with `spechatch secret put API_KEY`.

### Endpoints Reference

| Group | Method & Path | Min Role | Purpose |
| :--- | :--- | :--- | :--- |
| **Health** | `GET /health` | Public | Live `SELECT 1` DB healthcheck (`200 ok` / `503 degraded`), `db_latency_ms`, `auth_enabled`, and `version`. |
| **Auth & Users** | `GET /auth/me` | Authenticated | Inspect active principal, scopes, and memberships. |
| | `POST /users`, `GET /users`, `PATCH /users/{id}` | `superuser` | Create, list, update, or deactivate users (Argon2id hashing; blocks demoting/deactivating last active superuser). |
| | `POST /users/{id}/api-keys`, `GET /users/{id}/api-keys`, `DELETE /api-keys/{id}` | `superuser` / self | Issue (one-time plaintext), list, and revoke `shk_*` API keys. |
| | `GET /audit` | `superuser` | Query immutable `auth_audit_events` log. |
| **Projects** | `POST /projects`, `GET /projects`, `GET /projects/{slug}`, `PATCH /projects/{slug}` | `superuser` / `viewer+` / `owner` | Create, list, inspect, update, or archive/reactivate projects. |
| | `POST /projects/{slug}/members`, `GET /projects/{slug}/members`, `DELETE /projects/{slug}/members/{user_id}` | `maintainer+` | Manage project memberships & roles. |
| | `GET /projects/{slug}/settings`, `PATCH /projects/{slug}/settings` | `viewer+` / `owner` | Read or update DB-authoritative project governance settings (enforcement mode, human approvals, lease TTL caps, constitution hash). |
| | `GET /projects/{slug}/version`, `POST /projects/{slug}/version/bump` | `viewer+` / `developer+` | Read or atomically bump monotonic SemVer/CalVer project version (`FOR UPDATE`, `Idempotency-Key`, dispatches `version.bumped` webhooks). |
| **Ledger** | `POST /projects/{slug}/ids` | `developer+` | Atomic monotonic ID allocation (requires `Idempotency-Key` header). |
| | `POST /projects/{slug}/roadmap`, `GET /projects/{slug}/roadmap` | `developer+` / `viewer+` | Upsert (with DAG cycle detection) or list live roadmap rows. |
| | `POST /projects/{slug}/specs/{id}/tests` | `developer+` | Record a spec test run bound to `content_hash`. |
| | `POST /projects/{slug}/specs/{id}/abandon` | `developer+` | Mark a spec `abandoned` without ever reusing its ID. |
| | `POST /projects/{slug}/bootstrap` | `maintainer+` | Idempotently seed counters & ledger rows from an existing repo. |
| **Coordination** | `POST /projects/{slug}/specs/{id}/approvals`, `GET .../approvals` | `maintainer+` (`human`) / `viewer+` | Record/list human checkpoint approvals bound to `content_hash` & `constitution_hash`. |
| | `POST /projects/{slug}/specs/{id}/revise`, `GET .../revisions` | `developer+` / `viewer+` | Increment `rev`, record Change Delta, reopen `done` spec. |
| | `POST /projects/{slug}/specs/{id}/claim`, `DELETE .../claim` | `developer+` | Acquire/renew (`409` on active foreign lease) or release soft TTL lease. |
| | `GET /projects/{slug}/epics/{id}`, `GET .../epics/{id}/next` | `viewer+` | Dynamic epic progress roll-up & unblocked, unleased child queue. |
| | `GET /projects/{slug}/context?spec_id=...` | `viewer+` | Agent orientation context (active specs, leases, regressed specs, epic/upstream deps). |
| | `GET /projects/{slug}/events` | `viewer+` | Typed Server-Sent Events (`text/event-stream`). |
| **CI & Webhooks** | `POST /projects/{slug}/tests/ingest` | `developer+` | Ingest JUnit attribution results, update live `health`, emit `spec.regressed`. |
| | `POST /projects/{slug}/webhooks`, `GET .../webhooks`, `PATCH .../webhooks/{id}`, `POST .../webhooks/{id}/test`, `GET .../webhooks/{id}/deliveries`, `DELETE .../webhooks/{id}` | `maintainer+` / `viewer+` | Register (`json`/`slack`/`discord`/`teams`), list (masked), toggle, ping-test, inspect delivery logs, and delete filtered HMAC-SHA256 webhooks. |

---

## Docker Deployment

The included stateless, non-root [Dockerfile](https://github.com/ctasca/spechatch/blob/main/Dockerfile) connects directly to Neon PostgreSQL, any external PostgreSQL 15+, or MySQL 8+/MariaDB 10.6+ (with `[mysql]` extra) via `SPECHATCH_DATABASE_URL`. For external projects, you can scaffold a PyPI-based `Dockerfile` + `.dockerignore` in one command with `spechatch incubator init`:

```bash
# Build locally (from this repo or after `spechatch incubator init`)
docker build --load -t spechatch-incubator .

# Run with inline env vars (or `--env-file ~/.config/spechatch/.env`)
docker run --rm -p 8787:8787 \
  -e SPECHATCH_DATABASE_URL="postgresql://user:pass@ep-example.neon.tech/neondb?sslmode=require" \
  -e SPECHATCH_AUTH_ENABLED="true" \
  -e SPECHATCH_ADMIN_USERNAME="admin" \
  -e SPECHATCH_ADMIN_PASSWORD="change-me-strong-password" \
  spechatch-incubator
```

---

## Contributing & Roadmap

- For local development setup, quality gates (`Makefile` / `uv`), and contribution guidelines, see [CONTRIBUTING.md](https://github.com/ctasca/spechatch/blob/main/CONTRIBUTING.md).
- For the live, auto-generated list of all completed and in-progress specs, see [specs/ROADMAP.md](https://github.com/ctasca/spechatch/blob/main/specs/ROADMAP.md).
