# Plan Lifecycle — Detailed Reference

## Phase Mechanics

### Action Phase

An Action is a reusable plan template that is project-agnostic until bound via `agents plan use`. The Action phase is unique: it functions primarily as a template from which plans are instantiated. No significant processing occurs here.

**Action properties (YAML config):**

| Field | Required | Default | Description |
|-------|----------|---------|-------------|
| `name` | yes | — | Namespaced identifier (`[[server:]namespace/]name`) |
| `short_description` | no | auto-filled | Brief human-readable summary |
| `long_description` | no | — | Detailed description (recommended for reusable actions) |
| `definition_of_done` | yes | — | Explicit, testable completion criteria |
| `strategy_actor` | yes | — | Actor used for Strategize phase |
| `execution_actor` | yes | — | Actor used for Execute phase |
| `estimation_actor` | no | global default | Optional cost/risk estimator (runs after Strategize) |
| `invariant_actor` | no | global default | Optional Invariant Reconciliation Actor |
| `reusable` | no | `true` | If `false`, action self-deletes after first use |
| `read_only` | no | `false` | If `true`, plan can only use read-only tools |
| `inputs_schema` | no | — | Typed argument declarations with validation rules |
| `automation_profile` | no | global default | Default automation profile for plans from this action |

**States:** `available` | `archived`

### Strategize Phase

The strategy phase is **read-only**. No resource modifications occur. The strategy actor produces a complete decision tree.

What Strategize does:
1. Invokes the Invariant Reconciliation Actor to compute the effective invariant view
2. Records each effective invariant as an `invariant_enforced` decision
3. Gathers context from project resources via ACMS
4. Analyzes dependencies, constraints, and implementation options
5. Produces `strategy_choice`, `resource_selection`, `subplan_spawn`, and `subplan_parallel_spawn` decisions
6. (Optionally) runs the estimation actor for cost/risk estimate

**States:** `queued` | `processing` | `complete` | `errored` | `cancelled`

### Execute Phase

The execution phase carries out the strategy. All work happens in a sandbox.

Four key properties:
1. All modifications happen in an isolated sandbox until Apply
2. Execution actor can spawn child plans (via `subplan_spawn`/`subplan_parallel_spawn`)
3. Checkpointable tools create checkpoints at each decision point
4. Execution decisions are constrained by Strategize decisions

**Important**: CleverAgents does NOT parse LLM output to extract code. LLMs call tools directly (`write_file()`, `edit_file()`, etc.) and tools modify the sandbox state.

**States:** `queued` | `processing` | `complete` | `errored` | `cancelled`

### Apply Phase

Apply merges the sandbox changeset into real project resources. Validation runs during Execute, not Apply — by the time a plan reaches Apply, all validations have already passed.

Apply responsibilities:
- Diff review gate (if automation profile threshold requires human review)
- Conflict resolution (rebase/merge conflicts in git repos)
- Audit log (who applied, what changed, when, why)

**Terminal States:**

| State | Meaning |
|-------|---------|
| `applied` | Changes committed to real resources (success) |
| `constrained` | Cannot complete within current strategy's constraints; may revert to Strategize |
| `errored` | Failed; sandbox intact for inspection/retry |
| `cancelled` | User/system cancelled; sandbox intact |

---

## Phase Reversion Rules

Both Execute and Apply can revert to Strategize. **No other reversion target exists.**

### Execute → Strategize
- **Trigger**: Execution actor finds Strategize constraints too restrictive to proceed
- **What happens**: Plan reverts; strategy actor receives execution actor's findings and produces updated decision tree; plan re-enters Execute with revised strategy
- **Automation**: Controlled by `delete_content` automation profile flag

