# {ai} engineering — full documentation corpus

> Derived cache: concatenated user-facing and canonical docs for AI agent ingestion.
> Regenerate from: README, docs/guides/getting-started, docs/index, docs/architecture/index, docs/architecture/brand-tokens, docs/persistence-doctrine, CONSTITUTION, AGENTS.



================================================================
# FILE: README.md
================================================================

<div align="center">
  <a href="https://github.com/arcasilesgroup/ai-engineering">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/banner-dark.svg">
      <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/banner-light.svg">
      <img src="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/banner-light.svg" alt="{ai} engineering" width="720">
    </picture>
  </a>

  <p><strong>Turn AI-assisted delivery into a governed local workflow — in any repo, any IDE.</strong></p>

  <p>
    <a href="https://pypi.org/project/ai-engineering/"><img src="https://img.shields.io/pypi/v/ai-engineering.svg?style=flat-square&color=00D4AA&labelColor=0B1120" alt="PyPI version"></a>
    <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/Python-3.11%2B-00D4AA.svg?style=flat-square&labelColor=0B1120" alt="Python 3.11+"></a>
    <a href="https://github.com/arcasilesgroup/ai-engineering/actions"><img src="https://img.shields.io/github/actions/workflow/status/arcasilesgroup/ai-engineering/ci-check.yml?branch=main&style=flat-square&labelColor=0B1120" alt="CI"></a>
    <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-00D4AA.svg?style=flat-square&labelColor=0B1120" alt="License: MIT"></a>
  </p>

  <p><code>54 skills · 9 agents · 6 surfaces · 1 governed flow</code></p>

  <img src="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/demo.gif" alt="Terminal demo: pip install ai-engineering, then ai-eng install . and ai-eng doctor both report [PASS], then open your IDE and run /ai-start" width="760">
</div>

`{ai} engineering` installs a deterministic governance layer into any repository — specs, decisions, skills, agents, hooks, and an audit trail, all as versioned local files. No hosted control plane. No provider lock-in. Every IDE follows the same rules.

## Quickstart

Get a governed repo in under a minute:

```bash
pip install ai-engineering   # or: uv tool install ai-engineering
ai-eng install .             # adds governance to your repo
ai-eng doctor                # [PASS] hooks, mirrors, manifest, required tools
```

Then open your editor and type `/ai-start`. Prefer to ease in? Start in observe mode and enforce only what proves useful.

**What you get:** 54 skills and 9 agents you invoke with `/ai-<name>` · a spec-driven workflow · automatic checks on every change · versioned local files you own. Update any time with `ai-eng update`.

## The governed workflow

You drive the intent and approve each step; the gates catch the rest — no secrets, broken docs, or untested changes reach a merge.

<div align="center">
  <img src="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/diagrams/workflow.png" alt="The governed workflow: /ai-brainstorm agrees the spec, /ai-plan breaks it down, /ai-build or /ai-autopilot implements it, /ai-pr ships a reviewed and merged pull request. You approve each step; automatic checks (clean diff, tests, docs, review) must pass before merge." width="820">
</div>

The canonical chain is **`/ai-brainstorm → /ai-plan → /ai-build → /ai-pr`**. Use it whenever work changes product behavior, framework behavior, security posture, public docs, or release state. `/ai-commit` stays available for WIP checkpoints; it is not part of the chain.

## Your toolkit

Fifty-four skills and nine agents cover the whole delivery loop — and the same commands work in every supported editor.

<div align="center">
  <img src="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/diagrams/toolkit.png" alt="54 skills and 9 agents grouped by what you do: plan and build, ship safely, design and docs, research and learn. The same commands run in Claude Code, GitHub Copilot, Codex, Antigravity, OpenCode, and Cursor." width="820">
</div>

## Supported surfaces

One canonical payload is mirrored, byte-for-byte, into every enabled surface.

| Surface | Entry point |
|---------|-------------|
| Claude Code | [CLAUDE.md](CLAUDE.md) |
| GitHub Copilot | [.github/copilot-instructions.md](.github/copilot-instructions.md) |
| OpenAI Codex | [AGENTS.md](AGENTS.md) |
| Antigravity | [AGENTS.md](AGENTS.md) + `.agents/` |
| OpenCode | `.opencode/` |
| Cursor | `.cursor/` |

The ruleset lives in [AGENTS.md](AGENTS.md). Project identity and hard prohibitions live in [CONSTITUTION.md](CONSTITUTION.md). Release history lives in [CHANGELOG.md](CHANGELOG.md).

## Why governance matters

- **Spec-driven** — every change is tied to an approved scope, so LLM output stays on-task.
- **Deterministic gates** — secrets, broken mirrors, missing docs, and policy drift are caught before they land.
- **Local audit trail** — a hash-chained NDJSON log records what happened, with no telemetry by default.
- **Reviewable everywhere** — skills and agents are file-backed and synchronized across every IDE.

## Documentation

- [docs/](docs/) — architecture, getting started, and the diagram set
- [CONSTITUTION.md](CONSTITUTION.md) — mission, stakeholders, prohibitions
- [CHANGELOG.md](CHANGELOG.md) — release history and breakage notes

## Standing on the shoulders of

`{ai} engineering` builds on ideas and patterns from these projects:

