# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build & Development Commands

```bash
npm run build              # Lint + TypeScript compile
npm run typecheck          # tsc --noEmit (type-check only)
npm run lint               # ESLint with --max-warnings 0
npm run lint:fix           # ESLint with auto-fix
npm run test               # Vitest with coverage (via Nx)
npm run run                # Run CLI: tsx apps/control-plane/src/cli/aop.ts

# Run a single test file
npx vitest run apps/control-plane/test/<file>.spec.ts

# Run tests matching a pattern
npx vitest run -t "pattern"

# Validation scripts (also run in CI)
npm run validate:mcp-contracts
npm run validate:architecture
npm run validate:docker-mcp
```

## Architecture

This is an MCP-first, multi-agent orchestrator control plane. The codebase lives in an Nx monorepo with a single application at `apps/control-plane/`.

### Layer Overview

**CLI** (`apps/control-plane/src/cli/`) → **Supervisor** (`supervisor/`) → **Kernel** (`core/kernel.ts`) → **Services** (`application/services/`)

- **CLI**: Entry point at `cli/aop.ts` → delegates to `interfaces/cli/bootstrap.ts`. Commands: `run`, `add`, `status`, `questions`, `answer`, `resume`, `stop`, `delete`, `cleanup`, `rollback`, `init`, `dashboard`, `collision`, `retry`, `merge`, `send`, `attach`, `completion`, `help` (plus hidden `__complete` backend for generated shell scripts). `run` and `add` accept `-fi`/`--fi` (file) and `-fl`/`--fl` (folder); `add` also supports `--resume <feature-id>` to re-enroll an existing non-terminal feature into the active execution. `run`/`resume` support `--execution-mode <deterministic|interactive>` overrides. `questions` lists persisted human-input questions for a feature, and `answer` resolves one through the shared question protocol. `collision` supports `--allow`, `--list`, `--revoke`, and `--resume` for intentional overlap approvals. `merge` supports `--sync-remote <auto|skip>` for remote/local mainline divergence handling. `completion` emits Bash/Zsh/Fish registration scripts. All responses are structured JSON with `{ ok, data/error }`. Run `aop --help` or `aop help <command>` for usage details.
- **Kernel** (`core/kernel.ts`, ~900 lines): Deterministic orchestration engine. Manages schema validation, state, locks, plans, patches, gates, merges, and reporting. Delegates to 12+ domain services via port interfaces.
- **Supervisor** (`supervisor/runtime.ts`): Multi-agent runtime. Resolves providers (codex, claude, gemini, etc.), loads role-specific prompts, orchestrates planning/build/QA waves, manages lease heartbeats.
- **MCP Tool Runtime** (`mcp/tool-runtime.ts`): Tool execution pipeline with registry-based dispatch, input/output schema validation, role-based authorization, and idempotency tracking via `operation_id`.
- **Application Services** (`application/services/`): 12+ focused services (plan, patch, gates, QA, locks, merge, deletion, etc.) implementing port interfaces consumed by the kernel.

### Configuration Layer (`config/agentic/orchestrator/`)

- `policy.yaml` — Commit/patch/merge policies, lock TTL, RBAC, supervisor iteration limits
- `gates.yaml` — Gate profiles (fast/full/merge) with commands and coverage thresholds
- `agents.yaml` — Agent roles (planner/builder/qa), provider defaults, execution mode defaults (`deterministic|interactive`), prompt paths
- `prompts/` — Role-specific system prompts
- `tools/` — MCP tool contracts: `catalog.json` (33 tools), per-tool `schemas/input/` and `schemas/output/`
- `schemas/` — JSON schemas for policy, state, plan, index, gates, agents, qa_test_index

### Runtime Artifacts (`.aop/`)

- `.aop/features/index.json` — Global feature index (active/blocked/merged features, locks, sessions)
- `.aop/features/<id>/state.md` — Per-feature state (YAML frontmatter + markdown)
- `.aop/features/<id>/plan.json` — Versioned plan with optimistic concurrency
- `.aop/features/<id>/evidence/` — Gate evidence artifacts

