# Plan & Agent Modes — Strategic Analysis

**Status:** Active draft (2026-04-27)
**Owner:** Ben Booth
**Forcing context:** Axiom + Classroom must be a viable, compelling alternative to ChatGPT Codex / Claude Code / Cursor for the people we serve. Not "matches feature for feature" — *better on the dimensions our users actually need* (federation, classification, memory continuity, sovereignty).
**Related:** `prd-agents.md`, `spec-agent-architecture.md`, `working/competitive-parity-gaps.md`, `working/memory-roadmap.md`, `adr-033-layered-memory-architecture.md`, `spec-aeos-0.1.md`.

---

## 1. Why this document exists

Two pipeline modes have become table stakes in the agentic-IDE / agent-harness market:

- **Plan mode** — the agent proposes a structured plan before acting. Human reviews, edits, approves. Execution is gated on the approved plan.
- **Agent mode** — the agent executes autonomously through a multi-step task, calling tools, reading/writing files, recovering from errors. Human supervises rather than approves each step.

Codex (OpenAI), Claude Code (Anthropic), Cursor (Composer / Background Agents), Devin (Cognition), and Aider all ship some shape of these. Mastra and LangGraph ship the *primitives*. Our REPL agent framework ships the *agents* (AXI, SCAN, CURIO, PRESS, TIDY, TRIAGE) but **does not yet ship plan or agent modes as user-facing pipelines**.

The question this doc answers: **what should those modes look like for Axiom, given what we have, who we serve, and where we can credibly leap ahead?**

Three distinct readers should leave this doc with:

- **Implementer** — a pipeline architecture that fits ADR-033 memory, AEOS extensions, AskPipeline, and the federation primitives.
- **Reviewer / advisor** — a clear-eyed account of where we trail Codex/Claude Code and where we can credibly lead.
- **Skeptical instructor / operator** — confidence that "Axiom + NeutronOS + Classroom" can replace what they're using today, with capabilities they can't get there.

## 2. What we have to work with — inventory

Before chasing gaps, name the substrate. Most peer harnesses *don't* have these.

| Capability | Where it lives | What it gives plan/agent modes |
|---|---|---|
| **Layered memory (ADR-033)** | `axiom.memory.{events,graph,projections,federation}` | Plans become projections; execution becomes events; replay is free. |
| **AskPipeline** | `axiom.memory.ask` | Generic retrieval + composition + LLM call already factored. Plan/agent modes specialize via hooks, not forks. |
| **PromptComposer** | `axiom.infra.prompt_composer` | Seven-layer prompt construction (system + persona + memory + concept-expansion + retrieved + tool-spec + user) — already production-tested. |
| **CompositionService** | `axiom.memory.composition` | Single entry point for memorable writes. Every plan-step + tool-call lands here with provenance. |
| **AEOS skills + tools** | `spec-aeos-0.1.md §4`, `axi ext` runtime | Tools are declared, signed, classification-stamped. Plans reference tool-IDs that are guaranteed-resolvable. |
| **Federation primitives** | `axiom.vega.federation.*` | Plans + agent runs can be projected across cohort nodes; multi-agent collaboration spans organizations. |
| **Classification + visibility horizons** | `spec-federation-policy.md` | Plans can be authored at one classification level and run at another (with downgrade gates). No peer harness has this. |
| **Trust profiles** | `axiom.vega.federation.trust` | Plan execution can be auto-approved, manually approved, or rejected based on declared profile. |
| **REPL agents (AXI / SCAN / CURIO / PRESS / TRIAGE / TIDY)** | `axiom.extensions.builtins.*` | Agent mode is fundamentally the AXI loop with structured planning + tool calls. We already ship the loop; we need the pipeline. |
| **MemoryStack bootstrap** | `axiom.memory.bootstrap` | One-call setup means plan/agent modes get full memory continuity across runs without ceremony. |
| **schema_version + cohort fixtures** | `working/memory-persistence-plan.md` | Plans authored today survive Axiom upgrades for years. Codex plans don't outlive a model deprecation. |

**The headline:** every peer harness builds plan/agent modes on top of *prompt engineering plus a tool-call loop*. We can build them on top of *memory + composition + federation* — which means our plans aren't ephemeral artifacts, they're first-class memory that other agents (and other cohorts) can read, fork, replay, and build on.

## 3. State of the field — what we're being compared to

A clear-eyed read on where each peer is strong:

### 3.1 Plan mode

- **ChatGPT Codex** — "Reasoning trace + planned steps" surfaced before execution. User can accept, edit, or redirect. Plan rendered as collapsible UI; execution is one-shot per accepted plan.
- **Claude Code** — `ExitPlanMode` tool boundary makes planning explicit. Plan is markdown; user approves; execution proceeds. Plans support nested sub-tasks via `TaskCreate`.
- **Cursor Composer** — Plan is *the diff*. User sees proposed changes across files before any are applied; partial accept supported per-hunk.
- **Devin** — Plan is a tree of sub-goals; live-updating during execution; user can intervene mid-run.
- **Aider** — No formal plan mode. `--plan` flag prints reasoning; relies on tight diff loop.

**Common pattern:** plan = structured artifact (markdown / tree / diff). Approval = explicit gate. Execution = bounded by plan. Replay = reproduce *output*, not *plan derivation*.

### 3.2 Agent mode

- **Codex Agent** — Long-horizon execution in cloud sandbox; PR-creation as terminal step; multi-tool support; budget caps; "ask for help" interrupt.
- **Claude Code (general-purpose subagent)** — In-process subagent with tool access; isolated context; results returned to parent; supports background runs + worktrees.
- **Cursor Background Agents** — Async execution; cloud sandbox; PR-aware; integrated review loop.
- **Devin** — Most autonomous; full Linux VM; multi-day tasks; persistent workspace; weakest on safety.
- **Mastra / LangGraph** — Primitives, not products. Graph-based agent flows with checkpoint resume + HITL nodes.

**Common pattern:** sandbox + tools + loop + interrupt. Async execution increasingly default. PR-creation is the terminal artifact in coding contexts. *None* of them treat agent runs as memory; runs are logs, not first-class fragments.

