---
name: cleveragents-spec
description: |
  Complete specification skill for CleverAgents — covering every architectural
  concept, entity, workflow, CLI command, and design decision from
  docs/specification/. This skill explains WHAT the system is intended to
  build, and HOW all its parts fit together.

  Use this skill whenever you need to know: what a Plan is and how its four
  phases work, what a Decision is and what types exist, how Invariants work
  and their precedence rules, what an Actor is and how to configure one, what
  a Tool is and its four lifecycle stages, what a Validation is and how it
  differs from a plain Tool, what a Skill is and how tools compose into one,
  what a Resource is and how the DAG and resource type system work, what a
  Project is and how it links to resources, what an Automation Profile is and
  when to use each of the 8 built-in ones, how plan correction works (revert
  vs append), how the A2A protocol bridges all clients to the Application
  layer, what the 4-layer architecture is, what the ACMS context management
  system does, which milestone deliverables are current, and any other
  architectural or design question about the CleverAgents system.

  Covers: platform overview and value proposition, 4-phase plan lifecycle
  (Action → Strategize → Execute → Apply) with phase reversion rules, decision
  tree model (10 decision types, dual structural tree + influence DAG, context
  snapshots), decision correction (revert vs append, affected subtree
  computation, mid-Strategize vs mid-Execute correction), invariant system
  (4 scopes: global/project/action/plan; precedence plan > action > project >
  global; Invariant Reconciliation Actor; non-overridable global invariants;
  child plan inheritance), automation profiles (8 built-in profiles: manual
  through full-auto; 11 automatable task flags; confidence thresholds; Safety
  Profile sub-model; Automation Guard sub-model; Semantic Escalation), actors
  (LLM vs graph types; YAML configuration with Jinja2 + env-var preprocessing;
  hierarchical composition; specialized roles: strategy/execution/estimation/
  invariant-reconciliation), tools (atomic execution unit; 4 sources: custom/
  MCP/agent_skill/builtin; resource bindings and slots; 4-stage lifecycle;
  anonymous tools; metadata overrides; Validation subtype), skills (namespaced
  collections; named tool references; anonymous tools; skill inclusion; MCP
  and Agent Skills integration), projects (resource linking; context config;
  execution environment; multi-project operations), resources (ULID-identified;
  physical vs virtual; 34+ built-in types; DAG parent/child; resource type
  inheritance; devcontainer auto-discovery; 6-level execution environment
  routing), namespaces (local/ vs username/ vs orgname/; server-qualified
  format), ACMS (Universal Knowledge Ontology; Context Request Protocol;
  pluggable strategies; Context Assembly Pipeline; hot/warm/cold tiers;
  skeleton compression), A2A protocol (JSON-RPC 2.0; local=stdio vs
  server=HTTP; extension methods; streaming SSE; authentication; error codes),
  4-layer architecture (Presentation/Application/Domain/Infrastructure;
  DI container; Pydantic v2 data validation; SQLite/PostgreSQL persistence;
  LangGraph/LangChain runtime; Tantivy/FAISS/Neo4j indexing), complete CLI
  command reference (agents plan/session/project/actor/skill/tool/resource/
  action/invariant/automation-profile/validation/lsp/config), 6 output
  formats (rich/color/table/plain/json/yaml), milestone plan (v3.0.0 closed
  through v3.8.0 in progress).
references:
  - plan-lifecycle
  - entities
  - cli-commands
  - architecture
  - automation-profiles
  - resources
  - actors-tools-skills
  - acms
  - milestones
---

# CleverAgents Specification Skill

> **This skill covers WHAT CleverAgents is designed to be.** For HOW to contribute
> code to it (testing, nox, CI, branch naming), use the `cleveragents-contributing`
> skill. For company-wide policies and process, use `cleverthis-guidelines`.
>
> **Source of truth**: `docs/specification/` (see `docs/specification/index.md`). When implementation and this skill
> disagree, the specification is authoritative. Align code to spec, not vice versa.

---

## ⚡ Quick Concept Reference

| Concept | Identity | Created via | Short description |
|---------|----------|------------|-------------------|
| Plan | ULID | `agents plan use` | Unit of orchestration; progresses through 4 phases |
| Action | namespaced name | `agents action create` | Reusable plan template; project-agnostic |
| Decision | ULID | `record_decision` tool (auto) | A persisted choice point in the plan's decision tree |
| Invariant | ULID (attachment) | `agents invariant add` | Natural-language constraint; 4 scopes |
| Project | namespaced name | `agents project create` | Named scope linking resources |
| Resource | ULID | `agents resource add` | Anything readable/writable/queryable |
| Resource Type | name (built-in) or namespaced | `agents resource type add` | Schema-level definition constraining a resource category |
| Actor | namespaced name | `agents actor add --config` | Conversational unit (LLM or graph) |
| Tool | namespaced name | `agents tool add --config` | Atomic callable operation |
| Validation | namespaced name | `agents validation add` | Read-only Tool subtype with pass/fail semantics |
| Skill | namespaced name | `agents skill add --config` | Named collection of tools |
| Session | stable ID | `agents session create` | Persistent conversation thread |
| Automation Profile | namespaced name (or built-in) | `agents automation-profile add` | Named confidence thresholds controlling autonomy |

**Identity rules:**
- **ULID**: Plans, decisions, resources, correction attempts, validation attachments, checkpoints
- **Namespaced name** (`[[server:]namespace/]name`): Projects, actions, actors, tools, skills, resource types, automation profiles
- **`local/`** = this machine only; **`<username>/`** = personal server namespace; **`<orgname>/`** = org server namespace

---

## 🧭 Master Decision Trees

### "What am I working on or implementing?"

```
What concept or feature am I working on?
│
├─ Plan lifecycle (phases, states, decision tree)
│   └─ → "What is a Plan?" tree
│
├─ Starting a plan (action → use → execute → apply)
│   └─ → "How does a plan run?" tree
│
├─ Decisions (recording, types, correction)
│   └─ → "What is a Decision?" tree
│
├─ Plan correction (revert or append)
│   └─ → "How do I correct a plan?" tree
│
├─ Invariants (scopes, precedence, reconciliation)
│   └─ → "What is an Invariant?" tree
│
├─ Actors (LLM vs graph, YAML config, roles)
│   └─ → "What is an Actor?" tree
│
├─ Tools (definition, sources, lifecycle, bindings)
│   └─ → "What is a Tool?" tree
│
├─ Validations (vs tools, modes, attachment)
│   └─ → "What is a Validation?" tree
│
├─ Skills (composition, anonymous tools, includes)
│   └─ → "What is a Skill?" tree
│
├─ Resources (types, DAG, physical vs virtual)
│   └─ → "What is a Resource?" tree
│
├─ Projects (linking resources, context, multi-project)
│   └─ → "What is a Project?" tree
│
├─ Automation Profiles (which to use, thresholds)
│   └─ → "Which automation profile applies?" tree
│
├─ Namespaces and naming
│   └─ → "How does naming work?" tree
│
├─ CLI commands
│   └─ → "Which CLI command do I use?" tree
│
├─ Architecture (layers, A2A, DI, tech stack)
│   └─ → "What is the architecture?" tree
│
├─ ACMS and context management
│   └─ → "What is the ACMS?" tree
│
└─ Milestones (current status, deliverables)
    └─ → "Which milestone am I in?" tree
```

---

## 🔄 Concept Decision Trees

### "What is a Plan?"