## Key Patterns

- **Port-based DI**: Services define interface ports; the kernel implements them. This decouples domain logic from infrastructure.
- **Schema-driven validation**: All configs and artifacts validated via AJV against JSON schemas. Validation failures return structured errors with retry hints.
- **Atomic state management**: File locks, version guards, and optimistic concurrency for all state mutations.
- **Structured error codes**: 45+ error codes with `{ code, message, details: { retryable, requires_human, suggestions } }`.
- **Tool registry dispatch**: `catalog.json` metadata drives tool routing, replacing switch-based dispatch. Mutating tools require `operation_id` for idempotency.

## Design Principles

- **KISS (Keep It Simple, Stupid)**: Prefer the simplest design that satisfies requirements and preserves deterministic behavior.
- **SRP (Single Responsibility Principle)**: Each class/module should have one clear reason to change.
- **SOLID (pragmatic application)**:
  - Open/Closed: Extend by adding adapters/services instead of modifying unrelated orchestrator flow.
  - Interface Segregation: Keep interfaces focused (avoid broad "do everything" contracts).
  - Dependency Inversion: Depend on ports/interfaces, not concrete infrastructure.
- **Hexagonal Architecture**: Domain/application layers must not depend directly on provider CLI/SDK details; keep those in adapter boundaries.
- **Composition over Inheritance**: Build behavior through composed collaborators (factory + adapter + parser + service) rather than deep class hierarchies.
- **High Cohesion, Low Coupling**: Keep CLI parsing, provider execution, orchestration logic, and persistence concerns in separate modules.

## Lint Rules to Know

- `no-explicit-any` is **enforced** in source, relaxed in tests
- `no-floating-promises` and `no-misused-promises` are errors
- `require-await` is enforced in source, relaxed in tests
- `consistent-type-imports` is required (use `import type` for type-only imports)
- `no-console` is an error in source (except `warn`/`error`); allowed in scripts and CLI entry point
- Unused variables must be prefixed with `_`
- Zero warnings allowed (`--max-warnings 0`)

## Adding a New CLI Command or Flag

When adding a new command or flag to the CLI, update **all** of the following in the same change:

1. **`apps/control-plane/src/cli/types.ts`** — add the command to the `CliCommand` enum.
2. **`apps/control-plane/src/cli/cli-argument-parser.ts`** — parse the new flag/command token.
3. **`apps/control-plane/src/interfaces/cli/bootstrap.ts`** — dispatch the new command.
4. **`apps/control-plane/src/cli/help-command-handler.ts`** — add or update the entry in `COMMAND_HELP` (both the command summary and its flags list). This is the source of truth for `aop --help` output.
5. **`CLAUDE.md`** — update the command list in the CLI bullet point above.

## Coverage Thresholds

Lines: 90% | Branches: 90% | Functions: 90% | Statements: 90%

## Updating progress.md

`spec-files/progress.md` is the versioned work log for this repository. **After completing any meaningful code change** (new feature, bug fix, refactor, test coverage improvement, validator change, etc.), append a new numbered entry to the **Completed Tasks** section of `progress.md`.

### Entry format

Each entry must include:

- A sequential number (increment from the last entry)
- A short title describing what was done
- **Goal** — one sentence on why the change was made
- **Changes made** — bullet list of files modified and what changed; be specific (function names, test counts, metric deltas)
- **Result** — outcome verification (e.g. `npm test ✅`, `npm run lint ✅`, validator output)

```
✅ **Entry N — Short Title**
   - **Goal:** One-sentence description of the problem or objective.
   - **Changes made:**
     - `path/to/file.ts` — description of what changed and why.
     - `apps/control-plane/test/foo.spec.ts` — X tests added covering Y branches.
   - **Result:** `npm test` ✅ (N test files / M tests passing). `npm run lint` ✅.
```

### Rules

