Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(cli-agent): native claude session continuity via stable cwd + deterministic UUID5
trohitgecbe69bc6fd3
diff --git a/server/nodes/agent/claude_code_agent.py b/server/nodes/agent/claude_code_agent.pyindex 1335fae1..3d76ff93 100644--- a/server/nodes/agent/claude_code_agent.py+++ b/server/nodes/agent/claude_code_agent.py@@ -17,6 +17,7 @@ and passed to ``run_batch()`` so the MCP server can scope its responses.from __future__ import annotationsimport time+import uuidfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, List, Optional@@ -38,22 +39,6 @@ from services.cli_agent import ClaudeTaskSpec # noqa: E402from services.cli_agent.types import SessionResultModel # noqa: E402-def _compose_system_prompt(- base: Optional[str], memory_context: Optional[str],-) -> Optional[str]:- """Stitch a memory-context block onto a base ``system_prompt``.-- The base (per-task or per-node) sets behaviour ("you are X with Y- persona"); memory context gives prior conversation. Memory comes- AFTER the base so behaviour-defining instructions land first.- """- if not memory_context:- return base- if not base:- return memory_context- return f"{base}\n\n{memory_context}"--class ClaudeCodeAgentParams(BaseModel):"""Multi-task batch parameters for Claude Code.@@ -182,37 +167,52 @@ class ClaudeCodeAgentNode(ActionNode):if s.get("skill_name") or s.get("label")]- # Memory bridge: inject simpleMemory.memory_content (markdown)- # as a system-prompt context block. Universal P2 pattern —- # Cline/Continue/Aider/Cursor/Hermes/Anthropic-SDK all persist- # conversation in caller state and re-pass it each turn.- # `claude -p --session-id` doesn't auto-load and `--resume` is- # broken in headless mode (open bug- # `anthropics/claude-code#43696`), so we paste prior turns as- # `--append-system-prompt`. The same markdown surface aiAgent /- # chatAgent / deep_agent / rlm_agent already use.- memory_context: Optional[str] = None+ # Memory bridge: claude maintains its own session JSONL on disk+ # under `<CLAUDE_CONFIG_DIR>/projects/<cwd-encoded>/<UUID>.jsonl`.+ # The project_key is derived from cwd (`[^a-zA-Z0-9.-] -> -`),+ # so memory continuity needs (a) a STABLE cwd across runs and+ # (b) the right session_id passed on argv.+ #+ # (a) is 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()`.+ #+ # (b) splits on whether claude has run for this memory before:+ #+ # - First run (no last_session_id): pass `--session-id <UUID5>`+ # where UUID5 is deterministically derived from+ # (memory_node_id, simpleMemory.session_id). Claude creates+ # the session at exactly that UUID, writes its JSONL to a+ # predictable location. _persist_memory saves the same+ # UUID as last_session_id after success.+ #+ # - Subsequent runs: pass `--resume <last_session_id>`.+ # Claude finds its own JSONL and continues.+ #+ # Stale-`last_session_id` self-healing: if `--resume` fails with+ # "No conversation found", `_persist_memory` clears the stale+ # UUID; the next run falls into the first-run branch and+ # recovers automatically.+ resume_session_id: Optional[str] = None+ first_run_session_uuid: Optional[str] = Noneif memory_data:- raw = (memory_data.get("memory_content") or "").strip()- has_real_content = bool(raw) and "*No messages yet.*" not in raw+ last = memory_data.get("last_session_id") or None+ if last:+ resume_session_id = last+ else:+ raw = memory_data.get("session_id") or memory_data["node_id"]+ name = f"{memory_data['node_id']}:{raw}"+ first_run_session_uuid = str(+ uuid.uuid5(uuid.NAMESPACE_OID, name)+ )logger.info(- "[Claude Code memory] memory_content_length=%d real_content=%s",- len(raw), has_real_content,+ "[Claude Code memory] memory_node=%s last_session_id=%s "+ "-> %s",+ memory_data.get("node_id"),+ last,+ f"--resume {resume_session_id}" if resume_session_id+ else f"--session-id {first_run_session_uuid} (first run)",)- if has_real_content:- memory_context = (- "## Prior conversation context\n\n"- "The following is the prior conversation between you "- "and the user in this session. Continue naturally "- "from this context without re-introducing yourself "- "or restating prior steps.\n\n"- + raw- )- logger.info(- "[Claude Code memory] injecting %d chars of markdown "- "context as --append-system-prompt",- len(memory_context),- )tasks = list(params.tasks)if not tasks:@@ -236,10 +236,12 @@ class ClaudeCodeAgentNode(ActionNode):spec_kwargs: dict = {"prompt": prompt,"model": params.model,- "system_prompt": _compose_system_prompt(- params.system_prompt, memory_context,- ),+ "system_prompt": params.system_prompt,}+ if resume_session_id:+ spec_kwargs["resume_session_id"] = resume_session_id+ elif first_run_session_uuid:+ spec_kwargs["session_id"] = first_run_session_uuidtasks = [ClaudeTaskSpec(**spec_kwargs)]else:# Apply node-level defaults to tasks that don't override.@@ -247,12 +249,13 @@ class ClaudeCodeAgentNode(ActionNode):changed: dict = {}if not t.model and params.model:changed["model"] = params.model- # System prompt: per-task overrides node-level; memory- # context (if any) appends to whichever wins.- base_sp = t.system_prompt or params.system_prompt- composed = _compose_system_prompt(base_sp, memory_context)- if composed != t.system_prompt:- changed["system_prompt"] = composed+ if not t.system_prompt and params.system_prompt:+ changed["system_prompt"] = params.system_prompt+ if not t.session_id and not t.resume_session_id:+ if resume_session_id:+ changed["resume_session_id"] = resume_session_id+ elif first_run_session_uuid:+ changed["session_id"] = first_run_session_uuidif changed:tasks[i] = t.model_copy(update=changed)diff --git a/server/nodes/skill/simple_memory.py b/server/nodes/skill/simple_memory.pyindex a8ffdc52..71de402c 100644--- a/server/nodes/skill/simple_memory.py+++ b/server/nodes/skill/simple_memory.py@@ -68,6 +68,18 @@ class SimpleMemoryParams(BaseModel):description="Number of relevant memories to retrieve from long-term storage",json_schema_extra={"displayOptions": {"show": {"long_term_enabled": [True]}}},)+ last_session_id: Optional[str] = Field(+ default=None,+ title="Last Claude Session ID",+ description=(+ "Internal: the session UUID claude returned on the most "+ "recent successful run. Drives `--resume <UUID>` on the "+ "next spawn so claude finds and continues its own JSONL "+ "transcript on disk. Hidden from the UI; clearing the "+ "memory wipes this too."+ ),+ json_schema_extra={"hidden": True},+ )model_config = ConfigDict(extra="ignore")diff --git a/server/services/cli_agent/providers/anthropic_claude.py b/server/services/cli_agent/providers/anthropic_claude.pyindex 079b82d8..d453f103 100644--- a/server/services/cli_agent/providers/anthropic_claude.py+++ b/server/services/cli_agent/providers/anthropic_claude.py@@ -219,6 +219,11 @@ class AnthropicClaudeProvider:# System prompt — appended to Claude Code's built-in system promptif task.system_prompt:argv += ["--append-system-prompt", task.system_prompt]+ logger.info(+ "[CC-Agent argv] --append-system-prompt (task) "+ "length=%d preview=%r",+ len(task.system_prompt), task.system_prompt[:200],+ )# Connected-tools steering directive — ensures the agent prefers# wired MCP tools over built-in escape hatches (WebSearch,@@ -237,6 +242,11 @@ class AnthropicClaudeProvider:"purpose.")argv += ["--append-system-prompt", directive]+ logger.info(+ "[CC-Agent argv] --append-system-prompt (tools-directive) "+ "length=%d",+ len(directive),+ )# Optional per-task overrides (documented at code.claude.com/docs/en/cli-reference)if task.effort:diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.pyindex 15291ccf..86709693 100644--- a/server/services/cli_agent/service.py+++ b/server/services/cli_agent/service.py@@ -177,6 +177,7 @@ class AICliService:if t.get("node_type")],connected_skill_names=list(connected_skill_names or []),+ memory_bound=bool(connected_memory),)async with self._lock:self._active_sessions[key].append(session)@@ -217,13 +218,15 @@ class AICliService:unregister_batch(token)# Memory bridge: persist claude's session_id + append the- # rendered exchange to simpleMemory's JSONL transcript so the- # next run can `--resume <UUID>` and the UI shows the- # conversation. Fire-and-forget — failure here doesn't fail- # the batch.+ # rendered exchange to simpleMemory's markdown transcript so the+ # next run can `--resume <UUID>` and the UI sees the+ # conversation refresh live. Fire-and-forget — failure here+ # doesn't fail the batch.if connected_memory:try:- await self._persist_memory(connected_memory, results)+ await self._persist_memory(+ connected_memory, results, broadcaster=broadcaster,+ )except Exception as exc: # pragma: no cover — best-effortlogger.warning("[CC-Agent run_batch] memory persistence failed: %s",@@ -307,10 +310,40 @@ class AICliService:# Internals# ------------------------------------------------------------------+ @staticmethod+ async def _clear_stale_session_id(+ connected_memory: Dict[str, Any],+ ) -> None:+ """Wipe a stale ``last_session_id`` that no longer maps to any+ JSONL under the current cwd's project dir.++ Triggered when claude reports ``No conversation found with+ session ID: <UUID>``. Preserves ``memory_content`` (the+ user-visible markdown mirror) since that's informational; only+ the resume UUID is broken.+ """+ from services.plugin.deps import get_database++ db = get_database()+ memory_node_id = connected_memory["node_id"]+ params = await db.get_node_parameters(memory_node_id) or {}+ prior = params.get("last_session_id")+ if not prior:+ return # already cleared+ params["last_session_id"] = None+ await db.save_node_parameters(memory_node_id, params)+ logger.warning(+ "[CC-Agent _persist_memory] cleared stale last_session_id=%s "+ "from memory_node=%s; next run will spawn a fresh claude "+ "session and persist its new UUID.",+ prior, memory_node_id,+ )+@staticmethodasync def _persist_memory(connected_memory: Dict[str, Any],results: List[SessionResult],+ broadcaster: Any = None,) -> None:"""Append each successful run's user prompt + assistant responseto ``simpleMemory.memory_content`` (markdown). Mirrors aiAgent /@@ -321,10 +354,11 @@ class AICliService:successful = [r for r in results if r.success]logger.info("[CC-Agent _persist_memory] memory_node=%s results=%d "- "successful=%d",+ "successful=%d session_ids=%s",connected_memory.get("node_id"),len(results),len(successful),+ [r.session_id for r in successful],)if not successful:logger.warning(@@ -332,10 +366,26 @@ class AICliService:"save (memory_node=%s). Per-result: %s",connected_memory.get("node_id"),[- {"success": r.success, "error": (r.error or "")[:80]}+ {"success": r.success, "session_id": r.session_id,+ "error": (r.error or "")[:80]}for r in results],)+ # Auto-recovery: claude returns+ # ``No conversation found with session ID: <UUID>`` when the+ # `--resume <UUID>` we passed doesn't exist under the current+ # cwd's project dir (most often: a `last_session_id` saved+ # before the cwd-stability fix landed, or a session JSONL+ # that was wiped). Without this clear the same stale UUID+ # would re-fire on every retry and lock the user out+ # forever. The next run after this point will spawn a+ # fresh session and `_persist_memory` will save its UUID.+ stale = any(+ r.error and "No conversation found with session ID" in r.error+ for r in results+ )+ if stale:+ await AICliService._clear_stale_session_id(connected_memory)returnfrom services.memory import (@@ -348,6 +398,14 @@ class AICliService:memory_node_id = connected_memory["node_id"]params = await db.get_node_parameters(memory_node_id) or {}+ # 1. Persist claude's returned session_id from the most recent+ # successful run. Drives `--resume <UUID>` on the next spawn so+ # claude finds and continues its own JSONL transcript on disk.+ last_run = next((r for r in reversed(successful) if r.session_id), None)+ if last_run is not None:+ params["last_session_id"] = last_run.session_id++ # 2. Update the user-visible markdown mirror.content = params.get("memory_content") or ("# Conversation History\n\n*No messages yet.*\n")@@ -364,11 +422,32 @@ class AICliService:await db.save_node_parameters(memory_node_id, params)logger.info("[CC-Agent _persist_memory] saved memory_node=%s "- "appended_turns=%d archived_blocks=%d content_length=%d",- memory_node_id, len(successful),- len(removed_texts), len(content),+ "last_session_id=%s appended_turns=%d archived_blocks=%d "+ "content_length=%d",+ memory_node_id, params.get("last_session_id"),+ len(successful), len(removed_texts), len(content),)+ # Broadcast `node_parameters_updated` so the simpleMemory's+ # parameter panel + memory editor refetch live without a page+ # reload. Mirrors the pattern in+ # `routers/websocket.py:handle_save_node_parameters`. Without+ # this the DB has the latest conversation but the UI keeps+ # showing the stale snapshot it loaded at workflow open.+ if broadcaster is not None:+ try:+ await broadcaster.broadcast({+ "type": "node_parameters_updated",+ "node_id": memory_node_id,+ "parameters": params,+ "version": 1,+ "timestamp": time.time(),+ })+ except Exception as exc:+ logger.warning(+ "[CC-Agent _persist_memory] broadcast failed: %s", exc,+ )+if connected_memory.get("long_term_enabled") and removed_texts:from services.memory.vector_store import get_memory_vector_storediff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.pyindex 5748555d..e86d18cd 100644--- a/server/services/cli_agent/session.py+++ b/server/services/cli_agent/session.py@@ -66,6 +66,7 @@ class AICliSession(BaseProcessSupervisor):batch_token: str,connected_tool_names: Optional[List[str]] = None,connected_skill_names: Optional[List[str]] = None,+ memory_bound: bool = False,) -> None:super().__init__()self._provider = provider@@ -88,6 +89,15 @@ class AICliSession(BaseProcessSupervisor):# so claude auto-discovers them per the documented project-scope# path (https://code.claude.com/docs/en/skills#where-skills-live).self._connected_skill_names: List[str] = list(connected_skill_names or [])+ # Memory-bound runs use ``cwd=repo_root`` so claude's project_key+ # (derived from cwd via `[^a-zA-Z0-9.-] -> -`) stays stable+ # across spawns. With a stable project_key, ``--resume <UUID>``+ # finds the prior session JSONL claude wrote on its previous+ # turn under ``<CLAUDE_CONFIG_DIR>/projects/<key>/<UUID>.jsonl``.+ # The per-task git worktree (random `wt_t_<rand>` suffix) is+ # incompatible with this — every spawn would land under a+ # brand-new project_key with no prior JSONL.+ self._memory_bound: bool = bool(memory_bound)# Streaming stateself._events: List[Dict[str, Any]] = []@@ -140,6 +150,11 @@ class AICliSession(BaseProcessSupervisor):return f"http://127.0.0.1:{self._mcp_port}/mcp/ide/mcp"def cwd(self) -> Optional[Path]:+ # Memory-bound runs spawn directly under repo_root so claude's+ # project_key stays constant and `--resume` finds the prior+ # JSONL across runs. Non-memory runs use the per-task worktree.+ if self._memory_bound:+ return self._repo_rootreturn self._worktree_dirdef env(self) -> Dict[str, str]:@@ -162,24 +177,39 @@ class AICliSession(BaseProcessSupervisor):return easync def _pre_spawn(self) -> None:- """Create the per-task git worktree and (if supported) write the- IDE lockfile. Failures abort `_do_start` cleanly via RuntimeError."""- # 1. git worktree- 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}")+ """Create the per-task git worktree (non-memory-bound runs only)+ and (if supported) write the IDE lockfile. Failures abort+ `_do_start` cleanly via RuntimeError."""+ # 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}")+ else:+ logger.info(+ "[%s] memory-bound: skipping worktree, using cwd=%s",+ self.label, self._repo_root,+ )- # 2. IDE lockfile (VSCode pattern) — providers that support it+ # 2. IDE lockfile (VSCode pattern) — providers that support it.+ # `workspace_dir` in the lockfile points at whatever cwd will+ # actually be — repo_root for memory-bound runs, else worktree.+ lockfile_workspace = (+ self._repo_root if self._memory_bound else self._worktree_dir+ )if self._provider.supports("ide_lockfile") and self._provider.ide_lockfile_dir:try:self._lockfile_path = write_ide_lockfile(@@ -187,7 +217,7 @@ class AICliSession(BaseProcessSupervisor):pid=os.getpid(),port=self._mcp_port,token=self._batch_token,- workspace_dir=self._worktree_dir,+ workspace_dir=lockfile_workspace,ide_name=self._provider.name,)except OSError as exc:@@ -196,9 +226,9 @@ class AICliSession(BaseProcessSupervisor):self.label, exc,)- # 3. Materialise connected skills into `<worktree>/.claude/skills/`.- # Project-scope path auto-discovers because the worktree IS claude's- # cwd. Best-effort — failures warn but don't abort the spawn.+ # 3. Materialise connected skills under cwd's `.claude/skills/`.+ # cwd is repo_root for memory-bound, worktree otherwise — both+ # are project-scope per the spec.if self._connected_skill_names:await self._materialise_skills()@@ -211,7 +241,8 @@ class AICliSession(BaseProcessSupervisor):from services.skill_loader import get_skill_loaderloader = get_skill_loader()- skills_dir = self._worktree_dir / ".claude" / "skills"+ # cwd-relative — repo_root for memory-bound runs, worktree otherwise.+ skills_dir = self.cwd() / ".claude" / "skills"try:skills_dir.mkdir(parents=True, exist_ok=True)except OSError as exc:@@ -530,19 +561,20 @@ class AICliSession(BaseProcessSupervisor):remove_ide_lockfile(self._lockfile_path)self._lockfile_path = None- # Remove the worktree (force, since branch lifecycle is the- # batch's responsibility — best-effort).- try:- await anyio.run_process(- [- "git", "-C", str(self._repo_root),- "worktree", "remove", "--force",- str(self._worktree_dir),- ],- check=False,- )- except Exception as exc:- self._logger.debug("[%s] worktree remove: %s", self.label, exc)+ # Remove the per-task worktree (only created for non-memory+ # 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,+ )+ except Exception as exc:+ self._logger.debug("[%s] worktree remove: %s", self.label, exc)# ------------------------------------------------------------------# Result constructiondiff --git a/server/services/memory/state.py b/server/services/memory/state.pyindex 9712ffe2..e05bc280 100644--- a/server/services/memory/state.py+++ b/server/services/memory/state.py@@ -84,13 +84,17 @@ async def clear_agent_session_state(db = get_database()params = await db.get_node_parameters(memory_node_id) or {}params["memory_content"] = DEFAULT_MEMORY_CONTENT- params["memory_jsonl"] = None+ # Wipe `last_session_id` so claude_code_agent starts a fresh+ # session on next spawn instead of `--resume`-ing into the now-+ # cleared transcript. Drop any orphan JSONL field from the+ # earlier bridge revision.params["last_session_id"] = None+ params.pop("memory_jsonl", None)await db.save_node_parameters(memory_node_id, params)cleared_memory_node = Truelogger.info("[Memory] Cleared simpleMemory node fields memory_node=%s "- "(memory_content reset, memory_jsonl + last_session_id wiped)",+ "(memory_content reset + last_session_id wiped)",memory_node_id,)diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.pyindex 11de60f0..4dee29b0 100644--- a/server/services/plugin/edge_walker.py+++ b/server/services/plugin/edge_walker.py@@ -168,13 +168,19 @@ async def _build_memory_entry(),"long_term_enabled": memory_params.get("long_term_enabled", False),"retrieval_count": int(memory_params.get("retrieval_count", 3)),+ # Claude Code CLI session continuity: the UUID claude returned on+ # the previous successful run. claude_code_agent passes this as+ # `--resume <UUID>` so claude finds its own JSONL transcript at+ # `<CLAUDE_CONFIG_DIR>/projects/<cwd-encoded>/<UUID>.jsonl`.+ "last_session_id": memory_params.get("last_session_id"),}logger.info("%s Connected memory node: node=%s session=%s (auto=%s) "- "content_length=%d",+ "content_length=%d last_session_id=%s",log_prefix, memory_node_id, session_id,not configured_session or configured_session == "default",len(entry["memory_content"]),+ entry["last_session_id"],)return entry