```
A Plan is the fundamental unit of orchestration and traceability:
│
├─ IDENTITY
│   ├─ plan_id: ULID (unique, immutable)
│   ├─ parent_plan_id: ULID? (null for root plans)
│   ├─ root_plan_id: ULID (top-most plan in hierarchy)
│   ├─ attempt: int (increments on each correction/re-run)
│   └─ Top-level plans carry a namespaced name; child plans use plan_id only
│
├─ THE FOUR PHASES  (Action → Strategize → Execute → Apply)
│   │
│   ├─ ACTION PHASE
│   │   ├─ The plan is actually an Action (a reusable template)
│   │   ├─ No significant processing occurs here
│   │   ├─ Action is project-agnostic until bound via `agents plan use`
│   │   └─ States: available | archived
│   │
│   ├─ STRATEGIZE PHASE  (first phase with active processing)
│   │   ├─ Read-only — no resource modifications
│   │   ├─ Strategy actor gathers context from project resources
│   │   ├─ Invariant Reconciliation Actor resolves all applicable invariants
│   │   │   → Records each as invariant_enforced decision
│   │   ├─ Produces decision tree: strategy_choice, resource_selection,
│   │   │   subplan_spawn, subplan_parallel_spawn decisions
│   │   └─ States: queued | processing | complete | errored | cancelled
│   │
│   ├─ EXECUTE PHASE
│   │   ├─ Work happens in a sandbox (isolated from real resources)
│   │   ├─ Execution actor carries out strategy decisions
│   │   ├─ May spawn child plans (subplan_spawn or subplan_parallel_spawn)
│   │   ├─ LLMs call tools directly; tools modify sandbox state
│   │   │   ⚠️ CleverAgents does NOT parse LLM output — tools do the writing
│   │   ├─ Checkpointable tools create checkpoint groups at each decision
│   │   ├─ Execution decisions are constrained by Strategize decisions
│   │   │   → If constraints too restrictive → REVERT TO STRATEGIZE
│   │   └─ States: queued | processing | complete | errored | cancelled
│   │
│   └─ APPLY PHASE  (final phase)
│       ├─ Merges sandbox changeset into REAL project resources
│       ├─ Diff review gate: user sees changed files, diff, risk warnings
│       ├─ Validation runs during Execute, NOT Apply (Apply commits only)
│       └─ Terminal states:
│           ├─ applied → changes committed to real resources (success)
│           ├─ constrained → cannot complete; may revert to Strategize
│           ├─ errored → failed; sandbox intact for inspection/retry
│           └─ cancelled → user/system cancelled; sandbox intact
│
├─ PHASE TRANSITION VERBS (the public CLI contract)
│   ├─ create → Action phase
│   ├─ use    → Strategize phase  (no "strategize" command — by design)
│   ├─ execute → Execute phase
│   └─ apply  → Apply phase
│   ⚠️ There is NO `strategize` command. `use` describes the user's intent.
│
├─ PHASE REVERSION (both go to Strategize — the only reversion target)
│   ├─ Execute → Strategize
│   │   ├─ When: execution actor finds Strategize constraints too restrictive
│   │   ├─ Process: strategy actor receives findings, produces updated tree
│   │   └─ Controlled by: delete_content automation profile flag
│   └─ Apply → Strategize (via constrained terminal state)
│       ├─ When: changeset cannot be applied within current strategy constraints
│       ├─ Triggers: merge conflicts violating invariants, validation failures,
│       │   resource state drift contradicting strategy assumptions
│       └─ Controlled by: access_network automation profile flag
│
├─ PLAN HIERARCHY
│   ├─ Child plan = Plan with a parent_plan_id (identical data model)
│   ├─ subplan_spawn decisions → created during Strategize, spawned in Execute
│   ├─ subplan_parallel_spawn → spawns a group concurrently (max_parallel: 5 default)
│   ├─ Sequential: one child fails → subsequent children NOT started
│   ├─ Parallel: one child fails → other children continue
│   ├─ Dependency-ordered: topological sort; independent subplans run concurrently
│   └─ Result merging by resource type:
│       ├─ git-checkout → git three-way merge
│       ├─ database → sequential application or transaction coordination
│       └─ others → pluggable merge strategies
│
└─ DECISION TREE (persisted for audit and correction)
    ├─ Structural tree: parent_decision_id → rendering, navigation (plan tree)
    ├─ Influence DAG: decision_dependencies table → impact analysis (plan correct)
    ├─ Current tree: decisions WHERE superseded_by IS NULL
    ├─ Superseded decisions: NEVER deleted — permanent append-only history
    └─ Structural invariants: single root, reachability, acyclicity, monotonic seq#
```

### "How does a plan run?"

```
Step-by-step plan execution flow:
│
├─ STEP 1: Create an Action
│   ├─ agents action create --config ./actions/my-action.yaml
│   ├─ YAML defines: name, description, definition_of_done, actors, args,
│   │   reusable (default: true), read_only (default: false), automation_profile
│   └─ Action is namespaced, project-agnostic, reusable
│
├─ STEP 2: Use the Action on a Project (creates the Plan)
│   ├─ agents plan use local/my-action my-project
│   ├─ With args:     agents plan use local/my-action my-project --arg key=val
│   ├─ With invariant: agents plan use ... --invariant "Never modify payments"
│   ├─ With profile:  agents plan use ... --automation-profile cautious
│   ├─ Multi-project: agents plan use local/action proj-a proj-b proj-c
│   ├─ Returns:       Plan ID (ULID) — use this for all subsequent commands
│   ├─ System does:
│   │   1. Creates plan with unique ULID
│   │   2. Resolves automation profile (plan > action > project > global)
│   │   3. Carries forward action invariants + any --invariant flags
│   │   4. Enters Strategize phase
│   │   5. Invariant Reconciliation Actor computes effective invariant view
│   │   6. Strategy actor begins analyzing project resources
│   └─ ⚠️ Profile locked to plan after creation — cannot change for this plan
│
├─ STEP 3: Execute the Plan
│   ├─ agents plan execute <PLAN_ID>
│   ├─ System does:
│   │   1. Execution environment router determines where tools run (6-level chain)
│   │   2. Execution actor invokes tools to make changes IN THE SANDBOX
│   │   3. Each tool call records changes to the ChangeSet
│   │   4. Checkpointable tools create checkpoints at each decision
│   │   5. Child plans spawned as decided during Strategize
│   └─ Produces: reviewable diff + artifacts (changed files, reports, etc.)
│
├─ STEP 4: Review and Apply
│   ├─ agents plan diff <PLAN_ID>       → see what changed
│   ├─ agents plan artifacts <PLAN_ID>  → see produced artifacts
│   ├─ agents plan apply <PLAN_ID>      → commit sandbox to real resources
│   └─ After apply: plan state = applied; sandbox archived or cleaned up
│
├─ MONITORING COMMANDS (usable at any phase)
│   ├─ agents plan status <PLAN_ID>     → current phase + state
│   ├─ agents plan tree <PLAN_ID>       → decision tree visualization
│   ├─ agents plan explain <DECISION_ID>→ why this decision was made
│   └─ agents plan errors <PLAN_ID>     → error log
│
├─ CORRECTION COMMANDS
│   ├─ agents plan correct <DECISION_ID> --mode=revert --guidance "..."
│   ├─ agents plan correct <DECISION_ID> --mode=append --guidance "..."
│   └─ agents plan rollback <PLAN_ID> <CHECKPOINT_ID>
│
└─ AUTOMATION PROFILE INTERACTION
    ├─ decompose_task threshold → auto-enter Strategize after use?
    ├─ create_tool threshold    → auto-enter Execute after Strategize?
    ├─ select_tool threshold    → auto-enter Apply after Execute?
    ├─ edit_code threshold      → auto-decide during Strategize?
    └─ execute_command threshold→ auto-decide during Execute?
```

### "What is a Decision?"

