Skip to content

Self-improving AI Employees for everyone

docs(cli-agent): document the memory bridge — native --resume via stable cwd

trohitg1d857051991f
diff --git a/CLAUDE.md b/CLAUDE.md
index 77044422..b96f0849 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -48,7 +48,9 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Credentials Encryption](./docs-internal/credentials_encryption.md)** | Fernet + PBKDF2 encryption pipeline, separate credentials.db, two credential systems (OAuth vs API keys), multi-backend abstraction |
| **[Status Broadcaster](./docs-internal/status_broadcaster.md)** | WebSocket-first communication: StatusBroadcaster singleton, 89 handlers, broadcast message types, Android two-state model |
| **[RLM Service](./docs-internal/rlm_service.md)** | Recursive Language Model agent with REPL-based execution (llm_query, rlm_query, FINAL) |
-| **[Claude Code Agent](./docs-internal/claude_code_agent_architecture.md)** | Claude Code SDK integration as a specialized agent node |
+| **[Claude Code Agent](./docs-internal/claude_code_agent_architecture.md)** | Claude Code integration internals (LangGraph reference; companion to `cli_agent_framework.md`) |
+| **[CLI Agent Framework](./docs-internal/cli_agent_framework.md)** | Multi-provider CLI runtime (Claude Code / Codex / Gemini): `AICliService.run_batch`, per-task worktree isolation, FastMCP bridge, **memory bridge** (native `--resume` via stable `cwd=repo_root` + UUID5/`last_session_id` round-trip + auto-clear on stale UUID + `node_parameters_updated` broadcast). |
+| **[CLI Agent Canonical Patterns RFC](./docs-internal/cli_agent_canonical_patterns_rfc.md)** | Audit of MachinaOs's `services/cli_agent` against the official Claude Code spec — six invariants (skills-as-files, MCP-only transport, `list_changed`, deferral, visible-tool filtering, native-session-continuity-via-stable-cwd) with current implementation status. |
| **[Deep Agent](./docs-internal/deep_agent.md)** | LangChain DeepAgents integration with filesystem tools, sub-agent delegation, auto-summarization, and planning |
| **[Autonomous Agent Creation](./docs-internal/autonomous_agent_creation.md)** | Creating autonomous agents with Code Mode patterns and agentic loops |
| **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |
@@ -3407,11 +3409,16 @@ I don't have access to real-time weather data...
- **Uses LangChain's InMemoryVectorStore**: Per-session vector stores with HuggingFaceEmbeddings (BAAI/bge-small-en-v1.5)
### Key Files
-- **Node Definition**: `server/nodes/skill/simple_memory.py` - simpleMemory plugin (NodeSpec + execute)
-- **Memory Helpers**: `server/services/ai.py` - `_parse_memory_markdown()`, `_append_to_memory_markdown()`, `_trim_markdown_window()`
-- **Vector Store**: `server/services/ai.py` - `_get_memory_vector_store()` with InMemoryVectorStore
-- **AI Integration**: `server/services/ai.py` - execute_agent with memory_data parameter
-- **Handler**: `server/services/handlers/ai.py` - Collects memory parameters from connected node
+- **Node Definition**: `server/nodes/skill/simple_memory.py` - simpleMemory plugin (NodeSpec + execute). Carries an internal `last_session_id` field (hidden in UI) used by the claude_code_agent bridge for native session resume.
+- **Memory Package**: `server/services/memory/` — promoted from the old `services/memory.py` so each concern owns its own module:
+ - `services/memory/markdown.py` — `parse_memory_markdown`, `append_to_memory_markdown`, `trim_markdown_window` (the canonical helpers every agent uses; **previously inlined into `services/ai.py`**, now imported from here)
+ - `services/memory/jsonl.py` — standalone JSONL `parse_jsonl` / `append_message` / `trim_window` (Anthropic Messages API shape, kept for future SDK migration; not used by any agent bridge today)
+ - `services/memory/vector_store.py` — `get_memory_vector_store` + per-session `InMemoryVectorStore` cache
+ - `services/memory/state.py` — `clear_agent_session_state(session_id, workflow_id, clear_long_term, memory_node_id)`; when `memory_node_id` is supplied it resets `memory_content` to the default placeholder AND wipes `last_session_id` server-side (single DB write)
+ - `services/memory/__init__.py` — re-exports the full surface so existing `from services.memory import …` callers keep working
+- **AI Integration (aiAgent / chatAgent / deep_agent / rlm_agent)**: `server/services/ai.py` — `execute_agent` / `execute_chat_agent` consume `memory_data`, call the markdown helpers via the package re-exports
+- **CLI bridge (`claude_code_agent`)**: `server/services/cli_agent/service.py:_persist_memory` — appends turns to `memory_content` via the same markdown helpers AND saves `simpleMemory.last_session_id` from the most recent successful run's `r.session_id`. Always broadcasts `node_parameters_updated` so the simpleMemory parameter panel refetches live (no page reload needed).
+- **Edge walker**: `server/services/plugin/edge_walker.py:_build_memory_entry` — surfaces `memory_content` + `window_size` + `long_term_enabled` + `retrieval_count` + `last_session_id` to every consuming agent
### Node Properties
| Property | Type | Default | Description |
@@ -3447,6 +3454,29 @@ I don't have access to real-time weather data...
- **Window + Archive**: Short-term (recent messages) + long-term (semantic retrieval) memory pattern
- **Auto-Save**: AI Agent automatically saves updated markdown content to node parameters
+### claude_code_agent bridge — native session resume (NOT markdown injection)
+
+When `simpleMemory` is connected to `claude_code_agent`, memory continuity is handled via **claude's own native session JSONL on disk** rather than re-injecting markdown as a system prompt. Claude stores per-session transcripts under `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl` where `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))` (verified against the on-disk `data/claude-machina/projects/` listing — Python reproduces three directory names byte-for-byte).
+
+**The three coupled mechanisms** (see [docs-internal/cli_agent_framework.md → Memory bridge](./docs-internal/cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent) for full plumbing):
+
+1. **Stable cwd.** `AICliSession` accepts `memory_bound=True`. When set, `cwd()` returns `repo_root` instead of the per-task `wt_t_<random>` worktree; `_pre_spawn` skips `git worktree add`; `cleanup` skips `git worktree remove`. The same cwd every run keeps claude's `project_key` constant so `--resume <UUID>` finds the prior JSONL.
+2. **UUID5 first-run / `--resume` thereafter.** `claude_code_agent` derives `uuid5(NAMESPACE_OID, f"{memory_node_id}:{simpleMemory.session_id}")` for the first run and passes it as `--session-id <UUID5>`. Subsequent runs read `simpleMemory.last_session_id` (saved by `_persist_memory` from the previous run's `r.session_id`) and pass `--resume <UUID>` instead. Mutually exclusive in `providers/anthropic_claude.py:headless_argv` argv emission.
+3. **Auto-clear stale `last_session_id`.** When claude reports `No conversation found with session ID: <UUID>` (the JSONL was wiped, or the user's saved UUID predates the cwd-stability fix), `_persist_memory` substring-matches the error and fires `_clear_stale_session_id` which wipes `simpleMemory.last_session_id` (but preserves `memory_content`). Next run falls through to the first-run branch and self-heals.
+
+**`memory_content` is the UI mirror, not the resume channel.** Claude reads its own JSONL via `--resume`. The markdown in `memory_content` is appended every successful run (same `append_to_memory_markdown` + `trim_markdown_window` helpers aiAgent uses) for the human reader. User edits to `memory_content` do not influence claude's next response.
+
+**Parallel-batch guard.** When memory is wired AND `len(tasks) > 1`, `claude_code_agent` raises `NodeUserError` at handler entry — concurrent `--resume <UUID>` spawns against one JSONL would race.
+
+**Live UI refresh.** `_persist_memory` broadcasts `node_parameters_updated` after `save_node_parameters` so the simpleMemory parameter panel auto-refetches the moment a turn completes — without this the DB has the latest conversation but the UI shows the stale snapshot loaded at workflow open. Mirrors the pattern in `routers/websocket.py:handle_save_node_parameters`.
+
+**Logs to grep on a live run:**
+- `[Claude Code memory] memory_node=<id> last_session_id=<UUID|None> -> --resume <UUID>` (subsequent run) or `--session-id <UUID5> (first run)`
+- `[AICliSession_*] memory-bound: skipping worktree, using cwd=<repo_root>`
+- `[CC-Agent stream] result is_error=False ... session_id=<UUID>`
+- `[CC-Agent _persist_memory] saved memory_node=<id> last_session_id=<UUID> appended_turns=1 ... content_length=<N>`
+- On stale-UUID error: `[CC-Agent _persist_memory] cleared stale last_session_id=<UUID> from memory_node=<id>; next run will spawn a fresh claude session and persist its new UUID.`
+
## Memory Compaction, Token Tracking, and Cost Calculation
### Overview
diff --git a/docs-internal/cli_agent_canonical_patterns_rfc.md b/docs-internal/cli_agent_canonical_patterns_rfc.md
index d2265198..a15ef3b1 100644
--- a/docs-internal/cli_agent_canonical_patterns_rfc.md
+++ b/docs-internal/cli_agent_canonical_patterns_rfc.md
@@ -238,6 +238,38 @@ Across the official documentation:
> The pattern: register many internally, filter the model-visible
> subset.
+> **I-6. Native session continuity needs stable cwd + `--resume <UUID>`.**
+> Claude stores per-session JSONL under
+> `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl` where
+> `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`. Verified
+> against on-disk dir names: a worktree path of
+> `D:\startup\projects\MachinaOs\server\...\wt_t_af48d0a7` produces
+> `D--startup-projects-MachinaOs-server-...-wt-t-af48d0a7`.
+>
+> Two consequences:
+>
+> (a) **System-prompt injection is the wrong primitive for prior
+> conversation.** Universal P2 pattern across Cline / Continue.dev /
+> Aider / Cursor / Hermes / Anthropic SDK is *re-pass the full
+> messages array each turn*. For raw `claude -p` the documented
+> equivalent is native session resume; `--append-system-prompt`-stuffed
+> markdown is treated by claude as a rendered document, not as turns
+> it actually had.
+>
+> (b) **Per-task ephemeral worktree paths (`wt_t_<random>`) break
+> `--resume`.** Every spawn lands in a brand-new project dir with zero
+> prior JSONL → "No conversation found with session ID: <UUID>"
+> regardless of UUID stability or `--input-format=stream-json`
+> stdin protocol.
+>
+> Fix is structural, not format-related: when memory is wired, spawn
+> under `cwd=repo_root` so `project_key` is stable across runs, and
+> pass either `--resume <last_session_id>` (subsequent runs) or
+> `--session-id <UUID5(memory_node_id, simpleMemory.session_id)>`
+> (first run). On "No conversation found" error, auto-clear the stale
+> `last_session_id` so the next run falls through to `--session-id
+> <UUID5>` and self-heals.
+
## 4. MachinaOs `cli_agent` alignment audit
File:line evidence from a focused read of `services/cli_agent/`:
@@ -350,6 +382,60 @@ disable tool-search deferral globally — alternative to per-server
`alwaysLoad: true`. Per-server is finer-grained; env var is simpler.
Either works.
+### 4.8 Memory bridge — `simpleMemory` → `claude_code_agent` (DONE in `ecbe69b`)
+
+**Status:** native claude session resume works end-to-end via stable
+cwd + UUID5/last_session_id round-trip. Documented in
+[cli_agent_framework.md → Memory bridge](./cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent).
+
+**Project-key derivation verified empirically** by listing
+`data/claude-machina/projects/` on disk and reproducing each name from
+its source cwd via `re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`. Three
+sample names matched byte-for-byte:
+
+| cwd | project_key |
+|---|---|
+| `D:\startup\projects\MachinaOs` | `D--startup-projects-MachinaOs` |
+| `D:\startup\projects\MachinaOs\server` | `D--startup-projects-MachinaOs-server` |
+| `D:\startup\projects\MachinaOs\server\...\wt_t_af48d0a7` | `D--startup-projects-MachinaOs-server-...-wt-t-af48d0a7` |
+
+**Failure-mode evidence captured during dev** (log fragments):
+
+- `[CC-Agent stderr] No conversation found with session ID: cddd6def-...`
+ every spawn → confirmed that ephemeral worktree paths were defeating
+ `--resume`.
+- After switching to `cwd=repo_root`: same UUID continues across spawns,
+ `r.session_id` matches `last_session_id` on subsequent runs.
+- `_persist_memory` broadcast addition fixed a UI-staleness issue where
+ `memory_content` was correctly written to the DB but the simpleMemory
+ parameter panel only showed the update after a page reload.
+
+**Pre-bridge attempts that didn't work** (recorded for posterity so
+this isn't re-attempted):
+
+- **System-prompt injection of markdown turns.** Claude treated
+ `### **Human** (timestamp)` headers as a rendered document
+ description, not as actual conversation it had. Even with explicit
+ framing ("the following is your prior conversation, continue
+ naturally") claude responded "I don't have context from a previous
+ conversation about what to continue" — the system-prompt channel
+ isn't the right primitive.
+- **JSONL injection in the same channel.** Same fundamental problem;
+ format is irrelevant when the channel is wrong.
+- **Always `--session-id <UUID5>` without `--resume`.** Claude
+ accepted the UUID but didn't auto-load prior history from disk —
+ `--session-id` only *specifies* the UUID for THIS conversation, it
+ is not idempotent across spawns.
+- **`--resume <UUID>` against random-suffix worktree cwd.** Always
+ failed because the project_key changed every run.
+
+The Anthropic SDK Python package's `materialize_resume_session()`
+solves the same problem by writing the JSONL to a temp
+`CLAUDE_CONFIG_DIR` and spawning with `--resume`. Our approach is
+equivalent in outcome (claude finds its own JSONL via `--resume`)
+without the SDK dependency — we just keep cwd stable so the JSONL
+claude wrote on its previous turn stays findable.
+
### 4.7 Worktree contents
[`session.py:_pre_spawn`](../server/services/cli_agent/session.py): only
@@ -367,58 +453,90 @@ documented project-instruction surface.
| Invariant | Status | Action |
|---|---|---|
-| **I-1** Skills as files | **Gap** — exposed as MCP `getSkill`/`listSkills` only; never invoked. | Materialise `<worktree>/.claude/skills/<name>/` in `_pre_spawn`. Drop `getSkill`/`listSkills` after one release. |
+| **I-1** Skills as files | **DONE (`b40011e`).** [`session.py:_materialise_skills`](../server/services/cli_agent/session.py) writes connected skills to `<cwd>/.claude/skills/<name>/` on `_pre_spawn`. `mcp__machinaos__listSkills` / `getSkill` retained as a transitional fallback. | Drop `getSkill`/`listSkills` MCP tools after one release. |
| **I-2** MCP transport | **Aligned.** Streamable-HTTP via `--mcp-config`. | None. |
-| **I-3** `list_changed` notification | **Likely aligned, unverified.** FastMCP ≥1.0 emits on `add_tool`/`remove_tool`. | Add a unit test asserting the notification fires. |
-| **I-4** Tool-search deferral | **Gap.** Default `ENABLE_TOOL_SEARCH=true` defers our tools; agent never recovers them. | Add `"alwaysLoad": true` to the `machinaos` entry in `--mcp-config`. |
+| **I-3** `list_changed` notification | **DONE (`b40011e`).** [`workflow_tools._schedule_list_changed_notify`](../server/services/cli_agent/workflow_tools.py) fires after each `add_tool` / `remove_tool` since FastMCP doesn't emit it automatically. | Optional: unit test asserting `session.send_tool_list_changed` is called. |
+| **I-4** Tool-search deferral | **DONE (`b40011e`).** `"alwaysLoad": true` added to the `machinaos` server entry in [`providers/anthropic_claude.py:111-124`](../server/services/cli_agent/providers/anthropic_claude.py). | None. |
| **I-5** Visible-tool filtering | **Gap.** All 5 built-in MachinaOs MCP tools (including `getCredential`, `broadcastLog`) are visible to the model. | Mark internal-only tools `_meta["anthropic/alwaysLoad"]: false` or filter via FastMCP middleware. **Defer** — not breaking today. |
-| **System-prompt directive** (Cursor / `CLAUDE.md` pattern) | **Gap.** No instruction tells claude to prefer connected `mcp__machinaos__*` over built-ins. | Append a `--append-system-prompt` line listing connected tools. |
-| `--allowedTools` includes `Skill,WebSearch,WebFetch` | **Gap** — missing. | Extend default list. |
+| **I-6** Native session continuity | **DONE (`ecbe69b`).** [`session.py`](../server/services/cli_agent/session.py) accepts `memory_bound=True` → `cwd()` returns `repo_root`, `_pre_spawn` / `cleanup` skip the worktree. [`claude_code_agent.py`](../server/nodes/agent/claude_code_agent.py) derives UUID5 for first-run `--session-id`, reads `last_session_id` for `--resume`. [`service.py:_persist_memory`](../server/services/cli_agent/service.py) saves `last_session_id`, broadcasts `node_parameters_updated`, auto-clears stale UUIDs. See §4.8. | Drop the markdown `--append-system-prompt` injection block from `claude_code_agent` once SDK migration lands (the markdown surface remains as a UI mirror, not a context channel). Pending. |
+| **System-prompt directive** (Cursor / `CLAUDE.md` pattern) | **DONE (`b40011e`).** Second `--append-system-prompt` listing connected `mcp__machinaos__*` tools. | None. |
+| `--allowedTools` includes `Skill,WebSearch,WebFetch` | **DONE (`b40011e`).** [`ai_cli_providers.json`](../server/config/ai_cli_providers.json) + hardcoded fallback both updated. | None. |
| Composio-style server-side credentials | **Aligned.** `getCredential` allowlist + `auth_service.get_api_key`. | None. |
| Hermes-style `provider_data` envelope | **Aligned.** [`protocol.py:SessionResult.provider_data`](../server/services/cli_agent/protocol.py). | None. |
| Composio-style parent-run-id | **Aligned.** `MACHINA_PARENT_RUN_ID` env var. | None. |
## 6. Recommendations (mapped to the spec)
-**R1. Materialise connected skills into `<worktree>/.claude/skills/<name>/`
-on `_pre_spawn` (Closes I-1).** Documented at
-[skills#where-skills-live](https://code.claude.com/docs/en/skills#where-skills-live).
-Use [`skill_loader.load_skill(name)`](../server/services/skill_loader.py).
-Auto-discovery works because the worktree is claude's cwd. Remove the
-MCP `listSkills`/`getSkill` tools one release after this lands.
-
-**R2. Add `"alwaysLoad": true` to the `machinaos` entry in `--mcp-config`
-(Closes I-4).** Per §2.4: *"…also blocks startup until that server
-connects (5s cap)."* The 5s wait is acceptable — the FastMCP server is
-already up before spawn. Alternative: set
-`ENABLE_TOOL_SEARCH=false` in the spawn env. Either works; per-server
-is finer-grained.
-
-**R3. Extend `--allowedTools` defaults to include `Skill,WebSearch,WebFetch`.**
-`Skill` lets claude execute the materialised SKILL.md files (R1).
-`WebSearch`/`WebFetch` are escape hatches for prompts where no MCP tool
-fits — keeps the agent useful when wiring is incomplete. **Do not add
-`ToolSearch`** — it's permission-free.
-
-**R4. Append a system-prompt directive when MCP tools are wired (the
-`CLAUDE.md` / Cursor-rules pattern).** When `connected_tool_names` is
-non-empty, add a second `--append-system-prompt` arg with one line:
-
-```
-Workflow tools wired to this agent: <comma-separated mcp__machinaos__* names>.
-Prefer them over built-in equivalents (WebSearch, WebFetch, Bash) when
-the user's request matches their purpose.
-```
-
-Mirrors Cursor's per-request rule prepend
-([cursor.com/docs/rules](https://cursor.com/docs/rules): *"Cursor builds a
-fresh system prompt for every inline edit request, so it injects the
-rules every time."*).
+**R1 (DONE in `b40011e`). Skills materialised into `<cwd>/.claude/skills/<name>/`
+on `_pre_spawn` (Closes I-1).** Uses
+[`skill_loader.load_skill_async(name)`](../server/services/skill_loader.py).
+For memory-bound runs the cwd is `repo_root` so skills land at
+`<repo_root>/.claude/skills/`; for non-memory runs they go under the
+per-task worktree. MCP `listSkills` / `getSkill` retained as a fallback.
+
+**R2 (DONE in `b40011e`). `"alwaysLoad": true` set on the `machinaos`
+entry in `--mcp-config` (Closes I-4).** Per §2.4: *"…also blocks startup
+until that server connects (5s cap)."* The 5s wait is acceptable — the
+FastMCP server is already up before spawn.
+
+**R3 (DONE in `b40011e`). `--allowedTools` defaults extended with
+`Skill,WebSearch,WebFetch`.** Updated in both
+[`ai_cli_providers.json`](../server/config/ai_cli_providers.json) and
+the hardcoded fallback in
+[`anthropic_claude.py`](../server/services/cli_agent/providers/anthropic_claude.py).
+`ToolSearch` intentionally NOT added — it's permission-free.
+
+**R4 (DONE in `b40011e`). System-prompt directive when MCP tools are
+wired (the `CLAUDE.md` / Cursor-rules pattern).** Second
+`--append-system-prompt` listing connected `mcp__machinaos__*` tools.
**R5 (followup).** Filter `getCredential` and `broadcastLog` from the
model-visible tool list — they're host-internal RPC, the model has no
-business calling them. Use FastMCP middleware on `tools/list`. **Defer
-until R1–R4 land** — not breaking.
+business calling them. Use FastMCP middleware on `tools/list`.
+**Pending** — not breaking.
+
+**R6 (DONE in `ecbe69b`). Native session continuity for memory-bound
+runs (Closes I-6).** Three coupled mechanisms:
+
+1. **Stable cwd.** [`AICliSession.cwd()`](../server/services/cli_agent/session.py)
+ returns `self._repo_root` when `memory_bound=True`. `_pre_spawn`
+ skips `git worktree add`; `cleanup` skips `git worktree remove`.
+ Confirms claude's `project_key` is constant across runs.
+
+2. **UUID5 first-run / `--resume` thereafter.**
+ [`claude_code_agent.py`](../server/nodes/agent/claude_code_agent.py)
+ derives `uuid5(NAMESPACE_OID, f"{memory_node_id}:{simpleMemory.session_id}")`
+ for the very first run and passes it as `--session-id <UUID5>`.
+ Subsequent runs read `simpleMemory.last_session_id` and pass
+ `--resume <UUID>`. Mutually exclusive in argv emission
+ (`providers/anthropic_claude.py:141-146`).
+
+3. **Auto-clear stale `last_session_id`.**
+ [`_persist_memory`](../server/services/cli_agent/service.py)
+ substring-matches `"No conversation found with session ID"` in any
+ result's `error`; when matched, fires `_clear_stale_session_id`
+ which wipes `simpleMemory.last_session_id` only (preserves
+ `memory_content`). Next run falls into the first-run branch and
+ recovers automatically.
+
+4. **Live UI refresh.** `_persist_memory` broadcasts
+ `node_parameters_updated` after `save_node_parameters` so the
+ simpleMemory parameter panel refetches the moment the run
+ completes — mirrors the manual save broadcast in
+ [`routers/websocket.py:handle_save_node_parameters`](../server/routers/websocket.py).
+
+5. **Parallel-batch guard.** `len(tasks) > 1` with memory wired raises
+ `NodeUserError` at handler entry — concurrent `--resume <UUID>`
+ spawns against one JSONL would race.
+
+Markdown is the UI mirror. The `simpleMemory.memory_content` field
+keeps mirroring conversation turns via
+[`services.memory.append_to_memory_markdown`](../server/services/memory/markdown.py)
++ [`trim_markdown_window`](../server/services/memory/markdown.py) for
+human readability. **It is not the resume channel** — claude reads its
+own JSONL via `--resume`. User edits to `memory_content` do not
+influence claude's next response; the canonical record lives in
+claude's on-disk JSONL.
## 7. Open questions
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.md
index 6b5631cc..c8538bf8 100644
--- a/docs-internal/cli_agent_framework.md
+++ b/docs-internal/cli_agent_framework.md
@@ -313,6 +313,153 @@ Lifespan: `main.py` enters `mcp_app.router.lifespan_context()` so `StreamableHTT
`cost_usd` is the provider's reported value when available (Claude). For Codex (no native USD), `service.py:_derive_cost` falls back to `services.pricing.PricingService.calculate_cost()` from `canonical_usage` — single source of truth for LLM cost across MachinaOs. `summary.total_cost_usd` is `null` if any task didn't surface cost.
+## Memory bridge — `simpleMemory` → `claude_code_agent`
+
+Connecting a `simpleMemory` node to a `claude_code_agent` makes the
+spawned `claude -p` resume its prior session natively across runs.
+**No system-prompt injection, no JSONL synthesis, no API fallback.**
+Claude maintains its own session JSONL on disk under
+`<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl`; we
+just feed it the right argv and keep the cwd stable so the project
+key doesn't drift.
+
+### Why native resume needs a stable cwd
+
+Claude derives `project_key` from cwd via `re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`
+— every `:`, `\`, `/`, `_` becomes `-`. Verified against the on-disk
+`data/claude-machina/projects/` listing — Python reproduces three
+encoded directory names byte-for-byte. The pre-bridge per-task
+worktree (`<workspace>/<node_id>/wt_t_<random_8hex>`) changed cwd on
+every spawn → fresh project_key every run → `--resume <UUID>` looked
+under a brand-new directory with zero prior JSONL ("No conversation
+found with session ID").
+
+The fix: when memory is wired, spawn under `cwd=repo_root` and skip
+the worktree entirely. Same cwd every run → same project_key → claude
+finds its own JSONL.
+
+### Argv contract
+
+| Run state | Argv | Why |
+|---|---|---|
+| First run (no `last_session_id` in DB) | `--session-id <UUID5(memory_node_id, simpleMemory.session_id)>` | Deterministic UUID lets us address the same session predictably; survives session_id forks via the user-visible `simpleMemory.session_id` slot. |
+| Subsequent run (`last_session_id` saved) | `--resume <last_session_id>` | Native claude session resume. Same `cwd=repo_root` → same project_key → claude finds the JSONL it wrote on the previous turn. |
+| After "No conversation found" error | argv same as above on the spawn that errored; `_persist_memory` auto-clears `last_session_id` so the NEXT run falls into the first-run branch with `--session-id <UUID5>`. | Self-heal from a stale or wiped JSONL. |
+
+Argv emission lives in
+`providers/anthropic_claude.py:headless_argv` — picks up
+`task.session_id` vs `task.resume_session_id` (mutually exclusive
+fields on `ClaudeTaskSpec`).
+
+### Plumbing
+
+```
+ClaudeCodeAgentNode.execute_op
+ └─ collect_agent_connections() → memory_data {node_id, session_id,
+ memory_content, window_size,
+ long_term_enabled,
+ last_session_id}
+ └─ derive resume_session_id (= memory_data.last_session_id) OR
+ first_run_session_uuid (= uuid5(NAMESPACE_OID,
+ f"{memory_node_id}:{session_id}"))
+ └─ ClaudeTaskSpec(..., session_id=..., resume_session_id=...)
+ └─ run_batch(..., connected_memory=memory_data, broadcaster=...)
+ └─ AICliService.run_batch:
+ ├─ AICliSession(..., memory_bound=True) # ← drives cwd switch
+ │ └─ cwd() returns self._repo_root
+ │ └─ _pre_spawn skips `git worktree add`
+ │ └─ cleanup skips `git worktree remove`
+ └─ asyncio.gather → SessionResults
+ └─ _persist_memory(connected_memory, results, broadcaster):
+ ├─ saves params["last_session_id"] = most_recent.session_id
+ ├─ appends user/assistant turns to params["memory_content"]
+ │ via append_to_memory_markdown + trim_markdown_window
+ │ (the same helpers aiAgent / chatAgent / deep_agent / rlm_agent
+ │ use — reuse, don't duplicate)
+ ├─ database.save_node_parameters(memory_node_id, params)
+ └─ broadcaster.broadcast({"type": "node_parameters_updated",
+ "node_id": memory_node_id, ...})
+ # ← the UI's parameter panel auto-refreshes the moment
+ # the run completes. Without this the DB has the
+ # latest conversation but the UI keeps showing the
+ # stale snapshot it loaded at workflow open.
+```
+
+### Self-healing on stale UUID
+
+`AICliService._clear_stale_session_id(connected_memory)` substring-
+matches `"No conversation found with session ID"` in any result's
+`error`. When matched it wipes `simpleMemory.last_session_id` from
+the DB but preserves `memory_content` (the user-visible markdown
+transcript). Next run derives a fresh `--session-id <UUID5>` and
+proceeds with a clean session.
+
+Triggered automatically inside `_persist_memory` when zero results
+succeed. Without this the same stale UUID would re-fire every run
+and the user would be stuck.
+
+### Parallel-batch guard
+
+Memory continuity requires serial execution — N concurrent
+`--resume <UUID>` spawns against one session JSONL would race. When
+`memory_data` is wired AND `len(tasks) > 1`, `claude_code_agent`
+raises `NodeUserError("Memory-bound batches must run one task at a
+time. Reduce Tasks to a single entry, or disconnect the memory
+node.")` at handler entry — never spawns.
+
+### Markdown mirror
+
+`memory_content` (the markdown surface the simpleMemory UI shows) is
+**a display mirror, not the canonical record**. Claude's own JSONL
+is canonical. `_persist_memory` appends each successful run's prompt
++ response to `memory_content` via `append_to_memory_markdown` so the
+UI shows the conversation grow live. User edits to `memory_content`
+do NOT influence claude's next response — claude reads its own JSONL
+via `--resume`.
+
+To reset both: click the simpleMemory's clear button or invoke the
+`clear_memory` WS handler with `memory_node_id` — backend wipes
+`memory_content` to the default placeholder AND clears
+`last_session_id` in one DB write. Claude's on-disk JSONL is left
+alone (orphan, harmless). The next run with the same memory wired
+will spawn a fresh session at a NEW deterministic UUID5 (because
+the user's `simpleMemory.session_id` is part of the UUID5 inputs;
+unchanged after clear, but `last_session_id` being None routes us
+through the first-run branch).
+
+### Logs to watch
+
+```
+[Claude Code memory] memory_node=<id> last_session_id=<UUID|None>
+ -> --resume <UUID> | --session-id <UUID5> (first run)
+
+[CC-Agent run_batch] enter ... memory=<memory_node_id> ...
+
+[AICliSession_*] memory-bound: skipping worktree, using cwd=<repo_root>
+
+[CC-Agent stream] result is_error=False subtype=success
+ session_id=<UUID> duration_ms=...
+
+[CC-Agent _persist_memory] memory_node=<id> results=1 successful=1
+ session_ids=['<UUID>']
+[CC-Agent _persist_memory] saved memory_node=<id> last_session_id=<UUID>
+ appended_turns=1 archived_blocks=0 content_length=<N>
+```
+
+On a stale-resume failure path the trace ends with:
+
+```
+[CC-Agent stderr] No conversation found with session ID: <UUID>
+[CC-Agent stream] result is_error=True subtype=error_during_execution
+ session_id=<new-UUID-claude-assigned-to-the-failed-attempt>
+[CC-Agent _persist_memory] no successful runs; skipping save ...
+[CC-Agent _persist_memory] cleared stale last_session_id=<UUID>
+ from memory_node=<id>; next run will spawn a fresh claude session
+ and persist its new UUID.
+```
+
+— and the next run succeeds with `--session-id <UUID5>`.
+
## Status broadcast events
| Phase | When | Payload |