Skip to content

Self-improving AI Employees for everyone

fix(cli_agent): run pooled claude sessions in a per-workflow worktree; show the session id

trohitg81797e4dc921
diff --git a/CLAUDE.md b/CLAUDE.md
index 8432de98..580dd805 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,7 +64,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Status Broadcaster](./docs-internal/status_broadcaster.md)** | WebSocket-first communication: StatusBroadcaster singleton, live count via `len(MESSAGE_HANDLERS) + len(get_ws_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.md)** | Hub for the Claude Code agent — routes to architecture, interactive mode, CLI framework, canonical-patterns RFC, and the 5 CLI snapshot references. |
-| **[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** (host-minted `--session-id` on cold spawn + intra-process stream-json multi-turn + `--resume <last_session_id>` for memory-bound runs and crash recovery — never `--continue`, which the CLI resolves only against interactive sessions — all on a stable `cwd=repo_root`; `node_parameters_updated` broadcast on every successful turn). **Plugin-folder layout** (post-cutover): all claude-specific code lives in [`server/nodes/agent/claude_code_agent/`](./server/nodes/agent/claude_code_agent/) — `_provider.py`, `_pool.py`, `_skills.py`, `_oauth.py`, `_handlers.py` — and self-registers via three `factory.py` registries (`register_provider` / `register_session_pool` / `register_skill_materialiser`) plus `register_ws_handlers`. The generic framework at `services/cli_agent/` imports nothing from `nodes/`. |
+| **[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** (host-minted `--session-id` on cold spawn + intra-process stream-json multi-turn + `--resume <last_session_id>` for memory-bound runs and crash recovery — never `--continue`, which the CLI resolves only against interactive sessions — all in a stable per-workflow git worktree `<workspace>/<node>/wt_session` branched off the enclosing repo, never the repo root itself; `node_parameters_updated` broadcast on every successful turn). **Plugin-folder layout** (post-cutover): all claude-specific code lives in [`server/nodes/agent/claude_code_agent/`](./server/nodes/agent/claude_code_agent/) — `_provider.py`, `_pool.py`, `_skills.py`, `_oauth.py`, `_handlers.py` — and self-registers via three `factory.py` registries (`register_provider` / `register_session_pool` / `register_skill_materialiser`) plus `register_ws_handlers`. The generic framework at `services/cli_agent/` imports nothing from `nodes/`. |
| **[Claude Code Interactive Mode](./docs-internal/claude_code_interactive_mode.md)** | The interactive-mode cutover: OpenCompany no longer uses `claude -p` headless. `ClaudeSessionPool` (keyed by `simpleMemory.node_id`) spawns `claude` as a plain subprocess with stdio pipes — **no PTY** — and drives it over the VSCode-extension protocol: `--output-format stream-json --input-format stream-json --verbose --ide`. User prompts written as JSON to `proc.stdin` (`{"type":"user","message":{"role":"user","content":"..."}}\n`); `system/init` / `assistant` / `result` / `system/compact_boundary` events stream back on `proc.stdout` (parsed by a background `stdout_reader_task` — the on-disk JSONL is persistence-only, not the runtime contract, because `result` events are stdout-only in stream-json mode). Cross-platform via plain pipes (the earlier PTY pattern was broken on Windows because pywinpty/ConPTY's emulated stdin never reached claude's Ink TUI keystroke handler). Stays in interactive billing — entrypoint `claude-vscode`, NOT `sdk-cli`. Multi-turn within one warm subprocess preserves the session UUID (verified end-to-end); cross-batch continuity via `--continue` (first run) or `--resume <UUID>` (crash recovery). Four typed CloudEvents (`claude.session.{spawned,cleared,terminated,usage}`) fire from the pool. `/compact` events forward to `CompactionService`. Every Claude run routes through the pool (unbound runs get an ephemeral session per task, terminated after the batch); `AICliSession` (PTY + JSONL watcher) is no longer used for Claude because a PTY stdin makes the CLI reject stream-json input and that path never delivered the prompt (GitHub #133 / #134). A child exiting without a `result` wakes `send_turn` on stdout EOF with the exit code instead of burning the turn timeout. The CLI version is pinned via `package_version` in `config/ai_cli_providers.json`. |
| **[CLI Agent Canonical Patterns RFC](./docs-internal/cli_agent_canonical_patterns_rfc.md)** | Audit of OpenCompany'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. |
| **[Claude Code CLI Reference (snapshot)](./docs-internal/claude_code_cli_reference.md)** | Verbatim snapshot of [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference) — every CLI subcommand + flag + system-prompt-flag matrix + the subset we emit from `nodes/agent/claude_code_agent/_provider.py`. Fetched 2026-05-11. |
diff --git a/docs-internal/claude_code_agent.md b/docs-internal/claude_code_agent.md
index d436b469..db7294f6 100644
--- a/docs-internal/claude_code_agent.md
+++ b/docs-internal/claude_code_agent.md
@@ -6,8 +6,8 @@ stream-json protocol — not the `claude -p` headless path. A warm `ClaudeSessio
(keyed by the RFC-0002 conversation key when a Context node is connected, or by the
legacy `simpleMemory.node_id` on `input-memory` graphs — `services/cli_agent/service.py:354-358`)
preserves the session across turns;
-memory continuity is claude-native via a host-minted `--session-id` on the first run and `--resume <last_session_id>` afterwards on a stable
-`cwd=repo_root`. Connected tools and skills reach claude through an MCP bridge; the spawn
+memory continuity is claude-native via a host-minted `--session-id` on the first run and `--resume <last_session_id>` afterwards in a stable
+per-workflow git worktree (`<workspace>/<node>/wt_session`, branched off the enclosing repo; the repo root is never the cwd). Connected tools and skills reach claude through an MCP bridge; the spawn
runs under `--permission-mode dontAsk` with a strict `--allowedTools` allowlist and stays
in interactive billing (entrypoint `claude-vscode`, not `sdk-cli`).
diff --git a/docs-internal/claude_code_interactive_mode.md b/docs-internal/claude_code_interactive_mode.md
index e86c95bf..e0618997 100644
--- a/docs-internal/claude_code_interactive_mode.md
+++ b/docs-internal/claude_code_interactive_mode.md
@@ -334,8 +334,8 @@ rule, claude scans `.claude/skills/` inside every `--add-dir` path.
Two properties fall out:
- **Per-workflow isolation.** Workflow A's wired skills never bleed
- into workflow B's subprocess even when both spawn with
- `cwd=repo_root`. The workspace dir is unique per workflow.
+ into workflow B's subprocess: each runs in its own worktree under its
+ own workspace dir.
- **Live add/remove.** Claude live-watches the skills tree (same
skills spec, [Live change detection](https://code.claude.com/docs/en/skills#live-change-detection)),
so warm-reuse turns can toggle skills without respawning. Pool's
@@ -382,9 +382,10 @@ splices the per-workflow workspace
right after `task_list` is built — `interactive_argv` already emits
`--add-dir <path>` per entry. Runs BEFORE the pool branch so every
pooled session gets it. Without this, the workspace is invisible to
-claude: sessions spawn with `cwd=repo_root` (stable for `--resume`'s
-`project_key` resolution), which does not see files dropped by
-upstream nodes (`fileDownloader`,
+claude: sessions spawn in a git worktree under
+`<workspace>/<node>/` (`wt_session` for bound runs, one per task
+otherwise), which does not see files dropped by upstream nodes
+(`fileDownloader`,
`documentParser`, code executors, etc.). Mirrors the ai_agent
pattern ([`services/ai.py:1186`](../server/services/ai.py) in
`execute_agent`, `:1924` in `execute_chat_agent` —
diff --git a/docs-internal/cli_agent_canonical_patterns_rfc.md b/docs-internal/cli_agent_canonical_patterns_rfc.md
index 3a1154ca..68fda6d1 100644
--- a/docs-internal/cli_agent_canonical_patterns_rfc.md
+++ b/docs-internal/cli_agent_canonical_patterns_rfc.md
@@ -263,7 +263,7 @@ Across the official documentation:
> 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
+> in one stable per-node worktree 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
@@ -420,7 +420,7 @@ Either works.
mechanism is a host-minted `--session-id <uuid4>` on the first cold
spawn + intra-process stream-json multi-turn against a warm subprocess +
`--resume <last_session_id>` on later cold spawns and crash recovery —
-all on a stable `cwd=repo_root`. (An interim `--continue` variant was
+all in a stable per-node worktree under the workspace. (An interim `--continue` variant was
reverted: the CLI resolves `--continue` only against interactive
sessions, so it never found the pool's non-interactive ones.) The entry
point is
@@ -447,7 +447,7 @@ sample names matched byte-for-byte:
- `[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,
+- After switching to a stable per-node worktree: 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
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.md
index 188d8a8e..be16b235 100644
--- a/docs-internal/cli_agent_framework.md
+++ b/docs-internal/cli_agent_framework.md
@@ -398,9 +398,12 @@ 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.
+The fix: when memory is wired, spawn in one stable worktree per agent
+node (`<workspace>/<node>/wt_session`) instead of a fresh per-task one.
+Same cwd every run → same project_key → claude finds its own JSONL.
+Pooled sessions never run in the repo root itself: claude reads
+CLAUDE.md from cwd upward, and the checkout that contains DATA_DIR
+would otherwise ride into every session.
### Argv contract
@@ -440,7 +443,7 @@ ClaudeCodeAgentNode.execute_op (__init__.py:291-330)
└─ For context/memory-wired single-task runs, route through ClaudeSessionPool
(service.py:343-358 — use_pool = claude AND one task AND
(connected_memory OR a Context bridge)):
- ├─ pool.acquire(session_key, spec, cwd=repo_root, env, ...)
+ ├─ pool.acquire(session_key, spec, cwd=<workspace>/<node>/wt_session, env, ...)
│ session_key = context_bridge.pool_key when a Context node is wired (the
│ RFC-0002 conversation key, so a Reset's generation bump
│ fences the warm subprocess), else the legacy
diff --git a/server/nodes/agent/claude_code_agent/__init__.py b/server/nodes/agent/claude_code_agent/__init__.py
index 30412b2b..a6e69f54 100644
--- a/server/nodes/agent/claude_code_agent/__init__.py
+++ b/server/nodes/agent/claude_code_agent/__init__.py
@@ -440,21 +440,16 @@ class ClaudeCodeAgentNode(ActionNode):
task_models = [
session_result_to_model(t).model_dump() for t in result.tasks
]
- if context_descriptor is not None:
- for task_model in task_models:
- task_model["session_id"] = None
- # Legacy single-task convenience fields
+ # Legacy single-task convenience fields. ``session_id`` is claude's
+ # own session UUID (the pooled process reports it on every turn), so
+ # the operator can see whether successive messages share a session.
legacy_response = None
legacy_session_id = None
legacy_cost = None
if len(result.tasks) == 1:
legacy_response = result.tasks[0].response
- legacy_session_id = (
- result.tasks[0].session_id
- if context_descriptor is None
- else None
- )
+ legacy_session_id = result.tasks[0].session_id
legacy_cost = result.tasks[0].cost_usd
return {
diff --git a/server/nodes/agent/claude_code_agent/_pool.py b/server/nodes/agent/claude_code_agent/_pool.py
index 55003437..0956dc56 100644
--- a/server/nodes/agent/claude_code_agent/_pool.py
+++ b/server/nodes/agent/claude_code_agent/_pool.py
@@ -143,7 +143,7 @@ class PooledClaudeSession:
# "Automatic discovery from parent and nested directories" rule
# in code.claude.com/docs/en/skills. Per-workflow isolation:
# workflow A's wired skills never bleed into workflow B's
- # subprocess even when both spawn with ``cwd=repo_root``.
+ # subprocess (each spawns in a worktree under its own workspace).
workspace_dir: Optional[Path] = None
# Set of skill names currently materialised under
# ``<workspace_dir>/.claude/skills/`` for this warm subprocess.
@@ -716,8 +716,8 @@ class ClaudeSessionPool:
# ``.claude/skills/`` inside every ``--add-dir`` path per
# code.claude.com/docs/en/skills. This gives us per-workflow
# isolation — workflow A's wired skills never bleed into
- # workflow B's subprocess even when both spawn with
- # ``cwd=repo_root``. Paired with the conditional ``Skill``
+ # workflow B's subprocess (each spawns in a worktree under its
+ # own workspace). Paired with the conditional ``Skill``
# entry in ``--allowedTools`` (see ``interactive_argv``) —
# both fire when ``connected_skill_names`` is non-empty.
# Falls back to ``cwd`` only when no workspace_dir was
@@ -1177,44 +1177,28 @@ class ClaudeSessionPool:
if kind == "spawned":
await broadcaster.broadcast_claude_session_spawned(
wire_node_id,
- session_uuid=(
- "" if context_scoped else payload["session_uuid"]
- ),
+ session_uuid=payload["session_uuid"],
pid=payload["pid"],
workflow_id=workflow_id,
)
elif kind == "cleared":
await broadcaster.broadcast_claude_session_cleared(
wire_node_id,
- old_session_uuid=(
- ""
- if context_scoped
- else payload["old_session_uuid"]
- ),
- new_session_uuid=(
- ""
- if context_scoped
- else payload["new_session_uuid"]
- ),
+ old_session_uuid=payload["old_session_uuid"],
+ new_session_uuid=payload["new_session_uuid"],
workflow_id=workflow_id,
)
elif kind == "terminated":
await broadcaster.broadcast_claude_session_terminated(
wire_node_id,
reason=payload["reason"],
- session_uuid=(
- None
- if context_scoped
- else payload.get("session_uuid")
- ),
+ session_uuid=payload.get("session_uuid"),
workflow_id=workflow_id,
)
elif kind == "usage":
await broadcaster.broadcast_claude_session_usage(
wire_node_id,
- session_uuid=(
- "" if context_scoped else payload["session_uuid"]
- ),
+ session_uuid=payload["session_uuid"],
total_cost_usd=payload.get("total_cost_usd"),
input_tokens=payload.get("input_tokens", 0),
output_tokens=payload.get("output_tokens", 0),
diff --git a/server/nodes/agent/claude_code_agent/_skills.py b/server/nodes/agent/claude_code_agent/_skills.py
index b2714426..f271686c 100644
--- a/server/nodes/agent/claude_code_agent/_skills.py
+++ b/server/nodes/agent/claude_code_agent/_skills.py
@@ -18,9 +18,10 @@ this filesystem layer.
Why workspace_dir (not cwd)
---------------------------
-Memory-bound pool runs spawn with ``cwd = repo_root`` so claude's
-``project_key`` stays stable for ``--continue`` / ``--resume``.
-Writing skills into ``<repo_root>/.claude/skills/`` would:
+Pool runs spawn in a git worktree under the workspace (a stable
+``wt_session`` per agent node for bound runs) so claude's ``project_key``
+stays stable for ``--resume``. Writing skills into the worktree's own
+``.claude/skills/`` would:
- Pollute the user's repo (gitignored, but visible).
- Accumulate stale SKILL.md trees across workflow runs that wired
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index 61c3c71f..c91e9ca1 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -38,7 +38,7 @@ from services.cli_agent.context_bridge import (
SpecializedAgentContextBridge,
is_context,
)
-from services.cli_agent.factory import create_cli_provider
+from services.cli_agent.factory import create_cli_provider, get_session_pool
from services.cli_agent.mcp_server import (
BatchContext,
issue_token,
@@ -145,10 +145,9 @@ class AICliService:
# ``Edit``, ``Glob``, ``Grep``, ``Write``, ``Bash``) can access
# files produced by upstream nodes (``fileDownloader``,
# ``documentParser``, ``code`` executors, etc.). Without this
- # the workspace is invisible to claude: memory-bound runs spawn
- # with ``cwd=repo_root`` and non-memory runs with
- # ``cwd=worktree``, neither of which sees the workflow's
- # workspace files.
+ # the workspace is invisible to claude: every session spawns in a
+ # git worktree under ``<workspace>/<node>/``, which does not see
+ # the workflow's workspace files.
#
# Mirrors the ai_agent pattern (``services/ai.py:1899`` —
# ``config['workspace_dir'] = context.get('workspace_dir', '')``),
@@ -347,19 +346,37 @@ class AICliService:
# terminated once the whole batch is done so the shared
# token is unregistered exactly once (``unregister_batch``
# is idempotent).
- use_pool = provider_name == "claude"
+ # A provider that registered a session pool from its plugin folder
+ # (``register_session_pool``) runs pooled; the service never names
+ # providers. Every pooled session runs in a git worktree under the
+ # workflow workspace, branched off ``resolved_repo_root`` — the same
+ # isolation the per-task ``AICliSession`` path uses — so the repo
+ # root itself is never the CLI's cwd. Bound sessions keep one
+ # stable worktree per agent node; ephemeral tasks get their own and
+ # drop it afterwards.
+ session_pool = get_session_pool(provider_name)
+ use_pool = session_pool is not None
bound_key = (
context_bridge.pool_key
if context_bridge is not None
else connected_memory["node_id"] if connected_memory else None
)
+ from core.paths import safe_path_component
+ from services.cli_agent.worktree import add_worktree, remove_worktree
- async def run_pooled(task: BaseAICliTaskSpec, session_key: Any) -> SessionResult:
+ worktree_parent = Path(workspace_dir).resolve() / safe_path_component(node_id, "node")
+
+ async def run_pooled(task: BaseAICliTaskSpec, session_key: Any, worktree_name: str) -> SessionResult:
async with sem:
+ cwd = await add_worktree(
+ resolved_repo_root,
+ worktree_parent / f"wt_{worktree_name}",
+ f"opencompany/{safe_path_component(node_id, 'node')}-{worktree_name}",
+ )
return await self._run_pooled_turn(
task=task,
session_key=session_key,
- cwd=resolved_repo_root,
+ cwd=cwd,
workspace_dir=Path(workspace_dir).resolve(),
defaults=defaults,
mcp_port=port,
@@ -372,21 +389,22 @@ class AICliService:
results: List[SessionResult]
try:
if use_pool and bound_key is not None:
- results = [await run_pooled(task_list[0], bound_key)]
+ results = [await run_pooled(task_list[0], bound_key, "session")]
elif use_pool:
- ephemeral_keys = [f"{node_id}:{turn_execution_id}:{i}" for i in range(len(task_list))]
+ run_tag = str(turn_execution_id)[:8]
+ ephemeral = [(f"{node_id}:{turn_execution_id}:{i}", f"{run_tag}_{i}") for i in range(len(task_list))]
try:
results = await asyncio.gather(
- *(run_pooled(t, k) for t, k in zip(task_list, ephemeral_keys)),
+ *(run_pooled(t, key, name) for t, (key, name) in zip(task_list, ephemeral)),
return_exceptions=False,
)
finally:
- from services.cli_agent.factory import get_session_pool
-
- pool = get_session_pool("claude")
- if pool is not None:
- for k in ephemeral_keys:
- await pool.terminate(k)
+ for key, name in ephemeral:
+ await session_pool.terminate(key)
+ try:
+ await remove_worktree(resolved_repo_root, worktree_parent / f"wt_{name}")
+ except Exception as exc:
+ logger.debug("[CC-Agent run_batch] worktree remove: %s", exc)
else:
results = await asyncio.gather(
*(run_one(t) for t in task_list),
@@ -622,17 +640,15 @@ class AICliService:
instead of importing directly so the framework stays free of
any ``services → nodes`` layering violation.
"""
- from services.cli_agent.factory import get_session_pool
-
if not isinstance(task, ClaudeTaskSpec):
raise TypeError("Pooled turns require ClaudeTaskSpec, got " f"{type(task).__name__}")
- pool = get_session_pool("claude")
+ pool = get_session_pool(task.provider)
if pool is None:
raise RuntimeError(
- "No session pool registered for 'claude'. The "
- "claude_code_agent plugin's __init__.py should call "
- "register_session_pool('claude', get_session_pool). "
+ f"No session pool registered for {task.provider!r}. The "
+ "provider's plugin __init__.py should call "
+ "register_session_pool(<provider>, get_session_pool). "
"Did its module fail to import?"
)
await pool.start_reaper()
diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.py
index cf3fcafc..71880c89 100644
--- a/server/services/cli_agent/session.py
+++ b/server/services/cli_agent/session.py
@@ -49,7 +49,6 @@ import uuid
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional
-import anyio
from core.logging import get_logger
from core.paths import safe_path_component
@@ -242,30 +241,9 @@ class AICliSession(BaseProcessSupervisor):
# 1. Per-task git worktree — skipped for memory-bound runs
# which use cwd=repo_root to keep claude's project_key stable.
if not self._memory_bound:
- self._worktree_dir.parent.mkdir(parents=True, exist_ok=True)
- wt_proc = await anyio.run_process(
- [
- "git",
- "-C",
- str(self._repo_root),
- "worktree",
- "add",
- str(self._worktree_dir),
- "-b",
- self._branch,
- ],
- check=False,
- )
- if wt_proc.returncode != 0:
- err = (
- (wt_proc.stderr or b"")
- .decode(
- "utf-8",
- errors="replace",
- )
- .strip()
- )
- raise RuntimeError(f"git worktree add failed: {err}")
+ from services.cli_agent.worktree import add_worktree
+
+ await add_worktree(self._repo_root, self._worktree_dir, self._branch)
else:
logger.info(
"[%s] memory-bound: skipping worktree, using cwd=%s",
@@ -801,18 +779,9 @@ class AICliSession(BaseProcessSupervisor):
# runs; memory-bound spawns ran directly under repo_root).
if not self._memory_bound:
try:
- await anyio.run_process(
- [
- "git",
- "-C",
- str(self._repo_root),
- "worktree",
- "remove",
- "--force",
- str(self._worktree_dir),
- ],
- check=False,
- )
+ from services.cli_agent.worktree import remove_worktree
+
+ await remove_worktree(self._repo_root, self._worktree_dir)
except Exception as exc:
self._logger.debug("[%s] worktree remove: %s", self.label, exc)
diff --git a/server/services/cli_agent/worktree.py b/server/services/cli_agent/worktree.py
new file mode 100644
index 00000000..4fcfaec4
--- /dev/null
+++ b/server/services/cli_agent/worktree.py
@@ -0,0 +1,40 @@
+"""Per-workflow git worktrees for CLI agent sessions.
+
+Every CLI session runs inside a worktree branched off the repo that
+contains the workflow workspace, never in the repo root itself. That keeps
+one workflow's edits off another's checkout and gives a pooled session a
+stable, workflow-owned cwd. The ``git worktree add`` / ``remove`` calls
+lived in ``AICliSession``; they are shared here so the session pool path
+uses the same commands.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import anyio
+
+
+async def add_worktree(repo_root: Path, worktree_dir: Path, branch: str) -> Path:
+ """Create ``worktree_dir`` as a new worktree of ``repo_root`` on a new
+ ``branch``. Reuses an existing worktree directory as-is. Raises
+ ``RuntimeError`` with git's stderr on failure."""
+ if worktree_dir.exists():
+ return worktree_dir
+ worktree_dir.parent.mkdir(parents=True, exist_ok=True)
+ proc = await anyio.run_process(
+ ["git", "-C", str(repo_root), "worktree", "add", str(worktree_dir), "-b", branch],
+ check=False,
+ )
+ if proc.returncode != 0:
+ err = (proc.stderr or b"").decode("utf-8", errors="replace").strip()
+ raise RuntimeError(f"git worktree add failed: {err}")
+ return worktree_dir
+
+
+async def remove_worktree(repo_root: Path, worktree_dir: Path) -> None:
+ """Best-effort ``git worktree remove --force``."""
+ await anyio.run_process(
+ ["git", "-C", str(repo_root), "worktree", "remove", "--force", str(worktree_dir)],
+ check=False,
+ )
diff --git a/server/tests/nodes/test_specialized_context_bridges.py b/server/tests/nodes/test_specialized_context_bridges.py
index fb2b6a5e..67c32f78 100644
--- a/server/tests/nodes/test_specialized_context_bridges.py
+++ b/server/tests/nodes/test_specialized_context_bridges.py
@@ -108,8 +108,9 @@ async def test_claude_node_routes_context_separately_from_v1_memory(harness):
assert kwargs["connected_context"]["kind"] == "context"
task = list(kwargs["tasks"])[0]
assert task.continue_session is False
- assert result["result"]["session_id"] is None
- assert result["result"]["tasks"][0]["session_id"] is None
+ # Claude's own session UUID stays visible on Context-bound runs.
+ assert result["result"]["session_id"] == "uuid-1"
+ assert result["result"]["tasks"][0]["session_id"] == "uuid-1"
@pytest.mark.asyncio
diff --git a/server/tests/services/cli_agent/test_service.py b/server/tests/services/cli_agent/test_service.py
index 412a564d..8a7e977c 100644
--- a/server/tests/services/cli_agent/test_service.py
+++ b/server/tests/services/cli_agent/test_service.py
@@ -280,6 +280,20 @@ async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):
stub_pool = _StubPool()
monkeypatch.setattr(factory_mod, "get_session_pool", lambda name: stub_pool)
+ monkeypatch.setattr(svc_mod, "get_session_pool", lambda name: stub_pool)
+
+ # Pooled sessions run in a git worktree under the workspace; stub the
+ # git calls so the test never touches the real checkout.
+ from services.cli_agent import worktree as worktree_mod
+
+ added: list = []
+
+ async def fake_add(repo_root, worktree_dir, branch): # noqa: ANN001
+ added.append(worktree_dir)
+ return worktree_dir
+
+ monkeypatch.setattr(worktree_mod, "add_worktree", fake_add)
+ monkeypatch.setattr(worktree_mod, "remove_worktree", AsyncMock())
svc = get_ai_cli_service()
workspace = Path(__file__).resolve().parents[3] # the repo root (a git repo)
@@ -330,3 +344,8 @@ async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):
# Unbound run: the ephemeral pooled session is torn down after the batch.
assert len(terminated) == 1
assert terminated[0].startswith("ccode_test_happy:")
+ # It ran in its own worktree under the workspace, never in the repo root.
+ assert len(added) == 1
+ assert added[0].parent == workspace / "ccode_test_happy"
+ assert added[0].name.startswith("wt_")
+ assert worktree_mod.remove_worktree.await_count == 1