```
Decisions are persisted choice points in the plan's decision tree:
│
├─ DECISION TYPES (10 types)
│   ├─ prompt_definition       → root decision; the plan's prompt (always 1 per plan)
│   ├─ invariant_enforced      → an invariant applicable to this plan
│   ├─ strategy_choice         → high-level approach during Strategize
│   ├─ implementation_choice   → how to implement a specific task (Execute)
│   ├─ resource_selection      → which resources to read/modify
│   ├─ subplan_spawn           → decision to create a child plan
│   ├─ subplan_parallel_spawn  → group of child plans to spawn concurrently
│   ├─ tool_invocation         → which tool/skill to use
│   ├─ error_recovery          → how to handle a failure
│   ├─ validation_response     → response to a validation failure
│   └─ user_intervention       → user provided guidance or correction
│
├─ WHO CREATES EACH TYPE
│   ├─ System-created:          prompt_definition, user_intervention
│   ├─ Reconciliation-actor:    invariant_enforced
│   └─ Strategy/Execution actor: all remaining types
│
├─ DECISION RECORD FIELDS
│   ├─ decision_id: ULID (unique)
│   ├─ plan_id: ULID (parent plan)
│   ├─ parent_decision_id: ULID? (structural tree parent)
│   ├─ sequence_number: int (monotonically increasing, never reused)
│   ├─ decision_type: one of 10 types above
│   ├─ question: str (what question was being answered)
│   ├─ chosen_option: str (what was decided)
│   ├─ alternatives_considered: list[str]
│   ├─ confidence_score: float? (0.0–1.0)
│   ├─ rationale: str (why this option was chosen)
│   ├─ context_snapshot: {hot_context_hash, hot_context_ref, actor_state_ref}
│   ├─ downstream_decision_ids: list[ULID]
│   ├─ downstream_plan_ids: list[ULID]
│   ├─ artifacts_produced: list[ArtifactRef]
│   ├─ is_correction: bool
│   ├─ corrects_decision_id: ULID?
│   └─ superseded_by: ULID?
│
├─ HOW DECISIONS ARE RECORDED
│   ├─ Actors call the built-in record_decision tool (auto-included in all plans)
│   ├─ System automatically captures context snapshot at time of call
│   ├─ During Strategize: decisions inform subsequent actor reasoning
│   └─ During Execute: record_decision triggers coordinated checkpoint group
│       (one checkpoint per modified sandbox resource — 1:1 mapping)
│
├─ THE PROMPT AS ROOT DECISION
│   ├─ The prompt_definition is itself a decision (correctable!)
│   ├─ Correcting the prompt invalidates ALL downstream decisions
│   ├─ Child plan prompts are created by the parent plan (as decisions)
│   └─ All corrections use the same agents plan correct command
│
└─ DECISION TIMING BY PHASE
    ├─ Strategize: invariant_enforced, strategy_choice, subplan_spawn,
    │              subplan_parallel_spawn, resource_selection
    │              downstream_plan_ids = empty at this point
    ├─ Execute:    implementation_choice, tool_invocation, error_recovery,
    │              validation_response; populates downstream_plan_ids;
    │              constrained by Strategize decisions
    └─ Apply:      NO new decisions created
```

### "How do I correct a plan?"

```
Plan correction — modifying a plan after decisions were made:
│
├─ WHEN TO CORRECT vs RERUN
│   ├─ Strategy actor made a wrong choice on a specific question
│   │   → correct that specific decision (targeted)
│   ├─ Original prompt too vague or wrong
│   │   → correct the prompt_definition decision (cascades to all children)
│   ├─ Invariant should not apply to this plan
│   │   → correct (remove) the invariant_enforced decision
│   ├─ Sequential child plans should run in parallel
│   │   → correct to use subplan_parallel_spawn
│   └─ Small fix needed at end without rewriting history
│       → use append mode
│
├─ COMMAND
│   └─ agents plan correct <DECISION_ID> --mode=(revert|append) --guidance "..."
│       ├─ --dry-run shows warnings, estimated recompute time, and hint
│       └─ --yes skips confirmation prompt
│
├─ TWO CORRECTION MODES
│   │
│   ├─ REVERT mode (--mode=revert)
│   │   ├─ Rolls back all changes to the decision point
│   │   ├─ Re-runs from that decision point forward
│   │   ├─ Supersedes the target decision and all descendants
│   │   ├─ Old execution artifacts kept for comparison
│   │   ├─ Potentially expensive if high in the tree
│   │   └─ Use when: wrong approach; wrong strategy; wrong prompt
│   │
│   └─ APPEND mode (--mode=append)
│       ├─ Leaves history intact
│       ├─ Appends corrective guidance at the end
│       ├─ Does NOT rewrite history
│       ├─ Cheaper and safer
│       └─ Use when: small fix; additive improvement; missed detail
│
├─ WHAT HAPPENS IN REVERT MODE
│   │
│   ├─ If decision was created during STRATEGIZE (strategy_choice, etc.)
│   │   ├─ Only reasoning rollback needed (Strategize is read-only)
│   │   ├─ 1. Restore actor state from context_snapshot.actor_state_ref
│   │   ├─ 2. Supersede affected subtree (target + all descendants)
│   │   ├─ 3. Create user_intervention decision with guidance text
│   │   ├─ 4. Strategy actor continues from restored state
│   │   └─ 5. Record correction_attempts entry
│   │
│   └─ If decision was created during EXECUTE (implementation_choice, etc.)
│       ├─ BOTH resource rollback AND reasoning rollback needed
│       ├─ 1. Load checkpoint group for the target decision
│       ├─ 2. Classify resources: rollbackable | non-rollbackable | unaffected
│       ├─ 3. Warn user about non-rollbackable resources and irreversible effects
│       ├─ 4. For each rollbackable resource, apply strategy-specific rollback:
│       │      git_worktree → git reset --hard <commit_sha>
│       │      filesystem_copy → restore from archived snapshot
│       │      overlay → discard overlay writes
│       │      transaction_rollback → ROLLBACK TO SAVEPOINT <name>
│       └─ 5. Restore actor LangGraph state; supersede subtree; resume
│
├─ AFFECTED SUBTREE COMPUTATION
│   ├─ Walks BOTH structural tree (parent_decision_id) AND influence DAG
│   │   (decision_dependencies table) from the target decision
│   ├─ All decisions reachable via either structure are affected
│   └─ Affected child plans are also included
│
└─ SAFETY GUARANTEES
    ├─ plan.attempt incremented before recomputing subtree (atomically)
    ├─ Correction rejected if target decision's subtree contains applied child plans
    └─ Dry-run preserves correction status at PENDING; no state changes
```

### "What is an Invariant?"

```
Invariants are natural-language constraints on plan execution:
│
├─ WHAT INVARIANTS DO
│   ├─ Guide and constrain what actors can decide and do
│   ├─ Applied during Strategize phase (recorded as invariant_enforced decisions)
│   ├─ Inherited by child plans from parent's effective invariant view
│   └─ Correctable via standard agents plan correct command
│
├─ FOUR SCOPES (all managed via agents invariant add)
│   ├─ GLOBAL  → all plans across all projects
│   │   └─ agents invariant add --global "All APIs must maintain backward compat"
│   ├─ PROJECT → all plans targeting a specific project
│   │   └─ agents invariant add --project local/api "DB queries use parameterized stmts"
│   ├─ ACTION  → carried forward when action is used (becomes plan-level)
│   │   └─ agents invariant add --action local/code-coverage "No secrets in tests"
│   └─ PLAN    → specific plan and its child plans
│       └─ agents invariant add --plan <PLAN_ID> "Mock all TCP calls"
│
├─ PRECEDENCE (highest to lowest)
│   plan > action > project > global
│
│   Exception: NON-OVERRIDABLE global invariants ALWAYS win:
│   agents invariant add --global --non-overridable "Never commit secrets"
│   → This beats even plan-level invariants
│   → non_overridable only meaningful on GLOBAL scope; ignored elsewhere
│
├─ INVARIANT RECONCILIATION ACTOR
│   ├─ Dedicated actor for computing the effective invariant view
│   ├─ Called at start of Strategize to reconcile all scopes
│   ├─ Resolution order: plan → project → global config (first found)
│   ├─ Default: global config key actor.default.invariant
│   ├─ Per-project override: --invariant-actor on agents project create
│   └─ Per-plan override: --invariant-actor on agents action create or plan use
│
├─ RECONCILIATION PROCESS
│   1. Collect invariants from global, project, action, and plan scopes
│   2. Identify conflicts between scopes
│   3. Apply precedence (plan > action > project > global)
│   4. Non-overridable globals take absolute precedence over all
│   5. Produce final effective invariant set
│   6. Record each as invariant_enforced decision in plan's tree
│
└─ USEFUL COMMANDS
    ├─ agents invariant list --effective --plan <PLAN_ID>  → see reconciled view
    ├─ agents invariant list --global
    ├─ agents invariant list --project <PROJECT>
    └─ agents invariant remove <INVARIANT_ID>
```

### "What is an Actor?"

