Skip to content

Self-improving AI Employees for everyone

fix(cli_agent): route every Claude run through the session pool; resume by UUID

trohitg34e646b2f3f3
diff --git a/server/nodes/agent/claude_code_agent/__init__.py b/server/nodes/agent/claude_code_agent/__init__.py
index 622a1ca3..6b495445 100644
--- a/server/nodes/agent/claude_code_agent/__init__.py
+++ b/server/nodes/agent/claude_code_agent/__init__.py
@@ -300,33 +300,32 @@ class ClaudeCodeAgentNode(ActionNode):
# under `<CLAUDE_CONFIG_DIR>/projects/<cwd-encoded>/<UUID>.jsonl`.
# Context V2 resolution, explicit UUID resume, raw-event journalling,
# and binding persistence live in AICliService.
- # The project_key is derived from cwd (`[^a-zA-Z0-9.-] -> -`),
+ # The project_key is derived from cwd (`[^a-zA-Z0-9-] -> -`),
# so memory continuity needs only a STABLE cwd across runs.
# That's handled by AICliService passing memory_bound=True so
# AICliSession spawns under repo_root instead of an ephemeral
# worktree — see `services/cli_agent/session.py:cwd()`.
#
- # Continuity flag: when memory is wired, we set
- # ``continue_session=True`` on the task spec. The argv-builder
- # emits ``--continue`` and claude auto-loads the most recent
- # conversation under the cwd (per code.claude.com/docs/en/
- # cli-reference). No UUID round-trip through the memory node's
- # params required — claude tracks its own sessions on disk and
- # the auto-find-latest is the cleaner primitive than the
- # pre-cutover UUID5-pre-mint + `--session-id <UUID5>` dance.
- #
- # First run: ``--continue`` with no prior session under the cwd
- # is a benign no-op; claude starts fresh. Subsequent runs find
- # and continue the prior JSONL.
+ # Continuity: when memory is wired, resume the UUID the previous
+ # successful run persisted on the memory node (``last_session_id``,
+ # written by ``AICliService._persist_memory``) via ``--resume``.
+ # ``--continue`` is NOT usable here: per the CLI reference it
+ # skips sessions created non-interactively (``-p`` / stream-json
+ # input), which is exactly what the session pool spawns, so it
+ # never found the prior conversation. First run: no stored UUID,
+ # no flag — the pool mints a ``--session-id`` and the run's
+ # result persists it for next time. A stale UUID is cleared by
+ # ``_persist_memory`` when claude reports it as not found.
from services.cli_agent.context_bridge import is_context
context_v2 = context_data if is_context(context_data) else None
memory_data = context_data if context_data and not context_v2 else None
- continue_session = bool(memory_data)
+ resume_session_id = (memory_data or {}).get("last_session_id") or None
if memory_data:
logger.info(
- "[Claude Code memory] memory_node=%s -> --continue " "(claude auto-finds latest session under cwd)",
+ "[Claude Code memory] memory_node=%s -> %s",
memory_data.get("node_id"),
+ f"--resume {resume_session_id}" if resume_session_id else "fresh session (no last_session_id yet)",
)
tasks = list(params.tasks)
@@ -352,7 +351,7 @@ class ClaudeCodeAgentNode(ActionNode):
"prompt": prompt,
"model": params.model,
"system_prompt": params.system_prompt,
- "continue_session": continue_session,
+ "resume_session_id": resume_session_id,
}
if params.effort is not None:
spec_kwargs["effort"] = params.effort
@@ -371,10 +370,11 @@ class ClaudeCodeAgentNode(ActionNode):
changed["effort"] = params.effort
if t.fallback_model is None and params.fallback_model is not None:
changed["fallback_model"] = params.fallback_model
- # Only auto-enable --continue when memory is wired AND
- # the task didn't explicitly opt in/out or pick a UUID.
- if continue_session and not t.continue_session and not t.resume_session_id:
- changed["continue_session"] = True
+ # Only auto-resume the memory session when memory is
+ # wired AND the task didn't explicitly opt in/out or
+ # pick its own UUID.
+ if resume_session_id and not t.continue_session and not t.resume_session_id:
+ changed["resume_session_id"] = resume_session_id
if changed:
tasks[i] = t.model_copy(update=changed)
diff --git a/server/nodes/agent/claude_code_agent/_pool.py b/server/nodes/agent/claude_code_agent/_pool.py
index 68578b4f..4dbeaac4 100644
--- a/server/nodes/agent/claude_code_agent/_pool.py
+++ b/server/nodes/agent/claude_code_agent/_pool.py
@@ -51,15 +51,16 @@ Lifecycle policy:
Continuity across process restarts:
- - First spawn for a memory-bound run: argv emits ``--continue``
- (claude resolves the latest conversation under cwd's
- ``project_key`` automatically; works whether or not a prior
- JSONL exists).
- - Each successful turn captures ``result.session_id`` onto
- ``session.current_session_uuid``. If the subprocess is later
- reaped and a new ``acquire`` happens, the next spawn emits
- ``--resume <session.current_session_uuid>`` so the SAME JSONL
- keeps growing across process restarts.
+ - Cold spawn with no continuity flag: ``_spawn`` mints a ``uuid4``
+ and emits ``--session-id <UUID>``, so ``current_session_uuid`` is
+ known before the first event arrives.
+ - Memory-bound runs pass ``--resume <last_session_id>`` (persisted
+ on the memory node by ``AICliService._persist_memory``). Never
+ ``--continue``: the CLI resolves it only against interactive
+ sessions, so it never found the sessions this pool creates.
+ - If the subprocess is later reaped and a new ``acquire`` happens,
+ the next spawn emits ``--resume <session.current_session_uuid>``
+ so the SAME JSONL keeps growing across process restarts.
- :meth:`clear` is an explicit context-reset primitive: kill the
subprocess, drop the captured UUID, let the next ``acquire``
spawn fresh with no continuity flag (claude assigns a new UUID).
@@ -627,6 +628,22 @@ class ClaudeSessionPool:
success=False,
error=session.context_capture_error,
)
+ if not any(self._provider.is_final_event(e) for e in session.events_this_turn):
+ # Woken by stdout EOF, not by a ``result`` event: the
+ # subprocess died mid-turn. Report the exit code so the
+ # failure is diagnosable; whatever assistant text was
+ # buffered is still reconstructed by the provider.
+ try:
+ await asyncio.wait_for(session.process.wait(), timeout=_SHUTDOWN_GRACE)
+ except asyncio.TimeoutError:
+ pass
+ return self._build_result_from_events(
+ session=session,
+ events=session.events_this_turn,
+ prompt=prompt,
+ success=False,
+ error=(f"claude exited (code {session.process.returncode}) " "before emitting a result event"),
+ )
except asyncio.TimeoutError:
logger.warning(
"[ClaudeSessionPool] turn timeout memory_node=%s " "prompt_len=%d",
@@ -716,6 +733,14 @@ class ClaudeSessionPool:
log_label=f"pool {memory_node_id}",
)
+ # Cold spawn with no continuity flag: mint the session UUID here
+ # and pass it as ``--session-id`` so ``current_session_uuid`` is
+ # known before any event arrives. Crash-recovery respawns then
+ # always have a UUID to ``--resume`` (``acquire`` splices it), and
+ # memory persistence never depends on capturing it from stdout.
+ if not spec.resume_session_id and not spec.continue_session and not spec.session_id:
+ spec.session_id = str(uuid.uuid4())
+
# ``include_prompt`` is ignored by the new ``interactive_argv``
# (stream-json input mode reads the prompt from stdin), but we
# pass ``False`` to make the intent explicit for any future
@@ -747,6 +772,7 @@ class ClaudeSessionPool:
process=process,
cwd=cwd,
context_event_sink=context_event_sink,
+ current_session_uuid=spec.resume_session_id or spec.session_id or "",
)
# stdout reader — the single runtime contract in stream-json
@@ -761,6 +787,11 @@ class ClaudeSessionPool:
while True:
raw = await process.stdout.readline()
if not raw:
+ # stdout EOF means claude exited. Wake ``send_turn``
+ # now instead of letting it burn the full turn
+ # timeout waiting for a ``result`` that can never
+ # arrive (GitHub issue #133).
+ session.result_event.set()
return
line = raw.decode("utf-8", errors="replace").strip()
if not line:
diff --git a/server/nodes/agent/claude_code_agent/_provider.py b/server/nodes/agent/claude_code_agent/_provider.py
index 200a0809..17bda1b7 100644
--- a/server/nodes/agent/claude_code_agent/_provider.py
+++ b/server/nodes/agent/claude_code_agent/_provider.py
@@ -1,17 +1,19 @@
-"""Anthropic Claude Code CLI provider — interactive TUI mode.
+"""Anthropic Claude Code CLI provider — stream-json over stdio pipes.
Reference implementation for the `AICliProvider` Protocol. OpenCompany
-drives the same interactive `claude` invocation a normal user runs at
-their terminal — not `claude -p` headless. The PTY keeps the process
-alive in TUI mode while we read events from the on-disk session JSONL
-at ``<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session>.jsonl``
-instead of from stdout. See ``docs-internal/claude_code_interactive_mode.md``.
-
-Subprocess: ``claude --permission-mode bypassPermissions
---allowedTools <list> [--model ...] [--append-system-prompt ...]
-[--mcp-config ...] [--strict-mcp-config] [--resume <UUID>]
-[--effort ...] [--add-dir ...] [--disallowedTools ...] [--agent ...]
--- "<prompt>"``
+spawns ``claude`` as a plain subprocess with piped stdin/stdout/stderr
+(``ClaudeSessionPool``) and speaks the CLI's stream-json protocol: one
+``{"type":"user","message":{...}}`` line per turn on stdin, one JSON
+event per line on stdout, ending each turn with ``type == "result"``.
+No PTY, no on-disk JSONL parsing. See
+``docs-internal/claude_code_interactive_mode.md``.
+
+Subprocess: ``claude --output-format stream-json --input-format
+stream-json --verbose --ide [--mcp-config ...] [--strict-mcp-config]
+--model <m> [--resume <UUID> | --continue | --session-id <UUID>]
+[--allowedTools <list>] --permission-mode <mode>
+[--append-system-prompt ...] [--effort ...] [--add-dir ...]
+[--disallowedTools ...] [--agent ...]``
**Tools + skills are preserved**:
- ``--mcp-config`` registers OpenCompany's FastMCP server; the spawned
@@ -31,25 +33,29 @@ the keyboard to click "Allow." Behaviorally equivalent to
mode (``code.claude.com/docs/en/permission-modes``) and is the same
flag a Composio AO "permissionless" launch sets.
-Flags dropped in the interactive cutover (no longer emitted; the
-on-disk JSONL gives us the same data without `-p`):
-``-p / --print``, ``--output-format``, ``--verbose``,
-``--include-partial-messages``, ``--include-hook-events``,
-``--max-turns``, ``--max-budget-usd``, ``--session-id``,
-``--fallback-model``. ``--max-budget-usd`` / ``--max-turns`` become
-external monitors (Phase 2).
+Session identity: a cold spawn with no continuity flag gets a
+host-minted ``--session-id <UUID>`` (``ClaudeSessionPool._spawn``) so the
+UUID is known before the first event; memory-bound runs and crash
+recovery pass ``--resume <UUID>``. ``--continue`` is kept on the spec
+for callers that ask for it, but the CLI resolves it only against
+interactive sessions, so the node never sets it.
+
+Not emitted: ``-p`` / ``--print`` (the Agent SDK does not pass it
+either), ``--include-partial-messages``, ``--include-hook-events``,
+``--max-turns``, ``--max-budget-usd``, ``--fallback-model`` (print-mode
+only; the spec keeps the fields for back-compat), and a positional
+prompt (the prompt travels over stdin).
Binary + auth: shared with the auth surface via
-``._oauth.claude_binary_path()`` — single managed install under
-``<DATA_DIR>/packages/`` and ``CLAUDE_CONFIG_DIR``
-set on the spawn env so the agent picks up the same credentials the
-Login button wrote.
-
-Final event (parsed off disk by ``JsonlWatcher``): ``type == "result"``
-carries ``total_cost_usd``, ``duration_ms``, ``num_turns``,
-``session_id``, and the assistant's ``result`` string — same shape `-p`
-used to write to stdout (Claude Code CHANGELOG 2.1.101 / 2.1.126
-confirms the shared JSONL writer).
+``._oauth.claude_binary_path()`` — single managed install of the pinned
+``package_version`` under ``<DATA_DIR>/packages/`` and
+``CLAUDE_CONFIG_DIR`` set on the spawn env so the agent picks up the
+same credentials the Login button wrote.
+
+Final event: ``type == "result"`` on stdout carries ``total_cost_usd``,
+``duration_ms``, ``num_turns``, ``session_id``, ``usage`` and the
+assistant's ``result`` string. It is stdout-only — the on-disk session
+JSONL never contains it — so completion is detected from the stream.
"""
from __future__ import annotations
@@ -222,14 +228,18 @@ class AnthropicClaudeProvider:
# tracks its own sessions on disk under
# ``<CLAUDE_CONFIG_DIR>/projects/<project_key>/`` and
# ``--continue`` picks the newest.
- # - Neither → no flag (fresh session; claude assigns a new
- # UUID which the post-spawn JSONL locator discovers).
- # ``--session-id`` is intentionally NOT emitted in interactive
- # mode — the CLI rejects it.
+ # - ``session_id`` set → ``--session-id <UUID>`` (host-minted
+ # on cold spawn by ``ClaudeSessionPool._spawn`` so the UUID
+ # is known before the first event; the CLI requires a valid
+ # UUID and rejects one that is already in use).
+ # - None of the three → no flag; claude assigns its own UUID,
+ # reported on ``system/init``.
if task.resume_session_id:
argv += ["--resume", task.resume_session_id]
elif task.continue_session:
argv += ["--continue"]
+ elif task.session_id:
+ argv += ["--session-id", task.session_id]
# Allowed tools — STRICTLY scoped to what the operator wired
# through ``input-tools`` plus OpenCompany's own MCP infrastructure
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index 51a34a71..61c3c71f 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -332,40 +332,61 @@ class AICliService:
except (KeyError, ValueError):
pass
- # Pool branch: when memory is connected to a claude task, route
- # through ``ClaudeSessionPool`` so successive turns reuse the
- # warm PTY via ``/clear`` (saves ~1-2 s per turn). The
- # ``claude_code_agent`` plugin already enforces ``len(tasks)==1``
- # when memory is wired, so this branch is single-task. The pool
- # owns the PTY lifetime; the bearer token stays embedded in the
- # spawned claude's argv across batches (CLI handles its own MCP
- # auth — we don't issue/unregister per turn).
- use_pool = (
- provider_name == "claude"
- and len(task_list) == 1
- and (bool(connected_memory) or context_bridge is not None)
+ # Pool branch: every claude task runs through ``ClaudeSessionPool``
+ # — a plain subprocess on stdio pipes speaking stream-json, the
+ # same invocation the Agent SDK uses. ``AICliSession`` (PTY +
+ # on-disk JSONL) never delivered the prompt on this provider and
+ # a PTY stdin makes the CLI reject stream-json input (GitHub
+ # issues #133 / #134), so it is no longer used for claude.
+ #
+ # - Memory- or Context-bound: one warm session keyed by the
+ # conversation, released after the turn so later turns reuse
+ # it. The plugin enforces ``len(tasks)==1`` here. The pool
+ # owns the bearer token across batches (see the ``finally``).
+ # - Unbound: one ephemeral session per task keyed by task id,
+ # terminated once the whole batch is done so the shared
+ # token is unregistered exactly once (``unregister_batch``
+ # is idempotent).
+ use_pool = provider_name == "claude"
+ bound_key = (
+ context_bridge.pool_key
+ if context_bridge is not None
+ else connected_memory["node_id"] if connected_memory else None
)
+
+ async def run_pooled(task: BaseAICliTaskSpec, session_key: Any) -> SessionResult:
+ async with sem:
+ return await self._run_pooled_turn(
+ task=task,
+ session_key=session_key,
+ cwd=resolved_repo_root,
+ workspace_dir=Path(workspace_dir).resolve(),
+ defaults=defaults,
+ mcp_port=port,
+ mcp_bearer_token=token,
+ connected_tools=connected_tools or [],
+ connected_skill_names=list(connected_skill_names or []),
+ workflow_id=workflow_id,
+ )
+
results: List[SessionResult]
try:
- if use_pool:
- results = [
- await self._run_pooled_turn(
- task=task_list[0],
- session_key=(
- context_bridge.pool_key
- if context_bridge is not None
- else connected_memory["node_id"]
- ),
- cwd=resolved_repo_root,
- workspace_dir=Path(workspace_dir).resolve(),
- defaults=defaults,
- mcp_port=port,
- mcp_bearer_token=token,
- connected_tools=connected_tools or [],
- connected_skill_names=list(connected_skill_names or []),
- workflow_id=workflow_id,
+ if use_pool and bound_key is not None:
+ results = [await run_pooled(task_list[0], bound_key)]
+ elif use_pool:
+ ephemeral_keys = [f"{node_id}:{turn_execution_id}:{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)),
+ 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)
else:
results = await asyncio.gather(
*(run_one(t) for t in task_list),
diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.py
index 88788522..f9c04fb9 100644
--- a/server/services/cli_agent/session.py
+++ b/server/services/cli_agent/session.py
@@ -1,5 +1,11 @@
"""One CLI session per task — interactive PTY + on-disk JSONL events.
+**Not used for Claude.** ``AICliService.run_batch`` routes every Claude
+task through ``ClaudeSessionPool`` (plain pipes + stream-json): a PTY
+stdin makes the CLI reject ``--input-format stream-json``, and this
+class never wrote the prompt to the child (GitHub #133 / #134). It
+remains the generic PTY + JSONL path for other providers.
+
Each session is bound to:
- one provider (Claude or Codex)
- one task spec (`ClaudeTaskSpec` / `CodexTaskSpec`)
@@ -57,10 +63,11 @@ from services.cli_agent.types import BaseAICliTaskSpec
logger = get_logger(__name__)
# Claude derives its project_key from cwd by replacing every char that
-# isn't [a-zA-Z0-9.-] with `-`. Verified byte-for-byte against the
-# on-disk `<DATA_DIR>/claude/projects/` listing in the memory-bridge
-# research.
-_PROJECT_KEY_RE = re.compile(r"[^a-zA-Z0-9.-]")
+# isn't [a-zA-Z0-9-] with `-` (dots included: `.opencompany` becomes
+# `-opencompany`). Verified against the on-disk `~/.claude/projects/`
+# listing; keeping `.` in the class watched a directory the CLI never
+# wrote to (GitHub issue #132).
+_PROJECT_KEY_RE = re.compile(r"[^a-zA-Z0-9-]")
# How long to wait for claude to materialise its session JSONL after
# spawn on a first-run (no `--resume`). Five seconds is generous —
@@ -432,10 +439,8 @@ class AICliSession(BaseProcessSupervisor):
our cwd. ``<OPENCOMPANY_CLAUDE_DIR>/projects/<project_key>/``.
Claude derives ``project_key`` by replacing every non-
- ``[a-zA-Z0-9.-]`` char in ``str(cwd)`` with ``-``. Verified
- byte-for-byte against the on-disk
- ``<DATA_DIR>/claude/projects/`` listing in the memory-bridge
- research.
+ ``[a-zA-Z0-9-]`` char in ``str(cwd)`` with ``-`` (see
+ ``_PROJECT_KEY_RE``).
"""
from nodes.agent.claude_code_agent._oauth import OPENCOMPANY_CLAUDE_DIR
diff --git a/server/services/cli_agent/types.py b/server/services/cli_agent/types.py
index aee7cd06..17e25583 100644
--- a/server/services/cli_agent/types.py
+++ b/server/services/cli_agent/types.py
@@ -66,27 +66,23 @@ class ClaudeTaskSpec(BaseAICliTaskSpec):
provider: Literal["claude"] = "claude"
session_id: Optional[str] = Field(
default=None,
- description="Start a named session. Pair with `resume_session_id` "
- "to chain conversations. Note: silently dropped in "
- "interactive mode (claude assigns its own UUID); "
- "kept for back-compat.",
+ description="Session UUID to start under (`--session-id`; must be "
+ "a valid UUID). Minted by the session pool on cold "
+ "spawn when unset; ignored when `resume_session_id` or "
+ "`continue_session` is set.",
)
resume_session_id: Optional[str] = Field(
default=None,
- description="Resume from a specific prior session UUID. Mutually "
- "exclusive with `continue_session`. Generally unset by "
- "claude_code_agent — set `continue_session=True` for "
- "memory-bound runs and let claude find its own latest.",
+ description="Resume a specific prior session UUID (`--resume`). "
+ "Mutually exclusive with `continue_session`. Memory-bound "
+ "runs set this from the memory node's `last_session_id`.",
)
continue_session: bool = Field(
default=False,
- description="Emit `--continue` so claude auto-loads the most "
- "recent conversation under the current cwd (per "
- "code.claude.com/docs/en/cli-reference). The cleaner "
- "alternative to passing a specific UUID via "
- "`resume_session_id` — claude handles session "
- "tracking itself, no UUID round-trip through the "
- "memory node's params required.",
+ description="Emit `--continue` (most recent conversation under the "
+ "current cwd). Note the CLI skips non-interactive "
+ "sessions here, so it does not find sessions this pool "
+ "created; prefer `resume_session_id`.",
)
max_turns: Optional[int] = Field(
default=None,
diff --git a/server/tests/services/cli_agent/test_claude_pool_turn.py b/server/tests/services/cli_agent/test_claude_pool_turn.py
new file mode 100644
index 00000000..50f4edad
--- /dev/null
+++ b/server/tests/services/cli_agent/test_claude_pool_turn.py
@@ -0,0 +1,170 @@
+"""``ClaudeSessionPool`` turn contracts against a fake subprocess.
+
+Covers the stream-json runtime contract without spawning claude:
+ - a cold spawn mints ``--session-id`` and knows the UUID before any
+ event arrives;
+ - a turn completes on the ``result`` stdout event;
+ - stdout EOF (the child died) wakes ``send_turn`` immediately with the
+ exit code instead of burning the full turn timeout (GitHub #133).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+from nodes.agent.claude_code_agent import _pool as pool_mod
+from nodes.agent.claude_code_agent import _provider as provider_mod
+from nodes.agent.claude_code_agent._pool import ClaudeSessionPool
+from services.cli_agent.types import ClaudeTaskSpec
+
+
+class _FakeStdin:
+ def __init__(self) -> None:
+ self.written: list[bytes] = []
+ self.closed = False
+
+ def write(self, data: bytes) -> None:
+ self.written.append(data)
+
+ async def drain(self) -> None:
+ return None
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _FakeProcess:
+ def __init__(self) -> None:
+ self.pid = 4242
+ self.returncode: int | None = None
+ self.stdin = _FakeStdin()
+ self.stdout = asyncio.StreamReader()
+ self.stderr = asyncio.StreamReader()
+ self._exited = asyncio.Event()
+
+ def exit(self, code: int) -> None:
+ self.returncode = code
+ self.stdout.feed_eof()
+ self.stderr.feed_eof()
+ self._exited.set()
+
+ async def wait(self) -> int:
+ await self._exited.wait()
+ return self.returncode or 0
+
+ def kill(self) -> None:
+ if self.returncode is None:
+ self.exit(-9)
+
+
+def _feed(proc: _FakeProcess, event: dict) -> None:
+ proc.stdout.feed_data((json.dumps(event) + "\n").encode("utf-8"))
+
+
+def spawned(monkeypatch):
+ """A pool whose ``_spawn`` lands on a fake process; yields
+ ``(pool, session, proc, argv)``."""
+ captured: dict = {}
+
+ async def fake_exec(*argv, **kwargs):
+ captured["argv"] = list(argv)
+ return captured["proc"]
+
+ monkeypatch.setattr(pool_mod.asyncio, "create_subprocess_exec", fake_exec)
+ # Never touch the shared npm tree from a unit test.
+ monkeypatch.setattr(provider_mod, "claude_binary_path", lambda: "claude")
+ monkeypatch.setattr(pool_mod.ClaudeSessionPool, "_emit_event", AsyncMock())
+
+ pool = ClaudeSessionPool()
+
+ async def _make():
+ # StreamReader / Event need a running loop, so build inside the test.
+ proc = captured["proc"] = _FakeProcess()
+ session = await pool._spawn(
+ memory_node_id="node:turn:0",
+ spec=ClaudeTaskSpec(prompt="hi"),
+ cwd=Path.cwd(),
+ env={},
+ defaults={},
+ mcp_endpoint_url=None,
+ mcp_bearer_token=None,
+ connected_tool_names=None,
+ )
+ return pool, session, proc, captured["argv"]
+
+ return _make
+
+
+async def test_cold_spawn_mints_session_id(spawned):
+ _pool, session, proc, argv = await spawned()
+ idx = argv.index("--session-id")
+ assert argv[idx + 1] == session.current_session_uuid
+ assert session.current_session_uuid # known before any event
+ proc.exit(0)
+
+
+async def test_turn_completes_on_result_event(spawned):
+ pool, session, proc, _argv = await spawned()
+ sid = session.current_session_uuid
+
+ async def drive():
+ await asyncio.sleep(0)
+ _feed(proc, {"type": "system", "subtype": "init", "session_id": sid})
+ _feed(proc, {"type": "assistant", "message": {"content": [{"type": "text", "text": "OK"}]}, "session_id": sid})
+ _feed(
+ proc,
+ {"type": "result", "subtype": "success", "result": "OK", "session_id": sid, "num_turns": 1, "usage": {}},
+ )
+
+ asyncio.create_task(drive())
+ result = await asyncio.wait_for(pool.send_turn(session, "hi", timeout_seconds=10), timeout=5)
+
+ assert result.success is True
+ assert result.response == "OK"
+ assert result.session_id == sid
+ sent = json.loads(proc.stdin.written[0].decode("utf-8"))
+ assert sent == {"type": "user", "message": {"role": "user", "content": "hi"}}
+ proc.exit(0)
+
+
+async def test_child_exit_without_result_fails_fast(spawned):
+ pool, session, proc, _argv = await spawned()
+
+ async def die():
+ await asyncio.sleep(0)
+ _feed(proc, {"type": "assistant", "message": {"content": [{"type": "text", "text": "partial"}]}})
+ proc.exit(1)
+
+ asyncio.create_task(die())
+ # The turn timeout is far longer than the test budget: a hang here
+ # means EOF no longer wakes ``send_turn``.
+ result = await asyncio.wait_for(pool.send_turn(session, "hi", timeout_seconds=600), timeout=5)
+
+ assert result.success is False
+ assert "code 1" in (result.error or "")
+ assert "result" in (result.error or "")
+
+
+async def test_exit_before_turn_reports_exit_code(spawned):
+ pool, session, proc, _argv = await spawned()
+ proc.exit(3)
+ await asyncio.sleep(0)
+ result = await pool.send_turn(session, "hi", timeout_seconds=1)
+ assert result.success is False
+ assert "code 3" in (result.error or "")
+
+
+def test_project_key_matches_claude_encoding():
+ """Claude replaces every char outside ``[a-zA-Z0-9-]`` with ``-``,
+ dots included (GitHub #132). Runs are not collapsed."""
+ from services.cli_agent.session import _PROJECT_KEY_RE
+
+ assert _PROJECT_KEY_RE.sub("-", r"E:\Kae\.opencompany\workspaces\x") == "E--Kae--opencompany-workspaces-x"
+ assert _PROJECT_KEY_RE.sub("-", "/home/u/.opencompany/ws") == "-home-u--opencompany-ws"
+ assert _PROJECT_KEY_RE.sub("-", "D:\\startup\\projects\\opencompany") == "D--startup-projects-opencompany"
diff --git a/server/tests/services/cli_agent/test_providers.py b/server/tests/services/cli_agent/test_providers.py
index a3022253..348c5fe8 100644
--- a/server/tests/services/cli_agent/test_providers.py
+++ b/server/tests/services/cli_agent/test_providers.py
@@ -198,19 +198,21 @@ class TestClaudeArgv:
):
assert forbidden not in entries_with_skills
- def test_no_session_id_flag_in_interactive(self, claude_provider):
- """Claude assigns its own session UUID in interactive mode; we
- no longer pre-mint a UUID and pass it via `--session-id`. The
- `session_id` field on ClaudeTaskSpec is kept for back-compat
- but silently dropped from argv."""
+ def test_session_id_flag_emitted_when_set(self, claude_provider):
+ """A host-minted UUID (``ClaudeSessionPool._spawn`` sets it on a
+ cold spawn with no continuity flag) is passed as ``--session-id``
+ so the session UUID is known before the first stream event."""
task = ClaudeTaskSpec(prompt="x", session_id="sess-abc-123")
argv = claude_provider.interactive_argv(task, defaults={})
- assert "--session-id" not in argv
+ idx = argv.index("--session-id")
+ assert argv[idx + 1] == "sess-abc-123"
+ assert "--resume" not in argv
+ assert "--continue" not in argv
def test_resume_flag_emitted(self, claude_provider):
task = ClaudeTaskSpec(
prompt="x",
- session_id="new-sess", # silently dropped in interactive
+ session_id="new-sess", # loses to an explicit resume
resume_session_id="prior-sess",
)
argv = claude_provider.interactive_argv(task, defaults={})
diff --git a/server/tests/services/cli_agent/test_service.py b/server/tests/services/cli_agent/test_service.py
index 9244d362..412a564d 100644
--- a/server/tests/services/cli_agent/test_service.py
+++ b/server/tests/services/cli_agent/test_service.py
@@ -231,13 +231,15 @@ async def test_run_batch_emits_diagnostic_logs_when_workspace_not_git(monkeypatc
@pytest.mark.asyncio
async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):
- """Happy path: real resolver, real `register_batch`, but
- `AICliSession.start` is short-circuited so we don't spawn `claude`.
+ """Happy path: real resolver, real `register_batch`, but the claude
+ session pool is stubbed so we don't spawn `claude`. Every claude
+ task routes through ``ClaudeSessionPool``; an unbound run gets an
+ ephemeral session that is terminated once the batch settles.
Asserts the `[CC-Agent MCP register_batch]` log fires with the
expected tool list — proving the diagnostic chain is intact
end-to-end and the spawned CLI WOULD see the MCP server registered
for it."""
- from services.cli_agent import session as session_mod
+ from services.cli_agent import factory as factory_mod
from services.cli_agent import service as svc_mod
from services.cli_agent import mcp_server as mcp_mod
from services.cli_agent.protocol import SessionResult
@@ -251,26 +253,33 @@ async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):
monkeypatch.setattr(mcp_mod, "logger", mcp_logger)
started = {"count": 0}
+ terminated: list = []
+
+ class _StubPool:
+ async def start_reaper(self):
+ pass
+
+ async def acquire(self, session_key, **kwargs): # noqa: ANN001
+ started["count"] += 1
+ return SimpleNamespace(memory_node_id=session_key)
+
+ async def send_turn(self, session, prompt, **kwargs): # noqa: ANN001
+ return SessionResult(
+ task_id="t_stub",
+ provider="claude",
+ prompt=prompt,
+ success=True,
+ response="stub",
+ )
- async def _fake_start(self): # noqa: ANN001
- started["count"] += 1
- self._completed = True
-
- async def _fake_wait(self, timeout): # noqa: ANN001, ARG002
- return SessionResult(
- task_id=self.task_id,
- provider=self._provider.name,
- prompt=getattr(self._task, "prompt", ""),
- success=True,
- response="stub",
- )
+ async def release(self, session): # noqa: ANN001
+ pass
- async def _fake_cleanup(self): # noqa: ANN001
- pass
+ async def terminate(self, session_key): # noqa: ANN001
+ terminated.append(session_key)
- monkeypatch.setattr(session_mod.AICliSession, "start", _fake_start)
- monkeypatch.setattr(session_mod.AICliSession, "wait_for_completion", _fake_wait)
- monkeypatch.setattr(session_mod.AICliSession, "cleanup", _fake_cleanup)
+ stub_pool = _StubPool()
+ monkeypatch.setattr(factory_mod, "get_session_pool", lambda name: stub_pool)
svc = get_ai_cli_service()
workspace = Path(__file__).resolve().parents[3] # the repo root (a git repo)
@@ -318,3 +327,6 @@ async def test_run_batch_registers_mcp_batch_on_happy_path(monkeypatch):
# gather, not just the abort path):
assert started["count"] == 1
assert result.n_succeeded == 1
+ # Unbound run: the ephemeral pooled session is torn down after the batch.
+ assert len(terminated) == 1
+ assert terminated[0].startswith("ccode_test_happy:")