Files
cleveragents-core/docs/cleveragents-plan-lifecycle.md

12 KiB

CleverAgents Plan Lifecycle: Complete Guide

Overview

The CleverAgents plan system follows a stateful workflow model where plans progress through distinct phases. The core workflow has three primary phases (TELL → BUILD → APPLY) with additional supporting operations.


Plan Status States

Plans transition through these states defined in src/cleveragents/domain/models/core/plan.py:12-20:

Status Description
PENDING Plan created, awaiting build (initial state after TELL)
BUILDING AI is actively generating changes
BUILT Changes generated successfully, ready to apply
APPLIED Changes written to filesystem
ERROR An error occurred during processing
CANCELLED Plan was explicitly cancelled

Primary Workflow Phases

1. TELL Phase

Purpose: Create a new plan with natural language instructions.

Command: agents tell "<prompt>" or agents tell "<prompt>" --name <plan-name>

Activities Performed:

  1. Project Validation - Retrieves current project from ProjectService; fails if no project is initialized
  2. Name Generation - Auto-generates plan name from first 3 words of prompt (e.g., "add error handling" → add_error_handling), or uses custom name if provided
  3. Plan Creation - Creates a Plan object with:
    • status = PENDING
    • project_id linking to current project
    • prompt storing user instructions
    • created_at and updated_at timestamps
  4. Database Persistence - Saves plan via Unit of Work transaction pattern
  5. Current Plan Assignment - Sets this plan as the current plan for the project

Code Location: src/cleveragents/application/services/plan_service.py:289-362

Streaming Mode (--stream): When using --stream, the TELL command also immediately triggers the BUILD phase with real-time progress display through these stages:

  • "Loading context files"
  • "Analyzing requirements"
  • "Generating plan"
  • "Validating plan"

2. BUILD Phase

Purpose: Use AI to generate code changes based on plan instructions.

Command: agents build --actor <name> (requires an actor or a default actor)

Activities Performed:

  1. Plan Retrieval - Gets current plan from database; validates it exists and has a valid ID
  2. Status Update - Updates plan status to BUILDING
  3. Provider Resolution - Resolves AI provider (supports runtime override via CLI flags):
    • Checks for mock provider in testing mode
    • Falls back to injected provider or registry-based lookup
  4. Context Loading - Retrieves all context files associated with the plan from the database
  5. AI Generation - Calls ai_provider.generate_changes() with:
    • Project metadata
    • Plan instructions (prompt)
    • Context files
    • Progress callback for UI updates
  6. Response Processing:
    • Checks for errors in provider response
    • Extracts generated changes, model used, and token count
  7. Change Persistence - Saves all generated Change objects to database
  8. Plan Update - Updates plan with:
    • status = BUILT
    • PlanBuild object containing timestamps, model name, token count

Code Location: src/cleveragents/application/services/plan_service.py:377-477

Internal LangGraph Workflow:

The BUILD phase internally uses a LangGraph workflow (src/cleveragents/agents/graphs/plan_generation.py) with these nodes:

┌─────────────────┐
│  load_context   │  ← Prepares context information, initializes retry_count=0
└────────┬────────┘
         │
         ▼
┌─────────────────────────┐
│ analyze_requirements    │  ← Uses LLM to extract structured requirements from prompt
└────────┬────────────────┘
         │
         ▼
┌─────────────────┐
│ generate_plan   │  ← Uses LLM to generate code changes based on requirements
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│    validate     │  ← Uses LLM to validate generated code for quality/correctness
└────────┬────────┘
         │
    ┌────┴────┐
    │ PASS?   │
    └────┬────┘
   FAIL  │  PASS
  (retry<max)
    │    │
    ▼    ▼
 [loop]  END

Detailed Node Activities:

Node Activities
load_context Initializes state, resets retry counter, clears previous errors
analyze_requirements Formats context summary, invokes LLM with analysis prompt, parses requirements (files to modify, operation type, dependencies, challenges)
generate_plan Creates generation chain, invokes LLM with requirements and context, determines file paths and operation types, creates Change objects
validate Concatenates all generated code, invokes LLM for code review, checks for syntax/logic errors, security issues, best practices

3. APPLY Phase

Purpose: Write AI-generated changes to the filesystem.

Command: agents apply (with optional --yes to skip confirmation)

Activities Performed:

  1. Plan Retrieval - Gets current plan and its pending (unapplied) changes
  2. User Confirmation - Unless --yes flag or testing mode, prompts user to confirm changes
  3. Filesystem Operations - For each change, performs the appropriate operation:
Operation Action
CREATE Creates parent directories (if needed), writes new file
MODIFY Overwrites existing file with new content
DELETE Removes file if it exists
MOVE Renames/moves file to new path
  1. Change Marking - Marks each change as applied=True in database
  2. Plan Finalization - Updates plan with:
    • status = APPLIED
    • PlanResult containing statistics (files_created, files_modified, files_deleted)
    • applied_at timestamp

Code Location: src/cleveragents/application/services/plan_service.py:658-750


Supporting Operations

NEW

Purpose: Create an empty plan without instructions.

Command: agents new <name>

Activities: Creates a plan with placeholder prompt "New plan" and specified name. Useful when you want to add instructions incrementally.

Code Location: src/cleveragents/application/services/plan_service.py:364-375


CONTINUE

Purpose: Add more instructions to an existing plan.

Command: agents continue "<additional prompt>"

Activities:

  1. Retrieves current plan
  2. Appends new instructions to existing prompt (separated by double newline)
  3. Resets status to PENDING (allows re-building)
  4. Updates timestamp

Code Location: src/cleveragents/application/services/plan_service.py:815-852


CD (Switch)

Purpose: Switch to a different plan.

Command: agents cd <plan-name>

Activities:

  1. Looks up plan by name in current project
  2. Sets it as the current plan
  3. Returns the switched-to plan

Code Location: src/cleveragents/application/services/plan_service.py:782-813


LIST

Purpose: List all plans in the current project.

Command: agents list

Activities: Retrieves and displays all plans with their name, status, creation date, and current marker.


CURRENT

Purpose: View the current active plan.

Command: agents current

Activities: Retrieves and displays current plan details including name, status, creation time, and prompt preview.


CLEAR (Context)

Purpose: Clear all context files from the current plan.

Command: agents context clear

Activities: Removes all context file associations from the current plan.

Code Location: src/cleveragents/application/services/context_service.py:309+


ADD (Context)

Purpose: Add files to the plan's context.

Command: agents context add <path> (with optional --recursive)

Activities:

  1. Resolves file paths (supports directories with recursive option)
  2. Reads file content
  3. Creates Context objects with path, content, type classification
  4. Associates contexts with current plan

Code Location: src/cleveragents/application/services/context_service.py:88-163


State Transitions Diagram

                        ┌─────────────┐
                        │   START     │
                        └──────┬──────┘
                               │
               agents new      │     agents tell
               (empty plan)    │     (with prompt)
                    ┌──────────┴──────────┐
                    ▼                      ▼
             ┌─────────────┐        ┌─────────────┐
             │   PENDING   │◄───────│   PENDING   │
             └──────┬──────┘        └──────┬──────┘
                    │                      │
                    │    agents continue   │
                    │◄─────────────────────┤
                    │                      │
                    │        agents build  │
                    ├──────────────────────┘
                    ▼
             ┌─────────────┐
             │  BUILDING   │
             └──────┬──────┘
                    │
           success  │  error
              ┌─────┴─────┐
              ▼           ▼
       ┌─────────────┐  ┌─────────────┐
       │    BUILT    │  │    ERROR    │
       └──────┬──────┘  └─────────────┘
              │
              │ agents continue → back to PENDING
              │
              │ agents apply
              ▼
       ┌─────────────┐
       │   APPLIED   │
       └─────────────┘

Auto-Debug Feature

When enabled, failed builds can automatically retry with debugging:

Code Location: src/cleveragents/application/services/plan_service.py:479-636

Workflow:

  1. Build attempt fails
  2. AutoDebugAgent analyzes the error
  3. Agent generates a fix suggestion
  4. Fix is appended to plan prompt
  5. Build is retried (up to auto_debug_tries times)
  6. Each attempt is logged as a DebugAttempt in the database

Configuration Options

Plans can be configured via PlanConfig (src/cleveragents/domain/models/planconfig/plan_config.py):

Option Description
auto_mode Automation level (manual/auto/guided)
auto_continue Automatically continue after completion
auto_build Automatically build after tell
auto_apply Automatically apply after build
auto_commit Automatically git commit after apply
auto_debug Enable auto-debugging on failures
auto_debug_tries Max debug retry attempts
auto_revert_on_rewind Revert filesystem changes on rewind
smart_context Enable intelligent context selection
auto_context Automatically update context

Summary: Typical Workflow

# 1. Initialize project (one-time)
agents init

# 2. Add relevant files to context
agents context add src/myfile.py
agents context add src/utils/

# 3. Create plan with instructions (TELL)
agents tell "Add comprehensive error handling to the API endpoints"

# 4. Generate code changes (BUILD)
agents build

# 5. Review and apply changes (APPLY)
agents apply

# Optional: Add more instructions and rebuild
agents continue "Also add logging for errors"
agents build
agents apply