```
Actors are YAML-configured conversational units:
│
├─ WHAT AN ACTOR IS
│   ├─ Anything conversational — from a single LLM to an entire graph
│   ├─ Can be nested/hierarchical (orchestrator of orchestrators)
│   ├─ Every custom actor IS a graph (LangGraph via YAML)
│   └─ Named: <namespace>/<name> (e.g. local/my-reviewer, openai/gpt-4)
│
├─ ACTOR TYPES
│   ├─ LLM actor (type: llm)
│   │   ├─ Wraps a built-in LLM provider (openai/gpt-4, anthropic/claude-3-opus)
│   │   ├─ Has: config (actor, temperature, system_prompt), skills list
│   │   └─ Simple: one conversational agent
│   └─ Graph actor (type: graph — the default for custom actors)
│       ├─ A LangGraph composed of agent nodes, tool nodes, and routing
│       ├─ Can reference other actors as sub-nodes (hierarchical)
│       └─ Supports conditional edges, checkpointing, streaming
│
├─ SPECIALIZED ROLES IN PLAN LIFECYCLE
│   ├─ strategy_actor      → architect/planner; produces decision tree in Strategize
│   ├─ execution_actor     → builder/implementer; carries out decisions in Execute
│   ├─ estimation_actor    → optional; estimates cost/risk after Strategize
│   └─ invariant_actor     → Invariant Reconciliation Actor; resolves conflicts
│
├─ ACTOR CONFIGURATION (YAML — two-phase preprocessing)
│   ├─ Phase 1: Jinja2 template rendering ({{ }}, {% %}, {# #})
│   │   ├─ Sandboxed — no arbitrary Python, no filesystem access
│   │   ├─ Custom filters: yaml, indent, sum, selectattr
│   │   └─ system_prompt fields: templates deferred to runtime evaluation
│   ├─ Phase 2: Environment variable interpolation (${VAR}, ${VAR:default})
│   │   └─ Auto type coercion: "true"/"false"→bool, digits→int, floats→float
│   └─ Template context precedence: runtime > plan > session > global_context in YAML
│
├─ ACTOR COMPOSITION RULES
│   ├─ Actors reference other actors by name in graph nodes
│   ├─ Load order matters: referenced actors must be registered first
│   ├─ Circular references are PROHIBITED (detected at registration time)
│   └─ No depth limit on hierarchical composition
│
├─ ACTOR RESOLUTION CHAIN (for plan-level actors)
│   └─ CLI --flag override → Action YAML field → project config → global config key
│
└─ KEY COMMANDS
    ├─ agents actor add --config ./actors/my-actor.yaml
    ├─ agents actor run local/my-actor "Prompt text"
    ├─ agents actor list
    └─ agents actor show local/my-actor
```

### "What is a Tool?"

```
Tools are the atomic unit of execution in CleverAgents:
│
├─ WHAT A TOOL IS
│   ├─ Namespaced, independently registered, callable operation
│   ├─ Smallest piece of functionality that reads/writes/transforms resources
│   ├─ Defined in its own YAML config file, registered in Tool Registry
│   └─ Named: <namespace>/<name> (e.g. local/run-migrations)
│
├─ DUAL ROLE OF TOOLS
│   ├─ Role 1: Component of a Skill
│   │   → Skill lists tool by name → actor gets tool for LLM tool-calling
│   └─ Role 2: Tool node in an Actor graph
│       → type: tool node → deterministic, non-LLM step in a workflow
│
├─ FOUR TOOL SOURCES
│   ├─ custom       → Python code embedded in the YAML's code: field
│   ├─ mcp          → external MCP server endpoint (mcp_server.command field)
│   ├─ agent_skill  → Agent Skills (AgentSkills.io) folder  (agent_skill.path)
│   └─ builtin      → CleverAgents built-in tools (read_file, write_file, etc.)
│
├─ TOOL CAPABILITY METADATA
│   ├─ writes: bool          → does it modify resources?
│   ├─ write_scope:          → which resource slots it writes to
│   ├─ checkpointable: bool  → can it create rollback checkpoints?
│   ├─ checkpoint_scope:     → granularity (file/transaction/commit/snapshot)
│   ├─ side_effects: list    → e.g. [spawn_subplan, deploy, schema_mutation]
│   ├─ read_only: bool       → convenience flag (writes=false)
│   └─ environment:          → {required/preferred/specific} execution env
│
├─ TOOL FOUR-STAGE LIFECYCLE
│   ├─ discover   → tool is found and registered
│   ├─ activate   → tool is prepared for execution (connection, auth, etc.)
│   ├─ execute    → tool runs with parameters, operates on sandbox
│   └─ deactivate → tool cleans up after execution
│
├─ RESOURCE BINDINGS
│   ├─ Tools declare typed resource SLOTS (e.g. db: {type: local/database})
│   ├─ Slots resolve via:
│   │   ├─ Contextual binding → from the plan's project resources
│   │   ├─ Static binding     → hardcoded at registration
│   │   └─ Parameter binding  → passed at invocation
│   └─ ctx.resources["slot_name"] → access bound resource at execution time
│
├─ ANONYMOUS TOOLS (inline, unregistered)
│   ├─ Defined inline in a skill YAML or actor graph node
│   ├─ Same format as named tool YAML (no name field)
│   ├─ Not in Tool Registry; not reusable outside their context
│   └─ Easy to promote to named tool: copy to own YAML + agents tool add
│
├─ METADATA OVERRIDES (at point of use)
│   ├─ In skill: override capability for tools in that skill's context
│   ├─ In actor graph node: override capability for that node's invocation
│   ├─ Shallow-merged: only specified fields replaced
│   ├─ Never persist back to Tool Registry
│   └─ Only capability and description can be overridden (not schema)
│
├─ BUILT-IN RESOURCE TOOLS (auto-included, operate in sandbox)
│   ├─ read_file, write_file, edit_file, delete_file, move_file
│   ├─ create_directory, list_files, search_files, get_file_info
│   └─ Each automatically operates within sandbox, records to ChangeSet
│
└─ KEY COMMANDS
    ├─ agents tool add --config ./tools/my-tool.yaml [--update]
    ├─ agents tool list [--type tool|validation] [--namespace ns]
    ├─ agents tool show local/my-tool
    └─ agents tool remove local/my-tool
```

### "What is a Validation?"

```
Validations are a Tool subtype with pass/fail semantics:
│
├─ WHAT A VALIDATION IS
│   ├─ A specialized subtype of Tool (inherits all Tool properties)
│   ├─ Extends Tool with: mode (required|informational) + structured JSON return
│   ├─ Return format: { "passed": bool, "message": str, "data": object }
│   └─ Named in the same namespace as Tools (shared namespace — conflicts = error)
│
├─ KEY CONSTRAINTS ON VALIDATIONS
│   ├─ ALWAYS read-only: writes=false, checkpointable=false (never modify resources)
│   ├─ Can be used anywhere a Tool is expected (superset semantics)
│   ├─ But plain Tools cannot be used where a Validation is expected
│   └─ Listed separately: agents tool list --type validation
│
├─ TWO MODES
│   ├─ required      → failure BLOCKS apply (plan cannot be applied)
│   └─ informational → failure LOGGED but does not block apply
│
├─ TOOL WRAPPING
│   ├─ A Validation can wrap an existing plain Tool via wraps field
│   ├─ Reuses the Tool's implementation; interprets output via transform function
│   └─ Source type: wrapped (validation-specific source)
│
├─ VALIDATION ATTACHMENT (three attachment scopes)
│   ├─ Resource-direct: validation attached to a resource unconditionally
│   ├─ Project-scoped: validation applies to resource when plan is in that project
│   └─ Plan-scoped: validation applies to resource only for that specific plan
│   Commands:
│   ├─ agents validation add --config ./validations/my-val.yaml
│   ├─ agents validation attach [--project <P> | --plan <ID>] <RESOURCE> <VALIDATION>
│   └─ agents validation detach <ATTACHMENT_ID>
│
├─ WHEN VALIDATION RUNS
│   ├─ Runs during EXECUTE phase (after tool invocations produce output)
│   ├─ NOT during Apply (Apply commits what Execute already validated)
│   ├─ required failure → execution actor may attempt fix-then-revalidate loop
│   │   (max retries: 3 by default, configurable in automation profile)
│   └─ If required validation cannot be resolved → plan cannot apply
│
└─ DISTINCT FROM GUARDRAILS
    ├─ Guardrails = system-level pre-flight + runtime limits (infrastructure)
    └─ Validations = quality checks on the WORK PRODUCED by the plan (domain)
```

