# Missions

Missions are an orchestration layer above workflows. A mission decomposes a goal (from a spec or a prompt) into a structured plan of items, manages their dependencies and execution, and tracks every change as an auditable revision.

## Key Concepts

- **Mission session** — a named plan with lifecycle status, source provenance, and referenced artifacts
- **Mission item** — a work unit with status, priority, adapter binding, lane, concurrency group, and hold state
- **Dependency** — an edge between items: item B depends on item A completing before it becomes eligible
- **Execution** — an attempt to run an item through an adapter (workflow, noop, or future backends)
- **Revision** — a snapshot of every plan mutation with the operations applied and the artifacts that informed the decision
- **Event** — a runtime event (launch, completion, failure, hold) for observability

## Architecture

```
Spec or Prompt
    │
    ▼
Mission Compiler  ──→  CompiledPlan / CompiledPatch
    │
    ▼
Mission Storage   ──→  Sessions, Items, Dependencies, Revisions
    │
    ▼
Mission Scheduler ──→  Evaluates eligibility, launches via adapters
    │
    ▼
Adapters          ──→  NoopAdapter (instant), WorkflowAdapter (enqueue)
```

The **scheduler** is the only launch authority. Tools and CLI commands mutate state; the scheduler reacts by evaluating eligibility and launching items through adapters.

In supported runtime paths:

- the web/app runtime starts the mission scheduler automatically. For workflow-backed missions, set `workflow.executor_enabled: true` in config so the executor can dispatch enqueued runs
- local CLI-first execution uses `aroom mission scheduler`

## CLI Commands

### Create a mission from a spec

```bash
aroom mission create --spec @ns/spec/auth --adapter workflow --workflow-path defs/build.yaml
aroom mission create --spec @ns/spec/auth --profile parallel-review
```

This compiles the spec's approved tasks into mission items, previews the plan, and asks for confirmation before launching. Use `--launch` to skip confirmation. Use `--profile` to apply an execution profile that auto-selects adapters and configures lanes (see [Execution Profiles](#execution-profiles) below).

### Create a mission from a prompt

```bash
aroom mission create --prompt "Build the authentication module with login, signup, and password reset"
aroom mission create --prompt "Build auth module" --profile plan-then-execute
```

Uses the AI service to decompose the prompt into structured items. `--profile` applies execution preferences to the compiled plan.

### List missions

```bash
aroom mission list
aroom mission list --status active
```

### Show mission status

```bash
aroom mission status <session_id>
```

Shows items, progress, blockers, lanes, and referenced artifacts.

### Run the scheduler

```bash
aroom mission scheduler
aroom mission scheduler --once
```

Use this when you are running missions from the CLI without the web app. The command hosts the mission scheduler in the foreground and, for workflow-backed items, also co-hosts the workflow executor so enqueued workflow runs can start locally. Use `--once` for tests and scripts.

### Steer a mission conversationally

```bash
aroom mission talk <session_id>
```

Launches an interactive chat session with mission tools registered. You can:

- Ask about blockers: "Why is the deploy task blocked?"
- Add items: "Add a database migration task before the deploy"
- Hold items: "Hold the deploy task until I verify staging"
- Reprioritize: "Make the security audit highest priority"
- Drop items: "Drop the optional caching task"

### Update a plan

```bash
aroom mission update <session_id> --instruction "Split the backend task into API and database layers"
```

Compiles a structured patch from the instruction, previews the operations, and asks for confirmation. Use `--force` to apply operations targeting active items.

### View revision history

```bash
aroom mission revisions <session_id>
```

Shows every plan mutation with operation types, reasons, and the artifact references that informed each revision.

### Retry a failed item

```bash
aroom mission retry <item_id>
```

Resets a failed item to `pending` so the scheduler re-launches it on its next cycle. Only items in `failed` status can be retried. The `item_id` accepts unique ID prefixes — use the 8-character prefix shown by `mission status` and `observe`.

### Replace a running item

```bash
aroom mission replace <item_id>
```

Cancels the latest execution via the adapter and resets the item to `pending` for re-launch. Use this when an active execution is stuck or producing incorrect results. The command fails closed: if the adapter cannot confirm cancellation, the replacement is aborted to prevent duplicate concurrent executions. The `item_id` accepts unique ID prefixes.

### Cancel a mission

```bash
aroom mission cancel <session_id>
```

### Reconcile an item

