Skip to content

Self-improving AI Employees for everyone

fix(cli_agent): per-workflow workspace skills + live-diff on warm reuse

trohitg5c3312fbdad9
diff --git a/CLAUDE.md b/CLAUDE.md
index c521cf43..2e399432 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3501,7 +3501,7 @@ When `simpleMemory` is connected to `claude_code_agent`, memory continuity is ha
**Strict tool allowlist — no claude built-ins (except conditional `Skill`), gated by `--permission-mode dontAsk`.** The spawn argv emits `--permission-mode dontAsk` (documented as *"only pre-approved tools, no prompts"* per [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes)) so `--allowedTools` is actually enforced. The previous default `bypassPermissions` *"skips the permission layer entirely"* — same doc — which turned the allowlist into documentation-only and let claude's built-in `Read` / `Edit` / `Bash` / `Glob` / `Grep` / `Write` / `Skill` / `WebSearch` / `WebFetch` fire regardless of wiring. The new `--allowedTools` list contains exactly: (a) one `mcp__machinaos__<node_type>` per node wired through the agent's `input-tools` handle, (b) the claude built-in `Skill` **conditionally** — only when at least one skill is wired through `input-skill` (paired with the materialisation helper below; never enabled when no skill is connected), (c) the five MachinaOs MCP infrastructure tools (`getWorkspaceFiles`, `listSkills`, `getSkill`, `getCredential`, `broadcastLog`). Every filesystem / shell / web operation flows through wired MCP tools (`fileRead` / `fileModify` / `fsSearch` / `shell` / `browser` / `perplexitySearch`) — explicit wiring, no built-in escape hatches. Defaults live in [`server/config/ai_cli_providers.json`](./server/config/ai_cli_providers.json) (`default_allowed_tools: ""`, `default_permission_mode: "dontAsk"`); per-task override via `ClaudeTaskSpec.allowed_tools` is honored verbatim (no auto-merge).
-**Skill materialisation — shared helper, both paths.** [`services/cli_agent/_skills.py::materialise_skills`](./server/services/cli_agent/_skills.py) writes connected SKILL.md trees under `<cwd>/.claude/skills/<name>/` so claude's built-in `Skill` tool can load them. Filesystem skills are copied wholesale (`shutil.copytree`) preserving `scripts/` + `references/`; DB skills reconstruct the frontmatter from the loader's metadata. Called from BOTH `AICliSession._pre_spawn` (non-pool path) and `ClaudeSessionPool._spawn` (pool path) — closes the pre-existing gap where memory-bound runs got skills via MCP only. The helper is paired with the conditional `Skill` entry in `--allowedTools`: both fire iff `connected_skill_names` is non-empty.
+**Skill materialisation — per-workflow workspace, live-watched, diff-based.** [`services/cli_agent/_skills.py::materialise_skills`](./server/services/cli_agent/_skills.py) writes connected-AND-enabled SKILL.md trees under `<workspace_dir>/.claude/skills/<name>/` where `workspace_dir = data/workspaces/<workflow_id>/`. The workspace is passed via `--add-dir`, and claude scans `.claude/skills/` inside every `--add-dir` path per [the skills spec's "Automatic discovery from parent and nested directories" rule](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) — gives us per-workflow isolation (workflow A's skills can't bleed into workflow B's subprocess even when both spawn with `cwd=repo_root`). Pool tracks the materialised set in `PooledClaudeSession.materialised_skills: frozenset[str]`; on warm reuse, `acquire` calls `materialise_skills(workspace_dir, new_set, previous_skill_names=session.materialised_skills)` and the helper applies only the diff — `rmtree`'d skills disappear from claude's registry, new ones become invocable, all without respawning. Claude's [live filesystem watcher](https://code.claude.com/docs/en/skills#live-change-detection) picks up both edge events. Same helper drives both pool path and `AICliSession._pre_spawn` (non-pool) — uniform behaviour across transports. **Migration note**: pre-cutover the pool path wrote into `<repo_root>/.claude/skills/` so SKILL.md trees accumulated in the user's actual repo (gitignored but visible). Run `rm -rf .claude/skills/` once from the repo root to clean accumulated trees; future runs only write into per-workflow workspaces. We deliberately do NOT auto-prune because the repo's `.claude/` may contain user-authored skills outside the MachinaOs registry. **Architecture rationale**: surveyed alternatives — MCP `resources`/`prompts` require `@mention`/`/command` (not auto-loaded), hooks fire after skill discovery, `settings.json` doesn't expose per-session paths. Anthropic's own [Agent SDK Skills](https://code.claude.com/docs/en/agent-sdk/skills) uses the same filesystem-first pattern. Workspace-dir + live-watch is canonical.
**Warm-subprocess tool-surface rebind — no respawn cost.** Claude bakes the MCP bearer token into argv (`--mcp-config`) at spawn time and can't rotate without respawning. The pool stashes the spawn-time token on `PooledClaudeSession.batch_token` so subsequent batches can rebind the same persistent `BatchContext` in place. On warm reuse, `ClaudeSessionPool.acquire` calls [`rebind_batch(existing.batch_token, connected_tools=new_ctx.connected_tools, ...)`](./server/services/cli_agent/mcp_server.py) — diffs old vs new tool lists, calls `unexpose_workflow_tools(removed)` to decrement FastMCP refcounts (so a disconnected `duckduckgoSearch` falls off the tool list when its refcount hits zero), `expose_workflow_tools(added)` for newly-wired ones, then unregisters the redundant new token. `_terminate_locked` calls `unregister_batch(session.batch_token)` so refcounts drain on pool eviction / `clear` / `shutdown_all` (closes the long-standing leak where every pooled run permanently incremented every wired tool's refcount). The per-handler scope check in `workflow_tools._build_handler` reads `ctx.connected_tools` at call time, so even if claude's frozen `--allowedTools` argv still references a now-disconnected tool, the handler returns `{"error": "...not connected to this batch", "status": 403}` — double-lock against tool leakage across warm-reuse turns.
diff --git a/docs-internal/claude_code_interactive_mode.md b/docs-internal/claude_code_interactive_mode.md
index e407ac4d..e254f99d 100644
--- a/docs-internal/claude_code_interactive_mode.md
+++ b/docs-internal/claude_code_interactive_mode.md
@@ -293,21 +293,56 @@ Combined with `--permission-mode dontAsk`, the strict allowlist is
actually enforced (see "argv shape" above for why `bypassPermissions`
was the wrong default).
-**Skills — materialised on BOTH paths via the shared helper.**
+**Skills — per-workflow workspace, live-watched, diff-based.**
[`services/cli_agent/_skills.py::materialise_skills`](../server/services/cli_agent/_skills.py)
-writes one `SKILL.md` tree per connected skill under
-`<cwd>/.claude/skills/<name>/`. Filesystem skills (those declared
-under `server/skills/<group>/<name>/`) are copied wholesale via
-`shutil.copytree` so `scripts/` and `references/` survive
-intact; database skills (user-created from the UI) reconstruct
-the frontmatter (`name`, `description`, `allowed-tools`,
-`metadata`) plus the markdown body. Called from
+writes one `SKILL.md` tree per connected-and-enabled skill under
+`<workspace_dir>/.claude/skills/<name>/`. The workspace dir
+(`data/workspaces/<workflow_id>/`) is already passed via
+`--add-dir`, and per the skills spec's
+[Automatic discovery from parent and nested directories](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories)
+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.
+- **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
+ `acquire` calls `materialise_skills(workspace_dir, new_set,
+ previous_skill_names=session.materialised_skills)` to apply just
+ the delta — `rmtree`'d skills disappear from claude's registry,
+ newly-written ones become invocable. Same UX win as the MCP tool
+ rebind.
+
+Filesystem skills (declared under `server/skills/<group>/<name>/`)
+are copied wholesale via `shutil.copytree` so `scripts/` and
+`references/` subdirs survive. Database skills (user-created in
+the UI) reconstruct the frontmatter (`name`, `description`,
+`allowed-tools`, `metadata`) + the markdown body. Failure modes
+are non-fatal: a skill that fails to load or write logs at WARN
+and is skipped — the spawn continues. Same helper is called from
`AICliSession._pre_spawn` (non-pool path) and
-`ClaudeSessionPool._spawn` (pool path) — same helper, same
-semantics, so memory-bound runs get the built-in `Skill` tool
-working too (was the open follow-up before; closed now). Failure
-modes are non-fatal: a skill that fails to load or write logs at
-WARN and is skipped — the spawn continues.
+`ClaudeSessionPool._spawn` (pool path), so behaviour is uniform
+across the two transports.
+
+**Migration note.** Pre-cutover code wrote SKILL.md trees into
+`<repo_root>/.claude/skills/` so they accumulated in the user's
+actual repo. The repo's `.claude/` is gitignored but visible;
+future runs only write into per-workflow workspaces. Run
+`rm -rf .claude/skills/` once from the repo root to clean
+accumulated trees — we deliberately do NOT auto-prune because
+the repo's `.claude/` may contain user-authored skills outside
+the MachinaOs registry.
+
+**Why filesystem (not MCP).** We surveyed alternatives: MCP
+`resources`/`prompts` require explicit `@mention`/`/command`
+invocation by the user, not auto-loaded into context. Hooks fire
+after skill discovery, not before. `settings.json` doesn't expose
+per-session skill paths. Anthropic's own
+[Agent SDK](https://code.claude.com/docs/en/agent-sdk/skills) uses
+the same filesystem-first pattern. There is no programmatic
+skill-injection channel — workspace-dir + live-watch is canonical.
**Workspace dir — routed via `--add-dir`.**
[`AICliService.run_batch`](../server/services/cli_agent/service.py)
diff --git a/server/services/cli_agent/_skills.py b/server/services/cli_agent/_skills.py
index 4da704cd..bc96ffdc 100644
--- a/server/services/cli_agent/_skills.py
+++ b/server/services/cli_agent/_skills.py
@@ -1,33 +1,71 @@
-"""Skill materialisation helper shared by pool + non-pool claude paths.
-
-Writes ``<cwd>/.claude/skills/<name>/SKILL.md`` for each connected skill
-so the spawned claude can invoke them via its built-in ``Skill`` tool
-(when ``--allowedTools`` includes ``Skill``). The
-``AnthropicClaudeProvider.interactive_argv`` adds ``Skill`` to the
-allowlist iff ``connected_skill_names`` is non-empty — so this helper
-and the conditional allowlist entry are paired.
-
-Two skill shapes:
-
- - **Filesystem skills** (``server/skills/<group>/<name>/SKILL.md``):
- copied wholesale via ``shutil.copytree`` so ``scripts/`` and
- ``references/`` survive.
- - **Database skills** (user-created from the UI): reconstructed from
- frontmatter — ``name``, ``description``, ``allowed-tools``,
- ``metadata`` — plus the markdown body.
-
-This used to live as an instance method on ``AICliSession``; the pool
-path didn't call it. Extracted to a module-level free function so both
-``AICliSession._pre_spawn`` (non-pool, PTY-driven) and
-``ClaudeSessionPool._spawn`` (pool, subprocess+stream-json) call the
-same code with the same semantics.
+"""Skill materialisation for claude code agent — per-workflow workspace.
+
+Writes ``<workspace_dir>/.claude/skills/<name>/SKILL.md`` for each
+connected-and-enabled skill, so claude's built-in skill loader (the
+``Skill`` tool in ``--allowedTools``) can discover them. Claude live-
+watches its skill directories — adding, editing, or removing a
+``SKILL.md`` mid-session is picked up without restart per the
+[skills reference](https://code.claude.com/docs/en/skills) — which
+lets us toggle skills on a warm subprocess without respawning.
+
+This is the canonical pattern per Anthropic's own SDK
+(``code.claude.com/docs/en/agent-sdk/skills``): filesystem-first
+discovery with `SKILL.md` files. There is no programmatic
+skill-injection channel — neither MCP `resources`/`prompts`, hooks,
+nor settings.json offer a per-session skill toggle equivalent to
+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:
+
+ - Pollute the user's repo (gitignored, but visible).
+ - Accumulate stale SKILL.md trees across workflow runs that wired
+ different skills.
+ - Let workflow A's skills bleed into workflow B's subprocess
+ (claude walks parent dirs up to the repo root for skill discovery).
+
+The per-workflow workspace at ``data/workspaces/<workflow_id>/`` is
+already passed via ``--add-dir <workspace>`` (see
+``AICliService.run_batch``), and claude scans ``.claude/skills/``
+inside every ``--add-dir`` path. Materialising there gives us
+per-workflow isolation and no inter-workflow races.
+
+Diff-based add/remove
+---------------------
+
+:func:`materialise_skills` takes the previous skill set + the new one
+and applies just the delta to disk. Removed skills are ``rmtree``'d;
+added skills are written. Skills present in both sets are left alone.
+Claude's filesystem watcher picks up both edge events automatically.
+
+For the cold-spawn path, ``previous_skill_names=None`` is equivalent
+to ``previous_skill_names=set()`` — every skill in ``skill_names`` is
+written.
+
+Failures (skill not found, OSError on copy / write) log at WARNING
+and are skipped — never fatal to the spawn.
+
+Migration note
+--------------
+
+Pre-cutover, the pool path materialised under ``cwd = repo_root`` so
+SKILL.md trees accumulated in the user's actual repo. The user can
+safely run ``rm -rf .claude/skills/`` from the repo root once;
+no future runs write there. (We deliberately do NOT auto-clean —
+the repo's ``.claude/`` may contain user-authored skills that we
+have no right to touch.)
"""
from __future__ import annotations
+import asyncio
import shutil
from pathlib import Path
-from typing import Iterable
+from typing import FrozenSet, Iterable, Optional, Tuple
import yaml
@@ -37,94 +75,160 @@ logger = get_logger(__name__)
async def materialise_skills(
- cwd: Path,
+ workspace_dir: Path,
skill_names: Iterable[str],
*,
+ previous_skill_names: Optional[Iterable[str]] = None,
log_label: str = "cli-agent",
-) -> int:
- """Write SKILL.md trees under ``<cwd>/.claude/skills/`` for each name.
-
- Returns the number of skills successfully written. Failures (skill
- not found, OSError on copy / write) log at WARNING and are skipped
- — never fatal to the spawn.
+) -> Tuple[int, int]:
+ """Materialise the wired skill set under workspace_dir's
+ ``.claude/skills/``, removing any prior skills not in the new set.
Args:
- cwd: Spawn directory. Memory-bound runs pass ``repo_root``;
- non-memory runs pass the per-task git worktree. Either way
- the helper writes under ``<cwd>/.claude/skills/<name>/``.
- skill_names: The set of skill names to materialise. Caller is
- responsible for passing only the skills wired through
- the agent's ``input-skill`` handle.
- log_label: Free-form prefix shown in log lines. Defaults to
- ``"cli-agent"``; callers pass ``self.label`` for sessions
- and ``f"pool {memory_node_id}"`` for the pool path.
+ workspace_dir: ``data/workspaces/<workflow_id>/``. The helper
+ writes under ``<workspace_dir>/.claude/skills/<name>/``.
+ Claude picks these up via ``--add-dir <workspace_dir>``
+ (emitted in argv by :class:`AICliService.run_batch`) and
+ its live filesystem watcher.
+ skill_names: Skills that should be present after this call —
+ already filtered to "connected AND enabled" upstream
+ (master-skill expansion in
+ ``services.plugin.edge_walker._collect_agent_connections``
+ drops disabled entries from the wired set).
+ previous_skill_names: Skills present BEFORE this call. Pass
+ ``None`` or an empty set for cold spawn (writes everything
+ in ``skill_names``). For warm reuse, pass what was
+ materialised last time so we only touch the delta.
+ log_label: Free-form prefix for log lines (caller's identity).
+
+ Returns:
+ ``(added_count, removed_count)``. Caller uses these to log /
+ broadcast and to update its stored ``materialised_skills``
+ bookkeeping.
"""
- skill_list = [s for s in skill_names if s]
- if not skill_list:
- return 0
+ new_set: FrozenSet[str] = frozenset(s for s in skill_names if s)
+ prev_set: FrozenSet[str] = frozenset(
+ s for s in (previous_skill_names or ()) if s
+ )
- # Lazy import — the skill loader pulls the YAML parser + sqlmodel
- # which we don't want to charge on module import.
- from services.skill_loader import get_skill_loader
+ added = new_set - prev_set
+ removed = prev_set - new_set
- loader = get_skill_loader()
- skills_dir = Path(cwd) / ".claude" / "skills"
+ if not added and not removed:
+ return (0, 0)
+
+ skills_dir = Path(workspace_dir) / ".claude" / "skills"
try:
skills_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
logger.warning(
- "[%s] cannot create skills dir %s: %s — skipping materialisation",
+ "[%s] cannot create skills dir %s: %s — skipping all changes",
log_label, skills_dir, exc,
)
- return 0
-
- written = 0
- for name in skill_list:
- try:
- skill = await loader.load_skill_async(name)
- except Exception as exc:
- logger.warning(
- "[%s] load_skill_async(%r) failed: %s",
- log_label, name, exc,
- )
- continue
- if skill is None:
- logger.warning(
- "[%s] skill %r not found — skipping materialisation",
- log_label, name,
- )
- continue
+ return (0, 0)
+ # Remove first: claude's watcher fires deregistration events
+ # before re-registrations, which keeps the agent's tool/skill
+ # registry consistent across the diff.
+ removed_count = 0
+ for name in removed:
dest = skills_dir / name
+ if not dest.exists():
+ continue
try:
- if skill.metadata.path is not None:
- # Filesystem skill: copy whole directory tree so
- # `scripts/` + `references/` survive intact.
- shutil.copytree(skill.metadata.path, dest, dirs_exist_ok=True)
- else:
- # DB skill: reconstruct frontmatter + body.
- dest.mkdir(parents=True, exist_ok=True)
- frontmatter = {
- "name": skill.metadata.name,
- "description": skill.metadata.description,
- "allowed-tools": " ".join(skill.metadata.allowed_tools),
- "metadata": skill.metadata.metadata,
- }
- body = (
- f"---\n"
- f"{yaml.safe_dump(frontmatter, sort_keys=False)}"
- f"---\n\n"
- f"{skill.instructions}"
- )
- (dest / "SKILL.md").write_text(body, encoding="utf-8")
- written += 1
+ await asyncio.to_thread(shutil.rmtree, dest, ignore_errors=False)
+ removed_count += 1
logger.info(
- "[%s] materialised skill %r -> %s", log_label, name, dest,
+ "[%s] removed skill %r from %s", log_label, name, dest,
)
except OSError as exc:
logger.warning(
- "[%s] failed to materialise skill %r at %s: %s",
+ "[%s] failed to remove skill %r at %s: %s — leaving",
log_label, name, dest, exc,
)
- return written
+ if not added:
+ return (0, removed_count)
+
+ # Add: parallelise with asyncio.gather since each skill write is
+ # CPU- and disk-bound and independent of the others. Scales to
+ # the 1000-skill masterSkill case without serial slow-down.
+ from services.skill_loader import get_skill_loader
+
+ loader = get_skill_loader()
+ add_tasks = [
+ asyncio.create_task(
+ _materialise_one(loader, skills_dir, name, log_label),
+ name=f"materialise_skill({name})",
+ )
+ for name in sorted(added)
+ ]
+ results = await asyncio.gather(*add_tasks, return_exceptions=False)
+ added_count = sum(1 for ok in results if ok)
+ return (added_count, removed_count)
+
+
+async def _materialise_one(
+ loader,
+ skills_dir: Path,
+ name: str,
+ log_label: str,
+) -> bool:
+ """Write one skill. Returns True on success, False on skip / error.
+
+ Filesystem-origin skills are copytree'd wholesale (preserves
+ ``scripts/`` and ``references/`` subdirs verbatim); DB-origin
+ user skills get a synthesised SKILL.md from frontmatter + body.
+ """
+ try:
+ skill = await loader.load_skill_async(name)
+ except Exception as exc:
+ logger.warning(
+ "[%s] load_skill_async(%r) failed: %s — skipping",
+ log_label, name, exc,
+ )
+ return False
+ if skill is None:
+ logger.warning(
+ "[%s] skill %r not found in registry — skipping materialisation",
+ log_label, name,
+ )
+ return False
+
+ dest = skills_dir / name
+ try:
+ if skill.metadata.path is not None:
+ # Filesystem skill: copytree preserves SKILL.md +
+ # scripts/ + references/ + templates/ atomically.
+ await asyncio.to_thread(
+ shutil.copytree,
+ skill.metadata.path, dest, dirs_exist_ok=True,
+ )
+ else:
+ # DB skill: reconstruct frontmatter from metadata
+ # (allowed-tools is space-separated per Anthropic spec)
+ # + write body.
+ await asyncio.to_thread(dest.mkdir, parents=True, exist_ok=True)
+ frontmatter = {
+ "name": skill.metadata.name,
+ "description": skill.metadata.description,
+ "allowed-tools": " ".join(skill.metadata.allowed_tools),
+ "metadata": skill.metadata.metadata,
+ }
+ body = (
+ f"---\n"
+ f"{yaml.safe_dump(frontmatter, sort_keys=False)}"
+ f"---\n\n"
+ f"{skill.instructions}"
+ )
+ await asyncio.to_thread(
+ (dest / "SKILL.md").write_text, body, encoding="utf-8",
+ )
+ logger.info("[%s] materialised skill %r -> %s", log_label, name, dest)
+ return True
+ except OSError as exc:
+ logger.warning(
+ "[%s] failed to materialise skill %r at %s: %s",
+ log_label, name, dest, exc,
+ )
+ return False
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index 94cfe7c1..5a0cf9fd 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -258,6 +258,7 @@ class AICliService:
task=task_list[0],
memory_node_id=connected_memory["node_id"],
cwd=resolved_repo_root,
+ workspace_dir=Path(workspace_dir).resolve(),
defaults=defaults,
mcp_port=port,
mcp_bearer_token=token,
@@ -390,6 +391,7 @@ class AICliService:
task: BaseAICliTaskSpec,
memory_node_id: str,
cwd: Path,
+ workspace_dir: Path,
defaults: Dict[str, Any],
mcp_port: int,
mcp_bearer_token: str,
@@ -442,6 +444,7 @@ class AICliService:
mcp_bearer_token=mcp_bearer_token,
connected_tool_names=tool_names,
connected_skill_names=connected_skill_names,
+ workspace_dir=workspace_dir,
workflow_id=workflow_id,
)
try:
@@ -490,7 +493,7 @@ class AICliService:
) -> None:
"""Append each successful run's user prompt + assistant response
to ``simpleMemory.memory_content`` (markdown). Mirrors aiAgent /
- chatAgent / deep_agent / rlm_agent's persistence pattern exactly
+ chatAgent / rlm_agent's persistence pattern exactly
— same helpers (``append_to_memory_markdown``,
``trim_markdown_window``), same field. One DB write.
"""
diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.py
index 8ec2de9a..7e99f286 100644
--- a/server/services/cli_agent/session.py
+++ b/server/services/cli_agent/session.py
@@ -100,8 +100,14 @@ class AICliSession(BaseProcessSupervisor):
self._task = task
self._task_id = task.task_id or f"t_{uuid.uuid4().hex[:8]}"
self._repo_root = Path(repo_root).resolve()
+ # Per-workflow workspace dir (``data/workspaces/<workflow_id>/``).
+ # Passed via ``--add-dir`` so claude scans
+ # ``<workspace_dir>/.claude/skills/`` for materialised skills
+ # (per-workflow isolation; ``cwd`` for memory-bound runs is
+ # ``repo_root`` which would otherwise be shared across workflows).
+ self._workspace_dir = Path(workspace_dir).resolve()
self._worktree_dir = (
- Path(workspace_dir).resolve() / node_id / f"wt_{self._task_id}"
+ self._workspace_dir / node_id / f"wt_{self._task_id}"
)
self._branch = task.branch or f"machina/{self._task_id}"
self._broadcaster = broadcaster
@@ -261,15 +267,22 @@ class AICliSession(BaseProcessSupervisor):
self.label, exc,
)
- # 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. Same helper now also runs on
- # the pool path (``ClaudeSessionPool._spawn``) so memory-bound
- # runs get the built-in ``Skill`` tool too.
+ # 3. Materialise connected skills under the workspace's
+ # ``.claude/skills/``. Per-workflow isolation: workflow A's
+ # wired skills never bleed into workflow B's subprocess even
+ # when both share ``cwd=repo_root``. Claude discovers them
+ # via ``--add-dir <workspace_dir>`` (emitted in argv) per the
+ # skills spec's "Automatic discovery from parent and nested
+ # directories" rule. Same helper now also runs on the pool
+ # path so memory-bound runs get the built-in ``Skill`` tool
+ # too.
if self._connected_skill_names:
from services.cli_agent._skills import materialise_skills
await materialise_skills(
- self.cwd(), self._connected_skill_names, log_label=self.label,
+ self._workspace_dir,
+ self._connected_skill_names,
+ previous_skill_names=None,
+ log_label=self.label,
)
# ------------------------------------------------------------------
diff --git a/server/services/cli_agent/session_pool.py b/server/services/cli_agent/session_pool.py
index 731eb34f..7519cca6 100644
--- a/server/services/cli_agent/session_pool.py
+++ b/server/services/cli_agent/session_pool.py
@@ -131,6 +131,21 @@ class PooledClaudeSession:
# in ``_terminate_locked`` to drain the FastMCP tool refcounts
# when the subprocess dies.
batch_token: str = ""
+ # Per-workflow workspace dir (``data/workspaces/<workflow_id>/``)
+ # passed via ``--add-dir`` so claude discovers the skills tree
+ # under ``<workspace_dir>/.claude/skills/`` per the
+ # "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``.
+ workspace_dir: Optional[Path] = None
+ # Set of skill names currently materialised under
+ # ``<workspace_dir>/.claude/skills/`` for this warm subprocess.
+ # The pool calls :func:`services.cli_agent._skills.materialise_skills`
+ # with this as the ``previous_skill_names`` arg on every warm
+ # reuse, so only the delta is touched on disk. Claude's filesystem
+ # watcher picks up add/remove events without respawning.
+ materialised_skills: frozenset = field(default_factory=frozenset)
last_used_at: float = field(default_factory=time.monotonic)
# Per-session lock; held throughout a turn. The reaper consults
# ``lock.locked()`` to skip in-flight sessions.
@@ -213,6 +228,7 @@ class ClaudeSessionPool:
mcp_bearer_token: Optional[str],
connected_tool_names: Optional[List[str]] = None,
connected_skill_names: Optional[List[str]] = None,
+ workspace_dir: Optional[Path] = None,
workflow_id: Optional[str] = None,
) -> PooledClaudeSession:
"""Return a live :class:`PooledClaudeSession`.
@@ -278,6 +294,31 @@ class ClaudeSessionPool:
workspace_dir=new_ctx.workspace_dir,
)
unregister_batch(mcp_bearer_token)
+ # Live skill-tree update — claude live-watches
+ # ``<workspace_dir>/.claude/skills/`` so add/remove
+ # takes effect within the current session per the
+ # skills spec's "Live change detection" rule
+ # (code.claude.com/docs/en/skills#live-change-detection).
+ # Same diff semantics as the MCP rebind above:
+ # ``apply_skill_diff`` walks (added, removed) against
+ # ``existing.materialised_skills`` and only touches
+ # the delta on disk.
+ if existing.workspace_dir is not None:
+ from services.cli_agent._skills import materialise_skills
+ new_set = frozenset(connected_skill_names or [])
+ added, removed = await materialise_skills(
+ existing.workspace_dir,
+ new_set,
+ previous_skill_names=existing.materialised_skills,
+ log_label=f"pool {memory_node_id}",
+ )
+ if added or removed:
+ logger.info(
+ "[ClaudeSessionPool] skill diff "
+ "memory_node=%s +%d -%d (now %d wired)",
+ memory_node_id, added, removed, len(new_set),
+ )
+ existing.materialised_skills = new_set
logger.info(
"[ClaudeSessionPool] warm reuse memory_node=%s pid=%s uuid=%s",
memory_node_id, existing.process.pid,
@@ -304,6 +345,7 @@ class ClaudeSessionPool:
mcp_bearer_token=mcp_bearer_token,
connected_tool_names=connected_tool_names,
connected_skill_names=connected_skill_names,
+ workspace_dir=workspace_dir,
)
# Track the spawn-time bearer token so subsequent batches can
# rebind the persistent BatchContext in place (warm-reuse
@@ -311,6 +353,13 @@ class ClaudeSessionPool:
# tool refcounts on death.
if mcp_bearer_token:
session.batch_token = mcp_bearer_token
+ # Track the workspace + initial skill set so warm-reuse
+ # paths know where to materialise live updates and what
+ # the prior set was for the diff.
+ session.workspace_dir = workspace_dir
+ session.materialised_skills = frozenset(
+ connected_skill_names or []
+ )
if crashed_uuid:
# The new subprocess is resuming the prior session; pre-seed
# the UUID so the first turn's emitted CloudEvents carry
@@ -505,18 +554,29 @@ class ClaudeSessionPool:
mcp_bearer_token: Optional[str],
connected_tool_names: Optional[List[str]],
connected_skill_names: Optional[List[str]] = None,
+ workspace_dir: Optional[Path] = None,
) -> PooledClaudeSession:
"""Cold-spawn a new pooled claude subprocess. Caller holds pool_lock."""
- # Materialise connected skills under ``<cwd>/.claude/skills/``
- # BEFORE spawning so the spawned claude sees them on its first
- # filesystem scan. Same helper the non-pool ``AICliSession``
- # path uses. Paired with the conditional ``Skill`` entry in
- # ``--allowedTools`` (see ``interactive_argv``) — both fire when
- # ``connected_skill_names`` is non-empty.
+ # Materialise connected skills under
+ # ``<workspace_dir>/.claude/skills/`` BEFORE spawning so the
+ # spawned claude sees them on its first filesystem scan. The
+ # workspace dir (per-workflow) is passed via ``--add-dir``
+ # (emitted by ``AICliService.run_batch``), and claude scans
+ # ``.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``
+ # 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
+ # provided (defensive — every production caller passes one).
if connected_skill_names:
from services.cli_agent._skills import materialise_skills
+ target_dir = workspace_dir or cwd
await materialise_skills(
- cwd, connected_skill_names,
+ target_dir, connected_skill_names,
+ previous_skill_names=None, # cold spawn: no prior set
log_label=f"pool {memory_node_id}",
)