### "What is a Skill?"

```
Skills are composable, namespaced collections of tools:
│
├─ WHAT A SKILL IS
│   ├─ A named, composable collection of tools assembled by reference
│   ├─ Actors reference skills by name to acquire capabilities
│   └─ Named: <namespace>/<name> (e.g. local/file-ops, cleverthis/devops)
│
├─ FOUR WAYS TO POPULATE A SKILL
│   ├─ 1. Named tool references → tools: [local/run-migrations, local/validate-api]
│   ├─ 2. Inline anonymous tools → anonymous_tools: [{description:..., code:...}]
│   ├─ 3. Include other skills → includes: [local/base-devops, local/git-ops]
│   └─ 4. Agent Skills (AgentSkills.io) → instruction-driven SKILL.md workflows
│
├─ SKILL INCLUSION (with optional tool overrides)
│   ├─ When a skill includes another, it inherits ALL of the included skill's tools
│   └─ Individual tools from included skills can have capability overrides:
│       includes:
│         - name: local/devops-toolkit
│           tool_overrides:
│             - tool: local/run-migrations
│               override: {capability: {human_approval_required: true}}
│
└─ KEY COMMANDS
    ├─ agents skill add --config ./skills/my-skill.yaml [--update]
    ├─ agents skill list [--namespace ns]
    ├─ agents skill show local/my-skill
    ├─ agents skill tools local/my-skill  → list all tools in skill (including transitive)
    └─ agents skill remove local/my-skill
```

### "What is a Resource?"

```
Resources are ULID-identified entities that a plan can reason about or manipulate:
│
├─ WHAT A RESOURCE IS
│   ├─ Represents anything readable, writable, or queryable
│   │   (git repos, filesystems, databases, APIs, documents, infrastructure)
│   ├─ ULID-identified (unique per instance, not per type)
│   ├─ Independently registered; projects LINK to resources (don't own them)
│   └─ One resource can be linked to multiple projects (shared resources)
│
├─ PHYSICAL vs VIRTUAL
│   ├─ Physical: a specific, concrete manifestation at a specific location
│   │   (a file at a path, a repo at a URL, a database with a connection string)
│   └─ Virtual: an abstract equivalence identity linking equivalent physical resources
│       (has no location; cannot be directly read or written)
│       e.g. the file virtual type links an fs-file with a git-tree-entry of same content
│
├─ RESOURCE DAG (parent/child relationships)
│   ├─ Resources form a directed acyclic graph
│   ├─ A resource can have multiple parents and multiple children
│   ├─ Parent/child types are constrained by the resource type definition
│   ├─ Auto-discovery: registering git-checkout auto-discovers git and fs-directory children
│   └─ Manual linking: agents resource link-child <PARENT> <CHILD>
│
├─ FOUR USER-ADDABLE TOP-LEVEL TYPES
│   ├─ git-checkout  → locally checked-out repo; composes git + fs-directory
│   ├─ git           → remote or local git repo metadata only
│   ├─ fs-mount      → a physical filesystem mount point
│   └─ fs-directory  → an arbitrary directory (standalone)
│
├─ RESOURCE TYPE INHERITANCE
│   ├─ Types support single-inheritance via inherits field
│   ├─ Subtype inherits: properties, capabilities, child type constraints,
│   │   sandbox strategy, handler behavior
│   ├─ Polymorphic tool matching: tools bound to parent type work with subtypes
│   ├─ Maximum chain depth: 5 levels
│   └─ Example: devcontainer-instance inherits container-instance
│
├─ SANDBOX STRATEGIES (per resource type)
│   ├─ git_worktree    → git worktree/branch; rollback via git reset
│   ├─ copy_on_write   → filesystem copy; rollback via snapshot restore
│   ├─ overlay         → overlayfs; rollback via discard overlay writes
│   ├─ transaction_rollback → database; rollback via ROLLBACK TO SAVEPOINT
│   └─ none            → no sandbox (APIs, cloud services); user proceeds at own risk
│
├─ EXECUTION ENVIRONMENT (6-level precedence chain)
│   Priority 1: Plan-level override  (plan use --execution-env ... --priority override)
│   Priority 2: Project-level override (project context set --execution-env ... override)
│   Priority 3: Nearest-ancestor devcontainer (auto-detected .devcontainer/)
│   Priority 4: Plan-level fallback
│   Priority 5: Project-level fallback
│   Priority 6: Host (default — local OS)
│
├─ DEVCONTAINER INTEGRATION
│   ├─ Auto-discovered when git-checkout or fs-directory contains .devcontainer/
│   ├─ Creates devcontainer-instance resource (inherits container-instance)
│   ├─ Lazy activation: container built only when first needed by a plan
│   └─ devcontainer-instance is the type; devcontainer.json defines the container
│
└─ KEY COMMANDS
    ├─ agents resource add <TYPE> <NAME> [type-specific-flags...]
    ├─ agents resource list [--type <TYPE>]
    ├─ agents resource show <RESOURCE>
    ├─ agents resource inspect [--tree] [--file <PATH>] <RESOURCE>
    ├─ agents resource tree [-d N] <RESOURCE>
    ├─ agents resource link-child <PARENT> <CHILD>
    ├─ agents resource stop <NAME>   → stop container resources
    └─ agents resource rebuild <NAME>→ rebuild devcontainer
```

### "What is a Project?"

```
Projects are named scopes linking resources and configuration:
│
├─ WHAT A PROJECT IS
│   ├─ Answers: "Where is the work happening? What can this plan use?"
│   ├─ A collection of linked resources + context config + invariants
│   ├─ Does NOT define resources inline — it links existing registered resources
│   ├─ One resource can be linked to MULTIPLE projects (shared)
│   ├─ Identified by namespaced name only (no ULID)
│   └─ Created via CLI commands ONLY (not YAML config files)
│
├─ PROJECT TYPES
│   ├─ Local:  has at least one local-only resource → plans execute on client only
│   └─ Remote: all resources are remotely accessible → can execute on server
│
├─ CREATING A PROJECT (3-step process)
│   1. agents resource add git-checkout local/my-repo --path /path/to/repo
│   2. agents project create "my-api-service"
│   3. agents project link-resource "my-api-service" local/my-repo
│      (optionally: --read-only to restrict writes)
│
├─ WHAT A PROJECT CONTAINS
│   ├─ Linked resources (with optional project-level overrides: project_read_only)
│   ├─ Context configuration (ignore patterns, max file size, indexing strategy)
│   ├─ Execution environment preference (default container for tool execution)
│   ├─ Invariants (project-scoped, apply to all plans targeting this project)
│   └─ Validation attachments (validations applied to resources via this project)
│
├─ MULTI-PROJECT PLANS
│   ├─ A single plan can target MULTIPLE projects simultaneously
│   ├─ agents plan use local/schema-update api-service web-frontend mobile-app
│   ├─ Strategize must clarify which steps affect which project
│   ├─ Execute isolates sandboxes per project (or composite for shared resources)
│   └─ Apply commits to each project separately (separate approval records)
│
└─ KEY COMMANDS
    ├─ agents project create [--resource R]... [--invariant I]... <NAME>
    ├─ agents project link-resource [--read-only] <PROJECT> <RESOURCE>
    ├─ agents project unlink-resource <PROJECT> <RESOURCE_NAME>
    ├─ agents project context set [--view strategize|execute|apply|default] ... <PROJECT>
    ├─ agents project context show [--view ...] <PROJECT>
    ├─ agents project context inspect [--strategy S] [--focus URI] <PROJECT>
    ├─ agents project context simulate [--budget N] <PROJECT>
    ├─ agents project list [--namespace ns]
    ├─ agents project show <PROJECT>
    └─ agents project delete [--force] <PROJECT>
```

### "Which automation profile applies?"