**Automatic reconciliation.** For workflow-backed items with a linked GitHub issue, the scheduler automatically checks external reality before finalizing a failed item. If the GitHub issue is closed, the item is reconciled to `completed` with an `item_reconciled` event recording the evidence. When merged closing PRs are detected (via GitHub's `closedByPullRequestsReferences`), their numbers are included in the reason string (e.g. `"Issue #42 closed; merged closing PR(s): #85"`). No operator action is needed.

The issue-closed state is the sole decision signal. A merged PR alone does not trigger auto-reconciliation — the issue must also be closed. This is intentional: an issue with a merged PR that remains open may have been reopened for further work.

| External state | Auto-reconciled? | Operator action |
|---|---|---|
| GitHub issue closed | Yes | None — scheduler handles it |
| GitHub issue closed with merged PR | Yes (PR numbers in reason) | None — scheduler handles it |
| GitHub PR merged but issue still open | No | `aroom mission reconcile` (or close the issue) |
| Work done outside GitHub (manual deploy, external CI) | No | `aroom mission reconcile` |
| Noop-adapter item completed externally | No | `aroom mission reconcile` |
| Workflow item without `issue_number` in inputs | No | `aroom mission reconcile` |

**Manual reconciliation.** When work completes outside the tracked child run and automatic reconciliation does not apply (noop-adapter items, workflow items without a linked issue number, non-GitHub external completions), use `reconcile` to mark the item done and record why:

```bash
aroom mission reconcile <session_id> <item_id> --reason "Completed manually via CI pipeline"
aroom mission reconcile <session_id> <item_id> --status completed --reason "PR merged externally"
```

The command validates that the item is in an `active`, `failed`, or `blocked` state. If the item has a live execution (pending or running), reconcile **fails closed** to prevent silently discarding in-flight work. Pass `--force` to cancel the live execution via the adapter before reconciling:

```bash
aroom mission reconcile <session_id> <item_id> --force --reason "Superseded by hotfix deployed manually"
```

An `item_reconciled` event is emitted for audit trail visibility. The `item_id` accepts unique ID prefixes, scoped to the given session.

### Diagnose blockers

Show a concise per-item blocker summary for a mission. For items backed by a workflow run, delegates to the workflow diagnosis engine. For dependency-only blockers, lists the incomplete upstream items. Also shows which downstream items are blocked by each item.

```bash
aroom mission why <session_id>
```

Example output:

```
Eligible: abc12345 Set up environment — ready to run
Blocked: def67890 Run tests — waiting on: Set up environment (pending)
  Blocking: Deploy
```

### Summary and retrospective

Show a full retrospective for a completed, failed, or cancelled mission:

```bash
aroom mission summary <session_id>
```

Show a delta summary of events since a given timestamp:

```bash
aroom mission summary <session_id> --since 2025-03-28T10:00:00
```

The observe command also supports these flags:

```bash
aroom observe <session_id> --summary
aroom observe <session_id> --since 2025-03-28T10:00:00
```

Retrospectives are automatically generated when a mission reaches a terminal state:
- **Completed** sessions get a final retrospective stored as a `session_retrospective` event
- **Failed** sessions get a draft retrospective (`session_retrospective_draft`) that is superseded if the session recovers
- **Cancelled** sessions get a final retrospective at cancel time

## REPL Commands

Inside `aroom chat`, use `/mission` for quick access:

| Command | Description |
|---------|-------------|
| `/mission list` | List mission sessions |
| `/mission status <id>` | Show mission details |
| `/mission talk <id>` | Register mission tools in the current session |

After `/mission talk <id>`, all 10 mission tools become available to the AI for conversational steering.

## Adapters

Missions use adapters to execute items:

| Adapter | Behavior |
|---------|----------|
| `noop` | Instantly completes. For tracked work not executed by Anteroom. |
| `workflow` | Enqueues a workflow run. Scheduler polls until completion. |

Specify the adapter when creating a mission:

```bash
aroom mission create --spec @ns/spec/auth --adapter workflow --workflow-path defs/build.yaml
aroom mission create --spec @ns/spec/auth --profile hands-off
```

When using `--profile`, the compiler discovers available workflows, scores them against the profile's preferences, and auto-selects the best fit. Explicit `--adapter`/`--workflow-path` flags override profile-derived bindings.

## Execution Profiles

An execution profile captures reusable execution preferences — plan-first, parallel lanes, review gates, runner preferences — and translates them into concrete adapter bindings at compile time. Profiles bridge the gap between user intent ("work in parallel with review on each item") and the mission's item-level adapter/lane/dependency configuration.

### Built-in Profiles

| Profile | Description |
|---------|-------------|
| `default` | No special preferences; noop adapter, single lane |
| `plan-then-execute` | Adds a planning phase; execution items depend on planning completing first |
| `parallel-review` | Parallel lanes (limit 3) with review gate items after each work item; prefers `cli_claude` workflows |
| `hands-off` | Parallel execution (limit 3) with hold-on-failure escalation; prefers `cli_claude` workflows |

### How Binding Selection Works

When `--profile` is specified:

1. The compiler discovers all available workflow definitions (built-in + examples)
2. Each workflow is scored against the profile's preferences:
   - **Runner match** (40%): does the workflow use the profile's preferred runners?
   - **Input match** (30%): does the workflow accept the profile's required inputs?
   - **Tag match** (20%): do the workflow's tags match the profile?
   - **Structure match** (10%): does the workflow have gates/parallel steps matching the profile?
3. The highest-scoring workflow above the threshold (0.3) is selected
4. Items still on the `noop` adapter are bound to the matched workflow
5. If no workflow matches, items fall back to the profile's default adapter

Each item records a `_binding_reason` in its adapter config explaining why it was bound to a specific adapter — visible in the plan preview table.

### Precedence

Explicit CLI flags override profile-derived values:

- `--adapter workflow --workflow-path defs/build.yaml` always wins over profile selection
- `--profile` is applied after `--adapter` defaults, so items already bound by `--adapter` are not overridden

## Stale Child Run Recovery

When a workflow-backed mission item's child run has its heartbeat expire (worker crash), the workflow engine automatically reclaims the stale lock and marks the run failed or paused. The mission scheduler detects this during its poll cycle by checking the adapter status summary for `stale_heartbeat` markers and emits an `item_stale_recovered` event. The item remains in its current state for the next scheduler pass to reconcile.

## Further Reading

- [Best Practices](best-practices.md) — sizing items, adapter selection, workflow shapes, monitoring, and failure recovery patterns from real mission usage

## V1 Limitations

- Mission is CLI-first. Web UI mission steering will come in a future release.
- `aroom mission talk` launches a chat session; full inline steering TUI is planned.
- Lane and concurrency limits are enforced by the scheduler, not configurable per-session yet.