- **One entry per logical unit of work.** Don't bundle unrelated changes into one entry.
- **Do not edit or renumber past entries.** The log is append-only.
- Entries go in the **Completed Tasks** section (before the `## Next Tasks:` heading).
- The `## Next Tasks:` section lists only work that has **not yet been done**. Move items out of it once completed.
- After completing work from a spec file, update the **Spec Gap Tracker** table (if present) to mark the item `✅ Complete`.

## Executing a Spec

When beginning work from a spec file (e.g. `spec-files/agentic_orchestrator_*.md`):

1. **Before writing any code**, read the spec and add all planned tasks to the `## Next Tasks:` section of `progress.md`. Use the spec's section numbers as identifiers (e.g. `§3.1 — Add mutating cross-check`).
2. **As each task completes**, move it out of `## Next Tasks:` and into a new numbered `✅ **Entry N — ...`\*\* in the Completed Tasks section.
3. **Never leave a completed task in `## Next Tasks:`**. The section must only contain work that hasn't started or isn't finished.
4. If a task is blocked or deferred, leave it in `## Next Tasks:` with a `[BLOCKED]` or `[DEFERRED]` annotation and a one-line reason.

---

## TMS Operational Loop

Before proposing or writing any code, follow this read order:

1. `NEXT-TASKS.md` — understand current context and planned work
2. `docs/core/DOMAIN-LOGIC.md` — invariants and kernel rules that must be preserved
3. `docs/core/PATTERNS.md` — canonical implementation examples for this codebase
4. `docs/core/ARCHITECTURE.md` — component map and data flow for orientation
5. `docs/core/DECISIONS.md` — ADRs explaining why technical choices were made
6. `docs/core/TROUBLESHOOTING.md` — known gotchas and non-obvious workarounds

## Pre-Submission Checklist

Before proposing or submitting any code change:

- [ ] Logic verified against `docs/core/DOMAIN-LOGIC.md` invariants (state machine, lock rules, error handling).
- [ ] Implementation follows patterns in `docs/core/PATTERNS.md` (fail + ERROR_CODES, port DI, atomic writes, import types).
- [ ] Tests added or updated; `npm run test` passes at ≥90% coverage thresholds.
- [ ] No `console.log` in source files under `apps/control-plane/src/` (use `console.warn`/`console.error` only).
- [ ] No `any` types in source files; no `@ts-ignore`.
- [ ] `npm run verify` passes clean.
- [ ] `spec-files/progress.md` updated with a new numbered entry.

## Dependency and navigation policy

This repository includes an automatically generated dependency and navigation index produced by **IntentGraph**. You must use it as the primary source of truth for repository relationship questions.

### Required behavior

Use the IntentGraph index first whenever you need to understand:

- Dependency chains between files or modules
- Reverse dependencies
- Import or require relationships
- Likely impact surfaces of a code change
- Which files should be opened next for implementation work

### Index location

- `./docs/core/intentgraph.index.json`

### Required workflow

1. Consult the IntentGraph index to identify the smallest relevant set of files.
2. Open only those files needed to confirm implementation details.
3. Avoid broad repo scanning when the index already answers the relationship question.
4. If the index is missing, stale, or insufficient, regenerate it or explicitly state that analysis is proceeding without a fresh index.

### Token-efficiency rule

Do not load or paste the full IntentGraph output into context. Use only the relevant dependency edges, path segments, or file subsets needed for the task.

### Staleness rule

If the index contradicts the code, assume the index is stale until proven otherwise.

## TMS Documentation References

<!-- AI-DRAFT: Review before treating as canonical -->

| Doc                            | Purpose                                                     |
| :----------------------------- | :---------------------------------------------------------- |
| `docs/core/ARCHITECTURE.md`    | Component map, data flow, deployment, security posture      |
| `docs/core/DOMAIN-LOGIC.md`    | Business invariants (state machine, locks, patches, errors) |
| `docs/core/PATTERNS.md`        | Canonical implementation examples with anti-patterns        |
| `docs/core/DECISIONS.md`       | ADRs — why key technical decisions were made                |
| `docs/core/TROUBLESHOOTING.md` | Known issues and non-obvious workarounds                    |
| `NEXT-TASKS.md`                | Current sprint tasks and definition of done                 |