```
Automation profiles control which phase transitions and decisions are automatic:
│
├─ WHAT A PROFILE CONTROLS
│   ├─ 11 automatable task FLAGS (each a confidence threshold 0.0–1.0):
│   │   ├─ 0.0 = always automatic (proceed regardless of confidence)
│   │   └─ 1.0 = always manual (always require human approval)
│   └─ SAFETY PROFILE sub-model (hard binary constraints)
│
├─ THE 11 FLAGS (what each controls)
│   ├─ decompose_task   → auto-enter Strategize after plan use?
│   ├─ create_tool      → auto-enter Execute after Strategize?
│   ├─ select_tool      → auto-enter Apply after Execute?
│   ├─ edit_code        → auto-decide during Strategize?
│   ├─ execute_command  → auto-decide during Execute?
│   ├─ create_file      → auto-fix failing validations?
│   ├─ delete_content   → auto-revise strategy when Execute hits constraints?
│   ├─ access_network   → auto-revert from Apply (constrained) to Strategize?
│   ├─ install_dependency→ auto-spawn and execute child plans?
│   ├─ modify_config    → auto-retry transient failures?
│   └─ approve_plan     → auto-restore from checkpoint on failure?
│
├─ SAFETY PROFILE FLAGS (binary, not confidence-based)
│   ├─ require_sandbox       (default: true)
│   ├─ require_checkpoints   (default: true)
│   ├─ allow_unsafe_tools    (default: false)
│   ├─ require_human_approval(default: false)
│   ├─ allowed_skill_categories (default: [] = all allowed)
│   ├─ max_cost_per_plan     (default: null = no limit)
│   ├─ max_total_cost        (default: null = no limit)
│   └─ max_retries_per_step  (default: 3)
│
├─ 8 BUILT-IN PROFILES
│   │
│   ├─ manual      → all flags 1.0 (always manual); safest
│   │   Use: new users, critical production, sensitive projects
│   │
│   ├─ review      → phases auto (0.0); most decisions manual (1.0)
│   │   Use: stay in decision loop; let phases run; review each choice
│   │
│   ├─ supervised  → Strategize auto (0.0); Execute+Apply manual (1.0)
│   │   Use: trust the planning; review before execution
│   │
│   ├─ cautious    → intermediate thresholds (0.6–0.8+); Apply always manual
│   │   Use: gradual adoption; system self-assesses; escalates when uncertain
│   │
│   ├─ trusted     → most flags 0.0; Apply manual (1.0); strategy revision manual
│   │   Use: day-to-day development; routine refactoring; test generation
│   │
│   ├─ auto        → all 0.0 except Apply (1.0); self-revising strategy
│   │   Use: well-understood projects; strong invariant coverage; batch ops
│   │
│   ├─ ci          → all 0.0 (fully automatic, including Apply); sandbox mandatory
│   │   Use: CI/CD pipelines; headless; automated testing; batch jobs
│   │
│   └─ full-auto   → all 0.0; NO sandbox; unsafe tools allowed
│       Use: low-risk tasks; dependency updates; docs; formatting; external safety exists
│
├─ PROFILE PRECEDENCE (highest to lowest)
│   plan > action > project > global
│   ⚠️ Profile LOCKED to plan at plan use time — cannot change for running plan
│
├─ CHILD PLAN INHERITANCE
│   └─ Child plans inherit parent's effective automation profile
│
└─ SEMANTIC ESCALATION (how thresholds work)
    ├─ System computes confidence score (0.0–1.0) from multiple factors:
    │   past_success_rate, codebase_familiarity, risk_assessment, invariant_complexity
    ├─ Confidence >= threshold → proceed automatically
    ├─ Confidence < threshold → escalate to human (pause and prompt)
    └─ Progressive trust: start with manual → review → cautious → trusted → auto → ci
```

### "How does naming work?"

```
Namespace and naming conventions for all entities:
│
├─ FORMAT
│   └─ [[server:]namespace/]name
│       ├─ server:      optional — qualifies which server (e.g. prod:)
│       ├─ namespace/   the scoping segment
│       └─ name         the entity's stable identifier (kebab-case recommended)
│
├─ NAMESPACE TYPES
│   ├─ local/      → this machine only; never synced to server
│   │   Example: local/my-reviewer, local/code-coverage
│   ├─ <username>/ → personal server namespace (e.g. freemo/, jsmith/)
│   │   Created on server registration; personal items across devices
│   ├─ <orgname>/  → organization namespace (e.g. cleverthis/, acme/)
│   │   Shared across team members; org-level collaboration
│   └─ openai/, anthropic/, etc. → built-in LLM actors (no server/namespace needed)
│
├─ DEFAULT NAMESPACE
│   └─ When namespace omitted → defaults to local/
│
├─ BUILT-IN RESOURCE TYPES
│   └─ Unnamespaced (no namespace/): git-checkout, git, fs-mount, fs-directory, etc.
│       Custom types use namespace/: local/my-db-type, acme/custom-cloud
│
├─ IDENTITY RULES
│   ├─ ULID: Plans, decisions, resources, correction attempts,
│   │         validation attachments, checkpoints
│   └─ Namespaced name: Projects, actions, actors, tools, skills, resource types,
│                       automation profiles, LSP servers
│
└─ SERVER-QUALIFIED EXAMPLES
    ├─ prod:acme/deploy-action   → action on the "prod" server, "acme" namespace
    ├─ dev:freemo/custom-tool    → tool on the "dev" server, personal namespace
    └─ local/api-repo            → local-only resource (never synced)
```

### "Which CLI command do I use?"

```
CLI command selection guide:
│
├─ PLAN COMMANDS (agents plan ...)
│   ├─ use <ACTION> <PROJECT>...     → create plan (transition: Action → Strategize)
│   ├─ execute <PLAN_ID>             → run plan (Strategize → Execute)
│   ├─ apply <PLAN_ID>               → commit (Execute → Apply)
│   ├─ status <PLAN_ID>              → current phase + state
│   ├─ tree <PLAN_ID>                → visualize decision tree
│   ├─ explain <DECISION_ID>         → why this decision was made
│   ├─ correct <DECISION_ID>         → fix a decision (--mode=revert|append)
│   ├─ diff <PLAN_ID>                → see sandbox changes vs real resources
│   ├─ artifacts <PLAN_ID>           → list generated outputs
│   ├─ prompt <PLAN_ID> <GUIDANCE>   → inject user guidance mid-execution
│   ├─ rollback <PLAN_ID> <CKPT_ID> → revert to a specific checkpoint
│   ├─ cancel <PLAN_ID>              → cancel an in-progress plan
│   ├─ errors <PLAN_ID>              → show error log
│   └─ list [--phase] [--state] [--project] [--action] → list plans
│
├─ SESSION COMMANDS (agents session ...)
│   ├─ create [--actor ACTOR]         → start a new conversation
│   ├─ tell --session <ID> <PROMPT>  → send a message
│   ├─ list                           → list all sessions
│   ├─ show <SESSION_ID>              → show session details
│   ├─ delete <SESSION_ID>            → delete a session
│   ├─ export / import                → save or load session data
│   └─ [no session = agents init]    → first-time setup
│
├─ PROJECT COMMANDS (agents project ...)
│   ├─ create [--resource R]... <NAME> → create a project
│   ├─ link-resource [--read-only] <P> <R> → add resource to project
│   ├─ unlink-resource <P> <R>        → remove resource from project
│   ├─ context set ... <P>            → configure context policy
│   ├─ context show / inspect / simulate → view and test context
│   ├─ list / show / delete           → manage projects
│   └─ [to add invariant to project]: agents invariant add --project <P>
│
├─ ACTOR COMMANDS (agents actor ...)
│   ├─ add --config <FILE>            → register an actor from YAML
│   ├─ run <NAME> <PROMPT>            → run an actor interactively
│   ├─ list / show / remove           → manage actors
│   └─ context remove/list/show/export/import/clear → actor context management
│
├─ SKILL COMMANDS (agents skill ...)
│   ├─ add --config <FILE>            → register a skill from YAML
│   ├─ list / show / tools / remove   → manage skills
│
├─ TOOL COMMANDS (agents tool ...)
│   ├─ add --config <FILE>            → register a tool from YAML
│   ├─ list [--type tool|validation]  → list tools or validations
│   ├─ show / remove                  → manage tools
│
├─ VALIDATION COMMANDS (agents validation ...)
│   ├─ add --config <FILE>            → register a validation from YAML
│   ├─ attach [--project P|--plan ID] <RESOURCE> <VALIDATION> → attach
│   └─ detach <ATTACHMENT_ID>         → detach
│
├─ RESOURCE COMMANDS (agents resource ...)
│   ├─ type add/remove/list/show      → manage resource type definitions
│   ├─ add <TYPE> <NAME> [flags...]   → register a resource
│   ├─ list [--type T]                → list resources
│   ├─ show / inspect / tree          → explore resource structure
│   ├─ link-child / unlink-child      → manage DAG relationships
│   ├─ stop / rebuild                 → manage container resources
│   └─ remove                         → delete a resource
│
├─ ACTION COMMANDS (agents action ...)
│   ├─ create --config <FILE>         → create an action from YAML
│   ├─ list / show / archive          → manage actions
│
├─ INVARIANT COMMANDS (agents invariant ...)
│   ├─ add [--global|--project P|--plan ID|--action A] <TEXT>
│   ├─ list [--global|--project P|--plan ID|--action A] [--effective]
│   └─ remove <INVARIANT_ID>
│
├─ AUTOMATION PROFILE COMMANDS (agents automation-profile ...)
│   ├─ add --config <FILE>            → register a custom profile from YAML
│   ├─ list / show / remove           → manage profiles
│
├─ LSP COMMANDS (agents lsp ...)
│   ├─ add --config <FILE>            → register an LSP server from YAML
│   ├─ list [--language LANG]         → list LSP servers
│   ├─ show / remove                  → manage LSP servers
│   └─ serve [--log-level LEVEL]      → start LSP relay service
│
├─ CONFIG COMMANDS (agents config ...)
│   ├─ set <key> <value>              → set a configuration key
│   ├─ get <key>                      → get a configuration value
│   └─ list [<REGEX>]                 → list all config keys
│
├─ UTILITY COMMANDS
│   ├─ agents version     → print CLI version
│   ├─ agents info        → show runtime config and status
│   ├─ agents diagnostics → run health checks
│   └─ agents init        → first-time setup
│
└─ OUTPUT FORMAT (applies to ALL commands)
    ├─ --format rich   → default; colored, animated (interactive terminal)
    ├─ --format color  → plain text with ANSI color
    ├─ --format table  → ASCII box-drawing tables
    ├─ --format plain  → no color, no non-ASCII (piping, logs)
    ├─ --format json   → structured JSON (scripts, CI/CD)
    └─ --format yaml   → structured YAML (configuration)
```