### 3.3 What they all share — and what they all miss

All five **share**: tool-call loop, system prompt + retrieval, optional plan gate, optional sandbox, optional async. The differentiation among them is largely UX polish + ecosystem.

All five **miss** (or treat as afterthought):
- **Cross-agent collaboration** beyond single-tenant. Codex can't hand off to a peer's Codex.
- **Classification awareness** in the plan/run itself. CUI/EAR/ITAR is not a primitive.
- **Plans as durable, queryable memory.** Plans are files or session blobs.
- **Replay determinism** as an architectural property. They mostly aim for "approximate reproduction."
- **Federated inference choice** at the plan level. Claude Code uses Anthropic models; Codex uses OpenAI.
- **Pedagogical surfaces** — agents aware of learner mode, course context, instructor approval gates.
- **Cohort persistence** — plans authored under one model version are not guaranteed readable a year later.

These are the seams we walk through.

## 4. The plan mode design space — what good looks like for Axiom

### 4.1 What a plan *is*, in Axiom

A plan is a **MemoryFragment of cognitive_type=`procedural` (plan subtype)** containing:

- An ordered list of *steps* (each a structured object: goal, tool refs, inputs, outputs, gates).
- Optional *sub-plans* (each itself a plan fragment, referenced by ID).
- A *classification stamp* and *visibility horizon* matching the highest level of any step.
- A *target principal* — who or what executes (agent ID, role, federation peer).
- A *replay envelope* — the inputs needed to re-derive the plan deterministically (DPM-aligned).

This means a plan is:
- **Auditable** — provenance + signatures + immutable history (per ADR-033).
- **Queryable** — projections can answer "show me every plan that involved tool X" or "every plan in this scope from the past month."
- **Replayable** — re-running the plan derivation on the same inputs reproduces the same plan.
- **Federable** — plans can be projected to peer cohorts subject to classification + visibility rules.

### 4.2 The Plan pipeline — proposed shape

```mermaid
flowchart TD
    classDef input fill:#1f3a5f,color:#e6f0ff,stroke:#3b6fa8
    classDef proc fill:#1a4f3a,color:#e6fff0,stroke:#2f7a5c
    classDef gate fill:#5f3a1a,color:#fff0e6,stroke:#a86f3b
    classDef store fill:#3a1a5f,color:#f0e6ff,stroke:#6f3ba8
    classDef out fill:#5f1a3a,color:#ffe6f0,stroke:#a83b6f

    user[User: goal text + scope]:::input
    composer[PromptComposer<br/>+ AskPipeline retrieval]:::proc
    llm[LLM: derive plan]:::proc
    plan_frag[Plan fragment<br/>cognitive_type=procedural]:::store
    gate{Approval gate<br/>RACI / TrustProfile}:::gate
    exec[Hand off to Agent pipeline]:::out
    edit[User edit<br/>creates new plan version]:::input

    user --> composer --> llm --> plan_frag
    plan_frag --> gate
    gate -- approve --> exec
    gate -- edit --> edit
    edit --> plan_frag
    gate -- reject --> reject[End]:::out
```

Concretely:

```python
@dataclass(frozen=True)
class PlanRequest:
    goal: str
    scope_id: str
    principal_id: str
    target_classification: ClassificationStamp = unclassified
    target_horizon: VisibilityHorizon = SCOPE_INTERNAL
    constraints: Mapping[str, object] = ...   # budget, time, tool allowlist
    parent_plan_id: str | None = None         # for sub-plans

@dataclass(frozen=True)
class PlanStep:
    step_id: str
    intent: str                                # natural-language goal
    tool_id: str | None                        # AEOS tool ref
    inputs: Mapping[str, object]
    expected_outputs: Sequence[str]
    gate: Literal["auto", "approve", "manual"]
    on_error: Literal["abort", "skip", "ask"]

@dataclass(frozen=True)
class Plan:
    plan_id: str
    request: PlanRequest
    steps: Sequence[PlanStep]
    classification: ClassificationStamp
    horizon: VisibilityHorizon
    derived_from: Sequence[str]                # fragment IDs in evidence
    replay_envelope: Mapping[str, object]      # DPM-aligned reproducibility
```

### 4.3 Key design choices

- **Plan derivation reuses AskPipeline** — same retrieval + composition + LLM. New mode = new hooks (`PlanHooks`), not a fork. (Keeps the "single path" invariant from feedback memory.)
- **Steps reference AEOS tool IDs** — not free-text tool names. If the tool isn't installed/signed at execution time, the gate fails closed.
- **Approval is RACI-typed** — "Responsible / Accountable / Consulted / Informed" maps onto plan gates. A step can require A-level approval; the system knows who that is.
- **Plan edits create new versions, never mutate.** Append-only. Every edit is a new fragment that supersedes the prior with explicit `replaces:` provenance.
- **Sub-plans are normal plans** — composable; a plan can call out to another plan as a step.

## 5. The agent mode design space — what good looks like for Axiom

### 5.1 What an agent run *is*, in Axiom

An agent run is **a sequence of MemoryFragments** (each a tool call, a thought, an artifact, an error) bound to a parent plan and a `run_id`. The run is:

- A first-class queryable entity (`projection: agent_runs`).
- Streamed live to subscribers (gateway-level WebSocket / SSE).
- Resumable from any checkpoint (because every step is durable in the event log).
- Federated-aware (the run can hand off to a peer agent across cohort boundaries).

### 5.2 The Agent pipeline — proposed shape

