Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

add mermaid architecture diagrams (#494)

kt2fe329ad752f
diff --git a/README.md b/README.md
index 1e8da17052..b9057724a7 100644
--- a/README.md
+++ b/README.md
@@ -85,6 +85,7 @@ prime-agent shutdown [--force] # Stop every agent, worker, and background
## Documentation
- [Documentation index](packages/coding-agent/docs/index.md)
+- [Architecture overview](packages/coding-agent/docs/architecture.md)
- [Quickstart](packages/coding-agent/docs/quickstart.md)
- [RLM programming model](packages/coding-agent/docs/rlm.md)
- [Long-running and background agents](packages/coding-agent/docs/long-running-agents.md)
diff --git a/packages/coding-agent/docs/agent-connection-readme.md b/packages/coding-agent/docs/agent-connection.md
similarity index 93%
rename from packages/coding-agent/docs/agent-connection-readme.md
rename to packages/coding-agent/docs/agent-connection.md
index b2959eccab..1c76f3c31b 100644
--- a/packages/coding-agent/docs/agent-connection-readme.md
+++ b/packages/coding-agent/docs/agent-connection.md
@@ -1,17 +1,20 @@
-# AgentConnection Architecture
+# Agent Connection Architecture
`AgentConnection` is the client-side boundary between an interactive user interface and the process that owns agent execution. It lets the terminal UI remain transport-agnostic while normal local sessions run in daemon workers.
The normal interactive path is:
-```text
-InteractiveMode
- -> AgentConnection
- -> DaemonAgentConnection
- -> local daemon protocol
- -> session worker
- -> AgentSessionRuntime
- -> AgentSession
+```mermaid
+flowchart LR
+ ui["InteractiveMode<br/>terminal UI"]
+ connection["AgentConnection<br/>client interface"]
+ adapter["DaemonAgentConnection<br/>transport adapter"]
+ protocol["Local daemon protocol<br/>commands · snapshots · events"]
+ worker["Session worker<br/>execution owner"]
+ runtime["AgentSessionRuntime"]
+ session["AgentSession"]
+
+ ui --> connection --> adapter --> protocol --> worker --> runtime --> session
```
Explicit fallback and embedding paths may use `InProcessAgentConnection`, but `InteractiveMode` still talks to the same interface.
@@ -47,7 +50,7 @@ On attach it advertises supported capabilities and receives a coherent session s
The adapter rejects duplicate or retired-generation events. After a transient socket loss it reconnects with the same client identity and last cursor, reattaches, and emits a resynchronized snapshot. If incremental replay is unavailable, the session snapshot is the source of truth.
-Current implementation:
+Key files:
- `src/modes/agent-connection/daemon-agent-connection.ts`
- `src/modes/daemon/daemon-client.ts`
@@ -59,7 +62,7 @@ Current implementation:
In-process startup can also provide `InteractiveModeLocalSessionHost` for local callback-bearing extension behavior. JavaScript functions and render callbacks never cross the generic connection boundary.
-Current implementation:
+Key files:
- `src/modes/agent-connection/in-process-agent-connection.ts`
- `src/modes/interactive/interactive-mode-services.ts`
@@ -83,7 +86,7 @@ Some connection types still reuse internal `AgentMessage`, `AgentEvent`, and mod
## Reconnect and Replay
-The local protocol already implements the recovery mechanisms that the original boundary design left for later work:
+Reconnect and recovery use the following mechanisms:
1. Commands use a stable client ID and command ID.
2. Mutations are journaled by `clientId + commandId`.
diff --git a/packages/coding-agent/docs/architecture.md b/packages/coding-agent/docs/architecture.md
new file mode 100644
index 0000000000..65b9c91bb6
--- /dev/null
+++ b/packages/coding-agent/docs/architecture.md
@@ -0,0 +1,93 @@
+# Architecture Overview
+
+Prime Agent separates terminal presentation, process coordination, agent execution, model-facing Python, and persisted state. Normal interactive sessions use the daemon-backed path below; explicit SDK and fallback integrations can run the same `AgentSessionRuntime` in process.
+
+## System at a Glance
+
+```mermaid
+flowchart LR
+ interactive["Interactive TUI"]
+ headless["Print · JSON · RPC clients"]
+ connection["AgentConnection<br/>client-side execution boundary"]
+ supervisor["Daemon supervisor<br/>routing · attachments · recovery"]
+ catalog["Catalog process<br/>saved-session scans"]
+
+ subgraph worker["Session worker · one root session tree"]
+ runtime["AgentSessionRuntime"]
+ root["Root AgentSession"]
+ scheduler["Scheduler"]
+ kernel["Root IPython kernel"]
+ children["RLM child runtimes<br/>session + optional kernel"]
+
+ runtime --> root
+ runtime --> scheduler
+ root --> kernel
+ root --> children
+ scheduler --> root
+ end
+
+ providers["Model providers"]
+ storage["Session JSONL + artifacts"]
+
+ interactive --> connection
+ connection <-->|"local daemon protocol"| supervisor
+ headless -->|"local daemon protocol"| supervisor
+ supervisor --> catalog
+ supervisor --> runtime
+ root <-->|"model streams"| providers
+ children <-->|"model streams"| providers
+ root --> storage
+ children --> storage
+```
+
+- The client owns rendering, keyboard input, and local UI preferences; it does not own execution.
+- The supervisor owns discovery, routing, attachments, worker health, and cross-agent message delivery.
+- Each worker owns one root runtime, its scheduler, kernels, and all descendants below that root.
+- `AgentSession` owns provider calls, queues, tools, compaction, goals, child lifecycles, and transcript writes.
+- IPython is the model-facing control environment. Typed host requests return authoritative operations to the TypeScript session.
+
+Workers and kernels are separate processes for lifecycle and failure containment, not security sandboxes. They normally run with the same operating-system permissions as the client.
+
+## Prompt Execution Flow
+
+```mermaid
+sequenceDiagram
+ participant U as User interface
+ participant C as AgentConnection
+ participant S as Supervisor
+ participant W as Session worker
+ participant A as AgentSession
+ participant P as Model provider
+ participant K as IPython kernel
+ participant D as Session storage
+
+ U->>C: prompt, steer, or follow-up
+ C->>S: versioned command
+ S->>W: route to active session
+ W->>A: enqueue prompt
+ A->>P: stream model request
+ P-->>A: text or IPython tool call
+ opt IPython tool call
+ A->>K: execute Python
+ alt Typed host request
+ K->>A: request host operation
+ A-->>K: host result
+ else Ordinary execution
+ K-->>A: result, stdout, or error
+ end
+ end
+ A->>D: append transcript and artifacts
+ A-->>W: session events
+ W-->>S: generation-aware events
+ S-->>C: live stream or recovery snapshot
+ C-->>U: render updated state
+```
+
+From the session queue onward, the same execution and persistence path is used when a prompt comes from a heartbeat, cron schedule, goal continuation, autonomous mode, or another agent instead of an attached user.
+
+## Detailed Architecture
+
+- [Agent Connection Architecture](agent-connection.md) explains the client/runtime boundary, snapshots, replay, and reconnect behavior.
+- [Daemon Architecture](daemon.md) covers process ownership, leases, scheduling, backpressure, and crash recovery.
+- [RLM Runtime Architecture](rlm-runtime.md) follows IPython host requests and recursive child execution.
+- [Long-Running and Background Agents](long-running-agents.md) shows how detached sessions, messages, goals, and scheduled work share the worker runtime.
diff --git a/packages/coding-agent/docs/daemon-implementation-summary.md b/packages/coding-agent/docs/daemon.md
similarity index 93%
rename from packages/coding-agent/docs/daemon-implementation-summary.md
rename to packages/coding-agent/docs/daemon.md
index 84b2d4dc2a..35e4ce9dd9 100644
--- a/packages/coding-agent/docs/daemon-implementation-summary.md
+++ b/packages/coding-agent/docs/daemon.md
@@ -1,18 +1,23 @@
-# Daemon and Session Worker Architecture
+# Daemon Architecture
Prime Agent isolates each active root session tree in its own process. The daemon is internal infrastructure: interactive, print, JSON, RPC, piped-stdin, and `--no-session` describe client behavior and retain their public I/O contracts.
## Process Topology
-```text
-interactive / print / JSON / RPC clients
- |
- v
- detached supervisor
- |- catalog subprocess
- |- resident worker: root A + RLM descendants + kernels
- |- resident worker: root B + RLM descendants + kernels
- `- client-owned worker: hidden root + RLM descendants + kernels
+```mermaid
+flowchart TD
+ clients["Interactive · print · JSON · RPC clients"]
+ supervisor["Detached supervisor"]
+ catalog["Catalog subprocess<br/>saved-session scans"]
+ residentA["Resident worker<br/>root A · RLM descendants · kernels"]
+ residentB["Resident worker<br/>root B · RLM descendants · kernels"]
+ owned["Client-owned worker<br/>hidden root · RLM descendants · kernels"]
+
+ clients <-->|"public local protocol"| supervisor
+ supervisor --> catalog
+ supervisor --> residentA
+ supervisor --> residentB
+ supervisor --> owned
```
The supervisor owns public sockets, client attachments, routing, global agent-message delivery, worker health, command journals, and coordinated updates. It does not execute providers, tools, compaction, bash, kernels, schedules, or transcript scans.
diff --git a/packages/coding-agent/docs/docs.json b/packages/coding-agent/docs/docs.json
index 6cee553ea3..8523c0923c 100644
--- a/packages/coding-agent/docs/docs.json
+++ b/packages/coding-agent/docs/docs.json
@@ -12,9 +12,21 @@
"path": "quickstart.md"
},
{
- "title": "Using Pi",
+ "title": "Architecture Overview",
+ "path": "architecture.md"
+ },
+ {
+ "title": "Using Prime Agent",
"path": "usage.md"
},
+ {
+ "title": "RLM Programming Model",
+ "path": "rlm.md"
+ },
+ {
+ "title": "Long-Running and Background Agents",
+ "path": "long-running-agents.md"
+ },
{
"title": "Providers",
"path": "providers.md"
@@ -61,7 +73,7 @@
"path": "themes.md"
},
{
- "title": "Pi Packages",
+ "title": "Prime Agent Packages",
"path": "packages.md"
},
{
@@ -137,16 +149,16 @@
"path": "development.md"
},
{
- "title": "AgentConnection Architecture",
- "path": "agent-connection-readme.md"
+ "title": "Daemon Architecture",
+ "path": "daemon.md"
},
{
- "title": "Kernel and RLM Recursion",
- "path": "kernel-and-rlm-recursion.md"
+ "title": "Agent Connection Architecture",
+ "path": "agent-connection.md"
},
{
- "title": "/refine Verification Log",
- "path": "refine-verification-log.md"
+ "title": "RLM Runtime Architecture",
+ "path": "rlm-runtime.md"
}
]
}
diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.md
index 3d8cb62f32..26ca856422 100644
--- a/packages/coding-agent/docs/index.md
+++ b/packages/coding-agent/docs/index.md
@@ -25,6 +25,7 @@ Public releases are currently installed from versioned release artifacts. The in
- [Quickstart](quickstart.md) - install, authenticate, and run a first session.
- [Using Prime Agent](usage.md) - interactive mode, RLM subagents, slash commands, context files, and CLI reference.
+- [Architecture overview](architecture.md) - client, daemon, worker, session, kernel, provider, and storage boundaries.
- [RLM programming model](rlm.md) - programmatic execution, native subagents, Python skills, and durable state.
- [Long-running and background agents](long-running-agents.md) - daemon workers, messaging, heartbeats, goals, schedules, and autonomous mode.
- [Providers](providers.md) - subscription and API-key setup for built-in providers.
@@ -67,6 +68,7 @@ Public releases are currently installed from versioned release artifacts. The in
## Development
- [Development](development.md) - local setup, configuration, debugging, and validation.
-- [Daemon and Session Worker Architecture](daemon-implementation-summary.md) - supervisor, catalog, worker, lifecycle, and recovery details.
-- [AgentConnection Architecture](agent-connection-readme.md) - client/runtime connection boundary.
-- [Kernel and RLM Recursion](kernel-and-rlm-recursion.md) - ZeroMQ kernel transport and recursive subagent execution.
+- [Architecture overview](architecture.md) - system topology and end-to-end prompt flow.
+- [Daemon Architecture](daemon.md) - supervisor, catalog, worker, lifecycle, and recovery details.
+- [Agent Connection Architecture](agent-connection.md) - client/runtime connection boundary.
+- [RLM Runtime Architecture](rlm-runtime.md) - ZeroMQ kernel transport and recursive subagent execution.
diff --git a/packages/coding-agent/docs/long-running-agents.md b/packages/coding-agent/docs/long-running-agents.md
index dbeb375cff..617a1294ed 100644
--- a/packages/coding-agent/docs/long-running-agents.md
+++ b/packages/coding-agent/docs/long-running-agents.md
@@ -2,6 +2,46 @@
Prime Agent combines daemon-backed session workers with persistent state, scheduled prompts, direct agent messaging, goals, and bounded autonomous continuations. These features serve different purposes but share the same session and worker runtime.
+## Runtime Flow
+
+```mermaid
+flowchart TD
+ client["TUI or CLI client"]
+ peer["Peer agent or retained subagent"]
+ supervisor["Daemon supervisor<br/>routing + attachments"]
+
+ subgraph worker["Resident session worker"]
+ heartbeat["User + RLM heartbeats"]
+ schedule["One-time + cron schedules"]
+ goal["Persistent goal"]
+ autonomous["Autonomous mode"]
+ policy["Continuation policy"]
+ queue["Session prompt queue"]
+ session["AgentSession"]
+ kernel["Persistent IPython kernel"]
+ children["RLM child sessions"]
+
+ heartbeat --> queue
+ schedule --> queue
+ goal --> policy
+ autonomous --> policy
+ policy --> queue
+ queue --> session
+ session --> kernel
+ session <--> children
+ end
+
+ artifacts["JSONL transcript + session artifacts"]
+
+ client <-->|"attach · detach · commands"| supervisor
+ peer -->|"direct message"| supervisor
+ supervisor --> queue
+ session --> artifacts
+ artifacts -. "restore after restart" .-> session
+```
+
+The client can detach at any point. The resident worker continues to own the queue, schedules, session, kernel, descendants, and persisted state.
+
## Daemon-Backed Sessions
Normal interactive sessions run in resident worker processes managed by a local supervisor. The worker owns the root session, its IPython kernel, scheduled jobs, and RLM descendants.
@@ -193,4 +233,4 @@ await compact.run("Preserve the failing tests and remaining migration steps")
Compaction is not a completion signal. It does not stop goals, autonomous continuations, heartbeats, or existing child sessions; later parent turns continue from the compacted context.
-For lower-level process and recovery behavior, see [Daemon and Session Worker Architecture](daemon-implementation-summary.md). For recursive child lifecycle details, see [RLM Programming Model](rlm.md) and [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).
+For lower-level process and recovery behavior, see [Daemon Architecture](daemon.md). For recursive child lifecycle details, see [RLM Programming Model](rlm.md) and [RLM Runtime Architecture](rlm-runtime.md).
diff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.md
index c6d6ae5c2d..2965a019cf 100644
--- a/packages/coding-agent/docs/quickstart.md
+++ b/packages/coding-agent/docs/quickstart.md
@@ -85,7 +85,7 @@ You can prompt the model to use that capability directly:
Review authentication and test coverage as independent subtasks. Run them in parallel, then synthesize the findings.
```
-See [Kernel and RLM Recursion](kernel-and-rlm-recursion.md) for the API and execution model.
+See [RLM Runtime Architecture](rlm-runtime.md) for the API and execution model.
## Give Prime Agent Project Instructions
diff --git a/packages/coding-agent/docs/refine-verification-log.md b/packages/coding-agent/docs/refine-verification-log.md
deleted file mode 100644
index 5d3dc2acaa..0000000000
--- a/packages/coding-agent/docs/refine-verification-log.md
+++ /dev/null
@@ -1,218 +0,0 @@
-# /refine verification log
-
-This log records manual benchmark-verification checks for Prime Agent continual
-harness features. It is intentionally artifact-oriented so later benchmark runs
-can replay the same surfaces.
-
-Current design note: refined prompt notes, memories, skills, subagent specs, and
-refinement events are session-local by default under the session harness
-directory (`RLM_HARNESS_STATE_DIR`, falling back to `RLM_SESSION_DIR/harness`);
-explicitly global refinement writes the global agent harness directory
-(`RLM_GLOBAL_HARNESS_STATE_DIR`, for example
-`~/.prime/agent/harness/harness_state.json`). Session JSONL entries still
-record refinement results for auditability and rollback evidence. A compact
-overview of the merged global and local harness state is injected into the
-default system prompt
-so the agent can use learned state without first calling `rlm.harness.overview()`.
-The model-facing `rlm.harness` API uses explicit `create_*`, `update_*`, and
-`delete_*` calls for memory, skill, subagent, and prompt-note entries.
-
-## 2026-06-08 manual CLI session
-
-- Branch: `continual-harness-capabilities`
-- Repo: `/Users/milkkarten/Research/prime-agent`
-- CLI launch: `./prime-agent.sh` in tmux session `PrimeAgentCLI`
-- Model shown by CLI: `openai/gpt-5.5`
-- Legacy session file (before sessions moved to the flat session store):
- `/Users/milkkarten/.prime/agent/sessions/--Users-milkkarten-Research-prime-agent--/2026-06-08T19-08-33-915Z_019ea8a2-fafa-741b-902a-c00b6b8b997d.jsonl`
-- Harness state file:
- `/Users/milkkarten/.prime/agent/sessions/--Users-milkkarten-Research-prime-agent--/2026-06-08T19-08-33-915Z_019ea8a2-fafa-741b-902a-c00b6b8b997d/harness_state.json`
-
-Historical note: this manual run happened before the harness store was switched
-from session-backed to global-by-default persistence and before session JSONL
-files moved to `~/.prime/agent/sessions/<session-id>.jsonl`.
-
-### Harness availability
-
-Prompt sent:
-
-```text
-Use exactly one IPython tool call to run: print(hasattr(rlm, "harness")); print(type(rlm.harness).__name__); print(rlm.harness.overview()). Then summarize whether harness access works.
-```
-
-Expected result:
-
-- `rlm.harness` is available to the model-facing callable object.
-- `type(rlm.harness).__name__` is `HarnessState`.
-- `rlm.harness.overview()` prints the active `harness_state.json` path.
-
-Observed result:
-
-- Pass after patching callable `rlm` to expose `harness` and
- `get_harness_state`.
-- Before that patch, the same prompt failed with
- `AttributeError: '_RLMCallable' object has no attribute 'harness'`.
-
-### Direct CRUD through `rlm.harness`
-
-Prompt sent:
-
-```text
-Use exactly one IPython tool call to create one prompt note, one memory, one skill, one subagent, and one refinement event in rlm.harness with ids prefixed manual_cli_test_. Print rlm.harness.overview() and summarize the created ids.
-```
-
-Expected result:
-
-- One prompt, memory, skill, subagent, and refinement event are persisted.
-
-Observed result:
-
-- Pass. Created `manual_cli_test_prompt`, `manual_cli_test_memory`,
- `manual_cli_test_skill`, `manual_cli_test_subagent`, and `refine_0001`.
-- Defect found: `record_refinement(..., "single change")` stored a character
- list because the helper called `list(changes)`. The runtime helper was patched to
- normalize a single string into a one-item list and added a Python unit test.
-
-### `/refine` create, update, delete
-
-Command sent:
-
-```text
-/refine benchmark verification: create prompt note manual_cli_test_refine_prompt saying manual CLI benchmark checks should capture state paths and validation commands; update skill manual_cli_test_skill to require npm run check after PrimeAgent code changes; delete memory manual_cli_test_memory; create subagent manual_cli_test_refine_subagent for reviewing refinement results and rollback safety.
-```
-
-Expected result:
-
-- Create prompt `manual_cli_test_refine_prompt`.
-- Update skill `manual_cli_test_skill`.
-- Delete memory `manual_cli_test_memory`.
-- Create or update subagent `manual_cli_test_refine_subagent`.
-- Append `prime-agent.refinement` custom session history with applied edits and
- before/after snapshots.
-
-Observed result:
-
-- Pass. The session file includes refinement records:
- `refine_20260608191027670` and `refine_20260608191328216`.
-- The harness state recorded memory deletion, skill update, subagent creation,
- and prompt-note creation.
-- Tmux paste-buffer did not reliably submit the command in the TUI; literal
- `tmux send-keys -l ... && tmux send-keys C-m` worked.
-- The first failed paste appears to have later queued duplicate/no-op refine
- attempts. The persisted history made this visible even when TUI status lines
- were not present in the captured pane.
-
-### `/refine rollback`
-
-Command sent:
-
-```text
-/refine rollback refine_20260608191328216
-```
-
-Expected result:
-
-- Append a new refinement with `rollbackOf: refine_20260608191328216`.
-- Restore before-snapshots for updated entries.
-- Delete entries created by the rolled-back refinement.
-
-Observed result:
-
-- Pass. The session file includes `refine_20260608191633157` with
- `rollbackOf: refine_20260608191328216`.
-- The harness state removed `manual_cli_test_refine_prompt`.
-- `manual_cli_test_skill` reverted to the earlier `npm run check when
- applicable` text.
-- `manual_cli_test_refine_subagent` reverted to its earlier review-focused
- content.
-
-### Immutable base system prompt guardrail
-
-Command sent:
-
-```text
-/refine benchmark guardrail test: attempt to update prompt id base_system_prompt with title Base system prompt and content SHOULD_NOT_APPLY. This should be rejected by the immutable base prompt guardrail; do not create alternate prompt ids.
-```
-
-Expected result:
-
-- No `base_system_prompt` entry in editable harness prompt notes.
-- No alternate prompt entry created.
-- Refinement history records a no-op or failed edit rationale.
-
-Observed result:
-
-- Pass. `base_system_prompt` is absent from `entries.prompt`.
-- The only prompt entry after rollback remained `manual_cli_test_prompt`.
-- The session file includes `refine_20260608191730440` with no applied edits and
- rationale explaining the immutable base prompt guardrail.
-
-## Validation commands
-
-Run these after changes to refinement or harness runtime code:
-
-```bash
-PYTHONPATH=prime-agent-runtime/src python3 -m unittest discover prime-agent-runtime/test
-npx tsx ../../node_modules/vitest/dist/cli.js --run test/refinement.test.ts
-npx tsx ../../node_modules/vitest/dist/cli.js --run test/system-prompt.test.ts
-npx tsx ../../node_modules/vitest/dist/cli.js --run test/kernel-bootstrap.test.ts
-npm run check
-```
-
-## Automated matrix coverage
-
-`packages/coding-agent/test/refinement.test.ts` covers the deterministic
-refinement engine used by both interactive `/refine` and RPC `refine`.
-`prime-agent-runtime/test/test_harness.py` covers the Python `rlm.harness`
-runtime store exposed to model IPython calls.
-
-Covered action/kind combinations:
-
-- `create prompt`
-- `create memory`
-- `create skill`
-- `create subagent`
-- `update prompt`
-- `update memory`
-- `update skill`
-- `update subagent`
-- `delete prompt`
-- `delete memory`
-- `delete skill`
-- `delete subagent`
-
-Covered validation and recovery cases:
-
-- Generated ids for create edits without ids.
-- Default `path`, `metadata`, `source`, and version handling.
-- Global harness state directory resolution under the agent dir.
-- Compact global harness overview injection into the default system prompt.
-- `/refine` usage guidance in the injected harness overview.
-- Bounded harness prompt injection with entry overflow and content truncation.
-- Persistence to and reload from `harness_state.json`.
-- Refinement history extraction from `prime-agent.refinement` custom entries.
-- Duplicate create rejection for every editable kind.
-- Missing update target rejection for every editable kind.
-- Missing delete target rejection for every editable kind.
-- Required title/content validation for create and update.
-- Required id validation for update and delete.
-- Unsupported action rejection.
-- Unsupported kind rejection.
-- Immutable `base_system_prompt` rejection.
-- Rollback restoration for one created entry, one updated entry, and one deleted
- entry in the same target refinement.
-- Missing rollback target error.
-- Python runtime create, read, update, list, and delete for prompt, memory,
- skill, and subagent entries.
-- Python runtime explicit `create_*`, `update_*`, and `delete_*` model-facing
- methods.
-- Python runtime default backing store through `RLM_HARNESS_STATE_DIR`.
-- Python runtime unknown-kind rejection for `upsert`, `get`, `delete`, and
- `list`.
-
-## 2026-07-01 correction
-
-When the entries above were recorded, `RLM_HARNESS_STATE_DIR` pointed at the
-global harness directory. Since local-by-default refinement landed, the global
-directory is `RLM_GLOBAL_HARNESS_STATE_DIR` and `RLM_HARNESS_STATE_DIR` is the
-session-local store (falling back to `RLM_SESSION_DIR/harness`).
diff --git a/packages/coding-agent/docs/kernel-and-rlm-recursion.md b/packages/coding-agent/docs/rlm-runtime.md
similarity index 89%
rename from packages/coding-agent/docs/kernel-and-rlm-recursion.md
rename to packages/coding-agent/docs/rlm-runtime.md
index 15e6510a22..b033eb2b3c 100644
--- a/packages/coding-agent/docs/kernel-and-rlm-recursion.md
+++ b/packages/coding-agent/docs/rlm-runtime.md
@@ -1,23 +1,23 @@
-# Kernel and RLM Recursion
+# RLM Runtime Architecture
Prime Agent gives each agent session a persistent IPython kernel and a native recursive sub-agent interface. The Python `rlm` package is a model-facing shim; the TypeScript host owns child execution, persistence, usage accounting, and lifecycle.
## Architecture
-```text
-AgentSession (TypeScript)
- |
- | owns the ipython tool and host request handlers
- v
-KernelManager (TypeScript)
- |
- | ZeroMQ / Jupyter protocol
- v
-IPython kernel process (Python)
- |
- | prime-agent-runtime installed as module "rlm"
- v
-model-executed Python code
+```mermaid
+flowchart TD
+ session["AgentSession · TypeScript<br/>IPython tool + host request handlers"]
+ manager["KernelManager · TypeScript<br/>execution + comm dispatch"]
+ kernel["IPython kernel process · Python"]
+ runtime["prime-agent-runtime<br/>rlm module + Python skills"]
+ code["Model-executed Python code"]
+
+ session -->|"owns"| manager
+ manager <-->|"Jupyter protocol over ZeroMQ"| kernel
+ kernel --> runtime --> code
+ code -->|"rlm.run · goal.* · agent_message.*"| runtime
+ runtime -->|"comm target: host.request"| manager
+ manager -->|"typed dispatch"| session
```
When the model delegates work:
@@ -31,6 +31,32 @@ the call travels through a Jupyter comm target named `host.request`. `KernelMana
The same bridge supports other typed host requests. Bundled Python skills such as `goal` call `rlm.host_request("goal.get", ...)`; state and policy remain in the TypeScript host.
+## Delegation Flow
+
+```mermaid
+sequenceDiagram
+ participant M as Parent model
+ participant H as Parent AgentSession
+ participant K as IPython kernel
+ participant C as Child AgentSession
+ participant P as Model provider
+
+ M->>H: IPython tool call
+ H->>K: execute await rlm("inspect the API")
+ K->>H: host.request · rlm.run
+ H->>H: check depth and resolve model
+ H->>C: create child runtime and prompt
+ loop Child agent loop
+ C->>P: stream model request
+ P-->>C: response or tool call
+ end
+ C-->>H: final answer and usage
+ H->>H: update registry and attribute usage
+ H-->>K: RLMResult
+ K-->>H: tool output
+ H-->>M: IPython result
+```
+
## Component Ownership
| Component | Responsibility |
diff --git a/packages/coding-agent/docs/rlm.md b/packages/coding-agent/docs/rlm.md
index 21fc29fc39..f38cca50fc 100644
--- a/packages/coding-agent/docs/rlm.md
+++ b/packages/coding-agent/docs/rlm.md
@@ -2,6 +2,30 @@
Prime Agent is built around a recursive language model (RLM) runtime: the model works inside a persistent Python control environment and composes capabilities as code. Provider calls, session persistence, child lifecycles, scheduling, and safety policy remain in the TypeScript host; IPython is the model-facing programming surface.
+## RLM Loop
+
+```mermaid
+flowchart LR
+ task["Task + working context"]
+ parent["Parent model"]
+ kernel["Persistent IPython kernel"]
+ data["Files · data · shell commands"]
+ skills["Python-backed skills"]
+ children["rlm(...) child agents"]
+ answer["Answer or next turn"]
+
+ task --> parent
+ parent -->|"IPython call"| kernel
+ kernel <-->|"inspect · search · transform"| data
+ kernel <-->|"call functions"| skills
+ kernel -->|"delegate focused work"| children
+ children -->|"return results"| kernel
+ kernel -->|"tool result"| parent
+ parent --> answer
+```
+
+The parent keeps its own context focused while Python holds working state and child agents receive only the context needed for their subtasks.
+
## Core Invariants
### 1. Execution is programmatic
@@ -113,4 +137,4 @@ This keeps credentials, provider execution, transcript writes, worker routing, a
The IPython kernel runs model-generated Python and project commands with the worker's operating-system permissions. It is a durable control environment, not a security sandbox. Review third-party Python skills and use an external sandbox or restricted environment for untrusted repositories and instructions.
-For implementation details, see [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).
+For implementation details, see [RLM Runtime Architecture](rlm-runtime.md).
diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.md
index 392a33297e..ace7cd6a0a 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -121,7 +121,7 @@ children = await rlm.list_subagents()
result = await task
```
-Children inherit the parent model unless the user requests another model. They run as TypeScript `AgentSession` instances under the same root worker and can use the same provider, tools, skills, session storage, and scheduling system. See [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).
+Children inherit the parent model unless the user requests another model. They run as TypeScript `AgentSession` instances under the same root worker and can use the same provider, tools, skills, session storage, and scheduling system. See [RLM Runtime Architecture](rlm-runtime.md).
## Context Files