### "What is the architecture?"

```
CleverAgents is a 4-layer, event-driven, DDD application:
│
├─ FOUR LAYERS (strict dependency rule: outer → inner ONLY)
│   │
│   ├─ PRESENTATION LAYER
│   │   ├─ CLI (Typer + Rich)
│   │   ├─ TUI (Textual)
│   │   ├─ Web (Textual Web)
│   │   ├─ IDE Plugin (embedded TUI)
│   │   └─ A2A Server Endpoint (JSON-RPC 2.0)
│   │   ⚠️ No Presentation module imports Infrastructure directly
│   │
│   ├─ APPLICATION LAYER
│   │   ├─ Service Facade: PlanService, ProjectService, ActorService,
│   │   │   ContextService, ToolService, SkillService, ResourceService
│   │   ├─ Workflow Engine: PlanLifecycle, SessionWorkflow, CorrectionFlow, MergeWorkflow
│   │   ├─ Event Bus: EventEmitter, StructuredLog, MetricsCollector
│   │   └─ DI Container (dependency-injector DeclarativeContainer)
│   │
│   ├─ DOMAIN LAYER
│   │   ├─ Domain Models: Plan, Decision, Project, Resource, Actor, Action,
│   │   │   Tool, Skill, Session, Invariant, AutomationProfile, Checkpoint
│   │   ├─ Domain Services: InvariantEnforcer, AutonomyController,
│   │   │   ContextBuilder, MergeResolver
│   │   ├─ Repository Interfaces (Protocol classes — no DI framework annotations)
│   │   └─ Domain Events: PlanCreated, PhaseChanged, DecisionMade, etc.
│   │
│   └─ INFRASTRUCTURE LAYER
│       ├─ Database: SQLite (local) / PostgreSQL (server) via SQLAlchemy + Alembic
│       ├─ Indexing: Tantivy (full-text), FAISS/Qdrant (vector), Neo4j/rdflib (graph)
│       ├─ Sandbox: GitWorktree, FsCopy, TxnRollback, NoOp strategies
│       ├─ LLM/AI: LangChain + LangGraph, Provider registry, RxPY, MCP SDK
│       ├─ External: MCP Servers, Agent Skills, REST/gRPC clients
│       ├─ LSP Runtime: LSP server manager, LSPToolAdapter, language servers
│       └─ File System: Watchdog, Git CLI, OS process/signals
│
├─ TWO DEPLOYMENT MODES
│   ├─ LOCAL MODE
│   │   ├─ Single-process; all components in same Python process
│   │   ├─ A2A flows over stdio (agent as subprocess)
│   │   ├─ Database: SQLite
│   │   └─ A2a extension methods resolved in-process via A2aLocalFacade
│   └─ SERVER MODE
│       ├─ Multi-user service; CLI is thin client
│       ├─ A2A flows over HTTP to CleverAgents server (JSON-RPC 2.0)
│       ├─ Database: PostgreSQL
│       └─ Actor execution via LangGraph Platform (RemoteGraph)
│
├─ A2A PROTOCOL (the fundamental boundary between Presentation and Application)
│   ├─ JSON-RPC 2.0 wire format
│   ├─ Standard operations: message/send, message/stream, task lifecycle
│   ├─ Extension methods: _cleveragents/plan/*, _cleveragents/registry/*,
│   │   _cleveragents/context/*, _cleveragents/sync/*, _cleveragents/health/*
│   ├─ Streaming: TaskStatusUpdateEvent + TaskArtifactUpdateEvent via SSE
│   └─ Error codes: -32001 (not found), -32002 (auth required),
│       -32003 (forbidden), -32004 (invalid state), -32005 (already exists)
│
├─ DEPENDENCY INJECTION (DeclarativeContainer)
│   ├─ Single composition root for the entire application
│   ├─ Singleton providers: DB engine, repositories, event bus, index backends
│   ├─ Factory providers: sandbox instances, execution contexts
│   ├─ Configuration provider: TOML config + environment variables
│   └─ Domain code never imports dependency-injector (Protocol interfaces only)
│
└─ DATA VALIDATION (Pydantic v2)
    ├─ Every domain entity is a Pydantic model (via DomainBaseModel base class)
    ├─ All data crossing layer boundaries passes through a Pydantic model
    ├─ Raw dicts cannot propagate between layers
    ├─ JSON Schema auto-generated from models → used for tool definitions
    └─ CLEVERAGENTS_ prefix for environment variables (via Pydantic Settings)
```

### "What is the ACMS?"

```
The Advanced Context Management System (ACMS) assembles actor context:
│
├─ COMPONENTS
│   ├─ UKO (Universal Knowledge Ontology)
│   │   ├─ RDF-based ontology representing resources at multiple abstraction levels
│   │   ├─ Semantically aware — implicit relationships inferred from content
│   │   └─ 4 layers: universal foundation → domain → paradigm/format → technology
│   │
│   ├─ CRP (Context Request Protocol)
│   │   └─ Vocabulary for actors to declare needed info, depth, and scope
│   │
│   ├─ Context Strategies (pluggable retrieval components)
│   │   ├─ Keyword search, semantic embedding, graph navigation, temporal archaeology
│   │   └─ Executed in parallel by StrategyExecutor
│   │
│   ├─ Context Assembly Pipeline (10 pluggable slots, 3 phases)
│   │   ├─ Phase 1: Strategy Orchestration
│   │   ├─ Phase 2: Fragment Fusion (GreedyKnapsackPacker, RelevanceCoherenceOrderer)
│   │   └─ Phase 3: Context Finalization (SkeletonCompressor)
│   │
│   └─ Hot/Warm/Cold Storage Tiers
│       ├─ Hot: active context in memory (bounded by hot_max_tokens)
│       ├─ Warm: recent decisions (bounded by warm_max_decisions)
│       └─ Cold: persistent storage (all historical context)
│
├─ SKELETON COMPRESSION
│   └─ Compressed parent plan context passed to child plans
│       (size governed by skeleton_ratio budget parameter)
│
├─ CONTEXT VIEW CONFIGURATION (per project, per phase)
│   ├─ views: strategize | execute | apply | default
│   ├─ Configurable per project via: agents project context set --view <VIEW>
│   └─ Parameters: include/exclude resources + paths, hot/warm/cold limits,
│       max file/total size, summarize flag, strategy list, breadth/depth,
│       depth-gradient, skeleton-ratio, temporal-scope, execution-environment
│
└─ PIPELINE OVERRIDABILITY
    └─ All 10 pipeline components overridable at plan > project > global scope
```