### Apply → Strategize (via `constrained` terminal state)
- **Trigger**: Changeset cannot be successfully applied within current strategy constraints (merge conflicts violating invariants, validation failures unresolvable within strategy's scope, resource state drift)
- **What happens**: Plan enters `constrained` state; may revert automatically (if `access_network` flag allows) or pause for user decision; strategy actor receives Apply's findings
- **Automation**: Controlled by `access_network` automation profile flag

---

## Decision Tree Storage Schema

```sql
CREATE TABLE decisions (
    decision_id TEXT PRIMARY KEY,  -- ULID
    plan_id TEXT NOT NULL,
    parent_decision_id TEXT,       -- structural tree parent
    sequence_number INTEGER NOT NULL, -- monotonically increasing, never reused
    decision_type TEXT NOT NULL,   -- one of 10 types
    question TEXT,
    chosen_option TEXT NOT NULL,
    alternatives_considered TEXT, -- JSON array
    confidence_score REAL,         -- 0.0–1.0
    rationale TEXT,
    actor_reasoning TEXT,
    context_snapshot TEXT NOT NULL, -- JSON {hot_context_hash, hot_context_ref, actor_state_ref}
    is_correction BOOLEAN DEFAULT FALSE,
    corrects_decision_id TEXT,
    correction_reason TEXT,
    superseded_by TEXT,
    created_at TEXT NOT NULL,
    FOREIGN KEY (plan_id) REFERENCES plans(plan_id),
    FOREIGN KEY (parent_decision_id) REFERENCES decisions(decision_id),
    FOREIGN KEY (corrects_decision_id) REFERENCES decisions(decision_id),
    FOREIGN KEY (superseded_by) REFERENCES decisions(decision_id)
);

-- Influence DAG (many-to-many)
CREATE TABLE decision_dependencies (
    upstream_decision_id TEXT NOT NULL,
    downstream_decision_id TEXT NOT NULL,
    dependency_type TEXT NOT NULL,  -- 'decision', 'plan', 'artifact'
    downstream_ref TEXT NOT NULL,   -- actual ID of decision/plan/artifact
    PRIMARY KEY (upstream_decision_id, downstream_decision_id, downstream_ref)
);

-- Correction history
CREATE TABLE correction_attempts (
    attempt_id TEXT PRIMARY KEY,    -- ULID
    plan_id TEXT NOT NULL,
    original_decision_id TEXT NOT NULL,
    new_decision_id TEXT,
    original_subtree_snapshot TEXT, -- reference to archived state
    correction_reason TEXT,
    status TEXT NOT NULL,           -- 'pending', 'executing', 'completed', 'failed'
    created_at TEXT NOT NULL,
    completed_at TEXT
);
```

---

## Child Plan Execution Modes

### Sequential
Individual `subplan_spawn` decisions without a `subplan_parallel_spawn` wrapper. One child plan must complete before the next begins. If one fails, subsequent plans are NOT started.

### Parallel
Multiple `subplan_spawn` decisions grouped under a `subplan_parallel_spawn` decision. Execute concurrently up to `SubplanConfig.max_parallel` (default: 5, range: 1–50). If one fails, others continue.

### Dependency-Ordered
Respects explicit dependencies between child plans. A topological sort determines execution waves. Independent subplans in each wave run concurrently. If one fails, its dependents are NOT started; independent plans continue.

---

## Child Plan Result Merging

| Resource Type | Merge Strategy |
|---------------|----------------|
| `git-checkout` (code) | Git three-way merge |
| Database | Transaction coordination or sequential application |
| `fs-mount` / `fs-directory` | File-level merge or copy-on-write reconciliation |
| Non-mergeable | Sequential execution required |

---

## Automatic Checkpoint Triggers

Configured via `core.checkpoints.auto_create_on` (default: all four enabled):

| Trigger | When | Component |
|---------|------|-----------|
| `on_tool_write` | Before each write-tool execution | ToolRunner |
| `on_tool_write_complete` | After each write-tool execution | ToolRunner |
| `on_subplan_spawn` | Before first subplan execution attempt | SubplanExecutionService |
| `on_error` | When the Execute phase fails | PlanExecutor |

---

## Plan Identity Fields

| Field | Type | Description |
|-------|------|-------------|
| `plan_id` | ULID | Unique, immutable identifier |
| `parent_plan_id` | ULID? | Nullable; present for child plans |
| `root_plan_id` | ULID | Top-most plan in hierarchy |
| `attempt` | int | Increments on each phase re-run or correction |
| `created_at` | Timestamp | When the plan was created |
| `updated_at` | Timestamp | Last modification time |
| `completed_at` | Timestamp? | When the plan reached a terminal state |
| `created_by` | Identity | User or session identity |
