# Agentic-Orchestrator Project

[![TypeScript](https://img.shields.io/badge/TypeScript-NodeNext-3178C6.svg)](https://www.typescriptlang.org/)
[![Nx Workspace](https://img.shields.io/badge/Nx-Monorepo-143055.svg)](https://nx.dev/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A semi-deterministic, MCP-first control plane for parallel multi-agent feature development.

It combines:

- a **deterministic kernel** (state, locks, collisions, gates, evidence)
- a **supervisor runtime** (orchestrator/planner/builder/qa session coordination)
- a **CLI contract** (`aop <run|status|resume|stop|delete|cleanup|rollback|init|dashboard|retry|merge|send|attach|completion>`) with deterministic spec ingestion, runtime control, monitoring, cleanup, and shell registration output

> For complete normative requirements, see [agentic_orchestrator_spec.md](spec-files/agentic_orchestrator_spec.md).
> For implementation continuity and the latest status, see [progress.md](spec-files/progress.md).

---

## Quick Overview

Without a deterministic control plane, agentic parallel development is fragile:

```bash
# brittle: no centralized state, lock ownership, or collision arbitration
# (multiple agents independently edit overlapping files/resources)
```

With Agentic-Orchestrator:

```bash
# deterministic: canonical state + lock leases + collision checks + gate evidence
npm run run -- -fi ./.aop/features/my_feature/spec.md --agent-provider custom
```

Core guarantees:

- policy/schema validated plans before build
- worktree-per-feature isolation
- lock lease ownership for shared resources
- gate execution with evidence artifacts
- explicit merge promotion path (`feature.ready_to_merge`)

## Installation

```bash
npm install
```

## Quick Start

### 1. Prepare or use a feature spec

Canonical path format:

```text
.aop/features/<feature_id>/spec.md
```

### 2. Run typecheck and build

```bash
npm run typecheck
npm run build
```

### 3. Run one feature flow

```bash
npm run run -- -fi ./.aop/features/my_feature/spec.md --agent-provider custom
```

### 4. Check runtime status

```bash
npm run run -- status
```

### 5. Resume from persisted state

```bash
npm run run -- resume
```

---

## Development

This repository is the **control-plane workspace** for Agentic-Orchestrator.

### Project Structure

```text
Agentic-Orchestrator/
├── .aop/
│   ├── features/                      # runtime-generated feature artifacts
│   │   └── index.json                # global orchestration index
│   └── runtime/
│       └── operation-ledger/
├── agentic/
│   └── orchestrator/                  # policy/gates/agents config + schemas + prompts + tools
│       ├── policy.yaml
│       ├── gates.yaml
│       ├── agents.yaml
│       ├── adapters.yaml
│       ├── defaults/
│       │   └── policy.defaults.yaml   # bundled canonical policy defaults (deep-merged at runtime)
│       ├── schemas/                   # JSON schemas (policy, state, plan, gates, agents, etc.)
│       ├── prompts/                   # role-specific system prompts
│       └── tools/                    # MCP tool contracts: catalog.json, per-tool input/output schemas
├── apps/
│   └── control-plane/
│       ├── src/
│       │   ├── cli/                   # aop CLI commands and handlers
│       │   ├── core/                  # deterministic kernel (kernel.ts, schemas.ts)
│       │   ├── application/
│       │   │   └── services/          # 20+ domain services (plan, patch, gates, locks, policy-loader, etc.)
│       │   ├── interfaces/
│       │   │   └── cli/               # bootstrap.ts — CLI command dispatch
│       │   ├── mcp/                   # MCP tool runtime and tool-registry-loader
│       │   ├── providers/             # provider resolution + adapter
│       │   └── supervisor/            # runtime orchestration loop
│       ├── test/                      # Vitest suites
│       ├── project.json               # Nx targets
│       └── vitest.config.ts
├── docker/
│   ├── mcp.Dockerfile
│   ├── mcp.entrypoint.sh
│   └── mcp.compose.yaml
├── spec-files/
│   ├── completed/                     # completed spec files
│   ├── outstanding/                   # pending / in-progress specs
│   └── progress.md                    # implementation continuity log
└── README.md
```

### Setup

```bash
git clone https://github.com/Eric-Taurone-Software/Agentic-Orchestrator.git
cd Agentic-Orchestrator
npm install
```

### Development Workflow

#### Type-check

```bash
npm run typecheck
```

#### Build

```bash
npm run build
```

`npm run build` is lint-gated (`npm run lint && ...`) and fails on any lint warning/error.

#### Lint

```bash
npm run lint
```

#### Run tests

```bash
npm test
```

#### Validate MCP contract pins and registry/docs consistency

```bash
npm run validate:mcp-contracts
```

#### Validate architecture boundaries

```bash
npm run validate:architecture
```

#### Validate Docker MCP deployment contract

```bash
npm run validate:docker-mcp
```

#### Run orchestrator CLI

```bash
# source mode (tsx)
npm run run -- -fi ./.aop/features/my_feature/spec.md --agent-provider custom

# built artifact
node dist/apps/control-plane/cli/aop.js run -fi ./.aop/features/my_feature/spec.md --agent-provider custom
```

---

## CLI Contract

Primary command:

```bash
aop <command> [flags]
```

If no command is provided, the CLI defaults to `run`. Run `aop help` for the full command list, or `aop help <command>` for per-command flags.

All commands print JSON to stdout. Errors use:

```json
{ "ok": false, "error": { "code": "...", "message": "...", "details": { ... } } }
```

Available commands: `run`, `status`, `resume`, `stop`, `delete`, `cleanup`, `rollback`, `init`, `dashboard`, `retry`, `merge`, `send`, `attach`, `completion`, `help`.

### `completion`

Prints a shell registration script for Bash, Zsh, or Fish. This command writes raw shell code to stdout so it can be evaluated or sourced directly.

Examples:

```bash
# Bash
eval "$(aop completion bash)"

# Zsh
eval "$(aop completion zsh)"

# Fish
aop completion fish | source
```

The hidden backend `aop __complete` is reserved for the generated shell scripts and always degrades gracefully to empty output on malformed input.

### `run`

Starts orchestration for feature specs and returns runtime metadata (`runtime_status`, `queue_depth`, dashboard snapshot, and active feature list).

Examples:

```bash
# Installed binary
aop run -fi ./.aop/features/my_feature/spec.md --agent-provider custom

# In-repo dev command
npm run run -- -fi ./.aop/features/my_feature/spec.md --agent-provider custom
```

Behavior:

- Input resolution:
  - `-fi <path>` uses one file.
  - `-fl <path>` recursively discovers all `*.md` files in deterministic lexical order.
  - no `-fi/-fl` calls `feature.discover_specs` and runs discovered canonical specs.
- Canonical ingestion:
  - canonical input (`.aop/features/<feature_id>/spec.md`) runs in place.
  - non-canonical input is copied to `.aop/features/<feature_id>/spec.md`.
  - `feature_id` is derived from file stem (strips `.spec` or `-spec` suffixes when present).
  - each ingested feature runs `feature.init`, then state source metadata is patched with source path/hash.
- Provider selection precedence:
  1. CLI flags (`--agent-provider`, `--agent-model`, `--agent-config`, `--provider-config-env`)
  2. env vars (`AOP_AGENT_PROVIDER`, `AOP_AGENT_MODEL`, `AOP_AGENT_CONFIG`/`AOP_AGENT_CONFIG_JSON`, `AOP_PROVIDER_CONFIG_ENV`)
  3. `config/agentic/orchestrator/agents.yaml` runtime defaults
- Provider credential resolution (`provider_config_ref`):
  1. `--provider-config-env <NAME>` if `NAME` exists in env
  2. `agents.yaml runtime.provider_config_env` if that env var exists
  3. `AOP_PROVIDER_CONFIG_ENV` fallback:
     - if it looks like an env-var name and that env var exists, use that value (legacy indirection)
     - otherwise use `AOP_PROVIDER_CONFIG_ENV` as the direct credential value
- Runtime start:
  - starts `SupervisorRuntime` with `max_active_features=5`, `max_parallel_gate_runs=3`.
  - `max_iterations_per_phase` resolves from `policy.yaml` (`supervisor.max_iterations_per_phase`, default `6`).
  - `--takeover-stale-run` enables stale run-lease takeover when another run is stale.
  - `--execution-mode <deterministic|interactive>` overrides worker execution mode for the run:
    - `deterministic` (default): PATCH outputs are validated/applied through `repo.apply_patch`.
    - `interactive`: builder/qa workers get direct `working_directory` access and checkpoint validation snapshots are written under `.aop/features/<feature_id>/checkpoints/`.

### `status`

Returns orchestration snapshot via `report.dashboard`:

- global index (`active`, `blocked`, `merged`, locks, runtime session metadata)
- per-feature summaries (status, held locks, gate profile/results, timestamps)

Example:

```bash
aop status
```

### `resume`

Runs recovery (`kernel.recoverFromState`), reconstructs resumable non-terminal feature work, and restarts `SupervisorRuntime` from persisted state:

- candidate sources:
  - `index.active`
  - `index.blocked`
  - `index.blocked_queue`
  - `runtime_sessions.feature_sessions`
  - `feature.discover_specs`
- feature selection:
  - excludes terminal states (`merged`, `failed`)
  - computes deterministic `resume_phase` (`planning|building|qa|ready_to_merge`)
  - sorts by earliest phase then `feature_id`
- runtime restart:
  - reuses persisted `runtime_sessions.run_id` and `owner_instance_id` when present
  - starts supervisor loop with reconstructed feature set
  - supports `--execution-mode <deterministic|interactive>` override for resumed worker waves

If no resumable features are found, `resume` returns recovery metadata only and does not start a new loop.

Example:

```bash
aop resume
```

---

## Docker MCP Deployment

Baseline container artifacts:

- image definition: `docker/mcp.Dockerfile`
- runtime preflight entrypoint: `docker/mcp.entrypoint.sh`
- compose contract: `docker/mcp.compose.yaml`

Required runtime assumptions:

- target repository is bind-mounted at `/repo`
- container includes `node`, `npm`, `npx`, and `git`
- commands execute from `/repo`

Quick usage:

```bash
docker compose -f docker/mcp.compose.yaml build aop-mcp
docker compose -f docker/mcp.compose.yaml run --rm aop-mcp npm run run -- status --transport mcp
```

Contract validation:

```bash
npm run validate:docker-mcp
node apps/control-plane/scripts/validate-docker-mcp-contract.mjs --smoke
```

### `stop`

Stops the dashboard server by killing the process listening on a port.

Example:

```bash
aop stop

# Stop a custom dashboard port
aop stop --port 8080
```

### `delete`

Performs deterministic feature cleanup. Default behavior is preview-only (`dry_run=true`); destructive execution requires `--yes`.

Examples:

```bash
# Preview cleanup plan only (default behavior)
aop delete --feature-id my_feature

# Apply cleanup (remove runtime artifacts + worktree; keep local branch)
aop delete --feature-id my_feature --yes

# Apply cleanup and force-delete local branch
aop delete --feature-id my_feature --yes --remove-branch force
```

Behavior:

- blocks deletion when a fresh run lease exists (`run_already_active`)
- preview reports planned cleanup for feature files, index/session references, locks, blocked queue entries, worktree, and branch
- execution removes feature residue from index/runtime state, deletes `.aop/features/<feature_id>`, optionally removes worktree, and optionally removes local branch

### `cleanup`

Removes merged or stale feature artifacts, worktrees, and index residue. Default behavior is preview-only; destructive execution requires `--yes`.

```bash
# Preview what would be cleaned
aop cleanup

# Apply cleanup for all eligible (merged/stale) features
aop cleanup --yes
```

When `cleanup.auto_after_merge` is enabled in `policy.yaml`, the runtime automatically triggers cleanup after a successful merge.

### `rollback`

Reverses a checkpoint snapshot in the feature worktree using `git apply -R`.

```bash
# Preview rollback inputs
aop rollback --feature-id my_feature --checkpoint checkpoint-123 --dry-run

# Apply rollback
aop rollback --feature-id my_feature --checkpoint checkpoint-123
```

### `init`

Initialises agentic orchestrator configuration in the current directory. Generates `policy.yaml`, `gates.yaml`, `agents.yaml`, `adapters.yaml`, and system prompt templates. The wizard also captures default agent `provider`/`model`, `scm-provider`, and provider-auth mode.

Schema files are bundled with AOP and validated from the installation path; `aop init` does not copy schemas into the target repository.

```bash
# Interactive wizard (generates lean policy.yaml with common controls only)
aop init

# Non-interactive (all defaults, lean policy)
aop init --auto

# Generate full explicit policy.yaml with all advanced controls
aop init --advanced-policy

# Non-interactive with full policy
aop init --auto --advanced-policy

# Overwrite existing configuration
aop init --force
```

#### Policy Modes

**Lean policy (default):** `aop init` emits a minimal `policy.yaml` containing only the common controls users typically customise — `worktree.base_branch`, `supervisor.max_parallel_gate_runs`, `dashboard`, `merge_policy`, `notifications`, and `recovery`. All other fields (RBAC, locks, execution, implementation constraints, etc.) are provided by the bundled `policy.defaults.yaml` at runtime.

**Full policy (`--advanced-policy`):** Generates the complete `policy.yaml` with all controls expanded, useful for teams that need to audit or customise advanced settings.

#### Runtime Policy Composition

At runtime the kernel always composes a canonical full policy by:

1. Loading bundled `agentic/orchestrator/defaults/policy.defaults.yaml`
2. Loading `config/agentic/orchestrator/policy.yaml` from your repository
3. Deep-merging user overrides over defaults (scalars replace, objects merge, arrays replace wholesale)
4. Validating the merged result against the full `policy.schema.json`

Existing repositories with full `policy.yaml` files continue to work without changes — user values override defaults entirely.

#### Provider Auth Flow In `aop init`

- wizard prompt: `Will you use a local agent CLI ... (yes/no)` (default `yes`)
- if `yes`: init skips `runtime.provider_config_env` in `agents.yaml`
- if `no`: init asks for provider env var name and checks both process env and repo `.env`
- if missing: init prompts for a key, stores it in `.env` as `AOP_PROVIDER_CONFIG_ENV`, and writes `runtime.provider_config_env: AOP_PROVIDER_CONFIG_ENV`
- `aop init --auto` defaults to local-CLI mode and does not emit `provider_config_env`

### `dashboard`

Starts the web dashboard server (`packages/web-dashboard/`). Provides a real-time Kanban view of all features, review approval/denial, checkout, and SSE-based live updates.

```bash
# Start in production mode (default port 3000)
aop dashboard

# Custom port
aop dashboard --port 8080

# Development mode (Next.js hot reload)
aop dashboard --dev
```

### `retry`

Retries a failed gate or step for a feature. Use `--force` to reset state and force a gate re-run.

```bash
aop retry --feature-id my_feature

# Force retry regardless of current state
aop retry --feature-id my_feature --force
```

### `send`

Sends a message to the active agent session for a feature.

```bash
aop send --feature-id my_feature --message "focus on the error handling path"

# Positional form
aop send my_feature "focus on the error handling path"
```

### `attach`

Attaches interactively to the running agent session for a feature (provider support required).

```bash
aop attach --feature-id my_feature

# Positional form
aop attach my_feature
```

### `help`

Prints the full command list or detailed help for a specific command.

```bash
aop help
aop help run
aop help dashboard
```

### CLI Options

Supported options:

| Option                                                                | Description                                                                       |
| --------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `-fi <PATH>`                                                          | Run exactly one spec file                                                         |
| `-fl <PATH>`                                                          | Resolve all `**/*.md` files recursively in a folder (deterministic lexical order) |
| `--batch`                                                             | Batch-ingest all specs; skip already-active features (`run`)                      |
| `--agent-provider <codex\|claude\|gemini\|custom\|kiro-cli\|copilot>` | Provider selection                                                                |
| `--agent-model <model-id>`                                            | Model selection                                                                   |
| `--agent-config <json-object>`                                        | Additional provider-specific agent config (for example command/args payload)      |
| `--provider-config-env <ENV_VAR>`                                     | Provider auth/config env var name for API-backed providers                        |
| `--transport <mcp\|inprocess>`                                        | Tool transport selection (default `mcp`)                                          |
| `--takeover-stale-run`                                                | Allow stale run-lease takeover during `run`                                       |
| `--project <name>`                                                    | Select project from `multi-project.yaml` (run, status, resume, retry)             |
| `--feature-id <id>`                                                   | Target feature for `delete`, `cleanup`, `rollback`, `retry`, `send`, `attach`     |
| `--checkpoint <id>`                                                   | Target checkpoint id for `rollback`                                               |
| `--dry-run [true\|false]`                                             | Preview-only mode for `delete`, `cleanup`, and `rollback`                         |
| `--yes`                                                               | Confirm destructive `delete` or `cleanup` execution                               |
| `--remove-worktree [true\|false]`                                     | Whether to remove `.worktrees/<feature_id>` (default `true`)                      |
| `--remove-branch <none\|safe\|force>`                                 | Local branch cleanup mode (default `none`)                                        |
| `--summary`                                                           | Condensed one-line-per-feature output (`status`)                                  |
| `--all`                                                               | Aggregate across all projects (`status`); delete all features (`delete`)          |
| `--auto`                                                              | Non-interactive init with all defaults (`init`)                                   |
| `--force`                                                             | Overwrite existing config (`init`); force retry regardless of state (`retry`)     |
| `--port <number>`                                                     | Dashboard listen port (`aop dashboard`) or stop target port (`aop stop`)          |
| `--dev`                                                               | Start dashboard in Next.js dev mode                                               |
| `--foreground`                                                        | Keep dashboard server in the foreground                                           |
| `--message <text>`                                                    | Message to deliver to agent session (`send`)                                      |

Validation behavior:

- `-fi` and `-fl` are mutually exclusive (`invalid_cli_args`)
- missing path/folder -> `input_path_not_found`
- no discovered specs -> `no_specs_found`
- unsupported command -> `invalid_cli_args`
- invalid `--transport` -> `invalid_cli_args`
- `delete` without `--feature-id` -> `invalid_cli_args`
- destructive `delete` without `--yes` -> `invalid_cli_args` when explicitly requested via `--dry-run false`

Feature ID derivation for non-canonical inputs:

1. start from filename stem
2. remove `.spec` suffix if present
3. else remove `-spec` suffix if present
4. result must match `^[a-z0-9_][a-z0-9_-]*$`

Provider resolution precedence:

1. CLI flags
2. env vars (`AOP_AGENT_PROVIDER`, `AOP_AGENT_MODEL`, `AOP_AGENT_CONFIG`/`AOP_AGENT_CONFIG_JSON`, `AOP_PROVIDER_CONFIG_ENV`)
3. `config/agentic/orchestrator/agents.yaml` runtime defaults

Provider credential fallback:

1. `--provider-config-env <NAME>` if `NAME` exists
2. `runtime.provider_config_env` if that env var exists
3. `AOP_PROVIDER_CONFIG_ENV`:
   - `AOP_PROVIDER_CONFIG_ENV=OTHER_ENV` and `OTHER_ENV` exists -> use `OTHER_ENV`
   - otherwise treat `AOP_PROVIDER_CONFIG_ENV` as direct credential value

Transport behavior:

- default transport is `mcp`
- use `--transport inprocess` for test/recovery fallback paths
- `--transport mcp` remains available for explicitness

---

## Configuration

### Policy (`config/agentic/orchestrator/policy.yaml`)

Current defaults include:

- plan and allowed-area patch enforcement enabled
- collision policy `reject`
- lock resources: `openapi`, `events`, `db_migrations`, `protected:libs/core`
- lock acquisition behavior: wait + backoff, lease TTL `300s`
- default execution timeout `600s`
- coverage minimums `line>=0.90`, `branch>=0.90`
- coverage targets `line=1.00`, `branch=1.00`
- implementation constraints: `workspace=nx`, `framework=vitest`
- merge requires explicit user approval token
- supervisor iteration loop is policy-configurable via `supervisor.max_iterations_per_phase` (default `6`)
- `budget.per_feature_limit_usd` (default `50.00`) and `budget.alert_threshold` (default `0.8`) for cost enforcement
- `reactions` config: per-event retry rules (`gate_failed`, `agent_stuck`, `collision_detected`, `ready_to_merge`, `changes_requested`)
- `issue_tracker` config: provider (`github`/`linear`/`jira`), credentials, and field mapping
- `cleanup.auto_after_merge` / `cleanup.grace_period_seconds`: automatic merged-artifact removal

### Gates (`config/agentic/orchestrator/gates.yaml`)

Default profile modes:

- `fast` — supports `{base_branch}` / `{feature_id}` interpolation for incremental runs
- `full`
- `merge`

Gate steps support `parallel_group` and `depends_on` fields for parallel execution waves. Steps within the same `parallel_group` run concurrently via `Promise.allSettled()`.

Coverage parser:

- `lcov` from `coverage/control-plane/lcov.info`

### Agents (`config/agentic/orchestrator/agents.yaml`)

- role-specific system prompt paths
- default provider/model values with optional `runtime.provider_config_env` for API-backed providers
- optional `runtime.provider_configs.<provider>` objects for provider-specific payloads (for example `kiro-cli chat --agent dev`)
- optional `runtime.role_provider_overrides.<role>` to pin a smaller/larger model per phase (planner/builder/qa) without changing global defaults
- `runtime.execution_mode` default (`deterministic|interactive`) plus `runtime.interactive.*` checkpoint/watchdog controls (`checkpoint_interval_ms`, `watchdog_poll_interval_ms`, `max_uncommitted_changes`, `validation_on_checkpoint`, `revert_on_violation`, `violation_severity`)
- `worktree.post_create` commands and `worktree.symlinks` for workspace hook automation
- stack-specific examples: [`example-configurations/node/`](example-configurations/node) and [`example-configurations/java/`](example-configurations/java)

Interactive mode example:

```yaml
runtime:
  execution_mode: interactive
  interactive:
    checkpoint_interval_ms: 30000
    watchdog_poll_interval_ms: 2000
    max_uncommitted_changes: 50
    validation_on_checkpoint: true
    revert_on_violation: false
    violation_severity: warning
```

Per-phase model override example:

```yaml
runtime:
  role_provider_overrides:
    planner:
      model: gpt-4o-mini
    builder:
      model: gpt-4o
    qa:
      model: gpt-4o-mini
```

### Multi-Project (`config/agentic/orchestrator/multi-project.yaml`)

Optional. Defines multiple independent projects in one repository. Pass `--project <name>` on the CLI to scope commands to a project. `aop status --all` aggregates across all projects. Each project can override `policy` and `gates` paths.

### Adapter Registry (`config/agentic/orchestrator/adapters.yaml`)

Optional. Registers custom adapters for `notification-channel`, `activity-detector`, and `scm-provider` slots. Resolves at kernel/supervisor boot.

### Example configuration bundles

- overview: [`example-configurations/README.md`](example-configurations/README.md)
- Node.js bundle: [`example-configurations/node/`](example-configurations/node)
- Java (Maven) bundle: [`example-configurations/java/`](example-configurations/java)
- note: `policy.yaml` `implementation.workspace` and `testing.framework` are control-plane schema invariants; language-specific test execution lives in each bundle's `gates.yaml`.

---

## Required Schemas

This section defines the schema-governed files the target repository must contain or will be expected to produce at runtime.

### Who provides what

Files you provide/configure:

- `config/agentic/orchestrator/policy.yaml`
- `config/agentic/orchestrator/gates.yaml`
- `config/agentic/orchestrator/agents.yaml` (recommended; if present it is schema validated)
- `.aop/features/<feature_id>/spec.md` (input spec per feature)

Files the runtime creates/maintains:

- `.aop/features/index.json`
- `.aop/features/<feature_id>/state.md`
- `.aop/features/<feature_id>/plan.json`
- `.aop/features/<feature_id>/qa_test_index.json`
- `.aop/features/<feature_id>/checkpoints/*.diff` (interactive-mode checkpoint audit snapshots)
- `.aop/features/<feature_id>/logs/*`
- `.aop/features/<feature_id>/evidence/*`

### Schema mapping

| Runtime file                                       | Schema file                                              | Required/expected essentials                                                                                                                                                                                                       |
| -------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `.aop/features/<feature_id>/plan.json`             | `agentic/orchestrator/schemas/plan.schema.json`          | `feature_id`, `plan_version`, `summary`, `allowed_areas`, `forbidden_areas`, `base_ref`, `files.{create,modify,delete}`, `contracts.{openapi,events,db}`, `acceptance_criteria`, optional `gate_targets` (planner intent)          |
| `.aop/features/<feature_id>/state.md` front matter | `agentic/orchestrator/schemas/state.schema.json`         | `feature_id`, `version`, `branch`, `worktree_path`, `status`, `gate_profile`, `gates`, `locks.held`, `collisions`, `cluster`, `role_status`, `last_updated`, optional `execution_mode` override and `checkpoints[]` audit metadata |
| `.aop/features/index.json`                         | `agentic/orchestrator/schemas/index.schema.json`         | `version`, `active`, `blocked`, `merged`, `locks`, `lock_leases`, `blocked_queue`, `runtime_sessions.{run_id,orchestrator_session_id,owner_instance_id,lease_expires_at,feature_sessions}`                                         |
| `config/agentic/orchestrator/gates.yaml`           | `agentic/orchestrator/schemas/gates.schema.json`         | `version`, `profiles.<profile>.modes.<mode>[{name,cmd,...}]`, optional parser/threshold metadata                                                                                                                                   |
| `config/agentic/orchestrator/policy.yaml`          | `agentic/orchestrator/schemas/policy.schema.json`        | commit/merge policy, patch policy, lock config, collision policy, gate selection defaults/healing toggles, path rules, execution policy, RBAC, Nx/Vitest implementation constraints                                                |
| `config/agentic/orchestrator/agents.yaml`          | `agentic/orchestrator/schemas/agents.schema.json`        | `version`, `roles`, `missing_prompt_behavior`, optional runtime defaults                                                                                                                                                           |
| `.aop/features/<feature_id>/qa_test_index.json`    | `agentic/orchestrator/schemas/qa_test_index.schema.json` | `feature_id`, `version`, `source_diff_ref`, `items[]` with path/hunks/required_tests/status                                                                                                                                        |

### Important operational notes

- `state.md`, `index.json`, `plan.json`, and `qa_test_index.json` are not just data files; they are part of the runtime contract and are versioned/validated.
- mutating operations are optimistic-concurrency guarded (`expected_version`/`expected_plan_version` semantics).
- schema failures are blocked and returned as structured errors.

---

## Branches, Worktrees, and Review Before Merge

This runtime uses **feature branches + git worktrees**, not GitHub/GitLab fork automation.

- A feature flow creates/uses branch `<feature_id>`
- It creates worktree `.worktrees/<feature_id>`
- Changes are visible on host filesystem before merge
- Merge is never implicit on gate pass; it requires explicit promotion via `feature.ready_to_merge` after approval

### What gets created

For feature `my_feature`:

- branch: `my_feature`
- worktree path: `.worktrees/my_feature`

Base branch used for cut is configured in `policy.yaml` (`worktree.base_branch`, currently `main`).

`repo.reconcile_mainline` reconciles against the committed base-branch ref, not against uncommitted changes in your local working tree. If you want local fixes to be consumed automatically by reconciliation, commit them onto the base branch first or apply them directly in the feature worktree.

### Manual review workflow (recommended)

1. Inspect working changes in the feature worktree:
   ```bash
   git -C .worktrees/my_feature status
   git -C .worktrees/my_feature diff --stat
   git -C .worktrees/my_feature diff
   ```
2. Inspect commit history for the feature branch:
   ```bash
   git log --oneline --decorate main..my_feature
   ```
3. Compare branch delta against base:
   ```bash
   git diff --name-status main...my_feature
   git diff main...my_feature
   ```
4. Inspect runtime evidence and logs:
   ```bash
   ls -la .aop/features/my_feature/evidence
   ls -la .aop/features/my_feature/logs
   ```
5. Only after review/approval, allow merge promotion (`feature.ready_to_merge` path).

### If you want remote forks anyway

The runtime does not create remote forks automatically. If your workflow requires forks, push feature branches manually to your fork remote.

---

## Deterministic Tool Surface (Detailed Definitions)

Defined in [agentic/orchestrator/tools.md](agentic/orchestrator/tools.md).

All failures return structured error payloads with stable error codes.

### MCP contract artifacts

- `agentic/orchestrator/tools/catalog.json`: canonical tool list (33 tools), roles, handler bindings, mutating/idempotency requirements, and schema refs.
- `agentic/orchestrator/tools/protocol.json`: pinned MCP protocol + SDK metadata and required transports.
- `agentic/orchestrator/tools/errors.schema.json`: normalized error envelope contract.
- `agentic/orchestrator/tools/schemas/input/*.schema.json`: per-tool request schemas.
- `agentic/orchestrator/tools/schemas/output/*.schema.json`: per-tool success payload schemas.

Validation workflow:

```bash
npm run validate:mcp-contracts
npm run validate:architecture
```

The MCP contracts validator checks: protocol pinning, `catalog.json`/`tools.md`/schema parity, mutating-tool cross-check against `TOOL_BEHAVIOR_METADATA`, AJV schema compilation (draft-07 and 2020-12), orphan schema detection, and `supported_roles` validation. The architecture validator enforces layer dependency rules across 93 classified source files.

### Tool definitions

| Tool                         | Purpose                                                                | Mutates state/files | Typical caller role(s)                 |
| ---------------------------- | ---------------------------------------------------------------------- | ------------------- | -------------------------------------- |
| `feature.discover_specs`     | Discover canonical `spec.md` files under `.aop/features/*`             | No                  | orchestrator, system                   |
| `feature.init`               | Initialize feature folder/state and ensure branch/worktree             | Yes                 | orchestrator, system                   |
| `feature.get_context`        | Return spec + state + plan + latest evidence + QA index bundle         | No                  | orchestrator, planner, builder, qa     |
| `feature.state_get`          | Read parsed state front matter/body                                    | No                  | orchestrator/planner/builder/qa/system |
| `feature.state_patch`        | Patch canonical feature state with version guard                       | Yes                 | orchestrator, system                   |
| `feature.log_append`         | Append stamped note to feature decision log                            | Yes                 | orchestrator, system                   |
| `plan.submit`                | Validate and accept initial plan (schema/policy/lock/collision checks) | Yes                 | orchestrator, planner                  |
| `plan.get`                   | Get accepted plan                                                      | No                  | orchestrator, planner, builder, qa     |
| `plan.update`                | Submit versioned plan revision (`+1` version) with full revalidation   | Yes                 | orchestrator, planner                  |
| `repo.ensure_worktree`       | Ensure feature branch + worktree exist                                 | Yes                 | orchestrator, system                   |
| `repo.apply_patch`           | Apply unified diff with plan/policy/path/lock enforcement              | Yes                 | builder, qa, orchestrator              |
| `repo.status`                | Return porcelain status from feature worktree                          | No                  | builder, orchestrator                  |
| `repo.diff`                  | Return git diff for feature worktree                                   | No                  | builder, qa, orchestrator              |
| `repo.read_file`             | Read file content from feature worktree path                           | No                  | planner, builder, qa, orchestrator     |
| `repo.search`                | Repo-safe text search (`rg`) in feature worktree                       | No                  | planner, builder, qa, orchestrator     |
| `repo.diff_bundle`           | Return review bundle (stat/full diff/files/latest gate summary)        | No                  | orchestrator                           |
| `feature.ready_to_merge`     | Commit + merge promotion after required gates and approval checks      | Yes                 | orchestrator, system                   |
| `feature.delete`             | Delete feature runtime artifacts and optional local git/worktree state | Yes                 | orchestrator, system                   |
| `feature.send_message`       | Send a message to the active agent session for a feature               | Yes                 | orchestrator, system                   |
| `gates.list`                 | List available gate profiles/modes                                     | No                  | orchestrator, builder, qa              |
| `gates.run`                  | Execute gate profile/mode, capture logs/evidence, enforce thresholds   | Yes                 | builder, qa, orchestrator              |
| `evidence.latest`            | Return latest evidence summary for feature                             | No                  | qa, orchestrator                       |
| `qa.test_index_get`          | Return QA index + pending obligations summary                          | No                  | qa, orchestrator                       |
| `qa.test_index_update`       | Update QA hunk statuses with version guard and evidence refs           | Yes                 | qa, orchestrator, system               |
| `locks.acquire`              | Acquire/renew resource lease lock for feature                          | Yes                 | orchestrator, system                   |
| `locks.release`              | Release held resource lock                                             | Yes                 | orchestrator, system                   |
| `collisions.scan`            | Compute collision matrix across accepted plans                         | No                  | planner, orchestrator                  |
| `report.dashboard`           | Return global orchestration summary (includes cost and PR metadata)    | No                  | orchestrator                           |
| `report.feature_summary`     | Return per-feature state/diff/evidence summary                         | No                  | orchestrator                           |
| `cost.record`                | Record a cost entry for a feature (token usage, API cost)              | Yes                 | orchestrator, system                   |
| `cost.get`                   | Return accumulated cost for a feature                                  | No                  | orchestrator, system                   |
| `performance.record_outcome` | Record feature outcome (status, retries, duration, cost) for analytics | Yes                 | orchestrator, system                   |
| `performance.get_analytics`  | Return aggregated performance metrics by provider/model                | No                  | orchestrator, system                   |

### Role expectations at a glance

- `planner`: plan-focused, read/search, collision visibility
- `builder`: patch application + fast gate execution
- `qa`: patch/test follow-up + QA index updates + evidence inspection
- `orchestrator`: lifecycle coordination, locks, reporting, merge promotion, and feature cleanup (`delete`)
- `system`: internal automation fallback with broad access

---

## Quality & Testing

## Quality & Testing

- framework: Vitest (`apps/control-plane/vitest.config.ts`)
- coverage output: `coverage/control-plane`
- configured thresholds: lines/branches/functions/statements at `90%` (enforced per-file)
- workspace tooling: Nx targets (`run`, `build`, `test`, `typecheck`)
- Nx launcher: use `npm run nx -- <target>`; this workspace defaults to `NX_DAEMON=false` and `NX_ISOLATE_PLUGINS=false` to avoid Unix-socket worker failures in restricted environments.
- Shell setup for raw `npx nx` commands:
  ```bash
  source scripts/dev-shell-env.sh
  npx nx run control-plane:test
  ```

---

## IntentGraph dependency index

This repository maintains an automatically generated dependency and navigation index produced by **[IntentGraph](https://github.com/Raytracer76/IntentGraph)**. The index exists to help AI agents and contributors understand file relationships, dependency chains, and reverse-dependency paths **without repeatedly scanning the repository by hand**.

### Why this exists

For large or evolving codebases, repeatedly searching the repo to answer questions like:

- What depends on this file or module?
- What imports or calls this?
- What is the dependency path from A to B?
- What files are likely impacted by this change?

...is slow, noisy, and wasteful. The IntentGraph index provides a machine-readable relationship map that should be consulted first for dependency and navigation questions.

### Standard usage policy

Use the IntentGraph index as the **authoritative first-stop source** for repository relationship discovery.

- Consult the index first for dependency-chain and impact-analysis questions.
- Open source files only after the index has narrowed the candidate set.
- Do **not** manually recurse through large portions of the repo just to discover relationships that already exist in the generated index.

### Index location

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

### Install IntentGraph locally

Install IntentGraph locally before attempting to generate or refresh the index.

```bash
pip install intentgraph
```

If your local environment uses a virtual environment, install it inside that environment.

### Generate or refresh the index

Regenerate the index whenever you:

- Add, remove, move, or rename files
- Change imports, exports, module boundaries, or dependency wiring
- Refactor public APIs or shared interfaces
- Make architecture changes that alter call paths or dependency relationships

Example command:

```bash
intentgraph analyze . --output ./docs/core/intentgraph.index.json --level full
```

### Important usage note

Do not paste the entire generated JSON into prompts, comments, or pull request descriptions. Query or inspect only the smallest relevant subset needed for the current task. The point of the index is to reduce unnecessary repo traversal and reduce context waste.

### Staleness policy

If the generated index conflicts with the current repository contents, treat the index as stale. Regenerate it before relying on it for dependency analysis.

---

## Current Status

From [progress.md](spec-files/progress.md):

- Nx + TypeScript + Vitest migration complete
- Kernel + supervisor + CLI implemented end-to-end with 12 commands
- 33 MCP tools registered across 5 roles; all schemas AJV-validated in CI
- Web dashboard (`packages/web-dashboard/`) with SSE stream, Kanban UI, and review/checkout APIs
- Notification system (desktop, Slack, webhook, in-process) with 4-tier priority routing
- Cost tracking and budget enforcement (`cost.json` per feature, `PAUSED_BUDGET` status)
- Agent performance analytics with aggregates by provider/model
- Dependency-aware feature scheduling with circular detection and auto-promotion on merge
- Parallel gate execution with `parallel_group` / `depends_on` wave scheduling
- CI failure auto-remediation (`reactions-service`) with configurable retry and escalation
- PR lifecycle integration with merge scoring and `changes_requested` reaction
- Multi-project support (`multi-project.yaml`, `--project` flag, per-project lease isolation)
- Hash-based multi-instance isolation (SHA256 instance IDs, namespaced run-lease paths)
- Linear and Jira issue tracker adapters with full API-backed status sync
- Architecture boundary checks CI-enforced via `npm run validate:architecture` (93 files, 0 violations)
- Strict linting enforced (`npm run lint`) and build is lint-gated
- `npm run typecheck` passes; `npm test` passes (all per-file coverage ≥ 90%)

Environment note observed during implementation sessions:

- intermittent `npm install` DNS failures (`EAI_AGAIN` to `registry.npmjs.org`) can block full test runs in constrained environments.

---

## Contributing

Contributions are welcome.

Suggested workflow:

1. Create a feature branch (`feature/<name>`)
2. Implement changes with tests
3. Run quality checks:
   ```bash
   npm run typecheck
   npm run build
   npm test
   ```
4. Commit with clear, conventional commit messages
5. Open a pull request with scope, rationale, and verification notes

### Commit Convention

Recommended conventional prefixes:

- `feat:` new feature
- `fix:` bug fix
- `docs:` documentation
- `refactor:` internal structure change
- `test:` tests added/updated
- `chore:` maintenance and tooling

---

## License

MIT © Eric Taurone

See [LICENSE](LICENSE).

---

## Support & Links

- Repository: [Eric-Taurone-Software/Agentic-Orchestrator](https://github.com/Eric-Taurone-Software/Agentic-Orchestrator)
- Author: Eric Taurone
- Specification: [agentic_orchestrator_spec.md](spec-files/agentic_orchestrator_spec.md)
- Implementation log: [progress.md](spec-files/progress.md)
- Example bundles: [example-configurations/README.md](example-configurations/README.md)
- Tool catalog: [agentic/orchestrator/tools.md](agentic/orchestrator/tools.md)
- Policy config: [config/agentic/orchestrator/policy.yaml](config/agentic/orchestrator/policy.yaml)
- Gates config: [config/agentic/orchestrator/gates.yaml](config/agentic/orchestrator/gates.yaml)
- Agents config: [config/agentic/orchestrator/agents.yaml](config/agentic/orchestrator/agents.yaml)