### "Which milestone am I in?"

```
Current milestone status (as of 2026-04-11):
│
├─ v3.0.0 ✅ CLOSED — Minimal Local Source-Code Workflow
├─ v3.1.0 ✅ CLOSED — Actor Compiler + Full LLM Integration
│
├─ v3.2.0 🔄 IN PROGRESS — Decisions + Validations + Invariants
│   Goal: Decision recording, invariant enforcement, plan correction
│   Key deliverables: plan tree, plan explain, plan correct, invariant add/list
│   Constraints: ULID decisions, correction increments plan.attempt, validation read-only
│
├─ v3.3.0 🔄 IN PROGRESS — Corrections + Subplans + Checkpoints
│   Goal: Subplan spawning, parallel execution, three-way merge, rollback
│   Key deliverables: plan rollback, parallel subplan execution, merge strategies
│   Constraints: ULID child plans (no name), per-subplan sandbox, max_parallel enforced
│
├─ v3.4.0 🔄 IN PROGRESS — ACMS v1 + Context Scaling
│   Goal: ACMS pipeline operational; 10,000+ file projects indexed and queried
│   Key deliverables: context set/show/inspect/simulate, hot/warm/cold tiers, UKO indexing
│   Constraints: 10 pipeline slots overridable; ULID-stable UKO URIs; strategy parallelism
│
├─ v3.5.0 🔄 IN PROGRESS — Autonomy Hardening
│   Goal: Autonomous execution with 4+ subplan levels, correction, validation-gated apply
│   Key deliverables: A2A facade, guard enforcement, 8 built-in profiles, 10+ parallel subplans
│   Constraints: A2A local facade resolves in-process; denylist checked first; 0.0=auto/1.0=manual
│
├─ v3.6.0 🔄 IN PROGRESS — Advanced Concepts & Deferred Features
│   Goal: LSP integration, resource type inheritance, devcontainer, container execution
│   Key deliverables: agents lsp add/list/show, LSP tools via LSPToolAdapter, devcontainer lazy activation
│   Constraints: max inheritance depth 5; devcontainer-instance inherits container-instance
│
├─ v3.7.0 🔄 IN PROGRESS — TUI Implementation
│   Goal: Textual-based TUI with persona system, @ and / input modes, multi-session
│   Key deliverables: agents tui, sidebar states, persona YAML, TuiMaterializer
│   Constraints: Textual >= 1.0; TUI/CLI parity via A2A; personas scoped to TUI only
│
└─ v3.8.0 🔄 IN PROGRESS — Server Implementation
    Goal: A2A server, multi-user, team RBAC, LangGraph Platform, PostgreSQL
    Key deliverables: agents server add, HTTP A2A endpoint, entity sync, multi-device
    Constraints: A2A-only (no REST); shared domain/app layers with client; server ≠ critical path
    ⚠️ v3.8.0 has no deadline — focus on v3.2.0–v3.7.0 first
│
└─ CROSS-MILESTONE ARCHITECTURAL INVARIANTS (every milestone, always)
    1. Spec-first: no feature without spec coverage
    2. Layer boundaries: Presentation → Application → Domain → Infrastructure (no reverse)
    3. Type safety: Pyright strict; no # type: ignore
    4. Fail-fast: all argument validation at entry points
    5. ULID for: plans, decisions, resources, correction attempts, validation attachments
    6. Namespace format: [[server:]namespace/]name; local/ reserved
    7. A2A exclusivity: all client-server communication via A2A; no REST
    8. BDD tests: all unit-level tests as Behave/Gherkin scenarios; no xUnit
    9. File size: no source file exceeds 500 lines
```

---

## 📏 Key Numbers Reference

| Item | Value | Notes |
|------|-------|-------|
| Plan identifier | ULID | 26-char Crockford base32 |
| Plan phases | 4 | Action → Strategize → Execute → Apply |
| Decision types | 10 | prompt_definition through user_intervention |
| Invariant scopes | 4 | global / project / action / plan |
| Invariant precedence | plan > action > project > global | non-overridable global always wins |
| Built-in automation profiles | 8 | manual through full-auto |
| Automatable task flags | 11 | decompose_task through approve_plan |
| Confidence threshold range | 0.0 – 1.0 | 0.0 = always auto; 1.0 = always manual |
| Max parallel subplans | 5 (default) | range 1–50; SubplanConfig.max_parallel |
| Max subplan retries | 2 (default) | SubplanConfig.max_retries |
| Checkpoint triggers | 4 | on_tool_write, on_tool_write_complete, on_subplan_spawn, on_error |
| User-addable resource types | 4 | git-checkout, git, fs-mount, fs-directory |
| Built-in resource types | 34+ | 24 physical + 1 subtype + 9 virtual |
| Resource type inheritance depth max | 5 levels | circular = error at registration |
| Execution environment precedence | 6 levels | plan override → project override → devcontainer → plan fallback → project fallback → host |
| Tool lifecycle stages | 4 | discover → activate → execute → deactivate |
| Actor YAML preprocessing phases | 2 | Jinja2 rendering, then env-var interpolation |
| Max actor inheritance/nesting | unlimited | no depth limit on graph composition |
| Context assembly pipeline slots | 10 | 3 phases; each overridable |
| ACMS storage tiers | 3 | hot / warm / cold |
| Python minimum version | >= 3.13 | pattern matching, performance, type hint maturity |
| LangGraph | >= 0.2.60 | StateGraph, MemorySaver, RemoteGraph |
| LangChain | >= 0.3.18 | BaseLanguageModel, provider packages |
| Pydantic | >= 2.7.0 | v2; DomainBaseModel base class |
| SQLAlchemy | via Alembic | ORM + Unit of Work |
| Nox | >= 2025.4.22 | task runner |
| A2A error code range | -32001 to -32099 | application-specific |
| Local DB | SQLite | WAL mode for concurrent reads |
| Server DB | PostgreSQL | multi-tenant; same schema as SQLite |
| A2A wire format | JSON-RPC 2.0 | local=stdio; server=HTTP |
| Extension method prefix | _cleveragents/ | all platform operations |
| Streaming protocol | SSE | TaskStatusUpdateEvent, TaskArtifactUpdateEvent |
| Local TUI session DB | ~/.local/state/cleveragents/tui.db | separate from main data.db |
| TUI persona scope | TUI only | not visible to CLI or server |
| Devcontainer source | devcontainer.json | lazy-built on first access |
| v3.8.0 priority | not critical path | focus v3.2.0–v3.7.0 first |

---

## 📂 Reference Index

| Reference | Covers |
|-----------|--------|
| `references/plan-lifecycle/` | Detailed phase mechanics, decision tree storage schema, phase reversion rules, child plan execution modes, result merging, checkpointing detail |
| `references/entities/` | Complete data models for Plan, Decision, Action, Session, Invariant, Automation Profile, Safety Profile |
| `references/cli-commands/` | Complete CLI command reference with all flags and examples |
| `references/architecture/` | 4-layer architecture, A2A protocol (full method routing), DI container, tech stack, observability, security, extensibility |
| `references/automation-profiles/` | All 8 built-in profiles with threshold tables, Safety Profile, Automation Guard, Semantic Escalation |
| `references/resources/` | Complete resource type hierarchy (34+ types), DAG relationships, sandbox strategies, devcontainer integration |
| `references/actors-tools-skills/` | Actor YAML config schema, Jinja2 preprocessing, Tool YAML schema, Skill YAML schema, LSP integration |
| `references/acms/` | UKO ontology layers, CRP, Context Assembly Pipeline (all 10 slots), hot/warm/cold tiers, skeleton compression |
| `references/milestones/` | Detailed deliverables and constraints for each milestone v3.2.0–v3.8.0 |