```mermaid
flowchart TD
    classDef input fill:#1f3a5f,color:#e6f0ff,stroke:#3b6fa8
    classDef loop fill:#1a4f3a,color:#e6fff0,stroke:#2f7a5c
    classDef tool fill:#5f3a1a,color:#fff0e6,stroke:#a86f3b
    classDef store fill:#3a1a5f,color:#f0e6ff,stroke:#6f3ba8
    classDef gate fill:#5f1a3a,color:#ffe6f0,stroke:#a83b6f

    plan[Approved Plan]:::input
    init[Run init: write run_started fragment]:::store
    step[Read next step]:::loop
    compose[PromptComposer:<br/>plan + memory + concept-graph + tool-spec]:::loop
    llm[LLM: choose action]:::loop
    invoke{Action type?}:::loop
    tool_call[Tool invocation<br/>via AEOS runtime]:::tool
    write[Write event: thought / call / result]:::store
    check{Run gate?}:::gate
    interrupt[User interrupt /<br/>peer A2A handoff]:::input
    done[Run terminal:<br/>success / abort / handoff]:::store

    plan --> init --> step --> compose --> llm --> invoke
    invoke -- tool --> tool_call --> write --> check
    invoke -- thought --> write
    invoke -- done --> done
    check -- continue --> step
    check -- pause --> interrupt
    interrupt --> step
    check -- abort --> done
```

Concretely:

```python
@dataclass(frozen=True)
class AgentRunRequest:
    plan_id: str
    principal_id: str
    sandbox: SandboxSpec | None
    interrupt_policy: InterruptPolicy = "user_signal_only"
    max_steps: int = 100
    budget: BudgetSpec | None = None

class AgentPipeline:
    memory_stack: MemoryStack
    composer: PromptComposer
    llm: LLM
    tool_runtime: AEOSToolRuntime
    sandbox: Sandbox
    hooks: AgentHooks                          # extension specialization

    def run(self, req: AgentRunRequest) -> AgentRunResult:
        run = self._init_run(req)
        while not run.terminal:
            step = self._next_step(run)
            action = self._derive_action(run, step)
            result = self._execute(action, run)
            self._write_event(run, action, result)
            if self._should_pause(run):
                self._await_continue(run)
        return self._finalize(run)
```

### 5.3 Key design choices

- **Agent runs reuse AskPipeline + PromptComposer.** Same composition primitives; new hooks (`AgentHooks`) for run-loop specialization (mode resolution, gate logic, peer handoff).
- **Every event is a memory write.** No separate "logs" path — logs *are* fragments with `cognitive_type=episodic` and `kind=agent_event`. Replay = replay of memory, not of stdout.
- **Tools are AEOS-resolved at runtime.** Plan references tool ID; runtime looks up the signed extension; classification-stamped invocation is checked at every call.
- **Interrupts are first-class fragments.** A user interrupt or a peer A2A handoff lands as an `interrupt_received` event with full provenance. The run can resume cleanly.
- **Sandboxing is policy-pluggable.** No sandbox for read-only intent; ephemeral container for write-bounded; full VM for long-horizon. The sandbox class is a `TrustProfile` consequence, not a separate config.

## 6. Parity gaps — what must land for credibility

Pulled from `working/competitive-parity-gaps.md` + the survey above. These are *threshold* items — without them, Codex looks more capable.

| Gap | Why it matters for plan/agent modes | Cost | Recommended phase |
|---|---|---|---|
| **Plan visualization UI** (collapsible tree, inline diff for code-touching steps) | Approval gate is unusable without it. | Medium | Phase 1 (MVP) |
| **Async / background execution** | Agent runs that take >30s are common. Blocking REPL is a non-starter. | Medium | Phase 1 |
| **Sandboxing primitives** (read-only, ephemeral container, VM) | Without this we can't run untrusted plans safely. | Large | Phase 2 |
| **Streaming + interrupt** | Esc-to-halt during agent run; live-edit mid-stream. | Medium | Phase 1 |
| **Cost / budget tracking** | Budget caps per run; per-session token totals. | Small | Phase 1 |
| **PR-creation tool** (or equivalent terminal artifact) | Codex's terminal step is `gh pr create`. We need an analog — `axi plan ship` or similar. | Small | Phase 2 |
| **HITL approval at runtime** | Plans need mid-execution approval points, not just up-front. | Large | Phase 2 |
| **Tool ecosystem breadth** (filesystem, shell, browser, search, code-edit) | Without these, agent mode is academic. | Medium | Phase 1 (MVP set) |
| **Diff-review UI for edits** | Cursor Composer's per-hunk accept; Claude Code's diff display. | Medium | Phase 2 |
| **Cancellation + recovery on tool failure** | Typed fallback per `on_error` in PlanStep. | Small | Phase 1 |
| **Repo-aware planning** (knows current branch, working tree, recent commits) | A plan that ignores git state is worse than no plan. | Small | Phase 1 |

**MVP cut:** Phase 1 items only. The product needs to *feel* like Codex/Claude Code on day one for the 80% case. Phase 2 closes the rough edges.

## 7. Leap-ahead opportunities — where Axiom can lead, not just match

These are the bets that make Axiom + NeutronOS + Classroom *actually compelling*, not just "another harness."

### 7.1 Federated agent collaboration — A2A as native primitive

**The bet:** an agent running in Prague's cohort can hand off a sub-task to an agent running in Austin's cohort, with classification + visibility enforced at the gateway. The receiving agent's run is part of the same `run_id` lineage. Results federate back automatically.

**Why peers can't:** Codex / Claude Code / Cursor are single-tenant. There is no protocol for cross-tenant agent handoff with policy enforcement.