| Project | What we learned |
|---------|----------------|
| [Superpowers](https://github.com/NicolasMontworker/superpowers) | Brainstorm hard-gate, TDD-for-skills patterns |
| [review-code](https://github.com/peterknights1/review-code) | Handler-as-workflow, parallel specialist agents |
| [dotfiles/ai](https://github.com/ericbuess/dotfiles) | Agent matrix, SDLC coverage |
| [autoresearch](https://github.com/vgel/autoresearch) | Radical simplicity as a design principle |
| [SpecKit](https://github.com/speckit/speckit) | Spec-driven workflow inspiration |
| [Anthropic Skills](https://github.com/anthropics/claude-code-skills) | Frontend-design, skill-creator — absorbed and extended |

## Contributing

Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, testing, and the pull request process. This project follows the Contributor Covenant [Code of Conduct](CODE_OF_CONDUCT.md).

## License

MIT. See [LICENSE](LICENSE).


================================================================
# FILE: docs/guides/getting-started.md
================================================================

# Getting started

Install `{ai} engineering` and get a governed repository in under a minute.

<div align="center">
  <img src="https://raw.githubusercontent.com/arcasilesgroup/ai-engineering/main/.github/assets/diagrams/install.png" alt="Install in seconds: pip install ai-engineering, ai-eng install . adds governance to your repo, ai-eng doctor reports [PASS], then open your IDE and type /ai-start. What you get: 54 skills and 9 agents, a governed workflow, automatic checks, and versioned local files." width="820">
</div>

## 1 — Install the CLI

```bash
pip install ai-engineering
# or, with uv:
uv tool install ai-engineering
```

Verify it:

```bash
ai-eng version
```

## 2 — Add governance to a repository

```bash
cd your-project
ai-eng install .
ai-eng doctor
```

`ai-eng doctor` reports `[PASS]` once hooks, mirrors, the manifest, and required tools are in place. Warnings are advisory and non-blocking.

## 3 — Start a session

Open your editor and type:

```text
/ai-start
```

`/ai-start` loads project context and shows you recent activity and the commands available.

## 4 — Ship something the governed way

Drive the intent; approve each step. The gates handle the rest.

```text
/ai-brainstorm → /ai-plan → /ai-build → /ai-pr
```

- `/ai-brainstorm` interrogates the idea and produces an approved spec.
- `/ai-plan` turns the spec into a patch-ready plan.
- `/ai-build` (or `/ai-autopilot` for larger work) implements it under TDD and quality gates.
- `/ai-pr` verifies, reviews, and opens the pull request.

`/ai-commit` stays available for WIP checkpoints; it is not part of the chain.

## Keeping current

```bash
ai-eng update     # in each governed repo, refresh the installed framework files
ai-eng doctor
```

Next: [the architecture](../architecture/index.md).


================================================================
# FILE: docs/index.md
================================================================

# {ai} engineering — documentation

`{ai} engineering` turns AI-assisted delivery into a governed local workflow — in any repo, any IDE. Start here.

## Get going

- [Getting started](guides/getting-started.md) — install, your first session, the governed workflow.
- [The architecture](architecture/index.md) — how the pieces fit, for contributors.

## Reference

- [Brand tokens](architecture/brand-tokens.md) — palette, type, status grammar, asset rules.
- [Persistence doctrine](persistence-doctrine.md) — the files-only, three-tier model.
- [CI branch protection](ci-branch-protection.md) — required checks and merge policy.
- [Supply-chain control matrix](supply-chain-control-matrix.md) — provenance and scanning controls.
- [Cache-cleanup runbook](cache-cleanup-runbook.md) — GitHub Actions cache hygiene.

## Project identity

- [CONSTITUTION.md](../CONSTITUTION.md) — mission, stakeholders, prohibitions.
- [CHANGELOG.md](../CHANGELOG.md) — release history and breakage notes.
- [CONTRIBUTING.md](../CONTRIBUTING.md) — development setup and the pull request process.

The canonical chain is `/ai-brainstorm → /ai-plan → /ai-build → /ai-pr`. Use it whenever work changes product behavior, framework behavior, security posture, public docs, or release state.


================================================================
# FILE: docs/architecture/index.md
================================================================

# Architecture

How `{ai} engineering` is built, for contributors. (Using the framework? Start with [getting started](../guides/getting-started.md).)

## The big picture

`{ai} engineering` is a deterministic governance layer materialized as versioned local files: specs, decisions, skills, agents, hooks, and a hash-chained audit trail. There is no hosted control plane — every IDE reads the same canonical payload.

The authoritative architecture document is [solution-intent.md](../../.ai-engineering/solution-intent.md) (§3.1 carries the layered module map). It embeds the system-context, module-map, IDE-mirror, publication, observability, and security/quality diagrams as Mermaid, so they version with the code.

## Core ideas

- **The deterministic plane gates the probabilistic plane.** Every AI write passes hooks (secrets, policy, mirror-parity, docs-freshness, injection) before it lands; passing writes are appended to `framework-events.ndjson`.
- **Files-only persistence, one source of truth per datum.** See the [persistence doctrine](../persistence-doctrine.md) — Tier 1 NDJSON audit, Tier 2 JSON/YAML records and config, Tier 3 Markdown narrative, with explicitly labelled, rebuildable derived caches.
- **One canonical payload, six surfaces.** `CANONICAL.md` plus `.claude/` skills and agents are mirrored byte-for-byte into Claude Code, GitHub Copilot, Codex, Antigravity, OpenCode, and Cursor; parity is gate-enforced.
- **The canonical chain.** `/ai-brainstorm → /ai-plan → /ai-build → /ai-pr` is the spec-driven delivery workflow.

## The visual system

The README diagrams are diagrams-as-code: HTML/CSS source in [diagrams/build_diagrams.py](diagrams/build_diagrams.py), rendered to PNG and committed under `.github/assets/diagrams/`. The palette, type, and status grammar live in [brand-tokens.md](brand-tokens.md). The terminal demo is a checked-in VHS tape (`.github/assets/demo.tape`). Rendering runs in CI, never on the pre-commit hot path.

## Reference

- [Brand tokens](brand-tokens.md)
- [Persistence doctrine](../persistence-doctrine.md)
- [Supply-chain control matrix](../supply-chain-control-matrix.md)
- [CI branch protection](../ci-branch-protection.md)


================================================================
# FILE: docs/architecture/brand-tokens.md
================================================================

# Brand Tokens

Single source for every visual asset (SVG infographics, fal art prompts, Mermaid
renders, diagrams). Values lifted verbatim from `.github/assets/banner-dark.svg`
and `.ai-engineering/reference/brand-voice.md`. Authority for prose: `brand-voice.md`.

## Palette

| Token | Hex | Use |
|-------|-----|-----|
| `bg-deep` | `#0B1120` | Background outer (radial stop 100%) |
| `bg-mid` | `#162844` | Background inner (radial stop 0%) |
| `accent` | `#00D4AA` | Teal accent — brackets, separators, glow, edges |
| `text` | `#F8FAFB` | Primary text / nodes |
| `grid` | `#FFFFFF` @ 4% | Faint grid lines |
| `bracket` | `#00D4AA` @ 30% | Corner brackets |
| `glow` | `#00D4AA` @ 8% | Radial glow behind focal element |

## Type

- Family: `'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', 'Consolas', monospace`.
- Wordmark: `{ai} engineering` — `{` and `}` in `accent`, `ai` + `engineering` in `text`, weight 700.

## Status grammar (no emoji)

`[PASS]` · `[WARN]` · `[FAIL]` · `[PENDING]` — textual, never color-only, never decorative symbols.

## Stat line

Mid-dot inventory: `54 skills · 9 agents · 6 surfaces · 1 governed flow`.

## Asset rules

- fal raster art = abstract branded illustration only; NO load-bearing text (labels live in SVG/Mermaid).
- SVG infographics ship light + dark twins, embedded via `<picture>` with descriptive alt text.
- Mermaid blocks set NO `%%{init}%%` theme (GitHub auto-adapts); pre-rendered to committed SVG for off-GitHub surfaces.
- All README/PyPI image URLs are absolute `raw.githubusercontent.com/.../main/...`.


================================================================
# FILE: docs/persistence-doctrine.md
================================================================

# Persistence Doctrine

> Authoritative reference for **where data lives** in ai-engineering.
> Cited from [CONSTITUTION.md](../CONSTITUTION.md) §13 and
> [CLAUDE.md](../CLAUDE.md) §0. Files-only since spec-148 (the embedded
> SQLite `state.db` was removed); amendments require an ADR.

## The SSOT-PD rule

**Single Source of Truth Per Datum.** Every piece of framework state
lives in exactly one canonical writable store. Every other copy is a
*derived cache* — explicitly named, with a documented rebuild command,
and rebuildable on demand. Two stores accepting writes for the same
datum is the violation we close; one store with multiple writers is
acceptable.

- One canonical store per datum.
- Caches are explicitly labelled (named, with a rebuild command).
- Caches are rebuildable on demand — never the primary witness.
- Dual-writes (silent mirrors that drift) are forbidden.

## The three tiers

The framework stores state across three tiers chosen by the *shape* of
the data, not by convenience. A datum belongs to exactly one tier, and
within that tier to exactly one canonical file. There is **no database**:
spec-148 removed the embedded SQLite `state.db` so the obvious reading of
every store is a plain file on disk.

### Tier 1 — NDJSON audit log

- **Canonical for:** framework events (every hook fire, every skill
  invocation, every gate decision). The audit chain is the
  ground-truth witness used by `/ai-explain`, `/ai-verify`, and
  external auditors.
- **File pattern:** `.ai-engineering/state/framework-events.ndjson`
  (one JSON object per line, hash-chained via `prev_event_hash`).
- **Write SLA:** O(1) append — no parsing, no schema validation on
  write. Hot path budget under 50ms p95.
- **Read pattern:** sequential scan (cold path). `ai-eng audit tokens`
  (skill/agent/session rollups), `ai-eng audit replay` (span tree), and
  `ai-eng audit verify` (chain integrity) all read the NDJSON directly —
  there is no SQLite projection in between.
- **Write trigger:** every hook fire (PreToolUse, PostToolUse,
  SessionStart, SessionEnd, ...) and every policy decision via
  `src/ai_engineering/governance/decision_log.py:emit_policy_decision`.
- **Hot-path status:** yes — must stay append-only and lock-free.

### Tier 2 — JSON / YAML records + configuration

- **Canonical for:** mutable structured records and machine-readable
  configuration whose schema is declared in Python (Pydantic) and
  consumed by the deterministic plane. Small datasets read whole, with
  `mtime` caching — the scale at which a file beats a database.
- **Canonical record files (per-install state, written via the durable
  repository; gitignored):**
  - `.ai-engineering/state/decision-store.json` — governance decisions
    **and** risk acceptances (risk acceptances are decision records). Carries
    the optional per-entry SHA-256 hash chain verified by `ai-eng audit verify`.
  - `.ai-engineering/state/ownership-map.json` — the update-decision
    ownership map (`ai-eng update` reads it before evaluating create/update).
  - `.ai-engineering/state/install-state.json` — the writable install state
    (`InstallState` model dump: vcs/tooling/platforms/readiness + hook hashes).
  - `.ai-engineering/state/framework-capabilities.json` — the skill/agent
    capability catalog (a derived cache; see below).
  - `.ai-engineering/state/specs/<spec_id>.json` — the **canonical
    source-of-truth for spec lifecycle state** (one per-spec sidecar written
    atomically by `scripts/spec_lifecycle.py` under `artifact_lock`). The
    `LifecycleState` FSM (DRAFT→…→ARCHIVED), branch, PR, and timestamps live
    here. `specs/_history.md` (Tier 3) is its **derived projection** —
    rebuildable via `spec_lifecycle.py consolidate_shipped`.
- **Canonical seed corpus (committed, evaluated by CI):**
  - `.ai-engineering/evals/baseline.json` — the skill-evaluation baseline
    plus its `*.jsonl` golden cases. Canonical (not a cache): the
    `skill-evals.yml` CI workflow scores against `baseline.json`, so it is
    durable source data, never wiped by cleanup.
- **Configuration files:**
  - `.ai-engineering/manifest.yml` — framework configuration
    (stacks, surfaces, telemetry consent).
  - `.ai-engineering/state/hooks-manifest.json` — pinned sha256
    digests of every hook script for `run_hook_safe` integrity
    verification.
  - `.ai-engineering/state/gate-findings.json` — primary
    gate/risk/verify artifact; emitted by gate/review orchestration and
    read by verify/risk surfaces.
  - `.ai-engineering/suppression-allowlist.yml` — Article VII
    suppression exceptions (governed by `tools/no_suppression/`).
- **Write SLA:** sub-second; tooling-validated. Never written from the
  hot-path hooks.
- **Read pattern:** Pydantic parse on read; small enough to read whole.
- **Write trigger:** spec approval (`/ai-brainstorm`, `/ai-plan`), CLI
  commands (`ai-eng decision`, `ai-eng risk`, `ai-eng ownership import`),
  installer phases, and operator config edits.
- **Hot-path status:** read-only on the hot path; writes are cold path.

### Tier 3 — Markdown human-authored truth

- **Canonical for:** human-authored doctrine and narrative state.
  Reviewable in PRs, diffable across history, indexable by humans.
- **File patterns:**
  - `.ai-engineering/specs/spec.md`, `.ai-engineering/specs/plan.md`
    (active spec workflow output).
  - `.ai-engineering/specs/archive/spec-NNN-<slug>/` — the **canonical
    immutable post-ship snapshot directory** (holds the `spec.md` / `plan.md`
    captured by `mark_shipped` at the SHIPPED transition). The legacy flat
    `specs/archive/spec-NNN-*.md` form is the same canonical archive. Never
    rewritten; never a cleanup target.
  - `.ai-engineering/specs/drafts/*-brief.md` — researched problem briefs
    that feed `/ai-brainstorm`. **Tier 3, transient-with-TTL:** the `sweep`
    verb MOVES briefs older than `lifecycle.draft_ttl_days` (fail-open 14d)
    into `specs/archive/drafts/` when `reap_orphans` is set (never deletes).
  - `.ai-engineering/state/archive/delivery-logs/spec-*.md` — **canonical
    durable delivery-log prose** relocated out of `specs/_history.md`
    (the spec-122-a precedent). Immutable historical record; the file-existence
    validator excludes `state/archive/` from reference-checking (D-153-09)
    because it legitimately cites deferred/retired artifacts.
  - `.ai-engineering/LESSONS.md` (self-improvement loop per
    CLAUDE.md operating mindset #7).
  - [`CONSTITUTION.md`](../CONSTITUTION.md) (project identity).
  - [`CLAUDE.md`](../CLAUDE.md) (canonical cross-IDE rulebook;
    mirrors regenerated from
    `src/ai_engineering/templates/project/CANONICAL.md`).
  - [`CHANGELOG.md`](../CHANGELOG.md) (Keep-a-Changelog format;
    every removal / breaking change documented).
- **Write SLA:** human-typed; no machine perf budget. Mirror sync
  is the only mechanical writer.
- **Read pattern:** operator + LLM session bootstrap; CI parsers
  (decision backfill, mirror-parity gates).
- **Write trigger:** operator commits; `scripts/sync_mirrors/core.py`
  for the byte-equivalent CLAUDE.md / AGENTS.md /
  copilot-instructions.md mirrors.
- **Hot-path status:** no. Markdown is operator and reviewer surface.

## Derived caches

A *derived cache* is a writable store whose content is fully
reconstructible from a Tier 1–3 source-of-truth. Caches MAY be queried
for speed; they MUST NOT be the primary witness for any audit, gate, or
compliance claim.

| Cache name | Source-of-truth | Rebuild command | Freshness contract |
|------------|-----------------|-----------------|--------------------|
| `framework-capabilities.json` | The manifest + the on-disk skill/agent surface | `write_framework_capabilities()` (run by `ai-eng install`/`update`) | Rebuilt on demand from the manifest + disk; never authoritative on its own. |
| `decision-store.json` (ADR `D-NNN-NN` rows) | `.ai-engineering/specs/*.md` + `CHANGELOG.md` (Tier 3) | `ai-eng decision backfill` | Backfilled on operator demand and on `/ai-brainstorm` approval. Risk/flow decision rows written by `ai-eng risk`/`decision record` are lifecycle data, not rebuildable from specs. |

`ownership-map.json` is the canonical update-decision store, not a
derived cache: `ai-eng update` reads it before evaluating create/update
actions. `gate-findings.json` is the primary gate/risk/verify artifact.

## Bounded operational caches

`.ai-engineering/cache/gate/` is a bounded performance cache for
`ai-eng gate run`, not a canonical state-plane datum and not a deletion
target for `.ai-engineering/state/` cleanup. Entries are JSON files
keyed by gate-check inputs (tool version, relevant config hashes,
arguments, and staged blob SHAs); cache hits only skip recomputation,
they do not become audit or compliance witnesses.

- **Bounds:** entries expire after the existing 24-hour freshness
  window and writes prune the directory to 256 JSON entries.
- **Inspect:** `ai-eng gate cache --status`.
- **Clear:** `ai-eng gate cache --clear --yes` for a full wipe, or
  `ai-eng gate run --force` to clear matching entries before a fresh run.
- **State boundary:** old `.ai-engineering/state/gate-cache/` remains
  forbidden; the live cache belongs under `.ai-engineering/cache/gate/`.

## Transient runtime state

Some paths under `.ai-engineering/` are **not** a tier at all: they are
per-machine runtime state, gitignored, recreated on demand, and safe to
wipe. They carry no source-of-truth datum.

- `.ai-engineering/runtime/` — session-scoped autopilot/tool/checkpoint
  state (rotated by `runtime_rotate.py`, gitignored).
- `.ai-engineering/cache/` — bounded performance caches (gate cache above).
- `.ai-engineering/state/state.db` (+ `-wal` / `-shm`) — the retired
  pre-spec-148 SQLite projection. Files-only since spec-148: no live writer,
  reaped by `cleanup runtime` if a stale copy lingers.

## Cleanup Contract

What each `.ai-engineering/` location is, and which verb reclaims it. The
contract is binary: **KEEP-canonical** paths are never a cleanup target;
**TRANSIENT-wipe** paths are recreated on demand.

| Path | Class | Handled by |
|------|-------|------------|
| `state/framework-events.ndjson` | KEEP-canonical (Tier 1) | rotated in place by `cleanup runtime` (SessionEnd) — never deleted |
| `state/decision-store.json`, `state/ownership-map.json`, `state/install-state.json` | KEEP-canonical (Tier 2) | never wiped |
| `state/specs/*.json` | KEEP-canonical (Tier 2 lifecycle SoT) | never wiped (`sweep` only transitions state) |
| `evals/baseline.json` (+ `*.jsonl`) | KEEP-canonical seed corpus | never wiped |
| `specs/spec.md`, `specs/plan.md` | KEEP-canonical (Tier 3) | reset to placeholder on ship; never deleted |
| `specs/archive/spec-NNN-<slug>/` | KEEP-canonical immutable snapshot | never wiped |
| `state/archive/delivery-logs/` | KEEP-canonical durable logs | never wiped |
| `specs/drafts/*-brief.md` | TRANSIENT-with-TTL | `cleanup specs` → `sweep` MOVES briefs past `draft_ttl_days` into `specs/archive/drafts/` |
| `runtime/` (tool-outputs, autopilot, tool-history) | TRANSIENT-wipe | `cleanup runtime` (`runtime_rotate.py`) rotates per retention |
| `cache/gate/` | TRANSIENT-wipe | `ai-eng gate cache --clear --yes` |
| `state/locks/*.lock` | KEEP-canonical (spec-125 D-125-09 required dir; tracked 1-byte `fcntl` seed files) | never wiped; `artifact_lock` uses them as lock targets in place. Committing the seeds guarantees the required dir exists on a fresh checkout (`test_required_dirs_present`) |
| `state/state.db` (+ WAL/SHM) | TRANSIENT-wipe (stale) | `cleanup runtime` reaps a stale leftover |
| `state/gate-findings.json` | TRANSIENT (DOCUMENTED) | regenerated by gate/review flows |

## Strict rules

1. **No silent dual-writes.** A datum lives in exactly one canonical
   tier. If a second store needs the same datum for query speed, it
   is a derived cache — named in the table above, with a rebuild
   command, and clearly marked in code as `# derived cache; rebuild
   via <command>`.
2. **The audit chain stays on NDJSON.** `framework-events.ndjson` is
   the canonical witness; `ai-eng audit tokens`/`replay`/`verify` read
   it directly. Gates and external audits verify against the NDJSON
   (`ai-eng audit verify`).
3. **No SQLite anywhere (spec-148 files-only).** The embedded `state.db`
   was removed; no `src/` module nor hook may import `sqlite3` (except the
   one-shot legacy export migration in `ai-eng update`). Enforced
   mechanically by `tests/architecture/test_no_sqlite.py`.
4. **Schema authority lives in Pydantic.** The state models
   (`tools/skill_domain/state_models.py`) define each file's shape; the
   JSON file homes are written via the durable repository
   (`src/ai_engineering/state/repository.py`) and validated on read.
5. **Hard deletes — no shims.** Per CONSTITUTION.md §13.3, renamed
   / deleted / migrated stores are removed outright. No
   backwards-compatibility mirror, no dual-write fallback, no
   deprecation alias. The CHANGELOG documents every removal.

## Migration (pre-spec-148 installs)

`ai-eng update` runs a one-shot `export → verify → delete` migration: if
a legacy `state.db` is present, it ingests `install_state`, `decisions`,
and `ownership_map` into their file homes, verifies the export, then
deletes `state.db` (+ WAL/SHM). No backup — the fail-loud verify gate is
the safety net (`state.db` is never deleted unless every export verifies).
Idempotent; a no-op once `state.db` is gone.

## Operator surface — what changes for you

None of these run on the hot path; all are idempotent and safe to re-run.

- `ai-eng decision list` — read active decisions from
  `decision-store.json`. Empty on a fresh checkout until
  `ai-eng decision backfill` populates it from spec markdown.
- `ai-eng decision backfill` — parse `.ai-engineering/specs/*.md`
  and `CHANGELOG.md`, extract `D-NNN-NN` records, write
  `decision-store.json`. Idempotent.
- `ai-eng ownership import` — parse `.github/CODEOWNERS`, write
  `ownership-map.json`. Re-run after every CODEOWNERS edit.
- `ai-eng audit verify | tokens | replay` — verify the hash chain and
  report token usage / span trees over `framework-events.ndjson`.

## Glossary

- **SSOT-PD** — *Single Source of Truth Per Datum.* Every datum lives in
  exactly one canonical writable store; all other copies are labelled
  derived caches.
- **Derived cache** — a writable store whose content is fully
  reconstructible from a Tier 1–3 source-of-truth via a named rebuild
  command. Query convenience, never primary witness.
- **Hot path** — code reached by every operator action (every save,
  every commit, every prompt). Budgeted: pre-commit under 1 second,
  pre-push under 5 seconds, hooks under 50ms p95.
- **Cold path** — code reached by deliberate operator action (installer
  phases, `ai-eng <cmd>` invocations, SessionEnd, CI jobs). Correctness
  over latency.
- **Tier** — one of the three canonical persistence layers (NDJSON
  audit, JSON/YAML records+config, Markdown). Each tier has its own
  write SLA and hot-path status.
- **Files-only** — the framework's design choice (spec-148) to store
  every datum as a plain file (append-only chain for events, JSON/YAML
  for records and config, Markdown for human-authored doctrine) rather
  than an embedded database — the right shape for a kilobyte-scale,
  single-writer, cross-OS developer tool.


================================================================
# FILE: CONSTITUTION.md
================================================================

# CONSTITUTION

> Project-identity contract for this repository. AI-behaviour rules
> (engineering principles, plan-mode default, subagent strategy,
> commit conventions, etc.) live in
> [CANONICAL.md](src/ai_engineering/templates/project/CANONICAL.md)
> and its byte-equivalent mirrors (AGENTS.md, CLAUDE.md, GEMINI.md,
> .github/copilot-instructions.md). This file owns "what THIS project
> IS" — Mission, Stakeholders, Vocabulary, Prohibitions, Compliance
> gates, Anti-goals, Boundaries, Escalation, Language, Lifecycle phase.

Generated and maintained by the `/ai-constitution` skill (spec-131
D-131-04). Updates are ADR-required and rotate the prior body to
`.ai-engineering/specs/_history-constitution-<YYYY-MM-DD>.md`.

---

## Mission

ai-engineering is a governance framework for AI-assisted software
delivery in regulated environments. The framework ships a
deterministic preprocessor layer (planning, gating, audit) and a
probabilistic execution layer (LLM-driven skills + agents) with a
hard contract between the two: every probabilistic action passes
through a deterministic gate before it touches the filesystem or
the network. Adoption target is teams that ship under regulatory
constraints (banking, healthcare, public sector) where unattended
AI authoring is the cost-driver and auditability is the bar.

## Stakeholders

- **Operator engineers** consuming the framework through their IDE
  host (Claude Code, Codex, Gemini CLI, GitHub Copilot, OpenCode, Cursor).
- **Security + compliance reviewers** auditing the deterministic
  plane (policy engine, prompt-injection guard, append-only NDJSON
  audit chain).
- **Release engineers** wiring `ai-eng` into CI / CD pipelines.
- **Framework maintainers** — the canonical Spec-Driven Development
  flow (`/ai-brainstorm → /ai-plan → /ai-build → /ai-pr`) is the
  hand-off contract between operator + maintainer.

## Vocabulary

- **Skill** — a `.claude/skills/ai-<name>/SKILL.md` capability invoked
  via `/ai-<name>`. Skills carry frontmatter (`name`, `description`,
  `effort`, `model_tier`, `argument-hint`) plus a layout-conformant
  body (`## Quick start` / `## Workflow` / `## Examples` /
  `## Integration`).
- **Agent** — a `.claude/agents/ai-<name>.md` persona dispatched in a
  fresh context window. Build is the only agent with write
  permissions.
- **Canonical chain** — `/ai-brainstorm → /ai-plan → /ai-build →
  /ai-pr`. `/ai-commit` is an off-chain WIP-only skill.
- **Deterministic plane** — policy engine, audit chain,
  prompt-injection guard, gitleaks, semgrep. Never delegates to the
  LLM for go/no-go decisions.
- **Probabilistic plane** — LLM-driven skill execution. Every write
  passes through the deterministic plane first.

## Prohibitions

1. **No secrets in source.** `gitleaks protect --staged` blocks every
   commit; `gitleaks detect` blocks every push. Risk acceptance
   flows through the ledger (`ai-eng risk accept …`), never via
   inline allowlists.
2. **No suppression markers.** No `# noqa`, `# nosec`,
   `// @ts-ignore`, `// nolint`, `# pragma: no cover`, `// NOSONAR`.
   Refactor or risk-accept. spec-128 sub-d ships the repo-wide gate.
3. **No `--no-verify` ever.** Pre-commit and pre-push hooks are the
   on-disk evidence the deterministic plane fired.
4. **No backwards-compatibility shims** for renamed / deleted /
   migrated files. Hard rename, hard delete, hard migration.
   CHANGELOG documents the breakage.
5. **No PII, no operator names, no machine paths** in any committed
   file (specs, CHANGELOG, docs, telemetry, lessons, runbooks). Use
   placeholders (`$HOME/.local/bin`, `$(which …)`) where
   machine-relative references are needed.
6. **No multi-round retry inside the quality loop.** Fail-loud only;
   blockers STOP and escalate to the operator.
7. **No CONSTITUTION auto-amendment.** The 10 sections above are
   operator-authored. `/ai-constitution amend` rotates the prior
   body, applies the diff, bumps the minor version, and emits an
   audit event — but the operator types the new content.
8. **Single Source of Truth Per Datum.** Every datum has exactly
   one canonical writable store. Derived caches are explicitly
   labelled (named, with a rebuild command) and rebuildable on
   demand. See [docs/persistence-doctrine.md](docs/persistence-doctrine.md)
   for the four-tier model and the rebuild semantics.

## Compliance gates

1. **Pre-commit gate** (sub-1s p95) — `ai-eng gate pre-commit` runs
   `gitleaks protect --staged`, `ruff format --check`, `ruff check`,
   and `ai-eng spec verify` on staged hunks only. Anything heavier
   belongs on pre-push or CI.
2. **Pre-push gate** (under 5s p95) — `ai-eng gate pre-push` runs
   `semgrep --config .semgrep.yml`, `pip-audit`, the unit-test
   suite, and `ty` static type-checking.
3. **CI** — re-runs every gate above plus the slower checks
   (integration tests, SonarCloud, Scorecard, SBOM diff). CI is the
   final authority; local gates are an early-warning layer.
4. **Allowlist hard rule.** `.gitleaks.toml [allowlist] paths` MUST
   list explicit individual files, never wildcards. Regex
   allowlists and stopwords are forbidden for suppressing
   real-secret findings. When remediation cannot land before the
   publish window closes, bypass goes through
   `ai-eng risk accept --finding-id <rule_id>` — time-bounded,
   owner-attributed, spec-referenced.
5. **Supply-chain bar.** The framework's own dependencies and CI
   ship with Sigstore keyless OIDC signature verification where
   available, SLSA v1.0 provenance metadata, a CycloneDX SBOM
   published per release, and an OpenSSF Scorecard run wired into
   CI. `--ignore-scripts` for npm/bun installs disables
   install-time script execution. GitHub Actions are pinned to
   immutable commit SHAs, never mutable tags.

## Anti-goals

- **No skill marketplace, no plugin store, no remote skill fetch.**
  Skills live in-tree; users fork or contribute upstream.
- **No multi-LLM orchestration layer.** Each session runs against
  one IDE-host LLM at a time. BYOK CI is opt-in, documented as
  not-yet-implemented at the current scale.
- **No managed-cloud component.** The framework runs entirely on
  the operator's machine plus their existing CI runner.
- **No telemetry collection by default.** `telemetry.consent:
  strict-opt-in` in `manifest.yml`; the audit chain stays local
  NDJSON unless the operator wires an exporter.
- **No regulated-tier provider lock-in.** Vendor selection for
  Layer 3 (BYOK CI) is a deployment-time decision captured by ADR,
  never by framework default.

## Boundaries

- **Framework-owned** — every file under
  `.ai-engineering/`, `.claude/`, `.codex/`, `.gemini/`,
  `.github/skills/`, `.github/agents/`,
  `.github/copilot-instructions.md`, AGENTS.md, CLAUDE.md,
  GEMINI.md, CANONICAL.md, this CONSTITUTION.md, and
  `scripts/sync_mirrors/`. Operators MUST NOT hand-edit generated
  mirrors; `sync_command_mirrors.py` regenerates from canonical
  sources.
- **Team-owned** — every other file in the repository:
  application source, tests, configuration, CI workflows
  specific to the team's product surface.
- **Generated mirrors carry `DO NOT EDIT` headers** and
  `linguist-generated=true`. The deterministic plane reverts
  manual edits on the next sync.

## Escalation

- **Quality-gate failure** (pre-commit / pre-push / CI) → stop, fix,
  retry. `ai-eng doctor --fix` is the first-line tool.
- **Prompt-injection-guard fire** → exit 2 + framework_error event.
  Investigate the offending content; never bypass the guard.
- **Hook integrity violation** (`AIENG_HOOK_INTEGRITY_MODE=enforce`)
  → regenerate the manifest after intentional edits via
  `python3 .ai-engineering/scripts/regenerate-hooks-manifest.py`.
- **Risk-acceptance request** → `ai-eng risk accept --finding-id
  <id> --justification <text> --spec <id> --follow-up <plan>`. The
  ledger is the single source of truth; CI consumes it.
- **CONSTITUTION change request** → `/ai-constitution amend`,
  diff-confirm, rotate to `_history-constitution-<date>.md`,
  minor-version bump, audit event.

## Language

English (project natural language for code identifiers, commits,
specs, CHANGELOG entries, and docs). Operator-facing prompts in the
interview surface (`/ai-constitution`) accept any language; the
written CONSTITUTION.md stays in English for cross-team review.

## Lifecycle phase

**Stabilising** — the framework has shipped its canonical chain
(spec-127 / spec-128 / spec-129) and is now hardening DX (spec-131).
Breaking changes still land without backwards-compat shims (anti-goal
above), but the deterministic plane contract (audit chain shape,
risk-acceptance ledger, hooks manifest) is frozen modulo ADR.

---

<!--
ADAPTATION NOTE (spec-131 D-131-04)

This CONSTITUTION.md was rescoped on 2026-05-11 from a 13-Article
AI-behaviour document into a 10-section project-identity contract.
The pre-migration body is rotated verbatim to
`.ai-engineering/specs/archive/constitution-rotations/2026-05-11.md` for
traceability per R-131-03. All AI-behaviour content migrated to
`src/ai_engineering/templates/project/CANONICAL.md` §§1-13 and is
mirrored byte-equivalent into AGENTS.md / CLAUDE.md / GEMINI.md /
.github/copilot-instructions.md by
`scripts/sync_mirrors/core.py`.

Governance metadata:
- spec_ref: spec-131 (DX Excellence Refactor)
- decision_ref: D-131-04 (project-identity pivot)
- ratified: 2026-05-11
- last_amended: 2026-05-11
- amendments: [pre-2026-05-11 body preserved in archive/constitution-rotations/2026-05-11.md]
-->


================================================================
# FILE: AGENTS.md
================================================================

# Canonical Cross-IDE Rulebook

> Hard rules live in [CONSTITUTION.md](CONSTITUTION.md). This file is
> the canonical multi-IDE entry point for "how AI works in this repo".
> Every IDE-native mirror (AGENTS.md, CLAUDE.md,
> .github/copilot-instructions.md) carries identical canonical payload;
> IDE-specific extras live in the fenced block at the bottom.

## 0. Bootstrap

Every session: (1) read [CONSTITUTION.md](CONSTITUTION.md) (project
identity); (2) read `.ai-engineering/manifest.yml` (config SoT);
(3) consult [docs/persistence-doctrine.md](docs/persistence-doctrine.md)
for the canonical store of each datum (decisions live in spec markdown;
the `decision-store.json` cache is populated after `ai-eng decision
backfill` or `/ai-brainstorm` approval per spec-138 M3 follow-up);
(4) no implementation without an approved spec — invoke
`/ai-brainstorm` first when a task has no spec; (5) read
[SOUL.md](SOUL.md) (the agent's collaborator values — the judgment
layer above the deterministic plane).

See [docs/persistence-doctrine.md](docs/persistence-doctrine.md) for
the three-tier files-only model (NDJSON audit, JSON/YAML
records+config, Markdown) and the SSOT-PD rebuild semantics.

## Operating Mindset (§1–§9 condensed)

Karpathy / Boris one-liners that frame the §10 principles. Full prose
in [.ai-engineering/reference/principles.md](.ai-engineering/reference/principles.md) under "Operating Mindset".

1. **Think Before Coding** — read failing input + spec gates BEFORE editing.
2. **Simplicity First** — fewest moving parts; prefer deletion over abstraction.
3. **Surgical Changes** — one commit, one change; drive-by refactors get their own justification.
4. **Goal-Driven Execution** (Verification Before Done) — green gate before "done"; staff-engineer bar.
5. **Plan-Mode Default** — enter plan mode for non-trivial tasks; re-plan when things go sideways.
6. **Subagent Strategy** — one task per subagent; offload research into fresh context windows.
7. **Self-Improvement Loop** — every user correction updates `.ai-engineering/LESSONS.md`.
8. **Demand Elegance** — "is there a more elegant way?" on non-trivial changes; clear beats clever.
9. **Autonomous Bug Fixing** — fix bugs you spot; mention them in the commit.

## Soul

The agent's collaborator values — Pragmatic Helpfulness, Honest &
Direct, Collaborative Partner, Learn & Grow — live in
[SOUL.md](SOUL.md). They are the judgment layer above the deterministic
plane (gates, Prohibitions), read each session per §0. SOUL.md owns the
*values framing*; the Operating Mindset (§1-9) and §10 principles own
the engineering prose.

## 10. Engineering Principles (pointer)

The eight first-class principles (§10.1 KISS, §10.2 YAGNI, §10.3 SOLID,
§10.4 DRY, §10.5 TDD, §10.6 SDD, §10.7 Clean Code, §10.8 Hexagonal
Architecture) live in [.ai-engineering/reference/principles.md](.ai-engineering/reference/principles.md). Every
SKILL.md `## Workflow` cites at least one §10.x anchor; anchors are
stable at the new home.

## 11. Canonical Chain

The active spec workflow is:

**(/ai-spec-draft) → /ai-brainstorm → /ai-plan → /ai-build → /ai-pr**

- `/ai-spec-draft` is the OPTIONAL pre-step: it produces a researched
  problem brief at `.ai-engineering/specs/drafts/<topic>-brief.md` to hand
  off to `/ai-brainstorm`. Skip it when the problem is already well-scoped.
- `/ai-brainstorm` produces an approved spec at
  `.ai-engineering/specs/spec.md`.
- `/ai-plan` produces an exhaustive patch-ready plan at
  `.ai-engineering/specs/plan.md` and records the recommended executor
  route (`/ai-build` or `/ai-autopilot`).
- `/ai-build` executes plans routed to build (multi-stack implementation
  gateway, D-127-11). For specs with ≥3 concerns or ≥10 file changes,
  `/ai-autopilot` wraps the chain.
- `/ai-pr` runs the final quality loop (verify + review + commit
  pipeline internally) and opens the PR.

`/ai-commit` is preserved as a standalone off-chain skill for WIP
checkpoints. It does NOT appear in the canonical chain (D-131-07).

## 12. Surface Index

## Skills (54)

Canonical skills and agents live under `.claude/`; mirror surfaces under
`.codex/`, `.agents/`, and `.github/` are byte-equivalent regenerations
written by `scripts/sync_mirrors/core.py`. Invoke a skill via
`/ai-<name>` in the IDE agent surface — never via a synthetic terminal
equivalent.

## Agents (9)

The 9 user-facing agents are defined at
`.claude/agents/ai-<name>.md` — that directory is the source of truth
(there is no `agents.registry` manifest key). `.claude/agents/` also
holds the internal review and verifier families (`review-*`,
`reviewer-*`, `verifier-*`) dispatched by `/ai-review` and `/ai-verify`;
those are not part of the user-facing 9. Each agent runs in
its own context window — offload research and parallel analysis to them.

## Source of Truth

| Surface | Where |
|---------|-------|
| Skills (54) | `.claude/skills/ai-<name>/SKILL.md` |
| Agents (9) | `.claude/agents/ai-<name>.md` |
| Placement contract | `.ai-engineering/reference/knowledge-placement.md` |
| Hook scripts | `.ai-engineering/scripts/hooks/` |
| CLI | `ai-eng <command>` |
| Audit chain | `.ai-engineering/state/framework-events.ndjson` |
| Decisions | `.ai-engineering/state/decision-store.json` |
| Config | `.ai-engineering/manifest.yml` |
| Constitution | [CONSTITUTION.md](CONSTITUTION.md) |
| Architecture / solution intent | [.ai-engineering/solution-intent.md](.ai-engineering/solution-intent.md) (§3.1 layered module map) |

## 13. Hard Rules

Non-negotiable rules per commit, push, and risk-acceptance decision:

1. **Secrets gate.** `gitleaks protect --staged` on commit;
   `semgrep --config .semgrep.yml` + `pip-audit` on push. BLOCK at
   CRITICAL/HIGH/MEDIUM; LOW warns. Risk acceptance via
   `ai-eng risk accept --finding-id …` (never inline).
2. **No suppression.** No `# noqa`, `# nosec`, `// @ts-ignore`,
   `// nolint`, `# pragma: no cover`, `// NOSONAR`. Refactor or
   risk-accept (spec-128 sub-d gate).
3. **No backwards-compat shims** for renamed/deleted/migrated content.
   Hard rename, hard delete, hard migration. CHANGELOG documents the
   breakage.
4. **Anonymous content.** No PII, no machine paths, no operator names
   in committed files. Use placeholders (`$HOME/.local/bin`, `$(which
   …)`) for machine-relative references.
5. **Bounded fail-loud quality loop.** `/ai-build` and
   `/ai-autopilot` Phase 5 may spend ONE finding-scoped remediation
   pass on blocker/critical/high quality-loop findings, then run a
   terminal final reassessment. Remaining blocker/critical/high
   findings STOP and escalate — no second remediation pass. `/ai-pr`
   keeps its final quality gate fail-loud.
6. **Conventional Commits.** `<type>(<scope>): <subject>` imperative
   mood. Body explains "why", not "what". Never `--no-verify`.
7. **Single Source of Truth Per Datum.** Every datum has exactly one
   canonical writable store. Derived caches are explicitly labelled
   (named, with a rebuild command) and rebuildable on demand. See
   [docs/persistence-doctrine.md](docs/persistence-doctrine.md) for
   the three-tier files-only model and the rebuild semantics.

## 14–16. Pointer rows

The bulk of the canonical-payload prose lives in `.ai-engineering/reference/` so the
mirrors stay lean (spec-134 sub-005 mirror diet). Authoritative homes:

- **§10 Engineering Principles** → [.ai-engineering/reference/principles.md](.ai-engineering/reference/principles.md)
  (§10.1 KISS through §10.8 Hexagonal Architecture; the 34 skill /
  agent files that cite `§10.x` resolve here).
- **§14 Strict Content Contracts** + **§15 IDE-Extras Escape Hatch** →
  [.ai-engineering/reference/mirror-authoring.md](.ai-engineering/reference/mirror-authoring.md) (per-file
  authoring table + the `<!-- ide-extras:start -->` fence contract).
- **§16 Surface Axioms** (A1 / A2) →
  [.ai-engineering/reference/surface-axioms.md](.ai-engineering/reference/surface-axioms.md) (Surface Axiom and
  No-Twin Axiom; D-133-04 enforcement at `test_surface_parity.py`).
- **Error-handling posture** (fail-open vs fail-closed) →
  [.ai-engineering/reference/gate-policy.md](.ai-engineering/reference/gate-policy.md)
  (security/integrity boundaries fail closed; plumbing fails open and must log).

<!-- ide-extras:start -->
<!-- ide-extras:end -->
