# hatch3r — Development Instructions

> Last updated: 2026-06-09

> This file governs framework development. It is NOT generated output — it is the agentic setup for developing hatch3r itself.

hatch3r is an open-source CLI (TypeScript, Commander.js) that generates tool-agnostic agentic coding setups for 3 AI coding tools (Claude Code, Cursor, GitHub Copilot) from a canonical source model (this repo's top-level `agents/`, `skills/`, `rules/`, `commands/`, `hooks/`) and platform adapters. In v1.9.0 the adapter set was hard-cut from 15 to 3 and canonical content is shipped in the bundled npm package — end-user repos no longer materialize a `.agents/` mirror.

---

## Architecture

| Directory | Contents |
|-----------|----------|
| `src/cli/commands/` | 20 CLI commands: init, setup, sync, status, update, validate, verify, config, clean, add, worktree-setup, worktree-cleanup, cliTools, mcp, explain, rollback, provenance, show, deps, learn <!-- count auto-derived; see governance/inventory.json (cliCommands) --> |
| `src/adapters/` | 3 platform adapters: cursor, claude, copilot <!-- count auto-derived; see governance/inventory.json (adapters) --> |
| `src/pipeline/` | 22 pipeline modules: adapterTimeout, adapterToolTranslator, agentIdentity, agentToolAllowlist, checkpoint, circuitBreaker, complianceVerification, costEstimator, diffHash, failureLog, mcpDescriptionScan, observability, phaseOutputSchema, phaseTimeout, pipelineContext, pipelineTimeout, promptGuard, repoSubstitution, retryWithBackoff, reviewLoop, snapshot, spaceTelemetry <!-- count auto-derived; see governance/inventory.json (pipeline) --> |
| `src/content/` | Content indexing, presets (minimal/standard/full), tag system |
| `src/merge/` | Safe write (temp+rename atomic), managed block tracking |
| `src/content/contentRoot.ts` | `resolveBundledContentRoot()` — locates bundled canonical content shipped inside the npm package |
| `agents/` `skills/` `rules/` `commands/` `hooks/` | Canonical content artifacts. Top-level agents map to `inventory.json.counts.agents`; supporting `agents/modes/` and `agents/shared/` files are reference material outside the inventory count. Per-class totals (agents, skills, rules, commands, hooks) and full file lists: `governance/inventory.json` (regenerated by `npm run inventory`, CI gate `inventory --check-docs` runs five probe families — count probes against README + CLAUDE.md + `.cursor-plugin/plugin.json`, version probes, stale-token probes, per-class enumeration probes asserting every canonical id has a `website/docs/reference/*.md` row, and marketplace-description count probes against `docs/marketplace-submission.md`) <!-- counts auto-derived; see governance/inventory.json --> |
| `checks/` `prompts/` `github-agents/` | Additional content directories: 5 checks, 0 prompts (canonical ships none; class reserved for pack supply per `governance/pack-trust-model.md`), 4 github-agents. Filesystem-derived in `inventory.json` (`counts.checks`/`githubAgents`); the `checks` figure excludes `checks/README.md` (`type: documentation`) to match adapter emission |
| `governance/` | 8 Binding Pillars, 24 audit domains, audit cycle, closed-loop phases |
| `.claude/` | Rules, skills, hooks for framework development |

Entry: `src/cli/index.ts` | Build: tsup to `dist/` | Test: vitest | Lint: eslint

---

## Development Commands

```
npm test                    # vitest (global: 78/65/80/80 stmt/branch/func/line)
npm run lint                # eslint
npx tsc --noEmit            # typecheck
npm run build               # tsup
npx hatch3r validate        # content structure + frontmatter + cross-ref
npm run validate:canonical  # strict canonical-read gate: 0 warnings across published content types (release integrity)
```

Critical module thresholds: `src/merge/` (90/80/90/90), `src/content/` (85/70/85/85), `src/adapters/customization.ts` (85/75/85/85).

Commits: Conventional Commits (`feat|fix|refactor|test|docs|chore|audit(scope): msg`), DCO sign-off required (`git commit -s`).

---

## Two-Axis Pillar Framework (2.0.0)

Every change must serve at least one pillar on at least one axis. Full definitions: `governance/CONSTITUTION.md` §2.

**Governance axis (§2A — P1-P8):** how the framework operates.
**Content-quality axis (§2B — CQ1-CQ9):** what the framework produces in end-user code (UI / UX / Security / Reliability / Testability / Scalability / Performance / Maintainability / Enhancability). Each CQ pillar carries measurable thresholds and a specialist agent under `agents/hatch3r-{ui,ux,security,reliability,testability,scalability,performance,maintainability,enhancability}.md`.

| Pillar | Name | Enforcement | Primary Ref |
|--------|------|-------------|-------------|
| P1 | CLI UI/UX Excellence | Actionable errors, progressive disclosure, first-run success | D10 |
| P2 | Scientific & Practical Quality | Adversarial thinking, root-cause orientation, measurable criteria | D1,D5,D7,D13 |
| P3 | Adapter & External Tool Currency | Web-research platform docs + CLI tool releases + CVE feeds each cycle | D2,D9,D21 |
| P4 | Comprehensive Lean Coverage | No bloat, no duplication, single-source-of-truth, every file earns existence | D5,D16 |
| P5 | Governance Self-Quality | Governance passes its own tests, anti-slop, lean thresholds | D16,D18,D19 |
| P6 | Security & Trust Governance | OWASP ASI compliance, trust delegation, prompt injection guards | D15 |
| P7 | Speed & Token Efficiency | Static-first prompts, parallel tools, triage-first orchestration | D06 |
| P8 | Clarification & Fan-out Discipline | B1 ambiguity gate via `agents/shared/user-question-protocol.md`; B2 sub-agent count + rationale emission on delegating artifacts | D5,D7,D13 |

**Pillar Compliance Test** (required for governance/content changes — extended in 2.0.0):
1. Which pillar(s) does this change serve, on which axis (governance and/or content-quality)? If none → reject.
2. What measurable improvement does it produce?
3. Does it increase governance size? If yes → justify net value exceeding size cost.
4. Does it degrade end-user runtime efficiency? If yes → reject or document offset.
5. **Impact horizon (Decision 17):** short | medium | long? If unanswerable → reject.
6. **P8 dominance over P7:** does this change under-fan-out for token-cost reasons? If yes → reject (P8 dominates).

---

## Orchestrator Self-Discipline (Bypass Protection)

Every assistant turn in this repo that causes a file mutation AND operates as an orchestrator-style flow — whether via a registered `/h4tcher-*` command OR an ad-hoc multi-phase task — MUST:

1. Emit the **Per-Turn Pipeline-State Header** at turn start when the task is Tier >= 2 (per `rules/hatch3r-agent-orchestration.md` -> Per-Turn Pipeline-State Header).
2. Spawn `hatch3r-implementer` via the Task tool for every code mutation (per `rules/hatch3r-agent-orchestration.md` -> Implementation Delegation; Mandatory Delegation Directive). No inline `Edit`/`Write`/`MultiEdit` from the orchestrator turn itself except the `hatch3r-quick-change` Tier 1 carve-out.
3. Emit the **End-of-Turn Delegation Attestation** block immediately before the Iteration Summary, citing per-file the spawning sub-agent invocation and the `delegation_proof_id` it returned (per `rules/hatch3r-agent-orchestration.md` -> End-of-Turn Delegation Attestation).

Ad-hoc multi-phase workflows do not exempt these requirements. If you are running research and review sub-agents but inlining implementation, you are in bypass mode (CHANGELOG #73). Halt and re-delegate.

The three numbered steps above ARE the ad-hoc orchestrator scaffold — apply them in order from any session, no registered command required. The `hatch3r-adhoc-orchestrate` skill (`skills/hatch3r-adhoc-orchestrate/SKILL.md`, D24-SA24.2-F11) pre-fills the Per-Turn Pipeline-State Header, the no-inline delegation plan, and the End-of-Turn Delegation Attestation templates as a turnkey starting point; this numbered list remains the authoritative contract.

**Carve-out — capability-lifecycle authoring lane (D20-9).** The `/h4tcher-capability-{add,refactor,remove}` presets and the author skills they delegate to (`h4tcher-content-author`, `h4tcher-adapter-author`, `h4tcher-domain-author`) are a separate framework-authoring lane and are exempt from steps 2-3 above (the `hatch3r-implementer` mandate + `delegation_proof_id` attestation): the author skills are this lane's no-inline-authoring delegation target, and the preset's Step 6 gate table (`validate`, `test`, `tsc`, `lint`, `inventory`, anti-slop, Pillar Compliance) is its verification surface. Rationale + exact scope: `.claude/skills/h4tcher-capability-add/SKILL.md` → "Orchestrator-Self-Discipline boundary". The exemption never licenses inline authoring of any artifact type that has a matching author skill.

---

## Governance References

| File | Purpose |
|------|---------|
| `governance/VISION.md` | North star: identity, audience, quality bar, principles |
| `governance/CONSTITUTION.md` | Design rationale: 8 pillars (P1-P8), traceability matrix, lean thresholds |
| `governance/AUDIT.md` | Audit prompt: 24 domains, 124 sub-agents, behavioral charter |
| `governance/AUDIT-EXECUTE.md` | Execution: 4-wave model, regression gates, closed-loop phases |
| `governance/EVOLVE.md` | Unified interactive governance-evolution engine — 3 modes (full-rewrite / scoped / assess-only), corpus-scan + research fan-out, per-section verdict dialog, per-file-consent rewrite, checkpointed in .evolve-workspace/ |
| `governance/pack-trust-model.md` | Trust tiers + signing methods for distributed packs (referenced from D15) |
| `governance/audit/domains/D01-D24` + `D15-trust-reference.md` | Domain definitions with sub-agent checklists; D15 trust delegation governed appendix (EVOLVE P2, 2026-04-19); D22/D23/D24 domain bodies authored in subsequent audit cycles per Decision 19 |
| `governance/audit/templates/` | Sub-agent role templates + `calibration-protocol.md` for finding scoring |

Content fixes flow through the audit cycle (AUDIT.md then AUDIT-EXECUTE.md). No ad-hoc governance edits.

---

## Anti-Slop Wordlist

Zero tolerance in all `.md` files under `governance/`, `agents/`, `commands/`, `rules/`, `skills/`, `hooks/`. FAIL if any appear without measurable qualifier:

| Banned | Use Instead |
|--------|-------------|
| "best possible", "best-in-class", "world-class" | Specific measurable target |
| "comprehensive and thorough", "exhaustive" | Specific scope statement |
| "robust and resilient" | Named resilience pattern (circuit breaker, retry with backoff) |
| "high-quality" (no measure) | Specific quality metric |
| "ensure" (no method) | Specific verification step |
| "properly", "correctly" (no criterion) | Specific passing condition |
| "as needed", "as appropriate" (no trigger) | Specific trigger condition |
| "scalable" (no dimension) | Specific scale target (N users, M repos) |
| "carefully", "thoroughly" | Remove or replace with specific action |
| "it is important to note", "this section describes" | Remove — state the thing directly |
| "obviously", "clearly", "naturally", "intuitively", "without doubt", "certainly" (when not citing a source) | Cite specific source (file:line OR URL with access date) |
| "this might affect", "could be useful" (without specific impact) | Specify measurable impact prediction OR concrete use case |
| "successfully completed", "everything works", "works as expected" (without verification) | Cite verification command + result (e.g., "npm test exit 0, 432/432 passing") |
| "enterprise-grade", "production-grade" (without maturity tier) | Specify maturity tier per CONSTITUTION §2 P5 + Decision 16 (solo/team/scaleup/enterprise) |

---

## Key Patterns

- **Adapter:** Extend `BaseAdapter` (`src/adapters/base.ts`), implement `doGenerate()`, use `readCanonicalFiles()` (reads from `resolveBundledContentRoot()`, not the user's repo), `applyCustomization()`, `wrapInManagedBlock()`, register in `src/adapters/index.ts`
- **Customization precedence:** Four override layers (canonical frontmatter → `.customize.yaml` → `.customize.md` → manifest `customization`). Higher layer wins; protected + `floor:*` artifacts reject `enabled: false` at layer 2. Full table: `governance/audit/domains/D02-adapter-infrastructure.md` §2.3 → "Customization Precedence". JSDoc cite: `src/adapters/customization.ts::applyCustomizationImpl`.
- **Safe writes:** Temp file + atomic rename via `src/merge/safeWrite.ts`
- **Managed blocks:** `HATCH3R:BEGIN`/`HATCH3R:END` markers preserve user content during updates
- **Pipeline:** Circuit breaker (transient vs substantive failure), prompt guard (500KB input/1MB output), phase timeouts, tool allowlists per agent
- **Content frontmatter:** YAML with `id`, `type`, `description`, `tags`; `hatch3r-` filename prefix
- **Manifest + user state:** `.hatch3r/hatch.json` (manifest, schemaVersion 3), `.hatch3r/overrides/` (canonical overrides), `.hatch3r/learnings/`, `.hatch3r/handoffs/`, `.hatch3r/mcp/`
- **Drift detection:** `hatch3r status` / `hatch3r verify` regenerate adapter outputs from bundled content and diff against the on-disk copy — no `.integrity.json` checksum file

---

## Lean Thresholds

Mirrors `governance/CONSTITUTION.md` §2 P5 verbatim (validator `scripts/validate-lean-threshold-currency.ts` enforces row-by-row parity):

| Metric | Limit |
|--------|-------|
| CONSTITUTION.md | <=550 lines |
| VISION.md | <=250 lines |
| AUDIT.md | <=600 lines |
| AUDIT-EXECUTE.md | <=720 lines |
| EVOLVE.md | <=700 lines |
| pack-trust-model.md | <=300 lines |
| rules/*.md (precedence: critical or high) | <=250 lines |
| rules/*.md (precedence: normal or low) | <=120 lines |
| CLAUDE.md | <=300 lines |
| README.md | <=200 lines |
| docs/*.md per file | <=400 lines |
| Static-first prompt structure | required for `orchestrator: true` and `agents/*.md` |
| Parallel-tool-by-default directive | required when artifact uses ≥2 independent tool calls |
| Triage-first orchestrator | required when `orchestrator: true` |
| Audit-execute SA-per-finding ratio (Critical/High/Medium/Low/Info) | 1:1 / ≤1:8 / ≤1:15 / ≤1:30 / ≤1:50 |
| Finding impact-gating (Decision 17) | required: impact_horizon ∈ {short, medium, long} + progress_toward_pillar = <pillar_id>+<delta> |
| Anti-cache patterns | 0 per artifact |
| Domain file (SA ≤5) | 30-80 lines |
| Domain file (SA >5) | SA × 15 lines |
| Template file | 80-200 lines |
| Cross-file duplication | <5% |
| Finding inflation | <2.0x pre-dedup/post-impact-gating/post-triage |
| Governance total (sum of the 6 lean-tracked prompts: CONSTITUTION + VISION + AUDIT + AUDIT-EXECUTE + EVOLVE + pack-trust-model) | <=3120 lines |
| Generated UI a11y violations (axe-core, serious/critical) | 0 |
| Design-token adoption in generated code (color, spacing, typography) | >=95% |
| Four-state surface contract coverage on generated async views | 100% |
| Generated-service OTel instrumentation on request path | 100% |
| Migration expand-contract conformance | 100% |
| Shared-contract consumer-census coverage on taxonomy-touching diffs | 100% |
| API breaking-change events on stable endpoints | 0 per release |
| AI feature eval coverage | 100% |
| Per-feature test-class mandate compliance | 100% |
| Edge-case enumeration coverage on changed surfaces (generated code) | >=90% |
| Illegal-state-prevention adoption on state machines / unions (generated code) | 100% |
| Supply-chain floor coverage | 100% |
| User-facing service SLO defined | 100% |
| Auth depth coverage | 100% |
| Anti-slop phrases | 0 per file |
| Checklist items/SA | 4-8 |
| Ambiguity-detection gate coverage (agents/skills/commands) | 100% |
| Sub-agent count emission on delegating artifacts | 100% |
| Universal floor invariant (security + UI/UX + protocol + content-quality) | structural invariant: every non-custom preset admits every item tagged `floor:security`, `floor:ui-ux`, `floor:protocol`, or `floor:content-quality` unconditionally; under Decision 16 (dial, not gate) every preset admits the full corpus, so this row guarantees `floor:*` items can never be disabled at any tier, anchoring the §2B universal floor |
| Tag-facet integrity on canonical artifacts | every canonical agent/skill/rule/command/hook carries ≥1 capability tag OR ≥1 floor tag in frontmatter; `customize` and `floor:*` items are exempt from capability-gate filtering |
| Rule-precedence assignment policy | security + secrets rules → `precedence: critical` (rank 100, prefix `10-`); rules implementing CONSTITUTION §2 P2 hard-mandate floors (supply-chain, observability, migrations, auth depth, AI evals, accessibility, etc.) and framework-dev gatekeepers → `precedence: high` (rank 300, prefix `30-`); cosmetic/style → `precedence: normal` (rank 500, prefix `50-`); deprecation hawks → `precedence: low` (rank 700, prefix `70-`) |
| Detail-rule frontmatter declaration (`rules/*-detail.{md,mdc}`) | required: `detail_rule: true` + `consumed_by: <parent-rule-id>` on both `.md` and `.mdc` |

---

## Rules & Skills

- **Rules:** `.claude/rules/` — Loaded automatically each session. Enforce pillar-specific constraints.
- **Skills:** `.claude/skills/h4tcher-*/` — Invokable as `/h4tcher-<name>`. The `h4tcher-` prefix marks framework-internal slash commands so they are visually distinct in Claude Code's slash-command picker. Capability lifecycle presets:
  - `/h4tcher-capability-discover` — pre-flight artifact scan
  - `/h4tcher-capability-add` — author a new artifact (delegates to `h4tcher-content/adapter/domain-author`)
  - `/h4tcher-capability-refactor` — rename/split/merge/restructure with cross-reference scrubbing
  - `/h4tcher-capability-remove` — phase out with migration notes and reference cleanup
  - `/h4tcher-scoped-audit` — bounded focused audit of a maintainer-described slice (read-only, in-chat report)
- **Hooks:** `.claude/settings.json` — two channels are configured: a `SessionStart` hook loads governance context (CONSTITUTION preview + audit finding-registry summary), and a `ConfigChange` hook (matcher `user_settings`, added Cycle-10) prints a config-tamper notice when `.claude/settings.json` changes. No PreToolUse, PostToolUse, or SubagentStart channels are configured. When pruning hooks, keep both channels — dropping `ConfigChange` removes the config-tamper guard; any change to the channel set must be back-propagated here from `.claude/settings.json`.
  - **Dev-env vs generated split (D19-14):** the framework-dev `.claude/settings.json` deliberately omits the `TaskCompleted`/`TeammateIdle` quality-gate hooks — those are Agent-Teams runtime hooks the `claude` adapter generates into END-USER repos (`src/adapters/claude.ts` → `hooksConfig.TaskCompleted`/`TeammateIdle`, emitted into the generated `.claude/settings.json` and additively duplicated into `.claude/hooks/hatch3r-hooks.json`). Framework development gates quality through the audit cycle (`governance/AUDIT.md` → `AUDIT-EXECUTE.md`) and the orchestration rules in `.claude/rules/`, not runtime hooks. Re-deciding this (wiring those two hooks into the dev settings.json) is a behavior change — route it through a B1 clarification gate, not a silent edit.