**What we ship:** A2A protocol (already stub'd in `axiom.federation.a2a`) + run lineage that crosses cohort boundaries + projection-time enforcement at the federation gateway.

**User-visible win:** "I'm a student in Prague. My agent doesn't know our local reactor's primary loop pressure, but Austin's research agent does. Hand off, get the answer, come back, finish my plan." This is impossible in Codex.

### 7.2 Classification-aware skill marketplace

**The bet:** every AEOS skill carries a classification capability; plans authored at higher classification *automatically downscale* allowed skills; skills authored at higher classification are auto-redacted in lower-classification projections.

**Why peers can't:** classification is policy-grafted-on-top, not architecture. None of them treat ITAR / EAR / Part 810 as primitives.

**What we ship:** classification field on SkillManifest; downscale projection at plan-time; audit trail per classification cross.

**User-visible win:** the same plan template runs unchanged at unclassified, CUI, and Part 810 — with skill set narrowing automatically. Operators don't have to maintain three plan libraries.

### 7.3 DPM-aligned plan replay

**The bet:** a plan + its replay envelope reproduces byte-equivalent outputs on the same inputs, even six months later, even on a newer model — because the model + temperature + retrieval cutoff are all part of the envelope.

**Why peers can't:** they're prompt-engineering-shaped. Replay = "approximate," not deterministic. Codex plan from 2026-01 is unrunnable in 2026-07 if the model deprecates.

**What we ship:** `replay_envelope` field on Plan; pinned model snapshots (via federated inference); fixture-tested replay in compliance suite.

**User-visible win:** "I authored this plan during my MS in 2026. I can re-run it for my PhD in 2029 and get the same answer." This is a research-integrity property.

### 7.4 Pedagogical agents — plan/agent mode as teaching surface

**The bet:** Classroom-aware agent modes can run in *tutor*, *quiz*, *reflect*, or *review* mode (already shipped per Tier C progress). The same plan template, four pedagogical surfaces. Instructor sees aggregate; student sees individualized.

**Why peers can't:** Codex doesn't know what a course is. Claude Code's subagents have no notion of learner state.

**What we ship:** ClassroomAgentHooks specializing AgentPipeline (mirrors the ClassroomAskHooks pattern from task #63). Mode resolution at run time. Instructor dashboard projections.

**User-visible win:** The instructor's NE 101 students in Prague get an agent that *teaches* — not one that does their homework.

### 7.5 ModelStrategy — runtime-resolved LLM assembly

**The bet:** a plan does not pick *one* model — it declares a `ModelStrategy` that, at each step, dynamically resolves the right *assembly* of LLM calls given the current environment, the user's preferences, the step's intent, the classification of the inputs, the available endpoints, and the budget remaining. One step might use Bonsai-1.7B locally for routing + a Rascal-hosted Qwen for the actual generation + a public frontier model for a final polish pass — all transparently, with the plan unchanged.

**Why this is more than "pick a model":**

- *Composition over selection.* Modern agentic work is rarely one model call; it's a router → planner → executor → verifier chain. The strategy resolves *which model plays which role* per step.
- *Environment-aware.* On a Workstation with no VPN, the strategy degrades gracefully (no public-tier calls, no Rascal). On Platform tier with full federation, it lights up the full assembly.
- *Classification-gated.* CUI inputs cannot leave the network boundary. The strategy is the enforcement point — not a check bolted on after model selection.
- *Cost-aware.* Budget remaining shapes resolution: cheap routing model when budget is tight; frontier model when the step is high-stakes and budget is fresh.
- *Federation-aware.* A peer cohort might be running Qwen-72B that we don't host. The strategy can route a step there subject to A2A trust profile.

**Why peers can't:** Codex = OpenAI. Claude Code = Anthropic. Cursor lets you pick a model from a dropdown. None compose model assemblies; none classification-gate at the strategy layer; none federation-aware.

**What we ship:** Extend `spec-model-routing.md` with a `ModelStrategy` section (existing two-tier router becomes the simplest concrete strategy). Add `model_strategy` field on Plan + per-PlanStep override. Resolution at step-execution via `axiom.federation.inference` (ADR-030) consulting: classification stamp of step inputs, current network reachability, declared user/cohort policy, budget remaining, available endpoints (local + federated). Audit trail records the resolved assembly per step.

**User-visible win:** A Prague instructor says "use the cheapest local model that's good enough; never let CUI leak; if a step needs frontier reasoning and budget allows, route to Anthropic — but never for student-data-touching steps." That's a 3-line strategy declaration, not three weeks of router code.

**Spec home:** Amend `spec-model-routing.md` with §6 ModelStrategy. Cross-reference from this doc + ADR-030 + ADR-033 (memory carries the resolved-strategy audit per step).

### 7.6 Proof-bound plan steps — status tied to evidence

**The bet:** every PlanStep has a `proof` field declaring *what would constitute success*, and the step's status is gated on producing that proof. "Done" is not a flag; it's a verification artifact bound to the step.

**Concretely:** a step's proof can be:

- A **test-case proof** — named test(s) pass; output captured.
- A **type-check proof** — file compiles / passes linter / typechecker.
- A **structural proof** — diff matches a declared shape (file X exists, function Y has signature Z).
- A **retrieval proof** — the answer cites N fragments that meet a recency / relevance threshold.
- A **peer-attestation proof** — another principal (human or agent) signs the result.
- A **replay proof** — the step's output is byte-equivalent to a prior pinned run on the same inputs.
- A **null proof** — explicitly declared "best effort, no verification" (audit-visible).

```python
@dataclass(frozen=True)
class PlanStep:
    # ... existing fields
    proof: ProofSpec                          # what counts as done
    status: Literal[
        "pending", "running", "blocked",
        "proof_attempted", "proof_failed",
        "verified", "skipped", "null_proof"
    ]
    proof_artifacts: Sequence[str] = ()       # fragment IDs of proof evidence
```

**Why this is a leap-ahead:** Codex/Claude Code mark steps "done" when the LLM says they are. There's no machine-checkable predicate. Our maturity model already values *validated* knowledge — extending that discipline to plan steps means a "completed plan" is a plan whose every step has produced verifiable evidence. That's a research-grade property, and a regulatory-grade property.

**Why it's worth the cost:** every regulated workflow we touch (NRC submissions, lab-notebook-style research, classified analysis) requires evidence trails. Proof-bound steps *are* the evidence trail, generated as a side-effect of execution.

**Edge case — null proof.** Some steps genuinely can't be machine-verified ("draft a one-page summary"). We don't block those — we mark them `null_proof` explicitly. The audit shows which steps were verified vs. accepted-on-trust; reviewers see exactly where their attention is needed.

**What we ship:** `ProofSpec` protocol; built-in proof types (test, typecheck, structural, retrieval, attestation, replay, null); CLI: `axi plan verify <plan_id>` runs all pending proofs; projection: `unverified_steps_by_principal`.

**Spec home:** New section in plan/agent pipeline spec (Phase 0). Cross-references the maturity model — proof artifacts naturally promote into knowledge-fact candidates.

### 7.7 Human-principal binding — every agent action accountable to a human

**The bet:** every agent run, every tool call, every memory write is bound to *both* the AI persona that did the work and the *human principal who is accountable for it*. The human binding is not a session-cookie convenience — it's a load-bearing primitive in the architecture, surfaced everywhere the AI persona is surfaced.

**Why this is *the* differentiator:** agentic systems are converging on a future where AI work is unattributable mush. "ChatGPT did it" has no accountability geometry. Axiom's commitment is the inverse: *no AI action exists without a named human standing behind it.* That commitment, made architectural rather than aspirational, is what wins us regulated, educational, and government-aligned cohorts.

**What changes vs. the current model:**

- Today: `MemoryFragment.principal_id` is one principal. If an agent acts, the agent is the principal.
- Proposed: `MemoryFragment.principal_id` (the actor — agent or human) **plus** `accountable_human_id` (the human whose authority the actor invokes). Always populated. Never null. The accountable-human is the human who initiated the chain (or to whom delegation was explicitly made).

```python
@dataclass(frozen=True)
class MemoryFragment:
    # ... existing
    principal_id: str                          # who did the work (may be agent)
    accountable_human_id: str                  # human standing behind the action
    delegation_chain: Sequence[str] = ()       # principals between human → actor
```

**Plan-level:** `Plan.accountable_human` is mandatory. Every step inherits unless explicitly delegated to a different human (with that human's signature in the delegation chain).

**Agent-mode level:** an agent run carries the accountable-human throughout. Cross-cohort A2A handoff *requires* the receiving cohort to record the originating human, even if their local agent is the actor.

**UI/UX consequences:**
- Every agent message shows "this is `agent: AXI` acting under `accountable: ben:utexas`."
- Every tool call shows the accountable human in audit logs.
- Every projection can answer "show me everything done under my accountability" — for any human.
- Retraction (per spec-memory §3.6) is now anchored: a human can retract control over derivations made *under their accountability*, even if the actor was an agent.

**Why peers can't:** Codex's accountability ends at the OpenAI account. Claude Code's at the local user. Neither propagates the accountable human across federation, classification, or extension boundaries.

**Spec home:** New ADR — *ADR-035: Human-Principal Binding* — codifying this as architectural invariant. Touches: `MemoryFragment` schema (schema_version bump per persistence plan), CompositionService write path, federation policy (gateway records accountable-human per projection), every agent extension.

This is significant; it deserves its own ADR + amendments to spec-memory and spec-federation-policy. **Recommend:** elevate to peer-level differentiator alongside ADR-033, and begin spec drafting in parallel with Phase 1.

### 7.8 Memory bounding & knowledge-maturity unification

**The bet:** Axiom is aggressive about writing memory — every plan derivation, every step, every tool call, every interaction. That aggression is only safe if memory is bounded, rolled, and matured. This is the second half of the deal.

**What we already have:**

- `spec-rag-knowledge-maturity.md` — Layers 0-5 (Data → Patterns → Facts → Frameworks → Application → Wisdom) with promotion gates, SCAN crystallization, TIDY sweep, regression closure.
- ADR-033 layered memory — event log + concept graph + projections + federation policy.
- Schema versioning + cohort fixtures (persistence plan).

**What's not yet bridged:** the maturity model was written for RAG (chunk-level promotion). Post-ADR-033, *all memory* should follow it — including agent runs, plan steps, tool outputs, conversational fragments. The maturity model needs to be **promoted from a RAG concern to a unified-memory concern**.

**Concrete bounding mechanisms (proposed):**

| Mechanism | What it does | Where it applies |
|---|---|---|
| **Tiered retention** | Layer 0 (raw events) retained per-scope policy: hot for 30d, cold for 1yr, archive forever. Layer 1+ retained indefinitely (they're the durable knowledge). | All memory |
| **TIDY sweep** | Periodic compaction: cold events with no L1+ derivative are candidates for archive. Tombstones replace bytes; provenance preserved. | Memory + agent runs |
| **Promotion gates** | L0→L1: retrieval frequency. L1→L2: SCAN crystallization. L2→L3: CURIO synthesis + human review. Plan-step proofs are first-class L2 candidates. | All cognitive types |
| **Forgetting** | Per spec-memory §3.6: a human can request derivation-stoppage on fragments under their accountability. Original event preserved (audit), but no further L1+ promotion. | All memory |
| **Cohort archival** | When a cohort closes (Prague's class ends), its memory enters cold + read-only mode. Still queryable, still federable — but no new writes. | Cohort-scoped memory |
| **Concept-graph pruning** | Stale concepts (no recent fragment, no recent edge) drop to deprioritized tier. Re-promoted on touch. | Layer 2 |
| **Classification expiry** | Some classification stamps have explicit declass dates (CUI 25-year rule, some EAR controls). Memory carries the date; projections enforce. | Classified memory |

**Why this matters for plan/agent modes:** if we ship plan + agent modes that write 50× more fragments than today, *and* we do not have a unified bounding story, we will fill disks, slow projections, and lose the maturity discipline. The bounding story must ship *with* plan/agent modes, not after.

**What we ship:** Amend `spec-rag-knowledge-maturity.md` to cover unified memory (rename or split: `spec-memory-maturity.md`); promote the TIDY sweep + SCAN crystallization into platform-level operations (not RAG-only); add cohort archival to ADR-033 phasing; wire plan-step proofs into L2 facts naturally.

**Spec home:** Amendment to `spec-rag-knowledge-maturity.md` + cross-reference into spec-memory + ADR-033. New compliance test: cohort retention policy round-trip.

### 7.9 Cohort persistence — plans outlive Axiom releases

**The bet:** every plan carries `schema_version`; the persistence plan's decoder registry guarantees readability across Axiom upgrades for years.

**Why peers can't:** their plans are session-scoped or ephemeral.

**What we ship:** `schema_version` extension to Plan + AgentRun fragments (per `working/memory-persistence-plan.md`); compliance-suite test that pinned plan fixtures decode under every release.

**User-visible win:** Prague cohort 2026 plans are still queryable + replayable in 2029 when the next cohort comes through.

### 7.10 Plans as composable memory

**The bet:** plans are queryable like any fragment — concept-graph expansion can find related plans by topic; projections can summarize "every plan in scope X this month"; A2A peers can request peer plans subject to visibility horizon.

**Why peers can't:** plans are not memory. They're transient artifacts.

**What we ship:** This is mostly *free* given ADR-033. The work is registering plan + agent_run as native cognitive types and exposing the right projections.

**User-visible win:** "Show me every plan in the past three months that touched the safety analysis tool." Codex cannot answer this.

## 8. Recommended architecture — concrete proposal

### 8.1 Module layout

```
src/axiom/
  agents/
    pipeline/
      __init__.py
      plan.py              # PlanRequest, Plan, PlanStep, PlanPipeline
      agent.py             # AgentRunRequest, AgentRun, AgentPipeline
      hooks.py             # PlanHooks, AgentHooks protocols
      replay.py            # ReplayEnvelope, replay derivation
      sandbox.py           # SandboxSpec, sandbox runtime adapters
      gates.py             # Approval gates, RACI integration
    runs/
      projections.py       # agent_runs projection
      streaming.py         # SSE/WebSocket adapter
```

### 8.2 Layered alignment with ADR-033

| ADR-033 layer | Plan/Agent role |
|---|---|
| **Event log + Blob store** | Every plan derivation, plan version, agent step, tool call, interrupt = an event. Large outputs (tool stdout, fetched docs) = blobs. |
| **Concept graph** | Plans extract concepts (goal nouns, tool refs, classification subjects). 1-hop expansion at plan-derivation surfaces related prior plans. |
| **Projections** | `plan_summaries`, `active_runs`, `run_telemetry`, `cost_by_principal`. Cheap reads; expressive queries. |
| **Federation policy** | Plans + runs project across cohorts subject to VisibilityHorizon + ClassificationStamp. A2A handoff is a federation projection. |

### 8.3 AskPipeline / PlanPipeline / AgentPipeline relationship

```mermaid
flowchart TD
    classDef shared fill:#1a4f3a,color:#e6fff0,stroke:#2f7a5c
    classDef plan fill:#5f3a1a,color:#fff0e6,stroke:#a86f3b
    classDef agent fill:#3a1a5f,color:#f0e6ff,stroke:#6f3ba8
    classDef ext fill:#1f3a5f,color:#e6f0ff,stroke:#3b6fa8

    composer[PromptComposer]:::shared
    memory[MemoryStack:<br/>events / graph / projections]:::shared
    llm[LLM gateway]:::shared

    ask[AskPipeline]:::shared
    plan[PlanPipeline]:::plan
    agent[AgentPipeline]:::agent

    classroom_ask[ClassroomAskHooks]:::ext
    classroom_plan[ClassroomPlanHooks]:::ext
    classroom_agent[ClassroomAgentHooks]:::ext

    ask --> composer
    ask --> memory
    ask --> llm
    plan --> ask
    plan --> composer
    agent --> plan
    agent --> ask
    agent --> composer

    classroom_ask --> ask
    classroom_plan --> plan
    classroom_agent --> agent
```

The point: **AskPipeline is the substrate.** PlanPipeline composes Ask + a derivation step. AgentPipeline composes Plan + an execution loop. Every extension specializes via hooks at any layer. We do *not* build three parallel paths.

### 8.4 Where things hook to existing systems

- **CompositionService** receives every plan + run fragment.
- **AEOS toolruntime** is the only path to invoke tools — no shell-out from agent code.
- **TrustProfile** drives gate auto-approval thresholds.
- **Federation gateway** (Stage 5a in memory roadmap) is the egress for cross-cohort projection of plans + runs.
- **Concept graph** powers "find related plans" + "concept-aware retrieval at plan derivation."
- **schema_version** on Plan + AgentRun (mandated by `working/memory-persistence-plan.md`).

## 9. Phased delivery — tied to memory roadmap

### Phase 0 — design ratification (now, ~2 weeks)

- This document → reviewed → frozen as a working spec.
- **ADR-034: Plan & Agent Pipeline Architecture** (codifies the AskPipeline / PlanPipeline / AgentPipeline layering).
- **ADR-035: Human-Principal Binding** (every action accountable; `accountable_human_id` mandatory; delegation chain; schema_version bump).
- **Spec amendments (in parallel):**
  - `spec-model-routing.md` §6 — ModelStrategy (per §7.5).
  - `spec-rag-knowledge-maturity.md` — promote to unified-memory maturity (per §7.8); rename or split as `spec-memory-maturity.md`.
  - `spec-aeos-0.1.md` — tool reach declarations + sandbox-as-enforcer vocabulary (per §10.2).
  - `spec-memory.md` + `spec-federation-policy.md` — accountable-human propagation across federation.
  - `spec-hooks.md` — reach-enforcement hook points.
- Stub `src/axiom/agents/pipeline/` with empty modules + protocol definitions.

### Phase 1 — Plan mode MVP (Prague-aligned, ~3 weeks)

- `PlanPipeline` derives + validates + persists plans (Ask-driven).
- Approval gate (no UI yet — CLI: `axi plan show`, `axi plan approve`, `axi plan reject`).
- Repo-state awareness in plan derivation (current branch, dirty state, recent commits as concept evidence).
- Cost / budget tracking per plan.
- Tool ID resolution against AEOS-installed extensions; fail-closed on missing.
- Compliance test: plan round-trip fixture + replay envelope determinism.

### Phase 2 — Agent mode MVP (post-Prague launch, ~4 weeks)

- `AgentPipeline` executes approved plans (single-step → multi-step → loop with interrupts).
- Streaming + interrupt over SSE.
- Sandbox adapters: read-only mode + ephemeral-container mode (VM mode deferred).
- Tool ecosystem MVP: filesystem, shell, code-edit (via existing `axi` extension surfaces), search.
- PR-creation tool wraps GitLab + GitHub.
- HITL gate at step boundary (`gate: approve` in PlanStep pauses run).
- Compliance test: pinned agent-run fixture replay + classification leak test.

### Phase 3 — Pedagogical + classroom integration (parallel with Phase 2)

- `ClassroomPlanHooks` + `ClassroomAgentHooks` (mirrors the AskPipeline pattern).
- Tutor / quiz / reflect / review modes wired through agent pipeline (already shipped in classroom; this rewires onto the pipeline).
- Instructor dashboard projection: `class_plans_by_student`, `run_outcomes_by_unit`.

### Phase 4 — Federation leap-ahead (post-Stage 5a federation gateway)

- A2A plan handoff: peer agent receives sub-plan, executes, returns result fragment lineage-bound to parent run.
- Cross-cohort plan visibility (subject to horizon + classification).
- Federated inference: model policy honored; cohort-level overrides enforced.

### Phase 5 — Visualization + polish

- Plan tree UI (HTML or rich.live console; UI is a separate decision per Prague-architecture-unresolved).
- Diff-review for code-touching steps.
- Live run dashboard.

## 10. Open questions — refined positions

Most of the §10 questions have been resolved (or sharpened) by the design discussion. Status now:

### 10.1 Plan visualization + .md surface — RESOLVED (console + .md, explicit-import only)

**Position:** Console-first (Rich live tree). **Plus** a markdown round-trip surface so plans are readable + editable in any IDE alongside `.git` state.

**The model: memory is canonical; `.md` is a render artifact OR an explicit-import draft. There is no file watcher and no automatic sync.** Every path into memory goes through a CLI command that runs the parser. Every path out of memory is an explicit render.

**The five flows:**

| Direction | Command | What happens |
|---|---|---|
| Create from goal | `axi plan new --goal "<text>"` | PlanPipeline derives → CompositionService writes fragment → `.md` rendered as artifact. Memory is canonical immediately. |
| Edit round-trip | `axi plan edit <id>` | Renders temp `.md` → opens in `$EDITOR` → on save+close, parser reads → CompositionService writes new version (supersedes). |
| External import | `axi plan import <path.md>` | User authored `.md` from scratch (template, colleague's plan, repo-committed). Explicit command parses → writes new fragment. From then on, that `.md` is a render of the fragment. |
| Read (one-way render) | `axi plan show <id>` | Renders to console + writes/updates `plans/<id>.md` in workspace. The `.md` carries a frontmatter banner: `rendered_from: <fragment_id>; edits ignored unless re-imported`. |
| Re-render | `axi plan refresh <id>` | Used when the fragment was updated by another path (e.g., agent run appended step results, plan was edited via CLI step commands). Re-renders the `.md`. |

**What this avoids:** the dreaded `.md` ↔ rdbms drift. There is no implicit binding between a file on disk and a row in storage. A user who edits a rendered `.md` directly without running `import` or `edit` has just modified a derived artifact — it has no effect on memory until they explicitly run a parser command. The frontmatter banner makes that visible.

**The friction this creates:** IDE save doesn't auto-sync. Acceptable trade-off because it's predictable + auditable. Mitigations available later, all of which preserve the explicit-import model:

- `axi plan watch <dir>` — foreground file watcher; auto-runs `import` on `.md` save in declared dirs. Off by default; opt-in for interactive authoring sessions.
- Git pre-commit hook — detects changed plan `.md` files; runs `import` before commit. Catches the "I edited and forgot" case at commit time.
- VS Code extension (Phase 5 polish) — integrates save hook in plan dirs.

None of these break the model; they're convenience triggers around the same parser path. Memory is always written through CompositionService; `.md` is never read implicitly.

**One subtlety: shared / committed plans.** When a `.md` is committed to a git repo and shared, the receiving user's local memory doesn't know about it until they run `axi plan import`. This is correct: each user's memory is a sovereign store; sharing a `.md` is like sharing a draft, not auto-installing it.

**Phase mapping:** console render + `axi plan show/new/edit/import/refresh` = Phase 1; `axi plan watch` = Phase 2; pre-commit hook = Phase 2 (template'd); web UI = Phase 5 (defer).

### 10.2 Tool runtime trust boundary — RESOLVED in framing, work pending

**Position:** Sandboxing is required for write-intent tools and for any tool whose extension manifest declares non-trivial filesystem or network reach. Read-intent tools that touch only declared-public memory don't need a sandbox.

**The bigger UX rethink (per feedback):** sandboxing is *inscrutable* to most users. People intuitively understand "what directories can this process crawl" and "can it call the internet." That's the surface we should expose — not "ephemeral container vs VM."

**Proposed UX layer:**

```
Plan step: "edit codebase to add metrics"
Reach declared:
  • read:  ~/repos/myproject/**
  • write: ~/repos/myproject/src/**
  • net:   none
Approve? [y/N]
```

The user sees *what the process can touch*. Implementation underneath = ephemeral container + bind mounts + network policy. We hide the box; show the reach.

**The OpenClaw blend:** we want the *power* of "agent does whatever it needs" without the *uncompromising-security loss*. The synthesis: declared reach is a **contract**, the sandbox is the **enforcer**. Agent declares reach in the plan; user approves the reach; sandbox enforces. Agent goes outside the contract → hard fail with audit.

**Phase mapping:** declared-reach UX in Phase 1 (plan-step `reach:` field; CLI prompt). Container enforcement in Phase 2. VM-class sandbox deferred unless a use case forces it.

**Spec home:** New section in spec-aeos covering tool reach declarations + reach-vs-sandbox vocabulary. Likely also amends `spec-hooks.md` since pre-tool hooks are where reach is enforced.

### 10.3 Replay envelope completeness — RESOLVED (best-effort + declare)

**Position:** Capture what we can; *explicitly declare what we can't*. The envelope has a `captured: [...]` and a `not_captured: [...]` list. A plan replay that depends on `not_captured` content is allowed but flagged in the audit.

Captured by default: model + temperature + system prompt + retrieved-fragments-set + tool versions + tool input args.
Not captured by default: tool RNG state, real-time external inputs (web fetches, current time), file-system snapshot beyond declared reach.

A plan can opt into deeper capture (`replay: deterministic-strict`) at the cost of slowness + storage. Default is `replay: best-effort`.

### 10.4 Plan editing UX — RESOLVED (IDE + .git + .md + CLI)

**Position:** Assume the user is in an IDE with `.git` context. Support **both** workflows:

- **Markdown workflow** — `axi plan show` renders `.md`; `axi plan edit` opens in `$EDITOR`; save → re-derive (per §10.1).
- **CLI workflow** — `axi plan step add/edit/remove/reorder <plan_id>` for surgical edits without round-tripping the whole plan.

Both produce the same outcome: a new plan version (append-only), superseding the prior.

**Why both:** the markdown surface is for readability + git-grade review; the CLI is for fast iteration during planning conversations. Users will mix. We don't pick.

### 10.5 Classification cross at plan time vs. step time — RESOLVED (step-time)

**Position:** Gate at step-execution, not plan-derivation. A plan can be authored at a low classification and have steps that legitimately need to escalate (e.g., "fetch this CUI doc to ground the answer"). The gate prompts at the moment the step would execute.

If the gate is rejected, the step is marked `blocked`; the plan continues with whatever steps don't depend on it (per the DAG).

**Caveat:** confirm with security review before Prague. The default is conservative; if review pushes for plan-time gate-and-refuse, we add it as a `policy.classification_gate: plan_time | step_time` setting.

### 10.6 Agent persona binding — RESOLVED (hint + override; *and human binding is mandatory*)

**Position:** Per persona — hint with override. Per accountable human — *mandatory and propagated*, per §7.7.

This open-question was originally framed at the AI-persona level. The deeper insight is that the *human* binding is the load-bearing one; the AI persona is the more flexible one. Reflected in §7.7.

### 10.7 A2A compatibility window — STILL OPEN

The §7.1 federated agent collaboration bet says "peer agent across cohort handoff." The question of *what visibility horizons + classification levels* actually federate in Phase 4 needs more thought.

Initial recommendation (SCOPE_INTERNAL → PEERS_DECLARED only) was conservative-by-default. Open considerations:

- **Cohort-pair contracts.** Maybe federation isn't a global setting but per-cohort-pair: Prague ↔ Austin federates at PEERS_DECLARED for plan-projections + REQUEST_GATED for run-events. Austin ↔ TACC federates at SCOPE_INTERNAL only. The contract is signed by both cohort coordinators and recorded.
- **Plan-handoff vs. run-event federation.** A plan-handoff is one fragment; a run handoff is N fragments. The granularity at which federation applies may differ.
- **Classification handoff requires re-stamping.** A CUI plan handed to an unclassified peer can't just project — it has to be downscaled or refused. Who decides?

**Recommend:** defer to Phase 4 design review with security + cohort coordinators in the loop. Don't pre-bake the policy in this analysis.

### 10.8 New: Memory bounding policy per cohort — OPEN

§7.8 establishes the *primitives*. The *defaults* per cohort profile are open:

- Edge: aggressive TIDY sweep, low retention, local-only L1+ promotion?
- Workstation: balanced.
- Server: extended retention; full maturity pipeline.
- Platform: federation-aware archival; cohort-pair retention contracts.

**Recommend:** ship Phase 1 with a single default + a config knob; tune per cohort during Prague + first post-Prague reflection.

## 11. Follow-on specs and ADRs — index

A quick map of where each new concept lands. None of these are written yet; this is the blueprint.

| Concept | Spec home | Phase |
|---|---|---|
| Plan + Agent pipelines | New: ADR-034 + section in `spec-agent-architecture.md` | 0 |
| Human-principal binding | New: ADR-035 + amendments to `spec-memory.md`, `spec-federation-policy.md`, AEOS | 0 |
| ModelStrategy | Amend: `spec-model-routing.md` §6 (existing two-tier router becomes the simplest concrete strategy) | 0–1 |
| Unified memory maturity | Amend or split: `spec-rag-knowledge-maturity.md` → `spec-memory-maturity.md` | 0–1 |
| Proof-bound plan steps | Section in plan/agent pipeline spec; cross-link to maturity model | 0–1 |
| Tool reach + sandbox UX | New section in `spec-aeos-0.1.md` + `spec-hooks.md` | 1–2 |
| Replay envelope | Section in plan/agent pipeline spec; aligned with `working/memory-persistence-plan.md` | 1 |
| Plan markdown round-trip | Section in plan pipeline spec + `spec-axi-cli.md` updates | 1 |
| A2A plan/run handoff | Amendment to federation specs; defer until Phase 4 | 4 |
| Cohort-pair federation contracts | New: working doc → spec; gate on Phase 4 | 4 |

## 12. Why this is the right time

Three forcing functions converge:

- **Memory layer is ready.** ADR-033 + AskPipeline + L2 evidence-table refactor + persistence plan = the substrate that makes plans-as-memory cheap. A year ago we'd be building this on sand.
- **Prague is live in ~6 weeks.** Plan mode for instructor brief + agent mode for student tutor are both Tier B/C-aligned; they ship before class start.
- **Codex / Claude Code / Cursor are normalizing the expectation.** The window for "Axiom doesn't have plan mode" being acceptable closes by mid-2026. Either we have something credible by then or we're the harness without the table-stakes feature.

The cost of Phase 0+1 is small (one ADR + one pipeline module) and almost entirely composes existing layers. The leap-ahead bets in §7 don't add cost — they're consequences of architecture we've already chosen.

## 13. The bottom line

Axiom does not need to *match* Codex's plan/agent surface. We need to *out-architect* it on the dimensions our users actually require: federation, classification, sovereignty, replay, persistence, pedagogy — and now, sharpened: **proof-bound steps**, **accountable-human binding on every action**, **ModelStrategy as runtime-resolved assembly**, **bounded-and-matured memory** as a discipline.

Codex is built for one company's customers writing one company's code. Axiom is built for cohorts that span institutions, classifications, and decades — *and where every AI action carries the name of a human who stands behind it.*

If we ship Phase 1 + Phase 2 by end of summer 2026, with Phase 3 wired through Classroom, and Phase 4 lighting up the federation leap-ahead, we have a credible answer to "why would I use NeutronOS+Classroom over Codex?" — and the answer isn't "feature parity," it's *"because Codex can't do this, and you actually need it."*
